@tscircuit/eval 0.0.462 → 0.0.463

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -158,7 +158,7 @@ svg { font-family: 'Inter', 'Helvetica Neue', Arial, sans-serif; }
158
158
  fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *)
159
159
  )`,enabled:":not(:disabled)",checked:":is(:is(input[type=radio], input[type=checkbox])[checked], option:selected)",required:":is(input, select, textarea)[required]",optional:":is(input, select, textarea):not([required])",selected:"option:is([selected], select:not([multiple]):not(:has(> option[selected])) > :first-of-type)",checkbox:"[type=checkbox]",file:"[type=file]",password:"[type=password]",radio:"[type=radio]",reset:"[type=reset]",image:"[type=image]",submit:"[type=submit]",parent:":not(:empty)",header:":is(h1, h2, h3, h4, h5, h6)",button:":is(button, input[type=button])",input:":is(input, textarea, select, button)",text:"input:is(:not([type!='']), [type=text])"};var lr=Xt(kl(),1);var sI={};function aI(e,t){return e===lr.default.falseFunc?lr.default.falseFunc:n=>t.isTag(n)&&e(n)}function cI(e,t){let n=t.getSiblings(e);if(n.length<=1)return[];let i=n.indexOf(e);return i<0||i===n.length-1?[]:n.slice(i+1).filter(t.isTag)}function rI(e){return{xmlMode:!!e.xmlMode,lowerCaseAttributeNames:!!e.lowerCaseAttributeNames,lowerCaseTags:!!e.lowerCaseTags,quirksMode:!!e.quirksMode,cacheResults:!!e.cacheResults,pseudos:e.pseudos,adapter:e.adapter,equals:e.equals}}var oI=(e,t,n,i,o)=>{let r=o(t,rI(n),i);return r===lr.default.trueFunc?e:r===lr.default.falseFunc?lr.default.falseFunc:s=>r(s)&&e(s)},zg={is:oI,matches:oI,where:oI,not(e,t,n,i,o){let r=o(t,rI(n),i);return r===lr.default.falseFunc?e:r===lr.default.trueFunc?lr.default.falseFunc:s=>!r(s)&&e(s)},has(e,t,n,i,o){let{adapter:r}=n,s=rI(n);s.relativeSelector=!0;let a=t.some(u=>u.some(uf))?[sI]:void 0,c=o(t,s,a);if(c===lr.default.falseFunc)return lr.default.falseFunc;let l=aI(c,r);if(a&&c!==lr.default.trueFunc){let{shouldTestNextSiblings:u=!1}=c;return h=>{if(!e(h))return!1;a[0]=h;let d=r.getChildren(h),_=u?[...d,...cI(h,r)]:d;return r.existsOne(l,_)}}return u=>e(u)&&r.existsOne(l,r.getChildren(u))}};function hF(e,t,n,i,o){var r;let{name:s,data:a}=t;if(Array.isArray(a)){if(!(s in zg))throw new Error(`Unknown pseudo-class :${s}(${a})`);return zg[s](e,a,n,i,o)}let c=(r=n.pseudos)===null||r===void 0?void 0:r[s],l=typeof c=="string"?c:iI[s];if(typeof l=="string"){if(a!=null)throw new Error(`Pseudo ${s} doesn't have any arguments`);let u=lf(l);return zg.is(e,u,n,i,o)}if(typeof c=="function")return nI(c,s,a,1),u=>c(u,a)&&e(u);if(s in hf)return hf[s](e,a,n,i);if(s in Fg){let u=Fg[s];return nI(u,s,a,2),h=>u(h,n,a)&&e(h)}throw new Error(`Unknown pseudo-class :${s}`)}function lI(e,t){let n=t.getParent(e);return n&&t.isTag(n)?n:null}function dF(e,t,n,i,o){let{adapter:r,equals:s}=n;switch(t.type){case ae.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case ae.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case ae.Attribute:{if(t.namespace!=null)throw new Error("Namespaced attributes are not yet supported by css-select");return(!n.xmlMode||n.lowerCaseAttributeNames)&&(t.name=t.name.toLowerCase()),cF[t.action](e,t,n)}case ae.Pseudo:return hF(e,t,n,i,o);case ae.Tag:{if(t.namespace!=null)throw new Error("Namespaced tag names are not yet supported by css-select");let{name:a}=t;return(!n.xmlMode||n.lowerCaseTags)&&(a=a.toLowerCase()),function(l){return r.getName(l)===a&&e(l)}}case ae.Descendant:{if(n.cacheResults===!1||typeof WeakSet>"u")return function(l){let u=l;for(;u=lI(u,r);)if(e(u))return!0;return!1};let a=new WeakSet;return function(l){let u=l;for(;u=lI(u,r);)if(!a.has(u)){if(r.isTag(u)&&e(u))return!0;a.add(u)}return!1}}case"_flexibleDescendant":return function(c){let l=c;do if(e(l))return!0;while(l=lI(l,r));return!1};case ae.Parent:return function(c){return r.getChildren(c).some(l=>r.isTag(l)&&e(l))};case ae.Child:return function(c){let l=r.getParent(c);return l!=null&&r.isTag(l)&&e(l)};case ae.Sibling:return function(c){let l=r.getSiblings(c);for(let u=0;u<l.length;u++){let h=l[u];if(s(c,h))break;if(r.isTag(h)&&e(h))return!0}return!1};case ae.Adjacent:return r.prevElementSibling?function(c){let l=r.prevElementSibling(c);return l!=null&&e(l)}:function(c){let l=r.getSiblings(c),u;for(let h=0;h<l.length;h++){let d=l[h];if(s(c,d))break;r.isTag(d)&&(u=d)}return!!u&&e(u)};case ae.Universal:{if(t.namespace!=null&&t.namespace!=="*")throw new Error("Namespaced universal selectors are not yet supported by css-select");return e}}}function fF(e,t,n){let i=Dg(e,t,n);return aI(i,t.adapter)}function Dg(e,t,n){let i=typeof e=="string"?lf(e):e;return $g(i,t,n)}function mF(e){return e.type===ae.Pseudo&&(e.name==="scope"||Array.isArray(e.data)&&e.data.some(t=>t.some(mF)))}var L1t={type:ae.Descendant},F1t={type:"_flexibleDescendant"},z1t={type:ae.Pseudo,name:"scope",data:null};function D1t(e,{adapter:t},n){let i=!!n?.every(o=>{let r=t.isTag(o)&&t.getParent(o);return o===sI||r&&t.isTag(r)});for(let o of e){if(!(o.length>0&&uf(o[0])&&o[0].type!==ae.Descendant))if(i&&!o.some(mF))o.unshift(L1t);else continue;o.unshift(z1t)}}function $g(e,t,n){var i;e.forEach(Q5),n=(i=t.context)!==null&&i!==void 0?i:n;let o=Array.isArray(n),r=n&&(Array.isArray(n)?n:[n]);if(t.relativeSelector!==!1)D1t(e,t,r);else if(e.some(c=>c.length>0&&uf(c[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let s=!1,a=e.map(c=>{if(c.length>=2){let[l,u]=c;l.type!==ae.Pseudo||l.name!=="scope"||(o&&u.type===ae.Descendant?c[1]=F1t:(u.type===ae.Adjacent||u.type===ae.Sibling)&&(s=!0))}return $1t(c,t,r)}).reduce(j1t,Hs.default.falseFunc);return a.shouldTestNextSiblings=s,a}function $1t(e,t,n){var i;return e.reduce((o,r)=>o===Hs.default.falseFunc?Hs.default.falseFunc:dF(o,r,t,n,$g),(i=t.rootFunc)!==null&&i!==void 0?i:Hs.default.trueFunc)}function j1t(e,t){return t===Hs.default.falseFunc||e===Hs.default.trueFunc?e:e===Hs.default.falseFunc||t===Hs.default.trueFunc?t:function(i){return e(i)||t(i)}}var _F=(e,t)=>e===t,B1t={adapter:Og,equals:_F};function yF(e){var t,n,i,o;let r=e??B1t;return(t=r.adapter)!==null&&t!==void 0||(r.adapter=Og),(n=r.equals)!==null&&n!==void 0||(r.equals=(o=(i=r.adapter)===null||i===void 0?void 0:i.equals)!==null&&o!==void 0?o:_F),r}function pI(e){return function(n,i,o){let r=yF(i);return e(n,r,o)}}var Tzt=pI(fF),Mzt=pI(Dg),Czt=pI($g);function gF(e){return function(n,i,o){let r=yF(o);typeof n!="function"&&(n=Dg(n,r,i));let s=Y1t(i,r.adapter,n.shouldTestNextSiblings);return e(n,s,r)}}function Y1t(e,t,n=!1){return n&&(e=X1t(e,t)),Array.isArray(e)?t.removeSubsets(e):t.getChildren(e)}function X1t(e,t){let n=Array.isArray(e)?e.slice(0):[e],i=n.length;for(let o=0;o<i;o++){let r=cI(n[o],t);n.push(...r)}return n}var hI=gF((e,t,n)=>e===uI.default.falseFunc||!t||t.length===0?[]:n.adapter.findAll(e,t)),jg=gF((e,t,n)=>e===uI.default.falseFunc||!t||t.length===0?null:n.adapter.findOne(e,t));K();vt();K();var WF=Xt(Sn(),1);vt();var JF=Xt(Sn(),1),tz=Xt(Sn(),1);vt();Qr();bI();var xI=(e,t={})=>{let n=e._internal_store;if(!n){n={counts:{}},e._internal_store=n;for(let o of e){let r=o.type,s=o[`${r}_id`];if(!s)continue;let a=Number.parseInt(s.split("_").pop());Number.isNaN(a)||(n.counts[r]=Math.max(n.counts[r]??0,a))}}return new Proxy({},{get:(o,r)=>r==="toArray"?()=>e:{get:s=>e.find(a=>a.type===r&&a[`${r}_id`]===s),getUsing:s=>{let a=Object.keys(s);if(a.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");let c=a[0],l=c.replace("_id",""),u=e.find(h=>h.type===l&&h[c]===s[c]);return u?e.find(h=>h.type===r&&h[`${r}_id`]===u[`${r}_id`]):null},getWhere:s=>{let a=Object.keys(s);return e.find(c=>c.type===r&&a.every(l=>c[l]===s[l]))},list:s=>{let a=s?Object.keys(s):[];return e.filter(c=>c.type===r&&a.every(l=>c[l]===s[l]))},insert:s=>{var l;(l=n.counts)[r]??(l[r]=-1),n.counts[r]++;let a=n.counts[r],c={type:r,[`${r}_id`]:`${r}_${a}`,...s};return t.validateInserts&&(Pl[r]??wl).parse(c),e.push(c),c},delete:s=>{let a=e.find(c=>c[`${r}_id`]===s);a&&e.splice(e.indexOf(a),1)},update:(s,a)=>{let c=e.find(l=>l.type===r&&l[`${r}_id`]===s);if(c)return Object.assign(c,a),c},select:s=>{if(r==="source_component")return e.find(a=>a.type==="source_component"&&a.name===s.replace(/\./g,""));if(r==="pcb_port"||r==="source_port"||r==="schematic_port"){let[a,c]=s.replace(/\./g,"").split(/[\s\>]+/),l=e.find(h=>h.type==="source_component"&&h.name===a);if(!l)return null;let u=e.find(h=>h.type==="source_port"&&h.source_component_id===l.source_component_id&&(h.name===c||(h.port_hints??[]).includes(c)));if(!u)return null;if(r==="source_port")return u;if(r==="pcb_port")return e.find(h=>h.type==="pcb_port"&&h.source_port_id===u.source_port_id);if(r==="schematic_port")return e.find(h=>h.type==="schematic_port"&&h.source_port_id===u.source_port_id)}}}})};xI.unparsed=xI;var Rr=xI;var k$t=Xt(RF(),1);ji();function Or(e){let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,maxX:e.center.x+t,minY:e.center.y-n,maxY:e.center.y+n}}function yf(e,t){let n=Or(e),i=Or(t),o=Math.max(n.minX-i.maxX,i.minX-n.maxX,0),r=Math.max(n.minY-i.maxY,i.minY-n.maxY,0),s={x:0,y:0},a={x:0,y:0};return o===0&&r===0?{distance:0,pointA:e.center,pointB:t.center}:(s.x=Rn(e.center.x,i.minX,i.maxX),s.y=Rn(e.center.y,i.minY,i.maxY),a.x=Rn(t.center.x,n.minX,n.maxX),a.y=Rn(t.center.y,n.minY,n.maxY),{distance:Math.hypot(s.x-a.x,s.y-a.y),pointA:s,pointB:a})}function ts(e,t){return yf(e,t)}function II(e,t){let n=Or(e),i=Or(t),o=Math.max(n.minX-i.maxX,i.minX-n.maxX,0),r=Math.max(n.minY-i.maxY,i.minY-n.maxY,0);return Math.hypot(o,r)}function Rn(e,t,n){return Math.max(t,Math.min(n,e))}function gf(e,t){let n=Number.POSITIVE_INFINITY,i={x:0,y:0},o={x:0,y:0};for(let r of e)for(let s of t){let{distance:a,pointA:c,pointB:l}=yf(r,s);a<n&&(n=a,i=c,o=l)}return{pointA:i,pointB:o,distance:n}}ji();ji();var jF="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var BF=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=jF[n[e]&63];return t};ji();var $l=(e,t)=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y),YF=(e,t)=>{let n=t.x-e.x,i=t.y-e.y;return Math.abs(n)>Math.abs(i)?{dx:Math.sign(n),dy:0}:{dx:0,dy:Math.sign(i)}},UF=(e,t,n)=>Math.abs(e.x-t.x)*Math.abs(n.dx)+Math.abs(e.y-t.y)*Math.abs(n.dy),qF=(e,t=.1)=>`${Math.round(e.x/t)},${Math.round(e.y/t)}`,XF=(e,t)=>Math.abs(e-t)<1e-4,ZF=(e,t,{viaDiameter:n=.5}={})=>{let i=[];for(let o=0;o<e.length-1;o++){let[r,s]=[e[o],e[o+1]],a=o-1>=0?e[o-1]:null,c=XF(r.y,s.y),l=XF(r.x,s.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${t}, start: (${r.x}, ${r.y}), end: (${s.x}, ${s.y})`);let u={type:"rect",layers:[r.layer],center:{x:(r.x+s.x)/2,y:(r.y+s.y)/2},width:c?Math.abs(r.x-s.x):.1,height:l?Math.abs(r.y-s.y):.1,connectedTo:[t]};if(i.push(u),a&&a.layer===r.layer&&r.layer!==s.layer){let h={type:"rect",layers:[r.layer,s.layer],center:{x:r.x,y:r.y},connectedTo:[t],width:n,height:n};i.push(h)}}return i},KF=class{constructor(e){P(this,"obstacles");P(this,"GRID_STEP",.1);this.obstacles=e.map(t=>({...t,left:t.center.x-t.width/2,right:t.center.x+t.width/2,top:t.center.y+t.height/2,bottom:t.center.y-t.height/2}))}getObstacleAt(e,t,n){n??(n=this.GRID_STEP);for(let i of this.obstacles){let o=i.width/2+n,r=i.height/2+n;if(e>=i.center.x-o&&e<=i.center.x+o&&t>=i.center.y-r&&t<=i.center.y+r)return i}return null}isObstacleAt(e,t,n){return this.getObstacleAt(e,t,n)!==null}getDirectionDistancesToNearestObstacle(e,t){let{GRID_STEP:n}=this,i={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let o of this.obstacles)if(o.type==="rect"){let r=o.center.x-o.width/2-n,s=o.center.x+o.width/2+n,a=o.center.y+o.height/2+n,c=o.center.y-o.height/2-n;t>=c&&t<=a&&e>r&&(i.left=Math.min(i.left,e-s)),t>=c&&t<=a&&e<s&&(i.right=Math.min(i.right,r-e)),e>=r&&e<=s&&t<a&&(i.top=Math.min(i.top,c-t)),e>=r&&e<=s&&t>c&&(i.bottom=Math.min(i.bottom,t-a))}return i}getOrthoDirectionCollisionInfo(e,t,{margin:n=0}={}){let{x:i,y:o}=e,{dx:r,dy:s}=t,a=1/0,c=null;for(let l of this.obstacles){let u=l.left-n,h=l.right+n,d=l.top+n,_=l.bottom-n,y=null;r===1&&s===0?o>_&&o<d&&i<l.left&&(y=l.left-i):r===-1&&s===0?o>_&&o<d&&i>l.right&&(y=i-l.right):r===0&&s===1?i>u&&i<h&&o<l.bottom&&(y=l.bottom-o):r===0&&s===-1&&i>u&&i<h&&o>l.top&&(y=o-l.top),y!==null&&y<a&&(a=y,c=l)}return{dx:r,dy:s,wallDistance:a,obstacle:c}}getObstaclesOverlappingRegion(e){let t=[];for(let n of this.obstacles){let{left:i,right:o,top:r,bottom:s}=n;i<=e.maxX&&o>=e.minX&&r<=e.maxY&&s>=e.minY&&t.push(n)}return t}};function W1t(e){if(e.length<4)return e;let t=[{...e[0]}],n=e[0].layer;for(let i=1;i<e.length;i++){let o={start:e[i-1],end:e[i]},r=e[i].route_type==="via"||e[i-1].route_type==="via";if(e[i].layer!==n||r){t.push({...e[i]}),n=e[i].layer;continue}let s=!1,a=null,c=-1;for(let u=0;u<t.length-1;u++){let h={start:t[u],end:t[u+1]};if(h.start.layer===o.start.layer&&h.start.layer===o.start.layer){let d=Z1t(h,o);if(d){s=!0,a={...d,layer:n},c=u;break}}}s&&a&&(t.splice(c+1),t.push(a));let l=t[t.length-1];(l.x!==e[i].x||l.y!==e[i].y)&&t.push(e[i])}return t}function Z1t(e,t){if(e.start.x===e.end.x&&t.start.x===t.end.x||e.start.y===e.end.y&&t.start.y===t.end.y)return null;let n;if(e.start.x===e.end.x){let i=e.start.x,o=t.start.y;n={...e.start,x:i,y:o}}else{let i=t.start.x,o=e.start.y;n={...e.start,x:i,y:o}}return VF(n,e)&&VF(n,t)?n:null}function VF(e,t){return e.x>=Math.min(t.start.x,t.end.x)&&e.x<=Math.max(t.start.x,t.end.x)&&e.y>=Math.min(t.start.y,t.end.y)&&e.y<=Math.max(t.start.y,t.end.y)}function K1t(e){let t=[e[0]];for(let n=1;n<e.length-1;n++){let[i,o,r]=[e[n-1],e[n],e[n+1]];t.push(o),!(o.route_type!=="wire"||i.route_type!=="wire"||r.route_type!=="wire")&&i.layer===o.layer&&o.layer!==r.layer&&t.push({route_type:"via",from_layer:o.layer,to_layer:r.layer,x:o.x,y:o.y})}return t.push(e[e.length-1]),t}var E$t=(0,JF.default)("autorouter:shortenPathWithShortcuts");function J1t(e,t){if(e.length<=2)return e;let n=[e[0]];for(let i=1;i<e.length;i++){let o={start:n[n.length-1],end:e[i]},r=-1,s=o.start.x===o.end.x,a=o.start.y===o.end.y;for(let c=i+1;c<e.length;c++){if(c<=r)continue;let l={start:e[c],end:e[c+1]};if(!l.end)continue;let u=l.start.x===l.end.x,h=l.start.y===l.end.y,d=s&&u,_=a&&h;if(_&&d||!(d||_))continue;let g=!1,x=Math.min(o.start.x,o.end.x),w=Math.max(o.start.x,o.end.x),S=Math.min(l.start.x,l.end.x),T=Math.max(l.start.x,l.end.x),I=Math.min(o.start.y,o.end.y),E=Math.max(o.start.y,o.end.y),M=Math.min(l.start.y,l.end.y),k=Math.max(l.start.y,l.end.y);if(_?g=x<=T&&w>=S:d&&(g=I<=k&&E>=M),!g)continue;let N=[],A=n[n.length-1],R=e[c+2];if(!R)continue;_&&S<w&&R.x===S&&N.push({x:S,y:o.start.y,layer:o.start.layer}),_&&T>x&&R.x===T&&N.push({x:T,y:o.start.y,layer:o.start.layer}),d&&M<E&&R.y===M&&N.push({x:o.start.x,y:M,layer:o.start.layer}),d&&k>I&&R.y===k&&N.push({x:o.start.x,y:k,layer:o.start.layer});let $=null;for(let j of N)if(!(t(A,j)||t(R,j))){$=j;break}if($){n.push($),i=c+1,r=c+1;break}}r===-1&&n.push(e[i])}return n[n.length-1]!==e[e.length-1]&&n.push(e[e.length-1]),n}var Dl=(0,WF.default)("autorouting-dataset:astar"),QF=class{constructor(e){P(this,"openSet",[]);P(this,"closedSet",new Set);P(this,"debug",!1);P(this,"debugSolutions");P(this,"debugMessage",null);P(this,"debugTraceCount",0);P(this,"input");P(this,"obstacles");P(this,"allObstacles");P(this,"startNode");P(this,"goalPoint");P(this,"GRID_STEP");P(this,"OBSTACLE_MARGIN");P(this,"MAX_ITERATIONS");P(this,"isRemovePathLoopsEnabled");P(this,"isShortenPathWithShortcutsEnabled");P(this,"GREEDY_MULTIPLIER",1.1);P(this,"iterations",-1);this.input=e.input,this.allObstacles=e.input.obstacles,this.startNode=e.startNode,this.goalPoint=e.goalPoint?{l:0,...e.goalPoint}:void 0,this.GRID_STEP=e.GRID_STEP??.1,this.OBSTACLE_MARGIN=e.OBSTACLE_MARGIN??.15,this.MAX_ITERATIONS=e.MAX_ITERATIONS??100,this.debug=e.debug??Dl.enabled,this.isRemovePathLoopsEnabled=e.isRemovePathLoopsEnabled??!1,this.isShortenPathWithShortcutsEnabled=e.isShortenPathWithShortcutsEnabled??!1,this.debug&&(Dl.enabled=!0),Dl.enabled&&(this.debugSolutions={},this.debugMessage="")}getNeighbors(e){return[]}isSameNode(e,t){return $l(e,t)<this.GRID_STEP}computeG(e,t){return e.g+$l(e,t)}computeH(e){return $l(e,this.goalPoint)}getNodeName(e){return qF(e,this.GRID_STEP)}solveOneStep(){this.iterations+=1;let{openSet:e,closedSet:t,GRID_STEP:n,goalPoint:i}=this;e.sort((a,c)=>a.f-c.f);let o=e.shift();if(this.computeH(o)<=n*2)return{solved:!0,current:o,newNeighbors:[]};this.closedSet.add(this.getNodeName(o));let s=[];for(let a of this.getNeighbors(o)){if(t.has(this.getNodeName(a)))continue;let c=this.computeG(o,a),l=this.openSet.find(u=>this.isSameNode(u,a));if(!l||c<l.g){let u=this.computeH(a),h=c+u*this.GREEDY_MULTIPLIER,d={...a,g:c,h:u,f:h,obstacleHit:a.obstacleHit??void 0,manDistFromParent:$l(o,a),nodesInPath:o.nodesInPath+1,parent:o,enterMarginCost:a.enterMarginCost,travelMarginCostFactor:a.travelMarginCostFactor};e.push(d),s.push(d)}}return Dl.enabled&&(e.sort((a,c)=>a.f-c.f),this.drawDebugSolution({current:o,newNeighbors:s})),{solved:!1,current:o,newNeighbors:s}}getStartNode(e){return{x:e.pointsToConnect[0].x,y:e.pointsToConnect[0].y,manDistFromParent:0,f:0,g:0,h:0,nodesInPath:0,parent:null}}layerToIndex(e){return 0}indexToLayer(e){return"top"}preprocessConnectionBeforeSolving(e){return e}solveConnection(e){if(e.pointsToConnect.length>2)throw new Error("GeneralizedAstarAutorouter doesn't currently support 2+ points in a connection");e=this.preprocessConnectionBeforeSolving(e);let{pointsToConnect:t}=e;for(this.iterations=0,this.closedSet=new Set,this.startNode=this.getStartNode(e),this.goalPoint={...t[t.length-1],l:this.layerToIndex(t[t.length-1].layer)},this.openSet=[this.startNode];this.iterations<this.MAX_ITERATIONS;){let{solved:n,current:i}=this.solveOneStep();if(n){let o=[],r=i;for(;r;){let s=r.l;o.unshift({x:r.x,y:r.y,layer:s!==void 0?this.indexToLayer(s):t[0].layer}),r=r.parent}return Dl.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations
160
160
  `),this.isRemovePathLoopsEnabled&&(o=W1t(o)),this.isShortenPathWithShortcutsEnabled&&(o=J1t(o,(s,a)=>{if(s.x===a.x&&s.y===a.y)return!1;let c=this.obstacles.getOrthoDirectionCollisionInfo({x:s.x,y:s.y,l:this.layerToIndex(s.layer)??0},{dx:Math.sign(a.x-s.x),dy:Math.sign(a.y-s.y),dl:0},{margin:.05}),l=Math.sqrt((s.x-a.x)**2+(s.y-a.y)**2);return c.wallDistance<l})),{solved:!0,route:o,connectionName:e.name}}if(this.openSet.length===0)break}return Dl.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations (failed)
161
- `),{solved:!1,connectionName:e.name}}createObstacleList({dominantLayer:e,connection:t,obstaclesFromTraces:n}){return new KF(this.allObstacles.filter(i=>!i.connectedTo.includes(t.name)).filter(i=>i.layers.includes(e)).concat(n??[]))}postprocessConnectionSolveResult(e,t){return t}solve(){let e=[],t=[];this.debugTraceCount=0;for(let n of this.input.connections){let i=n.pointsToConnect[0].layer??"top";this.debugTraceCount+=1,this.obstacles=this.createObstacleList({dominantLayer:i,connection:n,obstaclesFromTraces:t});let o=this.solveConnection(n);o=this.postprocessConnectionSolveResult(n,o),e.push(o),Dl.enabled&&this.drawDebugTraceObstacles(t),o.solved&&t.push(...ZF(o.route.map(r=>({x:r.x,y:r.y,layer:r.layer??i})),n.name))}return e}solveAndMapToTraces(){return this.solve().flatMap(t=>t.solved?[{type:"pcb_trace",pcb_trace_id:`pcb_trace_for_${t.connectionName}`,route:K1t(t.route.map(n=>({route_type:"wire",x:n.x,y:n.y,width:this.input.minTraceWidth,layer:n.layer})))}]:[])}getDebugGroup(){let e=`t${this.debugTraceCount}_iter[${this.iterations-1}]`;return this.iterations<30||this.iterations<100&&this.iterations%10===0||this.iterations<1e3&&this.iterations%100===0||!this.debugSolutions?e:null}drawDebugTraceObstacles(e){let{debugTraceCount:t,debugSolutions:n}=this;for(let i in n)i.startsWith(`t${t}_`)&&n[i].push(...e.map((o,r)=>({type:"pcb_smtpad",pcb_component_id:"",layer:o.layers[0],width:o.width,shape:"rect",x:o.center.x,y:o.center.y,pcb_smtpad_id:`trace_obstacle_${r}`,height:o.height})))}drawDebugSolution({current:e,newNeighbors:t}){let n=this.getDebugGroup();if(!n)return;let{openSet:i,debugTraceCount:o,debugSolutions:r}=this;r[n]??(r[n]=[]);let s=r[n];s.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${e.x}_${e.y}`,font:"tscircuit2024",font_size:.25,text:"X"+(e.l!==void 0?e.l:""),pcb_component_id:"",layer:"top",anchor_position:{x:e.x,y:e.y},anchor_alignment:"center"});for(let a=0;a<i.length;a++){let c=i[a];s.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${c.x}_${c.y}`,layer:"top",route:[[0,.05],[.05,0],[0,-.05],[-.05,0],[0,.05]].map(([l,u])=>({x:c.x+l,y:c.y+u})),stroke_width:.01}),s.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${c.x}_${c.y}`,font:"tscircuit2024",font_size:.03,text:a.toString(),pcb_component_id:"",layer:"top",anchor_position:{x:c.x,y:c.y},anchor_alignment:"center"})}if(e.parent){let a=[],c=e;for(;c;)a.unshift(c),c=c.parent;s.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${e.x}_${e.y}`,layer:"top",route:a,stroke_width:.01})}}},Q1t=(0,tz.default)("autorouting-dataset:infinite-grid-ijump-astar:get-distance-to-overcome-obstacle");function TI({node:e,travelDir:t,wallDir:n,obstacle:i,obstacles:o,obstaclesInRow:r=0,OBSTACLE_MARGIN:s=.15,SHOULD_DETECT_CONJOINED_OBSTACLES:a=!1,MAX_CONJOINED_OBSTACLES:c=20}){let l;if(t.dx===0?t.dy>0?l=i.center.y+i.height/2-e.y:l=e.y-(i.center.y-i.height/2):t.dx>0?l=i.center.x+i.width/2-e.x:l=e.x-(i.center.x-i.width/2),l+=s,a&&r<c){let u=o.getObstacleAt(e.x+t.dx*l+n.dx*(n.wallDistance+.001),e.y+t.dy*l+n.dy*(n.wallDistance+.001));if(u===i)return l;if(u&&u.type==="rect"){let h=t.dy===0,d=h?i.height:i.width;if((h?u.height:u.width)>d)return Q1t("next obstacle on path is bigger, not trying to overcome it"),l;let y=TI({node:{x:e.x+t.dx*l,y:e.y+t.dy*l},travelDir:t,wallDir:n,obstacle:u,obstacles:o,obstaclesInRow:r+1,SHOULD_DETECT_CONJOINED_OBSTACLES:a,MAX_CONJOINED_OBSTACLES:c,OBSTACLE_MARGIN:s});l+=y}}return l}var t_t=class extends QF{constructor(){super(...arguments);P(this,"MAX_ITERATIONS",200)}getNeighbors(t){let n=this.obstacles,i=this.goalPoint,o;t.parent?o=YF(t.parent,t):o=YF(t,i);let r=[{dx:0,dy:1},{dx:1,dy:0},{dx:0,dy:-1},{dx:-1,dy:0}].filter(a=>a.dx===o.dx*-1&&a.dy===o.dy*-1?!1:!(a.dx===o.dx&&a.dy===o.dy&&t.parent?.obstacleHit)).map(a=>n.getOrthoDirectionCollisionInfo(t,a,{margin:this.OBSTACLE_MARGIN})).filter(a=>a.wallDistance>=this.OBSTACLE_MARGIN),s=[];for(let a of r){let c=null;t?.obstacleHit&&(c=TI({node:t,travelDir:a,wallDir:{...o,wallDistance:this.OBSTACLE_MARGIN},obstacle:t.obstacleHit,obstacles:n,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let l=UF(t,i,a),u=(a.dx===0||Math.sign(i.x-t.x)===a.dx)&&(a.dy===0||Math.sign(i.y-t.y)===a.dy);l<a.wallDistance&&l>0&&u?s.push({...a,travelDistance:l}):c!==null&&c<a.wallDistance?s.push({...a,travelDistance:c}):a.wallDistance!==1/0&&s.push({...a,travelDistance:a.wallDistance-this.OBSTACLE_MARGIN})}return s.filter(a=>!n.isObstacleAt(t.x+a.dx*a.travelDistance,t.y+a.dy*a.travelDistance)).map(a=>({x:t.x+a.dx*a.travelDistance,y:t.y+a.dy*a.travelDistance,obstacleHit:a.obstacle}))}};function e_t(e,t=4){let{center:n,width:i,height:o,rotation:r}=e,s=[],a=r*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(r%360+360)%360;if(o<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*c,x=-y*l,w=d*1.1,S=Math.abs(o*c)+Math.abs(d*l);s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}else{let d=o/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*l,x=y*c,w=Math.abs(i*c)+Math.abs(d*l),S=d*1.1;s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}return s}var Gg=["top","inner1","inner2","bottom"],ez=(e,t)=>{let n=o=>t?o.concat(o.map(r=>t?.getNetConnectedToId(r)).filter(Boolean)):o,i=[];for(let o of e)if(o.type==="pcb_smtpad"){if(o.shape==="circle")i.push({type:"oval",layers:[o.layer],center:{x:o.x,y:o.y},width:o.radius*2,height:o.radius*2,connectedTo:n([o.pcb_smtpad_id])});else if(o.shape==="rect")i.push({type:"rect",layers:[o.layer],center:{x:o.x,y:o.y},width:o.width,height:o.height,connectedTo:n([o.pcb_smtpad_id])});else if(o.shape==="rotated_rect"){let r={center:{x:o.x,y:o.y},width:o.width,height:o.height,rotation:o.ccw_rotation},s=e_t(r);for(let a of s)i.push({type:"rect",layers:[o.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([o.pcb_smtpad_id])})}}else if(o.type==="pcb_keepout")o.shape==="circle"?i.push({type:"oval",layers:o.layers,center:{x:o.center.x,y:o.center.y},width:o.radius*2,height:o.radius*2,connectedTo:[]}):o.shape==="rect"&&i.push({type:"rect",layers:o.layers,center:{x:o.center.x,y:o.center.y},width:o.width,height:o.height,connectedTo:[]});else if(o.type==="pcb_hole")o.hole_shape==="oval"?i.push({type:"oval",center:{x:o.x,y:o.y},width:o.hole_width,height:o.hole_height,connectedTo:[]}):o.hole_shape==="square"?i.push({type:"rect",layers:Gg,center:{x:o.x,y:o.y},width:o.hole_diameter,height:o.hole_diameter,connectedTo:[]}):(o.hole_shape==="round"||o.hole_shape==="circle")&&i.push({type:"rect",layers:Gg,center:{x:o.x,y:o.y},width:o.hole_diameter,height:o.hole_diameter,connectedTo:[]});else if(o.type==="pcb_plated_hole")o.shape==="circle"?i.push({type:"oval",layers:Gg,center:{x:o.x,y:o.y},width:o.outer_diameter,height:o.outer_diameter,connectedTo:n([o.pcb_plated_hole_id])}):(o.shape==="oval"||o.shape==="pill")&&i.push({type:"oval",layers:Gg,center:{x:o.x,y:o.y},width:o.outer_width,height:o.outer_height,connectedTo:n([o.pcb_plated_hole_id])});else if(o.type==="pcb_trace"){let r=ZF(o.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),o.source_trace_id);i.push(...r)}else o.type==="pcb_via"&&i.push({type:"rect",layers:o.layers,center:{x:o.x,y:o.y},connectedTo:[],width:o.outer_diameter,height:o.outer_diameter});return i};function HF(e){let{pcbConnMap:t,goalElementId:n}=e;if(!n.startsWith("pcb_port_"))throw new Error(`Currently alternative goal boxes must have a goal id with prefix "pcb_port_" (got ${n})`);let i=t.getAllTracesConnectedToPort(n);return ez(i).map(o=>({...o,connectedTo:[n]}))}var nz=e=>{let{connection:t,pcbConnMap:n}=e;if(t.pointsToConnect.length!==2)throw new Error(`Connection must have exactly 2 points for alternative goal boxes (got ${t.pointsToConnect.length})`);let[i,o]=t.pointsToConnect;if(!i.pcb_port_id||!o.pcb_port_id)throw new Error(`Connection points must have pcb_port_id for alternative goal box calculation (got ${i.pcb_port_id} and ${o.pcb_port_id})`);let r=HF({goalElementId:i.pcb_port_id,pcbConnMap:n}).concat([{center:i,width:.01,height:.01,connectedTo:[i.pcb_port_id],layers:[i.layer],type:"rect"}]),s=HF({goalElementId:o.pcb_port_id,pcbConnMap:n}).concat([{center:o,width:.01,height:.01,connectedTo:[o.pcb_port_id],layers:[o.layer],type:"rect"}]);if(r.length<=1&&s.length<=1)return{...t,startPoint:i,endPoint:o,goalBoxes:[]};let a=gf(r,s),c,l,u;return r.length>=s.length?(c={...o,...a.pointB},l={...i,...a.pointA},u=r):(c={...i,...a.pointA},l={...o,...a.pointB},u=s),{startPoint:c,endPoint:l,goalBoxes:u,name:t.name,pointsToConnect:[c,l]}},n_t=(e,t={})=>{let n={minTraceWidth:.1};n.layerCount=t.layerCount??1,n.obstacles=ez(e,t.connMap),n.connections=[];for(let o of e)if(o.type==="source_trace"){let r={name:o.source_trace_id,pointsToConnect:o.connected_source_port_ids.map(s=>{let a=Rr(e).pcb_port.getWhere({source_port_id:s});if(!a)throw new Error(`Could not find pcb_port for source_port_id "${s}"`);return{x:a.x,y:a.y,layer:a.layers?.[0]??"top",pcb_port_id:a.pcb_port_id}})};if(t.optimizeWithGoalBoxes){let s=new Hg(e);r=nz({connection:r,pcbConnMap:s})}n.connections.push(r),i_t(n.obstacles,r.pointsToConnect,r.name)}let i={minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0};for(let o of n.obstacles)i.minX=Math.min(i.minX,o.center.x-o.width/2),i.maxX=Math.max(i.maxX,o.center.x+o.width/2),i.minY=Math.min(i.minY,o.center.y-o.height/2),i.maxY=Math.max(i.maxY,o.center.y+o.height/2);for(let o of n.connections)for(let r of o.pointsToConnect)i.minX=Math.min(i.minX,r.x),i.maxX=Math.max(i.maxX,r.x),i.minY=Math.min(i.minY,r.y),i.maxY=Math.max(i.maxY,r.y);return n.bounds=i,n},i_t=(e,t,n)=>{for(let i of t)for(let o of e)o_t(i,o)&&o.connectedTo.push(n)};function o_t(e,t){let n=t.width/2,i=t.height/2;if(t.type==="rect")return e.x>=t.center.x-n&&e.x<=t.center.x+n&&e.y>=t.center.y-i&&e.y<=t.center.y+i;if(t.type==="oval"){let o=(e.x-t.center.x)/n,r=(e.y-t.center.y)/i;return o*o+r*r<=1}return!1}function GF(e,t){let n=t.x>e.x?1:t.x<e.x?-1:0,i=t.y>e.y?1:t.y<e.y?-1:0,o=t.l>e.l?1:t.l<e.l?-1:0;return{dx:n,dy:i,dl:o}}var MI={1:["top"],2:["top","bottom"],4:["top","inner1","inner2","bottom"]},r_t=e=>MI[e];function iz(e,t){let i=MI[e].indexOf(t);if(i===-1)throw new Error(`Invalid layer for getLayerIndex (for layerCount === ${e}): "${t}"`);return i}function s_t(e,t){let i=MI[e][t];if(!i)throw new Error(`Invalid index for indexToLayer (for layerCount === ${e}): "${t}"`);return i}var a_t=class extends KF{constructor(t,n){super([]);P(this,"obstacles");P(this,"GRID_STEP",.1);P(this,"layerCount");this.layerCount=t;let i=r_t(t);this.obstacles=n.flatMap(o=>o.layers.filter(r=>i.includes(r)).map(r=>({...o,left:o.center.x-o.width/2,right:o.center.x+o.width/2,top:o.center.y+o.height/2,bottom:o.center.y-o.height/2,l:iz(t,r)})))}getObstacleAt(t,n,i,o){o??(o=this.GRID_STEP);for(let r of this.obstacles){if(r.l!==i)continue;let s=r.width/2+o,a=r.height/2+o;if(t>=r.center.x-s&&t<=r.center.x+s&&n>=r.center.y-a&&n<=r.center.y+a)return r}return null}isObstacleAt(t,n,i,o){return this.getObstacleAt(t,n,i,o)!==null}getDirectionDistancesToNearestObstacle3d(t,n,i){let{GRID_STEP:o}=this,r={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let s of this.obstacles)if(s.l===i&&s.type==="rect"){let a=s.center.x-s.width/2-o,c=s.center.x+s.width/2+o,l=s.center.y+s.height/2+o,u=s.center.y-s.height/2-o;n>=u&&n<=l&&t>a&&(r.left=Math.min(r.left,t-c)),n>=u&&n<=l&&t<c&&(r.right=Math.min(r.right,a-t)),t>=a&&t<=c&&n<l&&(r.top=Math.min(r.top,u-n)),t>=a&&t<=c&&n>u&&(r.bottom=Math.min(r.bottom,n-l))}return r}getOrthoDirectionCollisionInfo(t,n,{margin:i=0}={}){let{x:o,y:r,l:s}=t,{dx:a,dy:c,dl:l}=n,u=1/0,h=null;if(l!==0){let d=s+l;return this.isObstacleAt(o,r,d,i)?(u=1,h=this.getObstacleAt(o,r,d,i)):u=1,{dx:a,dy:c,dl:l,wallDistance:u,obstacle:h}}else{for(let d of this.obstacles){if(d.l!==s)continue;let _=d.left-i,y=d.right+i,g=d.top+i,x=d.bottom-i,w=null;a===1&&c===0?r>x&&r<g&&o<d.left&&(w=d.left-o):a===-1&&c===0?r>x&&r<g&&o>d.right&&(w=o-d.right):a===0&&c===1?o>_&&o<y&&r<d.bottom&&(w=d.bottom-r):a===0&&c===-1&&o>_&&o<y&&r>d.top&&(w=r-d.top),w!==null&&w<u&&(u=w,h=d)}return{dx:a,dy:c,dl:0,wallDistance:u,obstacle:h}}}getObstaclesOverlappingRegion(t){let n=[];for(let i of this.obstacles){if(i.l!==t.l)continue;let{left:o,right:r,top:s,bottom:a}=i;o<=t.maxX&&r>=t.minX&&s>=t.minY&&a<=t.maxY&&n.push(i)}return n}},Ug=class extends QF{constructor(t){super(t);P(this,"MAX_ITERATIONS",500);P(this,"VIA_COST",4);P(this,"VIA_DIAMETER",.5);P(this,"allowLayerChange",!0);P(this,"layerCount");P(this,"obstacles");P(this,"optimizeWithGoalBoxes");P(this,"connMap");P(this,"pcbConnMap");P(this,"GOAL_RUSH_FACTOR",1.1);P(this,"defaultGoalViaMargin",.5);P(this,"marginsWithCosts");this.layerCount=t.input.layerCount??2,this.MAX_ITERATIONS=t.MAX_ITERATIONS??this.MAX_ITERATIONS,this.VIA_COST=t.VIA_COST??this.VIA_COST,this.connMap=t.connMap,this.pcbConnMap=t.pcbConnMap??new Hg,this.optimizeWithGoalBoxes=t.optimizeWithGoalBoxes??!1,this.obstacles=null,this.marginsWithCosts=t.marginsWithCosts??[{margin:1,enterCost:0,travelCostFactor:1},{margin:this.OBSTACLE_MARGIN,enterCost:10,travelCostFactor:2}]}get largestMargin(){return this.marginsWithCosts[0].margin}preprocessConnectionBeforeSolving(t){return this.optimizeWithGoalBoxes?nz({connection:t,pcbConnMap:this.pcbConnMap}):t}postprocessConnectionSolveResult(t,n){if(!n.solved)return n;if(this.optimizeWithGoalBoxes){let i=n.route.map(o=>({x:o.x,y:o.y,route_type:"wire",layer:o.layer,width:this.input.minTraceWidth}));i[0].start_pcb_port_id=t.pointsToConnect[0].pcb_port_id,i[i.length-1].end_pcb_port_id=t.pointsToConnect[1].pcb_port_id,this.pcbConnMap.addTrace({type:"pcb_trace",pcb_trace_id:`postprocess_trace_${BF(8)}`,route:i})}return n}createObstacleList({dominantLayer:t,connection:n,obstaclesFromTraces:i}){let o=this.connMap?this.connMap.getNetConnectedToId(n.name):n.name;if(!o)throw new Error(`The connection.name "${n.name}" wasn't present in the full connectivity map`);return new a_t(this.layerCount,this.allObstacles.filter(r=>!r.connectedTo.includes(o)).concat(i??[]))}computeG(t,n){let i=t.g+$l(t,n)*(t.travelMarginCostFactor??1)+(n.enterMarginCost??0);return(n.l??t.l!==-1??-1)&&(i+=this.VIA_COST),i}computeH(t){let n=Math.abs(t.x-this.goalPoint.x),i=Math.abs(t.y-this.goalPoint.y),o=Math.abs(t.l-this.goalPoint.l);return(n+i)**this.GOAL_RUSH_FACTOR+o*this.VIA_COST}getStartNode(t){return{...super.getStartNode(t),l:this.layerToIndex(t.pointsToConnect[0].layer)}}layerToIndex(t){return iz(this.layerCount,t)}indexToLayer(t){return s_t(this.layerCount,t)}getNodeName(t){return`${qF(t,this.GRID_STEP)}-${t.l??0}`}hasSpaceForVia(t,n){return t.every(i=>this.obstacles.getObstaclesOverlappingRegion({minX:n.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:n.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:n.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:n.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:i}).length===0)}getNeighborsSurroundingGoal(t){let n=this.obstacles,i=this.goalPoint,o=[],r=[{dx:1,dy:0,dl:0},{dx:-1,dy:0,dl:0},{dx:0,dy:1,dl:0},{dx:0,dy:-1,dl:0}],s=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin;for(let a of r){let c={x:t.x+a.dx*s,y:t.y+a.dy*s,l:t.l+a.dl,obstacleHit:null};this.hasSpaceForVia([t.l,i.l],c)&&o.push(c)}return o}getNeighbors(t){let n=this.obstacles,i=this.goalPoint,o=$l(t,i);if(o<=this.OBSTACLE_MARGIN)return this.getNeighborsSurroundingGoal(t);let r;t.parent?r=GF(t.parent,t):r=GF(t,i);let s=[{dx:0,dy:1,dl:0},{dx:1,dy:0,dl:0},{dx:0,dy:-1,dl:0},{dx:-1,dy:0,dl:0}],a=o>this.VIA_DIAMETER+this.OBSTACLE_MARGIN,c=$l(t,this.startNode)>this.VIA_DIAMETER+this.OBSTACLE_MARGIN;this.allowLayerChange&&a&&c&&(t.l<this.layerCount-1&&s.push({dx:0,dy:0,dl:1}),t.l>0&&s.push({dx:0,dy:0,dl:-1}));let l=s.filter(h=>h.dx===r.dx*-1&&h.dy===r.dy*-1&&h.dl===r.dl*-1?!1:!(h.dx===r.dx&&h.dy===r.dy&&h.dl===r.dl&&t.parent?.obstacleHit)).map(h=>n.getOrthoDirectionCollisionInfo(t,h,{margin:this.OBSTACLE_MARGIN})).filter(h=>!(h.wallDistance<this.OBSTACLE_MARGIN)),u=[];for(let h of l){let d=h.dx===0&&h.dy===0&&h.dl===1,_=h.dx===0&&h.dy===0&&h.dl===-1;if((d||_)&&![t.l,t.l+h.dl].every(S=>n.getObstaclesOverlappingRegion({minX:t.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:t.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:t.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:t.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:S}).length===0))continue;if(d){t.l<this.layerCount-1&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}if(_){t.l>0&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}let y=null;t?.obstacleHit&&(y=TI({node:t,travelDir:h,wallDir:{...r,wallDistance:this.OBSTACLE_MARGIN},obstacle:t.obstacleHit,obstacles:n,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let g=UF(t,i,h),x=(h.dx===0||Math.sign(i.x-t.x)===h.dx)&&(h.dy===0||Math.sign(i.y-t.y)===h.dy);if(g<h.wallDistance&&g>0&&x){let w=t.l===i.l,S=0;!w&&Math.abs(g-o)<this.GRID_STEP&&(S=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin),u.push({...h,travelDistance:g-S,enterMarginCost:0,travelMarginCostFactor:1})}else if(y!==null&&y<h.wallDistance){for(let{margin:w,enterCost:S,travelCostFactor:T}of this.marginsWithCosts)y-this.OBSTACLE_MARGIN+w*2<h.wallDistance&&u.push({...h,travelDistance:y-this.OBSTACLE_MARGIN+w,enterMarginCost:S,travelMarginCostFactor:T});if(h.wallDistance===1/0)u.push({...h,travelDistance:g,enterMarginCost:0,travelMarginCostFactor:1});else if(h.wallDistance>this.largestMargin)for(let{margin:w,enterCost:S,travelCostFactor:T}of this.marginsWithCosts)h.wallDistance>this.largestMargin+w&&u.push({...h,travelDistance:h.wallDistance-w,enterMarginCost:S,travelMarginCostFactor:T})}else if(h.wallDistance!==1/0)for(let{margin:w,enterCost:S,travelCostFactor:T}of this.marginsWithCosts)h.wallDistance>w&&u.push({...h,travelDistance:h.wallDistance-w,enterMarginCost:S,travelMarginCostFactor:T})}return u.map(h=>({x:t.x+h.dx*h.travelDistance,y:t.y+h.dy*h.travelDistance,l:t.l+h.dl,obstacleHit:h.obstacle,travelMarginCostFactor:h.travelMarginCostFactor,enterMarginCost:h.enterMarginCost}))}};function oz(e){let t=n_t(e),n=new t_t({input:t});return{solution:n.solveAndMapToTraces(),debugSolutions:n.debugSolutions,debugMessage:n.debugMessage}}K();K();vt();K();K();vt();vt();K();K();vt();K();K();K();K();vt();K();K();K();vt();K();K();vt();K();K();K();K();K();K();K();K();K();K();vt();K();vt();K();vt();K();K();vt();vt();K();vt();K();K();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();K();K();K();K();K();K();vt();K();vt();K();K();vt();K();vt();K();K();K();vt();K();vt();vt();K();K();K();vt();K();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();vt();K();vt();K();vt();K();K();vt();vt();K();K();vt();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();vt();K();vt();K();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();var Ct=e=>{};Ct("extra props b");Ct("missing props b");Ct(!0);Ct("property a has mismatched types");var c_t=p.enum(["up","down","left","right"]),U$t=p.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);Ct(!0);Ct(!0);var es=p.array(p.string().or(p.number()));Ct(!0);var Zg=p.object({x:Y,y:Y,z:Y}),l_t=p.object({x:p.union([p.number(),p.string()]),y:p.union([p.number(),p.string()]),z:p.union([p.number(),p.string()])}),Qa=p.object({rotationOffset:p.number().or(l_t).optional(),positionOffset:Zg.optional(),size:Zg.optional(),modelUnitToMmScale:Y.optional(),zOffsetFromSurface:Y.optional()});Ct(!0);var u_t=Qa.extend({stlUrl:p.string()}),p_t=Qa.extend({objUrl:p.string(),mtlUrl:p.string().optional()}),h_t=Qa.extend({gltfUrl:p.string()}),d_t=Qa.extend({glbUrl:p.string()}),f_t=Qa.extend({stepUrl:p.string()}),m_t=Qa.extend({wrlUrl:p.string()}),__t=Qa.extend({jscad:p.record(p.any())}),hz=p.union([p.null(),p.string(),p.custom(e=>e&&typeof e=="object"&&"type"in e&&"props"in e),u_t,p_t,h_t,d_t,f_t,m_t,__t]);Ct(!0);var y_t=p.custom(e=>!0),NI=p.object({silkscreenFontSize:Y.optional(),silkscreenTextPosition:p.union([p.enum(["centered","outside","none"]),p.object({offsetX:p.number(),offsetY:p.number()})]).optional(),silkscreenTextVisibility:p.enum(["hidden","visible","inherit"]).optional()});Ct(!0);var g_t=p.custom(e=>!0),Oe=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbRotation:Be.optional(),pcbPositionAnchor:p.string().optional(),pcbPositionMode:p.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),layer:se.optional(),pcbMarginTop:Y.optional(),pcbMarginRight:Y.optional(),pcbMarginBottom:Y.optional(),pcbMarginLeft:Y.optional(),pcbMarginX:Y.optional(),pcbMarginY:Y.optional(),pcbStyle:NI.optional(),pcbRelative:p.boolean().optional(),relative:p.boolean().optional()});Ct(!0);var Kg=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbRotation:Be.optional(),pcbPositionAnchor:p.string().optional(),pcbPositionMode:p.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),pcbMarginTop:Y.optional(),pcbMarginRight:Y.optional(),pcbMarginBottom:Y.optional(),pcbMarginLeft:Y.optional(),pcbMarginX:Y.optional(),pcbMarginY:Y.optional(),pcbStyle:NI.optional(),schMarginTop:Y.optional(),schMarginRight:Y.optional(),schMarginBottom:Y.optional(),schMarginLeft:Y.optional(),schMarginX:Y.optional(),schMarginY:Y.optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Be.optional(),layer:se.optional(),footprint:y_t.optional(),symbol:g_t.optional(),relative:p.boolean().optional(),schRelative:p.boolean().optional(),pcbRelative:p.boolean().optional()});Ct(!0);var b_t=p.object({supplierPartNumbers:p.record(Mp,p.array(p.string())).optional()});Ct(!0);var x_t=p.object({providesPower:p.boolean().optional(),requiresPower:p.boolean().optional(),providesGround:p.boolean().optional(),requiresGround:p.boolean().optional(),providesVoltage:p.union([p.string(),p.number()]).optional(),requiresVoltage:p.union([p.string(),p.number()]).optional(),doNotConnect:p.boolean().optional(),includeInBoardPinout:p.boolean().optional(),highlightColor:p.string().optional()});Ct(!0);var Dn=Kg.merge(b_t).extend({key:p.any().optional(),name:p.string(),cadModel:hz.optional(),children:p.any().optional(),symbolName:p.string().optional(),doNotPlace:p.boolean().optional(),obstructsWithinBounds:p.boolean().optional().describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath"),pinAttributes:p.record(p.string(),x_t).optional()});Ct(!0);var kI=["pin1","left","pin2","right"],Jg=["pin1","left","anode","pos","pin2","right","cathode","neg"],sjt=Y.or(p.enum(["2x","3x","4x"])),tc=p.enum(["vertical","horizontal","pos_top","pos_bottom","pos_left","pos_right","neg_top","neg_bottom","neg_left","neg_right"]).describe("horizontal means pins go 1->2 rightward and vertical means pins go 1->2 downward (generally, positive on top)");Ct(!0);var qg=p.object({pins:p.array(p.union([p.number(),p.string()])),direction:p.union([p.literal("top-to-bottom"),p.literal("left-to-right"),p.literal("bottom-to-top"),p.literal("right-to-left")])}),xf=p.object({leftSize:p.number().optional().describe("@deprecated, use leftPinCount"),topSize:p.number().optional().describe("@deprecated, use topPinCount"),rightSize:p.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:p.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftSide:qg.optional(),rightSide:qg.optional(),topSide:qg.optional(),bottomSide:qg.optional()}),AI=xf;Ct(!0);var vf=p.record(p.object({marginLeft:Y.optional(),marginRight:Y.optional(),marginTop:Y.optional(),marginBottom:Y.optional(),leftMargin:Y.optional(),rightMargin:Y.optional(),topMargin:Y.optional(),bottomMargin:Y.optional()}));Ct(!0);var ur=p.string().regex(/^[A-Za-z0-9_]+$/),Zp=p.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),Gs=p.object({x:Y,y:Y}),Sf=p.object({edit_event_id:p.string(),in_progress:p.boolean().optional(),created_at:p.number()});Ct(!0);var v_t=Sf.extend({pcb_edit_event_type:p.literal("edit_component_location").describe("deprecated"),edit_event_type:p.literal("edit_pcb_component_location"),pcb_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var S_t=Sf.extend({pcb_edit_event_type:p.literal("edit_trace_hint").describe("deprecated"),edit_event_type:p.literal("edit_pcb_trace_hint").optional(),pcb_port_id:p.string(),pcb_trace_hint_id:p.string().optional(),route:p.array(p.object({x:p.number(),y:p.number(),via:p.boolean().optional()}))});Ct(!0);var w_t=Sf.extend({edit_event_type:p.literal("edit_schematic_component_location"),schematic_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var wjt=Sf.extend({edit_event_type:p.literal("edit_pcb_group_location"),pcb_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var Ijt=Sf.extend({edit_event_type:p.literal("edit_schematic_group_location"),schematic_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var Mjt=p.union([v_t,S_t,w_t]);Ct(!0);var P_t=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:qt});Ct(!0);var I_t=p.object({pcb_port_selector:p.string(),offsets:p.array(Fi)});Ct(!0);var T_t=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:qt});Ct(!0);var M_t=p.object({pcb_placements:p.array(P_t).optional(),manual_trace_hints:p.array(I_t).optional(),schematic_placements:p.array(T_t).optional()});Ct(!0);var Kp=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),jl=e=>p.record(p.enum(e),Kp),bf=p.object({layoutMode:p.enum(["grid","flex","match-adapt","relative","none"]).optional(),position:p.enum(["absolute","relative"]).optional(),grid:p.boolean().optional(),gridCols:p.number().or(p.string()).optional(),gridRows:p.number().or(p.string()).optional(),gridTemplateRows:p.string().optional(),gridTemplateColumns:p.string().optional(),gridTemplate:p.string().optional(),gridGap:p.number().or(p.string()).optional(),gridRowGap:p.number().or(p.string()).optional(),gridColumnGap:p.number().or(p.string()).optional(),flex:p.boolean().or(p.string()).optional(),flexDirection:p.enum(["row","column"]).optional(),alignItems:p.enum(["start","center","end","stretch"]).optional(),justifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),flexRow:p.boolean().optional(),flexColumn:p.boolean().optional(),gap:p.number().or(p.string()).optional(),pack:p.boolean().optional().describe("Pack the contents of this group using a packing strategy"),packOrderStrategy:p.enum(["largest_to_smallest","first_to_last","highest_to_lowest_pin_count"]).optional(),packPlacementStrategy:p.enum(["shortest_connection_along_outline"]).optional(),padding:D.optional(),paddingLeft:D.optional(),paddingRight:D.optional(),paddingTop:D.optional(),paddingBottom:D.optional(),paddingX:D.optional(),paddingY:D.optional(),width:D.optional(),height:D.optional(),matchAdapt:p.boolean().optional(),matchAdaptTemplate:p.any().optional()});Ct(!0);var rz=p.object({strokeWidth:D.optional(),dashed:p.boolean().optional(),solid:p.boolean().optional()}),C_t=p.custom(e=>typeof e=="string"),E_t=p.object({serverUrl:p.string().optional(),inputFormat:p.enum(["simplified","circuit-json"]).optional(),serverMode:p.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:p.boolean().optional(),cache:p.custom(e=>!0).optional(),traceClearance:D.optional(),groupMode:p.enum(["sequential_trace","subcircuit","sequential-trace"]).optional(),algorithmFn:p.custom(e=>typeof e=="function"||e===void 0).optional(),preset:p.enum(["sequential_trace","subcircuit","auto","auto_local","auto_cloud","freerouting","laser_prefab","sequential-trace","auto-local","auto-cloud"]).optional(),local:p.boolean().optional()}),N_t=p.union([p.literal("sequential_trace"),p.literal("subcircuit"),p.literal("auto"),p.literal("auto_local"),p.literal("auto_cloud"),p.literal("freerouting"),p.literal("laser_prefab"),p.literal("sequential-trace"),p.literal("auto-local"),p.literal("auto-cloud")]),k_t=p.string(),dz=p.union([E_t,N_t,k_t]),RI=Kg.extend({name:p.string().optional(),children:p.any().optional(),schTitle:p.string().optional(),key:p.any().optional(),showAsSchematicBox:p.boolean().optional(),connections:p.record(p.string(),Kp.optional()).optional(),schPinArrangement:AI.optional(),schPinSpacing:D.optional(),schPinStyle:vf.optional(),...bf.shape,grid:bf.shape.grid.describe("@deprecated use pcbGrid"),flex:bf.shape.flex.describe("@deprecated use pcbFlex"),pcbGrid:p.boolean().optional(),pcbGridCols:p.number().or(p.string()).optional(),pcbGridRows:p.number().or(p.string()).optional(),pcbGridTemplateRows:p.string().optional(),pcbGridTemplateColumns:p.string().optional(),pcbGridTemplate:p.string().optional(),pcbGridGap:p.number().or(p.string()).optional(),pcbGridRowGap:p.number().or(p.string()).optional(),pcbGridColumnGap:p.number().or(p.string()).optional(),pcbFlex:p.boolean().or(p.string()).optional(),pcbFlexGap:p.number().or(p.string()).optional(),pcbFlexDirection:p.enum(["row","column"]).optional(),pcbAlignItems:p.enum(["start","center","end","stretch"]).optional(),pcbJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),pcbFlexRow:p.boolean().optional(),pcbFlexColumn:p.boolean().optional(),pcbGap:p.number().or(p.string()).optional(),pcbPack:p.boolean().optional(),pcbPackGap:p.number().or(p.string()).optional(),schGrid:p.boolean().optional(),schGridCols:p.number().or(p.string()).optional(),schGridRows:p.number().or(p.string()).optional(),schGridTemplateRows:p.string().optional(),schGridTemplateColumns:p.string().optional(),schGridTemplate:p.string().optional(),schGridGap:p.number().or(p.string()).optional(),schGridRowGap:p.number().or(p.string()).optional(),schGridColumnGap:p.number().or(p.string()).optional(),schFlex:p.boolean().or(p.string()).optional(),schFlexGap:p.number().or(p.string()).optional(),schFlexDirection:p.enum(["row","column"]).optional(),schAlignItems:p.enum(["start","center","end","stretch"]).optional(),schJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),schFlexRow:p.boolean().optional(),schFlexColumn:p.boolean().optional(),schGap:p.number().or(p.string()).optional(),schPack:p.boolean().optional(),schMatchAdapt:p.boolean().optional(),pcbWidth:D.optional(),pcbHeight:D.optional(),minTraceWidth:D.optional(),schWidth:D.optional(),schHeight:D.optional(),pcbLayout:bf.optional(),schLayout:bf.optional(),cellBorder:rz.nullable().optional(),border:rz.nullable().optional(),schPadding:D.optional(),schPaddingLeft:D.optional(),schPaddingRight:D.optional(),schPaddingTop:D.optional(),schPaddingBottom:D.optional(),pcbPadding:D.optional(),pcbPaddingLeft:D.optional(),pcbPaddingRight:D.optional(),pcbPaddingTop:D.optional(),pcbPaddingBottom:D.optional(),pcbPositionAnchor:C_t.optional()}),fz=p.custom(e=>"findPart"in e),OI=RI.extend({manualEdits:M_t.optional(),schAutoLayoutEnabled:p.boolean().optional(),schTraceAutoLabelEnabled:p.boolean().optional(),schMaxTraceDistance:Y.optional(),routingDisabled:p.boolean().optional(),defaultTraceWidth:D.optional(),minTraceWidth:D.optional(),partsEngine:fz.optional(),pcbRouteCache:p.custom(e=>!0).optional(),autorouter:dz.optional(),square:p.boolean().optional(),emptyArea:p.string().optional(),filledArea:p.string().optional(),width:Y.optional(),height:Y.optional(),outline:p.array(Gs).optional(),outlineOffsetX:Y.optional(),outlineOffsetY:Y.optional(),circuitJson:p.array(p.any()).optional()}),A_t=OI.extend({subcircuit:p.literal(!0)}),mz=p.discriminatedUnion("subcircuit",[RI.extend({subcircuit:p.literal(!1).optional()}),A_t]);Ct(!0);Ct(!0);Ct(!0);Ct(!0);var Wp=p.custom(e=>typeof e=="string"),LI=OI.omit({connections:!0}).extend({material:p.enum(["fr4","fr1"]).default("fr4"),layers:p.union([p.literal(2),p.literal(4)]).default(2),borderRadius:Y.optional(),thickness:Y.optional(),boardAnchorPosition:Gs.optional(),boardAnchorAlignment:Zp.optional(),title:p.string().optional(),solderMaskColor:Wp.optional(),topSolderMaskColor:Wp.optional(),bottomSolderMaskColor:Wp.optional(),silkscreenColor:Wp.optional(),topSilkscreenColor:Wp.optional(),bottomSilkscreenColor:Wp.optional(),doubleSidedAssembly:p.boolean().optional().default(!1)});Ct(!0);var _z=RI.omit({width:!0,height:!0,children:!0}).extend({width:Y,height:Y,children:p.any().optional(),noSolderMask:p.boolean().optional()});Ct(!0);var Djt=OI.extend({padding:Y.optional(),paddingLeft:Y.optional(),paddingRight:Y.optional(),paddingTop:Y.optional(),paddingBottom:Y.optional()});Ct(!0);var R_t=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),O_t=p.custom().pipe(p.record(p.string(),R_t)),L_t=p.record(ur,ur.or(p.array(ur).readonly()).or(p.array(ur)));Ct(!0);var F_t=p.object({manufacturerPartNumber:p.string().optional(),supplierPartNumber:p.record(Mp,p.array(p.string())).optional()}),Jp=Dn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:L_t.optional(),showPinAliases:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),externallyConnectedPins:p.array(p.array(p.string())).optional(),schPinArrangement:xf.optional(),schPortArrangement:xf.optional(),pinCompatibleVariants:p.array(F_t).optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),noSchematicRepresentation:p.boolean().optional(),connections:O_t.optional()});Ct(!0);var yz=Jp;Ct(!0);var FI=Dn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(ur),ur.or(p.array(ur))).optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),schDirection:p.enum(["left","right"]).optional(),schPinArrangement:AI.optional(),schPortArrangement:xf.optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),pinCount:p.union([p.literal(2),p.literal(3)]).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),connections:p.custom().pipe(p.record(p.string(),Kp)).optional()});Ct(!0);var gz=FI.extend({bridgedPins:p.array(p.array(p.string())).optional(),bridged:p.boolean().optional()});Ct(!0);var Gjt=Dn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(ur),ur.or(p.array(ur))).optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),schDirection:p.enum(["left","right"]).optional(),schPortArrangement:xf.optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),standard:p.enum(["usb_c","m2"]).optional()});Ct(!0);var bz=Dn.extend({currentRating:p.union([p.number(),p.string()]),voltageRating:p.union([p.number(),p.string()]).optional(),schShowRatings:p.boolean().optional(),schOrientation:tc.optional(),connections:p.record(p.string(),p.union([p.string(),p.array(p.string()).readonly(),p.array(p.string())])).optional()}),Wg=p.custom().transform(e=>{if(e!==void 0)return Y.parse(e)}),xz=p.discriminatedUnion("shape",[Oe.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circle"),holeDiameter:Y,outerDiameter:Y,portHints:es.optional()}),Oe.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("oval"),outerWidth:Y,outerHeight:Y,holeWidth:Wg,holeHeight:Wg,innerWidth:Y.optional().describe("DEPRECATED use holeWidth"),innerHeight:Y.optional().describe("DEPRECATED use holeHeight"),portHints:es.optional()}),Oe.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill"),rectPad:p.boolean().optional(),outerWidth:Y,outerHeight:Y,holeWidth:Wg,holeHeight:Wg,innerWidth:Y.optional().describe("DEPRECATED use holeWidth"),innerHeight:Y.optional().describe("DEPRECATED use holeHeight"),portHints:es.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional()}),Oe.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circular_hole_with_rect_pad"),holeDiameter:Y,rectPadWidth:Y,rectPadHeight:Y,rectBorderRadius:Y.optional(),holeShape:p.literal("circle").optional(),padShape:p.literal("rect").optional(),portHints:es.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional()}),Oe.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill_hole_with_rect_pad"),holeShape:p.literal("pill"),padShape:p.literal("rect"),holeWidth:Y,holeHeight:Y,rectPadWidth:Y,rectPadHeight:Y,portHints:es.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional()})]).refine(e=>("innerWidth"in e&&e.innerWidth!==void 0&&(e.holeWidth??(e.holeWidth=e.innerWidth)),"innerHeight"in e&&e.innerHeight!==void 0&&(e.holeHeight??(e.holeHeight=e.innerHeight)),e));Ct(!0);var z_t=["pin1","pin2","pos","neg"],vz=Dn.extend({resistance:Ha,pullupFor:p.string().optional(),pullupTo:p.string().optional(),pulldownFor:p.string().optional(),pulldownTo:p.string().optional(),schOrientation:tc.optional(),connections:jl(z_t).optional()}),Sz=kI;Ct(!0);var wz=Dn.extend({maxResistance:Ha,pinVariant:p.enum(["two_pin","three_pin"]).optional()});Ct(!0);var D_t=kI,Pz=Dn.extend({frequency:Wi,loadCapacitance:zs,manufacturerPartNumber:p.string().optional(),mpn:p.string().optional(),pinVariant:p.enum(["two_pin","four_pin"]).optional(),schOrientation:tc.optional(),connections:jl(D_t).optional()});Ct(!0);var Iz=Dn.extend({frequency:Wi,loadCapacitance:zs,pinVariant:p.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});Ct(!0);var sBt=LI.extend({leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftPins:p.array(p.string()).optional(),rightPins:p.array(p.string()).optional(),topPins:p.array(p.string()).optional(),bottomPins:p.array(p.string()).optional(),pinPitch:Y.optional(),innerHoles:p.boolean().optional()});Ct(!0);var $_t=["pin1","pin2","pos","neg","anode","cathode"],Tz=Dn.extend({capacitance:zs,maxVoltageRating:ai.optional(),schShowRatings:p.boolean().optional().default(!1),polarized:p.boolean().optional().default(!1),decouplingFor:p.string().optional(),decouplingTo:p.string().optional(),bypassFor:p.string().optional(),bypassTo:p.string().optional(),maxDecouplingTraceLength:p.number().optional(),schOrientation:tc.optional(),connections:jl($_t).optional()}),Mz=Jg;Ct(!0);var uBt=p.object({name:p.string(),connectsTo:p.string().or(p.array(p.string())).optional(),highlightColor:p.string().optional(),isPowerNet:p.boolean().optional(),isGroundNet:p.boolean().optional()});Ct(!0);var hBt=p.object({name:p.string().optional(),pcbOnly:p.boolean().optional(),schOnly:p.boolean().optional()});Ct(!0);var j_t=p.object({pcb:p.literal(!0).optional(),xDist:Y,left:p.string(),right:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});Ct(!0);var B_t=p.object({pcb:p.literal(!0).optional(),yDist:Y,top:p.string(),bottom:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});Ct(!0);var Y_t=p.object({pcb:p.literal(!0).optional(),sameY:p.literal(!0).optional(),for:p.array(p.string())});Ct(!0);var X_t=p.object({pcb:p.literal(!0).optional(),sameX:p.literal(!0).optional(),for:p.array(p.string())});Ct(!0);var Cz=p.union([j_t,B_t,Y_t,X_t]);Ct(!0);var V_t=Oe.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y});Ct(!0);var H_t=Oe.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:Y});Ct(!0);var G_t=Oe.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Gs)});Ct(!0);var Ez=p.discriminatedUnion("shape",[V_t,H_t,G_t]),U_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y,rectBorderRadius:Y.optional(),cornerRadius:Y.optional(),portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var q_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rotated_rect"),width:Y,height:Y,ccwRotation:p.number(),cornerRadius:Y.optional(),portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var W_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:Y,portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var Z_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("pill"),width:Y,height:Y,radius:Y,portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var K_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Gs),portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var Nz=p.discriminatedUnion("shape",[W_t,U_t,q_t,Z_t,K_t]);Ct(!0);var J_t=Oe.omit({pcbRotation:!0}).extend({shape:p.literal("rect"),width:Y,height:Y});Ct(!0);var Q_t=Oe.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:Y});Ct(!0);var yBt=p.union([Q_t,J_t]);Ct(!0);var tyt=Oe.extend({name:p.string().optional(),shape:p.literal("circle").optional(),diameter:Y.optional(),radius:Y.optional()}).transform(e=>({...e,diameter:e.diameter??2*e.radius,radius:e.radius??e.diameter/2})),eyt=Oe.extend({name:p.string().optional(),shape:p.literal("pill"),width:Y,height:Y}),nyt=Oe.extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y}),kz=p.union([tyt,eyt,nyt]);Ct(!0);var CI=p.union([p.string(),p.custom(e=>!!e.getPortSelector)]),sz=p.object({key:p.string().optional(),thickness:Y.optional(),width:Y.optional().describe("Alias for trace thickness"),schematicRouteHints:p.array(Gs).optional(),pcbRouteHints:p.array(Fi).optional(),pcbPathRelativeTo:p.string().optional(),pcbPath:p.array(p.union([Gs,p.string()])).optional(),schDisplayLabel:p.string().optional(),schStroke:p.string().optional(),highlightColor:p.string().optional(),maxLength:Y.optional()}),Az=p.union([sz.extend({path:p.array(CI)}),sz.extend({from:CI,to:CI})]),Rz=p.object({originalLayer:se.default("top").optional()});Ct(!0);var Oz=p.object({originalFacingDirection:p.enum(["up","down","left","right"]).default("right").optional()});Ct(!0);var iyt=p.number().or(p.string().endsWith("mAh")).transform(e=>{if(typeof e=="string"){let t=e.replace("mAh",""),n=Number.parseFloat(t);if(Number.isNaN(n))throw new Error("Invalid capacity");return n}return e}).describe("Battery capacity in mAh"),Lz=Dn.extend({capacity:iyt.optional(),voltage:ai.optional(),standard:p.enum(["AA","AAA","9V","CR2032","18650","C"]).optional(),schOrientation:tc.optional()});Ct(!0);var oyt=p.enum(["vertical","horizontal"]).describe("vertical means pins go 1->2 downward and horizontal means pins go 1->2 rightward");Ct(!0);var Fz=Dn.extend({pinCount:p.number(),pitch:Y.optional(),schFacingDirection:p.enum(["up","down","left","right"]).optional(),gender:p.enum(["male","female","unpopulated"]).optional().default("male"),showSilkscreenPinLabels:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),doubleRow:p.boolean().optional(),rightAngle:p.boolean().optional(),pcbOrientation:oyt.optional(),holeDiameter:Y.optional(),platedDiameter:Y.optional(),pinLabels:p.record(p.string(),ur).or(p.array(ur)).optional(),connections:p.custom().pipe(p.record(p.string(),Kp)).optional(),facingDirection:p.enum(["left","right"]).optional(),schPinArrangement:AI.optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional()});Ct(!0);var kBt=p.object({net:p.string().optional(),connection:p.string().optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Be.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});Ct(!0);var zz=p.object({net:p.string().optional(),connection:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Be.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});Ct(!0);var Dz=Jp.extend({});Ct(!0);Ct(!0);var ryt=p.custom(e=>typeof e=="string"),$z=p.object({simulationType:p.literal("spice_transient_analysis").default("spice_transient_analysis"),duration:qi.optional(),timePerStep:qi.optional(),spiceEngine:ryt.optional()});Ct(!0);var syt=["pin1","pin2","pin3","emitter","collector","base","gate","source","drain"],jz=Dn.extend({type:p.enum(["npn","pnp","bjt","jfet","mosfet","igbt"]),connections:jl(syt).optional()});Ct(!0);var Bz=Dn.extend({channelType:p.enum(["n","p"]),mosfetMode:p.enum(["enhancement","depletion"])});Ct(!0);var ayt=kI,Yz=Dn.extend({inductance:I_,maxCurrentRating:p.union([p.string(),p.number()]).optional(),schOrientation:tc.optional(),connections:jl(ayt).optional()});Ct(!0);var cyt=p.enum(["anode","cathode","pin1","pin2","pos","neg"]),lyt=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),uyt=p.record(cyt,lyt),pyt=p.enum(["standard","schottky","zener","avalanche","photo","tvs"]),Xz=Dn.extend({connections:uyt.optional(),variant:pyt.optional().default("standard"),standard:p.boolean().optional(),schottky:p.boolean().optional(),zener:p.boolean().optional(),avalanche:p.boolean().optional(),photo:p.boolean().optional(),tvs:p.boolean().optional(),schOrientation:tc.optional()}).superRefine((e,t)=>{if([e.standard,e.schottky,e.zener,e.avalanche,e.photo,e.tvs].filter(Boolean).length>1)return t.addIssue({code:p.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),p.INVALID}).transform(e=>{let t={...e,standard:!1,schottky:!1,zener:!1,avalanche:!1,photo:!1,tvs:!1};if(e.standard)t.standard=!0;else if(e.schottky)t.schottky=!0;else if(e.zener)t.zener=!0;else if(e.photo)t.photo=!0;else if(e.tvs)t.tvs=!0;else switch(e.variant){case"standard":t.standard=!0;break;case"schottky":t.schottky=!0;break;case"zener":t.zener=!0;break;case"avalanche":t.avalanche=!0;break;case"photo":t.photo=!0;break;case"tvs":t.tvs=!0;break;default:t.standard=!0}return t}),Vz=Jg;Ct(!0);var Hz=Dn.extend({color:p.string().optional(),wavelength:p.string().optional(),schDisplayValue:p.string().optional(),schOrientation:tc.optional(),connections:jl(Jg).optional(),laser:p.boolean().optional()}),Gz=Jg,Uz=Dn.extend({type:p.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:p.boolean().optional().default(!1),spst:p.boolean().optional(),spdt:p.boolean().optional(),dpst:p.boolean().optional(),dpdt:p.boolean().optional(),simSwitchFrequency:Wi.optional(),simCloseAt:qi.optional(),simOpenAt:qi.optional(),simStartClosed:p.boolean().optional(),simStartOpen:p.boolean().optional(),connections:p.custom().pipe(p.record(p.string(),Kp)).optional()}).transform(e=>{let t={...e};switch(t.dpdt?t.type="dpdt":t.spst?t.type="spst":t.spdt?t.type="spdt":t.dpst&&(t.type="dpst"),t.type){case"spdt":t.spdt=!0;break;case"spst":t.spst=!0;break;case"dpst":t.dpst=!0;break;case"dpdt":t.dpdt=!0;break}return t});Ct(!0);var qz=Oe.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional()});Ct(!0);var Wz=Oe.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional(),cornerRadius:Y.optional()}),Zz=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Fi),strokeWidth:D.optional(),color:p.string().optional()}),az=p.union([p.string(),Gs]),Kz=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:az,to:az,text:p.string().optional(),offset:Y.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional(),arrowSize:Y.optional(),units:p.enum(["in","mm"]).optional(),outerEdgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional(),innerEdgeToEdge:p.literal(!0).optional()});Ct(!0);var tYt=p.object({layer:p.string().optional(),thickness:Y.optional(),route:p.array(Fi)}),Jz=Kg.extend({name:p.string().optional(),fromLayer:se,toLayer:se,holeDiameter:Y,outerDiameter:Y,connectsTo:p.string().or(p.array(p.string())).optional(),netIsAssignable:p.boolean().optional()});Ct(!0);var hyt=p.object({pin1:Kp}).strict(),Qz=Dn.extend({connections:hyt.optional(),footprintVariant:p.enum(["pad","through_hole"]).optional(),padShape:p.enum(["rect","circle"]).optional().default("circle"),padDiameter:Y.optional(),holeDiameter:Y.optional(),width:Y.optional(),height:Y.optional()}).refine(e=>e.footprintVariant!=="through_hole"||e.holeDiameter!==void 0,{message:"holeDiameter is required for through_hole testpoints"});Ct(!0);var tD=Oe.omit({pcbRotation:!0,layer:!0}).extend({connection:p.string()});Ct(!0);var eD=p.union([Oe.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:Y}),Oe.extend({shape:p.literal("rect"),width:Y,height:Y})]),uYt=Oe.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),dYt=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({outline:p.array(Gs),strokeWidth:D.optional(),isClosed:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),nD=p.object({name:p.string().optional(),layer:se,connectsTo:p.string(),padMargin:Y.optional(),traceMargin:Y.optional(),clearance:Y.optional(),boardEdgeMargin:Y.optional(),cutoutMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional().default(!0)});Ct(!0);var iD=p.object({originalLayer:se.default("top").optional(),children:p.any().optional()});Ct(!0);var dyt=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbZ:Y.optional()}),fyt=Qa.extend({modelUrl:p.string(),stepUrl:p.string().optional()}),myt=fyt.merge(dyt);Ct(!0);var oD=p.union([p.null(),p.string(),myt]),rD=Dn.extend({voltage:ai}),_yt=["pin1","pin2","pos","neg"],yyt=p.union([p.string(),p.number()]).transform(e=>typeof e=="string"?e.endsWith("%")?parseFloat(e.slice(0,-1))/100:parseFloat(e):e).pipe(p.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),SYt=Dn.extend({voltage:ai.optional(),frequency:Wi.optional(),peakToPeakVoltage:ai.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Be.optional(),dutyCycle:yyt.optional(),connections:jl(_yt).optional()});Ct(!0);var sD=Dn.omit({name:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string()))});Ct(!0);var aD=p.object({center:qt,radius:Y,startAngleDegrees:Be,endAngleDegrees:Be,direction:p.enum(["clockwise","counterclockwise"]).default("counterclockwise"),strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),cD=p.object({schX:Y.optional(),schY:Y.optional(),width:Y.optional(),height:Y.optional(),overlay:p.array(p.string()).optional(),padding:Y.optional(),paddingLeft:Y.optional(),paddingRight:Y.optional(),paddingTop:Y.optional(),paddingBottom:Y.optional(),title:p.string().optional(),titleAlignment:Zp.default("top_left"),titleColor:p.string().optional(),titleFontSize:Y.optional(),titleInside:p.boolean().default(!1),strokeStyle:p.enum(["solid","dashed"]).default("solid")}).refine(e=>e.width!==void 0&&e.height!==void 0||Array.isArray(e.overlay)&&e.overlay.length>0,{message:"Must provide either both `width` and `height`, or a non-empty `overlay` array."}).refine(e=>!(e.width!==void 0&&e.height!==void 0&&Array.isArray(e.overlay)&&e.overlay.length>0),{message:"Cannot provide both `width`/`height` and `overlay` at the same time."}),lD=p.object({center:qt,radius:Y,strokeWidth:Y.optional(),color:p.string().optional(),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),uD=p.object({schX:Y.optional(),schY:Y.optional(),width:Y,height:Y,rotation:Be.default(0),strokeWidth:Y.optional(),color:p.string().optional(),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1),cornerRadius:Y.optional()}),pD=p.object({x1:Y,y1:Y,x2:Y,y2:Y,strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),gyt=p.enum(["center","left","right","top","bottom"]),hD=p.object({schX:Y.optional(),schY:Y.optional(),text:p.string(),fontSize:p.number().default(1),anchor:p.union([gyt.describe("legacy"),Zp]).default("center"),color:p.string().default("#000000"),schRotation:Be.default(0)}),$Yt=p.object({points:p.array(qt),isFilled:p.boolean().optional().default(!1),fillColor:p.enum(["red","blue"]).optional()}),dD=p.object({schX:Y.optional(),schY:Y.optional(),children:p.any().optional(),cellPadding:Y.optional(),borderWidth:Y.optional(),anchor:Zp.optional(),fontSize:Y.optional()});Ct(!0);var fD=p.object({children:p.any().optional(),height:Y.optional()});Ct(!0);var mD=p.object({children:p.string().optional(),horizontalAlign:p.enum(["left","center","right"]).optional(),verticalAlign:p.enum(["top","middle","bottom"]).optional(),fontSize:Y.optional(),rowSpan:p.number().optional(),colSpan:p.number().optional(),width:Y.optional(),text:p.string().optional()});Ct(!0);var qYt=Oe.extend({text:p.string(),anchorAlignment:Zp.default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),layers:p.array(se).optional()}),_D=Oe.extend({text:p.string(),anchorAlignment:Zp.default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),isKnockout:p.boolean().optional(),knockoutPadding:D.optional(),knockoutPaddingLeft:D.optional(),knockoutPaddingRight:D.optional(),knockoutPaddingTop:D.optional(),knockoutPaddingBottom:D.optional(),layers:p.array(se).optional()}),yD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Fi),strokeWidth:D.optional()}),gD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({strokeWidth:Y,x1:Y,y1:Y,x2:Y,y2:Y}),bD=Oe.omit({pcbRotation:!0}).extend({filled:p.boolean().default(!0).optional(),stroke:p.enum(["dashed","solid","none"]).optional(),strokeWidth:Y.optional(),width:Y,height:Y,cornerRadius:Y.optional()}),xD=Oe.omit({pcbRotation:!0}).extend({isFilled:p.boolean().optional(),isOutline:p.boolean().optional(),strokeWidth:Y.optional(),radius:Y}),cz=p.object({x:Y,y:Y,via:p.boolean().optional(),toLayer:se.optional()}),vD=p.object({for:p.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:p.number().optional(),offset:Fi.or(cz).optional(),offsets:p.array(Fi).or(p.array(cz)).optional(),traceWidth:p.number().optional()}),aXt=Kg.extend({name:p.string(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),direction:c_t,connectsTo:p.string().or(p.array(p.string())).optional()}),SD=Oe.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional()});Ct(!0);var wD=Oe.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional(),cornerRadius:Y.optional()});Ct(!0);var PD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Fi),strokeWidth:D.optional(),color:p.string().optional()});Ct(!0);var ID=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({x1:Y,y1:Y,x2:Y,y2:Y,strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional()});Ct(!0);var lz=p.union([p.string(),Gs]),TD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:lz,to:lz,text:p.string().optional(),offset:Y.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional(),arrowSize:Y.optional(),units:p.enum(["in","mm"]).optional(),outerEdgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional(),innerEdgeToEdge:p.literal(!0).optional()});Ct(!0);var MD=p.array(p.any()).describe("Circuit JSON"),EI=p.object({footprintCircuitJson:p.array(p.any()),cadModel:hz.optional()}),uz=p.function().args(p.string()).returns(p.promise(EI)).or(p.function().args(p.string(),p.object({resolvedPcbStyle:NI.optional()}).optional()).returns(p.promise(EI))).describe("A function that takes a path and returns Circuit JSON"),byt=p.object({loadFromUrl:p.function().args(p.string()).returns(p.promise(EI)).describe("A function that takes a footprint file URL and returns Circuit JSON")}),xyt=p.object({engineVersionString:p.string().optional(),simulationResultCircuitJson:MD}),vyt=p.object({simulate:p.function().args(p.string()).returns(p.promise(xyt)).describe("A function that takes a SPICE string and returns a simulation result")}),Syt=p.custom(e=>typeof e=="string"),pz=p.object({run:p.function().args().returns(p.promise(p.unknown())).describe("Run the autorouter"),getOutputSimpleRouteJson:p.function().args().returns(p.promise(p.any())).describe("Get the resulting SimpleRouteJson")}),wyt=p.object({createAutorouter:p.function().args(p.any(),p.any().optional()).returns(p.union([pz,p.promise(pz)])).describe("Create an autorouter instance")}),Pyt=p.object({partsEngine:fz.optional(),autorouter:dz.optional(),autorouterMap:p.record(p.string(),wyt).optional(),registryApiUrl:p.string().optional(),cloudAutorouterUrl:p.string().optional(),projectName:p.string().optional(),projectBaseUrl:p.string().optional(),version:p.string().optional(),url:p.string().optional(),printBoardInformationToSilkscreen:p.boolean().optional(),includeBoardFiles:p.array(p.string()).describe('The board files to automatically build with "tsci build", defaults to ["**/*.circuit.tsx"]. Can be an array of files or globs').optional(),snapshotsDir:p.string().describe('The directory where snapshots are stored for "tsci snapshot", defaults to "tests/__snapshots__"').optional(),defaultSpiceEngine:Syt.optional(),localCacheEngine:p.any().optional(),pcbDisabled:p.boolean().optional(),schematicDisabled:p.boolean().optional(),partsEngineDisabled:p.boolean().optional(),spiceEngineMap:p.record(p.string(),vyt).optional(),footprintLibraryMap:p.record(p.string(),p.union([uz,p.record(p.string(),p.union([MD,uz]))])).optional(),footprintFileParserMap:p.record(p.string(),byt).optional(),resolveProjectStaticFileImportUrl:p.function().args(p.string()).returns(p.promise(p.string())).describe("A function that returns a string URL for static files for the project").optional()});Ct(!0);var Iyt=Pyt,bXt=Iyt.pick({projectName:!0,projectBaseUrl:!0,version:!0,url:!0,printBoardInformationToSilkscreen:!0,includeBoardFiles:!0,snapshotsDir:!0,defaultSpiceEngine:!0});Ct(!0);vt();K();vt();Ys();K();var ca=Xt(Mr(),1);Ys();K();function ec(){return new zI}var zI=class e{constructor(){P(this,"index",{});P(this,"array",[])}size(){return this.array.length}empty(){return this.array.length===0}itemAt(t){return this.array[t]}contains(t){return this.index[t.id()]!==void 0}find(t){let n=this.index[t.id()];return n===void 0?void 0:this.array[n]}setDefault(t,n){let i=this.index[t.id()];if(i===void 0){let o=new Qg(t,n());return this.index[t.id()]=this.array.length,this.array.push(o),o}else return this.array[i]}insert(t,n){let i=new Qg(t,n),o=this.index[t.id()];return o===void 0?(this.index[t.id()]=this.array.length,this.array.push(i)):this.array[o]=i,i}erase(t){let n=this.index[t.id()];if(n===void 0)return;this.index[t.id()]=void 0;let i=this.array[n],o=this.array.pop();return i!==o&&(this.array[n]=o,this.index[o.first.id()]=n),i}copy(){let t=new e;for(let n=0;n<this.array.length;n++){let i=this.array[n].copy();t.array[n]=i,t.index[i.first.id()]=n}return t}},Qg=class e{constructor(t,n){P(this,"first");P(this,"second");this.first=t,this.second=n}copy(){return new e(this.first,this.second)}};var Us=class{constructor(t=""){P(this,"_name");P(this,"_value",0);P(this,"_context",null);P(this,"_id",Tyt++);this._name=t}id(){return this._id}name(){return this._name}setName(t){this._name=t}context(){return this._context}setContext(t){this._context=t}value(){return this._value}setValue(t){this._value=t}plus(t){return new Cn(this,t)}minus(t){return new Cn(this,typeof t=="number"?-t:[-1,t])}multiply(t){return new Cn([t,this])}divide(t){return new Cn([1/t,this])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},Tyt=0;var Cn=class e{constructor(){P(this,"_terms");P(this,"_constant");let t=Myt(arguments);this._terms=t.terms,this._constant=t.constant}terms(){return this._terms}constant(){return this._constant}value(){let t=this._constant;for(let n=0,i=this._terms.size();n<i;n++){let o=this._terms.itemAt(n);t+=o.first.value()*o.second}return t}plus(t){return new e(this,t)}minus(t){return new e(this,typeof t=="number"?-t:[-1,t])}multiply(t){return new e([t,this])}divide(t){return new e([1/t,this])}isConstant(){return this._terms.size()==0}toString(){let t=this._terms.array.map(function(n){return n.second+"*"+n.first.toString()}).join(" + ");return!this.isConstant()&&this._constant!==0&&(t+=" + "),t+=this._constant,t}};function Myt(e){let t=0,n=()=>0,i=ec();for(let o=0,r=e.length;o<r;++o){let s=e[o];if(typeof s=="number")t+=s;else if(s instanceof Us)i.setDefault(s,n).second+=1;else if(s instanceof Cn){t+=s.constant();let a=s.terms();for(let c=0,l=a.size();c<l;c++){let u=a.itemAt(c);i.setDefault(u.first,n).second+=u.second}}else if(s instanceof Array){if(s.length!==2)throw new Error("array must have length 2");let a=s[0],c=s[1];if(typeof a!="number")throw new Error("array item 0 must be a number");if(c instanceof Us)i.setDefault(c,n).second+=a;else if(c instanceof Cn){t+=c.constant()*a;let l=c.terms();for(let u=0,h=l.size();u<h;u++){let d=l.itemAt(u);i.setDefault(d.first,n).second+=d.second*a}}else throw new Error("array item 1 must be a variable or expression")}else throw new Error("invalid Expression argument: "+s)}return{terms:i,constant:t}}var Lr=class Lr{static create(t,n,i,o=1){let r=0;return r+=Math.max(0,Math.min(1e3,t*o))*1e6,r+=Math.max(0,Math.min(1e3,n*o))*1e3,r+=Math.max(0,Math.min(1e3,i*o)),r}static clip(t){return Math.max(0,Math.min(Lr.required,t))}};P(Lr,"required",Lr.create(1e3,1e3,1e3)),P(Lr,"strong",Lr.create(1,0,0)),P(Lr,"medium",Lr.create(0,1,0)),P(Lr,"weak",Lr.create(0,0,1));var wn=Lr;var Vn;(function(e){e[e.Le=0]="Le",e[e.Ge=1]="Ge",e[e.Eq=2]="Eq"})(Vn||(Vn={}));var ci=class{constructor(t,n,i,o=wn.required){P(this,"_expression");P(this,"_operator");P(this,"_strength");P(this,"_id",Cyt++);this._operator=n,this._strength=wn.clip(o),i===void 0&&t instanceof Cn?this._expression=t:this._expression=t.minus(i)}id(){return this._id}expression(){return this._expression}op(){return this._operator}strength(){return this._strength}toString(){return this._expression.toString()+" "+["<=",">=","="][this._operator]+" 0 ("+this._strength.toString()+")"}},Cyt=0;var Qp=class{constructor(){P(this,"maxIterations",1e3);P(this,"_cnMap",Eyt());P(this,"_rowMap",Nyt());P(this,"_varMap",kyt());P(this,"_editMap",Ayt());P(this,"_infeasibleRows",[]);P(this,"_objective",new nb);P(this,"_artificial",null);P(this,"_idTick",0)}createConstraint(t,n,i,o=wn.required){let r=new ci(t,n,i,o);return this.addConstraint(r),r}addConstraint(t){if(this._cnMap.find(t)!==void 0)throw new Error("duplicate constraint");let i=this._createRow(t),o=i.row,r=i.tag,s=this._chooseSubject(o,r);if(s.type()===Ue.Invalid&&o.allDummies())if(tb(o.constant()))s=r.marker;else throw new Error("unsatisfiable constraint");if(s.type()===Ue.Invalid){if(!this._addWithArtificialVariable(o))throw new Error("unsatisfiable constraint")}else o.solveFor(s),this._substitute(s,o),this._rowMap.insert(s,o);this._cnMap.insert(t,r),this._optimize(this._objective)}removeConstraint(t){let n=this._cnMap.erase(t);if(n===void 0)throw new Error("unknown constraint");this._removeConstraintEffects(t,n.second);let i=n.second.marker,o=this._rowMap.erase(i);if(o===void 0){let r=this._getMarkerLeavingSymbol(i);if(r.type()===Ue.Invalid)throw new Error("failed to find leaving row");o=this._rowMap.erase(r),o.second.solveForEx(r,i),this._substitute(i,o.second)}this._optimize(this._objective)}hasConstraint(t){return this._cnMap.contains(t)}getConstraints(){return this._cnMap.array.map(({first:t})=>t)}addEditVariable(t,n){if(this._editMap.find(t)!==void 0)throw new Error("duplicate edit variable");if(n=wn.clip(n),n===wn.required)throw new Error("bad required strength");let o=new Cn(t),r=new ci(o,Vn.Eq,void 0,n);this.addConstraint(r);let a={tag:this._cnMap.find(r).second,constraint:r,constant:0};this._editMap.insert(t,a)}removeEditVariable(t){let n=this._editMap.erase(t);if(n===void 0)throw new Error("unknown edit variable");this.removeConstraint(n.second.constraint)}hasEditVariable(t){return this._editMap.contains(t)}suggestValue(t,n){let i=this._editMap.find(t);if(i===void 0)throw new Error("unknown edit variable");let o=this._rowMap,r=i.second,s=n-r.constant;r.constant=n;let a=r.tag.marker,c=o.find(a);if(c!==void 0){c.second.add(-s)<0&&this._infeasibleRows.push(a),this._dualOptimize();return}let l=r.tag.other;if(c=o.find(l),c!==void 0){c.second.add(s)<0&&this._infeasibleRows.push(l),this._dualOptimize();return}for(let u=0,h=o.size();u<h;++u){let d=o.itemAt(u),_=d.second,y=_.coefficientFor(a);y!==0&&_.add(s*y)<0&&d.first.type()!==Ue.External&&this._infeasibleRows.push(d.first)}this._dualOptimize()}updateVariables(){let t=this._varMap,n=this._rowMap;for(let i=0,o=t.size();i<o;++i){let r=t.itemAt(i),s=n.find(r.second);s!==void 0?r.first.setValue(s.second.constant()):r.first.setValue(0)}}_getVarSymbol(t){let n=()=>this._makeSymbol(Ue.External);return this._varMap.setDefault(t,n).second}_createRow(t){let n=t.expression(),i=new nb(n.constant()),o=n.terms();for(let c=0,l=o.size();c<l;++c){let u=o.itemAt(c);if(!tb(u.second)){let h=this._getVarSymbol(u.first),d=this._rowMap.find(h);d!==void 0?i.insertRow(d.second,u.second):i.insertSymbol(h,u.second)}}let r=this._objective,s=t.strength(),a={marker:nc,other:nc};switch(t.op()){case Vn.Le:case Vn.Ge:{let c=t.op()===Vn.Le?1:-1,l=this._makeSymbol(Ue.Slack);if(a.marker=l,i.insertSymbol(l,c),s<wn.required){let u=this._makeSymbol(Ue.Error);a.other=u,i.insertSymbol(u,-c),r.insertSymbol(u,s)}break}case Vn.Eq:{if(s<wn.required){let c=this._makeSymbol(Ue.Error),l=this._makeSymbol(Ue.Error);a.marker=c,a.other=l,i.insertSymbol(c,-1),i.insertSymbol(l,1),r.insertSymbol(c,s),r.insertSymbol(l,s)}else{let c=this._makeSymbol(Ue.Dummy);a.marker=c,i.insertSymbol(c)}break}}return i.constant()<0&&i.reverseSign(),{row:i,tag:a}}_chooseSubject(t,n){let i=t.cells();for(let r=0,s=i.size();r<s;++r){let a=i.itemAt(r);if(a.first.type()===Ue.External)return a.first}let o=n.marker.type();return(o===Ue.Slack||o===Ue.Error)&&t.coefficientFor(n.marker)<0?n.marker:(o=n.other.type(),(o===Ue.Slack||o===Ue.Error)&&t.coefficientFor(n.other)<0?n.other:nc)}_addWithArtificialVariable(t){let n=this._makeSymbol(Ue.Slack);this._rowMap.insert(n,t.copy()),this._artificial=t.copy(),this._optimize(this._artificial);let i=tb(this._artificial.constant());this._artificial=null;let o=this._rowMap.erase(n);if(o!==void 0){let s=o.second;if(s.isConstant())return i;let a=this._anyPivotableSymbol(s);if(a.type()===Ue.Invalid)return!1;s.solveForEx(n,a),this._substitute(a,s),this._rowMap.insert(a,s)}let r=this._rowMap;for(let s=0,a=r.size();s<a;++s)r.itemAt(s).second.removeSymbol(n);return this._objective.removeSymbol(n),i}_substitute(t,n){let i=this._rowMap;for(let o=0,r=i.size();o<r;++o){let s=i.itemAt(o);s.second.substitute(t,n),s.second.constant()<0&&s.first.type()!==Ue.External&&this._infeasibleRows.push(s.first)}this._objective.substitute(t,n),this._artificial&&this._artificial.substitute(t,n)}_optimize(t){let n=0;for(;n<this.maxIterations;){let i=this._getEnteringSymbol(t);if(i.type()===Ue.Invalid)return;let o=this._getLeavingSymbol(i);if(o.type()===Ue.Invalid)throw new Error("the objective is unbounded");let r=this._rowMap.erase(o).second;r.solveForEx(o,i),this._substitute(i,r),this._rowMap.insert(i,r),n++}throw new Error("solver iterations exceeded")}_dualOptimize(){let t=this._rowMap,n=this._infeasibleRows;for(;n.length!==0;){let i=n.pop(),o=t.find(i);if(o!==void 0&&o.second.constant()<0){let r=this._getDualEnteringSymbol(o.second);if(r.type()===Ue.Invalid)throw new Error("dual optimize failed");let s=o.second;t.erase(i),s.solveForEx(i,r),this._substitute(r,s),t.insert(r,s)}}}_getEnteringSymbol(t){let n=t.cells();for(let i=0,o=n.size();i<o;++i){let r=n.itemAt(i),s=r.first;if(r.second<0&&s.type()!==Ue.Dummy)return s}return nc}_getDualEnteringSymbol(t){let n=Number.MAX_VALUE,i=nc,o=t.cells();for(let r=0,s=o.size();r<s;++r){let a=o.itemAt(r),c=a.first,l=a.second;if(l>0&&c.type()!==Ue.Dummy){let h=this._objective.coefficientFor(c)/l;h<n&&(n=h,i=c)}}return i}_getLeavingSymbol(t){let n=Number.MAX_VALUE,i=nc,o=this._rowMap;for(let r=0,s=o.size();r<s;++r){let a=o.itemAt(r),c=a.first;if(c.type()!==Ue.External){let l=a.second,u=l.coefficientFor(t);if(u<0){let h=-l.constant()/u;h<n&&(n=h,i=c)}}}return i}_getMarkerLeavingSymbol(t){let n=Number.MAX_VALUE,i=n,o=n,r=nc,s=r,a=r,c=r,l=this._rowMap;for(let u=0,h=l.size();u<h;++u){let d=l.itemAt(u),_=d.second,y=_.coefficientFor(t);if(y===0)continue;let g=d.first;if(g.type()===Ue.External)c=g;else if(y<0){let x=-_.constant()/y;x<i&&(i=x,s=g)}else{let x=_.constant()/y;x<o&&(o=x,a=g)}}return s!==r?s:a!==r?a:c}_removeConstraintEffects(t,n){n.marker.type()===Ue.Error&&this._removeMarkerEffects(n.marker,t.strength()),n.other.type()===Ue.Error&&this._removeMarkerEffects(n.other,t.strength())}_removeMarkerEffects(t,n){let i=this._rowMap.find(t);i!==void 0?this._objective.insertRow(i.second,-n):this._objective.insertSymbol(t,-n)}_anyPivotableSymbol(t){let n=t.cells();for(let i=0,o=n.size();i<o;++i){let r=n.itemAt(i),s=r.first.type();if(s===Ue.Slack||s===Ue.Error)return r.first}return nc}_makeSymbol(t){return new eb(t,this._idTick++)}};function tb(e){let t=1e-8;return e<0?-e<t:e<t}function Eyt(){return ec()}function Nyt(){return ec()}function kyt(){return ec()}function Ayt(){return ec()}var Ue;(function(e){e[e.Invalid=0]="Invalid",e[e.External=1]="External",e[e.Slack=2]="Slack",e[e.Error=3]="Error",e[e.Dummy=4]="Dummy"})(Ue||(Ue={}));var eb=class{constructor(t,n){P(this,"_id");P(this,"_type");this._id=n,this._type=t}id(){return this._id}type(){return this._type}},nc=new eb(Ue.Invalid,-1),nb=class e{constructor(t=0){P(this,"_cellMap",ec());P(this,"_constant");this._constant=t}cells(){return this._cellMap}constant(){return this._constant}isConstant(){return this._cellMap.empty()}allDummies(){let t=this._cellMap;for(let n=0,i=t.size();n<i;++n)if(t.itemAt(n).first.type()!==Ue.Dummy)return!1;return!0}copy(){let t=new e(this._constant);return t._cellMap=this._cellMap.copy(),t}add(t){return this._constant+=t}insertSymbol(t,n=1){let i=this._cellMap.setDefault(t,()=>0);tb(i.second+=n)&&this._cellMap.erase(t)}insertRow(t,n=1){this._constant+=t._constant*n;let i=t._cellMap;for(let o=0,r=i.size();o<r;++o){let s=i.itemAt(o);this.insertSymbol(s.first,s.second*n)}}removeSymbol(t){this._cellMap.erase(t)}reverseSign(){this._constant=-this._constant;let t=this._cellMap;for(let n=0,i=t.size();n<i;++n){let o=t.itemAt(n);o.second=-o.second}}solveFor(t){let n=this._cellMap,o=-1/n.erase(t).second;this._constant*=o;for(let r=0,s=n.size();r<s;++r)n.itemAt(r).second*=o}solveForEx(t,n){this.insertSymbol(t,-1),this.solveFor(n)}coefficientFor(t){let n=this._cellMap.find(t);return n!==void 0?n.second:0}substitute(t,n){let i=this._cellMap.erase(t);i!==void 0&&this.insertRow(n,i.second)}};var RH=Xt(Sn(),1);K();vt();vt();ji();var YI={};il(YI,{areBoundsCompletelyInsidePolygon:()=>BI,areBoundsOverlappingPolygon:()=>jI,boundsAreaOverlap:()=>jD,boundsDistance:()=>BD,boundsIntersection:()=>YD,clamp:()=>Rn,computeDistanceBetweenBoxes:()=>ts,computeGapBetweenBoxes:()=>II,computeManhattanDistanceBetweenBoxes:()=>yf,distSq:()=>RD,distance:()=>vi,doBoundsOverlap:()=>ic,doSegmentsIntersect:()=>li,doesLineIntersectLine:()=>qs,doesSegmentIntersectRect:()=>DI,findNearestPointsBetweenBoxSets:()=>gf,getBoundingBox:()=>Or,getBoundsFromPoints:()=>ns,getSegmentIntersection:()=>Xl,getUnitVectorFromDirection:()=>ab,getUnitVectorFromPointAToB:()=>sb,grid:()=>XD,isPointInsidePolygon:()=>rb,isRectCompletelyInsidePolygon:()=>DD,isRectOverlappingPolygon:()=>zD,midpoint:()=>AD,normalizeDegrees:()=>Vl,onSegment:()=>Yl,orientation:()=>Bl,pointToBoundsDistance:()=>kD,pointToBoxDistance:()=>ND,pointToSegmentClosestPoint:()=>ED,pointToSegmentDistance:()=>ei,range:()=>$D,segmentToBoundsMinDistance:()=>wf,segmentToBoxMinDistance:()=>ib,segmentToCircleMinDistance:()=>ob,segmentToSegmentMinDistance:()=>th});function qs([e,t],[n,i],{lineThickness:o=0}={}){return o===0?li(e,t,n,i):Ryt(e,t,n,i)<=o}function li(e,t,n,i){let o=Bl(e,t,n),r=Bl(e,t,i),s=Bl(n,i,e),a=Bl(n,i,t);return!!(o!==r&&s!==a||o===0&&Yl(e,n,t)||r===0&&Yl(e,i,t)||s===0&&Yl(n,e,i)||a===0&&Yl(n,t,i))}function Bl(e,t,n){let i=(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y);return i===0?0:i>0?1:2}function Yl(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function Ryt(e,t,n,i){if(e.x===t.x&&e.y===t.y)return ei(e,n,i);if(n.x===i.x&&n.y===i.y)return ei(n,e,t);if(li(e,t,n,i))return 0;let o=[ei(e,n,i),ei(t,n,i),ei(n,e,t),ei(i,e,t)];return Math.min(...o)}function ei(e,t,n){let i=(n.x-t.x)**2+(n.y-t.y)**2;if(i===0)return vi(e,t);let o=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/i;o=Math.max(0,Math.min(1,o));let r={x:t.x+o*(n.x-t.x),y:t.y+o*(n.y-t.y)};return vi(e,r)}function vi(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}function Xl(e,t,n,i){let o=t.x-e.x,r=t.y-e.y,s=i.x-n.x,a=i.y-n.y,c=e.x-n.x,l=e.y-n.y,u=o*a-r*s;if(Math.abs(u)<1e-10)return null;let h=(l*s-c*a)/u,d=(o*l-r*c)/u,_=1e-9;if(h>=-_&&h<=1+_&&d>=-_&&d<=1+_){let y=e.x+h*o,g=e.y+h*r;return{x:y,y:g}}return null}function DI(e,t,n){let i=c=>c.x>=n.minX&&c.x<=n.maxX&&c.y>=n.minY&&c.y<=n.maxY;if(i(e)||i(t))return!0;let o={x:n.minX,y:n.minY},r={x:n.maxX,y:n.minY},s={x:n.minX,y:n.maxY},a={x:n.maxX,y:n.maxY};return li(e,t,o,r)||li(e,t,r,a)||li(e,t,a,s)||li(e,t,s,o)}function th(e,t,n,i){if(e.x===t.x&&e.y===t.y)return ei(e,n,i);if(n.x===i.x&&n.y===i.y)return ei(n,e,t);if(li(e,t,n,i))return 0;let o=[ei(e,n,i),ei(t,n,i),ei(n,e,t),ei(i,e,t)];return Math.min(...o)}function wf(e,t,n){let i={x:n.minX,y:n.minY},o={x:n.maxX,y:n.minY},r={x:n.minX,y:n.maxY},s={x:n.maxX,y:n.maxY};if(li(e,t,i,o)||li(e,t,o,s)||li(e,t,s,r)||li(e,t,r,i)||e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY&&t.x>=n.minX&&t.x<=n.maxX&&t.y>=n.minY&&t.y<=n.maxY)return 0;let a=[ei(i,e,t),ei(o,e,t),ei(r,e,t),ei(s,e,t)];if(e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY||t.x>=n.minX&&t.x<=n.maxX&&t.y>=n.minY&&t.y<=n.maxY)return 0;if(e.x<n.minX||e.x>n.maxX||e.y<n.minY||e.y>n.maxY){let c=Rn(e.x,n.minX,n.maxX),l=Rn(e.y,n.minY,n.maxY);a.push(vi(e,{x:c,y:l}))}if(t.x<n.minX||t.x>n.maxX||t.y<n.minY||t.y>n.maxY){let c=Rn(t.x,n.minX,n.maxX),l=Rn(t.y,n.minY,n.maxY);a.push(vi(t,{x:c,y:l}))}return Math.min(...a)}function ib(e,t,n){let i=n.width/2,o=n.height/2,r={minX:n.center.x-i,maxX:n.center.x+i,minY:n.center.y-o,maxY:n.center.y+o};return wf(e,t,r)}function ob(e,t,n){let i={x:n.x,y:n.y};if(e.x===t.x&&e.y===t.y)return Math.max(0,vi(e,i)-n.radius);let o={x:t.x-e.x,y:t.y-e.y},r={x:i.x-e.x,y:i.y-e.y},s=o.x*o.x+o.y*o.y,a=Math.max(0,Math.min(1,(o.x*r.x+o.y*r.y)/s)),c={x:e.x+a*o.x,y:e.y+a*o.y},l=vi(c,i);return Math.max(0,l-n.radius)}function ED(e,t,n){let i=n.x-t.x,o=n.y-t.y,r=i*i+o*o;if(r===0)return{x:t.x,y:t.y};let s=((e.x-t.x)*i+(e.y-t.y)*o)/r;return s=Math.max(0,Math.min(1,s)),{x:t.x+s*i,y:t.y+s*o}}function Vl(e){return(e%360+360)%360}function ND(e,t){let n=t.width/2,i=t.height/2,o=t.center.x-n,r=t.center.x+n,s=t.center.y-i,a=t.center.y+i;if(e.x>=o&&e.x<=r&&e.y>=s&&e.y<=a)return 0;let c=Rn(e.x,o,r),l=Rn(e.y,s,a);return vi(e,{x:c,y:l})}function kD(e,t){if(e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)return 0;let n=Rn(e.x,t.minX,t.maxX),i=Rn(e.y,t.minY,t.maxY);return vi(e,{x:n,y:i})}function AD(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function RD(e,t){let n=e.x-t.x,i=e.y-t.y;return n*n+i*i}var OD=e=>{if("minX"in e)return e;let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,minY:e.center.y-n,maxX:e.center.x+t,maxY:e.center.y+n}},$I=e=>[{x:e.minX,y:e.minY},{x:e.maxX,y:e.minY},{x:e.maxX,y:e.maxY},{x:e.minX,y:e.maxY}],LD=e=>{let t=[];for(let n=0;n<e.length;n++){let i=e[n],o=e[(n+1)%e.length];t.push([i,o])}return t},Oyt=(e,t,n)=>{let i=(e.y-t.y)*(n.x-t.x)-(e.x-t.x)*(n.y-t.y);if(Math.abs(i)>1e-9)return!1;let o=(e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y);if(o<0)return!1;let r=(n.x-t.x)**2+(n.y-t.y)**2;return!(o>r)},Lyt=(e,t)=>e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY,rb=(e,t)=>{if(t.length<3)return!1;let n=LD(t);for(let[o,r]of n)if(Oyt(e,o,r))return!0;let i=!1;for(let o=0,r=t.length-1;o<t.length;r=o++){let s=t[o].x,a=t[o].y,c=t[r].x,l=t[r].y;a>e.y!=l>e.y&&e.x<(c-s)*(e.y-a)/(l-a)+s&&(i=!i)}return i},FD=(e,t)=>{let n=$I(e),i=[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]],o=LD(t);for(let[r,s]of o)for(let[a,c]of i)if(li(r,s,a,c))return!0;return!1},jI=(e,t)=>t.length<3?!1:t.some(i=>Lyt(i,e))||$I(e).some(i=>rb(i,t))?!0:FD(e,t),BI=(e,t)=>t.length<3||!$I(e).every(i=>rb(i,t))?!1:!FD(e,t),zD=(e,t)=>jI(OD(e),t),DD=(e,t)=>BI(OD(e),t);function $D(e,t,n=1){if(n===0)throw new Error("step cannot be 0");let i,o;t===void 0?(i=0,o=e):(i=e,o=t);let r=[];if(n>0)for(let s=i;s<o;s+=n)r.push(s);else for(let s=i;s>o;s+=n)r.push(s);return r}var jD=(e,t)=>{let n=Math.max(0,Math.min(e.maxX,t.maxX)-Math.max(e.minX,t.minX)),i=Math.max(0,Math.min(e.maxY,t.maxY)-Math.max(e.minY,t.minY));return n*i};var BD=(e,t)=>{let n=e.maxX<t.minX?t.minX-e.maxX:t.maxX<e.minX?e.minX-t.maxX:0,i=e.maxY<t.minY?t.minY-e.maxY:t.maxY<e.minY?e.minY-t.maxY:0;return Math.sqrt(n*n+i*i)};var YD=(e,t)=>{let n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),o=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return n>o||i>r?null:{minX:n,minY:i,maxX:o,maxY:r}};var ic=(e,t)=>!(e.maxX<t.minX||t.maxX<e.minX||e.maxY<t.minY||t.maxY<e.minY);var ns=e=>{if(e.length===0)return null;let t=e[0].x,n=e[0].y,i=e[0].x,o=e[0].y;for(let r=1;r<e.length;r++){let s=e[r];s.x<t&&(t=s.x),s.y<n&&(n=s.y),s.x>i&&(i=s.x),s.y>o&&(o=s.y)}return{minX:t,minY:n,maxX:i,maxY:o}};var sb=(e,t)=>{let n={x:t.x-e.x,y:t.y-e.y},i=Math.sqrt(n.x**2+n.y**2);return{x:n.x/i,y:n.y/i}},ab=e=>{switch(e){case"up":return{x:0,y:1};case"down":return{x:0,y:-1};case"left":return{x:-1,y:0};case"right":return{x:1,y:0}}};function XD({rows:e,cols:t,xSpacing:n,ySpacing:i,width:o,height:r,offsetX:s=0,offsetY:a=0,yDirection:c="cartesian",centered:l=!0}){let u=n??1,h=i??1,d=o??t*u,_=r??e*h,y=l?-d/2:0,g=l?-_/2:0,x=o?o/t:u,w=r?r/e:h,S=[];for(let T=0;T<e;T++)for(let I=0;I<t;I++){let E=T*t+I,M=s+y+I*x+x/2,k=a+T*w+w/2,N=c==="cartesian"?a+g+(e-1-T)*w+w/2:a+g+T*w+w/2;S.push({index:E,center:{x:M,y:N},topLeft:{x:M-x/2,y:N+w/2},bottomRight:{x:M+x/2,y:N-w/2},row:T,col:I})}return S}vt();Pf();var VD={name:"@tscircuit/capacity-autorouter",main:"./dist/index.js",version:"0.0.140",type:"module",files:["dist"],scripts:{start:"cosmos",build:"tsup ./lib/index.ts --minify terser --external @tscircuit/core --external circuit-to-svg --format esm --dts --sourcemap",bench:"bun test tests/spatial-index-bench.test.ts",format:"biome format --write .","format:check":"biome format .","vercel-build":"cosmos-export","repomix:lib":"repomix --ignore 'testing/**,**/TwoRouteHighDensitySolver/**,**/RouteStitchingSolver/**,solvers/CapacitySegmentPointOptimizer/CapacitySegmentPointOptimizer.ts' lib","bug-report":"bun run scripts/download-bug-report.ts","bug-report-with-test":"bun run scripts/create-bug-report-test.ts"},devDependencies:{"@biomejs/biome":"^1.9.4","@radix-ui/react-icons":"^1.3.2","@radix-ui/react-menubar":"^1.1.14","@react-hook/resize-observer":"^2.0.2","@resvg/resvg-js":"^2.6.2","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.46","@tscircuit/core":"^0.0.337","@tscircuit/math-utils":"^0.0.27","@types/bun":"^1.2.23","@types/fast-json-stable-stringify":"^2.1.2","@types/object-hash":"^3.0.6","@types/rbush":"^4.0.0","@types/react":"^19.0.8","@types/react-dom":"^19.0.3","@vercel/node":"^5.1.7","@vitejs/plugin-react":"^4.3.4","circuit-json-to-connectivity-map":"^0.0.19","circuit-to-svg":"^0.0.220",clsx:"^2.1.1",flatbush:"^4.4.0","graphics-debug":"^0.0.44","looks-same":"9",rbush:"^4.0.1",react:"18","react-cosmos":"^6.2.3","react-cosmos-plugin-vite":"^6.2.0","react-dom":"18","react-konva":"18",recharts:"^2.15.1","tailwind-merge":"^3.2.0",terser:"^5.43.1",tsup:"^8.3.6",typescript:"^5.9.3","use-mouse-matrix-transform":"^1.3.0",vite:"^6.0.11","vite-tsconfig-paths":"^5.1.4"},dependencies:{"fast-json-stable-stringify":"^2.1.0","object-hash":"^3.0.0"}};vt();ji();ke();var N4=Xt(Mr(),1);vt();var BH=Xt(Sn(),1);var bT={};il(bT,{AssignableViaAutoroutingPipelineSolver:()=>Tgt,AutoroutingPipelineSolver:()=>dj,CapacityMeshSolver:()=>xgt,InMemoryCache:()=>W$,LocalStorageCache:()=>Z$,calculateOptimalCapacityDepth:()=>mT,convertSrjToGraphicsObject:()=>zf,getGlobalInMemoryCache:()=>hh,getGlobalLocalStorageCache:()=>K$,getTunedTotalCapacity1:()=>zr,setupGlobalCaches:()=>Ff});var q$=Xt(pb(),1),aj=Xt(pb(),1),uj=Xt(pb(),1);var Wl=(...e)=>{let t={points:[],lines:[],circles:[],rects:[]};return e.forEach((n,i)=>{n&&(n.lines&&(t.lines=[...t.lines||[],...n.lines.map(o=>({...o,step:i}))]),n.points&&(t.points=[...t.points||[],...n.points.map(o=>({...o,step:i}))]),n.circles&&(t.circles=[...t.circles||[],...n.circles.map(o=>({...o,step:i}))]),n.rects&&(t.rects=[...t.rects||[],...n.rects.map(o=>({...o,step:i}))]))}),t},Ke=class{constructor(){P(this,"MAX_ITERATIONS",1e3);P(this,"solved",!1);P(this,"failed",!1);P(this,"iterations",0);P(this,"progress",0);P(this,"error",null);P(this,"activeSubSolver");P(this,"failedSubSolvers");P(this,"timeToSolve");P(this,"stats",{});P(this,"cacheHit");P(this,"cacheKey");P(this,"cacheToSolveSpaceTransform")}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.constructor.name} error: ${e}`,console.error(this.error),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`,console.error(this.error),this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){let e=Date.now();for(;!this.solved&&!this.failed;)this.step();let t=Date.now();this.timeToSolve=t-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function o$(e){let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,maxX:e.center.x+t,minY:e.center.y-n,maxY:e.center.y+n}}function sc(e,t,n){return Math.max(t,Math.min(n,e))}function Si(e,t,n,i){let o=hb(e,t,n),r=hb(e,t,i),s=hb(n,i,e),a=hb(n,i,t);return o!==r&&s!==a||!(o!==0||!db(e,n,t))||!(r!==0||!db(e,i,t))||!(s!==0||!db(n,e,i))||!(a!==0||!db(n,t,i))}function hb(e,t,n){let i=(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y);return i===0?0:i>0?1:2}function db(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function Qi(e,t,n){let i=(n.x-t.x)**2+(n.y-t.y)**2;if(i===0)return Wt(e,t);let o=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/i;return o=Math.max(0,Math.min(1,o)),Wt(e,{x:t.x+o*(n.x-t.x),y:t.y+o*(n.y-t.y)})}function Wt(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}function k$(e,t,n,i){let o=t.x-e.x,r=t.y-e.y,s=i.x-n.x,a=i.y-n.y,c=e.x-n.x,l=e.y-n.y,u=o*a-r*s;if(Math.abs(u)<1e-10)return null;let h=(l*s-c*a)/u,d=(o*l-r*c)/u,_=1e-9;return h>=-1e-9&&h<=1+_&&d>=-1e-9&&d<=1+_?{x:e.x+h*o,y:e.y+h*r}:null}function r$(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}var A$=e=>{if("minX"in e)return e;let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,minY:e.center.y-n,maxX:e.center.x+t,maxY:e.center.y+n}},fT=e=>[{x:e.minX,y:e.minY},{x:e.maxX,y:e.minY},{x:e.maxX,y:e.maxY},{x:e.minX,y:e.maxY}],R$=e=>{let t=[];for(let n=0;n<e.length;n++){let i=e[n],o=e[(n+1)%e.length];t.push([i,o])}return t},qyt=(e,t,n)=>{let i=(e.y-t.y)*(n.x-t.x)-(e.x-t.x)*(n.y-t.y);if(Math.abs(i)>1e-9)return!1;let o=(e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y);return o<0?!1:!(o>(n.x-t.x)**2+(n.y-t.y)**2)},O$=(e,t)=>{if(t.length<3)return!1;let n=R$(t);for(let[o,r]of n)if(qyt(e,o,r))return!0;let i=!1;for(let o=0,r=t.length-1;o<t.length;r=o++){let s=t[o].x,a=t[o].y,c=t[r].x,l=t[r].y;a>e.y!=l>e.y&&e.x<(c-s)*(e.y-a)/(l-a)+s&&(i=!i)}return i},L$=(e,t)=>{let n=fT(e),i=[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]],o=R$(t);for(let[r,s]of o)for(let[a,c]of i)if(Si(r,s,a,c))return!0;return!1},iT=(e,t)=>((n,i)=>!(i.length<3)&&(!!i.some(o=>((r,s)=>r.x>=s.minX&&r.x<=s.maxX&&r.y>=s.minY&&r.y<=s.maxY)(o,n))||!!fT(n).some(o=>O$(o,i))||L$(n,i)))(A$(e),t),F$=(e,t)=>((n,i)=>!(i.length<3)&&!!fT(n).every(o=>O$(o,i))&&!L$(n,i))(A$(e),t);function oT(e,t,n,i){if(e.x===t.x&&e.y===t.y)return Qi(e,n,i);if(n.x===i.x&&n.y===i.y)return Qi(n,e,t);if(Si(e,t,n,i))return 0;let o=[Qi(e,n,i),Qi(t,n,i),Qi(n,e,t),Qi(i,e,t)];return Math.min(...o)}function z$(e,t,n){let i=n.width/2,o=n.height/2;return(function(r,s,a){let c={x:a.minX,y:a.minY},l={x:a.maxX,y:a.minY},u={x:a.minX,y:a.maxY},h={x:a.maxX,y:a.maxY};if(Si(r,s,c,l)||Si(r,s,l,h)||Si(r,s,h,u)||Si(r,s,u,c)||r.x>=a.minX&&r.x<=a.maxX&&r.y>=a.minY&&r.y<=a.maxY&&s.x>=a.minX&&s.x<=a.maxX&&s.y>=a.minY&&s.y<=a.maxY)return 0;let d=[Qi(c,r,s),Qi(l,r,s),Qi(u,r,s),Qi(h,r,s)];if(r.x>=a.minX&&r.x<=a.maxX&&r.y>=a.minY&&r.y<=a.maxY||s.x>=a.minX&&s.x<=a.maxX&&s.y>=a.minY&&s.y<=a.maxY)return 0;if(r.x<a.minX||r.x>a.maxX||r.y<a.minY||r.y>a.maxY){let _=sc(r.x,a.minX,a.maxX),y=sc(r.y,a.minY,a.maxY);d.push(Wt(r,{x:_,y}))}if(s.x<a.minX||s.x>a.maxX||s.y<a.minY||s.y>a.maxY){let _=sc(s.x,a.minX,a.maxX),y=sc(s.y,a.minY,a.maxY);d.push(Wt(s,{x:_,y}))}return Math.min(...d)})(e,t,{minX:n.center.x-i,maxX:n.center.x+i,minY:n.center.y-o,maxY:n.center.y+o})}function ah(e,t,n){let i=n.x-t.x,o=n.y-t.y,r=i*i+o*o;if(r===0)return{x:t.x,y:t.y};let s=((e.x-t.x)*i+(e.y-t.y)*o)/r;return s=Math.max(0,Math.min(1,s)),{x:t.x+s*i,y:t.y+s*o}}function Io(){return Io=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},Io.apply(null,arguments)}function Cb(e,t){return(Cb=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n})(e,t)}function D$(e){return(D$=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(e)}function $$(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return($$=function(){return!!e})()}function rT(e){var t=typeof Map=="function"?new Map:void 0;return rT=function(n){if(n===null||!(function(o){try{return Function.toString.call(o).indexOf("[native code]")!==-1}catch{return typeof o=="function"}})(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(t!==void 0){if(t.has(n))return t.get(n);t.set(n,i)}function i(){return(function(o,r,s){if($$())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,r);var c=new(o.bind.apply(o,a));return s&&Cb(c,s.prototype),c})(n,arguments,D$(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Cb(i,n)},rT(e)}var Po=(function(e){var t,n;function i(o){var r;if(1)r=e.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+o+" for more information.")||this;else for(var s,a,c;c<s;c++);return(function(l){if(l===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return l})(r)}return n=e,(t=i).prototype=Object.create(n.prototype),t.prototype.constructor=t,Cb(t,n),i})(rT(Error));function s$(e,t){return e.substr(-t.length)===t}var Wyt=/^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;function a$(e){return typeof e!="string"?e:e.match(Wyt)?parseFloat(e):e}var c$=function(e){return function(t,n){n===void 0&&(n="16px");var i=t,o=n;if(typeof t=="string"){if(!s$(t,"px"))throw new Po(69,e,t);i=a$(t)}if(typeof n=="string"){if(!s$(n,"px"))throw new Po(70,e,n);o=a$(n)}if(typeof i=="string")throw new Po(71,t,e);if(typeof o=="string")throw new Po(72,n,e);return""+i/o+e}};c$("em"),c$("rem");function GI(e){return Math.round(255*e)}function Zyt(e,t,n){return GI(e)+","+GI(t)+","+GI(n)}function Rf(e,t,n,i){if(i===void 0&&(i=Zyt),t===0)return i(n,n,n);var o=(e%360+360)%360/60,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o%2-1)),a=0,c=0,l=0;o>=0&&o<1?(a=r,c=s):o>=1&&o<2?(a=s,c=r):o>=2&&o<3?(c=r,l=s):o>=3&&o<4?(c=s,l=r):o>=4&&o<5?(a=s,l=r):o>=5&&o<6&&(a=r,l=s);var u=n-r/2;return i(a+u,c+u,l+u)}var l$={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},Kyt=/^#[a-fA-F0-9]{6}$/,Jyt=/^#[a-fA-F0-9]{8}$/,Qyt=/^#[a-fA-F0-9]{3}$/,t0t=/^#[a-fA-F0-9]{4}$/,UI=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,e0t=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,n0t=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,i0t=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function ch(e){if(typeof e!="string")throw new Po(3);var t=(function(d){if(typeof d!="string")return d;var _=d.toLowerCase();return l$[_]?"#"+l$[_]:d})(e);if(t.match(Kyt))return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16)};if(t.match(Jyt)){var n=parseFloat((parseInt(""+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16),alpha:n}}if(t.match(Qyt))return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16)};if(t.match(t0t)){var i=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:i}}var o=UI.exec(t);if(o)return{red:parseInt(""+o[1],10),green:parseInt(""+o[2],10),blue:parseInt(""+o[3],10)};var r=e0t.exec(t.substring(0,50));if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10),alpha:parseFloat(""+r[4])>1?parseFloat(""+r[4])/100:parseFloat(""+r[4])};var s=n0t.exec(t);if(s){var a="rgb("+Rf(parseInt(""+s[1],10),parseInt(""+s[2],10)/100,parseInt(""+s[3],10)/100)+")",c=UI.exec(a);if(!c)throw new Po(4,t,a);return{red:parseInt(""+c[1],10),green:parseInt(""+c[2],10),blue:parseInt(""+c[3],10)}}var l=i0t.exec(t.substring(0,50));if(l){var u="rgb("+Rf(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",h=UI.exec(u);if(!h)throw new Po(4,t,u);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+l[4])>1?parseFloat(""+l[4])/100:parseFloat(""+l[4])}}throw new Po(5)}function ac(e){return(function(t){var n,i=t.red/255,o=t.green/255,r=t.blue/255,s=Math.max(i,o,r),a=Math.min(i,o,r),c=(s+a)/2;if(s===a)return t.alpha!==void 0?{hue:0,saturation:0,lightness:c,alpha:t.alpha}:{hue:0,saturation:0,lightness:c};var l=s-a,u=c>.5?l/(2-s-a):l/(s+a);switch(s){case i:n=(o-r)/l+(o<r?6:0);break;case o:n=(r-i)/l+2;break;default:n=(i-o)/l+4}return n*=60,t.alpha!==void 0?{hue:n,saturation:u,lightness:c,alpha:t.alpha}:{hue:n,saturation:u,lightness:c}})(ch(e))}var sT=function(e){return e.length===7&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?"#"+e[1]+e[3]+e[5]:e};function Ul(e){var t=e.toString(16);return t.length===1?"0"+t:t}function qI(e){return Ul(Math.round(255*e))}function o0t(e,t,n){return sT("#"+qI(e)+qI(t)+qI(n))}function fb(e,t,n){return Rf(e,t,n,o0t)}function aT(e,t,n){if(typeof e=="number"&&typeof t=="number"&&typeof n=="number")return sT("#"+Ul(e)+Ul(t)+Ul(n));if(typeof e=="object"&&t===void 0&&n===void 0)return sT("#"+Ul(e.red)+Ul(e.green)+Ul(e.blue));throw new Po(6)}function Fb(e,t,n,i){if(typeof e=="string"&&typeof t=="number"){var o=ch(e);return"rgba("+o.red+","+o.green+","+o.blue+","+t+")"}if(typeof e=="number"&&typeof t=="number"&&typeof n=="number"&&typeof i=="number")return i>=1?aT(e,t,n):"rgba("+e+","+t+","+n+","+i+")";if(typeof e=="object"&&t===void 0&&n===void 0&&i===void 0)return e.alpha>=1?aT(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new Po(7)}function cc(e){if(typeof e!="object")throw new Po(8);if((function(t){return typeof t.red=="number"&&typeof t.green=="number"&&typeof t.blue=="number"&&typeof t.alpha=="number"})(e))return Fb(e);if((function(t){return typeof t.red=="number"&&typeof t.green=="number"&&typeof t.blue=="number"&&(typeof t.alpha!="number"||t.alpha===void 0)})(e))return aT(e);if((function(t){return typeof t.hue=="number"&&typeof t.saturation=="number"&&typeof t.lightness=="number"&&typeof t.alpha=="number"})(e))return(function(t,n,i,o){if(typeof t=="number"&&typeof n=="number"&&typeof i=="number"&&typeof o=="number")return o>=1?fb(t,n,i):"rgba("+Rf(t,n,i)+","+o+")";if(typeof t=="object"&&n===void 0&&i===void 0&&o===void 0)return t.alpha>=1?fb(t.hue,t.saturation,t.lightness):"rgba("+Rf(t.hue,t.saturation,t.lightness)+","+t.alpha+")";throw new Po(2)})(e);if((function(t){return typeof t.hue=="number"&&typeof t.saturation=="number"&&typeof t.lightness=="number"&&(typeof t.alpha!="number"||t.alpha===void 0)})(e))return(function(t,n,i){if(typeof t=="number"&&typeof n=="number"&&typeof i=="number")return fb(t,n,i);if(typeof t=="object"&&n===void 0&&i===void 0)return fb(t.hue,t.saturation,t.lightness);throw new Po(1)})(e);throw new Po(8)}function j$(e,t,n){return function(){var i=n.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):j$(e,t,i)}}function Bo(e){return j$(e,e.length,[])}Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{hue:n.hue+parseFloat(e)}))});function ph(e,t,n){return Math.max(e,Math.min(t,n))}Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{lightness:ph(0,1,n.lightness-parseFloat(e))}))});Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{saturation:ph(0,1,n.saturation-parseFloat(e))}))});Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{lightness:ph(0,1,n.lightness+parseFloat(e))}))});var B$=Bo(function(e,t,n){if(t==="transparent")return n;if(n==="transparent")return t;if(e===0)return n;var i=ch(t),o=Io({},i,{alpha:typeof i.alpha=="number"?i.alpha:1}),r=ch(n),s=Io({},r,{alpha:typeof r.alpha=="number"?r.alpha:1}),a=o.alpha-s.alpha,c=2*parseFloat(e)-1,l=((c*a===-1?c:c+a)/(1+c*a)+1)/2,u=1-l;return Fb({red:Math.floor(o.red*l+s.red*u),green:Math.floor(o.green*l+s.green*u),blue:Math.floor(o.blue*l+s.blue*u),alpha:o.alpha*parseFloat(e)+s.alpha*(1-parseFloat(e))})});Bo(function(e,t){if(t==="transparent")return t;var n=ch(t);return Fb(Io({},n,{alpha:ph(0,1,(100*(typeof n.alpha=="number"?n.alpha:1)+100*parseFloat(e))/100)}))});Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{saturation:ph(0,1,n.saturation+parseFloat(e))}))});Bo(function(e,t){return t==="transparent"?t:cc(Io({},ac(t),{hue:parseFloat(e)}))});Bo(function(e,t){return t==="transparent"?t:cc(Io({},ac(t),{lightness:parseFloat(e)}))});Bo(function(e,t){return t==="transparent"?t:cc(Io({},ac(t),{saturation:parseFloat(e)}))});Bo(function(e,t){return t==="transparent"?t:B$(parseFloat(e),"rgb(0, 0, 0)",t)});Bo(function(e,t){return t==="transparent"?t:B$(parseFloat(e),"rgb(255, 255, 255)",t)});var r0t=Bo(function(e,t){if(t==="transparent")return t;var n=ch(t);return Fb(Io({},n,{alpha:ph(0,1,+(100*(typeof n.alpha=="number"?n.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))}),u$=["blue","orange","purple","cyan","magenta","yellowgreen","darkgoldenrod","deeppink"],Of=(e,t)=>{let n={};for(let i=0;i<e.connections.length;i++){let o=e.connections[i],r=t?.getNetConnectedToId(o.name);r&&!n[r]&&(n[r]=`hsl(${300*i/e.connections.length}, 100%, 50%)`),n[o.name]=(r?n[r]:null)??`hsl(${340*i/e.connections.length}, 100%, 50%)`}return n},$n=(e,t)=>{try{return r0t(t,e)}catch(n){return console.error(n),e}},Zl=(e,t)=>e==="top"?0:e==="bottom"?t-1:parseInt(e.slice(5)),zr=(e,t=1)=>{let n=(("width"in e?e.width:e)/.5/2)**1.1*t;return e.availableZ?.length===1&&n>1?1:n},mT=(e,t=.5,n=16)=>{let i=0,o=e;for(;i<n&&!(zr({width:o})<=t);)o/=2,i++;return Math.max(1,i)};function Y$(e,t,n=0,i=e.length-1,o=s0t){for(;i>n;){if(i-n>600){let c=i-n+1,l=t-n+1,u=Math.log(c),h=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*h*(c-h)/c)*(l-c/2<0?-1:1);Y$(e,t,Math.max(n,Math.floor(t-l*h/c+d)),Math.min(i,Math.floor(t+(c-l)*h/c+d)),o)}let r=e[t],s=n,a=i;for(Tf(e,n,t),o(e[i],r)>0&&Tf(e,n,i);s<a;){for(Tf(e,s,a),s++,a--;o(e[s],r)<0;)s++;for(;o(e[a],r)>0;)a--}o(e[n],r)===0?Tf(e,n,a):(a++,Tf(e,a,i)),a<=t&&(n=a+1),t<=a&&(i=a-1)}}function Tf(e,t,n){let i=e[t];e[t]=e[n],e[n]=i}function s0t(e,t){return e<t?-1:e>t?1:0}var a0t=class{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data,n=[];if(!_b(e,t))return n;let i=this.toBBox,o=[];for(;t;){for(let r=0;r<t.children.length;r++){let s=t.children[r],a=t.leaf?i(s):s;_b(e,a)&&(t.leaf?n.push(s):ZI(e,a)?this._all(s,n):o.push(s))}t=o.pop()}return n}collides(e){let t=this.data;if(!_b(e,t))return!1;let n=[];for(;t;){for(let i=0;i<t.children.length;i++){let o=t.children[i],r=t.leaf?this.toBBox(o):o;if(_b(e,r)){if(t.leaf||ZI(e,r))return!0;n.push(o)}}t=n.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let n=0;n<e.length;n++)this.insert(e[n]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){let n=this.data;this.data=t,t=n}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=rh([]),this}remove(e,t){if(!e)return this;let n=this.data,i=this.toBBox(e),o=[],r=[],s,a,c;for(;n||o.length;){if(n||(n=o.pop(),a=o[o.length-1],s=r.pop(),c=!0),n.leaf){let l=c0t(e,n.children,t);if(l!==-1)return n.children.splice(l,1),o.push(n),this._condense(o),this}c||n.leaf||!ZI(n,i)?a?(s++,n=a.children[s],c=!1):n=null:(o.push(n),r.push(s),s=0,a=n,n=n.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){let n=[];for(;e;)e.leaf?t.push(...e.children):n.push(...e.children),e=n.pop();return t}_build(e,t,n,i){let o=n-t+1,r,s=this._maxEntries;if(o<=s)return r=rh(e.slice(t,n+1)),oh(r,this.toBBox),r;i||(i=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/Math.pow(s,i-1))),r=rh([]),r.leaf=!1,r.height=i;let a=Math.ceil(o/s),c=a*Math.ceil(Math.sqrt(s));p$(e,t,n,c,this.compareMinX);for(let l=t;l<=n;l+=c){let u=Math.min(l+c-1,n);p$(e,l,u,a,this.compareMinY);for(let h=l;h<=u;h+=a){let d=Math.min(h+a-1,u);r.children.push(this._build(e,h,d,i-1))}}return oh(r,this.toBBox),r}_chooseSubtree(e,t,n,i){for(;i.push(t),!t.leaf&&i.length-1!==n;){let o,r=1/0,s=1/0;for(let a=0;a<t.children.length;a++){let c=t.children[a],l=WI(c),u=p0t(e,c)-l;u<s?(s=u,r=l<r?l:r,o=c):u===s&&l<r&&(r=l,o=c)}t=o||t.children[0]}return t}_insert(e,t,n){let i=n?e:this.toBBox(e),o=[],r=this._chooseSubtree(i,this.data,t,o);for(r.children.push(e),Cf(r,i);t>=0&&o[t].children.length>this._maxEntries;)this._split(o,t),t--;this._adjustParentBBoxes(i,o,t)}_split(e,t){let n=e[t],i=n.children.length,o=this._minEntries;this._chooseSplitAxis(n,o,i);let r=this._chooseSplitIndex(n,o,i),s=rh(n.children.splice(r,n.children.length-r));s.height=n.height,s.leaf=n.leaf,oh(n,this.toBBox),oh(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)}_splitRoot(e,t){this.data=rh([e,t]),this.data.height=e.height+1,this.data.leaf=!1,oh(this.data,this.toBBox)}_chooseSplitIndex(e,t,n){let i,o=1/0,r=1/0;for(let s=t;s<=n-t;s++){let a=Mf(e,0,s,this.toBBox),c=Mf(e,s,n,this.toBBox),l=h0t(a,c),u=WI(a)+WI(c);l<o?(o=l,i=s,r=u<r?u:r):l===o&&u<r&&(r=u,i=s)}return i||n-t}_chooseSplitAxis(e,t,n){let i=e.leaf?this.compareMinX:l0t,o=e.leaf?this.compareMinY:u0t;this._allDistMargin(e,t,n,i)<this._allDistMargin(e,t,n,o)&&e.children.sort(i)}_allDistMargin(e,t,n,i){e.children.sort(i);let o=this.toBBox,r=Mf(e,0,t,o),s=Mf(e,n-t,n,o),a=mb(r)+mb(s);for(let c=t;c<n-t;c++){let l=e.children[c];Cf(r,e.leaf?o(l):l),a+=mb(r)}for(let c=n-t-1;c>=t;c--){let l=e.children[c];Cf(s,e.leaf?o(l):l),a+=mb(s)}return a}_adjustParentBBoxes(e,t,n){for(let i=n;i>=0;i--)Cf(t[i],e)}_condense(e){for(let t,n=e.length-1;n>=0;n--)e[n].children.length===0?n>0?(t=e[n-1].children,t.splice(t.indexOf(e[n]),1)):this.clear():oh(e[n],this.toBBox)}};function c0t(e,t,n){if(!n)return t.indexOf(e);for(let i=0;i<t.length;i++)if(n(e,t[i]))return i;return-1}function oh(e,t){Mf(e,0,e.children.length,t,e)}function Mf(e,t,n,i,o){o||(o=rh(null)),o.minX=1/0,o.minY=1/0,o.maxX=-1/0,o.maxY=-1/0;for(let r=t;r<n;r++){let s=e.children[r];Cf(o,e.leaf?i(s):s)}return o}function Cf(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function l0t(e,t){return e.minX-t.minX}function u0t(e,t){return e.minY-t.minY}function WI(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function mb(e){return e.maxX-e.minX+(e.maxY-e.minY)}function p0t(e,t){return(Math.max(t.maxX,e.maxX)-Math.min(t.minX,e.minX))*(Math.max(t.maxY,e.maxY)-Math.min(t.minY,e.minY))}function h0t(e,t){let n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),o=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return Math.max(0,o-n)*Math.max(0,r-i)}function ZI(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function _b(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function rh(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function p$(e,t,n,i,o){let r=[t,n];for(;r.length;){if((n=r.pop())-(t=r.pop())<=i)continue;let s=t+Math.ceil((n-t)/i/2)*i;Y$(e,s,t,n,o),r.push(t,s,s,n)}}var h$=class{constructor(e=9){P(this,"tree");this.tree=new a0t(e)}insert(e,t,n,i,o){this.tree.insert({minX:t,minY:n,maxX:i,maxY:o,data:e})}bulkLoad(e){let t=e.map(({item:n,minX:i,minY:o,maxX:r,maxY:s})=>({minX:i,minY:o,maxX:r,maxY:s,data:n}));this.tree.load(t)}search(e,t,n,i){return this.tree.search({minX:e,minY:t,maxX:n,maxY:i}).map(o=>o.data)}clear(){this.tree.clear()}},d0t=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(e,t){let n=this.length++;for(;n>0;){let i=n-1>>1,o=this.values[i];if(t>=o)break;this.ids[n]=this.ids[i],this.values[n]=o,n=i}this.ids[n]=e,this.values[n]=t}pop(){if(this.length===0)return;let e=this.ids,t=this.values,n=e[0],i=--this.length;if(i>0){let o=e[i],r=t[i],s=0,a=i>>1;for(;s<a;){let c=1+(s<<1),l=c+1,u=c+(+(l<i)&+(t[l]<t[c]));if(t[u]>=r)break;e[s]=e[u],t[s]=t[u],s=u}e[s]=o,t[s]=r}return n}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){this.ids.length=this.values.length=this.length}},d$=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],f$=class X${static from(t,n=0){if(n%8!=0)throw new Error("byteOffset must be 8-byte aligned.");if(!t||t.byteLength===void 0||t.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[i,o]=new Uint8Array(t,n+0,2);if(i!==251)throw new Error("Data does not appear to be in a Flatbush format.");let r=o>>4;if(r!==3)throw new Error(`Got v${r} data when expected v3.`);let s=d$[15&o];if(!s)throw new Error("Unrecognized array type.");let[a]=new Uint16Array(t,n+2,1),[c]=new Uint32Array(t,n+4,1);return new X$(c,a,s,void 0,t,n)}constructor(t,n=16,i=Float64Array,o=ArrayBuffer,r,s=0){if(t===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(t)||t<=0)throw new Error(`Unexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+n,2),65535),this.byteOffset=s;let a=t,c=a;this._levelBounds=[4*a];do a=Math.ceil(a/this.nodeSize),c+=a,this._levelBounds.push(4*c);while(a!==1);this.ArrayType=i,this.IndexArrayType=c<16384?Uint16Array:Uint32Array;let l=d$.indexOf(i),u=4*c*i.BYTES_PER_ELEMENT;if(l<0)throw new Error(`Unexpected typed array class: ${i}.`);if(r)this.data=r,this._boxes=new i(r,s+8,4*c),this._indices=new this.IndexArrayType(r,s+8+u,c),this._pos=4*c,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1];else{let h=this.data=new o(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(h,8,4*c),this._indices=new this.IndexArrayType(h,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(h,0,2).set([251,48+l]),new Uint16Array(h,2,1)[0]=n,new Uint32Array(h,4,1)[0]=t}this._queue=new d0t}add(t,n,i=t,o=n){let r=this._pos>>2,s=this._boxes;return this._indices[r]=r,s[this._pos++]=t,s[this._pos++]=n,s[this._pos++]=i,s[this._pos++]=o,t<this.minX&&(this.minX=t),n<this.minY&&(this.minY=n),i>this.maxX&&(this.maxX=i),o>this.maxY&&(this.maxY=o),r}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let t=this._boxes;if(this.numItems<=this.nodeSize)return t[this._pos++]=this.minX,t[this._pos++]=this.minY,t[this._pos++]=this.maxX,void(t[this._pos++]=this.maxY);let n=this.maxX-this.minX||1,i=this.maxY-this.minY||1,o=new Uint32Array(this.numItems);for(let r=0,s=0;r<this.numItems;r++){let a=t[s++],c=t[s++],l=t[s++],u=t[s++],h=Math.floor(65535*((a+l)/2-this.minX)/n),d=Math.floor(65535*((c+u)/2-this.minY)/i);o[r]=m0t(h,d)}cT(o,t,this._indices,0,this.numItems-1,this.nodeSize);for(let r=0,s=0;r<this._levelBounds.length-1;r++){let a=this._levelBounds[r];for(;s<a;){let c=s,l=t[s++],u=t[s++],h=t[s++],d=t[s++];for(let _=1;_<this.nodeSize&&s<a;_++)l=Math.min(l,t[s++]),u=Math.min(u,t[s++]),h=Math.max(h,t[s++]),d=Math.max(d,t[s++]);this._indices[this._pos>>2]=c,t[this._pos++]=l,t[this._pos++]=u,t[this._pos++]=h,t[this._pos++]=d}}}search(t,n,i,o,r){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=[],c=[];for(;s!==void 0;){let l=Math.min(s+4*this.nodeSize,m$(s,this._levelBounds));for(let u=s;u<l;u+=4){let h=this._boxes[u];if(i<h)continue;let d=this._boxes[u+1];if(o<d)continue;let _=this._boxes[u+2];if(t>_)continue;let y=this._boxes[u+3];if(n>y)continue;let g=0|this._indices[u>>2];s>=4*this.numItems?a.push(g):(r===void 0||r(g,h,d,_,y))&&c.push(g)}s=a.pop()}return c}neighbors(t,n,i=1/0,o=1/0,r){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=this._queue,c=[],l=o*o;t:for(;s!==void 0;){let u=Math.min(s+4*this.nodeSize,m$(s,this._levelBounds));for(let h=s;h<u;h+=4){let d=0|this._indices[h>>2],_=this._boxes[h],y=this._boxes[h+1],g=this._boxes[h+2],x=this._boxes[h+3],w=t<_?_-t:t>g?t-g:0,S=n<y?y-n:n>x?n-x:0,T=w*w+S*S;T>l||(s>=4*this.numItems?a.push(d<<1,T):(r===void 0||r(d))&&a.push(1+(d<<1),T))}for(;a.length&&1&a.peek();)if(a.peekValue()>l||(c.push(a.pop()>>1),c.length===i))break t;s=a.length?a.pop()>>1:void 0}return a.clear(),c}};function m$(e,t){let n=0,i=t.length-1;for(;n<i;){let o=n+i>>1;t[o]>e?i=o:n=o+1}return t[n]}function cT(e,t,n,i,o,r){if(Math.floor(i/r)>=Math.floor(o/r))return;let s=e[i],a=e[i+o>>1],c=e[o],l=c,u=Math.max(s,a);c>u?l=u:u===s?l=Math.max(a,c):u===a&&(l=Math.max(s,c));let h=i-1,d=o+1;for(;;){do h++;while(e[h]<l);do d--;while(e[d]>l);if(h>=d)break;f0t(e,t,n,h,d)}cT(e,t,n,i,d,r),cT(e,t,n,d+1,o,r)}function f0t(e,t,n,i,o){let r=e[i];e[i]=e[o],e[o]=r;let s=4*i,a=4*o,c=t[s],l=t[s+1],u=t[s+2],h=t[s+3];t[s]=t[a],t[s+1]=t[a+1],t[s+2]=t[a+2],t[s+3]=t[a+3],t[a]=c,t[a+1]=l,t[a+2]=u,t[a+3]=h;let d=n[i];n[i]=n[o],n[o]=d}function m0t(e,t){let n=e^t,i=65535^n,o=65535^(e|t),r=e&(65535^t),s=n|i>>1,a=n>>1^n,c=o>>1^i&r>>1^o,l=n&o>>1^r>>1^r;n=s,i=a,o=c,r=l,s=n&n>>2^i&i>>2,a=n&i>>2^i&(n^i)>>2,c^=n&o>>2^i&r>>2,l^=i&o>>2^(n^i)&r>>2,n=s,i=a,o=c,r=l,s=n&n>>4^i&i>>4,a=n&i>>4^i&(n^i)>>4,c^=n&o>>4^i&r>>4,l^=i&o>>4^(n^i)&r>>4,n=s,i=a,o=c,r=l,c^=n&o>>8^i&r>>8,l^=i&o>>8^(n^i)&r>>8,n=c^c>>1,i=l^l>>1;let u=e^t,h=i|65535^(u|n);return u=16711935&(u|u<<8),u=252645135&(u|u<<4),u=858993459&(u|u<<2),u=1431655765&(u|u<<1),h=16711935&(h|h<<8),h=252645135&(h|h<<4),h=858993459&(h|h<<2),h=1431655765&(h|h<<1),(h<<1|u)>>>0}var _0t=class{constructor(e){P(this,"index");P(this,"items",[]);P(this,"currentIndex",0);P(this,"capacity");this.capacity=Math.max(1,e),this.index=new f$(this.capacity)}insert(e,t,n,i,o){if(this.currentIndex>=this.index.numItems)throw new Error("Exceeded initial capacity");this.items[this.currentIndex]=e,this.index.add(t,n,i,o),this.currentIndex++}finish(){this.index.finish()}search(e,t,n,i){return this.index.search(e,t,n,i).map(o=>this.items[o]||null).filter(Boolean)}clear(){this.items=[],this.currentIndex=0,this.index=new f$(this.capacity)}},V$=class{constructor(e="native",t=[]){P(this,"idx");P(this,"storage",[]);e==="flatbush"?t.length===0?(this.idx=new h$,e="rbush"):this.idx=new _0t(t.length):this.idx=e==="rbush"?new h$:new class{constructor(){P(this,"shi",new y0t(t))}insert(n){}search(n,i,o,r){let s=(n+o)/2,a=(i+r)/2,c=o-n,l=r-i;return this.shi.getNodesInArea(s,a,c,l)}clear(){}},t.forEach(n=>this.insert(n)),e==="flatbush"&&t.length>0&&this.idx.finish?.()}insert(e){this.storage.push(e),this.idx.insert(e,e.center.x-e.width/2,e.center.y-e.height/2,e.center.x+e.width/2,e.center.y+e.height/2)}search(e){return this.idx.search(e.minX,e.minY,e.maxX,e.maxY)}searchArea(e,t,n,i){return this.search({minX:e-n/2,minY:t-i/2,maxX:e+n/2,maxY:t+i/2})}},y0t=class{constructor(e){P(this,"buckets");P(this,"CELL_SIZE",.4);this.obstacles=e,this.buckets=new Map;for(let t=0;t<e.length;t++){let n=e[t],i=n.center.x-n.width/2,o=n.center.y-n.height/2,r=n.center.x+n.width/2,s=n.center.y+n.height/2;for(let a=i;a<=r;a+=this.CELL_SIZE)for(let c=o;c<=s;c+=this.CELL_SIZE){let l=this.getBucketKey(a,c),u=this.buckets.get(l);u?u.push([n,t]):this.buckets.set(l,[[n,t]])}}}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getNodesInArea(e,t,n,i){let o=[],r=new Set,s=t-i/2,a=e+n/2,c=t+i/2;for(let l=e-n/2;l<=a;l+=this.CELL_SIZE)for(let u=s;u<=c;u+=this.CELL_SIZE){let h=this.getBucketKey(l,u),d=this.buckets.get(h)||[];for(let _ of d)r.has(_[1])||(r.add(_[1]),o.push(_[0]))}return o}},g0t=class{constructor(e){P(this,"buckets");P(this,"CELL_SIZE",5);this.targets=e,this.buckets=new Map;for(let t=0;t<e.length;t++){let n=e[t],i=Math.floor(n.bounds.minX/this.CELL_SIZE)*this.CELL_SIZE,o=Math.floor(n.bounds.minY/this.CELL_SIZE)*this.CELL_SIZE,r=n.bounds.maxX,s=n.bounds.maxY;for(let a=i;a<=r;a+=this.CELL_SIZE)for(let c=o;c<=s;c+=this.CELL_SIZE){let l=this.getBucketKey(a,c),u=this.buckets.get(l);u?u.push([n,t]):this.buckets.set(l,[[n,t]])}}}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getTargetsInArea(e,t,n,i){let o=[],r=new Set,s=Math.floor((e-n/2)/this.CELL_SIZE)*this.CELL_SIZE,a=Math.floor((t-i/2)/this.CELL_SIZE)*this.CELL_SIZE,c=e+n/2,l=t+i/2;for(let u=s;u<=c;u+=this.CELL_SIZE)for(let h=a;h<=l;h+=this.CELL_SIZE){let d=this.getBucketKey(u,h),_=this.buckets.get(d)||[];for(let y of _)r.has(y[1])||(r.add(y[1]),o.push(y[0]))}return o}},b0t=class extends Ke{constructor(t,n={}){super();P(this,"unfinishedNodes");P(this,"finishedNodes");P(this,"nodeToXYOverlappingObstaclesMap");P(this,"layerCount");P(this,"outlinePolygon");P(this,"MAX_DEPTH",4);P(this,"targets");P(this,"targetTree");P(this,"obstacleTree");P(this,"_nextNodeCounter",0);this.srj=t,this.opts=n,this.MAX_DEPTH=n?.capacityDepth??this.MAX_DEPTH,this.MAX_ITERATIONS=1e5,this.layerCount=t.layerCount??2,this.outlinePolygon=t.outline&&t.outline.length>=3?t.outline:void 0;for(let s of t.obstacles)if(!s.zLayers){let a=[];for(let c of s.layers)a.push(Zl(c,t.layerCount));s.zLayers=a}let i={x:(t.bounds.minX+t.bounds.maxX)/2,y:(t.bounds.minY+t.bounds.maxY)/2},o={width:t.bounds.maxX-t.bounds.minX,height:t.bounds.maxY-t.bounds.minY},r=Math.max(o.width,o.height);this.unfinishedNodes=[{capacityMeshNodeId:this.getNextNodeId(),center:i,width:r,height:r,layer:"top",availableZ:Array.from({length:this.layerCount},(s,a)=>a),_depth:0,_containsTarget:!0,_containsObstacle:!0,_completelyInsideObstacle:!1}],this.finishedNodes=[],this.nodeToXYOverlappingObstaclesMap=new Map,this.obstacleTree=new V$("flatbush",this.srj.obstacles),this.targets=this.computeTargets(),this.targetTree=new g0t(this.targets)}computeTargets(){let t=[];for(let n of this.srj.connections)for(let i of n.pointsToConnect){let o=this.obstacleTree.searchArea(i.x,i.y,.01,.01).filter(a=>a.zLayers.some(c=>c===Zl(i.layer,this.layerCount))),r={minX:i.x-.005,minY:i.y-.005,maxX:i.x+.005,maxY:i.y+.005};o.length>0&&(r={minX:Math.min(...o.map(a=>a.center.x-a.width/2)),minY:Math.min(...o.map(a=>a.center.y-a.height/2)),maxX:Math.max(...o.map(a=>a.center.x+a.width/2)),maxY:Math.max(...o.map(a=>a.center.y+a.height/2))});let s={...i,connectionName:n.name,availableZ:[Zl(i.layer,this.layerCount)],bounds:r};t.push(s)}return t}getNodeBounds(t){let n=t.width/2,i=t.height/2;return{minX:t.center.x-n,maxX:t.center.x+n,minY:t.center.y-i,maxY:t.center.y+i}}getNodeRect(t){return{center:{x:t.center.x,y:t.center.y},width:t.width,height:t.height}}getNextNodeId(){return"cn"+this._nextNodeCounter++}getCapacityFromDepth(t){return(this.MAX_DEPTH-t+1)**2}getTargetIfNodeContainsTarget(t){let n=t.width>4*this.targetTree.CELL_SIZE?this.targets:this.targetTree.getTargetsInArea(t.center.x,t.center.y,t.width,t.height);for(let i of n)if(i.bounds.minX<=t.center.x+t.width/2&&i.bounds.maxX>=t.center.x-t.width/2&&i.bounds.minY<=t.center.y+t.height/2&&i.bounds.maxY>=t.center.y-t.height/2&&i.availableZ.some(o=>t.availableZ.includes(o)))return i;return null}getXYOverlappingObstacles(t){let n=this.nodeToXYOverlappingObstaclesMap.get(t.capacityMeshNodeId);if(n)return n;let i=[],o=this.getNodeBounds(t),r=o.minX,s=o.maxX,a=o.minY,c=o.maxY,l=t._parent?this.getXYOverlappingObstacles(t._parent):this.srj.obstacles;for(let u of l){let h=u.center.x-u.width/2,d=u.center.x+u.width/2,_=u.center.y-u.height/2,y=u.center.y+u.height/2;(s>=h&&r<=d&&c>=_&&a<=y||r>=h&&s<=d&&a>=_&&c<=y||h>=r&&d<=s&&_>=a&&y<=c)&&i.push(u)}return this.nodeToXYOverlappingObstaclesMap.set(t.capacityMeshNodeId,i),i}getXYZOverlappingObstacles(t){let n=this.getXYOverlappingObstacles(t),i=[];for(let o of n)t.availableZ.some(r=>o.zLayers.includes(r))&&i.push(o);return i}doesNodeOverlapObstacle(t){if(this.getXYZOverlappingObstacles(t).length>0)return!0;let n=this.getNodeBounds(t);if(this.outlinePolygon){let i=this.getNodeRect(t);if(!F$(i,this.outlinePolygon))return!0}return n.minX<this.srj.bounds.minX||n.maxX>this.srj.bounds.maxX||n.minY<this.srj.bounds.minY||n.maxY>this.srj.bounds.maxY}isNodeCompletelyInsideObstacle(t){let n=this.getXYZOverlappingObstacles(t),i=this.getNodeBounds(t);if(this.outlinePolygon){let o=this.getNodeRect(t);if(!iT(o,this.outlinePolygon))return!0}for(let o of n){let r=o.center.x-o.width/2,s=o.center.x+o.width/2,a=o.center.y-o.height/2,c=o.center.y+o.height/2;if(i.minX>=r&&i.maxX<=s&&i.minY>=a&&i.maxY<=c)return!0}return!1}getChildNodes(t){if(t._depth===this.MAX_DEPTH)return[];let n=[],i={width:t.width/2,height:t.height/2},o=[{x:t.center.x-i.width/2,y:t.center.y-i.height/2},{x:t.center.x+i.width/2,y:t.center.y-i.height/2},{x:t.center.x-i.width/2,y:t.center.y+i.height/2},{x:t.center.x+i.width/2,y:t.center.y+i.height/2}];for(let r of o){let s={capacityMeshNodeId:this.getNextNodeId(),center:r,width:i.width,height:i.height,layer:t.layer,availableZ:t.availableZ,_depth:(t._depth??0)+1,_parent:t};s._containsObstacle=this.doesNodeOverlapObstacle(s);let a=this.getTargetIfNodeContainsTarget(s);a&&(s._targetConnectionName=a.connectionName,s.availableZ=a.availableZ,s._containsTarget=!0),s._containsObstacle&&(s._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(s)),s._completelyInsideObstacle&&!s._containsTarget||n.push(s)}return n}shouldNodeBeXYSubdivided(t){return!(t._depth>=this.MAX_DEPTH)&&(!!t._containsTarget||!(!t._containsObstacle||t._completelyInsideObstacle))}_step(){let t=this.unfinishedNodes.pop();if(!t)return void(this.solved=!0);let n=this.getChildNodes(t),i=[],o=[];for(let r of n){let s=this.shouldNodeBeXYSubdivided(r);s?o.push(r):s||r._containsObstacle?!s&&r._containsTarget&&i.push(r):i.push(r)}this.unfinishedNodes.push(...o),this.finishedNodes.push(...i)}visualize(){let t={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Capacity Mesh Visualization"};if(this.outlinePolygon&&this.outlinePolygon.length>=2){let i=this.outlinePolygon.map(o=>({x:o.x,y:o.y}));i.push({...i[0]}),t.lines.push({points:i,strokeColor:"rgba(0, 136, 255, 0.95)",label:"outline"});for(let o of this.outlinePolygon)t.points.push({x:o.x,y:o.y,color:"rgba(0, 136, 255, 0.95)"})}for(let i of this.srj.obstacles)t.rects.push({center:i.center,width:i.width,height:i.height,fill:i.zLayers?.length===1&&i.zLayers?.includes(1)?"rgba(0,0,255,0.3)":"rgba(255,0,0,0.3)",stroke:"red",label:["obstacle",`z: ${i.zLayers.join(",")}`].join(`
161
+ `),{solved:!1,connectionName:e.name}}createObstacleList({dominantLayer:e,connection:t,obstaclesFromTraces:n}){return new KF(this.allObstacles.filter(i=>!i.connectedTo.includes(t.name)).filter(i=>i.layers.includes(e)).concat(n??[]))}postprocessConnectionSolveResult(e,t){return t}solve(){let e=[],t=[];this.debugTraceCount=0;for(let n of this.input.connections){let i=n.pointsToConnect[0].layer??"top";this.debugTraceCount+=1,this.obstacles=this.createObstacleList({dominantLayer:i,connection:n,obstaclesFromTraces:t});let o=this.solveConnection(n);o=this.postprocessConnectionSolveResult(n,o),e.push(o),Dl.enabled&&this.drawDebugTraceObstacles(t),o.solved&&t.push(...ZF(o.route.map(r=>({x:r.x,y:r.y,layer:r.layer??i})),n.name))}return e}solveAndMapToTraces(){return this.solve().flatMap(t=>t.solved?[{type:"pcb_trace",pcb_trace_id:`pcb_trace_for_${t.connectionName}`,route:K1t(t.route.map(n=>({route_type:"wire",x:n.x,y:n.y,width:this.input.minTraceWidth,layer:n.layer})))}]:[])}getDebugGroup(){let e=`t${this.debugTraceCount}_iter[${this.iterations-1}]`;return this.iterations<30||this.iterations<100&&this.iterations%10===0||this.iterations<1e3&&this.iterations%100===0||!this.debugSolutions?e:null}drawDebugTraceObstacles(e){let{debugTraceCount:t,debugSolutions:n}=this;for(let i in n)i.startsWith(`t${t}_`)&&n[i].push(...e.map((o,r)=>({type:"pcb_smtpad",pcb_component_id:"",layer:o.layers[0],width:o.width,shape:"rect",x:o.center.x,y:o.center.y,pcb_smtpad_id:`trace_obstacle_${r}`,height:o.height})))}drawDebugSolution({current:e,newNeighbors:t}){let n=this.getDebugGroup();if(!n)return;let{openSet:i,debugTraceCount:o,debugSolutions:r}=this;r[n]??(r[n]=[]);let s=r[n];s.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${e.x}_${e.y}`,font:"tscircuit2024",font_size:.25,text:"X"+(e.l!==void 0?e.l:""),pcb_component_id:"",layer:"top",anchor_position:{x:e.x,y:e.y},anchor_alignment:"center"});for(let a=0;a<i.length;a++){let c=i[a];s.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${c.x}_${c.y}`,layer:"top",route:[[0,.05],[.05,0],[0,-.05],[-.05,0],[0,.05]].map(([l,u])=>({x:c.x+l,y:c.y+u})),stroke_width:.01}),s.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${c.x}_${c.y}`,font:"tscircuit2024",font_size:.03,text:a.toString(),pcb_component_id:"",layer:"top",anchor_position:{x:c.x,y:c.y},anchor_alignment:"center"})}if(e.parent){let a=[],c=e;for(;c;)a.unshift(c),c=c.parent;s.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${e.x}_${e.y}`,layer:"top",route:a,stroke_width:.01})}}},Q1t=(0,tz.default)("autorouting-dataset:infinite-grid-ijump-astar:get-distance-to-overcome-obstacle");function TI({node:e,travelDir:t,wallDir:n,obstacle:i,obstacles:o,obstaclesInRow:r=0,OBSTACLE_MARGIN:s=.15,SHOULD_DETECT_CONJOINED_OBSTACLES:a=!1,MAX_CONJOINED_OBSTACLES:c=20}){let l;if(t.dx===0?t.dy>0?l=i.center.y+i.height/2-e.y:l=e.y-(i.center.y-i.height/2):t.dx>0?l=i.center.x+i.width/2-e.x:l=e.x-(i.center.x-i.width/2),l+=s,a&&r<c){let u=o.getObstacleAt(e.x+t.dx*l+n.dx*(n.wallDistance+.001),e.y+t.dy*l+n.dy*(n.wallDistance+.001));if(u===i)return l;if(u&&u.type==="rect"){let h=t.dy===0,d=h?i.height:i.width;if((h?u.height:u.width)>d)return Q1t("next obstacle on path is bigger, not trying to overcome it"),l;let y=TI({node:{x:e.x+t.dx*l,y:e.y+t.dy*l},travelDir:t,wallDir:n,obstacle:u,obstacles:o,obstaclesInRow:r+1,SHOULD_DETECT_CONJOINED_OBSTACLES:a,MAX_CONJOINED_OBSTACLES:c,OBSTACLE_MARGIN:s});l+=y}}return l}var t_t=class extends QF{constructor(){super(...arguments);P(this,"MAX_ITERATIONS",200)}getNeighbors(t){let n=this.obstacles,i=this.goalPoint,o;t.parent?o=YF(t.parent,t):o=YF(t,i);let r=[{dx:0,dy:1},{dx:1,dy:0},{dx:0,dy:-1},{dx:-1,dy:0}].filter(a=>a.dx===o.dx*-1&&a.dy===o.dy*-1?!1:!(a.dx===o.dx&&a.dy===o.dy&&t.parent?.obstacleHit)).map(a=>n.getOrthoDirectionCollisionInfo(t,a,{margin:this.OBSTACLE_MARGIN})).filter(a=>a.wallDistance>=this.OBSTACLE_MARGIN),s=[];for(let a of r){let c=null;t?.obstacleHit&&(c=TI({node:t,travelDir:a,wallDir:{...o,wallDistance:this.OBSTACLE_MARGIN},obstacle:t.obstacleHit,obstacles:n,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let l=UF(t,i,a),u=(a.dx===0||Math.sign(i.x-t.x)===a.dx)&&(a.dy===0||Math.sign(i.y-t.y)===a.dy);l<a.wallDistance&&l>0&&u?s.push({...a,travelDistance:l}):c!==null&&c<a.wallDistance?s.push({...a,travelDistance:c}):a.wallDistance!==1/0&&s.push({...a,travelDistance:a.wallDistance-this.OBSTACLE_MARGIN})}return s.filter(a=>!n.isObstacleAt(t.x+a.dx*a.travelDistance,t.y+a.dy*a.travelDistance)).map(a=>({x:t.x+a.dx*a.travelDistance,y:t.y+a.dy*a.travelDistance,obstacleHit:a.obstacle}))}};function e_t(e,t=4){let{center:n,width:i,height:o,rotation:r}=e,s=[],a=r*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(r%360+360)%360;if(o<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*c,x=-y*l,w=d*1.1,S=Math.abs(o*c)+Math.abs(d*l);s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}else{let d=o/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*l,x=y*c,w=Math.abs(i*c)+Math.abs(d*l),S=d*1.1;s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}return s}var Gg=["top","inner1","inner2","bottom"],ez=(e,t)=>{let n=o=>t?o.concat(o.map(r=>t?.getNetConnectedToId(r)).filter(Boolean)):o,i=[];for(let o of e)if(o.type==="pcb_smtpad"){if(o.shape==="circle")i.push({type:"oval",layers:[o.layer],center:{x:o.x,y:o.y},width:o.radius*2,height:o.radius*2,connectedTo:n([o.pcb_smtpad_id])});else if(o.shape==="rect")i.push({type:"rect",layers:[o.layer],center:{x:o.x,y:o.y},width:o.width,height:o.height,connectedTo:n([o.pcb_smtpad_id])});else if(o.shape==="rotated_rect"){let r={center:{x:o.x,y:o.y},width:o.width,height:o.height,rotation:o.ccw_rotation},s=e_t(r);for(let a of s)i.push({type:"rect",layers:[o.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([o.pcb_smtpad_id])})}}else if(o.type==="pcb_keepout")o.shape==="circle"?i.push({type:"oval",layers:o.layers,center:{x:o.center.x,y:o.center.y},width:o.radius*2,height:o.radius*2,connectedTo:[]}):o.shape==="rect"&&i.push({type:"rect",layers:o.layers,center:{x:o.center.x,y:o.center.y},width:o.width,height:o.height,connectedTo:[]});else if(o.type==="pcb_hole")o.hole_shape==="oval"?i.push({type:"oval",center:{x:o.x,y:o.y},width:o.hole_width,height:o.hole_height,connectedTo:[]}):o.hole_shape==="square"?i.push({type:"rect",layers:Gg,center:{x:o.x,y:o.y},width:o.hole_diameter,height:o.hole_diameter,connectedTo:[]}):(o.hole_shape==="round"||o.hole_shape==="circle")&&i.push({type:"rect",layers:Gg,center:{x:o.x,y:o.y},width:o.hole_diameter,height:o.hole_diameter,connectedTo:[]});else if(o.type==="pcb_plated_hole")o.shape==="circle"?i.push({type:"oval",layers:Gg,center:{x:o.x,y:o.y},width:o.outer_diameter,height:o.outer_diameter,connectedTo:n([o.pcb_plated_hole_id])}):(o.shape==="oval"||o.shape==="pill")&&i.push({type:"oval",layers:Gg,center:{x:o.x,y:o.y},width:o.outer_width,height:o.outer_height,connectedTo:n([o.pcb_plated_hole_id])});else if(o.type==="pcb_trace"){let r=ZF(o.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),o.source_trace_id);i.push(...r)}else o.type==="pcb_via"&&i.push({type:"rect",layers:o.layers,center:{x:o.x,y:o.y},connectedTo:[],width:o.outer_diameter,height:o.outer_diameter});return i};function HF(e){let{pcbConnMap:t,goalElementId:n}=e;if(!n.startsWith("pcb_port_"))throw new Error(`Currently alternative goal boxes must have a goal id with prefix "pcb_port_" (got ${n})`);let i=t.getAllTracesConnectedToPort(n);return ez(i).map(o=>({...o,connectedTo:[n]}))}var nz=e=>{let{connection:t,pcbConnMap:n}=e;if(t.pointsToConnect.length!==2)throw new Error(`Connection must have exactly 2 points for alternative goal boxes (got ${t.pointsToConnect.length})`);let[i,o]=t.pointsToConnect;if(!i.pcb_port_id||!o.pcb_port_id)throw new Error(`Connection points must have pcb_port_id for alternative goal box calculation (got ${i.pcb_port_id} and ${o.pcb_port_id})`);let r=HF({goalElementId:i.pcb_port_id,pcbConnMap:n}).concat([{center:i,width:.01,height:.01,connectedTo:[i.pcb_port_id],layers:[i.layer],type:"rect"}]),s=HF({goalElementId:o.pcb_port_id,pcbConnMap:n}).concat([{center:o,width:.01,height:.01,connectedTo:[o.pcb_port_id],layers:[o.layer],type:"rect"}]);if(r.length<=1&&s.length<=1)return{...t,startPoint:i,endPoint:o,goalBoxes:[]};let a=gf(r,s),c,l,u;return r.length>=s.length?(c={...o,...a.pointB},l={...i,...a.pointA},u=r):(c={...i,...a.pointA},l={...o,...a.pointB},u=s),{startPoint:c,endPoint:l,goalBoxes:u,name:t.name,pointsToConnect:[c,l]}},n_t=(e,t={})=>{let n={minTraceWidth:.1};n.layerCount=t.layerCount??1,n.obstacles=ez(e,t.connMap),n.connections=[];for(let o of e)if(o.type==="source_trace"){let r={name:o.source_trace_id,pointsToConnect:o.connected_source_port_ids.map(s=>{let a=Rr(e).pcb_port.getWhere({source_port_id:s});if(!a)throw new Error(`Could not find pcb_port for source_port_id "${s}"`);return{x:a.x,y:a.y,layer:a.layers?.[0]??"top",pcb_port_id:a.pcb_port_id}})};if(t.optimizeWithGoalBoxes){let s=new Hg(e);r=nz({connection:r,pcbConnMap:s})}n.connections.push(r),i_t(n.obstacles,r.pointsToConnect,r.name)}let i={minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0};for(let o of n.obstacles)i.minX=Math.min(i.minX,o.center.x-o.width/2),i.maxX=Math.max(i.maxX,o.center.x+o.width/2),i.minY=Math.min(i.minY,o.center.y-o.height/2),i.maxY=Math.max(i.maxY,o.center.y+o.height/2);for(let o of n.connections)for(let r of o.pointsToConnect)i.minX=Math.min(i.minX,r.x),i.maxX=Math.max(i.maxX,r.x),i.minY=Math.min(i.minY,r.y),i.maxY=Math.max(i.maxY,r.y);return n.bounds=i,n},i_t=(e,t,n)=>{for(let i of t)for(let o of e)o_t(i,o)&&o.connectedTo.push(n)};function o_t(e,t){let n=t.width/2,i=t.height/2;if(t.type==="rect")return e.x>=t.center.x-n&&e.x<=t.center.x+n&&e.y>=t.center.y-i&&e.y<=t.center.y+i;if(t.type==="oval"){let o=(e.x-t.center.x)/n,r=(e.y-t.center.y)/i;return o*o+r*r<=1}return!1}function GF(e,t){let n=t.x>e.x?1:t.x<e.x?-1:0,i=t.y>e.y?1:t.y<e.y?-1:0,o=t.l>e.l?1:t.l<e.l?-1:0;return{dx:n,dy:i,dl:o}}var MI={1:["top"],2:["top","bottom"],4:["top","inner1","inner2","bottom"]},r_t=e=>MI[e];function iz(e,t){let i=MI[e].indexOf(t);if(i===-1)throw new Error(`Invalid layer for getLayerIndex (for layerCount === ${e}): "${t}"`);return i}function s_t(e,t){let i=MI[e][t];if(!i)throw new Error(`Invalid index for indexToLayer (for layerCount === ${e}): "${t}"`);return i}var a_t=class extends KF{constructor(t,n){super([]);P(this,"obstacles");P(this,"GRID_STEP",.1);P(this,"layerCount");this.layerCount=t;let i=r_t(t);this.obstacles=n.flatMap(o=>o.layers.filter(r=>i.includes(r)).map(r=>({...o,left:o.center.x-o.width/2,right:o.center.x+o.width/2,top:o.center.y+o.height/2,bottom:o.center.y-o.height/2,l:iz(t,r)})))}getObstacleAt(t,n,i,o){o??(o=this.GRID_STEP);for(let r of this.obstacles){if(r.l!==i)continue;let s=r.width/2+o,a=r.height/2+o;if(t>=r.center.x-s&&t<=r.center.x+s&&n>=r.center.y-a&&n<=r.center.y+a)return r}return null}isObstacleAt(t,n,i,o){return this.getObstacleAt(t,n,i,o)!==null}getDirectionDistancesToNearestObstacle3d(t,n,i){let{GRID_STEP:o}=this,r={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let s of this.obstacles)if(s.l===i&&s.type==="rect"){let a=s.center.x-s.width/2-o,c=s.center.x+s.width/2+o,l=s.center.y+s.height/2+o,u=s.center.y-s.height/2-o;n>=u&&n<=l&&t>a&&(r.left=Math.min(r.left,t-c)),n>=u&&n<=l&&t<c&&(r.right=Math.min(r.right,a-t)),t>=a&&t<=c&&n<l&&(r.top=Math.min(r.top,u-n)),t>=a&&t<=c&&n>u&&(r.bottom=Math.min(r.bottom,n-l))}return r}getOrthoDirectionCollisionInfo(t,n,{margin:i=0}={}){let{x:o,y:r,l:s}=t,{dx:a,dy:c,dl:l}=n,u=1/0,h=null;if(l!==0){let d=s+l;return this.isObstacleAt(o,r,d,i)?(u=1,h=this.getObstacleAt(o,r,d,i)):u=1,{dx:a,dy:c,dl:l,wallDistance:u,obstacle:h}}else{for(let d of this.obstacles){if(d.l!==s)continue;let _=d.left-i,y=d.right+i,g=d.top+i,x=d.bottom-i,w=null;a===1&&c===0?r>x&&r<g&&o<d.left&&(w=d.left-o):a===-1&&c===0?r>x&&r<g&&o>d.right&&(w=o-d.right):a===0&&c===1?o>_&&o<y&&r<d.bottom&&(w=d.bottom-r):a===0&&c===-1&&o>_&&o<y&&r>d.top&&(w=r-d.top),w!==null&&w<u&&(u=w,h=d)}return{dx:a,dy:c,dl:0,wallDistance:u,obstacle:h}}}getObstaclesOverlappingRegion(t){let n=[];for(let i of this.obstacles){if(i.l!==t.l)continue;let{left:o,right:r,top:s,bottom:a}=i;o<=t.maxX&&r>=t.minX&&s>=t.minY&&a<=t.maxY&&n.push(i)}return n}},Ug=class extends QF{constructor(t){super(t);P(this,"MAX_ITERATIONS",500);P(this,"VIA_COST",4);P(this,"VIA_DIAMETER",.5);P(this,"allowLayerChange",!0);P(this,"layerCount");P(this,"obstacles");P(this,"optimizeWithGoalBoxes");P(this,"connMap");P(this,"pcbConnMap");P(this,"GOAL_RUSH_FACTOR",1.1);P(this,"defaultGoalViaMargin",.5);P(this,"marginsWithCosts");this.layerCount=t.input.layerCount??2,this.MAX_ITERATIONS=t.MAX_ITERATIONS??this.MAX_ITERATIONS,this.VIA_COST=t.VIA_COST??this.VIA_COST,this.connMap=t.connMap,this.pcbConnMap=t.pcbConnMap??new Hg,this.optimizeWithGoalBoxes=t.optimizeWithGoalBoxes??!1,this.obstacles=null,this.marginsWithCosts=t.marginsWithCosts??[{margin:1,enterCost:0,travelCostFactor:1},{margin:this.OBSTACLE_MARGIN,enterCost:10,travelCostFactor:2}]}get largestMargin(){return this.marginsWithCosts[0].margin}preprocessConnectionBeforeSolving(t){return this.optimizeWithGoalBoxes?nz({connection:t,pcbConnMap:this.pcbConnMap}):t}postprocessConnectionSolveResult(t,n){if(!n.solved)return n;if(this.optimizeWithGoalBoxes){let i=n.route.map(o=>({x:o.x,y:o.y,route_type:"wire",layer:o.layer,width:this.input.minTraceWidth}));i[0].start_pcb_port_id=t.pointsToConnect[0].pcb_port_id,i[i.length-1].end_pcb_port_id=t.pointsToConnect[1].pcb_port_id,this.pcbConnMap.addTrace({type:"pcb_trace",pcb_trace_id:`postprocess_trace_${BF(8)}`,route:i})}return n}createObstacleList({dominantLayer:t,connection:n,obstaclesFromTraces:i}){let o=this.connMap?this.connMap.getNetConnectedToId(n.name):n.name;if(!o)throw new Error(`The connection.name "${n.name}" wasn't present in the full connectivity map`);return new a_t(this.layerCount,this.allObstacles.filter(r=>!r.connectedTo.includes(o)).concat(i??[]))}computeG(t,n){let i=t.g+$l(t,n)*(t.travelMarginCostFactor??1)+(n.enterMarginCost??0);return(n.l??t.l!==-1??-1)&&(i+=this.VIA_COST),i}computeH(t){let n=Math.abs(t.x-this.goalPoint.x),i=Math.abs(t.y-this.goalPoint.y),o=Math.abs(t.l-this.goalPoint.l);return(n+i)**this.GOAL_RUSH_FACTOR+o*this.VIA_COST}getStartNode(t){return{...super.getStartNode(t),l:this.layerToIndex(t.pointsToConnect[0].layer)}}layerToIndex(t){return iz(this.layerCount,t)}indexToLayer(t){return s_t(this.layerCount,t)}getNodeName(t){return`${qF(t,this.GRID_STEP)}-${t.l??0}`}hasSpaceForVia(t,n){return t.every(i=>this.obstacles.getObstaclesOverlappingRegion({minX:n.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:n.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:n.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:n.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:i}).length===0)}getNeighborsSurroundingGoal(t){let n=this.obstacles,i=this.goalPoint,o=[],r=[{dx:1,dy:0,dl:0},{dx:-1,dy:0,dl:0},{dx:0,dy:1,dl:0},{dx:0,dy:-1,dl:0}],s=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin;for(let a of r){let c={x:t.x+a.dx*s,y:t.y+a.dy*s,l:t.l+a.dl,obstacleHit:null};this.hasSpaceForVia([t.l,i.l],c)&&o.push(c)}return o}getNeighbors(t){let n=this.obstacles,i=this.goalPoint,o=$l(t,i);if(o<=this.OBSTACLE_MARGIN)return this.getNeighborsSurroundingGoal(t);let r;t.parent?r=GF(t.parent,t):r=GF(t,i);let s=[{dx:0,dy:1,dl:0},{dx:1,dy:0,dl:0},{dx:0,dy:-1,dl:0},{dx:-1,dy:0,dl:0}],a=o>this.VIA_DIAMETER+this.OBSTACLE_MARGIN,c=$l(t,this.startNode)>this.VIA_DIAMETER+this.OBSTACLE_MARGIN;this.allowLayerChange&&a&&c&&(t.l<this.layerCount-1&&s.push({dx:0,dy:0,dl:1}),t.l>0&&s.push({dx:0,dy:0,dl:-1}));let l=s.filter(h=>h.dx===r.dx*-1&&h.dy===r.dy*-1&&h.dl===r.dl*-1?!1:!(h.dx===r.dx&&h.dy===r.dy&&h.dl===r.dl&&t.parent?.obstacleHit)).map(h=>n.getOrthoDirectionCollisionInfo(t,h,{margin:this.OBSTACLE_MARGIN})).filter(h=>!(h.wallDistance<this.OBSTACLE_MARGIN)),u=[];for(let h of l){let d=h.dx===0&&h.dy===0&&h.dl===1,_=h.dx===0&&h.dy===0&&h.dl===-1;if((d||_)&&![t.l,t.l+h.dl].every(S=>n.getObstaclesOverlappingRegion({minX:t.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:t.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:t.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:t.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:S}).length===0))continue;if(d){t.l<this.layerCount-1&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}if(_){t.l>0&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}let y=null;t?.obstacleHit&&(y=TI({node:t,travelDir:h,wallDir:{...r,wallDistance:this.OBSTACLE_MARGIN},obstacle:t.obstacleHit,obstacles:n,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let g=UF(t,i,h),x=(h.dx===0||Math.sign(i.x-t.x)===h.dx)&&(h.dy===0||Math.sign(i.y-t.y)===h.dy);if(g<h.wallDistance&&g>0&&x){let w=t.l===i.l,S=0;!w&&Math.abs(g-o)<this.GRID_STEP&&(S=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin),u.push({...h,travelDistance:g-S,enterMarginCost:0,travelMarginCostFactor:1})}else if(y!==null&&y<h.wallDistance){for(let{margin:w,enterCost:S,travelCostFactor:T}of this.marginsWithCosts)y-this.OBSTACLE_MARGIN+w*2<h.wallDistance&&u.push({...h,travelDistance:y-this.OBSTACLE_MARGIN+w,enterMarginCost:S,travelMarginCostFactor:T});if(h.wallDistance===1/0)u.push({...h,travelDistance:g,enterMarginCost:0,travelMarginCostFactor:1});else if(h.wallDistance>this.largestMargin)for(let{margin:w,enterCost:S,travelCostFactor:T}of this.marginsWithCosts)h.wallDistance>this.largestMargin+w&&u.push({...h,travelDistance:h.wallDistance-w,enterMarginCost:S,travelMarginCostFactor:T})}else if(h.wallDistance!==1/0)for(let{margin:w,enterCost:S,travelCostFactor:T}of this.marginsWithCosts)h.wallDistance>w&&u.push({...h,travelDistance:h.wallDistance-w,enterMarginCost:S,travelMarginCostFactor:T})}return u.map(h=>({x:t.x+h.dx*h.travelDistance,y:t.y+h.dy*h.travelDistance,l:t.l+h.dl,obstacleHit:h.obstacle,travelMarginCostFactor:h.travelMarginCostFactor,enterMarginCost:h.enterMarginCost}))}};function oz(e){let t=n_t(e),n=new t_t({input:t});return{solution:n.solveAndMapToTraces(),debugSolutions:n.debugSolutions,debugMessage:n.debugMessage}}K();K();vt();K();K();vt();vt();K();K();vt();K();K();K();K();vt();K();K();K();vt();K();K();vt();K();K();K();K();K();K();K();K();K();K();vt();K();vt();K();vt();K();K();vt();vt();K();vt();K();K();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();K();K();K();K();K();K();vt();K();vt();K();K();vt();K();vt();K();K();K();vt();K();vt();vt();K();K();K();vt();K();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();vt();K();vt();K();vt();K();K();vt();vt();K();K();vt();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();vt();K();vt();K();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();var Ct=e=>{};Ct("extra props b");Ct("missing props b");Ct(!0);Ct("property a has mismatched types");var c_t=p.enum(["up","down","left","right"]),U$t=p.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);Ct(!0);Ct(!0);var es=p.array(p.string().or(p.number()));Ct(!0);var Zg=p.object({x:Y,y:Y,z:Y}),l_t=p.object({x:p.union([p.number(),p.string()]),y:p.union([p.number(),p.string()]),z:p.union([p.number(),p.string()])}),Qa=p.object({rotationOffset:p.number().or(l_t).optional(),positionOffset:Zg.optional(),size:Zg.optional(),modelUnitToMmScale:Y.optional(),zOffsetFromSurface:Y.optional()});Ct(!0);var u_t=Qa.extend({stlUrl:p.string()}),p_t=Qa.extend({objUrl:p.string(),mtlUrl:p.string().optional()}),h_t=Qa.extend({gltfUrl:p.string()}),d_t=Qa.extend({glbUrl:p.string()}),f_t=Qa.extend({stepUrl:p.string()}),m_t=Qa.extend({wrlUrl:p.string()}),__t=Qa.extend({jscad:p.record(p.any())}),hz=p.union([p.null(),p.string(),p.custom(e=>e&&typeof e=="object"&&"type"in e&&"props"in e),u_t,p_t,h_t,d_t,f_t,m_t,__t]);Ct(!0);var y_t=p.custom(e=>!0),NI=p.object({silkscreenFontSize:Y.optional(),silkscreenTextPosition:p.union([p.enum(["centered","outside","none"]),p.object({offsetX:p.number(),offsetY:p.number()})]).optional(),silkscreenTextVisibility:p.enum(["hidden","visible","inherit"]).optional()});Ct(!0);var g_t=p.custom(e=>!0),Oe=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbRotation:Be.optional(),pcbPositionAnchor:p.string().optional(),pcbPositionMode:p.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),layer:se.optional(),pcbMarginTop:Y.optional(),pcbMarginRight:Y.optional(),pcbMarginBottom:Y.optional(),pcbMarginLeft:Y.optional(),pcbMarginX:Y.optional(),pcbMarginY:Y.optional(),pcbStyle:NI.optional(),pcbRelative:p.boolean().optional(),relative:p.boolean().optional()});Ct(!0);var Kg=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbRotation:Be.optional(),pcbPositionAnchor:p.string().optional(),pcbPositionMode:p.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),pcbMarginTop:Y.optional(),pcbMarginRight:Y.optional(),pcbMarginBottom:Y.optional(),pcbMarginLeft:Y.optional(),pcbMarginX:Y.optional(),pcbMarginY:Y.optional(),pcbStyle:NI.optional(),schMarginTop:Y.optional(),schMarginRight:Y.optional(),schMarginBottom:Y.optional(),schMarginLeft:Y.optional(),schMarginX:Y.optional(),schMarginY:Y.optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Be.optional(),layer:se.optional(),footprint:y_t.optional(),symbol:g_t.optional(),relative:p.boolean().optional(),schRelative:p.boolean().optional(),pcbRelative:p.boolean().optional()});Ct(!0);var b_t=p.object({supplierPartNumbers:p.record(Mp,p.array(p.string())).optional()});Ct(!0);var x_t=p.object({providesPower:p.boolean().optional(),requiresPower:p.boolean().optional(),providesGround:p.boolean().optional(),requiresGround:p.boolean().optional(),providesVoltage:p.union([p.string(),p.number()]).optional(),requiresVoltage:p.union([p.string(),p.number()]).optional(),doNotConnect:p.boolean().optional(),includeInBoardPinout:p.boolean().optional(),highlightColor:p.string().optional()});Ct(!0);var Dn=Kg.merge(b_t).extend({key:p.any().optional(),name:p.string(),cadModel:hz.optional(),children:p.any().optional(),symbolName:p.string().optional(),doNotPlace:p.boolean().optional(),obstructsWithinBounds:p.boolean().optional().describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath"),pinAttributes:p.record(p.string(),x_t).optional()});Ct(!0);var kI=["pin1","left","pin2","right"],Jg=["pin1","left","anode","pos","pin2","right","cathode","neg"],sjt=Y.or(p.enum(["2x","3x","4x"])),tc=p.enum(["vertical","horizontal","pos_top","pos_bottom","pos_left","pos_right","neg_top","neg_bottom","neg_left","neg_right"]).describe("horizontal means pins go 1->2 rightward and vertical means pins go 1->2 downward (generally, positive on top)");Ct(!0);var qg=p.object({pins:p.array(p.union([p.number(),p.string()])),direction:p.union([p.literal("top-to-bottom"),p.literal("left-to-right"),p.literal("bottom-to-top"),p.literal("right-to-left")])}),xf=p.object({leftSize:p.number().optional().describe("@deprecated, use leftPinCount"),topSize:p.number().optional().describe("@deprecated, use topPinCount"),rightSize:p.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:p.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftSide:qg.optional(),rightSide:qg.optional(),topSide:qg.optional(),bottomSide:qg.optional()}),AI=xf;Ct(!0);var vf=p.record(p.object({marginLeft:Y.optional(),marginRight:Y.optional(),marginTop:Y.optional(),marginBottom:Y.optional(),leftMargin:Y.optional(),rightMargin:Y.optional(),topMargin:Y.optional(),bottomMargin:Y.optional()}));Ct(!0);var ur=p.string().regex(/^[A-Za-z0-9_]+$/),Zp=p.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),Gs=p.object({x:Y,y:Y}),Sf=p.object({edit_event_id:p.string(),in_progress:p.boolean().optional(),created_at:p.number()});Ct(!0);var v_t=Sf.extend({pcb_edit_event_type:p.literal("edit_component_location").describe("deprecated"),edit_event_type:p.literal("edit_pcb_component_location"),pcb_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var S_t=Sf.extend({pcb_edit_event_type:p.literal("edit_trace_hint").describe("deprecated"),edit_event_type:p.literal("edit_pcb_trace_hint").optional(),pcb_port_id:p.string(),pcb_trace_hint_id:p.string().optional(),route:p.array(p.object({x:p.number(),y:p.number(),via:p.boolean().optional()}))});Ct(!0);var w_t=Sf.extend({edit_event_type:p.literal("edit_schematic_component_location"),schematic_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var wjt=Sf.extend({edit_event_type:p.literal("edit_pcb_group_location"),pcb_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var Ijt=Sf.extend({edit_event_type:p.literal("edit_schematic_group_location"),schematic_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var Mjt=p.union([v_t,S_t,w_t]);Ct(!0);var P_t=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:qt});Ct(!0);var I_t=p.object({pcb_port_selector:p.string(),offsets:p.array(Fi)});Ct(!0);var T_t=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:qt});Ct(!0);var M_t=p.object({pcb_placements:p.array(P_t).optional(),manual_trace_hints:p.array(I_t).optional(),schematic_placements:p.array(T_t).optional()});Ct(!0);var Kp=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),jl=e=>p.record(p.enum(e),Kp),bf=p.object({layoutMode:p.enum(["grid","flex","match-adapt","relative","none"]).optional(),position:p.enum(["absolute","relative"]).optional(),grid:p.boolean().optional(),gridCols:p.number().or(p.string()).optional(),gridRows:p.number().or(p.string()).optional(),gridTemplateRows:p.string().optional(),gridTemplateColumns:p.string().optional(),gridTemplate:p.string().optional(),gridGap:p.number().or(p.string()).optional(),gridRowGap:p.number().or(p.string()).optional(),gridColumnGap:p.number().or(p.string()).optional(),flex:p.boolean().or(p.string()).optional(),flexDirection:p.enum(["row","column"]).optional(),alignItems:p.enum(["start","center","end","stretch"]).optional(),justifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),flexRow:p.boolean().optional(),flexColumn:p.boolean().optional(),gap:p.number().or(p.string()).optional(),pack:p.boolean().optional().describe("Pack the contents of this group using a packing strategy"),packOrderStrategy:p.enum(["largest_to_smallest","first_to_last","highest_to_lowest_pin_count"]).optional(),packPlacementStrategy:p.enum(["shortest_connection_along_outline"]).optional(),padding:D.optional(),paddingLeft:D.optional(),paddingRight:D.optional(),paddingTop:D.optional(),paddingBottom:D.optional(),paddingX:D.optional(),paddingY:D.optional(),width:D.optional(),height:D.optional(),matchAdapt:p.boolean().optional(),matchAdaptTemplate:p.any().optional()});Ct(!0);var rz=p.object({strokeWidth:D.optional(),dashed:p.boolean().optional(),solid:p.boolean().optional()}),C_t=p.custom(e=>typeof e=="string"),E_t=p.object({serverUrl:p.string().optional(),inputFormat:p.enum(["simplified","circuit-json"]).optional(),serverMode:p.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:p.boolean().optional(),cache:p.custom(e=>!0).optional(),traceClearance:D.optional(),groupMode:p.enum(["sequential_trace","subcircuit","sequential-trace"]).optional(),algorithmFn:p.custom(e=>typeof e=="function"||e===void 0).optional(),preset:p.enum(["sequential_trace","subcircuit","auto","auto_local","auto_cloud","freerouting","laser_prefab","sequential-trace","auto-local","auto-cloud"]).optional(),local:p.boolean().optional()}),N_t=p.union([p.literal("sequential_trace"),p.literal("subcircuit"),p.literal("auto"),p.literal("auto_local"),p.literal("auto_cloud"),p.literal("freerouting"),p.literal("laser_prefab"),p.literal("sequential-trace"),p.literal("auto-local"),p.literal("auto-cloud")]),k_t=p.string(),dz=p.union([E_t,N_t,k_t]),RI=Kg.extend({name:p.string().optional(),children:p.any().optional(),schTitle:p.string().optional(),key:p.any().optional(),showAsSchematicBox:p.boolean().optional(),connections:p.record(p.string(),Kp.optional()).optional(),schPinArrangement:AI.optional(),schPinSpacing:D.optional(),schPinStyle:vf.optional(),...bf.shape,grid:bf.shape.grid.describe("@deprecated use pcbGrid"),flex:bf.shape.flex.describe("@deprecated use pcbFlex"),pcbGrid:p.boolean().optional(),pcbGridCols:p.number().or(p.string()).optional(),pcbGridRows:p.number().or(p.string()).optional(),pcbGridTemplateRows:p.string().optional(),pcbGridTemplateColumns:p.string().optional(),pcbGridTemplate:p.string().optional(),pcbGridGap:p.number().or(p.string()).optional(),pcbGridRowGap:p.number().or(p.string()).optional(),pcbGridColumnGap:p.number().or(p.string()).optional(),pcbFlex:p.boolean().or(p.string()).optional(),pcbFlexGap:p.number().or(p.string()).optional(),pcbFlexDirection:p.enum(["row","column"]).optional(),pcbAlignItems:p.enum(["start","center","end","stretch"]).optional(),pcbJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),pcbFlexRow:p.boolean().optional(),pcbFlexColumn:p.boolean().optional(),pcbGap:p.number().or(p.string()).optional(),pcbPack:p.boolean().optional(),pcbPackGap:p.number().or(p.string()).optional(),schGrid:p.boolean().optional(),schGridCols:p.number().or(p.string()).optional(),schGridRows:p.number().or(p.string()).optional(),schGridTemplateRows:p.string().optional(),schGridTemplateColumns:p.string().optional(),schGridTemplate:p.string().optional(),schGridGap:p.number().or(p.string()).optional(),schGridRowGap:p.number().or(p.string()).optional(),schGridColumnGap:p.number().or(p.string()).optional(),schFlex:p.boolean().or(p.string()).optional(),schFlexGap:p.number().or(p.string()).optional(),schFlexDirection:p.enum(["row","column"]).optional(),schAlignItems:p.enum(["start","center","end","stretch"]).optional(),schJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),schFlexRow:p.boolean().optional(),schFlexColumn:p.boolean().optional(),schGap:p.number().or(p.string()).optional(),schPack:p.boolean().optional(),schMatchAdapt:p.boolean().optional(),pcbWidth:D.optional(),pcbHeight:D.optional(),minTraceWidth:D.optional(),schWidth:D.optional(),schHeight:D.optional(),pcbLayout:bf.optional(),schLayout:bf.optional(),cellBorder:rz.nullable().optional(),border:rz.nullable().optional(),schPadding:D.optional(),schPaddingLeft:D.optional(),schPaddingRight:D.optional(),schPaddingTop:D.optional(),schPaddingBottom:D.optional(),pcbPadding:D.optional(),pcbPaddingLeft:D.optional(),pcbPaddingRight:D.optional(),pcbPaddingTop:D.optional(),pcbPaddingBottom:D.optional(),pcbPositionAnchor:C_t.optional()}),fz=p.custom(e=>"findPart"in e),OI=RI.extend({manualEdits:M_t.optional(),schAutoLayoutEnabled:p.boolean().optional(),schTraceAutoLabelEnabled:p.boolean().optional(),schMaxTraceDistance:Y.optional(),routingDisabled:p.boolean().optional(),defaultTraceWidth:D.optional(),minTraceWidth:D.optional(),partsEngine:fz.optional(),pcbRouteCache:p.custom(e=>!0).optional(),autorouter:dz.optional(),square:p.boolean().optional(),emptyArea:p.string().optional(),filledArea:p.string().optional(),width:Y.optional(),height:Y.optional(),outline:p.array(Gs).optional(),outlineOffsetX:Y.optional(),outlineOffsetY:Y.optional(),circuitJson:p.array(p.any()).optional()}),A_t=OI.extend({subcircuit:p.literal(!0)}),mz=p.discriminatedUnion("subcircuit",[RI.extend({subcircuit:p.literal(!1).optional()}),A_t]);Ct(!0);Ct(!0);Ct(!0);Ct(!0);var Wp=p.custom(e=>typeof e=="string"),LI=OI.omit({connections:!0}).extend({material:p.enum(["fr4","fr1"]).default("fr4"),layers:p.union([p.literal(2),p.literal(4)]).default(2),borderRadius:Y.optional(),thickness:Y.optional(),boardAnchorPosition:Gs.optional(),boardAnchorAlignment:Zp.optional(),title:p.string().optional(),solderMaskColor:Wp.optional(),topSolderMaskColor:Wp.optional(),bottomSolderMaskColor:Wp.optional(),silkscreenColor:Wp.optional(),topSilkscreenColor:Wp.optional(),bottomSilkscreenColor:Wp.optional(),doubleSidedAssembly:p.boolean().optional().default(!1),schematicDisabled:p.boolean().optional()});Ct(!0);var _z=RI.omit({width:!0,height:!0,children:!0}).extend({width:Y,height:Y,children:p.any().optional(),noSolderMask:p.boolean().optional()});Ct(!0);var Djt=OI.extend({padding:Y.optional(),paddingLeft:Y.optional(),paddingRight:Y.optional(),paddingTop:Y.optional(),paddingBottom:Y.optional()});Ct(!0);var R_t=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),O_t=p.custom().pipe(p.record(p.string(),R_t)),L_t=p.record(ur,ur.or(p.array(ur).readonly()).or(p.array(ur)));Ct(!0);var F_t=p.object({manufacturerPartNumber:p.string().optional(),supplierPartNumber:p.record(Mp,p.array(p.string())).optional()}),Jp=Dn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:L_t.optional(),showPinAliases:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),externallyConnectedPins:p.array(p.array(p.string())).optional(),schPinArrangement:xf.optional(),schPortArrangement:xf.optional(),pinCompatibleVariants:p.array(F_t).optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),noSchematicRepresentation:p.boolean().optional(),connections:O_t.optional()});Ct(!0);var yz=Jp;Ct(!0);var FI=Dn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(ur),ur.or(p.array(ur))).optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),schDirection:p.enum(["left","right"]).optional(),schPinArrangement:AI.optional(),schPortArrangement:xf.optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),pinCount:p.union([p.literal(2),p.literal(3)]).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),connections:p.custom().pipe(p.record(p.string(),Kp)).optional()});Ct(!0);var gz=FI.extend({bridgedPins:p.array(p.array(p.string())).optional(),bridged:p.boolean().optional()});Ct(!0);var Gjt=Dn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(ur),ur.or(p.array(ur))).optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),schDirection:p.enum(["left","right"]).optional(),schPortArrangement:xf.optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),standard:p.enum(["usb_c","m2"]).optional()});Ct(!0);var bz=Dn.extend({currentRating:p.union([p.number(),p.string()]),voltageRating:p.union([p.number(),p.string()]).optional(),schShowRatings:p.boolean().optional(),schOrientation:tc.optional(),connections:p.record(p.string(),p.union([p.string(),p.array(p.string()).readonly(),p.array(p.string())])).optional()}),Wg=p.custom().transform(e=>{if(e!==void 0)return Y.parse(e)}),xz=p.discriminatedUnion("shape",[Oe.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circle"),holeDiameter:Y,outerDiameter:Y,portHints:es.optional()}),Oe.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("oval"),outerWidth:Y,outerHeight:Y,holeWidth:Wg,holeHeight:Wg,innerWidth:Y.optional().describe("DEPRECATED use holeWidth"),innerHeight:Y.optional().describe("DEPRECATED use holeHeight"),portHints:es.optional()}),Oe.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill"),rectPad:p.boolean().optional(),outerWidth:Y,outerHeight:Y,holeWidth:Wg,holeHeight:Wg,innerWidth:Y.optional().describe("DEPRECATED use holeWidth"),innerHeight:Y.optional().describe("DEPRECATED use holeHeight"),portHints:es.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional()}),Oe.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circular_hole_with_rect_pad"),holeDiameter:Y,rectPadWidth:Y,rectPadHeight:Y,rectBorderRadius:Y.optional(),holeShape:p.literal("circle").optional(),padShape:p.literal("rect").optional(),portHints:es.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional()}),Oe.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill_hole_with_rect_pad"),holeShape:p.literal("pill"),padShape:p.literal("rect"),holeWidth:Y,holeHeight:Y,rectPadWidth:Y,rectPadHeight:Y,portHints:es.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional()})]).refine(e=>("innerWidth"in e&&e.innerWidth!==void 0&&(e.holeWidth??(e.holeWidth=e.innerWidth)),"innerHeight"in e&&e.innerHeight!==void 0&&(e.holeHeight??(e.holeHeight=e.innerHeight)),e));Ct(!0);var z_t=["pin1","pin2","pos","neg"],vz=Dn.extend({resistance:Ha,pullupFor:p.string().optional(),pullupTo:p.string().optional(),pulldownFor:p.string().optional(),pulldownTo:p.string().optional(),schOrientation:tc.optional(),connections:jl(z_t).optional()}),Sz=kI;Ct(!0);var wz=Dn.extend({maxResistance:Ha,pinVariant:p.enum(["two_pin","three_pin"]).optional()});Ct(!0);var D_t=kI,Pz=Dn.extend({frequency:Wi,loadCapacitance:zs,manufacturerPartNumber:p.string().optional(),mpn:p.string().optional(),pinVariant:p.enum(["two_pin","four_pin"]).optional(),schOrientation:tc.optional(),connections:jl(D_t).optional()});Ct(!0);var Iz=Dn.extend({frequency:Wi,loadCapacitance:zs,pinVariant:p.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});Ct(!0);var sBt=LI.extend({leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftPins:p.array(p.string()).optional(),rightPins:p.array(p.string()).optional(),topPins:p.array(p.string()).optional(),bottomPins:p.array(p.string()).optional(),pinPitch:Y.optional(),innerHoles:p.boolean().optional()});Ct(!0);var $_t=["pin1","pin2","pos","neg","anode","cathode"],Tz=Dn.extend({capacitance:zs,maxVoltageRating:ai.optional(),schShowRatings:p.boolean().optional().default(!1),polarized:p.boolean().optional().default(!1),decouplingFor:p.string().optional(),decouplingTo:p.string().optional(),bypassFor:p.string().optional(),bypassTo:p.string().optional(),maxDecouplingTraceLength:p.number().optional(),schOrientation:tc.optional(),connections:jl($_t).optional()}),Mz=Jg;Ct(!0);var uBt=p.object({name:p.string(),connectsTo:p.string().or(p.array(p.string())).optional(),highlightColor:p.string().optional(),isPowerNet:p.boolean().optional(),isGroundNet:p.boolean().optional()});Ct(!0);var hBt=p.object({name:p.string().optional(),pcbOnly:p.boolean().optional(),schOnly:p.boolean().optional()});Ct(!0);var j_t=p.object({pcb:p.literal(!0).optional(),xDist:Y,left:p.string(),right:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});Ct(!0);var B_t=p.object({pcb:p.literal(!0).optional(),yDist:Y,top:p.string(),bottom:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});Ct(!0);var Y_t=p.object({pcb:p.literal(!0).optional(),sameY:p.literal(!0).optional(),for:p.array(p.string())});Ct(!0);var X_t=p.object({pcb:p.literal(!0).optional(),sameX:p.literal(!0).optional(),for:p.array(p.string())});Ct(!0);var Cz=p.union([j_t,B_t,Y_t,X_t]);Ct(!0);var V_t=Oe.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y});Ct(!0);var H_t=Oe.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:Y});Ct(!0);var G_t=Oe.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Gs)});Ct(!0);var Ez=p.discriminatedUnion("shape",[V_t,H_t,G_t]),U_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y,rectBorderRadius:Y.optional(),cornerRadius:Y.optional(),portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var q_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rotated_rect"),width:Y,height:Y,ccwRotation:p.number(),cornerRadius:Y.optional(),portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var W_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:Y,portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var Z_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("pill"),width:Y,height:Y,radius:Y,portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var K_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Gs),portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var Nz=p.discriminatedUnion("shape",[W_t,U_t,q_t,Z_t,K_t]);Ct(!0);var J_t=Oe.omit({pcbRotation:!0}).extend({shape:p.literal("rect"),width:Y,height:Y});Ct(!0);var Q_t=Oe.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:Y});Ct(!0);var yBt=p.union([Q_t,J_t]);Ct(!0);var tyt=Oe.extend({name:p.string().optional(),shape:p.literal("circle").optional(),diameter:Y.optional(),radius:Y.optional()}).transform(e=>({...e,diameter:e.diameter??2*e.radius,radius:e.radius??e.diameter/2})),eyt=Oe.extend({name:p.string().optional(),shape:p.literal("pill"),width:Y,height:Y}),nyt=Oe.extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y}),kz=p.union([tyt,eyt,nyt]);Ct(!0);var CI=p.union([p.string(),p.custom(e=>!!e.getPortSelector)]),sz=p.object({key:p.string().optional(),thickness:Y.optional(),width:Y.optional().describe("Alias for trace thickness"),schematicRouteHints:p.array(Gs).optional(),pcbRouteHints:p.array(Fi).optional(),pcbPathRelativeTo:p.string().optional(),pcbPath:p.array(p.union([Gs,p.string()])).optional(),schDisplayLabel:p.string().optional(),schStroke:p.string().optional(),highlightColor:p.string().optional(),maxLength:Y.optional()}),Az=p.union([sz.extend({path:p.array(CI)}),sz.extend({from:CI,to:CI})]),Rz=p.object({originalLayer:se.default("top").optional()});Ct(!0);var Oz=p.object({originalFacingDirection:p.enum(["up","down","left","right"]).default("right").optional()});Ct(!0);var iyt=p.number().or(p.string().endsWith("mAh")).transform(e=>{if(typeof e=="string"){let t=e.replace("mAh",""),n=Number.parseFloat(t);if(Number.isNaN(n))throw new Error("Invalid capacity");return n}return e}).describe("Battery capacity in mAh"),Lz=Dn.extend({capacity:iyt.optional(),voltage:ai.optional(),standard:p.enum(["AA","AAA","9V","CR2032","18650","C"]).optional(),schOrientation:tc.optional()});Ct(!0);var oyt=p.enum(["vertical","horizontal"]).describe("vertical means pins go 1->2 downward and horizontal means pins go 1->2 rightward");Ct(!0);var Fz=Dn.extend({pinCount:p.number(),pitch:Y.optional(),schFacingDirection:p.enum(["up","down","left","right"]).optional(),gender:p.enum(["male","female","unpopulated"]).optional().default("male"),showSilkscreenPinLabels:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),doubleRow:p.boolean().optional(),rightAngle:p.boolean().optional(),pcbOrientation:oyt.optional(),holeDiameter:Y.optional(),platedDiameter:Y.optional(),pinLabels:p.record(p.string(),ur).or(p.array(ur)).optional(),connections:p.custom().pipe(p.record(p.string(),Kp)).optional(),facingDirection:p.enum(["left","right"]).optional(),schPinArrangement:AI.optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional()});Ct(!0);var kBt=p.object({net:p.string().optional(),connection:p.string().optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Be.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});Ct(!0);var zz=p.object({net:p.string().optional(),connection:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Be.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});Ct(!0);var Dz=Jp.extend({});Ct(!0);Ct(!0);var ryt=p.custom(e=>typeof e=="string"),$z=p.object({simulationType:p.literal("spice_transient_analysis").default("spice_transient_analysis"),duration:qi.optional(),timePerStep:qi.optional(),spiceEngine:ryt.optional()});Ct(!0);var syt=["pin1","pin2","pin3","emitter","collector","base","gate","source","drain"],jz=Dn.extend({type:p.enum(["npn","pnp","bjt","jfet","mosfet","igbt"]),connections:jl(syt).optional()});Ct(!0);var Bz=Dn.extend({channelType:p.enum(["n","p"]),mosfetMode:p.enum(["enhancement","depletion"])});Ct(!0);var ayt=kI,Yz=Dn.extend({inductance:I_,maxCurrentRating:p.union([p.string(),p.number()]).optional(),schOrientation:tc.optional(),connections:jl(ayt).optional()});Ct(!0);var cyt=p.enum(["anode","cathode","pin1","pin2","pos","neg"]),lyt=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),uyt=p.record(cyt,lyt),pyt=p.enum(["standard","schottky","zener","avalanche","photo","tvs"]),Xz=Dn.extend({connections:uyt.optional(),variant:pyt.optional().default("standard"),standard:p.boolean().optional(),schottky:p.boolean().optional(),zener:p.boolean().optional(),avalanche:p.boolean().optional(),photo:p.boolean().optional(),tvs:p.boolean().optional(),schOrientation:tc.optional()}).superRefine((e,t)=>{if([e.standard,e.schottky,e.zener,e.avalanche,e.photo,e.tvs].filter(Boolean).length>1)return t.addIssue({code:p.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),p.INVALID}).transform(e=>{let t={...e,standard:!1,schottky:!1,zener:!1,avalanche:!1,photo:!1,tvs:!1};if(e.standard)t.standard=!0;else if(e.schottky)t.schottky=!0;else if(e.zener)t.zener=!0;else if(e.photo)t.photo=!0;else if(e.tvs)t.tvs=!0;else switch(e.variant){case"standard":t.standard=!0;break;case"schottky":t.schottky=!0;break;case"zener":t.zener=!0;break;case"avalanche":t.avalanche=!0;break;case"photo":t.photo=!0;break;case"tvs":t.tvs=!0;break;default:t.standard=!0}return t}),Vz=Jg;Ct(!0);var Hz=Dn.extend({color:p.string().optional(),wavelength:p.string().optional(),schDisplayValue:p.string().optional(),schOrientation:tc.optional(),connections:jl(Jg).optional(),laser:p.boolean().optional()}),Gz=Jg,Uz=Dn.extend({type:p.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:p.boolean().optional().default(!1),spst:p.boolean().optional(),spdt:p.boolean().optional(),dpst:p.boolean().optional(),dpdt:p.boolean().optional(),simSwitchFrequency:Wi.optional(),simCloseAt:qi.optional(),simOpenAt:qi.optional(),simStartClosed:p.boolean().optional(),simStartOpen:p.boolean().optional(),connections:p.custom().pipe(p.record(p.string(),Kp)).optional()}).transform(e=>{let t={...e};switch(t.dpdt?t.type="dpdt":t.spst?t.type="spst":t.spdt?t.type="spdt":t.dpst&&(t.type="dpst"),t.type){case"spdt":t.spdt=!0;break;case"spst":t.spst=!0;break;case"dpst":t.dpst=!0;break;case"dpdt":t.dpdt=!0;break}return t});Ct(!0);var qz=Oe.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional()});Ct(!0);var Wz=Oe.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional(),cornerRadius:Y.optional()}),Zz=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Fi),strokeWidth:D.optional(),color:p.string().optional()}),az=p.union([p.string(),Gs]),Kz=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:az,to:az,text:p.string().optional(),offset:Y.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional(),arrowSize:Y.optional(),units:p.enum(["in","mm"]).optional(),outerEdgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional(),innerEdgeToEdge:p.literal(!0).optional()});Ct(!0);var tYt=p.object({layer:p.string().optional(),thickness:Y.optional(),route:p.array(Fi)}),Jz=Kg.extend({name:p.string().optional(),fromLayer:se,toLayer:se,holeDiameter:Y,outerDiameter:Y,connectsTo:p.string().or(p.array(p.string())).optional(),netIsAssignable:p.boolean().optional()});Ct(!0);var hyt=p.object({pin1:Kp}).strict(),Qz=Dn.extend({connections:hyt.optional(),footprintVariant:p.enum(["pad","through_hole"]).optional(),padShape:p.enum(["rect","circle"]).optional().default("circle"),padDiameter:Y.optional(),holeDiameter:Y.optional(),width:Y.optional(),height:Y.optional()}).refine(e=>e.footprintVariant!=="through_hole"||e.holeDiameter!==void 0,{message:"holeDiameter is required for through_hole testpoints"});Ct(!0);var tD=Oe.omit({pcbRotation:!0,layer:!0}).extend({connection:p.string()});Ct(!0);var eD=p.union([Oe.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:Y}),Oe.extend({shape:p.literal("rect"),width:Y,height:Y})]),uYt=Oe.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),dYt=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({outline:p.array(Gs),strokeWidth:D.optional(),isClosed:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),nD=p.object({name:p.string().optional(),layer:se,connectsTo:p.string(),padMargin:Y.optional(),traceMargin:Y.optional(),clearance:Y.optional(),boardEdgeMargin:Y.optional(),cutoutMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional().default(!0)});Ct(!0);var iD=p.object({originalLayer:se.default("top").optional(),children:p.any().optional()});Ct(!0);var dyt=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbZ:Y.optional()}),fyt=Qa.extend({modelUrl:p.string(),stepUrl:p.string().optional()}),myt=fyt.merge(dyt);Ct(!0);var oD=p.union([p.null(),p.string(),myt]),rD=Dn.extend({voltage:ai}),_yt=["pin1","pin2","pos","neg"],yyt=p.union([p.string(),p.number()]).transform(e=>typeof e=="string"?e.endsWith("%")?parseFloat(e.slice(0,-1))/100:parseFloat(e):e).pipe(p.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),SYt=Dn.extend({voltage:ai.optional(),frequency:Wi.optional(),peakToPeakVoltage:ai.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Be.optional(),dutyCycle:yyt.optional(),connections:jl(_yt).optional()});Ct(!0);var sD=Dn.omit({name:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string()))});Ct(!0);var aD=p.object({center:qt,radius:Y,startAngleDegrees:Be,endAngleDegrees:Be,direction:p.enum(["clockwise","counterclockwise"]).default("counterclockwise"),strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),cD=p.object({schX:Y.optional(),schY:Y.optional(),width:Y.optional(),height:Y.optional(),overlay:p.array(p.string()).optional(),padding:Y.optional(),paddingLeft:Y.optional(),paddingRight:Y.optional(),paddingTop:Y.optional(),paddingBottom:Y.optional(),title:p.string().optional(),titleAlignment:Zp.default("top_left"),titleColor:p.string().optional(),titleFontSize:Y.optional(),titleInside:p.boolean().default(!1),strokeStyle:p.enum(["solid","dashed"]).default("solid")}).refine(e=>e.width!==void 0&&e.height!==void 0||Array.isArray(e.overlay)&&e.overlay.length>0,{message:"Must provide either both `width` and `height`, or a non-empty `overlay` array."}).refine(e=>!(e.width!==void 0&&e.height!==void 0&&Array.isArray(e.overlay)&&e.overlay.length>0),{message:"Cannot provide both `width`/`height` and `overlay` at the same time."}),lD=p.object({center:qt,radius:Y,strokeWidth:Y.optional(),color:p.string().optional(),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),uD=p.object({schX:Y.optional(),schY:Y.optional(),width:Y,height:Y,rotation:Be.default(0),strokeWidth:Y.optional(),color:p.string().optional(),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1),cornerRadius:Y.optional()}),pD=p.object({x1:Y,y1:Y,x2:Y,y2:Y,strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),gyt=p.enum(["center","left","right","top","bottom"]),hD=p.object({schX:Y.optional(),schY:Y.optional(),text:p.string(),fontSize:p.number().default(1),anchor:p.union([gyt.describe("legacy"),Zp]).default("center"),color:p.string().default("#000000"),schRotation:Be.default(0)}),$Yt=p.object({points:p.array(qt),isFilled:p.boolean().optional().default(!1),fillColor:p.enum(["red","blue"]).optional()}),dD=p.object({schX:Y.optional(),schY:Y.optional(),children:p.any().optional(),cellPadding:Y.optional(),borderWidth:Y.optional(),anchor:Zp.optional(),fontSize:Y.optional()});Ct(!0);var fD=p.object({children:p.any().optional(),height:Y.optional()});Ct(!0);var mD=p.object({children:p.string().optional(),horizontalAlign:p.enum(["left","center","right"]).optional(),verticalAlign:p.enum(["top","middle","bottom"]).optional(),fontSize:Y.optional(),rowSpan:p.number().optional(),colSpan:p.number().optional(),width:Y.optional(),text:p.string().optional()});Ct(!0);var qYt=Oe.extend({text:p.string(),anchorAlignment:Zp.default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),layers:p.array(se).optional()}),_D=Oe.extend({text:p.string(),anchorAlignment:Zp.default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),isKnockout:p.boolean().optional(),knockoutPadding:D.optional(),knockoutPaddingLeft:D.optional(),knockoutPaddingRight:D.optional(),knockoutPaddingTop:D.optional(),knockoutPaddingBottom:D.optional(),layers:p.array(se).optional()}),yD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Fi),strokeWidth:D.optional()}),gD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({strokeWidth:Y,x1:Y,y1:Y,x2:Y,y2:Y}),bD=Oe.omit({pcbRotation:!0}).extend({filled:p.boolean().default(!0).optional(),stroke:p.enum(["dashed","solid","none"]).optional(),strokeWidth:Y.optional(),width:Y,height:Y,cornerRadius:Y.optional()}),xD=Oe.omit({pcbRotation:!0}).extend({isFilled:p.boolean().optional(),isOutline:p.boolean().optional(),strokeWidth:Y.optional(),radius:Y}),cz=p.object({x:Y,y:Y,via:p.boolean().optional(),toLayer:se.optional()}),vD=p.object({for:p.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:p.number().optional(),offset:Fi.or(cz).optional(),offsets:p.array(Fi).or(p.array(cz)).optional(),traceWidth:p.number().optional()}),aXt=Kg.extend({name:p.string(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),direction:c_t,connectsTo:p.string().or(p.array(p.string())).optional()}),SD=Oe.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional()});Ct(!0);var wD=Oe.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional(),cornerRadius:Y.optional()});Ct(!0);var PD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Fi),strokeWidth:D.optional(),color:p.string().optional()});Ct(!0);var ID=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({x1:Y,y1:Y,x2:Y,y2:Y,strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional()});Ct(!0);var lz=p.union([p.string(),Gs]),TD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:lz,to:lz,text:p.string().optional(),offset:Y.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional(),arrowSize:Y.optional(),units:p.enum(["in","mm"]).optional(),outerEdgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional(),innerEdgeToEdge:p.literal(!0).optional()});Ct(!0);var MD=p.array(p.any()).describe("Circuit JSON"),EI=p.object({footprintCircuitJson:p.array(p.any()),cadModel:hz.optional()}),uz=p.function().args(p.string()).returns(p.promise(EI)).or(p.function().args(p.string(),p.object({resolvedPcbStyle:NI.optional()}).optional()).returns(p.promise(EI))).describe("A function that takes a path and returns Circuit JSON"),byt=p.object({loadFromUrl:p.function().args(p.string()).returns(p.promise(EI)).describe("A function that takes a footprint file URL and returns Circuit JSON")}),xyt=p.object({engineVersionString:p.string().optional(),simulationResultCircuitJson:MD}),vyt=p.object({simulate:p.function().args(p.string()).returns(p.promise(xyt)).describe("A function that takes a SPICE string and returns a simulation result")}),Syt=p.custom(e=>typeof e=="string"),pz=p.object({run:p.function().args().returns(p.promise(p.unknown())).describe("Run the autorouter"),getOutputSimpleRouteJson:p.function().args().returns(p.promise(p.any())).describe("Get the resulting SimpleRouteJson")}),wyt=p.object({createAutorouter:p.function().args(p.any(),p.any().optional()).returns(p.union([pz,p.promise(pz)])).describe("Create an autorouter instance")}),Pyt=p.object({partsEngine:fz.optional(),autorouter:dz.optional(),autorouterMap:p.record(p.string(),wyt).optional(),registryApiUrl:p.string().optional(),cloudAutorouterUrl:p.string().optional(),projectName:p.string().optional(),projectBaseUrl:p.string().optional(),version:p.string().optional(),url:p.string().optional(),printBoardInformationToSilkscreen:p.boolean().optional(),includeBoardFiles:p.array(p.string()).describe('The board files to automatically build with "tsci build", defaults to ["**/*.circuit.tsx"]. Can be an array of files or globs').optional(),snapshotsDir:p.string().describe('The directory where snapshots are stored for "tsci snapshot", defaults to "tests/__snapshots__"').optional(),defaultSpiceEngine:Syt.optional(),localCacheEngine:p.any().optional(),pcbDisabled:p.boolean().optional(),schematicDisabled:p.boolean().optional(),partsEngineDisabled:p.boolean().optional(),spiceEngineMap:p.record(p.string(),vyt).optional(),footprintLibraryMap:p.record(p.string(),p.union([uz,p.record(p.string(),p.union([MD,uz]))])).optional(),footprintFileParserMap:p.record(p.string(),byt).optional(),resolveProjectStaticFileImportUrl:p.function().args(p.string()).returns(p.promise(p.string())).describe("A function that returns a string URL for static files for the project").optional()});Ct(!0);var Iyt=Pyt,bXt=Iyt.pick({projectName:!0,projectBaseUrl:!0,version:!0,url:!0,printBoardInformationToSilkscreen:!0,includeBoardFiles:!0,snapshotsDir:!0,defaultSpiceEngine:!0});Ct(!0);vt();K();vt();Ys();K();var ca=Xt(Mr(),1);Ys();K();function ec(){return new zI}var zI=class e{constructor(){P(this,"index",{});P(this,"array",[])}size(){return this.array.length}empty(){return this.array.length===0}itemAt(t){return this.array[t]}contains(t){return this.index[t.id()]!==void 0}find(t){let n=this.index[t.id()];return n===void 0?void 0:this.array[n]}setDefault(t,n){let i=this.index[t.id()];if(i===void 0){let o=new Qg(t,n());return this.index[t.id()]=this.array.length,this.array.push(o),o}else return this.array[i]}insert(t,n){let i=new Qg(t,n),o=this.index[t.id()];return o===void 0?(this.index[t.id()]=this.array.length,this.array.push(i)):this.array[o]=i,i}erase(t){let n=this.index[t.id()];if(n===void 0)return;this.index[t.id()]=void 0;let i=this.array[n],o=this.array.pop();return i!==o&&(this.array[n]=o,this.index[o.first.id()]=n),i}copy(){let t=new e;for(let n=0;n<this.array.length;n++){let i=this.array[n].copy();t.array[n]=i,t.index[i.first.id()]=n}return t}},Qg=class e{constructor(t,n){P(this,"first");P(this,"second");this.first=t,this.second=n}copy(){return new e(this.first,this.second)}};var Us=class{constructor(t=""){P(this,"_name");P(this,"_value",0);P(this,"_context",null);P(this,"_id",Tyt++);this._name=t}id(){return this._id}name(){return this._name}setName(t){this._name=t}context(){return this._context}setContext(t){this._context=t}value(){return this._value}setValue(t){this._value=t}plus(t){return new Cn(this,t)}minus(t){return new Cn(this,typeof t=="number"?-t:[-1,t])}multiply(t){return new Cn([t,this])}divide(t){return new Cn([1/t,this])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},Tyt=0;var Cn=class e{constructor(){P(this,"_terms");P(this,"_constant");let t=Myt(arguments);this._terms=t.terms,this._constant=t.constant}terms(){return this._terms}constant(){return this._constant}value(){let t=this._constant;for(let n=0,i=this._terms.size();n<i;n++){let o=this._terms.itemAt(n);t+=o.first.value()*o.second}return t}plus(t){return new e(this,t)}minus(t){return new e(this,typeof t=="number"?-t:[-1,t])}multiply(t){return new e([t,this])}divide(t){return new e([1/t,this])}isConstant(){return this._terms.size()==0}toString(){let t=this._terms.array.map(function(n){return n.second+"*"+n.first.toString()}).join(" + ");return!this.isConstant()&&this._constant!==0&&(t+=" + "),t+=this._constant,t}};function Myt(e){let t=0,n=()=>0,i=ec();for(let o=0,r=e.length;o<r;++o){let s=e[o];if(typeof s=="number")t+=s;else if(s instanceof Us)i.setDefault(s,n).second+=1;else if(s instanceof Cn){t+=s.constant();let a=s.terms();for(let c=0,l=a.size();c<l;c++){let u=a.itemAt(c);i.setDefault(u.first,n).second+=u.second}}else if(s instanceof Array){if(s.length!==2)throw new Error("array must have length 2");let a=s[0],c=s[1];if(typeof a!="number")throw new Error("array item 0 must be a number");if(c instanceof Us)i.setDefault(c,n).second+=a;else if(c instanceof Cn){t+=c.constant()*a;let l=c.terms();for(let u=0,h=l.size();u<h;u++){let d=l.itemAt(u);i.setDefault(d.first,n).second+=d.second*a}}else throw new Error("array item 1 must be a variable or expression")}else throw new Error("invalid Expression argument: "+s)}return{terms:i,constant:t}}var Lr=class Lr{static create(t,n,i,o=1){let r=0;return r+=Math.max(0,Math.min(1e3,t*o))*1e6,r+=Math.max(0,Math.min(1e3,n*o))*1e3,r+=Math.max(0,Math.min(1e3,i*o)),r}static clip(t){return Math.max(0,Math.min(Lr.required,t))}};P(Lr,"required",Lr.create(1e3,1e3,1e3)),P(Lr,"strong",Lr.create(1,0,0)),P(Lr,"medium",Lr.create(0,1,0)),P(Lr,"weak",Lr.create(0,0,1));var wn=Lr;var Vn;(function(e){e[e.Le=0]="Le",e[e.Ge=1]="Ge",e[e.Eq=2]="Eq"})(Vn||(Vn={}));var ci=class{constructor(t,n,i,o=wn.required){P(this,"_expression");P(this,"_operator");P(this,"_strength");P(this,"_id",Cyt++);this._operator=n,this._strength=wn.clip(o),i===void 0&&t instanceof Cn?this._expression=t:this._expression=t.minus(i)}id(){return this._id}expression(){return this._expression}op(){return this._operator}strength(){return this._strength}toString(){return this._expression.toString()+" "+["<=",">=","="][this._operator]+" 0 ("+this._strength.toString()+")"}},Cyt=0;var Qp=class{constructor(){P(this,"maxIterations",1e3);P(this,"_cnMap",Eyt());P(this,"_rowMap",Nyt());P(this,"_varMap",kyt());P(this,"_editMap",Ayt());P(this,"_infeasibleRows",[]);P(this,"_objective",new nb);P(this,"_artificial",null);P(this,"_idTick",0)}createConstraint(t,n,i,o=wn.required){let r=new ci(t,n,i,o);return this.addConstraint(r),r}addConstraint(t){if(this._cnMap.find(t)!==void 0)throw new Error("duplicate constraint");let i=this._createRow(t),o=i.row,r=i.tag,s=this._chooseSubject(o,r);if(s.type()===Ue.Invalid&&o.allDummies())if(tb(o.constant()))s=r.marker;else throw new Error("unsatisfiable constraint");if(s.type()===Ue.Invalid){if(!this._addWithArtificialVariable(o))throw new Error("unsatisfiable constraint")}else o.solveFor(s),this._substitute(s,o),this._rowMap.insert(s,o);this._cnMap.insert(t,r),this._optimize(this._objective)}removeConstraint(t){let n=this._cnMap.erase(t);if(n===void 0)throw new Error("unknown constraint");this._removeConstraintEffects(t,n.second);let i=n.second.marker,o=this._rowMap.erase(i);if(o===void 0){let r=this._getMarkerLeavingSymbol(i);if(r.type()===Ue.Invalid)throw new Error("failed to find leaving row");o=this._rowMap.erase(r),o.second.solveForEx(r,i),this._substitute(i,o.second)}this._optimize(this._objective)}hasConstraint(t){return this._cnMap.contains(t)}getConstraints(){return this._cnMap.array.map(({first:t})=>t)}addEditVariable(t,n){if(this._editMap.find(t)!==void 0)throw new Error("duplicate edit variable");if(n=wn.clip(n),n===wn.required)throw new Error("bad required strength");let o=new Cn(t),r=new ci(o,Vn.Eq,void 0,n);this.addConstraint(r);let a={tag:this._cnMap.find(r).second,constraint:r,constant:0};this._editMap.insert(t,a)}removeEditVariable(t){let n=this._editMap.erase(t);if(n===void 0)throw new Error("unknown edit variable");this.removeConstraint(n.second.constraint)}hasEditVariable(t){return this._editMap.contains(t)}suggestValue(t,n){let i=this._editMap.find(t);if(i===void 0)throw new Error("unknown edit variable");let o=this._rowMap,r=i.second,s=n-r.constant;r.constant=n;let a=r.tag.marker,c=o.find(a);if(c!==void 0){c.second.add(-s)<0&&this._infeasibleRows.push(a),this._dualOptimize();return}let l=r.tag.other;if(c=o.find(l),c!==void 0){c.second.add(s)<0&&this._infeasibleRows.push(l),this._dualOptimize();return}for(let u=0,h=o.size();u<h;++u){let d=o.itemAt(u),_=d.second,y=_.coefficientFor(a);y!==0&&_.add(s*y)<0&&d.first.type()!==Ue.External&&this._infeasibleRows.push(d.first)}this._dualOptimize()}updateVariables(){let t=this._varMap,n=this._rowMap;for(let i=0,o=t.size();i<o;++i){let r=t.itemAt(i),s=n.find(r.second);s!==void 0?r.first.setValue(s.second.constant()):r.first.setValue(0)}}_getVarSymbol(t){let n=()=>this._makeSymbol(Ue.External);return this._varMap.setDefault(t,n).second}_createRow(t){let n=t.expression(),i=new nb(n.constant()),o=n.terms();for(let c=0,l=o.size();c<l;++c){let u=o.itemAt(c);if(!tb(u.second)){let h=this._getVarSymbol(u.first),d=this._rowMap.find(h);d!==void 0?i.insertRow(d.second,u.second):i.insertSymbol(h,u.second)}}let r=this._objective,s=t.strength(),a={marker:nc,other:nc};switch(t.op()){case Vn.Le:case Vn.Ge:{let c=t.op()===Vn.Le?1:-1,l=this._makeSymbol(Ue.Slack);if(a.marker=l,i.insertSymbol(l,c),s<wn.required){let u=this._makeSymbol(Ue.Error);a.other=u,i.insertSymbol(u,-c),r.insertSymbol(u,s)}break}case Vn.Eq:{if(s<wn.required){let c=this._makeSymbol(Ue.Error),l=this._makeSymbol(Ue.Error);a.marker=c,a.other=l,i.insertSymbol(c,-1),i.insertSymbol(l,1),r.insertSymbol(c,s),r.insertSymbol(l,s)}else{let c=this._makeSymbol(Ue.Dummy);a.marker=c,i.insertSymbol(c)}break}}return i.constant()<0&&i.reverseSign(),{row:i,tag:a}}_chooseSubject(t,n){let i=t.cells();for(let r=0,s=i.size();r<s;++r){let a=i.itemAt(r);if(a.first.type()===Ue.External)return a.first}let o=n.marker.type();return(o===Ue.Slack||o===Ue.Error)&&t.coefficientFor(n.marker)<0?n.marker:(o=n.other.type(),(o===Ue.Slack||o===Ue.Error)&&t.coefficientFor(n.other)<0?n.other:nc)}_addWithArtificialVariable(t){let n=this._makeSymbol(Ue.Slack);this._rowMap.insert(n,t.copy()),this._artificial=t.copy(),this._optimize(this._artificial);let i=tb(this._artificial.constant());this._artificial=null;let o=this._rowMap.erase(n);if(o!==void 0){let s=o.second;if(s.isConstant())return i;let a=this._anyPivotableSymbol(s);if(a.type()===Ue.Invalid)return!1;s.solveForEx(n,a),this._substitute(a,s),this._rowMap.insert(a,s)}let r=this._rowMap;for(let s=0,a=r.size();s<a;++s)r.itemAt(s).second.removeSymbol(n);return this._objective.removeSymbol(n),i}_substitute(t,n){let i=this._rowMap;for(let o=0,r=i.size();o<r;++o){let s=i.itemAt(o);s.second.substitute(t,n),s.second.constant()<0&&s.first.type()!==Ue.External&&this._infeasibleRows.push(s.first)}this._objective.substitute(t,n),this._artificial&&this._artificial.substitute(t,n)}_optimize(t){let n=0;for(;n<this.maxIterations;){let i=this._getEnteringSymbol(t);if(i.type()===Ue.Invalid)return;let o=this._getLeavingSymbol(i);if(o.type()===Ue.Invalid)throw new Error("the objective is unbounded");let r=this._rowMap.erase(o).second;r.solveForEx(o,i),this._substitute(i,r),this._rowMap.insert(i,r),n++}throw new Error("solver iterations exceeded")}_dualOptimize(){let t=this._rowMap,n=this._infeasibleRows;for(;n.length!==0;){let i=n.pop(),o=t.find(i);if(o!==void 0&&o.second.constant()<0){let r=this._getDualEnteringSymbol(o.second);if(r.type()===Ue.Invalid)throw new Error("dual optimize failed");let s=o.second;t.erase(i),s.solveForEx(i,r),this._substitute(r,s),t.insert(r,s)}}}_getEnteringSymbol(t){let n=t.cells();for(let i=0,o=n.size();i<o;++i){let r=n.itemAt(i),s=r.first;if(r.second<0&&s.type()!==Ue.Dummy)return s}return nc}_getDualEnteringSymbol(t){let n=Number.MAX_VALUE,i=nc,o=t.cells();for(let r=0,s=o.size();r<s;++r){let a=o.itemAt(r),c=a.first,l=a.second;if(l>0&&c.type()!==Ue.Dummy){let h=this._objective.coefficientFor(c)/l;h<n&&(n=h,i=c)}}return i}_getLeavingSymbol(t){let n=Number.MAX_VALUE,i=nc,o=this._rowMap;for(let r=0,s=o.size();r<s;++r){let a=o.itemAt(r),c=a.first;if(c.type()!==Ue.External){let l=a.second,u=l.coefficientFor(t);if(u<0){let h=-l.constant()/u;h<n&&(n=h,i=c)}}}return i}_getMarkerLeavingSymbol(t){let n=Number.MAX_VALUE,i=n,o=n,r=nc,s=r,a=r,c=r,l=this._rowMap;for(let u=0,h=l.size();u<h;++u){let d=l.itemAt(u),_=d.second,y=_.coefficientFor(t);if(y===0)continue;let g=d.first;if(g.type()===Ue.External)c=g;else if(y<0){let x=-_.constant()/y;x<i&&(i=x,s=g)}else{let x=_.constant()/y;x<o&&(o=x,a=g)}}return s!==r?s:a!==r?a:c}_removeConstraintEffects(t,n){n.marker.type()===Ue.Error&&this._removeMarkerEffects(n.marker,t.strength()),n.other.type()===Ue.Error&&this._removeMarkerEffects(n.other,t.strength())}_removeMarkerEffects(t,n){let i=this._rowMap.find(t);i!==void 0?this._objective.insertRow(i.second,-n):this._objective.insertSymbol(t,-n)}_anyPivotableSymbol(t){let n=t.cells();for(let i=0,o=n.size();i<o;++i){let r=n.itemAt(i),s=r.first.type();if(s===Ue.Slack||s===Ue.Error)return r.first}return nc}_makeSymbol(t){return new eb(t,this._idTick++)}};function tb(e){let t=1e-8;return e<0?-e<t:e<t}function Eyt(){return ec()}function Nyt(){return ec()}function kyt(){return ec()}function Ayt(){return ec()}var Ue;(function(e){e[e.Invalid=0]="Invalid",e[e.External=1]="External",e[e.Slack=2]="Slack",e[e.Error=3]="Error",e[e.Dummy=4]="Dummy"})(Ue||(Ue={}));var eb=class{constructor(t,n){P(this,"_id");P(this,"_type");this._id=n,this._type=t}id(){return this._id}type(){return this._type}},nc=new eb(Ue.Invalid,-1),nb=class e{constructor(t=0){P(this,"_cellMap",ec());P(this,"_constant");this._constant=t}cells(){return this._cellMap}constant(){return this._constant}isConstant(){return this._cellMap.empty()}allDummies(){let t=this._cellMap;for(let n=0,i=t.size();n<i;++n)if(t.itemAt(n).first.type()!==Ue.Dummy)return!1;return!0}copy(){let t=new e(this._constant);return t._cellMap=this._cellMap.copy(),t}add(t){return this._constant+=t}insertSymbol(t,n=1){let i=this._cellMap.setDefault(t,()=>0);tb(i.second+=n)&&this._cellMap.erase(t)}insertRow(t,n=1){this._constant+=t._constant*n;let i=t._cellMap;for(let o=0,r=i.size();o<r;++o){let s=i.itemAt(o);this.insertSymbol(s.first,s.second*n)}}removeSymbol(t){this._cellMap.erase(t)}reverseSign(){this._constant=-this._constant;let t=this._cellMap;for(let n=0,i=t.size();n<i;++n){let o=t.itemAt(n);o.second=-o.second}}solveFor(t){let n=this._cellMap,o=-1/n.erase(t).second;this._constant*=o;for(let r=0,s=n.size();r<s;++r)n.itemAt(r).second*=o}solveForEx(t,n){this.insertSymbol(t,-1),this.solveFor(n)}coefficientFor(t){let n=this._cellMap.find(t);return n!==void 0?n.second:0}substitute(t,n){let i=this._cellMap.erase(t);i!==void 0&&this.insertRow(n,i.second)}};var RH=Xt(Sn(),1);K();vt();vt();ji();var YI={};il(YI,{areBoundsCompletelyInsidePolygon:()=>BI,areBoundsOverlappingPolygon:()=>jI,boundsAreaOverlap:()=>jD,boundsDistance:()=>BD,boundsIntersection:()=>YD,clamp:()=>Rn,computeDistanceBetweenBoxes:()=>ts,computeGapBetweenBoxes:()=>II,computeManhattanDistanceBetweenBoxes:()=>yf,distSq:()=>RD,distance:()=>vi,doBoundsOverlap:()=>ic,doSegmentsIntersect:()=>li,doesLineIntersectLine:()=>qs,doesSegmentIntersectRect:()=>DI,findNearestPointsBetweenBoxSets:()=>gf,getBoundingBox:()=>Or,getBoundsFromPoints:()=>ns,getSegmentIntersection:()=>Xl,getUnitVectorFromDirection:()=>ab,getUnitVectorFromPointAToB:()=>sb,grid:()=>XD,isPointInsidePolygon:()=>rb,isRectCompletelyInsidePolygon:()=>DD,isRectOverlappingPolygon:()=>zD,midpoint:()=>AD,normalizeDegrees:()=>Vl,onSegment:()=>Yl,orientation:()=>Bl,pointToBoundsDistance:()=>kD,pointToBoxDistance:()=>ND,pointToSegmentClosestPoint:()=>ED,pointToSegmentDistance:()=>ei,range:()=>$D,segmentToBoundsMinDistance:()=>wf,segmentToBoxMinDistance:()=>ib,segmentToCircleMinDistance:()=>ob,segmentToSegmentMinDistance:()=>th});function qs([e,t],[n,i],{lineThickness:o=0}={}){return o===0?li(e,t,n,i):Ryt(e,t,n,i)<=o}function li(e,t,n,i){let o=Bl(e,t,n),r=Bl(e,t,i),s=Bl(n,i,e),a=Bl(n,i,t);return!!(o!==r&&s!==a||o===0&&Yl(e,n,t)||r===0&&Yl(e,i,t)||s===0&&Yl(n,e,i)||a===0&&Yl(n,t,i))}function Bl(e,t,n){let i=(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y);return i===0?0:i>0?1:2}function Yl(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function Ryt(e,t,n,i){if(e.x===t.x&&e.y===t.y)return ei(e,n,i);if(n.x===i.x&&n.y===i.y)return ei(n,e,t);if(li(e,t,n,i))return 0;let o=[ei(e,n,i),ei(t,n,i),ei(n,e,t),ei(i,e,t)];return Math.min(...o)}function ei(e,t,n){let i=(n.x-t.x)**2+(n.y-t.y)**2;if(i===0)return vi(e,t);let o=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/i;o=Math.max(0,Math.min(1,o));let r={x:t.x+o*(n.x-t.x),y:t.y+o*(n.y-t.y)};return vi(e,r)}function vi(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}function Xl(e,t,n,i){let o=t.x-e.x,r=t.y-e.y,s=i.x-n.x,a=i.y-n.y,c=e.x-n.x,l=e.y-n.y,u=o*a-r*s;if(Math.abs(u)<1e-10)return null;let h=(l*s-c*a)/u,d=(o*l-r*c)/u,_=1e-9;if(h>=-_&&h<=1+_&&d>=-_&&d<=1+_){let y=e.x+h*o,g=e.y+h*r;return{x:y,y:g}}return null}function DI(e,t,n){let i=c=>c.x>=n.minX&&c.x<=n.maxX&&c.y>=n.minY&&c.y<=n.maxY;if(i(e)||i(t))return!0;let o={x:n.minX,y:n.minY},r={x:n.maxX,y:n.minY},s={x:n.minX,y:n.maxY},a={x:n.maxX,y:n.maxY};return li(e,t,o,r)||li(e,t,r,a)||li(e,t,a,s)||li(e,t,s,o)}function th(e,t,n,i){if(e.x===t.x&&e.y===t.y)return ei(e,n,i);if(n.x===i.x&&n.y===i.y)return ei(n,e,t);if(li(e,t,n,i))return 0;let o=[ei(e,n,i),ei(t,n,i),ei(n,e,t),ei(i,e,t)];return Math.min(...o)}function wf(e,t,n){let i={x:n.minX,y:n.minY},o={x:n.maxX,y:n.minY},r={x:n.minX,y:n.maxY},s={x:n.maxX,y:n.maxY};if(li(e,t,i,o)||li(e,t,o,s)||li(e,t,s,r)||li(e,t,r,i)||e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY&&t.x>=n.minX&&t.x<=n.maxX&&t.y>=n.minY&&t.y<=n.maxY)return 0;let a=[ei(i,e,t),ei(o,e,t),ei(r,e,t),ei(s,e,t)];if(e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY||t.x>=n.minX&&t.x<=n.maxX&&t.y>=n.minY&&t.y<=n.maxY)return 0;if(e.x<n.minX||e.x>n.maxX||e.y<n.minY||e.y>n.maxY){let c=Rn(e.x,n.minX,n.maxX),l=Rn(e.y,n.minY,n.maxY);a.push(vi(e,{x:c,y:l}))}if(t.x<n.minX||t.x>n.maxX||t.y<n.minY||t.y>n.maxY){let c=Rn(t.x,n.minX,n.maxX),l=Rn(t.y,n.minY,n.maxY);a.push(vi(t,{x:c,y:l}))}return Math.min(...a)}function ib(e,t,n){let i=n.width/2,o=n.height/2,r={minX:n.center.x-i,maxX:n.center.x+i,minY:n.center.y-o,maxY:n.center.y+o};return wf(e,t,r)}function ob(e,t,n){let i={x:n.x,y:n.y};if(e.x===t.x&&e.y===t.y)return Math.max(0,vi(e,i)-n.radius);let o={x:t.x-e.x,y:t.y-e.y},r={x:i.x-e.x,y:i.y-e.y},s=o.x*o.x+o.y*o.y,a=Math.max(0,Math.min(1,(o.x*r.x+o.y*r.y)/s)),c={x:e.x+a*o.x,y:e.y+a*o.y},l=vi(c,i);return Math.max(0,l-n.radius)}function ED(e,t,n){let i=n.x-t.x,o=n.y-t.y,r=i*i+o*o;if(r===0)return{x:t.x,y:t.y};let s=((e.x-t.x)*i+(e.y-t.y)*o)/r;return s=Math.max(0,Math.min(1,s)),{x:t.x+s*i,y:t.y+s*o}}function Vl(e){return(e%360+360)%360}function ND(e,t){let n=t.width/2,i=t.height/2,o=t.center.x-n,r=t.center.x+n,s=t.center.y-i,a=t.center.y+i;if(e.x>=o&&e.x<=r&&e.y>=s&&e.y<=a)return 0;let c=Rn(e.x,o,r),l=Rn(e.y,s,a);return vi(e,{x:c,y:l})}function kD(e,t){if(e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)return 0;let n=Rn(e.x,t.minX,t.maxX),i=Rn(e.y,t.minY,t.maxY);return vi(e,{x:n,y:i})}function AD(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function RD(e,t){let n=e.x-t.x,i=e.y-t.y;return n*n+i*i}var OD=e=>{if("minX"in e)return e;let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,minY:e.center.y-n,maxX:e.center.x+t,maxY:e.center.y+n}},$I=e=>[{x:e.minX,y:e.minY},{x:e.maxX,y:e.minY},{x:e.maxX,y:e.maxY},{x:e.minX,y:e.maxY}],LD=e=>{let t=[];for(let n=0;n<e.length;n++){let i=e[n],o=e[(n+1)%e.length];t.push([i,o])}return t},Oyt=(e,t,n)=>{let i=(e.y-t.y)*(n.x-t.x)-(e.x-t.x)*(n.y-t.y);if(Math.abs(i)>1e-9)return!1;let o=(e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y);if(o<0)return!1;let r=(n.x-t.x)**2+(n.y-t.y)**2;return!(o>r)},Lyt=(e,t)=>e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY,rb=(e,t)=>{if(t.length<3)return!1;let n=LD(t);for(let[o,r]of n)if(Oyt(e,o,r))return!0;let i=!1;for(let o=0,r=t.length-1;o<t.length;r=o++){let s=t[o].x,a=t[o].y,c=t[r].x,l=t[r].y;a>e.y!=l>e.y&&e.x<(c-s)*(e.y-a)/(l-a)+s&&(i=!i)}return i},FD=(e,t)=>{let n=$I(e),i=[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]],o=LD(t);for(let[r,s]of o)for(let[a,c]of i)if(li(r,s,a,c))return!0;return!1},jI=(e,t)=>t.length<3?!1:t.some(i=>Lyt(i,e))||$I(e).some(i=>rb(i,t))?!0:FD(e,t),BI=(e,t)=>t.length<3||!$I(e).every(i=>rb(i,t))?!1:!FD(e,t),zD=(e,t)=>jI(OD(e),t),DD=(e,t)=>BI(OD(e),t);function $D(e,t,n=1){if(n===0)throw new Error("step cannot be 0");let i,o;t===void 0?(i=0,o=e):(i=e,o=t);let r=[];if(n>0)for(let s=i;s<o;s+=n)r.push(s);else for(let s=i;s>o;s+=n)r.push(s);return r}var jD=(e,t)=>{let n=Math.max(0,Math.min(e.maxX,t.maxX)-Math.max(e.minX,t.minX)),i=Math.max(0,Math.min(e.maxY,t.maxY)-Math.max(e.minY,t.minY));return n*i};var BD=(e,t)=>{let n=e.maxX<t.minX?t.minX-e.maxX:t.maxX<e.minX?e.minX-t.maxX:0,i=e.maxY<t.minY?t.minY-e.maxY:t.maxY<e.minY?e.minY-t.maxY:0;return Math.sqrt(n*n+i*i)};var YD=(e,t)=>{let n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),o=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return n>o||i>r?null:{minX:n,minY:i,maxX:o,maxY:r}};var ic=(e,t)=>!(e.maxX<t.minX||t.maxX<e.minX||e.maxY<t.minY||t.maxY<e.minY);var ns=e=>{if(e.length===0)return null;let t=e[0].x,n=e[0].y,i=e[0].x,o=e[0].y;for(let r=1;r<e.length;r++){let s=e[r];s.x<t&&(t=s.x),s.y<n&&(n=s.y),s.x>i&&(i=s.x),s.y>o&&(o=s.y)}return{minX:t,minY:n,maxX:i,maxY:o}};var sb=(e,t)=>{let n={x:t.x-e.x,y:t.y-e.y},i=Math.sqrt(n.x**2+n.y**2);return{x:n.x/i,y:n.y/i}},ab=e=>{switch(e){case"up":return{x:0,y:1};case"down":return{x:0,y:-1};case"left":return{x:-1,y:0};case"right":return{x:1,y:0}}};function XD({rows:e,cols:t,xSpacing:n,ySpacing:i,width:o,height:r,offsetX:s=0,offsetY:a=0,yDirection:c="cartesian",centered:l=!0}){let u=n??1,h=i??1,d=o??t*u,_=r??e*h,y=l?-d/2:0,g=l?-_/2:0,x=o?o/t:u,w=r?r/e:h,S=[];for(let T=0;T<e;T++)for(let I=0;I<t;I++){let E=T*t+I,M=s+y+I*x+x/2,k=a+T*w+w/2,N=c==="cartesian"?a+g+(e-1-T)*w+w/2:a+g+T*w+w/2;S.push({index:E,center:{x:M,y:N},topLeft:{x:M-x/2,y:N+w/2},bottomRight:{x:M+x/2,y:N-w/2},row:T,col:I})}return S}vt();Pf();var VD={name:"@tscircuit/capacity-autorouter",main:"./dist/index.js",version:"0.0.140",type:"module",files:["dist"],scripts:{start:"cosmos",build:"tsup ./lib/index.ts --minify terser --external @tscircuit/core --external circuit-to-svg --format esm --dts --sourcemap",bench:"bun test tests/spatial-index-bench.test.ts",format:"biome format --write .","format:check":"biome format .","vercel-build":"cosmos-export","repomix:lib":"repomix --ignore 'testing/**,**/TwoRouteHighDensitySolver/**,**/RouteStitchingSolver/**,solvers/CapacitySegmentPointOptimizer/CapacitySegmentPointOptimizer.ts' lib","bug-report":"bun run scripts/download-bug-report.ts","bug-report-with-test":"bun run scripts/create-bug-report-test.ts"},devDependencies:{"@biomejs/biome":"^1.9.4","@radix-ui/react-icons":"^1.3.2","@radix-ui/react-menubar":"^1.1.14","@react-hook/resize-observer":"^2.0.2","@resvg/resvg-js":"^2.6.2","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.46","@tscircuit/core":"^0.0.337","@tscircuit/math-utils":"^0.0.27","@types/bun":"^1.2.23","@types/fast-json-stable-stringify":"^2.1.2","@types/object-hash":"^3.0.6","@types/rbush":"^4.0.0","@types/react":"^19.0.8","@types/react-dom":"^19.0.3","@vercel/node":"^5.1.7","@vitejs/plugin-react":"^4.3.4","circuit-json-to-connectivity-map":"^0.0.19","circuit-to-svg":"^0.0.220",clsx:"^2.1.1",flatbush:"^4.4.0","graphics-debug":"^0.0.44","looks-same":"9",rbush:"^4.0.1",react:"18","react-cosmos":"^6.2.3","react-cosmos-plugin-vite":"^6.2.0","react-dom":"18","react-konva":"18",recharts:"^2.15.1","tailwind-merge":"^3.2.0",terser:"^5.43.1",tsup:"^8.3.6",typescript:"^5.9.3","use-mouse-matrix-transform":"^1.3.0",vite:"^6.0.11","vite-tsconfig-paths":"^5.1.4"},dependencies:{"fast-json-stable-stringify":"^2.1.0","object-hash":"^3.0.0"}};vt();ji();ke();var N4=Xt(Mr(),1);vt();var BH=Xt(Sn(),1);var bT={};il(bT,{AssignableViaAutoroutingPipelineSolver:()=>Tgt,AutoroutingPipelineSolver:()=>dj,CapacityMeshSolver:()=>xgt,InMemoryCache:()=>W$,LocalStorageCache:()=>Z$,calculateOptimalCapacityDepth:()=>mT,convertSrjToGraphicsObject:()=>zf,getGlobalInMemoryCache:()=>hh,getGlobalLocalStorageCache:()=>K$,getTunedTotalCapacity1:()=>zr,setupGlobalCaches:()=>Ff});var q$=Xt(pb(),1),aj=Xt(pb(),1),uj=Xt(pb(),1);var Wl=(...e)=>{let t={points:[],lines:[],circles:[],rects:[]};return e.forEach((n,i)=>{n&&(n.lines&&(t.lines=[...t.lines||[],...n.lines.map(o=>({...o,step:i}))]),n.points&&(t.points=[...t.points||[],...n.points.map(o=>({...o,step:i}))]),n.circles&&(t.circles=[...t.circles||[],...n.circles.map(o=>({...o,step:i}))]),n.rects&&(t.rects=[...t.rects||[],...n.rects.map(o=>({...o,step:i}))]))}),t},Ke=class{constructor(){P(this,"MAX_ITERATIONS",1e3);P(this,"solved",!1);P(this,"failed",!1);P(this,"iterations",0);P(this,"progress",0);P(this,"error",null);P(this,"activeSubSolver");P(this,"failedSubSolvers");P(this,"timeToSolve");P(this,"stats",{});P(this,"cacheHit");P(this,"cacheKey");P(this,"cacheToSolveSpaceTransform")}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.constructor.name} error: ${e}`,console.error(this.error),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`,console.error(this.error),this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){let e=Date.now();for(;!this.solved&&!this.failed;)this.step();let t=Date.now();this.timeToSolve=t-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function o$(e){let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,maxX:e.center.x+t,minY:e.center.y-n,maxY:e.center.y+n}}function sc(e,t,n){return Math.max(t,Math.min(n,e))}function Si(e,t,n,i){let o=hb(e,t,n),r=hb(e,t,i),s=hb(n,i,e),a=hb(n,i,t);return o!==r&&s!==a||!(o!==0||!db(e,n,t))||!(r!==0||!db(e,i,t))||!(s!==0||!db(n,e,i))||!(a!==0||!db(n,t,i))}function hb(e,t,n){let i=(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y);return i===0?0:i>0?1:2}function db(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function Qi(e,t,n){let i=(n.x-t.x)**2+(n.y-t.y)**2;if(i===0)return Wt(e,t);let o=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/i;return o=Math.max(0,Math.min(1,o)),Wt(e,{x:t.x+o*(n.x-t.x),y:t.y+o*(n.y-t.y)})}function Wt(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}function k$(e,t,n,i){let o=t.x-e.x,r=t.y-e.y,s=i.x-n.x,a=i.y-n.y,c=e.x-n.x,l=e.y-n.y,u=o*a-r*s;if(Math.abs(u)<1e-10)return null;let h=(l*s-c*a)/u,d=(o*l-r*c)/u,_=1e-9;return h>=-1e-9&&h<=1+_&&d>=-1e-9&&d<=1+_?{x:e.x+h*o,y:e.y+h*r}:null}function r$(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}var A$=e=>{if("minX"in e)return e;let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,minY:e.center.y-n,maxX:e.center.x+t,maxY:e.center.y+n}},fT=e=>[{x:e.minX,y:e.minY},{x:e.maxX,y:e.minY},{x:e.maxX,y:e.maxY},{x:e.minX,y:e.maxY}],R$=e=>{let t=[];for(let n=0;n<e.length;n++){let i=e[n],o=e[(n+1)%e.length];t.push([i,o])}return t},qyt=(e,t,n)=>{let i=(e.y-t.y)*(n.x-t.x)-(e.x-t.x)*(n.y-t.y);if(Math.abs(i)>1e-9)return!1;let o=(e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y);return o<0?!1:!(o>(n.x-t.x)**2+(n.y-t.y)**2)},O$=(e,t)=>{if(t.length<3)return!1;let n=R$(t);for(let[o,r]of n)if(qyt(e,o,r))return!0;let i=!1;for(let o=0,r=t.length-1;o<t.length;r=o++){let s=t[o].x,a=t[o].y,c=t[r].x,l=t[r].y;a>e.y!=l>e.y&&e.x<(c-s)*(e.y-a)/(l-a)+s&&(i=!i)}return i},L$=(e,t)=>{let n=fT(e),i=[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]],o=R$(t);for(let[r,s]of o)for(let[a,c]of i)if(Si(r,s,a,c))return!0;return!1},iT=(e,t)=>((n,i)=>!(i.length<3)&&(!!i.some(o=>((r,s)=>r.x>=s.minX&&r.x<=s.maxX&&r.y>=s.minY&&r.y<=s.maxY)(o,n))||!!fT(n).some(o=>O$(o,i))||L$(n,i)))(A$(e),t),F$=(e,t)=>((n,i)=>!(i.length<3)&&!!fT(n).every(o=>O$(o,i))&&!L$(n,i))(A$(e),t);function oT(e,t,n,i){if(e.x===t.x&&e.y===t.y)return Qi(e,n,i);if(n.x===i.x&&n.y===i.y)return Qi(n,e,t);if(Si(e,t,n,i))return 0;let o=[Qi(e,n,i),Qi(t,n,i),Qi(n,e,t),Qi(i,e,t)];return Math.min(...o)}function z$(e,t,n){let i=n.width/2,o=n.height/2;return(function(r,s,a){let c={x:a.minX,y:a.minY},l={x:a.maxX,y:a.minY},u={x:a.minX,y:a.maxY},h={x:a.maxX,y:a.maxY};if(Si(r,s,c,l)||Si(r,s,l,h)||Si(r,s,h,u)||Si(r,s,u,c)||r.x>=a.minX&&r.x<=a.maxX&&r.y>=a.minY&&r.y<=a.maxY&&s.x>=a.minX&&s.x<=a.maxX&&s.y>=a.minY&&s.y<=a.maxY)return 0;let d=[Qi(c,r,s),Qi(l,r,s),Qi(u,r,s),Qi(h,r,s)];if(r.x>=a.minX&&r.x<=a.maxX&&r.y>=a.minY&&r.y<=a.maxY||s.x>=a.minX&&s.x<=a.maxX&&s.y>=a.minY&&s.y<=a.maxY)return 0;if(r.x<a.minX||r.x>a.maxX||r.y<a.minY||r.y>a.maxY){let _=sc(r.x,a.minX,a.maxX),y=sc(r.y,a.minY,a.maxY);d.push(Wt(r,{x:_,y}))}if(s.x<a.minX||s.x>a.maxX||s.y<a.minY||s.y>a.maxY){let _=sc(s.x,a.minX,a.maxX),y=sc(s.y,a.minY,a.maxY);d.push(Wt(s,{x:_,y}))}return Math.min(...d)})(e,t,{minX:n.center.x-i,maxX:n.center.x+i,minY:n.center.y-o,maxY:n.center.y+o})}function ah(e,t,n){let i=n.x-t.x,o=n.y-t.y,r=i*i+o*o;if(r===0)return{x:t.x,y:t.y};let s=((e.x-t.x)*i+(e.y-t.y)*o)/r;return s=Math.max(0,Math.min(1,s)),{x:t.x+s*i,y:t.y+s*o}}function Io(){return Io=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},Io.apply(null,arguments)}function Cb(e,t){return(Cb=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n})(e,t)}function D$(e){return(D$=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(e)}function $$(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return($$=function(){return!!e})()}function rT(e){var t=typeof Map=="function"?new Map:void 0;return rT=function(n){if(n===null||!(function(o){try{return Function.toString.call(o).indexOf("[native code]")!==-1}catch{return typeof o=="function"}})(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(t!==void 0){if(t.has(n))return t.get(n);t.set(n,i)}function i(){return(function(o,r,s){if($$())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,r);var c=new(o.bind.apply(o,a));return s&&Cb(c,s.prototype),c})(n,arguments,D$(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Cb(i,n)},rT(e)}var Po=(function(e){var t,n;function i(o){var r;if(1)r=e.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+o+" for more information.")||this;else for(var s,a,c;c<s;c++);return(function(l){if(l===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return l})(r)}return n=e,(t=i).prototype=Object.create(n.prototype),t.prototype.constructor=t,Cb(t,n),i})(rT(Error));function s$(e,t){return e.substr(-t.length)===t}var Wyt=/^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;function a$(e){return typeof e!="string"?e:e.match(Wyt)?parseFloat(e):e}var c$=function(e){return function(t,n){n===void 0&&(n="16px");var i=t,o=n;if(typeof t=="string"){if(!s$(t,"px"))throw new Po(69,e,t);i=a$(t)}if(typeof n=="string"){if(!s$(n,"px"))throw new Po(70,e,n);o=a$(n)}if(typeof i=="string")throw new Po(71,t,e);if(typeof o=="string")throw new Po(72,n,e);return""+i/o+e}};c$("em"),c$("rem");function GI(e){return Math.round(255*e)}function Zyt(e,t,n){return GI(e)+","+GI(t)+","+GI(n)}function Rf(e,t,n,i){if(i===void 0&&(i=Zyt),t===0)return i(n,n,n);var o=(e%360+360)%360/60,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o%2-1)),a=0,c=0,l=0;o>=0&&o<1?(a=r,c=s):o>=1&&o<2?(a=s,c=r):o>=2&&o<3?(c=r,l=s):o>=3&&o<4?(c=s,l=r):o>=4&&o<5?(a=s,l=r):o>=5&&o<6&&(a=r,l=s);var u=n-r/2;return i(a+u,c+u,l+u)}var l$={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},Kyt=/^#[a-fA-F0-9]{6}$/,Jyt=/^#[a-fA-F0-9]{8}$/,Qyt=/^#[a-fA-F0-9]{3}$/,t0t=/^#[a-fA-F0-9]{4}$/,UI=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,e0t=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,n0t=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,i0t=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function ch(e){if(typeof e!="string")throw new Po(3);var t=(function(d){if(typeof d!="string")return d;var _=d.toLowerCase();return l$[_]?"#"+l$[_]:d})(e);if(t.match(Kyt))return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16)};if(t.match(Jyt)){var n=parseFloat((parseInt(""+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16),alpha:n}}if(t.match(Qyt))return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16)};if(t.match(t0t)){var i=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:i}}var o=UI.exec(t);if(o)return{red:parseInt(""+o[1],10),green:parseInt(""+o[2],10),blue:parseInt(""+o[3],10)};var r=e0t.exec(t.substring(0,50));if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10),alpha:parseFloat(""+r[4])>1?parseFloat(""+r[4])/100:parseFloat(""+r[4])};var s=n0t.exec(t);if(s){var a="rgb("+Rf(parseInt(""+s[1],10),parseInt(""+s[2],10)/100,parseInt(""+s[3],10)/100)+")",c=UI.exec(a);if(!c)throw new Po(4,t,a);return{red:parseInt(""+c[1],10),green:parseInt(""+c[2],10),blue:parseInt(""+c[3],10)}}var l=i0t.exec(t.substring(0,50));if(l){var u="rgb("+Rf(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",h=UI.exec(u);if(!h)throw new Po(4,t,u);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+l[4])>1?parseFloat(""+l[4])/100:parseFloat(""+l[4])}}throw new Po(5)}function ac(e){return(function(t){var n,i=t.red/255,o=t.green/255,r=t.blue/255,s=Math.max(i,o,r),a=Math.min(i,o,r),c=(s+a)/2;if(s===a)return t.alpha!==void 0?{hue:0,saturation:0,lightness:c,alpha:t.alpha}:{hue:0,saturation:0,lightness:c};var l=s-a,u=c>.5?l/(2-s-a):l/(s+a);switch(s){case i:n=(o-r)/l+(o<r?6:0);break;case o:n=(r-i)/l+2;break;default:n=(i-o)/l+4}return n*=60,t.alpha!==void 0?{hue:n,saturation:u,lightness:c,alpha:t.alpha}:{hue:n,saturation:u,lightness:c}})(ch(e))}var sT=function(e){return e.length===7&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?"#"+e[1]+e[3]+e[5]:e};function Ul(e){var t=e.toString(16);return t.length===1?"0"+t:t}function qI(e){return Ul(Math.round(255*e))}function o0t(e,t,n){return sT("#"+qI(e)+qI(t)+qI(n))}function fb(e,t,n){return Rf(e,t,n,o0t)}function aT(e,t,n){if(typeof e=="number"&&typeof t=="number"&&typeof n=="number")return sT("#"+Ul(e)+Ul(t)+Ul(n));if(typeof e=="object"&&t===void 0&&n===void 0)return sT("#"+Ul(e.red)+Ul(e.green)+Ul(e.blue));throw new Po(6)}function Fb(e,t,n,i){if(typeof e=="string"&&typeof t=="number"){var o=ch(e);return"rgba("+o.red+","+o.green+","+o.blue+","+t+")"}if(typeof e=="number"&&typeof t=="number"&&typeof n=="number"&&typeof i=="number")return i>=1?aT(e,t,n):"rgba("+e+","+t+","+n+","+i+")";if(typeof e=="object"&&t===void 0&&n===void 0&&i===void 0)return e.alpha>=1?aT(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new Po(7)}function cc(e){if(typeof e!="object")throw new Po(8);if((function(t){return typeof t.red=="number"&&typeof t.green=="number"&&typeof t.blue=="number"&&typeof t.alpha=="number"})(e))return Fb(e);if((function(t){return typeof t.red=="number"&&typeof t.green=="number"&&typeof t.blue=="number"&&(typeof t.alpha!="number"||t.alpha===void 0)})(e))return aT(e);if((function(t){return typeof t.hue=="number"&&typeof t.saturation=="number"&&typeof t.lightness=="number"&&typeof t.alpha=="number"})(e))return(function(t,n,i,o){if(typeof t=="number"&&typeof n=="number"&&typeof i=="number"&&typeof o=="number")return o>=1?fb(t,n,i):"rgba("+Rf(t,n,i)+","+o+")";if(typeof t=="object"&&n===void 0&&i===void 0&&o===void 0)return t.alpha>=1?fb(t.hue,t.saturation,t.lightness):"rgba("+Rf(t.hue,t.saturation,t.lightness)+","+t.alpha+")";throw new Po(2)})(e);if((function(t){return typeof t.hue=="number"&&typeof t.saturation=="number"&&typeof t.lightness=="number"&&(typeof t.alpha!="number"||t.alpha===void 0)})(e))return(function(t,n,i){if(typeof t=="number"&&typeof n=="number"&&typeof i=="number")return fb(t,n,i);if(typeof t=="object"&&n===void 0&&i===void 0)return fb(t.hue,t.saturation,t.lightness);throw new Po(1)})(e);throw new Po(8)}function j$(e,t,n){return function(){var i=n.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):j$(e,t,i)}}function Bo(e){return j$(e,e.length,[])}Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{hue:n.hue+parseFloat(e)}))});function ph(e,t,n){return Math.max(e,Math.min(t,n))}Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{lightness:ph(0,1,n.lightness-parseFloat(e))}))});Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{saturation:ph(0,1,n.saturation-parseFloat(e))}))});Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{lightness:ph(0,1,n.lightness+parseFloat(e))}))});var B$=Bo(function(e,t,n){if(t==="transparent")return n;if(n==="transparent")return t;if(e===0)return n;var i=ch(t),o=Io({},i,{alpha:typeof i.alpha=="number"?i.alpha:1}),r=ch(n),s=Io({},r,{alpha:typeof r.alpha=="number"?r.alpha:1}),a=o.alpha-s.alpha,c=2*parseFloat(e)-1,l=((c*a===-1?c:c+a)/(1+c*a)+1)/2,u=1-l;return Fb({red:Math.floor(o.red*l+s.red*u),green:Math.floor(o.green*l+s.green*u),blue:Math.floor(o.blue*l+s.blue*u),alpha:o.alpha*parseFloat(e)+s.alpha*(1-parseFloat(e))})});Bo(function(e,t){if(t==="transparent")return t;var n=ch(t);return Fb(Io({},n,{alpha:ph(0,1,(100*(typeof n.alpha=="number"?n.alpha:1)+100*parseFloat(e))/100)}))});Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{saturation:ph(0,1,n.saturation+parseFloat(e))}))});Bo(function(e,t){return t==="transparent"?t:cc(Io({},ac(t),{hue:parseFloat(e)}))});Bo(function(e,t){return t==="transparent"?t:cc(Io({},ac(t),{lightness:parseFloat(e)}))});Bo(function(e,t){return t==="transparent"?t:cc(Io({},ac(t),{saturation:parseFloat(e)}))});Bo(function(e,t){return t==="transparent"?t:B$(parseFloat(e),"rgb(0, 0, 0)",t)});Bo(function(e,t){return t==="transparent"?t:B$(parseFloat(e),"rgb(255, 255, 255)",t)});var r0t=Bo(function(e,t){if(t==="transparent")return t;var n=ch(t);return Fb(Io({},n,{alpha:ph(0,1,+(100*(typeof n.alpha=="number"?n.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))}),u$=["blue","orange","purple","cyan","magenta","yellowgreen","darkgoldenrod","deeppink"],Of=(e,t)=>{let n={};for(let i=0;i<e.connections.length;i++){let o=e.connections[i],r=t?.getNetConnectedToId(o.name);r&&!n[r]&&(n[r]=`hsl(${300*i/e.connections.length}, 100%, 50%)`),n[o.name]=(r?n[r]:null)??`hsl(${340*i/e.connections.length}, 100%, 50%)`}return n},$n=(e,t)=>{try{return r0t(t,e)}catch(n){return console.error(n),e}},Zl=(e,t)=>e==="top"?0:e==="bottom"?t-1:parseInt(e.slice(5)),zr=(e,t=1)=>{let n=(("width"in e?e.width:e)/.5/2)**1.1*t;return e.availableZ?.length===1&&n>1?1:n},mT=(e,t=.5,n=16)=>{let i=0,o=e;for(;i<n&&!(zr({width:o})<=t);)o/=2,i++;return Math.max(1,i)};function Y$(e,t,n=0,i=e.length-1,o=s0t){for(;i>n;){if(i-n>600){let c=i-n+1,l=t-n+1,u=Math.log(c),h=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*h*(c-h)/c)*(l-c/2<0?-1:1);Y$(e,t,Math.max(n,Math.floor(t-l*h/c+d)),Math.min(i,Math.floor(t+(c-l)*h/c+d)),o)}let r=e[t],s=n,a=i;for(Tf(e,n,t),o(e[i],r)>0&&Tf(e,n,i);s<a;){for(Tf(e,s,a),s++,a--;o(e[s],r)<0;)s++;for(;o(e[a],r)>0;)a--}o(e[n],r)===0?Tf(e,n,a):(a++,Tf(e,a,i)),a<=t&&(n=a+1),t<=a&&(i=a-1)}}function Tf(e,t,n){let i=e[t];e[t]=e[n],e[n]=i}function s0t(e,t){return e<t?-1:e>t?1:0}var a0t=class{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data,n=[];if(!_b(e,t))return n;let i=this.toBBox,o=[];for(;t;){for(let r=0;r<t.children.length;r++){let s=t.children[r],a=t.leaf?i(s):s;_b(e,a)&&(t.leaf?n.push(s):ZI(e,a)?this._all(s,n):o.push(s))}t=o.pop()}return n}collides(e){let t=this.data;if(!_b(e,t))return!1;let n=[];for(;t;){for(let i=0;i<t.children.length;i++){let o=t.children[i],r=t.leaf?this.toBBox(o):o;if(_b(e,r)){if(t.leaf||ZI(e,r))return!0;n.push(o)}}t=n.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let n=0;n<e.length;n++)this.insert(e[n]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){let n=this.data;this.data=t,t=n}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=rh([]),this}remove(e,t){if(!e)return this;let n=this.data,i=this.toBBox(e),o=[],r=[],s,a,c;for(;n||o.length;){if(n||(n=o.pop(),a=o[o.length-1],s=r.pop(),c=!0),n.leaf){let l=c0t(e,n.children,t);if(l!==-1)return n.children.splice(l,1),o.push(n),this._condense(o),this}c||n.leaf||!ZI(n,i)?a?(s++,n=a.children[s],c=!1):n=null:(o.push(n),r.push(s),s=0,a=n,n=n.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){let n=[];for(;e;)e.leaf?t.push(...e.children):n.push(...e.children),e=n.pop();return t}_build(e,t,n,i){let o=n-t+1,r,s=this._maxEntries;if(o<=s)return r=rh(e.slice(t,n+1)),oh(r,this.toBBox),r;i||(i=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/Math.pow(s,i-1))),r=rh([]),r.leaf=!1,r.height=i;let a=Math.ceil(o/s),c=a*Math.ceil(Math.sqrt(s));p$(e,t,n,c,this.compareMinX);for(let l=t;l<=n;l+=c){let u=Math.min(l+c-1,n);p$(e,l,u,a,this.compareMinY);for(let h=l;h<=u;h+=a){let d=Math.min(h+a-1,u);r.children.push(this._build(e,h,d,i-1))}}return oh(r,this.toBBox),r}_chooseSubtree(e,t,n,i){for(;i.push(t),!t.leaf&&i.length-1!==n;){let o,r=1/0,s=1/0;for(let a=0;a<t.children.length;a++){let c=t.children[a],l=WI(c),u=p0t(e,c)-l;u<s?(s=u,r=l<r?l:r,o=c):u===s&&l<r&&(r=l,o=c)}t=o||t.children[0]}return t}_insert(e,t,n){let i=n?e:this.toBBox(e),o=[],r=this._chooseSubtree(i,this.data,t,o);for(r.children.push(e),Cf(r,i);t>=0&&o[t].children.length>this._maxEntries;)this._split(o,t),t--;this._adjustParentBBoxes(i,o,t)}_split(e,t){let n=e[t],i=n.children.length,o=this._minEntries;this._chooseSplitAxis(n,o,i);let r=this._chooseSplitIndex(n,o,i),s=rh(n.children.splice(r,n.children.length-r));s.height=n.height,s.leaf=n.leaf,oh(n,this.toBBox),oh(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)}_splitRoot(e,t){this.data=rh([e,t]),this.data.height=e.height+1,this.data.leaf=!1,oh(this.data,this.toBBox)}_chooseSplitIndex(e,t,n){let i,o=1/0,r=1/0;for(let s=t;s<=n-t;s++){let a=Mf(e,0,s,this.toBBox),c=Mf(e,s,n,this.toBBox),l=h0t(a,c),u=WI(a)+WI(c);l<o?(o=l,i=s,r=u<r?u:r):l===o&&u<r&&(r=u,i=s)}return i||n-t}_chooseSplitAxis(e,t,n){let i=e.leaf?this.compareMinX:l0t,o=e.leaf?this.compareMinY:u0t;this._allDistMargin(e,t,n,i)<this._allDistMargin(e,t,n,o)&&e.children.sort(i)}_allDistMargin(e,t,n,i){e.children.sort(i);let o=this.toBBox,r=Mf(e,0,t,o),s=Mf(e,n-t,n,o),a=mb(r)+mb(s);for(let c=t;c<n-t;c++){let l=e.children[c];Cf(r,e.leaf?o(l):l),a+=mb(r)}for(let c=n-t-1;c>=t;c--){let l=e.children[c];Cf(s,e.leaf?o(l):l),a+=mb(s)}return a}_adjustParentBBoxes(e,t,n){for(let i=n;i>=0;i--)Cf(t[i],e)}_condense(e){for(let t,n=e.length-1;n>=0;n--)e[n].children.length===0?n>0?(t=e[n-1].children,t.splice(t.indexOf(e[n]),1)):this.clear():oh(e[n],this.toBBox)}};function c0t(e,t,n){if(!n)return t.indexOf(e);for(let i=0;i<t.length;i++)if(n(e,t[i]))return i;return-1}function oh(e,t){Mf(e,0,e.children.length,t,e)}function Mf(e,t,n,i,o){o||(o=rh(null)),o.minX=1/0,o.minY=1/0,o.maxX=-1/0,o.maxY=-1/0;for(let r=t;r<n;r++){let s=e.children[r];Cf(o,e.leaf?i(s):s)}return o}function Cf(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function l0t(e,t){return e.minX-t.minX}function u0t(e,t){return e.minY-t.minY}function WI(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function mb(e){return e.maxX-e.minX+(e.maxY-e.minY)}function p0t(e,t){return(Math.max(t.maxX,e.maxX)-Math.min(t.minX,e.minX))*(Math.max(t.maxY,e.maxY)-Math.min(t.minY,e.minY))}function h0t(e,t){let n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),o=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return Math.max(0,o-n)*Math.max(0,r-i)}function ZI(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function _b(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function rh(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function p$(e,t,n,i,o){let r=[t,n];for(;r.length;){if((n=r.pop())-(t=r.pop())<=i)continue;let s=t+Math.ceil((n-t)/i/2)*i;Y$(e,s,t,n,o),r.push(t,s,s,n)}}var h$=class{constructor(e=9){P(this,"tree");this.tree=new a0t(e)}insert(e,t,n,i,o){this.tree.insert({minX:t,minY:n,maxX:i,maxY:o,data:e})}bulkLoad(e){let t=e.map(({item:n,minX:i,minY:o,maxX:r,maxY:s})=>({minX:i,minY:o,maxX:r,maxY:s,data:n}));this.tree.load(t)}search(e,t,n,i){return this.tree.search({minX:e,minY:t,maxX:n,maxY:i}).map(o=>o.data)}clear(){this.tree.clear()}},d0t=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(e,t){let n=this.length++;for(;n>0;){let i=n-1>>1,o=this.values[i];if(t>=o)break;this.ids[n]=this.ids[i],this.values[n]=o,n=i}this.ids[n]=e,this.values[n]=t}pop(){if(this.length===0)return;let e=this.ids,t=this.values,n=e[0],i=--this.length;if(i>0){let o=e[i],r=t[i],s=0,a=i>>1;for(;s<a;){let c=1+(s<<1),l=c+1,u=c+(+(l<i)&+(t[l]<t[c]));if(t[u]>=r)break;e[s]=e[u],t[s]=t[u],s=u}e[s]=o,t[s]=r}return n}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){this.ids.length=this.values.length=this.length}},d$=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],f$=class X${static from(t,n=0){if(n%8!=0)throw new Error("byteOffset must be 8-byte aligned.");if(!t||t.byteLength===void 0||t.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[i,o]=new Uint8Array(t,n+0,2);if(i!==251)throw new Error("Data does not appear to be in a Flatbush format.");let r=o>>4;if(r!==3)throw new Error(`Got v${r} data when expected v3.`);let s=d$[15&o];if(!s)throw new Error("Unrecognized array type.");let[a]=new Uint16Array(t,n+2,1),[c]=new Uint32Array(t,n+4,1);return new X$(c,a,s,void 0,t,n)}constructor(t,n=16,i=Float64Array,o=ArrayBuffer,r,s=0){if(t===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(t)||t<=0)throw new Error(`Unexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+n,2),65535),this.byteOffset=s;let a=t,c=a;this._levelBounds=[4*a];do a=Math.ceil(a/this.nodeSize),c+=a,this._levelBounds.push(4*c);while(a!==1);this.ArrayType=i,this.IndexArrayType=c<16384?Uint16Array:Uint32Array;let l=d$.indexOf(i),u=4*c*i.BYTES_PER_ELEMENT;if(l<0)throw new Error(`Unexpected typed array class: ${i}.`);if(r)this.data=r,this._boxes=new i(r,s+8,4*c),this._indices=new this.IndexArrayType(r,s+8+u,c),this._pos=4*c,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1];else{let h=this.data=new o(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(h,8,4*c),this._indices=new this.IndexArrayType(h,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(h,0,2).set([251,48+l]),new Uint16Array(h,2,1)[0]=n,new Uint32Array(h,4,1)[0]=t}this._queue=new d0t}add(t,n,i=t,o=n){let r=this._pos>>2,s=this._boxes;return this._indices[r]=r,s[this._pos++]=t,s[this._pos++]=n,s[this._pos++]=i,s[this._pos++]=o,t<this.minX&&(this.minX=t),n<this.minY&&(this.minY=n),i>this.maxX&&(this.maxX=i),o>this.maxY&&(this.maxY=o),r}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let t=this._boxes;if(this.numItems<=this.nodeSize)return t[this._pos++]=this.minX,t[this._pos++]=this.minY,t[this._pos++]=this.maxX,void(t[this._pos++]=this.maxY);let n=this.maxX-this.minX||1,i=this.maxY-this.minY||1,o=new Uint32Array(this.numItems);for(let r=0,s=0;r<this.numItems;r++){let a=t[s++],c=t[s++],l=t[s++],u=t[s++],h=Math.floor(65535*((a+l)/2-this.minX)/n),d=Math.floor(65535*((c+u)/2-this.minY)/i);o[r]=m0t(h,d)}cT(o,t,this._indices,0,this.numItems-1,this.nodeSize);for(let r=0,s=0;r<this._levelBounds.length-1;r++){let a=this._levelBounds[r];for(;s<a;){let c=s,l=t[s++],u=t[s++],h=t[s++],d=t[s++];for(let _=1;_<this.nodeSize&&s<a;_++)l=Math.min(l,t[s++]),u=Math.min(u,t[s++]),h=Math.max(h,t[s++]),d=Math.max(d,t[s++]);this._indices[this._pos>>2]=c,t[this._pos++]=l,t[this._pos++]=u,t[this._pos++]=h,t[this._pos++]=d}}}search(t,n,i,o,r){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=[],c=[];for(;s!==void 0;){let l=Math.min(s+4*this.nodeSize,m$(s,this._levelBounds));for(let u=s;u<l;u+=4){let h=this._boxes[u];if(i<h)continue;let d=this._boxes[u+1];if(o<d)continue;let _=this._boxes[u+2];if(t>_)continue;let y=this._boxes[u+3];if(n>y)continue;let g=0|this._indices[u>>2];s>=4*this.numItems?a.push(g):(r===void 0||r(g,h,d,_,y))&&c.push(g)}s=a.pop()}return c}neighbors(t,n,i=1/0,o=1/0,r){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=this._queue,c=[],l=o*o;t:for(;s!==void 0;){let u=Math.min(s+4*this.nodeSize,m$(s,this._levelBounds));for(let h=s;h<u;h+=4){let d=0|this._indices[h>>2],_=this._boxes[h],y=this._boxes[h+1],g=this._boxes[h+2],x=this._boxes[h+3],w=t<_?_-t:t>g?t-g:0,S=n<y?y-n:n>x?n-x:0,T=w*w+S*S;T>l||(s>=4*this.numItems?a.push(d<<1,T):(r===void 0||r(d))&&a.push(1+(d<<1),T))}for(;a.length&&1&a.peek();)if(a.peekValue()>l||(c.push(a.pop()>>1),c.length===i))break t;s=a.length?a.pop()>>1:void 0}return a.clear(),c}};function m$(e,t){let n=0,i=t.length-1;for(;n<i;){let o=n+i>>1;t[o]>e?i=o:n=o+1}return t[n]}function cT(e,t,n,i,o,r){if(Math.floor(i/r)>=Math.floor(o/r))return;let s=e[i],a=e[i+o>>1],c=e[o],l=c,u=Math.max(s,a);c>u?l=u:u===s?l=Math.max(a,c):u===a&&(l=Math.max(s,c));let h=i-1,d=o+1;for(;;){do h++;while(e[h]<l);do d--;while(e[d]>l);if(h>=d)break;f0t(e,t,n,h,d)}cT(e,t,n,i,d,r),cT(e,t,n,d+1,o,r)}function f0t(e,t,n,i,o){let r=e[i];e[i]=e[o],e[o]=r;let s=4*i,a=4*o,c=t[s],l=t[s+1],u=t[s+2],h=t[s+3];t[s]=t[a],t[s+1]=t[a+1],t[s+2]=t[a+2],t[s+3]=t[a+3],t[a]=c,t[a+1]=l,t[a+2]=u,t[a+3]=h;let d=n[i];n[i]=n[o],n[o]=d}function m0t(e,t){let n=e^t,i=65535^n,o=65535^(e|t),r=e&(65535^t),s=n|i>>1,a=n>>1^n,c=o>>1^i&r>>1^o,l=n&o>>1^r>>1^r;n=s,i=a,o=c,r=l,s=n&n>>2^i&i>>2,a=n&i>>2^i&(n^i)>>2,c^=n&o>>2^i&r>>2,l^=i&o>>2^(n^i)&r>>2,n=s,i=a,o=c,r=l,s=n&n>>4^i&i>>4,a=n&i>>4^i&(n^i)>>4,c^=n&o>>4^i&r>>4,l^=i&o>>4^(n^i)&r>>4,n=s,i=a,o=c,r=l,c^=n&o>>8^i&r>>8,l^=i&o>>8^(n^i)&r>>8,n=c^c>>1,i=l^l>>1;let u=e^t,h=i|65535^(u|n);return u=16711935&(u|u<<8),u=252645135&(u|u<<4),u=858993459&(u|u<<2),u=1431655765&(u|u<<1),h=16711935&(h|h<<8),h=252645135&(h|h<<4),h=858993459&(h|h<<2),h=1431655765&(h|h<<1),(h<<1|u)>>>0}var _0t=class{constructor(e){P(this,"index");P(this,"items",[]);P(this,"currentIndex",0);P(this,"capacity");this.capacity=Math.max(1,e),this.index=new f$(this.capacity)}insert(e,t,n,i,o){if(this.currentIndex>=this.index.numItems)throw new Error("Exceeded initial capacity");this.items[this.currentIndex]=e,this.index.add(t,n,i,o),this.currentIndex++}finish(){this.index.finish()}search(e,t,n,i){return this.index.search(e,t,n,i).map(o=>this.items[o]||null).filter(Boolean)}clear(){this.items=[],this.currentIndex=0,this.index=new f$(this.capacity)}},V$=class{constructor(e="native",t=[]){P(this,"idx");P(this,"storage",[]);e==="flatbush"?t.length===0?(this.idx=new h$,e="rbush"):this.idx=new _0t(t.length):this.idx=e==="rbush"?new h$:new class{constructor(){P(this,"shi",new y0t(t))}insert(n){}search(n,i,o,r){let s=(n+o)/2,a=(i+r)/2,c=o-n,l=r-i;return this.shi.getNodesInArea(s,a,c,l)}clear(){}},t.forEach(n=>this.insert(n)),e==="flatbush"&&t.length>0&&this.idx.finish?.()}insert(e){this.storage.push(e),this.idx.insert(e,e.center.x-e.width/2,e.center.y-e.height/2,e.center.x+e.width/2,e.center.y+e.height/2)}search(e){return this.idx.search(e.minX,e.minY,e.maxX,e.maxY)}searchArea(e,t,n,i){return this.search({minX:e-n/2,minY:t-i/2,maxX:e+n/2,maxY:t+i/2})}},y0t=class{constructor(e){P(this,"buckets");P(this,"CELL_SIZE",.4);this.obstacles=e,this.buckets=new Map;for(let t=0;t<e.length;t++){let n=e[t],i=n.center.x-n.width/2,o=n.center.y-n.height/2,r=n.center.x+n.width/2,s=n.center.y+n.height/2;for(let a=i;a<=r;a+=this.CELL_SIZE)for(let c=o;c<=s;c+=this.CELL_SIZE){let l=this.getBucketKey(a,c),u=this.buckets.get(l);u?u.push([n,t]):this.buckets.set(l,[[n,t]])}}}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getNodesInArea(e,t,n,i){let o=[],r=new Set,s=t-i/2,a=e+n/2,c=t+i/2;for(let l=e-n/2;l<=a;l+=this.CELL_SIZE)for(let u=s;u<=c;u+=this.CELL_SIZE){let h=this.getBucketKey(l,u),d=this.buckets.get(h)||[];for(let _ of d)r.has(_[1])||(r.add(_[1]),o.push(_[0]))}return o}},g0t=class{constructor(e){P(this,"buckets");P(this,"CELL_SIZE",5);this.targets=e,this.buckets=new Map;for(let t=0;t<e.length;t++){let n=e[t],i=Math.floor(n.bounds.minX/this.CELL_SIZE)*this.CELL_SIZE,o=Math.floor(n.bounds.minY/this.CELL_SIZE)*this.CELL_SIZE,r=n.bounds.maxX,s=n.bounds.maxY;for(let a=i;a<=r;a+=this.CELL_SIZE)for(let c=o;c<=s;c+=this.CELL_SIZE){let l=this.getBucketKey(a,c),u=this.buckets.get(l);u?u.push([n,t]):this.buckets.set(l,[[n,t]])}}}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getTargetsInArea(e,t,n,i){let o=[],r=new Set,s=Math.floor((e-n/2)/this.CELL_SIZE)*this.CELL_SIZE,a=Math.floor((t-i/2)/this.CELL_SIZE)*this.CELL_SIZE,c=e+n/2,l=t+i/2;for(let u=s;u<=c;u+=this.CELL_SIZE)for(let h=a;h<=l;h+=this.CELL_SIZE){let d=this.getBucketKey(u,h),_=this.buckets.get(d)||[];for(let y of _)r.has(y[1])||(r.add(y[1]),o.push(y[0]))}return o}},b0t=class extends Ke{constructor(t,n={}){super();P(this,"unfinishedNodes");P(this,"finishedNodes");P(this,"nodeToXYOverlappingObstaclesMap");P(this,"layerCount");P(this,"outlinePolygon");P(this,"MAX_DEPTH",4);P(this,"targets");P(this,"targetTree");P(this,"obstacleTree");P(this,"_nextNodeCounter",0);this.srj=t,this.opts=n,this.MAX_DEPTH=n?.capacityDepth??this.MAX_DEPTH,this.MAX_ITERATIONS=1e5,this.layerCount=t.layerCount??2,this.outlinePolygon=t.outline&&t.outline.length>=3?t.outline:void 0;for(let s of t.obstacles)if(!s.zLayers){let a=[];for(let c of s.layers)a.push(Zl(c,t.layerCount));s.zLayers=a}let i={x:(t.bounds.minX+t.bounds.maxX)/2,y:(t.bounds.minY+t.bounds.maxY)/2},o={width:t.bounds.maxX-t.bounds.minX,height:t.bounds.maxY-t.bounds.minY},r=Math.max(o.width,o.height);this.unfinishedNodes=[{capacityMeshNodeId:this.getNextNodeId(),center:i,width:r,height:r,layer:"top",availableZ:Array.from({length:this.layerCount},(s,a)=>a),_depth:0,_containsTarget:!0,_containsObstacle:!0,_completelyInsideObstacle:!1}],this.finishedNodes=[],this.nodeToXYOverlappingObstaclesMap=new Map,this.obstacleTree=new V$("flatbush",this.srj.obstacles),this.targets=this.computeTargets(),this.targetTree=new g0t(this.targets)}computeTargets(){let t=[];for(let n of this.srj.connections)for(let i of n.pointsToConnect){let o=this.obstacleTree.searchArea(i.x,i.y,.01,.01).filter(a=>a.zLayers.some(c=>c===Zl(i.layer,this.layerCount))),r={minX:i.x-.005,minY:i.y-.005,maxX:i.x+.005,maxY:i.y+.005};o.length>0&&(r={minX:Math.min(...o.map(a=>a.center.x-a.width/2)),minY:Math.min(...o.map(a=>a.center.y-a.height/2)),maxX:Math.max(...o.map(a=>a.center.x+a.width/2)),maxY:Math.max(...o.map(a=>a.center.y+a.height/2))});let s={...i,connectionName:n.name,availableZ:[Zl(i.layer,this.layerCount)],bounds:r};t.push(s)}return t}getNodeBounds(t){let n=t.width/2,i=t.height/2;return{minX:t.center.x-n,maxX:t.center.x+n,minY:t.center.y-i,maxY:t.center.y+i}}getNodeRect(t){return{center:{x:t.center.x,y:t.center.y},width:t.width,height:t.height}}getNextNodeId(){return"cn"+this._nextNodeCounter++}getCapacityFromDepth(t){return(this.MAX_DEPTH-t+1)**2}getTargetIfNodeContainsTarget(t){let n=t.width>4*this.targetTree.CELL_SIZE?this.targets:this.targetTree.getTargetsInArea(t.center.x,t.center.y,t.width,t.height);for(let i of n)if(i.bounds.minX<=t.center.x+t.width/2&&i.bounds.maxX>=t.center.x-t.width/2&&i.bounds.minY<=t.center.y+t.height/2&&i.bounds.maxY>=t.center.y-t.height/2&&i.availableZ.some(o=>t.availableZ.includes(o)))return i;return null}getXYOverlappingObstacles(t){let n=this.nodeToXYOverlappingObstaclesMap.get(t.capacityMeshNodeId);if(n)return n;let i=[],o=this.getNodeBounds(t),r=o.minX,s=o.maxX,a=o.minY,c=o.maxY,l=t._parent?this.getXYOverlappingObstacles(t._parent):this.srj.obstacles;for(let u of l){let h=u.center.x-u.width/2,d=u.center.x+u.width/2,_=u.center.y-u.height/2,y=u.center.y+u.height/2;(s>=h&&r<=d&&c>=_&&a<=y||r>=h&&s<=d&&a>=_&&c<=y||h>=r&&d<=s&&_>=a&&y<=c)&&i.push(u)}return this.nodeToXYOverlappingObstaclesMap.set(t.capacityMeshNodeId,i),i}getXYZOverlappingObstacles(t){let n=this.getXYOverlappingObstacles(t),i=[];for(let o of n)t.availableZ.some(r=>o.zLayers.includes(r))&&i.push(o);return i}doesNodeOverlapObstacle(t){if(this.getXYZOverlappingObstacles(t).length>0)return!0;let n=this.getNodeBounds(t);if(this.outlinePolygon){let i=this.getNodeRect(t);if(!F$(i,this.outlinePolygon))return!0}return n.minX<this.srj.bounds.minX||n.maxX>this.srj.bounds.maxX||n.minY<this.srj.bounds.minY||n.maxY>this.srj.bounds.maxY}isNodeCompletelyInsideObstacle(t){let n=this.getXYZOverlappingObstacles(t),i=this.getNodeBounds(t);if(this.outlinePolygon){let o=this.getNodeRect(t);if(!iT(o,this.outlinePolygon))return!0}for(let o of n){let r=o.center.x-o.width/2,s=o.center.x+o.width/2,a=o.center.y-o.height/2,c=o.center.y+o.height/2;if(i.minX>=r&&i.maxX<=s&&i.minY>=a&&i.maxY<=c)return!0}return!1}getChildNodes(t){if(t._depth===this.MAX_DEPTH)return[];let n=[],i={width:t.width/2,height:t.height/2},o=[{x:t.center.x-i.width/2,y:t.center.y-i.height/2},{x:t.center.x+i.width/2,y:t.center.y-i.height/2},{x:t.center.x-i.width/2,y:t.center.y+i.height/2},{x:t.center.x+i.width/2,y:t.center.y+i.height/2}];for(let r of o){let s={capacityMeshNodeId:this.getNextNodeId(),center:r,width:i.width,height:i.height,layer:t.layer,availableZ:t.availableZ,_depth:(t._depth??0)+1,_parent:t};s._containsObstacle=this.doesNodeOverlapObstacle(s);let a=this.getTargetIfNodeContainsTarget(s);a&&(s._targetConnectionName=a.connectionName,s.availableZ=a.availableZ,s._containsTarget=!0),s._containsObstacle&&(s._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(s)),s._completelyInsideObstacle&&!s._containsTarget||n.push(s)}return n}shouldNodeBeXYSubdivided(t){return!(t._depth>=this.MAX_DEPTH)&&(!!t._containsTarget||!(!t._containsObstacle||t._completelyInsideObstacle))}_step(){let t=this.unfinishedNodes.pop();if(!t)return void(this.solved=!0);let n=this.getChildNodes(t),i=[],o=[];for(let r of n){let s=this.shouldNodeBeXYSubdivided(r);s?o.push(r):s||r._containsObstacle?!s&&r._containsTarget&&i.push(r):i.push(r)}this.unfinishedNodes.push(...o),this.finishedNodes.push(...i)}visualize(){let t={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Capacity Mesh Visualization"};if(this.outlinePolygon&&this.outlinePolygon.length>=2){let i=this.outlinePolygon.map(o=>({x:o.x,y:o.y}));i.push({...i[0]}),t.lines.push({points:i,strokeColor:"rgba(0, 136, 255, 0.95)",label:"outline"});for(let o of this.outlinePolygon)t.points.push({x:o.x,y:o.y,color:"rgba(0, 136, 255, 0.95)"})}for(let i of this.srj.obstacles)t.rects.push({center:i.center,width:i.width,height:i.height,fill:i.zLayers?.length===1&&i.zLayers?.includes(1)?"rgba(0,0,255,0.3)":"rgba(255,0,0,0.3)",stroke:"red",label:["obstacle",`z: ${i.zLayers.join(",")}`].join(`
162
162
  `)});let n=[...this.finishedNodes,...this.unfinishedNodes];for(let i of n){let o=Math.min(...i.availableZ),r=this.unfinishedNodes.length>0&&i===this.unfinishedNodes[this.unfinishedNodes.length-1];t.rects.push({center:{x:i.center.x+o*i.width*.05,y:i.center.y-o*i.width*.05},width:Math.max(i.width-2,.8*i.width),height:Math.max(i.height-2,.8*i.height),fill:i._containsObstacle?"rgba(255,0,0,0.1)":{"0,1":"rgba(0,0,0,0.1)",0:"rgba(0,200,200, 0.1)",1:"rgba(0,0,200, 0.1)"}[i.availableZ.join(",")]??"rgba(0,200,200,0.1)",stroke:r?"rgba(255,165,0,0.5)":void 0,label:[i.capacityMeshNodeId,`availableZ: ${i.availableZ.join(",")}`,`target? ${i._containsTarget??!1}`,`obs? ${i._containsObstacle??!1}`,`${i.width.toFixed(2)}x${i.height.toFixed(2)}`,`capacity: ${zr(i).toFixed(2)}`].join(`
163
163
  `)})}return t.rects.sort((i,o)=>i.center.y-o.center.y),this.srj.connections.forEach((i,o)=>{let r=u$[o%u$.length];for(let s of i.pointsToConnect)t.points.push({x:s.x,y:s.y,label:`conn-${o} (${s.layer})`,color:r})}),t}},H$=class extends b0t{constructor(t,n={}){super(t,n);P(this,"VIA_DIAMETER",.6);P(this,"OBSTACLE_MARGIN",.1);P(this,"OVERLAP_THRESHOLD_FOR_SINGLE_LAYER_NODES",.2);this.srj=t,this.opts=n}isNodeCompletelyOutsideBounds(t){if(this.outlinePolygon){let n=this.getNodeRect(t);if(!iT(n,this.outlinePolygon))return!0}return t.center.x+t.width/2<this.srj.bounds.minX||t.center.x-t.width/2>this.srj.bounds.maxX||t.center.y+t.height/2<this.srj.bounds.minY||t.center.y-t.height/2>this.srj.bounds.maxY}isNodePartiallyOutsideBounds(t){if(this.outlinePolygon){let n=this.getNodeRect(t);return!!iT(n,this.outlinePolygon)&&!F$(n,this.outlinePolygon)}return t.center.x-t.width/2<this.srj.bounds.minX||t.center.x+t.width/2>this.srj.bounds.maxX||t.center.y-t.height/2<this.srj.bounds.minY||t.center.y+t.height/2>this.srj.bounds.maxY}getObstacleCoveragePercentage(t){let n=this.getXYZOverlappingObstacles(t);if(n.length===0)return 0;let i=t.center.x-t.width/2,o=t.center.x+t.width/2,r=t.center.y-t.height/2,s=t.center.y+t.height/2,a=t.width*t.height,c=0;for(let l of n){let u=Math.max(i,l.center.x-l.width/2),h=Math.min(o,l.center.x+l.width/2),d=Math.max(r,l.center.y-l.height/2),_=Math.min(s,l.center.y+l.height/2);u<h&&d<_&&(c+=(h-u)*(_-d))}return c/a}shouldFilterSingleLayerNodeForObstacle(t){return t.availableZ.length!==1||!t._containsObstacle?!1:this.getObstacleCoveragePercentage(t)>this.OVERLAP_THRESHOLD_FOR_SINGLE_LAYER_NODES}shouldFilterNodeForObstacle(t){return!!t._containsObstacle&&(t.availableZ.length!==1||this.shouldFilterSingleLayerNodeForObstacle(t))}createChildNodeAtPosition(t,n){let i={capacityMeshNodeId:this.getNextNodeId(),center:n.center,width:n.width,height:n.height,layer:t.layer,availableZ:n.availableZ,_depth:n._depth??(t._depth??0)+1,_parent:t},o=this.getXYZOverlappingObstacles(i);i._containsObstacle=o.length>0||this.isNodePartiallyOutsideBounds(i);let r=this.getTargetIfNodeContainsTarget(i);return r&&(i._targetConnectionName=r.connectionName,i._containsTarget=!0),i._containsObstacle&&(i._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(i)),i}getZSubdivisionChildNodes(t){if(t.availableZ.length===1)return[];let n=[],i=t.availableZ.map(o=>[o]);for(let o of i){let r=this.createChildNodeAtPosition(t,{center:{...t.center},width:t.width,height:t.height,availableZ:o,_depth:t._depth});this.isNodeCompletelyOutsideBounds(r)||n.push(r)}return n}getChildNodes(t){if(t._depth>=this.MAX_DEPTH)return[];let n=[],i={width:t.width/2,height:t.height/2},o=[{x:t.center.x-i.width/2,y:t.center.y-i.height/2},{x:t.center.x+i.width/2,y:t.center.y-i.height/2},{x:t.center.x-i.width/2,y:t.center.y+i.height/2},{x:t.center.x+i.width/2,y:t.center.y+i.height/2}];for(let r of o){let s=this.createChildNodeAtPosition(t,{center:r,width:i.width,height:i.height,availableZ:t.availableZ});this.isNodeCompletelyOutsideBounds(s)||n.push(s)}return n}shouldNodeBeXYSubdivided(t){return!(t._depth>=this.MAX_DEPTH)&&(!!t._containsTarget||t.availableZ.length===1&&t._depth<=this.MAX_DEPTH||!(!t._containsObstacle||t._completelyInsideObstacle))}_step(){let t=this.unfinishedNodes.pop();if(!t)return void(this.solved=!0);let n=this.getChildNodes(t),i=[],o=[];for(let r of n){let s=this.shouldNodeBeXYSubdivided(r),a=r.availableZ.length>1&&!s&&(r._containsObstacle||r.width<this.VIA_DIAMETER+this.OBSTACLE_MARGIN);if(s)o.push(r);else if(s||this.shouldFilterNodeForObstacle(r)||a)if(!s&&r._containsTarget)if(a){let c=this.getZSubdivisionChildNodes(r);i.push(...c.filter(l=>l._containsTarget||!this.shouldFilterNodeForObstacle(l)))}else i.push(r);else a&&i.push(...this.getZSubdivisionChildNodes(r).filter(c=>!this.shouldFilterNodeForObstacle(c)));else i.push(r)}this.unfinishedNodes.push(...o),this.finishedNodes.push(...i)}};function lh(e){let t=new Map;for(let n of e)for(let i of n.nodeIds)t.set(i,[...t.get(i)??[],n]);return t}var G$=class extends Ke{constructor({nodes:t,edges:n,capacityPaths:i,colorMap:o}){super();P(this,"nodes");P(this,"edges");P(this,"capacityPaths");P(this,"nodeMap");P(this,"nodeEdgeMap");P(this,"unprocessedNodeIds");P(this,"nodePortSegments");P(this,"colorMap");this.nodes=t,this.edges=n,this.nodeMap=new Map(t.map(r=>[r.capacityMeshNodeId,r])),this.nodeEdgeMap=lh(n),this.capacityPaths=i,this.colorMap=o??{},this.unprocessedNodeIds=[...new Set(i.flatMap(r=>r.nodeIds))],this.nodePortSegments=new Map}step(){let t=this.unprocessedNodeIds.pop();if(!t)return void(this.solved=!0);let n=[];for(let s of this.capacityPaths){let a=s.nodeIds.indexOf(t);a!==-1&&n.push({path:s,indexOfNodeInPath:a})}let i=this.nodeMap.get(t),o=[];for(let{path:s,indexOfNodeInPath:a}of n){let c=s.nodeIds[a-1],l=s.nodeIds[a+1];for(let u of[c,l]){let h=this.nodeMap.get(u);if(!h)continue;let d=x0t(i,h),_=h.availableZ.filter(g=>i.availableZ.includes(g));if(_.length===0)continue;let y={capacityMeshNodeId:t,start:d.start,end:d.end,connectionNames:[s.connectionName],availableZ:_};o.push(y)}}let r=(function(s){let a=[],c=s.map(l=>({...l,connectionNames:[...l.connectionNames],availableZ:[...l.availableZ].sort((u,h)=>u-h)}));for(;c.length>0;){let l=c.pop(),u=!1;for(let h=0;h<a.length;h++){let d=a[h],_=yb(d.start,l.start)&&yb(d.end,l.end)||yb(d.start,l.end)&&yb(d.end,l.start),y=v0t(d.availableZ,l.availableZ);if(_&&y){let g=new Set(d.connectionNames);l.connectionNames.forEach(x=>g.add(x)),d.connectionNames=Array.from(g),u=!0;break}}u||a.push(l)}return a})(o);this.nodePortSegments.set(t,r)}visualize(){let t={lines:[],points:[],rects:[],circles:[]};return this.nodePortSegments.forEach((n,i)=>{this.nodeMap.get(i),n.forEach(o=>{o.start.x,o.end.x;for(let r=0;r<o.connectionNames.length;r++){let s={x:.05*Math.max(...o.availableZ),y:.05*Math.max(...o.availableZ)},a={x:(o.start.x+o.end.x)/2,y:(o.start.y+o.end.y)/2},c={x:a.x+s.x,y:a.y+s.y};s.x>0&&t.lines.push({points:[a,c],strokeColor:"rgba(0, 0, 0, 0.25)",strokeDash:"5 5"}),t.points.push({x:c.x,y:c.y,label:`${i}: ${o.connectionNames.join(", ")}
164
164
  availableZ: ${o.availableZ.join(",")}
@@ -248,7 +248,7 @@ ${a._facingDirection??dm(a,s)}`,x:a.x,y:a.y,color:fr(a.pinId,.8)})}for(let s of
248
248
  ${_.message}`):_}}let s=i.nodes.count()-1;for(let a=0;a<i.V.length;a++){let c=i.V[a];c&&(c.index=s+a)}for(let a of i.S){let c=t.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by switch ${a.name}`);a.model=c,a.isOn=!1}for(let a of i.D){let c=n.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by diode ${a.name}`);a.model=c}return i}var qe=class na{constructor(t=0,n=0){P(this,"re");P(this,"im");this.re=t,this.im=n}static from(t,n=0){return new na(t,n)}static fromPolar(t,n=0){let i=n*Math.PI/180;return new na(t*Math.cos(i),t*Math.sin(i))}clone(){return new na(this.re,this.im)}add(t){return new na(this.re+t.re,this.im+t.im)}sub(t){return new na(this.re-t.re,this.im-t.im)}mul(t){return new na(this.re*t.re-this.im*t.im,this.re*t.im+this.im*t.re)}div(t){let n=t.re*t.re+t.im*t.im;if(n<Hn)throw new Error("Complex divide by ~0");return new na((this.re*t.re+this.im*t.im)/n,(this.im*t.re-this.re*t.im)/n)}inv(){let t=this.re*this.re+this.im*this.im;if(t<Hn)throw new Error("Complex invert by ~0");return new na(this.re/t,-this.im/t)}abs(){return Math.hypot(this.re,this.im)}phaseDeg(){return Math.atan2(this.im,this.re)*180/Math.PI}};function DSt(e,t){let n=e.length;for(let o=0;o<n;o++){let r=e[o],s=t[o];if(!r||!s)throw new Error("Matrix dimensions mismatch");let a=r.map(c=>c.clone());a.push(s.clone()),e[o]=a}for(let o=0;o<n;o++){let r=o,s=e[o];if(!s)throw new Error("Matrix row missing");let a=s[o]?.abs()??0;for(let u=o+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[o]?.abs()??0;d>a&&(a=d,r=u)}if(a<Hn)throw new Error("Singular matrix (complex)");if(r!==o){let u=e[o];e[o]=e[r],e[r]=u}let c=e[o];if(!c)throw new Error("Pivot row missing");let l=c[o];if(!l)throw new Error("Zero pivot encountered");for(let u=o+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[o];if(!d)continue;let _=d.div(l);if(!(_.abs()<Hn))for(let y=o;y<=n;y++){let g=h[y],x=c[y];!g||!x||(h[y]=g.sub(_.mul(x)))}}}let i=new Array(n);for(let o=n-1;o>=0;o--){let r=e[o];if(!r)throw new Error("Matrix row missing");let s=r[n];if(!s)throw new Error("Augmented column missing");for(let c=o+1;c<n;c++){let l=r[c],u=i[c];!l||!u||(s=s.sub(l.mul(u)))}let a=r[o];if(!a)throw new Error("Zero pivot on back-substitution");i[o]=s.div(a)}return i}function $St(e,t,n){if(e<=0||t<=0)throw new Error(".ac frequencies must be > 0");t<e&&([e,t]=[t,e]);let i=Math.log10(t/e),o=Math.max(1,Math.ceil(i*n)),r=[];for(let a=0;a<=o;a++)r.push(e*Math.pow(10,a/n));let s=r[r.length-1];return(s==null||s<t*(1-Hn))&&r.push(t),r}function WM(e,t,n,i,o){let r=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);if(r>=0){let a=e[r];if(!a)throw new Error("Matrix row missing while stamping");a[r]=a[r]?.add(o)??o}if(s>=0){let a=e[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.add(o)??o}if(r>=0&&s>=0){let a=e[r],c=e[s];if(!a||!c)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.sub(o)??qe.from(0,0).sub(o),c[r]=c[r]?.sub(o)??qe.from(0,0).sub(o)}}function jSt(e,t,n,i,o){let r=n.matrixIndexOfNode(i.n1),s=n.matrixIndexOfNode(i.n2),a=i.index,c=qe.from(1,0);if(r>=0){let u=e[r];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.add(c)??c}if(s>=0){let u=e[s];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.sub(c)??qe.from(0,0).sub(c)}let l=e[a];if(!l)throw new Error("Branch row missing while stamping voltage source");r>=0&&(l[r]=l[r]?.add(c)??c),s>=0&&(l[s]=l[s]?.sub(c)??qe.from(0,0).sub(c)),t[a]=(t[a]??qe.from(0,0)).add(o)}function BSt(e){var d,_,y,g;if(!e.analyses.ac)return null;let{mode:t,N:n,f1:i,f2:o}=e.analyses.ac,r=e.nodes.count()-1,s=e.V.length,a=r+s,c=t==="dec"?$St(i,o,n):(()=>{let x=[],w=Math.max(2,n),S=(o-i)/(w-1);for(let T=0;T<w;T++)x.push(i+T*S);return x})(),l={};e.nodes.rev.forEach((x,w)=>{w!==0&&(l[x]=[])});let u={},h=2*Math.PI;for(let x of c){let w=Array.from({length:a},()=>Array.from({length:a},()=>qe.from(0,0))),S=Array.from({length:a},()=>qe.from(0,0));for(let I of e.R){if(I.R<=0)throw new Error(`R ${I.name} must be > 0`);let E=qe.from(1/I.R,0);WM(w,e.nodes,I.n1,I.n2,E)}for(let I of e.C){let E=qe.from(0,h*x*I.C);WM(w,e.nodes,I.n1,I.n2,E)}for(let I of e.L){let E=qe.from(0,h*x*I.L),M=E.abs()<Hn?qe.from(0,0):qe.from(1,0).div(E);WM(w,e.nodes,I.n1,I.n2,M)}for(let I of e.V){let E=qe.fromPolar(I.acMag||0,I.acPhaseDeg||0);jSt(w,S,e.nodes,I,E)}let T=DSt(w,S);for(let I=1;I<e.nodes.count();I++){let E=I-1,M=e.nodes.rev[I];if(!M)continue;let k=l[M];k&&k.push(T[E]??qe.from(0,0))}for(let I of e.R){let E=I.n1===0?qe.from(0,0):T[I.n1-1]??qe.from(0,0),M=I.n2===0?qe.from(0,0):T[I.n2-1]??qe.from(0,0),N=qe.from(1/I.R,0).mul(E.sub(M));(u[d=I.name]||(u[d]=[])).push(N)}for(let I of e.C){let E=I.n1===0?qe.from(0,0):T[I.n1-1]??qe.from(0,0),M=I.n2===0?qe.from(0,0):T[I.n2-1]??qe.from(0,0),N=qe.from(0,h*x*I.C).mul(E.sub(M));(u[_=I.name]||(u[_]=[])).push(N)}for(let I of e.L){let E=I.n1===0?qe.from(0,0):T[I.n1-1]??qe.from(0,0),M=I.n2===0?qe.from(0,0):T[I.n2-1]??qe.from(0,0),k=qe.from(0,h*x*I.L),A=(k.abs()<Hn?qe.from(0,0):qe.from(1,0).div(k)).mul(E.sub(M));(u[y=I.name]||(u[y]=[])).push(A)}for(let I of e.V){let E=T[I.index]??qe.from(0,0);(u[g=I.name]||(u[g]=[])).push(E)}}return{freqs:c,nodeVoltages:l,elementCurrents:u}}function YSt(e,t){let n=e.length;for(let o=0;o<n;o++){let r=e[o],s=t[o];if(!r||s==null)throw new Error("Matrix dimensions mismatch");let a=r.slice();a.push(s),e[o]=a}for(let o=0;o<n;o++){let r=o,s=e[o];if(!s)throw new Error("Matrix row missing");let a=Math.abs(s[o]??0);for(let u=o+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=Math.abs(h[o]??0);d>a&&(a=d,r=u)}if(a<Hn)throw new Error("Singular matrix (real)");if(r!==o){let u=e[o];e[o]=e[r],e[r]=u}let c=e[o];if(!c)throw new Error("Pivot row missing");let l=c[o];if(l==null)throw new Error("Zero pivot encountered");for(let u=o+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[o];if(d==null)continue;let _=d/l;if(!(Math.abs(_)<Hn))for(let y=o;y<=n;y++){let g=h[y],x=c[y];g==null||x==null||(h[y]=g-_*x)}}}let i=new Array(n).fill(0);for(let o=n-1;o>=0;o--){let r=e[o];if(!r)throw new Error("Matrix row missing");let s=r[n];if(s==null)throw new Error("Augmented column missing");for(let c=o+1;c<n;c++){let l=r[c],u=i[c];l==null||u==null||(s-=l*u)}let a=r[o];if(a==null)throw new Error("Zero pivot on back-substitution");i[o]=s/a}return i}function _m(e,t,n,i,o){let r=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);if(r>=0){let a=e[r];if(!a)throw new Error("Matrix row missing while stamping");a[r]=(a[r]??0)+o}if(s>=0){let a=e[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)+o}if(r>=0&&s>=0){let a=e[r],c=e[s];if(!a||!c)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)-o,c[r]=(c[r]??0)-o}}function ZM(e,t,n,i,o){let r=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);r>=0&&(e[r]=(e[r]??0)-o),s>=0&&(e[s]=(e[s]??0)+o)}function XSt(e,t,n,i,o){let r=n.matrixIndexOfNode(i.n1),s=n.matrixIndexOfNode(i.n2),a=i.index;if(r>=0){let l=e[r];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)+1}if(s>=0){let l=e[s];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)-1}let c=e[a];if(!c)throw new Error("Branch row missing while stamping voltage source");r>=0&&(c[r]=(c[r]??0)+1),s>=0&&(c[s]=(c[s]??0)-1),t[a]=(t[a]??0)+o}function VSt(e){var _,y,g,x,w,S;if(!e.analyses.tran)return null;let{dt:t,tstop:n}=e.analyses.tran,i=t>Hn?t:Math.max(n/1e3,Hn),o=Math.max(1,Math.ceil(n/Math.max(i,Hn))),r=o>0?n/o:n,s=e.nodes.count()-1,a=e.V.length,c=s+a,l=[],u={};e.nodes.rev.forEach((T,I)=>{I!==0&&(u[T]=[])});let h={},d=0;for(let T=0;T<=o;T++,d=T*r){l.push(d);let I=new Array(c).fill(0);for(let E=0;E<20;E++){let M=Array.from({length:c},()=>new Array(c).fill(0)),k=new Array(c).fill(0);for(let R of e.R){let $=1/R.R;_m(M,e.nodes,R.n1,R.n2,$)}for(let R of e.C){let $=R.C/Math.max(r,Hn);_m(M,e.nodes,R.n1,R.n2,$);let j=-$*R.vPrev;ZM(k,e.nodes,R.n1,R.n2,j)}for(let R of e.L){let $=Math.max(r,Hn)/R.L;_m(M,e.nodes,R.n1,R.n2,$),ZM(k,e.nodes,R.n1,R.n2,R.iPrev)}for(let R of e.S){let $=R.model;if(!$)continue;let j=R.isOn?$.Ron:$.Roff,X=1/Math.max(Math.abs(j),Hn);_m(M,e.nodes,R.n1,R.n2,X)}for(let R of e.V){let $=R.waveform?R.waveform(d):R.dc||0;XSt(M,k,e.nodes,R,$)}let N=.02585;for(let R of e.D){let $=R.model;if(!$)continue;let{nPlus:j,nMinus:H}=R,X=e.nodes.matrixIndexOfNode(j),G=e.nodes.matrixIndexOfNode(H),tt=j===0?0:I[X]??0,Q=H===0?0:I[G]??0,V=tt-Q,rt=E===0?R.vdPrev:V,et=$.N*N,J=rt;rt>.8&&(J=.8),rt<-1&&(J=-1);let pt=Math.exp(J/et),ht=$.Is*(pt-1),St=Math.max($.Is/et*pt,1e-12),wt=ht-St*J;_m(M,e.nodes,j,H,St),ZM(k,e.nodes,j,H,wt)}I=YSt(M,k);let A=!1;for(let R of e.S){let $=R.model;if(!$)continue;let j=R.ncPos===0?0:I[R.ncPos-1]??0,H=R.ncNeg===0?0:I[R.ncNeg-1]??0,X=j-H,G=R.isOn;R.isOn?X<$.Voff&&(G=!1):X>$.Von&&(G=!0),G!==R.isOn&&(R.isOn=G,A=!0)}if(!A||E===19)break}for(let E=1;E<e.nodes.count();E++){let M=E-1,k=e.nodes.rev[E];if(!k)continue;let N=u[k];N&&N.push(I[M]??0)}for(let E of e.R){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0,N=(M-k)/E.R;(h[_=E.name]||(h[_]=[])).push(N)}for(let E of e.C){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0,N=E.C*(M-k-E.vPrev)/Math.max(r,Hn);(h[y=E.name]||(h[y]=[])).push(N)}for(let E of e.L){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0,A=Math.max(r,Hn)/E.L*(M-k)+E.iPrev;(h[g=E.name]||(h[g]=[])).push(A)}for(let E of e.V){let M=I[E.index]??0;(h[x=E.name]||(h[x]=[])).push(M)}for(let E of e.S){let M=E.model;if(!M)continue;let k=E.n1===0?0:I[E.n1-1]??0,N=E.n2===0?0:I[E.n2-1]??0,A=E.isOn?M.Ron:M.Roff,R=Math.max(Math.abs(A),Hn),$=(k-N)/R;(h[w=E.name]||(h[w]=[])).push($)}for(let E of e.D){if(!E.model)continue;let{nPlus:M,nMinus:k,model:N}=E,A=M===0?0:I[M-1]??0,R=k===0?0:I[k-1]??0,$=A-R,H=N.N*.02585,X=Math.exp($/H),G=N.Is*(X-1);(h[S=E.name]||(h[S]=[])).push(G)}for(let E of e.C){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0;E.vPrev=M-k}for(let E of e.L){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0,N=Math.max(r,Hn)/E.L;E.iPrev=N*(M-k)+E.iPrev}for(let E of e.D){let M=E.nPlus===0?0:I[E.nPlus-1]??0,k=E.nMinus===0?0:I[E.nMinus-1]??0;E.vdPrev=M-k}}if(e.probes.tran.length>0){let T={},I=e.probes.tran.map(E=>E.toUpperCase());for(let E in u)I.includes(E.toUpperCase())&&(T[E]=u[E]);return{times:l,nodeVoltages:T,elementCurrents:h}}return{times:l,nodeVoltages:u,elementCurrents:h}}function SX(e){let t=zSt(e),n=BSt(t),i=VSt(t);return{circuit:t,ac:n,tran:i}}function wX(e,t,n){if(!e||!t.analyses.tran)return[];let{dt:i,tstop:o}=t.analyses.tran,{times:r,nodeVoltages:s}=e,a=[];for(let c in s){let l=s[c];a.push({type:"simulation_transient_voltage_graph",simulation_transient_voltage_graph_id:`stvg_${n}_${c}`,simulation_experiment_id:n,timestamps_ms:r.map(u=>u*1e3),voltage_levels:l,time_per_step:i*1e3,start_time_ms:0,end_time_ms:o*1e3,name:`V(${c})`})}return a}ji();ke();ji();ke();ke();vt();ke();ke();Qr();ke();ji();ke();ji();ke();ke();ji();ke();function PX(e,t,n,i){return Math.sqrt((n-e)**2+(i-t)**2)}var HSt=e=>{let t=e.filter(r=>r.type==="pcb_port"),n=e.filter(r=>r.type==="pcb_smtpad"),i=e.filter(r=>r.type==="pcb_trace");function o(r,s={}){let a=s.traceWidth||0,c=t.find(l=>PX(l.x,l.y,r.x,r.y)<.01);if(c)return c.pcb_port_id;if(s.isFirstOrLastPoint){let l=n.find(u=>{if(u.shape==="rect")return Math.abs(r.x-u.x)<u.width/2+a/2&&Math.abs(r.y-u.y)<u.height/2+a/2;if(u.shape==="circle")return PX(r.x,r.y,u.x,u.y)<u.radius});if(l)return l.pcb_port_id??null}return null}for(let r of i)for(let s=0;s<r.route.length;s++){let a=r.route[s],c=s===0||s===r.route.length-1;if(a.route_type==="wire"){if(!a.start_pcb_port_id&&s===0){let l=o(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.start_pcb_port_id=l)}if(!a.end_pcb_port_id&&s===r.route.length-1){let l=o(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.end_pcb_port_id=l)}}}};function TX(e){HSt(e);let t=e.filter(s=>s.type==="source_trace"),n=e.filter(s=>s.type==="pcb_port"),i=[],o=$i(e),r=new Map;for(let s of n)r.set(s.source_port_id,s);for(let s of t){let a=s.connected_source_port_ids;if(a.length<2)continue;let c=[],l=[];for(let y of a){let g=r.get(y);g?c.push(g):l.push(y)}if(c.length<2)continue;let u=c[0],h=o.getNetConnectedToId(u.pcb_port_id);o.getIdsConnectedToNet(h).filter(y=>e.some(g=>g.type==="pcb_trace"&&("pcb_trace_id"in g&&g.pcb_trace_id===y||"route_id"in g&&g.route_id===y))).length===0&&new Set(c.map(g=>g.pcb_component_id)).size>1&&i.push({type:"pcb_port_not_connected_error",message:`pcb_port_not_connected_error: Pcb ports [${c.map(g=>g.pcb_port_id).join(", ")}] are not connected together through the same net.`,error_type:"pcb_port_not_connected_error",pcb_port_ids:c.map(g=>g.pcb_port_id),pcb_component_ids:c.map(g=>g.pcb_component_id),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${s.source_trace_id}`})}return i}var GSt=class{constructor({objects:e,getBounds:t,getId:n,CELL_SIZE:i}){P(this,"buckets");P(this,"objectsById");P(this,"getBounds");P(this,"getId");P(this,"CELL_SIZE",.4);P(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=t,this.getId=n??(()=>this._getNextId()),this.CELL_SIZE=i??this.CELL_SIZE;for(let o of e)this.addObject(o)}_getNextId(){return`${this._idCounter++}`}addObject(e){let t=this.getBounds(e),n=this.getId(e),i={...e,spatialIndexId:n};this.objectsById.set(n,i);let o=Math.floor(t.minX/this.CELL_SIZE),r=Math.floor(t.minY/this.CELL_SIZE),s=Math.floor(t.maxX/this.CELL_SIZE),a=Math.floor(t.maxY/this.CELL_SIZE);for(let c=o;c<=s;c++)for(let l=r;l<=a;l++){let u=`${c}x${l}`,h=this.buckets.get(u);h?h.push(i):this.buckets.set(u,[i])}}removeObject(e){let t=this.objectsById.get(e);if(!t)return!1;this.objectsById.delete(e);let n=this.getBounds(t),i=Math.floor(n.minX/this.CELL_SIZE),o=Math.floor(n.minY/this.CELL_SIZE),r=Math.floor(n.maxX/this.CELL_SIZE),s=Math.floor(n.maxY/this.CELL_SIZE);for(let a=i;a<=r;a++)for(let c=o;c<=s;c++){let l=`${a}x${c}`,u=this.buckets.get(l);if(u){let h=u.findIndex(d=>d.spatialIndexId===e);h!==-1&&(u.splice(h,1),u.length===0&&this.buckets.delete(l))}}return!0}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getObjectsInBounds(e,t=0){let n=[],i=new Set,o=Math.floor((e.minX-t)/this.CELL_SIZE),r=Math.floor((e.minY-t)/this.CELL_SIZE),s=Math.floor((e.maxX+t)/this.CELL_SIZE),a=Math.floor((e.maxY+t)/this.CELL_SIZE);for(let c=o;c<=s;c++)for(let l=r;l<=a;l++){let u=`${c}x${l}`,h=this.buckets.get(u)||[];for(let d of h){let _=d.spatialIndexId;i.has(_)||(i.add(_),n.push(d))}}return n}},ym=e=>e.type==="pcb_trace_segment"?{minX:Math.min(e.x1,e.x2),minY:Math.min(e.y1,e.y2),maxX:Math.max(e.x1,e.x2),maxY:Math.max(e.y1,e.y2)}:nh([e]),KM=.1,USt=.15;var qSt=.2,WSt=.3,gm=.005;function ZSt(e){let t=new Set;for(let n of e.route)n.route_type==="wire"&&(n.start_pcb_port_id&&t.add(n.start_pcb_port_id),n.end_pcb_port_id&&t.add(n.end_pcb_port_id));return Array.from(t)}function JM(e){let t=new Set;for(let n of e)for(let i of ZSt(n))t.add(i);return Array.from(t)}var KSt=(e,t)=>{let n={x:e.x1,y:e.y1},i={x:e.x2,y:e.y2},o={x:t.x1,y:t.y1},r={x:t.x2,y:t.y2},s={x:i.x-n.x,y:i.y-n.y},a={x:r.x-o.x,y:r.y-o.y},c=s.x*s.x+s.y*s.y,l=a.x*a.x+a.y*a.y;if(c===0||l===0){if(c===0&&l===0)return{x:(n.x+o.x)/2,y:(n.y+o.y)/2};if(c===0){let $=ds(((n.x-o.x)*a.x+(n.y-o.y)*a.y)/l,0,1),j={x:o.x+$*a.x,y:o.y+$*a.y};return{x:(n.x+j.x)/2,y:(n.y+j.y)/2}}let A=ds(((o.x-n.x)*s.x+(o.y-n.y)*s.y)/c,0,1),R={x:n.x+A*s.x,y:n.y+A*s.y};return{x:(R.x+o.x)/2,y:(R.y+o.y)/2}}let u={x:n.x-o.x,y:n.y-o.y},h=s.x*s.x+s.y*s.y,d=s.x*a.x+s.y*a.y,_=s.x*u.x+s.y*u.y,y=a.x*a.x+a.y*a.y,g=a.x*u.x+a.y*u.y,x=h*y-d*d;if(x<1e-10)return JSt(n,i,o,r,s,a,c,l);let w=(d*g-y*_)/x,S=(h*g-d*_)/x;w=ds(w,0,1),S=ds(S,0,1),S=(w*d+g)/y,S=ds(S,0,1),w=(S*d-_)/h,w=ds(w,0,1);let T={x:n.x+w*s.x,y:n.y+w*s.y},I={x:o.x+S*a.x,y:o.y+S*a.y},E=T.x-I.x,M=T.y-I.y,k=Math.sqrt(E*E+M*M);return{x:(T.x+I.x)/2,y:(T.y+I.y)/2}},JSt=(e,t,n,i,o,r,s,a)=>{let c=((n.x-e.x)*o.x+(n.y-e.y)*o.y)/s;c=ds(c,0,1);let l={x:e.x+c*o.x,y:e.y+c*o.y},u=((i.x-e.x)*o.x+(i.y-e.y)*o.y)/s;u=ds(u,0,1);let h={x:e.x+u*o.x,y:e.y+u*o.y},d=((e.x-n.x)*r.x+(e.y-n.y)*r.y)/a;d=ds(d,0,1);let _={x:n.x+d*r.x,y:n.y+d*r.y},y=((t.x-n.x)*r.x+(t.y-n.y)*r.y)/a;y=ds(y,0,1);let g={x:n.x+y*r.x,y:n.y+y*r.y},w=[{pointA:l,pointB:n,distance:Math.sqrt((l.x-n.x)**2+(l.y-n.y)**2)},{pointA:h,pointB:i,distance:Math.sqrt((h.x-i.x)**2+(h.y-i.y)**2)},{pointA:e,pointB:_,distance:Math.sqrt((e.x-_.x)**2+(e.y-_.y)**2)},{pointA:t,pointB:g,distance:Math.sqrt((t.x-g.x)**2+(t.y-g.y)**2)}].reduce((S,T)=>T.distance<S.distance?T:S);return{x:(w.pointA.x+w.pointB.x)/2,y:(w.pointA.y+w.pointB.y)/2}},ds=(e,t,n)=>Math.max(t,Math.min(n,e)),QSt=e=>{if(e.type==="pcb_via"||e.type==="pcb_plated_hole"&&e.shape==="circle")return e.outer_diameter/2;if(e.type==="pcb_hole"&&e.hole_shape==="circle")return e.hole_diameter/2;if(e.type==="pcb_smtpad"&&e.shape==="circle")return e.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(e)}`)},IX=(e,t)=>{let n={x:e.x1,y:e.y1},i={x:e.x2,y:e.y2},o=t.minX,r=t.minY,s=t.maxX,a=t.maxY;if(n.x===i.x&&n.y===i.y){let N=Math.max(o,Math.min(s,n.x)),A=Math.max(r,Math.min(a,n.y));return N===n.x&&A===n.y?{x:n.x,y:n.y}:{x:N,y:A}}let c=i.x-n.x,l=i.y-n.y,u=c!==0?(o-n.x)/c:Number.NEGATIVE_INFINITY,h=c!==0?(s-n.x)/c:Number.POSITIVE_INFINITY,d=l!==0?(r-n.y)/l:Number.NEGATIVE_INFINITY,_=l!==0?(a-n.y)/l:Number.POSITIVE_INFINITY,y=Math.max(Math.min(u,h),Math.min(d,_)),g=Math.min(Math.max(u,h),Math.max(d,_));if(y<=g&&g>=0&&y<=1){let N=Math.max(0,Math.min(1,y));return{x:n.x+N*c,y:n.y+N*l}}let x={x:Math.max(o,Math.min(s,n.x)),y:Math.max(r,Math.min(a,n.y))},w={x:Math.max(o,Math.min(s,i.x)),y:Math.max(r,Math.min(a,i.y))},S=(x.x-n.x)**2+(x.y-n.y)**2,T=(w.x-i.x)**2+(w.y-i.y)**2,I=[{start:{x:o,y:r},end:{x:s,y:r}},{start:{x:s,y:r},end:{x:s,y:a}},{start:{x:s,y:a},end:{x:o,y:a}},{start:{x:o,y:a},end:{x:o,y:r}}],E=Math.min(S,T),M=S<=T?x:w,k=(N,A,R)=>Math.max(A,Math.min(R,N));for(let N of I){let A={x:i.x-n.x,y:i.y-n.y},R={x:N.end.x-N.start.x,y:N.end.y-N.start.y},$={x:n.x-N.start.x,y:n.y-N.start.y},j=A.x*A.x+A.y*A.y,H=A.x*R.x+A.y*R.y,X=A.x*$.x+A.y*$.y,G=R.x*R.x+R.y*R.y,tt=R.x*$.x+R.y*$.y,Q=j*G-H*H;if(Math.abs(Q)<1e-10)continue;let V=(H*tt-G*X)/Q,rt=(j*tt-H*X)/Q;V=k(V,0,1),rt=k(rt,0,1);let et={x:n.x+V*A.x,y:n.y+V*A.y},J={x:N.start.x+rt*R.x,y:N.start.y+rt*R.y},pt=et.x-J.x,ht=et.y-J.y,St=pt*pt+ht*ht;St<E&&(E=St,M={x:(et.x+J.x)/2,y:(et.y+J.y)/2})}return M};function twt(e){return e.type==="pcb_trace_segment"?[e.layer]:e.type==="pcb_smtpad"?[e.layer]:e.type==="pcb_plated_hole"?Array.isArray(e.layers)?e.layers:[...Cp]:e.type==="pcb_hole"?[...Cp]:e.type==="pcb_via"?Array.isArray(e.layers)?e.layers:[...Cp]:e.type==="pcb_keepout"?Array.isArray(e.layers)?e.layers:[]:[]}function MX(e,{connMap:t}={}){let n=[];t??(t=$i(e));let o=Ge(e).pcb_trace.list().flatMap(y=>{let g=[];for(let x=0;x<y.route.length-1;x++){let w=y.route[x],S=y.route[x+1];w.route_type==="wire"&&S.route_type==="wire"&&w.layer===S.layer&&g.push({type:"pcb_trace_segment",pcb_trace_id:y.pcb_trace_id,_pcbTrace:y,thickness:"width"in w?w.width:"width"in S?S.width:USt,layer:w.layer,x1:w.x,y1:w.y,x2:S.x,y2:S.y})}return g}),r=Ge(e).pcb_smtpad.list(),s=Ge(e).pcb_plated_hole.list(),a=Ge(e).pcb_hole.list(),c=Ge(e).pcb_via.list(),l=Ge(e).pcb_keepout.list(),u=[...o,...r,...s,...a,...c,...l],h=new GSt({objects:u,getBounds:ym}),d=y=>pr(e,y),_=new Set;for(let y of o){let g=KM,x=ym(y),w=h.getObjectsInBounds(x,g+y.thickness/2);if(!(y.x1===y.x2&&y.y1===y.y2))for(let S of w){if(!twt(S).includes(y.layer))continue;if(S.type==="pcb_trace_segment"){let M=S;if(y.layer!==M.layer||t.areIdsConnected(y.pcb_trace_id,M.pcb_trace_id))continue;let k=th({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},{x:M.x1,y:M.y1},{x:M.x2,y:M.y2})-y.thickness/2-M.thickness/2;if(k>KM-gm)continue;let N=`overlap_${y.pcb_trace_id}_${M.pcb_trace_id}`,A=`overlap_${M.pcb_trace_id}_${y.pcb_trace_id}`;if(_.has(N)||_.has(A))continue;_.add(N),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${d(M.pcb_trace_id)} ${k<0?"(accidental contact)":`(gap: ${k.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:N,pcb_component_ids:[],center:KSt(y,M),pcb_port_ids:JM([y._pcbTrace,M._pcbTrace])});continue}let T=is(S);if(t.areIdsConnected(y.pcb_trace_id,"pcb_trace_id"in S?S.pcb_trace_id:T))continue;if(S.type==="pcb_via"||S.type==="pcb_plated_hole"&&S.shape==="circle"||S.type==="pcb_hole"||S.type==="pcb_smtpad"&&S.shape==="circle"){let M=QSt(S),N=ob({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},{x:S.x,y:S.y,radius:M})-y.thickness/2;if(N>KM-gm)continue;let A=`overlap_${y.pcb_trace_id}_${T}`;if(_.has(A))continue;_.add(A),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${S.type} "${d(is(S))}" ${N<0?"(accidental contact)":`(gap: ${N.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,center:IX(y,ym(S)),source_trace_id:"",pcb_trace_error_id:A,pcb_component_ids:["pcb_component_id"in S?S.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...JM([y._pcbTrace]),"pcb_port_id"in S?S.pcb_port_id:void 0].filter(Boolean)})}let E=wf({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},ym(S))-y.thickness/2;if(E+gm<g){let M=`overlap_${y.pcb_trace_id}_${T}`;if(_.has(M))continue;_.add(M),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${S.type} "${d(is(S))}" ${E<0?"(accidental contact)":`(gap: ${E.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:M,pcb_component_ids:["pcb_component_id"in S?S.pcb_component_id:void 0].filter(Boolean),center:IX(y,ym(S)),pcb_port_ids:[...JM([y._pcbTrace]),"pcb_port_id"in S?S.pcb_port_id:void 0].filter(Boolean)})}}}return n}function CX(e){return e.area()>=0}function EX({center:e,size:t,rotationDeg:n=0}){let i=e.x,o=e.y,r=t.width/2,s=t.height/2,a=[new hs(i-r,o-s),new hs(i+r,o-s),new hs(i+r,o+s),new hs(i-r,o+s)],c=new lm(a);if(n){let l=Yg(n,i,o),u=a.map(h=>{let d=yn(l,{x:h.x,y:h.y});return new hs(d.x,d.y)});c=new lm(u)}return CX(c)||c.reverse(),c}function ewt({board:e}){if(e.outline&&e.outline.length>0){let t=e.outline.map(i=>new hs(i.x,i.y)),n=new lm(t);return CX(n)||n.reverse(),n}return e.center&&typeof e.width=="number"&&typeof e.height=="number"?EX({center:e.center,size:{width:e.width,height:e.height},rotationDeg:0}):null}function nwt({circuitJson:e,component:t}){if(t.source_component_id){let n=e.find(i=>i.type==="source_component"&&i.source_component_id===t.source_component_id);if(n&&"name"in n&&n.name)return n.name}return pr(e,t.pcb_component_id)||"Unknown"}function iwt(e,t,n,i,o,r){let s=new hs(n.x,n.y);if(!t.contains(s)){let g=t.distanceTo(s);return Array.isArray(g)?g[0]:Number(g)||0}let a=i/2,c=o/2,l=[{x:n.x-a,y:n.y-c},{x:n.x+a,y:n.y-c},{x:n.x+a,y:n.y+c},{x:n.x-a,y:n.y+c}],u=[];for(let g=0;g<4;g++){let x=(g+1)%4;u.push({x:(l[g].x+l[x].x)/2,y:(l[g].y+l[x].y)/2})}let h=Yg(r,n.x,n.y),d=g=>{let x=yn(h,g);return new hs(x.x,x.y)},_=l.concat(u).map(d),y=0;for(let g of _)if(!t.contains(g)){let x=t.distanceTo(g),w=Array.isArray(x)?x[0]:Number(x)||0;w>y&&(y=w)}if(y>0)return y;try{let g=PM.intersect(e,t),x=0;g?Array.isArray(g)?x=g.reduce((S,T)=>S+(typeof T.area=="function"?T.area():0),0):typeof g.area=="function"?x=g.area():x=0:x=0;let w=e.area();if(x>0&&x<w){let S=1-x/w,T=Math.abs(i),I=Math.abs(o);return Math.min(T,I)*S}else return .1}catch{return .1}}function NX(e){let t=e.find(r=>r.type==="pcb_board");if(!t)return[];let n=ewt({board:t});if(!n)return[];let i=e.filter(r=>r.type==="pcb_component");if(i.length===0)return[];let o=[];for(let r of i){if(!r.center||typeof r.width!="number"||typeof r.height!="number"||r.width<=0||r.height<=0)continue;let s=EX({center:r.center,size:{width:r.width,height:r.height},rotationDeg:r.rotation||0});if(s.area()===0||n.contains(s))continue;let c=iwt(s,n,r.center,r.width,r.height,r.rotation||0),l=nwt({circuitJson:e,component:r}),u=Math.round(c*100)/100;o.push({type:"pcb_component_outside_board_error",error_type:"pcb_component_outside_board_error",pcb_component_outside_board_error_id:`pcb_component_outside_board_${r.pcb_component_id}`,message:`Component ${l} (${r.pcb_component_id}) extends outside board boundaries by ${u}mm`,pcb_component_id:r.pcb_component_id,pcb_board_id:t.pcb_board_id,component_center:r.center,component_bounds:{min_x:s.box.xmin,max_x:s.box.xmax,min_y:s.box.ymin,max_y:s.box.ymax},subcircuit_id:r.subcircuit_id,source_component_id:r.source_component_id})}return o}function owt(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function kX(e,{connMap:t,minSpacing:n=qSt}={}){let i=e.filter(s=>s.type==="pcb_via");if(i.length<2)return[];t??(t=$i(e));let o=[],r=new Set;for(let s=0;s<i.length;s++)for(let a=s+1;a<i.length;a++){let c=i[s],l=i[a];if(!t.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=owt(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+gm>=n)continue;let h=[c.pcb_via_id,l.pcb_via_id].sort().join("_");r.has(h)||(r.add(h),o.push({type:"pcb_via_clearance_error",pcb_error_id:`same_net_vias_close_${h}`,message:`Vias ${pr(e,c.pcb_via_id)} and ${pr(e,l.pcb_via_id)} are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:n,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return o}function rwt(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function AX(e,{connMap:t,minSpacing:n=WSt}={}){let i=e.filter(s=>s.type==="pcb_via");if(i.length<2)return[];t??(t=$i(e));let o=[],r=new Set;for(let s=0;s<i.length;s++)for(let a=s+1;a<i.length;a++){let c=i[s],l=i[a];if(t.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=rwt(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+gm>=n)continue;let h=[c.pcb_via_id,l.pcb_via_id].sort().join("_");r.has(h)||(r.add(h),o.push({type:"pcb_via_clearance_error",pcb_error_id:`different_net_vias_close_${h}`,message:`Vias ${pr(e,c.pcb_via_id)} and ${pr(e,l.pcb_via_id)} from different nets are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:n,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return o}var swt=.2;function awt(e){if(e.outline&&e.outline.length>0)return e.outline.map(t=>({x:t.x,y:t.y}));if(e.center&&typeof e.width=="number"&&typeof e.height=="number"){let t=e.center.x,n=e.center.y,i=e.width/2,o=e.height/2;return[{x:t-i,y:n-o},{x:t+i,y:n-o},{x:t+i,y:n+o},{x:t-i,y:n+o}]}return null}function RX(e,t={}){let n=[],i=t.margin??swt,o=e.find(a=>a.type==="pcb_board");if(!o)return n;let r=awt(o);if(!r)return n;let s=Ge(e).pcb_trace.list();for(let a of s)if(!(a.route.length<2))for(let c=0;c<a.route.length-1;c++){let l=a.route[c],u=a.route[c+1];if(l.route_type!=="wire"||u.route_type!=="wire")continue;let h="width"in l?l.width:"width"in u?u.width:.1,d={x:l.x,y:l.y},_={x:u.x,y:u.y},y=1/0;for(let x=0;x<r.length;x++){let w=r[x],S=r[(x+1)%r.length],T=th(d,_,w,S);T<y&&(y=T)}let g=h/2+i;if(y<g){let x={type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:`trace_too_close_to_board_${a.pcb_trace_id}_segment_${c}`,message:`Trace too close to board edge (${y.toFixed(3)}mm < ${g.toFixed(3)}mm required, margin: ${i}mm)`,pcb_trace_id:a.pcb_trace_id,source_trace_id:a.source_trace_id||"",center:{x:(d.x+_.x)/2,y:(d.y+_.y)/2},pcb_component_ids:[],pcb_port_ids:[]};n.push(x)}}return n}function cwt(e,t){let n=nh([e]),i=nh([t]);return ic(n,i)}function OX(e){let t=[],n=$i(e),i=Ge(e).pcb_smtpad.list(),o=Ge(e).pcb_plated_hole.list(),r=Ge(e).pcb_hole.list(),s=new Map;for(let c of i){let l=c.pcb_component_id||`standalone_pad_${is(c)}`;s.has(l)||s.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),s.get(l).elements.push(c)}for(let c of o){let l=c.pcb_component_id||`standalone_plated_hole_${is(c)}`;s.has(l)||s.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),s.get(l).elements.push(c)}for(let c of r){let l=`standalone_hole_${is(c)}`;s.set(l,{component_id:l,elements:[c],bounds:{minX:0,minY:0,maxX:0,maxY:0}})}for(let[c,l]of s)l.elements.length>0&&(l.bounds=nh(l.elements));let a=Array.from(s.values());for(let c=0;c<a.length;c++)for(let l=c+1;l<a.length;l++){let u=a[c],h=a[l];if(ic(u.bounds,h.bounds))for(let d of u.elements)for(let _ of h.elements){let y=is(d),g=is(_);if(!(d.type==="pcb_smtpad"&&_.type==="pcb_smtpad"&&n.areIdsConnected(y,g))&&cwt(d,_)){let x={type:"pcb_footprint_overlap_error",pcb_error_id:`pcb_footprint_overlap_${y}_${g}`,error_type:"pcb_footprint_overlap_error",message:`PCB component ${d.type} "${y}" overlaps with ${_.type} "${g}"`};(d.type==="pcb_smtpad"||_.type==="pcb_smtpad")&&(x.pcb_smtpad_ids=[],d.type==="pcb_smtpad"&&x.pcb_smtpad_ids.push(y),_.type==="pcb_smtpad"&&x.pcb_smtpad_ids.push(g)),(d.type==="pcb_plated_hole"||_.type==="pcb_plated_hole")&&(x.pcb_plated_hole_ids=[],d.type==="pcb_plated_hole"&&x.pcb_plated_hole_ids.push(y),_.type==="pcb_plated_hole"&&x.pcb_plated_hole_ids.push(g)),(d.type==="pcb_hole"||_.type==="pcb_hole")&&(x.pcb_hole_ids=[],d.type==="pcb_hole"&&x.pcb_hole_ids.push(y),_.type==="pcb_hole"&&x.pcb_hole_ids.push(g)),t.push(x)}}}return t}var QM=[{value:1e12,symbol:"T"},{value:1e9,symbol:"G"},{value:1e6,symbol:"M"},{value:1e3,symbol:"k"},{value:1,symbol:""},{value:.001,symbol:"m"},{value:1e-6,symbol:"\xB5"},{value:1e-9,symbol:"n"},{value:1e-12,symbol:"p"}];function ni(e){if(e==null)return"";if(e===0)return"0";let t=Math.abs(e),n=QM.find(r=>{let s=t/r.value;return s>=1&&s<1e3})||QM[QM.length-1],o=(e/n.value).toPrecision(3);return o.includes(".")&&!/\.0+$/.test(o)&&(o=o.replace(/0+$/,"")),o=o.replace(/\.0+$/,""),`${o}${n.symbol}`}vt();vt();K();ke();Pf();var lwt=class{constructor(){P(this,"MAX_ITERATIONS",1e5);P(this,"solved",!1);P(this,"failed",!1);P(this,"iterations",0);P(this,"progress",0);P(this,"error",null);P(this,"activeSubSolver");P(this,"failedSubSolvers");P(this,"timeToSolve");P(this,"stats",{});P(this,"_setupDone",!1)}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(e){throw this.error=`${this.constructor.name} error: ${e}`,console.error(this.error),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`,console.error(this.error),this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}getOutput(){return null}solve(){let e=Date.now();for(;!this.solved&&!this.failed;)this.step();let t=Date.now();this.timeToSolve=t-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};var LX=class extends lwt{constructor(t){super();P(this,"startTimeOfPhase",{});P(this,"endTimeOfPhase",{});P(this,"timeSpentOnPhase",{});P(this,"firstIterationOfPhase",{});P(this,"currentPipelineStepIndex",0);P(this,"inputProblem");P(this,"pipelineOutputs",{});this.inputProblem=t,this.MAX_ITERATIONS=1e6}_step(){let t=this.pipelineDef[this.currentPipelineStepIndex];if(!t){this.solved=!0;return}if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){this.endTimeOfPhase[t.solverName]=performance.now(),this.timeSpentOnPhase[t.solverName]=this.endTimeOfPhase[t.solverName]-this.startTimeOfPhase[t.solverName];let i=this.activeSubSolver.getOutput();i!==null&&(this.pipelineOutputs[t.solverName]=i),t.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++}else this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let n=t.getConstructorParams(this);this.activeSubSolver=new t.solverClass(...n),this[t.solverName]=this.activeSubSolver,this.timeSpentOnPhase[t.solverName]=0,this.startTimeOfPhase[t.solverName]=performance.now(),this.firstIterationOfPhase[t.solverName]=this.iterations}solveUntilPhase(t){for(;this.getCurrentPhase().toLowerCase()!==t.toLowerCase()&&(this.step(),!(this.failed||this.solved)););}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}getPhaseProgress(){let t=this.pipelineDef.length;if(t===0)return 1;let n=this.activeSubSolver?.progress??0;return(this.currentPipelineStepIndex+n)/t}getPhaseStats(){let t={};for(let n of this.pipelineDef){let i=this.timeSpentOnPhase[n.solverName]||0,o=this.firstIterationOfPhase[n.solverName]||0,r=this.iterations,s=n.solverName===this.getCurrentPhase()?r-o:0,a=this.currentPipelineStepIndex>this.pipelineDef.findIndex(c=>c.solverName===n.solverName);t[n.solverName]={timeSpent:i,iterations:s,completed:a}}return t}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let t=this.pipelineDef.map((n,i)=>{let r=this[n.solverName]?.visualize();if(!r)return null;for(let s of r.rects??[])s.step=i;for(let s of r.points??[])s.step=i;for(let s of r.circles??[])s.step=i;for(let s of r.texts??[])s.step=i;for(let s of r.lines??[])s.step=i;return r}).filter(Boolean);return t.length===0?{points:[],rects:[],lines:[],circles:[],texts:[]}:t.length===1?t[0]:{points:t.flatMap(n=>n.points||[]),rects:t.flatMap(n=>n.rects||[]),lines:t.flatMap(n=>n.lines||[]),circles:t.flatMap(n=>n.circles||[]),texts:t.flatMap(n=>n.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}computeProgress(){return this.getPhaseProgress()}getStepOutput(t){return this.pipelineOutputs[t]}getAllOutputs(){return{...this.pipelineOutputs}}hasStepOutput(t){return t in this.pipelineOutputs}getSolver(t){return this[t]}};var uwt=e=>{let t=e.board_edge_margin??0;if(e.outline&&e.outline.length>0){let o=new L.Polygon(e.outline.map(r=>L.point(r.x,r.y)));return o.orientation()===L.ORIENTATION.CW&&o.reverse(),o}let{bounds:n}=e,i={minX:n.minX+t,minY:n.minY+t,maxX:n.maxX-t,maxY:n.maxY-t};return i.minX>=i.maxX||i.minY>=i.maxY?new L.Polygon:new L.Polygon(new L.Box(i.minX,i.minY,i.maxX,i.maxY).toPoints())},t4=(e,t=32)=>{let n=[];for(let i=0;i<t;i++){let o=i/t*2*Math.PI;n.push(new L.Point(e.center.x+e.r*Math.cos(o),e.center.y+e.r*Math.sin(o)))}return new L.Polygon(n)},pwt=e=>e.shape==="rect",hwt=e=>e.shape==="trace",dwt=e=>e.shape==="circle",fwt=e=>e.shape==="polygon",mwt=(e,t,n,i)=>{let o=[],{padMargin:r,traceMargin:s,board_edge_margin:a,cutoutMargin:c}=n;if(i&&i.length>0&&a&&a>0){let l=new L.Polygon(i.map(h=>L.point(h.x,h.y)));l.area()<0&&l.reverse();let u=l.vertices;for(let h=0;h<u.length;h++){let d=u[h===0?u.length-1:h-1],_=u[h],y=u[(h+1)%u.length];if(!d||!_||!y)continue;let g=new L.Vector(d,_),x=new L.Vector(_,y),w=g.cross(x),S=new L.Circle(_,a);if(o.push(t4(S)),w<0){let T=new L.Box(_.x-a,_.y-a,_.x+a,_.y+a);o.push(new L.Polygon(T.toPoints()))}}for(let h=0;h<u.length;h++){let d=u[h],_=u[(h+1)%u.length];if(!d||!_)continue;let y=Math.hypot(d.x-_.x,d.y-_.y);if(y===0)continue;let g=a*2,x=(d.x+_.x)/2,w=(d.y+_.y)/2,S=Math.atan2(_.y-d.y,_.x-d.x)*180/Math.PI,T=y/2,I=g/2,E=S*Math.PI/180,M=Math.cos(E),k=Math.sin(E),A=[{x:-T,y:-I},{x:T,y:-I},{x:T,y:I},{x:-T,y:I}].map(R=>({x:x+R.x*M-R.y*k,y:w+R.x*k+R.y*M}));o.push(new L.Polygon(A.map(R=>L.point(R.x,R.y))))}}for(let l of e){if(l.connectivityKey===t)continue;let h=l.connectivityKey.startsWith("hole:")||l.connectivityKey.startsWith("cutout:");if(dwt(l)){let d=h?c??0:r,_=new L.Circle(new L.Point(l.x,l.y),l.radius+d);o.push(t4(_));continue}if(pwt(l)){let d=h?c??0:r,{bounds:_}=l,y=new L.Box(_.minX-d,_.minY-d,_.maxX+d,_.maxY+d);o.push(new L.Polygon(y.toPoints()));continue}if(fwt(l)){let d=h?c??0:0,_=new Set,y=l.points.filter(T=>{let I=`${T.x},${T.y}`;return _.has(I)?!1:(_.add(I),!0)});if(y.length<3)continue;let g=new L.Polygon(y.map(T=>L.point(T.x,T.y)));if(Math.abs(g.area())<1e-9)continue;if(d<=0){o.push(g);continue}g.area()>0&&g.reverse();let x=[],w=g.vertices;for(let T=0;T<w.length;T++){let I=w[T],E=w[(T+1)%w.length],M=L.segment(I,E);if(M.length===0)continue;let k=L.line(M.start,M.end),N=k.norm,A=k.translate(N.multiply(-d));x.push(A)}let S=[];for(let T=0;T<x.length;T++){let I=x[T],E=x[(T+1)%x.length],M=I.intersect(E);M.length>0&&S.push(M[0])}S.length>=3&&o.push(new L.Polygon(S));continue}if(hwt(l)){for(let d of l.segments){let _=new L.Circle(new L.Point(d.x,d.y),l.width/2+s);o.push(t4(_))}for(let d=0;d<l.segments.length-1;d++){let _=l.segments[d],y=l.segments[d+1];if(!_||!y)continue;let g=Math.hypot(_.x-y.x,_.y-y.y);if(g===0)continue;let x=l.width+s*2,w=(_.x+y.x)/2,S=(_.y+y.y)/2,T=Math.atan2(y.y-_.y,y.x-_.x)*180/Math.PI,I=g/2,E=x/2,M=T*Math.PI/180,k=Math.cos(M),N=Math.sin(M),R=[{x:-I,y:-E},{x:I,y:-E},{x:I,y:E},{x:-I,y:E}].map($=>({x:w+$.x*k-$.y*N,y:S+$.x*N+$.y*k}));o.push(new L.Polygon(R.map($=>L.point($.x,$.y))))}continue}}return{polygonsToSubtract:o}},FX=e=>e.edges.map(t=>{let n={x:t.start.x,y:t.start.y};if(t.isArc){let i=Math.tan(t.shape.sweep/4);Math.abs(i)>1e-9&&(n.bulge=i)}return n}),_wt=e=>{let t=[],n=Array.isArray(e)?e:[e];for(let i of n){let o=i.splitToIslands();for(let r of o){if(r.isEmpty())continue;let s=[...r.faces],a=s.find(h=>h.orientation()===L.ORIENTATION.CCW),c=s.filter(h=>h.orientation()===L.ORIENTATION.CW);if(!a)continue;a.reverse();let l=FX(a),u=c.map(h=>(h.reverse(),{vertices:FX(h)}));t.push({outer_ring:{vertices:l},inner_rings:u})}}return t},zX=class extends LX{constructor(t){super(t);P(this,"pipelineDef",[]);this.input=t}getOutput(){let t=[];for(let n of this.input.regionsForPour){let i=uwt(n),o=this.input.pads.filter(c=>c.layer===n.layer),{polygonsToSubtract:r}=mwt(o,n.connectivityKey,{padMargin:n.padMargin,traceMargin:n.traceMargin,board_edge_margin:n.board_edge_margin,cutoutMargin:n.cutout_margin},n.outline),s=i;for(let c of r){let l=Array.isArray(s)?s:[s],u=[];for(let h of l){let d=L.BooleanOperations.subtract(h,c);d&&(Array.isArray(d)?u.push(...d.filter(_=>!_.isEmpty())):d.isEmpty()||u.push(d))}s=u}let a=_wt(s);t.push(...a)}return{brep_shapes:t}}},DX=(e,t)=>{let n=e.filter(T=>T.type==="source_port"),i=e.filter(T=>T.type==="pcb_port"),o=e.filter(T=>T.type==="source_trace"),r=e.filter(T=>T.type==="pcb_trace"),s=e.filter(T=>T.type==="source_net"),a=e.find(T=>T.type==="pcb_board");if(!a)throw new Error("No pcb_board found in circuit json");let c=Object.fromEntries(n.map(T=>[T.source_port_id,T.subcircuit_connectivity_map_key])),l=Object.fromEntries(i.map(T=>[T.pcb_port_id,c[T.source_port_id]])),u={};for(let T of i)T.pcb_port_id&&(u[T.pcb_port_id]=l[T.pcb_port_id]);let h=Object.fromEntries(o.map(T=>[T.source_trace_id,T.subcircuit_connectivity_map_key])),d=Object.fromEntries(s.map(T=>[T.source_net_id,T.subcircuit_connectivity_map_key])),_={...h,...d},y=Object.fromEntries(r.map(T=>[T.pcb_trace_id,T.source_trace_id?_[T.source_trace_id]:void 0]).filter(T=>!!T[1])),g=[];for(let T of e)if(T.type==="pcb_smtpad"){let I=T;if(I.layer!==t.layer)continue;let E;I.pcb_port_id&&(E=l[I.pcb_port_id]),E||(E=`unconnected:${I.pcb_smtpad_id}`),I.shape==="rect"?g.push({shape:"rect",padId:I.pcb_smtpad_id,layer:I.layer,connectivityKey:E,bounds:{minX:I.x-I.width/2,minY:I.y-I.height/2,maxX:I.x+I.width/2,maxY:I.y+I.height/2}}):I.shape==="circle"&&g.push({shape:"circle",padId:I.pcb_smtpad_id,layer:I.layer,connectivityKey:E,x:I.x,y:I.y,radius:I.radius})}else if(T.type==="pcb_plated_hole"){let I=T;if(I.shape!=="circle"||!I.layers.includes(t.layer))continue;let E=u[I.pcb_plated_hole_id];E||(E=`unconnected-plated-hole:${I.pcb_plated_hole_id}`),g.push({shape:"circle",padId:I.pcb_plated_hole_id,layer:t.layer,connectivityKey:E,x:I.x,y:I.y,radius:I.outer_diameter/2})}else if(T.type==="pcb_hole"){let I=T;if(I.hole_shape!=="circle")continue;g.push({shape:"circle",padId:I.pcb_hole_id,layer:t.layer,connectivityKey:`hole:${I.pcb_hole_id}`,x:I.x,y:I.y,radius:I.hole_diameter/2})}else if(T.type==="pcb_cutout"){let I=T;I.shape==="rect"?g.push({shape:"rect",padId:I.pcb_cutout_id,layer:t.layer,connectivityKey:`cutout:${I.pcb_cutout_id}`,bounds:{minX:I.center.x-I.width/2,minY:I.center.y-I.height/2,maxX:I.center.x+I.width/2,maxY:I.center.y+I.height/2}}):I.shape==="circle"?g.push({shape:"circle",padId:I.pcb_cutout_id,layer:t.layer,connectivityKey:`cutout:${I.pcb_cutout_id}`,x:I.center.x,y:I.center.y,radius:I.radius}):I.shape==="polygon"&&g.push({shape:"polygon",padId:I.pcb_cutout_id,layer:t.layer,connectivityKey:`cutout:${I.pcb_cutout_id}`,points:I.points})}else if(T.type==="pcb_via"){let I=T;if(!I.layers.includes(t.layer))continue;let E=I.subcircuit_connectivity_map_key??y[I.pcb_trace_id??""]??`unconnected-via:${I.pcb_via_id}`;g.push({shape:"circle",padId:I.pcb_via_id,layer:t.layer,connectivityKey:E,x:I.x,y:I.y,radius:I.outer_diameter/2})}else if(T.type==="pcb_trace"){let I=T;if(!I.source_trace_id)continue;let E=_[I.source_trace_id];if(!E)continue;let M=[],k=null,N=()=>{M.length>1&&g.push({shape:"trace",padId:`${I.pcb_trace_id}-${g.length}`,layer:t.layer,connectivityKey:E,segments:M,width:k}),M=[],k=null};for(let A of I.route){let R=A;R.route_type==="wire"&&R.layer===t.layer?(k===null&&(k=R.width),M.push({x:R.x,y:R.y})):N()}N()}let{width:x,height:w}=a,S=[{shape:"rect",layer:t.layer,bounds:{minX:-x/2,minY:-w/2,maxX:x/2,maxY:w/2},outline:a.outline,connectivityKey:t.pour_connectivity_key,padMargin:t.pad_margin,traceMargin:t.trace_margin,board_edge_margin:t.board_edge_margin??0,cutout_margin:t.cutout_margin}];return{pads:g,regionsForPour:S}};Ys();vt();ke();var QG=Xt(Mr(),1);var O4=Xt(Sn(),1),Bh=Xt(Mr(),1),Fne=Xt(Mr(),1);var mu=Xt(uu(),1);var tU=Xt(uu(),1),eU=Xt(uu(),1);var nU=Xt(uu(),1);var iU=Xt(uu(),1);var oU=Xt(uu(),1),rU=Xt(Mr(),1);var y5t=Object.defineProperty,g5t=(e,t)=>{for(var n in t)y5t(e,n,{get:t[n],enumerable:!0})},SH={};g5t(SH,{AnalogSimulation:()=>KG,Battery:()=>NG,Board:()=>QH,Breakout:()=>SG,BreakoutPoint:()=>wG,CadAssembly:()=>DH,CadModel:()=>zH,Capacitor:()=>eG,Chip:()=>Fm,Constraint:()=>uG,CopperPour:()=>EG,Crystal:()=>FG,Cutout:()=>Rm,Diode:()=>iG,FabricationNoteDimension:()=>fG,FabricationNotePath:()=>hG,FabricationNoteRect:()=>pG,FabricationNoteText:()=>dG,Footprint:()=>OH,Fuse:()=>oG,Group:()=>Tc,Hole:()=>Xh,Inductor:()=>RG,Jumper:()=>rG,Keepout:()=>Rx,Led:()=>aG,Mosfet:()=>DG,Net:()=>z4,NetLabel:()=>PG,NormalComponent:()=>On,Panel:()=>tG,PcbNoteDimension:()=>bG,PcbNoteLine:()=>mG,PcbNotePath:()=>gG,PcbNoteRect:()=>_G,PcbNoteText:()=>yG,PcbTrace:()=>$4,PinHeader:()=>kG,Pinout:()=>nG,PlatedHole:()=>Yh,Port:()=>Ni,Potentiometer:()=>OG,PowerSource:()=>cG,PrimitiveComponent:()=>xe,PushButton:()=>LG,Renderable:()=>L4,Resistor:()=>X4,Resonator:()=>AG,SchematicArc:()=>VG,SchematicBox:()=>GG,SchematicCell:()=>WG,SchematicCircle:()=>HG,SchematicLine:()=>YG,SchematicRect:()=>XG,SchematicRow:()=>qG,SchematicTable:()=>UG,SchematicText:()=>BG,SilkscreenCircle:()=>IG,SilkscreenLine:()=>MG,SilkscreenPath:()=>D4,SilkscreenRect:()=>TG,SilkscreenText:()=>Dx,SmtPad:()=>Am,SolderJumper:()=>sG,Subcircuit:()=>vG,Switch:()=>$G,Symbol:()=>ZG,TestPoint:()=>jG,Trace:()=>$r,TraceHint:()=>B4,Transistor:()=>zG,Via:()=>CG,VoltageProbe:()=>JG,VoltageSource:()=>lG});var b5t=(0,IH.default)("tscircuit:renderable"),aa=["ReactSubtreesRender","InflateSubcircuitCircuitJson","SourceNameDuplicateComponentRemoval","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","AssignFallbackProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SourceDesignRuleChecks","SimulationRender","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicComponentSizeCalculation","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbComponentAnchorAlignment","PcbLayout","PcbBoardAutoSize","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbCopperPourRender","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender","SimulationSpiceEngineRender"],x5t={PcbFootprintLayout:["PcbFootprintStringRender"],PcbComponentSizeCalculation:["PcbFootprintStringRender"],PcbLayout:["PcbFootprintStringRender"],PcbBoardAutoSize:["PcbFootprintStringRender"],PcbTraceHintRender:["PcbFootprintStringRender"],PcbManualTraceRender:["PcbFootprintStringRender"],PcbCopperPourRender:["PcbFootprintStringRender","PcbTraceRender","PcbRouteNetIslands"],PcbTraceRender:["PcbFootprintStringRender"],PcbRouteNetIslands:["PcbFootprintStringRender"],PcbDesignRuleChecks:["PcbFootprintStringRender"],SilkscreenOverlapAdjustment:["PcbFootprintStringRender"],CadModelRender:["PcbFootprintStringRender"],PartsEngineRender:["PcbFootprintStringRender"],PcbComponentAnchorAlignment:["PcbFootprintStringRender"]},v5t=0,L4=class TH{constructor(t){P(this,"renderPhaseStates");P(this,"shouldBeRemoved",!1);P(this,"children");P(this,"isPcbPrimitive",!1);P(this,"isSchematicPrimitive",!1);P(this,"_renderId");P(this,"_currentRenderPhase",null);P(this,"_asyncEffects",[]);P(this,"parent",null);this._renderId=`${v5t++}`,this.children=[],this.renderPhaseStates={};for(let n of aa)this.renderPhaseStates[n]={initialized:!1,dirty:!1}}_markDirty(t){this.renderPhaseStates[t].dirty=!0;let n=aa.indexOf(t);for(let i=n+1;i<aa.length;i++)this.renderPhaseStates[aa[i]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(t)}_queueAsyncEffect(t,n){let i={promise:n(),phase:this._currentRenderPhase,effectName:t,complete:!1};this._asyncEffects.push(i),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:t,componentDisplayName:this.getString(),phase:i.phase}),i.promise.then(()=>{i.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:t,componentDisplayName:this.getString(),phase:i.phase})}).catch(o=>{console.error(`Async effect error in ${i.phase} "${t}":
249
249
  ${o.stack}`),i.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:t,componentDisplayName:this.getString(),phase:i.phase,error:o.toString()})})}_emitRenderLifecycleEvent(t,n){b5t(`${t}:${n} ${this.getString()}`);let i=`renderable:renderLifecycle:${t}:${n}`,o={renderId:this._renderId,componentDisplayName:this.getString(),type:i};"root"in this&&this.root&&(this.root.emit(i,o),this.root.emit("renderable:renderLifecycle:anyEvent",{...o,type:i}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(t=>!t.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(t){for(let n of this._asyncEffects)if(!n.complete&&n.phase===t)return!0;for(let n of this.children)if(n._hasIncompleteAsyncEffectsInSubtreeForPhase(t))return!0;return!1}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(t=>t.getRenderGraph())}}getTopLevelRenderable(){let t=this;for(;t.parent&&t.parent instanceof TH;)t=t.parent;return t}runRenderCycle(){for(let t of aa)this.runRenderPhaseForChildren(t),this.runRenderPhase(t)}runRenderPhase(t){this._currentRenderPhase=t;let n=this.renderPhaseStates[t],i=n.initialized,o=n.dirty;if(!i&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&i){this._emitRenderLifecycleEvent(t,"start"),this?.[`remove${t}`]?.(),n.initialized=!1,n.dirty=!1,this._emitRenderLifecycleEvent(t,"end");return}let r=aa.indexOf(t)-1;if(r>=0){let a=aa[r];if(this._asyncEffects.filter(l=>l.phase===a).some(l=>!l.complete))return}let s=x5t[t]||[];if(s.length>0){let a=this.getTopLevelRenderable();for(let c of s)if(a._hasIncompleteAsyncEffectsInSubtreeForPhase(c))return}if(this._emitRenderLifecycleEvent(t,"start"),i){o&&(this?.[`update${t}`]?.(),n.dirty=!1),this._emitRenderLifecycleEvent(t,"end");return}n.dirty=!1,this?.[`doInitial${t}`]?.(),n.initialized=!0,this._emitRenderLifecycleEvent(t,"end")}runRenderPhaseForChildren(t){for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}renderError(t){throw typeof t=="string"?new Error(t):new Error(JSON.stringify(t,null,2))}},Ax={},MH=e=>{let t=Object.fromEntries(Object.entries(e).map(([n,i])=>[n.toLowerCase(),i]));Object.assign(Ax,e),Object.assign(Ax,t)},S5t=class extends Error{constructor(e,t,n){let i,o=Object.keys(n).filter(c=>c!=="_errors"),r=[],s=t.pinLabels;if(s)for(let[c,l]of Object.entries(s)){let u=Array.isArray(l)?l:[l];for(let h of u)typeof h=="string"&&(h.startsWith(" ")||h.endsWith(" "))&&r.push(`pinLabels.${c} ("${h}" has leading or trailing spaces)`)}let a=o.map(c=>c==="pinLabels"&&r.length>0?r.join(", "):n[c]._errors[0]?`${c} (${n[c]._errors[0]})`:`${c} (${JSON.stringify(n[c])})`).join(", ");"name"in t?i=`Invalid props for ${e} "${t.name}": ${a}`:"footprint"in t&&typeof t.footprint=="string"?i=`Invalid props for ${e} (unnamed ${t.footprint} component): ${a}`:i=`Invalid props for ${e} (unnamed): ${a}`,super(i),this.componentName=e,this.originalProps=t,this.formattedError=n}};function b4(e,t){let n=t.match(/^#(\w+)/);if(n)return e.props.id===n[1];let i=t.match(/^\.(\w+)/);if(i)return e.isMatchingNameOrAlias(i[1]);let[o,...r]=t.split(/(?=[#.[])/);return o==="pin"&&(o="port"),o&&o!=="*"&&e.lowercaseComponentName!==o.toLowerCase()?!1:r.every(s=>{if(s.startsWith("#"))return e.props.id===s.slice(1);if(s.startsWith("."))return e.isMatchingNameOrAlias(s.slice(1));let a=s.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!a)return!0;let[,c,l]=a;return e.props[c].toString()===l})}var F4={isTag:e=>!0,getParent:e=>e.parent,getChildren:e=>e.children,getName:e=>e.lowercaseComponentName,getAttributeValue:(e,t)=>{if(t==="class"&&"getNameAndAliases"in e)return e.getNameAndAliases().join(" ");if(t==="name"&&e._parsedProps?.name)return e._parsedProps.name;if(e._parsedProps&&t in e._parsedProps){let i=e._parsedProps[t];return typeof i=="string"?i:i!=null?String(i):null}if(t in e){let i=e[t];return typeof i=="string"?i:i!=null?String(i):null}let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e){let o=e[i];return typeof o=="string"?o:o!=null?String(o):null}}return null},hasAttrib:(e,t)=>{if(t==="class")return!!e._parsedProps?.name;if(e._parsedProps&&t in e._parsedProps||t in e)return!0;let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e)return!0}return!1},getSiblings:e=>e.parent?e.parent.children:[],prevElementSibling:e=>{if(!e.parent)return null;let t=e.parent.children,n=t.indexOf(e);return n>0?t[n-1]:null},getText:()=>"",removeSubsets:e=>e.filter((t,n)=>!e.some((i,o)=>n!==o&&i!==t&&i.getDescendants().includes(t))),existsOne:(e,t)=>t.some(e),findAll:(e,t)=>{let n=[],i=o=>{e(o)&&n.push(o);for(let r of o.children)i(r)};for(let o of t)i(o);return n},findOne:(e,t)=>{for(let n of t){if(e(n))return n;let i=n.children;if(i.length>0){let o=F4.findOne(e,i);if(o)return o}}return null},equals:(e,t)=>e._renderId===t._renderId,isHovered:e=>!1,isVisited:e=>!1,isActive:e=>!1},w5t={...F4,getChildren:e=>e.children.filter(t=>!t.isSubcircuit)},KV={...F4,getChildren:e=>e.children.filter(t=>t.isSubcircuit)},JV=e=>{if(/net\.[^\s>]*\./.test(e))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(e))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(e)){let t=e.match(/net\.([^ >]+)/),n=t?t[1]:"";throw new Error(`Net name "${n}" cannot start with a number, try using a prefix like "VBUS1"`)}return e.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(t,n,i,o)=>{let r=/^\d+$/.test(o)?`pin${o}`:o;return`${n}.${i} > .${r}`}).trim()},x4={adapter:w5t,cacheResults:!0},xe=class extends L4{constructor(t){super(t);P(this,"parent",null);P(this,"children");P(this,"childrenPendingRemoval");P(this,"props");P(this,"_parsedProps");P(this,"externallyAddedAliases");P(this,"isPrimitiveContainer",!1);P(this,"canHaveTextChildren",!1);P(this,"source_group_id",null);P(this,"source_component_id",null);P(this,"schematic_component_id",null);P(this,"pcb_component_id",null);P(this,"cad_component_id",null);P(this,"fallbackUnassignedName");P(this,"_cachedSelectAllQueries",new Map);P(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=t??{},this.externallyAddedAliases=[];let i=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(t??{});if(i.success)this._parsedProps=i.data;else throw new S5t(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:p.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(t){let n=this;for(;n;){if(n._parsedProps&&t in n._parsedProps)return n._parsedProps[t];n=n.parent}if(this.root?.platform&&t in this.root.platform)return this.root.platform[t]}getInheritedMergedProperty(t){let n=this.parent?.getInheritedMergedProperty?.(t),i=this._parsedProps?.[t];return{...n,...i}}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(t){let n=this.config.zodProps.parse({...this.props,...t}),i=this.props;this.props=n,this._parsedProps=this.config.zodProps.parse(t),this.onPropsChange({oldProps:i,newProps:n,changedProps:Object.keys(t)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:t}=this.props;return typeof t=="string"?parseFloat(t):t??null}computePcbPropsTransform(){let{_parsedProps:t}=this,n=this._getPcbRotationBeforeLayout()??0;return Qn(vn(t.pcbX??0,t.pcbY??0),Ua(n*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let t=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(t&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let n=this._getPcbRotationBeforeLayout()??0;return Qn(this.parent?._computePcbGlobalTransformBeforeLayout()??zi(),Qn(vn(t.x,t.y),Ua(n*Math.PI/180)))}if(this.isPcbPrimitive){let n=this.getPrimitiveContainer();if(n&&n._parsedProps.layer==="bottom")return Qn(this.parent?._computePcbGlobalTransformBeforeLayout()??zi(),y8(),this.computePcbPropsTransform())}return Qn(this.parent?._computePcbGlobalTransformBeforeLayout()??zi(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}getParentNormalComponent(){let t=this.parent;for(;t;){if(t.isPrimitiveContainer&&t.doInitialPcbComponentRender)return t;t=t.parent}return null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let t=this.getPrimitiveContainer(),n=t?t._parsedProps.layer==="bottom":!1;return{isFlipped:n,maybeFlipLayer:o=>n?o==="top"?"bottom":"top":o}}_setPositionFromLayout(t){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:t}=this;return Qn(vn(t.schX??0,t.schY??0))}computeSchematicGlobalTransform(){let t=this._getSchematicGlobalManualPlacementTransform(this);return t||Qn(this.parent?.computeSchematicGlobalTransform?.()??zi(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:t}=this,n=this.config.schematicSymbolName,i={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},o=t.schOrientation!==void 0?i[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}`);let r=`${n}_horz`,s=`${n}_vert`,a=`${n}_up`,c=`${n}_down`,l=`${n}_left`,u=`${n}_right`;if(u in ti&&o===0)return u;if(a in ti&&o===90)return a;if(l in ti&&o===180)return l;if(c in ti&&o===270)return c;if(r in ti&&(o===0||o===180))return r;if(s in ti&&(o===90||o===270))return s;if(n in ti)return n}_getSchematicSymbolNameOrThrow(){let t=this._getSchematicSymbolName();if(!t)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return t}getSchematicSymbol(){let t=this._getSchematicSymbolName();return t?ti[t]??null:null}_getPcbManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n?.pcb_placements;if(!i)return null;for(let o of i)if(b4(t,o.selector)||t.props.name===o.selector)return Ne(this._computePcbGlobalTransformBeforeLayout(),o.center);return null}_getSchematicManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n.schematic_placements;if(!i)return null;for(let o of i)if(b4(t,o.selector)||t.props.name===o.selector)return Ne(this.computeSchematicGlobalTransform(),o.center);return null}_getSchematicGlobalManualPlacementTransform(t){let n=this.getSubcircuit()?._parsedProps.manualEdits;if(!n)return null;for(let i of n.schematic_placements??[])if((b4(t,i.selector)||t.props.name===i.selector)&&i.relative_to==="group_center")return Qn(this.parent?._computePcbGlobalTransformBeforeLayout()??zi(),vn(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return Ne(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return Ne(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(t){this.parent=t}onPropsChange(t){}onChildChanged(t){this.parent?.onChildChanged?.(t)}add(t){let n=t.__text;if(typeof n=="string"){if(this.canHaveTextChildren||n.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${n}"`)}if(Object.keys(t).length!==0){if(this.lowercaseComponentName==="board"&&t.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(t.lowercaseComponentName==="panel")throw new Error("<panel> must be a root-level element");if(!t.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(t)}"`);t.onAddToParent(this),t.parent=this,this.children.push(t)}}addAll(t){for(let n of t)this.add(n)}remove(t){this.children=this.children.filter(n=>n!==t),this.childrenPendingRemoval.push(t),t.shouldBeRemoved=!0}getSubcircuitSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?n:`${this.parent.getSubcircuitSelector()} > ${n}`}getFullPathSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName,i=this.parent?.getFullPathSelector?.();return i?`${i} > ${n}`:n}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(t){return this.getNameAndAliases().includes(t)}isMatchingAnyOf(t){return this.getNameAndAliases().some(n=>t.map(i=>i.toString()).includes(n))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(t){let n=[this.componentName,this.lowercaseComponentName],i=[this.name].filter(Boolean),o=t.trim().split(/\> /)[0],r=o[0];return o.length>1?!1:!!(t==="*"||t[0]==="#"&&t.slice(1)===this.props.id||t[0]==="."&&i.includes(t.slice(1))||/^[a-zA-Z0-9_]/.test(r)&&n.includes(r))}getSubcircuit(){if(this.isSubcircuit)return this;let t=this.parent?.getSubcircuit?.();if(!t)throw new Error("Component is not inside an opaque group (no board?)");return t}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let t=this.selectAll("port");for(let n of t){let o=(n.getParentNormalComponent?.()??n.parent)?.getNameAndAliases(),r=n.getNameAndAliases();if(o)for(let s of o)for(let a of r){let c=[`.${s} > .${a}`,`.${s} .${a}`];for(let l of c){let u=this._cachedSelectAllQueries.get(l);u?u.push(n):this._cachedSelectAllQueries.set(l,[n])}}}for(let[n,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(n,i[0])}selectAll(t){if(this._cachedSelectAllQueries.has(t))return this._cachedSelectAllQueries.get(t);let n=JV(t),i=hI(n,this,x4);if(i.length>0)return this._cachedSelectAllQueries.set(t,i),i;let[o,...r]=n.split(" "),s=jg(o,this,{adapter:KV});if(!s)return[];let a=s.selectAll(r.join(" "));return this._cachedSelectAllQueries.set(t,a),a}selectOne(t,n){if(this._cachedSelectOneQueries.has(t))return this._cachedSelectOneQueries.get(t);let i=JV(t);n?.port&&(n.type="port");let o=null;if(n?.type&&(o=hI(i,this,x4).find(l=>l.lowercaseComponentName===n.type)),o??(o=jg(i,this,x4)),o)return this._cachedSelectOneQueries.set(t,o),o;let[r,...s]=i.split(" "),a=jg(r,this,{adapter:KV});return a?(o=a.selectOne(s.join(" "),n),this._cachedSelectOneQueries.set(t,o),o):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:t}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[t(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?this.root?._getBoard()?.allLayers??["top","bottom"]:[]}return[]}getDescendants(){let t=[];for(let n of this.children)t.push(n),t.push(...n.getDescendants());return t}getSelectableDescendants(){let t=[];for(let n of this.children)n.isSubcircuit?t.push(n):(t.push(n),t.push(...n.getSelectableDescendants()));return t}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this;return{schWidth:t.schWidth,schHeight:t.schHeight}}renderError(t){if(typeof t=="string")return super.renderError(t);switch(t.type){case"pcb_placement_error":this.root?.db.pcb_placement_error.insert(t);break;case"pcb_via_clearance_error":this.root?.db.pcb_via_clearance_error.insert(t);break;case"pcb_trace_error":this.root?.db.pcb_trace_error.insert(t);break;case"pcb_manual_edit_conflict_warning":this.root?.db.pcb_manual_edit_conflict_warning.insert(t);break;default:this.root?.db.pcb_placement_error.insert(t)}}getString(){let{lowercaseComponentName:t,_parsedProps:n,parent:i}=this;return n?.pinNumber!==void 0&&i?.props?.name&&n?.name?`<${t}#${this._renderId}(pin:${n.pinNumber} .${i?.props.name}>.${n.name}) />`:i?.props?.name&&n?.name?`<${t}#${this._renderId}(.${i?.props.name}>.${n?.name}) />`:n?.from&&n?.to?`<${t}#${this._renderId}(from:${n.from} to:${n?.to}) />`:n?.name?`<${t}#${this._renderId} name=".${n?.name}" />`:n?.portHints?`<${t}#${this._renderId}(${n.portHints.map(o=>`.${o}`).join(", ")}) />`:`<${t}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},P5t=class extends xe{constructor(e,t){super(e),this._parsedProps={...e,error:t,type:e.type||"unknown",component_name:e.name,error_type:"source_failed_to_create_component_error",message:t instanceof Error?t.message:String(t),pcbX:e.pcbX,pcbY:e.pcbY,schX:e.schX,schY:e.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:p.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let e=this._getGlobalPcbPositionBeforeLayout(),t=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:e,schematic_center:t})}}};function I5t(e,t){return new P5t(e,t)}function T5t(e,t){let n=e;return n.__tsci={...t},e}var M5t={supportsMutation:!0,createInstance(e,t){let n=Ax[e];if(!n)throw Object.keys(Ax).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type "${e}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return T5t(new n(t),{})}catch(i){return I5t({...t,componentType:e},i)}},createTextInstance(e){return{__text:e}},appendInitialChild(e,t){e.add(t)},appendChild(e,t){e.add(t)},appendChildToContainer(e,t){e.add(t)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(e){return e},preparePortalMount(e){throw new Error("Function not implemented.")},scheduleTimeout(e,t){throw new Error("Function not implemented.")},cancelTimeout(e){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(e){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(e,t)=>{throw new Error("Function not implemented.")},getInstanceFromScope:e=>{throw new Error("Function not implemented.")},detachDeletedInstance:e=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>Nx.DefaultEventPriority,getCurrentUpdatePriority:()=>Nx.DefaultEventPriority,resolveUpdatePriority:()=>Nx.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},Tx=(0,PH.default)(M5t),CH=e=>{let t={children:[],props:{name:"$root"},add(r){r.parent=this,this.children.push(r)},computePcbGlobalTransform(){return zi()}},n=[],i=Tx.createContainer(t,0,null,!1,null,"tsci",r=>{console.log("Error in createContainer"),console.error(r),n.push(r)},null);if(Tx.updateContainerSync(e,i,null,()=>{}),Tx.flushSyncWork(),n.length>0)throw n[0];let o=Tx.getPublicRootInstance(i);return o||t.children[0]},Om=(e,t)=>{if(typeof e=="number")return e;if(e.startsWith("pin"))return Number(e.slice(3));if(!t)throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`);for(let n in t)if((Array.isArray(t[n])?t[n]:[t[n]]).includes(e))return Number(n.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`)},C5t=(e,t)=>{if(!e)return;let n={},i={};for(let[o,r]of Object.entries(e)){let s=Om(o,t);i[s]={...i[s],...r}}for(let[o,r]of Object.entries(i)){let s=`pin${o}`;n[s]={bottom_margin:r.bottomMargin,left_margin:r.leftMargin,right_margin:r.rightMargin,top_margin:r.topMargin}}return n},E5t=e=>{if(e){if("leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e)return{left_side:e.leftSide,right_side:e.rightSide,top_side:e.topSide,bottom_side:e.bottomSide};if("leftPinCount"in e||"rightPinCount"in e||"topPinCount"in e||"bottomPinCount"in e)return{left_size:e.leftPinCount,right_size:e.rightPinCount,top_size:e.topPinCount,bottom_size:e.bottomPinCount};if("leftSize"in e||"rightSize"in e||"topSize"in e||"bottomSize"in e)return{left_size:e.leftSize,right_size:e.rightSize,top_size:e.topSize,bottom_size:e.bottomSize}}};function EH(e){let t=[];for(let n=0;n<e.length-1;n++)t.push([e[n],e[n+1]]);return t}var N5t=p.object({name:p.string().refine(e=>!/[+-]/.test(e),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),z4=class extends xe{constructor(){super(...arguments);P(this,"source_net_id");P(this,"subcircuit_connectivity_map_key",null)}get config(){return{componentName:"Net",zodProps:N5t}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=n.name.startsWith("GND"),o=n.name.startsWith("V"),r=t.source_net.insert({name:n.name,member_source_group_ids:[],is_ground:i,is_power:o,is_positive_voltage_source:o});this.source_net_id=r.source_net_id}doInitialSourceParentAttachment(){let t=this.getSubcircuit();if(!t)return;let{db:n}=this.root;n.source_net.update(this.source_net_id,{subcircuit_id:t.subcircuit_id})}getAllConnectedPorts(){let t=this.getSubcircuit().selectAll("port"),n=[];for(let i of t){let o=i._getDirectlyConnectedTraces();for(let r of o)if(r._isExplicitlyConnectedToNet(this)){n.push(i);break}}return n}_getAllDirectlyConnectedTraces(){let t=this.getSubcircuit().selectAll("trace"),n=[];for(let i of t)i._isExplicitlyConnectedToNet(this)&&n.push(i);return n}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getAllDirectlyConnectedTraces().filter(s=>(s._portsRoutedOnPcb?.length??0)>0),o=[];for(let s of i){let a=s._portsRoutedOnPcb,c=o.find(l=>a.some(u=>l.ports.includes(u)));if(!c){o.push({ports:[...a],traces:[s]});continue}c.traces.push(s),c.ports.push(...a)}if(o.length===0)return;let r=EH(o);for(let[s,a]of r){let c=s.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),u=1/0,h=[-1,-1];for(let w=0;w<c.length;w++){let S=c[w];for(let T=0;T<l.length;T++){let I=l[T],E=Math.sqrt((S.x-I.x)**2+(S.y-I.y)**2);E<u&&(u=E,h=[w,T])}}let d=s.ports[h[0]],_=a.ports[h[1]],y=t.toArray().filter(w=>w.type==="pcb_smtpad"||w.type==="pcb_trace"||w.type==="pcb_plated_hole"||w.type==="pcb_hole"||w.type==="source_port"||w.type==="pcb_port"),{solution:g}=oz(y.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[d.source_port_id,_.source_port_id]}])),x=g[0];if(!x){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[d.pcb_component_id,_.pcb_component_id].filter(Boolean),pcb_port_ids:[d.pcb_port_id,_.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}t.pcb_trace.insert(x)}}renderError(t){if(typeof t=="string")return super.renderError(t);this.root?.db.pcb_trace_error.insert(t)}},zx=(e,t)=>{for(let n of t)if(typeof n=="string"&&n.startsWith("net.")){if(/net\.[^\s>]*\./.test(n))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(n))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(n)){let o=n.split("net.")[1];throw new Error(`Net name "${o}" cannot start with a number, try using a prefix like "VBUS1"`)}let i=e.getSubcircuit();if(!i.selectOne(n)){let o=new z4({name:n.split("net.")[1]});i.add(o)}}},Am=class extends xe{constructor(){super(...arguments);P(this,"pcb_smtpad_id",null);P(this,"matchedPort",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:Nz}}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="rotated_rect"){let i=(t.ccwRotation??0)*Math.PI/180,o=Math.cos(i),r=Math.sin(i),s=Math.abs(t.width*o)+Math.abs(t.height*r),a=Math.abs(t.width*r)+Math.abs(t.height*o);return{width:s,height:a}}if(t.shape==="polygon"){let n=t.points,i=n.map(l=>l.x),o=n.map(l=>l.y),r=Math.min(...i),s=Math.max(...i),a=Math.min(...o),c=Math.max(...o);return{width:s-r,height:c-a}}if(t.shape==="pill")return{width:t.width,height:t.height};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.coveredWithSolderMask??!1,o=!i;if(!n.portHints)return;let r=this.getSubcircuit(),s=this._getGlobalPcbPositionBeforeLayout(),a=this._computePcbGlobalTransformBeforeLayout(),u=(Ar(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,h=.01,d=Math.abs(u)<h||Math.abs(u-180)<h||Math.abs(u-360)<h,_=Math.abs(u-90)<h||Math.abs(u-270)<h,y=Math.abs(u-360)<h?0:u,g=y,{maybeFlipLayer:x,isFlipped:w}=this._getPcbPrimitiveFlippedHelpers();w&&(y=(360-y+360)%360);let S=null,T=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(n.shape==="circle")S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"circle",radius:n.radius,port_hints:n.portHints.map(I=>I.toString()),is_covered_with_solder_mask:i,x:s.x,y:s.y,subcircuit_id:r?.subcircuit_id??void 0}),o&&t.pcb_solder_paste.insert({layer:S.layer,shape:"circle",radius:S.radius*.7,x:S.x,y:S.y,pcb_component_id:S.pcb_component_id,pcb_smtpad_id:S.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});else if(n.shape==="rect")!d&&!_?S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"rotated_rect",width:n.width,height:n.height,corner_radius:n.cornerRadius??void 0,x:s.x,y:s.y,ccw_rotation:y,port_hints:n.portHints.map(E=>E.toString()),is_covered_with_solder_mask:i,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"rect",width:_?n.height:n.width,height:_?n.width:n.height,corner_radius:n.cornerRadius??void 0,port_hints:n.portHints.map(E=>E.toString()),is_covered_with_solder_mask:i,x:s.x,y:s.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),o&&(S.shape==="rect"?t.pcb_solder_paste.insert({layer:x(n.layer??"top"),shape:"rect",width:S.width*.7,height:S.height*.7,x:S.x,y:S.y,pcb_component_id:S.pcb_component_id,pcb_smtpad_id:S.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):S.shape==="rotated_rect"&&t.pcb_solder_paste.insert({layer:x(n.layer??"top"),shape:"rotated_rect",width:S.width*.7,height:S.height*.7,x:S.x,y:S.y,ccw_rotation:S.ccw_rotation,pcb_component_id:S.pcb_component_id,pcb_smtpad_id:S.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));else if(n.shape==="rotated_rect"){let I=n.ccwRotation??0,E=(g+I+360)%360,M=w?(360-E+360)%360:E;S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"rotated_rect",width:n.width,height:n.height,corner_radius:n.cornerRadius??void 0,x:s.x,y:s.y,ccw_rotation:M,port_hints:n.portHints.map(k=>k.toString()),is_covered_with_solder_mask:i,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),o&&t.pcb_solder_paste.insert({layer:x(n.layer??"top"),shape:"rotated_rect",width:S.width*.7,height:S.height*.7,x:s.x,y:s.y,ccw_rotation:M,pcb_component_id:T,pcb_smtpad_id:S.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="polygon"){let I=n.points.map(E=>{let M=Ne(a,{x:Y.parse(E.x),y:Y.parse(E.y)});return{x:M.x,y:M.y}});S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"polygon",points:I,port_hints:n.portHints.map(E=>E.toString()),is_covered_with_solder_mask:i,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else n.shape==="pill"&&(S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"pill",x:s.x,y:s.y,radius:n.radius,height:n.height,width:n.width,port_hints:n.portHints.map(I=>I.toString()),is_covered_with_solder_mask:i,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));S&&(this.pcb_smtpad_id=S.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_smtpad.get(this.pcb_smtpad_id);if(n.shape==="rect")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.width/2,top:n.y+n.height/2,right:n.x+n.width/2,bottom:n.y-n.height/2},width:n.width,height:n.height};if(n.shape==="rotated_rect"){let i=n.ccw_rotation*Math.PI/180,o=Math.cos(i),r=Math.sin(i),s=n.width/2,a=n.height/2,c=Math.abs(s*o)+Math.abs(a*r),l=Math.abs(s*r)+Math.abs(a*o);return{center:{x:n.x,y:n.y},bounds:{left:n.x-c,right:n.x+c,top:n.y-l,bottom:n.y+l},width:c*2,height:l*2}}if(n.shape==="circle")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.radius,top:n.y-n.radius,right:n.x+n.radius,bottom:n.y+n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){let i=n.points,o=i.map(u=>u.x),r=i.map(u=>u.y),s=Math.min(...o),a=Math.max(...o),c=Math.min(...r),l=Math.max(...r);return{center:{x:(s+a)/2,y:(c+l)/2},bounds:{left:s,top:l,right:a,bottom:c},width:a-s,height:l-c}}if(n.shape==="pill"){let i=n.width/2,o=n.height/2;return{center:{x:n.x,y:n.y},bounds:{left:n.x-i,top:n.y-o,right:n.x+i,bottom:n.y+o},width:n.width,height:n.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${n.shape}"`)}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y});let i=n.pcb_solder_paste.list().find(o=>o.pcb_smtpad_id===this.pcb_smtpad_id);i&&n.pcb_solder_paste.update(i.pcb_solder_paste_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}},D4=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_path_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:yD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenPath. Must be "top" or "bottom".`);let r=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_path.insert({pcb_component_id:a,layer:o,route:n.route.map(l=>{let u=Ne(r,{x:l.x,y:l.y});return{...l,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=c.pcb_silkscreen_path_id}_setPositionFromLayout(t){let{db:n}=this.root,{_parsedProps:i}=this,o=n.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!o)return;let r=0,s=0;for(let u of o.route)r+=u.x,s+=u.y;r/=o.route.length,s/=o.route.length;let a=t.x-r,c=t.y-s,l=o.route.map(u=>({...u,x:u.x+a,y:u.y+c}));n.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:l})}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,o=1/0,r=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),o=Math.min(o,s.y),r=Math.max(r,s.y);return{width:i-n,height:r-o}}},k5t=p.object({route:p.array(N_),source_trace_id:p.string().optional()}),$4=class extends xe{constructor(){super(...arguments);P(this,"pcb_trace_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:k5t}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),o=this.getSubcircuit(),{maybeFlipLayer:r}=this._getPcbPrimitiveFlippedHelpers(),s=this._computePcbGlobalTransformBeforeLayout(),a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=Ne(s,{x:u,y:h});return l.route_type==="wire"&&l.layer?{..._,...d,layer:r(l.layer)}:{..._,...d}}),c=t.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:n.source_trace_id,route:a,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,o=1/0,r=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),o=Math.min(o,s.y),r=Math.max(r,s.y),s.route_type==="wire"&&(n=Math.min(n,s.x-s.width/2),i=Math.max(i,s.x+s.width/2),o=Math.min(o,s.y-s.width/2),r=Math.max(r,s.y+s.width/2));return n===1/0||i===-1/0||o===1/0||r===-1/0?{width:0,height:0}:{width:i-n,height:r-o}}},Yh=class extends xe{constructor(){super(...arguments);P(this,"pcb_plated_hole_id",null);P(this,"matchedPort",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:xz}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.outerDiameter,height:t.outerDiameter};if(t.shape==="oval"||t.shape==="pill")return{width:t.outerWidth,height:t.outerHeight};if(t.shape==="circular_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};if(t.shape==="pill_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_plated_hole.get(this.pcb_plated_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y+i.height/2,right:n.x+i.width/2,bottom:n.y-i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,r=this.getSubcircuit();if(n.shape==="circle"){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:n.outerDiameter,hole_diameter:n.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="pill"&&n.rectPad){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:n.pcbRotation??0,rect_ccw_rotation:n.pcbRotation??0,rect_pad_width:n.outerWidth,rect_pad_height:n.outerHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill"||n.shape==="oval"){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:n.shape,port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:n.pcbRotation??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="circular_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:n.holeDiameter,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,rect_border_radius:n.rectBorderRadius??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:n.holeWidth,hole_height:n.holeHeight,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},Rx=class extends xe{constructor(){super(...arguments);P(this,"pcb_keepout_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:eD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let t=this.getSubcircuit(),{db:n}=this.root,{_parsedProps:i}=this,o=this._getGlobalPcbPositionBeforeLayout(),r=Ar(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(r.rotation.angle*(180/Math.PI)-90)%180<.01,a=null;i.shape==="circle"?a=n.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:o.x,y:o.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0}):i.shape==="rect"&&(a=n.pcb_keepout.insert({layers:["top"],shape:"rect",...s?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:o.x,y:o.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0})),a&&(this.pcb_keepout_id=a.pcb_keepout_id)}},Xh=class extends xe{constructor(){super(...arguments);P(this,"pcb_hole_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:kz}}getPcbSize(){let{_parsedProps:t}=this,n=t.shape==="pill",i=t.shape==="rect";return n?{width:t.width,height:t.height}:i?{width:t.width,height:t.height}:{width:t.diameter,height:t.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),o=this._getGlobalPcbPositionBeforeLayout();if(n.shape==="pill")if(n.pcbRotation&&n.pcbRotation!==0){let r=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"rotated_pill",hole_width:n.width,hole_height:n.height,x:o.x,y:o.y,ccw_rotation:n.pcbRotation,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=r.pcb_hole_id}else{let r=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"pill",hole_width:n.width,hole_height:n.height,x:o.x,y:o.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=r.pcb_hole_id}else if(n.shape==="rect"){let r=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"rect",hole_width:n.width,hole_height:n.height,x:o.x,y:o.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=r.pcb_hole_id}else{let r=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"circle",hole_diameter:n.diameter,x:o.x,y:o.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=r.pcb_hole_id}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_hole.get(this.pcb_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_hole.update(this.pcb_hole_id,{x:t.x,y:t.y})}},Dx=class extends xe{constructor(){super(...arguments);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:_D}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),o=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:r,isFlipped:s}=this._getPcbPrimitiveFlippedHelpers(),a=this.getSubcircuit(),c=0;if(n.pcbRotation!==void 0&&n.pcbRotation!==0)c=n.pcbRotation;else{let d=this._computePcbGlobalTransformBeforeLayout();c=Ar(d).rotation.angle*180/Math.PI}s&&(c=(c+180)%360);let l=new Set(n.layers);n.layer&&l.add(n.layer);let u=l.size>0?Array.from(l):["top"],h=n.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1;for(let d of u)t.pcb_silkscreen_text.insert({anchor_alignment:n.anchorAlignment,anchor_position:{x:o.x,y:o.y},font:n.font??"tscircuit2024",font_size:h,layer:r(d),text:n.text??"",ccw_rotation:c,pcb_component_id:i.pcb_component_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:t}=this,n=t.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1,o=(t.text??"").length*n,r=n;return{width:o*n,height:r*n}}},Rm=class extends xe{constructor(){super(...arguments);P(this,"pcb_cutout_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:Ez}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),o=this.getGroup()?.pcb_group_id??void 0,r=this._getGlobalPcbPositionBeforeLayout(),a=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,c;if(n.shape==="rect"){let l=typeof a=="string"?parseInt(a.replace("deg",""),10):a,u=Math.abs(l%180)===90,h={shape:"rect",center:r,width:u?n.height:n.width,height:u?n.width:n.height,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:o};c=t.pcb_cutout.insert(h)}else if(n.shape==="circle"){let l={shape:"circle",center:r,radius:n.radius,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:o};c=t.pcb_cutout.insert(l)}else if(n.shape==="polygon"){let l=this._computePcbGlobalTransformBeforeLayout(),h={shape:"polygon",points:n.points.map(d=>Ne(l,d)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:o};c=t.pcb_cutout.insert(h)}c&&(this.pcb_cutout_id=c.pcb_cutout_id)}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return{width:0,height:0};let n=1/0,i=-1/0,o=1/0,r=-1/0;for(let s of t.points)n=Math.min(n,s.x),i=Math.max(i,s.x),o=Math.min(o,s.y),r=Math.max(r,s.y);return{width:i-n,height:r-o}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_cutout.get(this.pcb_cutout_id);if(!n)return super._getPcbCircuitJsonBounds();if(n.shape==="rect")return{center:n.center,bounds:{left:n.center.x-n.width/2,top:n.center.y+n.height/2,right:n.center.x+n.width/2,bottom:n.center.y-n.height/2},width:n.width,height:n.height};if(n.shape==="circle")return{center:n.center,bounds:{left:n.center.x-n.radius,top:n.center.y+n.radius,right:n.center.x+n.radius,bottom:n.center.y-n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){if(n.points.length===0)return super._getPcbCircuitJsonBounds();let i=1/0,o=-1/0,r=1/0,s=-1/0;for(let a of n.points)i=Math.min(i,a.x),o=Math.max(o,a.x),r=Math.min(r,a.y),s=Math.max(s,a.y);return{center:{x:(i+o)/2,y:(r+s)/2},bounds:{left:i,top:s,right:o,bottom:r},width:o-i,height:s-r}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(t){if(!this.pcb_cutout_id)return;let{db:n}=this.root,i=n.pcb_cutout.get(this.pcb_cutout_id);if(i){if(i.shape==="rect"||i.shape==="circle")n.pcb_cutout.update(this.pcb_cutout_id,{...i,center:t});else if(i.shape==="polygon"){let o=this._getPcbCircuitJsonBounds().center,r=t.x-o.x,s=t.y-o.y,a=i.points.map(c=>({x:c.x+r,y:c.y+s}));n.pcb_cutout.update(this.pcb_cutout_id,{...i,points:a})}}}},A5t=({elm:e,pinLabels:t,layer:n,readableRotation:i,anchorAlignment:o})=>{let r=e.text.replace(/[{}]/g,"").toLowerCase(),s=r;if(Array.isArray(t)){let a=parseInt(r.replace(/[^\d]/g,""),10)-1;s=String(t[a]??r)}else typeof t=="object"&&(s=String(t[r]??r));return new Dx({anchorAlignment:o||"center",text:s??r,layer:n||"top",fontSize:e.font_size+.2,pcbX:isNaN(e.anchor_position.x)?0:e.anchor_position.x,pcbY:e.anchor_position.y,pcbRotation:i??0})},R5t=(e,t)=>{let n=parseInt(e||"0",10),i;return t!=null?i=t-n:i=n,(i%360+360)%360},Vh=({componentName:e,componentRotation:t,footprinterString:n,pinLabels:i,pcbPinLabels:o},r)=>{let s=[];for(let a of r)if(a.type==="pcb_smtpad"&&a.shape==="rect")s.push(new Am({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"rect",height:a.height,width:a.width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius}));else if(a.type==="pcb_smtpad"&&a.shape==="circle")s.push(new Am({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"circle",radius:a.radius,portHints:a.port_hints}));else if(a.type==="pcb_smtpad"&&a.shape==="pill")s.push(new Am({shape:"pill",height:a.height,width:a.width,radius:a.radius,portHints:a.port_hints,pcbX:a.x,pcbY:a.y,layer:a.layer}));else if(a.type==="pcb_silkscreen_path")s.push(new D4({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?s.push(new Yh({pcbX:a.x,pcbY:a.y,shape:"circle",holeDiameter:a.hole_diameter,outerDiameter:a.outer_diameter,portHints:a.port_hints})):a.shape==="circular_hole_with_rect_pad"?s.push(new Yh({pcbX:a.x,pcbY:a.y,shape:"circular_hole_with_rect_pad",holeDiameter:a.hole_diameter,rectPadHeight:a.rect_pad_height,rectPadWidth:a.rect_pad_width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y})):a.shape==="pill"||a.shape==="oval"?s.push(new Yh({pcbX:a.x,pcbY:a.y,shape:a.shape,holeWidth:a.hole_width,holeHeight:a.hole_height,outerWidth:a.outer_width,outerHeight:a.outer_height,portHints:a.port_hints})):a.shape==="pill_hole_with_rect_pad"&&s.push(new Yh({pcbX:a.x,pcbY:a.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:a.hole_width,holeHeight:a.hole_height,rectPadWidth:a.rect_pad_width,rectPadHeight:a.rect_pad_height,portHints:a.port_hints,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y}));else if(a.type==="pcb_keepout"&&a.shape==="circle")s.push(new Rx({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius}));else if(a.type==="pcb_keepout"&&a.shape==="rect")s.push(new Rx({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height}));else if(a.type==="pcb_hole"&&a.hole_shape==="circle")s.push(new Xh({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_hole"&&a.hole_shape==="rect")s.push(new Xh({pcbX:a.x,pcbY:a.y,shape:"rect",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="pill")s.push(new Xh({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="rotated_pill")s.push(new Xh({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height,pcbRotation:a.ccw_rotation}));else if(a.type==="pcb_cutout")a.shape==="rect"?s.push(new Rm({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?s.push(new Rm({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&s.push(new Rm({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=R5t(t,a.ccw_rotation);n?.includes("pinrow")&&a.text.includes("PIN")?s.push(A5t({elm:a,pinLabels:o??i??{},layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):s.push(new Dx({anchorAlignment:a.anchor_alignment||"center",text:e,fontSize:a.font_size+.2,pcbX:Number.isNaN(a.anchor_position.x)?0:a.anchor_position.x,pcbY:a.anchor_position.y,pcbRotation:c??0}))}else a.type==="pcb_trace"&&s.push(new $4({route:a.route}));return s};function $x(e){let t=1/0,n=1/0,i=-1/0,o=-1/0,r=!1;for(let c of e)if(c.isPcbPrimitive&&!c.componentName.startsWith("Silkscreen")){let{x:l,y:u}=c._getGlobalPcbPositionBeforeLayout(),{width:h,height:d}=c.getPcbSize();t=Math.min(t,l-h/2),n=Math.min(n,u-d/2),i=Math.max(i,l+h/2),o=Math.max(o,u+d/2),r=!0}else if(c.children.length>0){let l=$x(c.children);(l.width>0||l.height>0)&&(t=Math.min(t,l.minX),n=Math.min(n,l.minY),i=Math.max(i,l.maxX),o=Math.max(o,l.maxY),r=!0)}if(!r)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let s=i-t,a=o-n;return s<0&&(s=0),a<0&&(a=0),{minX:t,minY:n,maxX:i,maxY:o,width:s,height:a}}function QV(e){let t=e%360;return t<0?t+360:t}function O5t(e,t,n,i){return i==="counterclockwise"?n>=t?e>=t&&e<=n:e>=t||e<=n:n<=t?e<=t&&e>=n:e<=t||e>=n}function L5t(e){let t=e.center,n=e.radius,i=e.start_angle_degrees,o=e.end_angle_degrees,r=e.direction??"counterclockwise";if(!t||typeof t.x!="number"||typeof t.y!="number"||typeof n!="number"||typeof i!="number"||typeof o!="number")return null;let s=QV(i),a=QV(o),c=new Set([s,a]),l=[0,90,180,270];for(let y of l)O5t(y,s,a,r)&&c.add(y);let u=1/0,h=1/0,d=-1/0,_=-1/0;for(let y of c){let g=y*Math.PI/180,x=t.x+n*Math.cos(g),w=t.y+n*Math.sin(g);u=Math.min(u,x),d=Math.max(d,x),h=Math.min(h,w),_=Math.max(_,w)}return!Number.isFinite(u)||!Number.isFinite(h)?null:{minX:u,maxX:d,minY:h,maxY:_}}function NH(e){let t=1/0,n=1/0,i=-1/0,o=-1/0;for(let r of e){let s,a,c,l;if(r.type==="schematic_component")s=r.center?.x,a=r.center?.y,c=r.size?.width,l=r.size?.height;else if(r.type==="schematic_box")s=r.x,a=r.y,c=r.width,l=r.height;else if(r.type==="schematic_port")s=r.center?.x,a=r.center?.y,c=.2,l=.2;else if(r.type==="schematic_text")s=r.position?.x,a=r.position?.y,c=(r.text?.length??0)*.1,l=.2;else if(r.type==="schematic_line"){let u=r.x1??0,h=r.y1??0,d=r.x2??0,_=r.y2??0;s=(u+d)/2,a=(h+_)/2,c=Math.abs(d-u),l=Math.abs(_-h)}else if(r.type==="schematic_rect")s=r.center?.x,a=r.center?.y,c=r.width,l=r.height;else if(r.type==="schematic_circle"){s=r.center?.x,a=r.center?.y;let u=r.radius;typeof u=="number"&&(c=u*2,l=u*2)}else if(r.type==="schematic_arc"){let u=L5t(r);u&&(t=Math.min(t,u.minX),i=Math.max(i,u.maxX),n=Math.min(n,u.minY),o=Math.max(o,u.maxY));continue}typeof s=="number"&&typeof a=="number"&&typeof c=="number"&&typeof l=="number"&&(t=Math.min(t,s-c/2),i=Math.max(i,s+c/2),n=Math.min(n,a-l/2),o=Math.max(o,a+l/2))}return{minX:t,maxX:i,minY:n,maxY:o}}function F5t(e,t){let n=t.x-e.x,i=t.y-e.y;return Math.abs(n)>Math.abs(i)?n>=0?"right":"left":i>=0?"up":"down"}var tH=e=>{if(e.length<=1)return!0;let t=e.map(r=>{let s=r._getPcbCircuitJsonBounds();return{left:s.bounds.left,right:s.bounds.right,top:s.bounds.top,bottom:s.bounds.bottom}}),n=Array(t.length).fill(!1).map(()=>Array(t.length).fill(!1));for(let r=0;r<t.length;r++)for(let s=r+1;s<t.length;s++){let a=t[r],c=t[s];n[r][s]=n[s][r]=!(a.right<c.left||a.left>c.right||a.bottom>c.top||a.top<c.bottom)}let i=new Set,o=r=>{i.add(r);for(let s=0;s<t.length;s++)n[r][s]&&!i.has(s)&&o(s)};return o(0),i.size===t.length},eH=e=>{if(e.length===0)throw new Error("Cannot get center of empty PCB primitives array");let t=e.map(o=>o._getPcbCircuitJsonBounds().center).filter(Boolean),n=t.reduce((o,r)=>o+r.x,0),i=t.reduce((o,r)=>o+r.y,0);return{x:n/t.length,y:i/t.length}},z5t=p.object({name:p.string().optional(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),layer:p.string().optional(),layers:p.array(p.string()).optional(),schX:p.number().optional(),schY:p.number().optional(),direction:p.enum(["up","down","left","right"]).optional(),connectsTo:p.union([p.string(),p.array(p.string())]).optional()}),Ni=class extends xe{constructor(t,n={}){if(!t.name&&t.pinNumber!==void 0&&(t.name=`pin${t.pinNumber}`),!t.name)throw new Error("Port must have a name or a pinNumber");super(t);P(this,"source_port_id",null);P(this,"pcb_port_id",null);P(this,"schematic_port_id",null);P(this,"schematicSymbolPortDef",null);P(this,"matchedComponents");P(this,"facingDirection",null);P(this,"originDescription",null);n.originDescription&&(this.originDescription=n.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:z5t}}isGroupPort(){return this.parent?.componentName==="Group"}isComponentPort(){return!this.isGroupPort()}_getConnectedPortsFromConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo;if(!n)return[];let i=[],o=Array.isArray(n)?n:[n];for(let r of o){let s=this.getSubcircuit().selectOne(r,{type:"port"});s&&i.push(s)}return i}_isBoardPinoutFromAttributes(){let t=this.parent;if(t?._parsedProps?.pinAttributes){let n=t._parsedProps.pinAttributes;for(let i of this.getNameAndAliases())if(n[i]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let t=this.matchedComponents.find(i=>i.isPcbPrimitive),n=this.parent;if(n&&!n.props.footprint)throw new Error(`${n.componentName} "${n.props.name}" does not have a footprint. Add a footprint prop, e.g. <${n.componentName.toLowerCase()} footprint="..." />`);if(!t)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return t?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_port.get(this.pcb_port_id);return{center:{x:n.x,y:n.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let t=this.parent;if(!t||!t._getInternallyConnectedPins)return[];let n=t._getInternallyConnectedPins();for(let i of n)if(i.some(o=>o===this))return i;return[]}_hasSchematicPort(){let{schX:t,schY:n}=this._parsedProps;if(t!==void 0&&n!==void 0)return!0;let i=this.getParentNormalComponent();if(i?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(a=>a.schematicSymbolPortDef));let r=i?._getSchematicBoxDimensions();return!!(r&&this.props.pinNumber!==void 0&&r.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let{schX:t,schY:n}=this._parsedProps;if(t!==void 0&&n!==void 0)return{x:t,y:n};let i=this.getParentNormalComponent(),o=i?.getSchematicSymbol();if(o){let s=this.schematicSymbolPortDef;if(!s&&(s=this._getPortsInternallyConnectedToThisPort().find(c=>c.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!s))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let a=Qn(i.computeSchematicGlobalTransform(),vn(-o.center.x,-o.center.y));return Ne(a,s)}let r=i?._getSchematicBoxDimensions();if(r&&this.props.pinNumber!==void 0){let s=r.getPortPositionByPinNumber(this.props.pinNumber);if(!s)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return Ne(i.computeSchematicGlobalTransform(),s)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:t}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let n=t.schematic_port.get(this.schematic_port_id);if(!n)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return n.center}registerMatch(t){this.matchedComponents.push(t)}getNameAndAliases(){let{_parsedProps:t}=this;return Array.from(new Set([...t.name?[t.name]:[],...t.aliases??[],...typeof t.pinNumber=="number"?[`pin${t.pinNumber}`,t.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let t=this.parent?._parsedProps?.pinAttributes;if(!t)return[];let n=[];for(let i of this.getNameAndAliases()){let o=t[i];o&&n.push(o)}return n}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(t=>t.includeInBoardPinout===!0)}isMatchingPort(t){return this.isMatchingAnyOf(t.getNameAndAliases())}getPortSelector(){return`.${(this.getParentNormalComponent()??this.parent)?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:t,layers:n}=this._parsedProps;return n||(t?[t]:Array.from(new Set(this.matchedComponents.flatMap(i=>i.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(i=>!i._couldNotFindPort).filter(i=>i._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getNameAndAliases(),o=this.getParentNormalComponent(),s=(this.parent?.source_component_id?this.parent:o)?.source_component_id??null,a=t.source_port.insert({name:n.name,pin_number:n.pinNumber,port_hints:i,source_component_id:s,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=a.source_port_id}doInitialSourceParentAttachment(){let{db:t}=this.root,n=this.getParentNormalComponent(),i=this.parent?.source_component_id?this.parent:n;if(this.isGroupPort()){t.source_port.update(this.source_port_id,{source_component_id:null,subcircuit_id:this.getSubcircuit()?.subcircuit_id});return}if(!i?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);t.source_port.update(this.source_port_id,{source_component_id:i.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=i.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{matchedComponents:n}=this;if(this.isGroupPort()){let a=this._getConnectedPortsFromConnectsTo();if(a.length===0)return;let c=a[0];if(!c.pcb_port_id)return;let l=t.pcb_port.get(c.pcb_port_id),u={x:l.x,y:l.y},h=this.getSubcircuit(),d=t.pcb_port.insert({pcb_component_id:void 0,layers:c.getAvailablePcbLayers(),subcircuit_id:h?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...u,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=d.pcb_port_id;return}let i=this.getParentNormalComponent(),o=this.parent?.pcb_component_id?this.parent:i;if(!o?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()}, parentNormalComponent: ${i?.getString()})`);let r=n.filter(a=>a.isPcbPrimitive);if(r.length===0)return;let s=null;if(r.length===1&&(s=r[0]._getPcbCircuitJsonBounds().center),r.length>1){if(!tH(r))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${r.map(a=>a.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);s=eH(r)}if(s){let a=this.getSubcircuit(),c=this._shouldIncludeInBoardPinout(),l=t.pcb_port.insert({pcb_component_id:o.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...c?{is_board_pinout:!0}:{},...s,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=l.pcb_port_id}else{let a=r[0];throw new Error(`${a.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;if(this.pcb_port_id)return;if(this.isGroupPort()){let l=this._getConnectedPortsFromConnectsTo();if(l.length===0)return;let u=l[0];if(!u.pcb_port_id)return;let h=t.pcb_port.get(u.pcb_port_id),d={x:h.x,y:h.y},_=this.getSubcircuit(),y=t.pcb_port.insert({pcb_component_id:void 0,layers:u.getAvailablePcbLayers(),subcircuit_id:_?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...d,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=y.pcb_port_id;return}let n=this.matchedComponents.filter(l=>l.isPcbPrimitive);if(n.length===0)return;let i=null;if(n.length===1&&(i=n[0]._getPcbCircuitJsonBounds().center),n.length>1)try{tH(n)&&(i=eH(n))}catch{}if(!i)return;let o=this.getParentNormalComponent(),r=this.parent?.pcb_component_id?this.parent:o,s=this.getSubcircuit(),a=this._shouldIncludeInBoardPinout(),c=t.pcb_port.insert({pcb_component_id:r?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...a?{is_board_pinout:!0}:{},...i,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=c.pcb_port_id}_getBestDisplayPinLabel(){let{db:t}=this.root,n=t.source_port.get(this.source_port_id),i=[];for(let s of n?.port_hints??[])s.match(/^(pin)?\d+$/)||s.match(/^(left|right)/)&&!n?.name.match(/^(left|right)/)||i.push(s);if(this.getParentNormalComponent()?.props?.showPinAliases&&i.length>0)return i.join("/");if(i.length>0)return i[0]}doInitialSchematicPortRender(){let{db:t}=this.root,{_parsedProps:n}=this,{schX:i,schY:o}=n,r=i!==void 0&&o!==void 0?this.getParentNormalComponent():this.getPrimitiveContainer();if(!r||!this._hasSchematicPort())return;let s=r._getGlobalSchematicPositionBeforeLayout(),a=this._getGlobalSchematicPositionBeforeLayout(),c=null,l=r._getSchematicBoxDimensions();l&&n.pinNumber!==void 0&&(c=l.getPortPositionByPinNumber(n.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&t.schematic_debug_object.insert({shape:"rect",center:a,size:{width:.1,height:.1},label:"obstacle"}),c?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[c.side]:this.facingDirection=F5t(s,a);let u=this._getBestDisplayPinLabel(),d={type:"schematic_port",schematic_component_id:this.getParentNormalComponent()?.schematic_component_id,center:a,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:c?.side,pin_number:n.pinNumber,true_ccw_index:c?.trueIndex,display_pin_label:u,is_connected:!1};for(let y of this._getMatchingPinAttributes())y.requiresPower&&(d.has_input_arrow=!0),y.providesPower&&(d.has_output_arrow=!0);let _=t.schematic_port.insert(d);this.schematic_port_id=_.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_port_id&&n.pcb_port.update(this.pcb_port_id,{x:t.x,y:t.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(t=>t.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},kH=e=>{let t=e.find(n=>/^(pin)?\d+$/.test(n));return t?Number.parseInt(t.replace(/^pin/,"")):null};function Cm(e,t){let n=kH(e);if(!n)return null;let o=[...e.filter(r=>r.toString()!==n.toString()&&r!==`pin${n}`),...t?.additionalAliases?.[`pin${n}`]??[]];return new Ni({pinNumber:n,aliases:o})}var D5t=e=>{for(let t of["leftSide","rightSide","topSide","bottomSide"])if(t in e&&typeof e[t]=="number")throw new Error(`A number was specified for "${t}", you probably meant to use "size" not "side"`);return"leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e},$5t=e=>{if(D5t(e))return{leftSize:e.leftSide?.pins.length??0,rightSize:e.rightSide?.pins.length??0,topSize:e.topSide?.pins.length??0,bottomSize:e.bottomSide?.pins.length??0};let{leftSize:t=0,rightSize:n=0,topSize:i=0,bottomSize:o=0}=e;return{leftSize:t,rightSize:n,topSize:i,bottomSize:o}},Mx=.4;function AH(e){let t=e;return t.leftSide!==void 0||t.rightSide!==void 0||t.topSide!==void 0||t.bottomSide!==void 0}var j5t=e=>{let t=e.portDistanceFromEdge??.4,n=e.schPortArrangement?$5t(e.schPortArrangement):null,i={left:0,right:0,top:0,bottom:0},o=e.pinCount??null;if(o===null)if(n)o=n.leftSize+n.rightSize+n.topSize;else throw new Error("Could not determine pin count for the schematic box");if(o&&!n){let y=Math.floor(o/2);n={leftSize:o-y,rightSize:y,topSize:0,bottomSize:0}}n||(n={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let r=({side:y,sideIndex:g,truePinIndex:x})=>{if(!e.schPortArrangement||!AH(e.schPortArrangement))return x+1;let w={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[y],S=e.schPortArrangement?.[`${y}Side`]?.direction??w,T=e.schPortArrangement?.[`${y}Side`]?.pins,I=g;return S!==w&&(I=T.length-g-1),Om(T[I],e.pinLabels)},s=[],a=0,c=0;for(let y=0;y<n.leftSize;y++){let g=r({side:"left",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.topMargin&&(a+=x.topMargin),s.push({trueIndex:c,pinNumber:g,side:"left",distanceFromOrthogonalEdge:a}),x?.bottomMargin&&(a+=x.bottomMargin),y===n.leftSize-1?i.left=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.bottomSize;y++){let g=r({side:"bottom",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.leftMargin&&(a+=x.leftMargin),s.push({trueIndex:c,pinNumber:g,side:"bottom",distanceFromOrthogonalEdge:a}),x?.rightMargin&&(a+=x.rightMargin),y===n.bottomSize-1?i.bottom=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.rightSize;y++){let g=r({side:"right",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.bottomMargin&&(a+=x.bottomMargin),s.push({trueIndex:c,pinNumber:g,side:"right",distanceFromOrthogonalEdge:a}),x?.topMargin&&(a+=x.topMargin),y===n.rightSize-1?i.right=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.topSize;y++){let g=r({side:"top",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.rightMargin&&(a+=x.rightMargin),s.push({trueIndex:c,pinNumber:g,side:"top",distanceFromOrthogonalEdge:a}),x?.leftMargin&&(a+=x.leftMargin),y===n.topSize-1?i.top=a:a+=e.schPinSpacing,c++}let l=e.schWidth;if(l===void 0){l=Math.max(i.top+Mx,i.bottom+Mx),e.pinLabels&&s.filter(S=>S.side==="left"||S.side==="right").some(S=>e.pinLabels?.[`pin${S.pinNumber}`]||e.pinLabels?.[S.pinNumber])&&(l=Math.max(l,.5));let y=e.pinLabels?Math.max(...Object.values(e.pinLabels).map(x=>x.length*.1)):0,g=y>0?1.1:0;l=Math.max(l,y+g)}let u=e.schHeight;u||(u=Math.max(i.left+Mx,i.right+Mx));let h={left:{x:-l/2-t,y:i.left/2},bottom:{x:-i.bottom/2,y:-u/2-t},right:{x:l/2+t,y:-i.right/2},top:{x:i.top/2,y:u/2+t}},d={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},_=s.map(y=>{let{distanceFromOrthogonalEdge:g,side:x}=y,w=h[x],S=d[x];return{x:w.x+g*S.x,y:w.y+g*S.y,...y}});return{getPortPositionByPinNumber(y){let g=_.find(x=>x.pinNumber.toString()===y.toString());return g||null},getSize(){return{width:l,height:u}},getSizeIncludingPins(){return{width:l+(n.leftSize||n.rightSize?.4:0),height:u+(n.topSize||n.bottomSize?.4:0)}},pinCount:o}},B5t=(0,RH.default)("tscircuit:core:footprint"),OH=class extends xe{get config(){return{componentName:"Footprint",zodProps:Rz}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let e=this.children.filter(h=>h.componentName==="Constraint");if(e.length===0)return;let{isFlipped:t}=this._getPcbPrimitiveFlippedHelpers(),n=h=>t&&"left"in h&&"right"in h?{...h,left:h.right,right:h.left}:h,i=e.flatMap(h=>h._getAllReferencedComponents().componentsWithSelectors).map(({component:h,selector:d,componentSelector:_,edge:y})=>({component:h,selector:d,componentSelector:_,edge:y,bounds:h._getPcbCircuitJsonBounds()}));if(i.some(h=>h.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function o(h){return i.find(({selector:d})=>d===h)}let r=new Qp,s={};function a(h){return h in s||(s[h]=new Us(h),r.addEditVariable(s[h],wn.weak)),s[h]}for(let{selector:h,bounds:d}of i){let _=a(`${h}_x`),y=a(`${h}_y`);r.suggestValue(_,d.center.x),r.suggestValue(y,d.center.y)}for(let h of e){let d=h._parsedProps;if("xDist"in d){let{xDist:_,left:y,right:g,edgeToEdge:x,centerToCenter:w}=n(d),S=a(`${y}_x`),T=a(`${g}_x`),I=o(y)?.bounds,E=o(g)?.bounds;if(w){let M=new Cn(T,[-1,S]);r.addConstraint(new ci(M,Vn.Eq,d.xDist,wn.required))}else if(x){let M=new Cn(T,-E.width/2,[-1,S],-I.width/2);r.addConstraint(new ci(M,Vn.Eq,d.xDist,wn.required))}}else if("yDist"in d){let{yDist:_,top:y,bottom:g,edgeToEdge:x,centerToCenter:w}=d,S=a(`${y}_y`),T=a(`${g}_y`),I=o(y)?.bounds,E=o(g)?.bounds;if(w){let M=new Cn(S,[-1,T]);r.addConstraint(new ci(M,Vn.Eq,d.yDist,wn.required))}else if(x){let M=new Cn(S,I.height/2,[-1,T],-E.height/2);r.addConstraint(new ci(M,Vn.Eq,d.yDist,wn.required))}}else if("sameY"in d){let{for:_}=d;if(_.length<2)continue;let y=_.map(x=>a(`${x}_y`)),g=new Cn(...y.slice(1));r.addConstraint(new ci(g,Vn.Eq,y[0],wn.required))}else if("sameX"in d){let{for:_}=d;if(_.length<2)continue;let y=_.map(x=>a(`${x}_x`)),g=new Cn(...y.slice(1));r.addConstraint(new ci(g,Vn.Eq,y[0],wn.required))}}r.updateVariables(),B5t.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(s).map(([h,d])=>({var:h,val:d.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:h,bounds:{width:d,height:_}}of i){let y=a(`${h}_x`),g=a(`${h}_y`),x=y.value()-d/2,w=y.value()+d/2,S=g.value()+_/2,T=g.value()-_/2;c.left=Math.min(c.left,x),c.right=Math.max(c.right,w),c.top=Math.max(c.top,S),c.bottom=Math.min(c.bottom,T)}let l={x:-(c.right+c.left)/2,y:-(c.top+c.bottom)/2},u=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();l.x+=u.x,l.y+=u.y;for(let{component:h,selector:d}of i){let _=a(`${d}_x`),y=a(`${d}_y`);h._setPositionFromLayout({x:_.value()+l.x,y:y.value()+l.y})}}},LH=e=>{if(!e)return null;let n=e.split("?")[0].split("#")[0],i=n.split("/").pop()??n;return i.includes(".")?i.split(".").pop()?.toLowerCase()??null:null},Y5t=(e,t)=>{let n=e.replace(/\/+$/,""),i=t.replace(/^\/+/,"");return`${n}/${i}`},FH=(e,t)=>{if(!t||!e.startsWith("/"))return e;try{let n=new URL(t);return n.pathname!=="/"&&e.startsWith(n.pathname)?new URL(e,n.origin).toString():Y5t(t,e)}catch{return e}},v4=p.union([p.number(),p.string()]),nH=p.object({x:v4,y:v4,z:v4}),zH=class extends xe{get config(){return{componentName:"CadModel",zodProps:oD}}doInitialCadModelRender(){let e=this._findParentWithPcbComponent();if(!e||!e.pcb_component_id)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=e._getPcbCircuitJsonBounds(),o=t.pcb_component.get(e.pcb_component_id),r=this._parsedProps;if(!r||typeof r.modelUrl!="string"&&typeof r.stepUrl!="string")return;let s=e._computePcbGlobalTransformBeforeLayout(),c=Ar(s).rotation.angle*180/Math.PI,l=nH.parse({x:0,y:0,z:0});if(typeof r.rotationOffset=="number")l.z=Number(r.rotationOffset);else if(typeof r.rotationOffset=="object"){let x=nH.parse(r.rotationOffset);l.x=Number(x.x),l.y=Number(x.y),l.z=Number(x.z)}let u=Zg.parse({x:r.pcbX??0,y:r.pcbY??0,z:r.pcbZ??0,...typeof r.positionOffset=="object"?r.positionOffset:{}}),h=r.zOffsetFromSurface!==void 0?Y.parse(r.zOffsetFromSurface):0,d=e.props.layer==="bottom"?"bottom":"top",_=r.modelUrl?LH(r.modelUrl):void 0,y={};if(_==="stl"?y.model_stl_url=this._addCachebustToModelUrl(r.modelUrl):_==="obj"?y.model_obj_url=this._addCachebustToModelUrl(r.modelUrl):_==="gltf"?y.model_gltf_url=this._addCachebustToModelUrl(r.modelUrl):_==="glb"?y.model_glb_url=this._addCachebustToModelUrl(r.modelUrl):_==="step"||_==="stp"?y.model_step_url=this._addCachebustToModelUrl(r.modelUrl):_==="wrl"||_==="vrml"?y.model_wrl_url=this._addCachebustToModelUrl(r.modelUrl):y.model_stl_url=this._addCachebustToModelUrl(r.modelUrl),r.stepUrl){let x=this._addCachebustToModelUrl(r.stepUrl);x&&(y.model_step_url=x)}let g=t.cad_component.insert({position:{x:i.center.x+Number(u.x),y:i.center.y+Number(u.y),z:(d==="bottom"?-n/2:n/2)+(d==="bottom"?-h:h)+Number(u.z)},rotation:{x:Number(l.x),y:(d==="top"?0:180)+Number(l.y),z:d==="bottom"?-(c+Number(l.z))+180:c+Number(l.z)},pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,model_unit_to_mm_scale_factor:typeof r.modelUnitToMmScale=="number"?r.modelUnitToMmScale:void 0,...y});this.cad_component_id=g.cad_component_id}_findParentWithPcbComponent(){let e=this.parent;for(;e&&!e.pcb_component_id;)e=e.parent;return e}_addCachebustToModelUrl(e){if(!e)return e;let t=this.root?.platform?.projectBaseUrl,n=FH(e,t);if(!n.includes("modelcdn.tscircuit.com"))return n;let i=this.root?.getClientOrigin()??"";return`${n}${n.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(i)}`}},DH=class extends xe{constructor(){super(...arguments);P(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:iD}}},X5t=(e,t)=>{if(!e)return;let n={};for(let[i,o]of Object.entries(e)){let r=Om(i,t),s={leftMargin:o.marginLeft??o.leftMargin,rightMargin:o.marginRight??o.rightMargin,topMargin:o.marginTop??o.topMargin,bottomMargin:o.marginBottom??o.bottomMargin};n[`pin${r}`]={...n[`pin${r}`],...s}}return n},iH=class{constructor({input:e}){P(this,"input");this.input=e}solveAndMapToTraces(){let e=[];for(let t of this.input.connections){if(t.pointsToConnect.length!==2)continue;let[n,i]=t.pointsToConnect,o={type:"pcb_trace",pcb_trace_id:"",connection_name:t.name,route:[{route_type:"wire",x:n.x,y:n.y,layer:"top",width:.1},{route_type:"wire",x:i.x,y:i.y,layer:"top",width:.1}]};e.push(o)}return e}},V5t=e=>{let t=Math.min(...e.map(r=>r.center.x)),n=Math.max(...e.map(r=>r.center.x)),i=Math.min(...e.map(r=>r.center.y)),o=Math.max(...e.map(r=>r.center.y));return{minX:t,maxX:n,minY:i,maxY:o}},oH=["top","bottom","inner1","inner2"],kx=(e,t=[])=>{let n=[];if(t.length===0){let a=e[0].layers;for(let c of a)n.push(...kx(e.slice(1),[c]));return n}if(e.length===0)return[];let i=e[0],o=i.via||i.optional_via,r=t[t.length-1];if(e.length===1){let a=i;return a.layers&&o?a.layers.map(c=>({layer_path:[...t,c]})):a.layers?.includes(r)?[{layer_path:[...t,r]}]:[]}if(!o)return i.layers&&!i.layers.includes(r)?[]:kx(e.slice(1),t.concat([r]));let s=(i.optional_via?oH:oH.filter(a=>a!==r)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of s)n.push(...kx(e.slice(1),t.concat(a)));return n};function rH(e){let t={x:e.to.x-e.from.x,y:e.to.y-e.from.y},n=Math.abs(t.x),i=Math.abs(t.y);return n>i?t.x>0?"right":"left":t.y>0?"down":"up"}function zh(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}var H5t=e=>{if(e.length===1)return e[0];if(e.some(c=>c.length===0))throw new Error("Cannot merge routes with zero length");let t=[],n=e[0][0],i=e[0][e[0].length-1],o=e[1][0],r=e[1][e[1].length-1],s=Math.min(zh(n,o),zh(n,r)),a=Math.min(zh(i,o),zh(i,r));s<a?t.push(...e[0].reverse()):t.push(...e[0]);for(let c=1;c<e.length;c++){let l=t[t.length-1],u=e[c],h=u[0],d=u[u.length-1],_=zh(l,h),y=zh(l,d);_<y?t.push(...u):t.push(...u.reverse())}for(let c=1;c<t.length-1;c++){let l=t[c-1],u=t[c];l.route_type==="wire"&&u.route_type==="wire"&&l.layer!==u.layer&&t.splice(c,0,{x:l.x,y:l.y,from_layer:l.layer,to_layer:u.layer,route_type:"via"})}return t},G5t=(e,t)=>{let n="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e,i="_getGlobalPcbPositionBeforeLayout"in t?t._getGlobalPcbPositionBeforeLayout():t;return Math.sqrt((n.x-i.x)**2+(n.y-i.y)**2)};function U5t(e,t){if(t.length===0)throw new Error("No candidates given to getClosest method");let n=t[0],i=1/0;for(let o of t){let r=G5t(e,o);r<i&&(n=o,i=r)}return n}var q5t=(e,t)=>{let n=0;n+=e.length??0,n+=t.filter(i=>i.is_crossing).length;for(let i=1;i<t.length;i++){let o=t[i-1],r=t[i],s=Math.abs(o.from.x-o.to.x)<.01,a=Math.abs(r.from.x-r.to.x)<.01;s!==a&&n++}return n},Lm=e=>({up:"bottom",down:"top",left:"right",right:"left"})[e]??null,M4=({firstEdge:e,firstEdgePort:t,firstDominantDirection:n,lastEdge:i,lastEdgePort:o,lastDominantDirection:r})=>{if(e&&t)return M4({lastEdge:{from:e.to,to:e.from},lastEdgePort:t,lastDominantDirection:n}).reverse().map(a=>({from:a.to,to:a.from}));let s=[];if(i&&o){let a={x:i.to.x,y:i.to.y};r==="left"||r==="right"?(a.x=o.position.x,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...o.position}})):(a.y=o.position.y,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...o.position}}))}return s=s.filter(a=>vi(a.from,a.to)>.01),s};function W5t(e){try{return[e(),null]}catch(t){return[null,t]}}var Z5t=(e,{db:t})=>{let n=e.map(i=>{let o=t.source_port.get(i.source_port_id);if(!o?.source_component_id)return null;let r=t.source_component.get(o.source_component_id);return r?.ftype==="simple_capacitor"?r.max_decoupling_trace_length:null}).filter(i=>i!==null);if(n.length!==0)return Math.min(...n)};function K5t({ports:e,nets:t}){if(e.length>=2)return`${e[0]?.selector} to ${e[1]?.selector}`;if(e.length===1&&t.length===1)return`${e[0]?.selector} to net.${t[0]._parsedProps.name}`}var J5t=(e,{db:t})=>{let n=t.pcb_board.list()[0];if(n.outline){let c=n.outline,l=(u,h)=>{let d=!1;for(let _=0,y=h.length-1;_<h.length;y=_++){let g=h[_].x,x=h[_].y,w=h[y].x,S=h[y].y;x>u.y!=S>u.y&&u.x<(w-g)*(u.y-x)/(S-x)+g&&(d=!d)}return d};return e.some(u=>!l(u,c))}let i=n.width,o=n.height,r=n.center.x,s=n.center.y;return e.some(c=>c.x<r-i/2||c.y<s-o/2||c.x>r+i/2||c.y>s+o/2)},sH=(e,t)=>Math.abs(e-t)<1e-4,Q5t=(e,t,{viaDiameter:n=.5}={})=>{let i=[];for(let o=0;o<e.length-1;o++){let[r,s]=[e[o],e[o+1]],a=o-1>=0?e[o-1]:null,c=sH(r.y,s.y),l=sH(r.x,s.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${t}, start: (${r.x}, ${r.y}), end: (${s.x}, ${s.y})`);let u={type:"rect",layers:[r.layer],center:{x:(r.x+s.x)/2,y:(r.y+s.y)/2},width:c?Math.abs(r.x-s.x):.1,height:l?Math.abs(r.y-s.y):.1,connectedTo:[t]};if(i.push(u),a&&a.layer===r.layer&&r.layer!==s.layer){let h={type:"rect",layers:[r.layer,s.layer],center:{x:r.x,y:r.y},connectedTo:[t],width:n,height:n};i.push(h)}}return i};function tIt(e,t=4){let{center:n,width:i,height:o,rotation:r}=e,s=[],a=r*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(r%360+360)%360;if(o<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*c,x=-y*l,w=d*1.1,S=Math.abs(o*c)+Math.abs(d*l);s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}else{let d=o/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*l,x=y*c,w=Math.abs(i*c)+Math.abs(d*l),S=d*1.1;s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}return s}function eIt(e,t={}){if(e.length<3)return[];let{rectHeight:n=.1}=t,i=[],o=e.map(a=>a.y),r=Math.min(...o),s=Math.max(...o);for(let a=r;a<s;a+=n){let c=a+n/2,l=[];for(let u=0;u<e.length;u++){let h=e[u],d=e[(u+1)%e.length];if(h.y<=c&&d.y>c||d.y<=c&&h.y>c){let _=(c-h.y)*(d.x-h.x)/(d.y-h.y)+h.x;l.push(_)}}l.sort((u,h)=>u-h);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let h=l[u],_=l[u+1]-h;_>1e-6&&i.push({center:{x:h+_/2,y:c},width:_,height:n})}}return i}function nIt(e,t={}){let{center:n,radius:i}=e,{rectHeight:o=.1}=t,r=[],s=Math.ceil(i*2/o);for(let a=0;a<s;a++){let c=n.y-i+(a+.5)*o,l=c-n.y,u=Math.sqrt(i*i-l*l);u>0&&r.push({center:{x:n.x,y:c},width:u*2,height:o})}return r}var ra=["top","inner1","inner2","bottom"],$H=(e,t)=>{let n=o=>t?o.concat(o.map(r=>t?.getNetConnectedToId(r)).filter(Boolean)):o,i=[];for(let o of e)if(o.type==="pcb_smtpad"){if(o.shape==="circle")i.push({type:"oval",layers:[o.layer],center:{x:o.x,y:o.y},width:o.radius*2,height:o.radius*2,connectedTo:n([o.pcb_smtpad_id])});else if(o.shape==="rect")i.push({type:"rect",layers:[o.layer],center:{x:o.x,y:o.y},width:o.width,height:o.height,connectedTo:n([o.pcb_smtpad_id])});else if(o.shape==="rotated_rect"){let r={center:{x:o.x,y:o.y},width:o.width,height:o.height,rotation:o.ccw_rotation},s=tIt(r);for(let a of s)i.push({type:"rect",layers:[o.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([o.pcb_smtpad_id])})}}else if(o.type==="pcb_keepout")o.shape==="circle"?i.push({type:"oval",layers:o.layers,center:{x:o.center.x,y:o.center.y},width:o.radius*2,height:o.radius*2,connectedTo:[]}):o.shape==="rect"&&i.push({type:"rect",layers:o.layers,center:{x:o.center.x,y:o.center.y},width:o.width,height:o.height,connectedTo:[]});else if(o.type==="pcb_cutout"){if(o.shape==="rect")i.push({type:"rect",layers:ra,center:{x:o.center.x,y:o.center.y},width:o.width,height:o.height,connectedTo:[]});else if(o.shape==="circle"){let r=nIt({center:o.center,radius:o.radius},{rectHeight:.6});for(let s of r)i.push({type:"rect",layers:ra,center:s.center,width:s.width,height:s.height,connectedTo:[]})}else if(o.shape==="polygon"){let r=eIt(o.points,{rectHeight:.6});for(let s of r)i.push({type:"rect",layers:ra,center:s.center,width:s.width,height:s.height,connectedTo:[]})}}else if(o.type==="pcb_hole")o.hole_shape==="oval"?i.push({type:"oval",center:{x:o.x,y:o.y},width:o.hole_width,height:o.hole_height,connectedTo:[]}):o.hole_shape==="rect"?i.push({type:"rect",layers:ra,center:{x:o.x,y:o.y},width:o.hole_width,height:o.hole_height,connectedTo:[]}):o.hole_shape==="square"?i.push({type:"rect",layers:ra,center:{x:o.x,y:o.y},width:o.hole_diameter,height:o.hole_diameter,connectedTo:[]}):(o.hole_shape==="round"||o.hole_shape==="circle")&&i.push({type:"rect",layers:ra,center:{x:o.x,y:o.y},width:o.hole_diameter,height:o.hole_diameter,connectedTo:[]});else if(o.type==="pcb_plated_hole")o.shape==="circle"?i.push({type:"oval",layers:ra,center:{x:o.x,y:o.y},width:o.outer_diameter,height:o.outer_diameter,connectedTo:n([o.pcb_plated_hole_id])}):o.shape==="circular_hole_with_rect_pad"?i.push({type:"rect",layers:ra,center:{x:o.x,y:o.y},width:o.rect_pad_width,height:o.rect_pad_height,connectedTo:n([o.pcb_plated_hole_id])}):(o.shape==="oval"||o.shape==="pill")&&i.push({type:"oval",layers:ra,center:{x:o.x,y:o.y},width:o.outer_width,height:o.outer_height,connectedTo:n([o.pcb_plated_hole_id])});else if(o.type==="pcb_trace"){let r=Q5t(o.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),o.source_trace_id);i.push(...r)}else if(o.type==="pcb_via"){let r=!!(o.net_is_assignable??o.netIsAssignable);i.push({type:"rect",layers:o.layers,center:{x:o.x,y:o.y},connectedTo:[],width:o.outer_diameter,height:o.outer_diameter,netIsAssignable:r||void 0})}return i},Ic=({anchor_position:e,anchor_side:t,text:n,font_size:i=.18})=>{let o=.1*(i/.18),r=n.length*o,s=i,a={...e};switch(t){case"right":a.x-=r/2;break;case"left":a.x+=r/2;break;case"top":a.y-=s/2;break;case"bottom":a.y+=s/2;break}return a},j4=({db:e,source_trace_id:t,sameNetOnly:n,differentNetOnly:i})=>{!n&&!i&&(i=!0);let o=e.source_trace.get(t),r=[];for(let s of e.schematic_trace.list()){if(s.source_trace_id===t)continue;let c=e.source_trace.get(s.source_trace_id)?.subcircuit_connectivity_map_key===o.subcircuit_connectivity_map_key;i&&c||n&&!c||r.push(s)}return r},iIt=({edges:e,otherEdges:t})=>{let n=[...e];for(let i=0;i<n.length;i++){if(i>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let o=n[i],r=Math.abs(o.from.x-o.to.x)<.01?"vertical":o.from.y===o.to.y?"horizontal":"not-orthogonal";if(r==="not-orthogonal")continue;let s=[];for(let g of t){let x=g.from.x===g.to.x?"vertical":g.from.y===g.to.y?"horizontal":"not-orthogonal";if(x==="not-orthogonal"||r===x)continue;if(qs([o.from,o.to],[g.from,g.to],{lineThickness:.01})){let S=r==="vertical"?o.from.x:g.from.x,T=r==="vertical"?g.from.y:o.from.y,I={x:S,y:T};s.push({otherEdge:g,crossingPoint:I,distanceFromEdgeFrom:vi(o.from,I)})}}if(s.length===0)continue;let a=s[0];for(let g of s)g.distanceFromEdgeFrom<a.distanceFromEdgeFrom&&(a=g);let c=a.crossingPoint,l=.075;if(c.x===o.from.x&&c.y===o.from.y)continue;let u=sb(o.from,c),h={x:c.x-u.x*l/2,y:c.y-u.y*l/2},d={x:c.x+u.x*l/2,y:c.y+u.y*l/2},_=vi(d,o.to)<l,y=[{from:o.from,to:h},{from:h,to:d,is_crossing:!0},{from:d,to:o.to}];n.splice(i,1,...y),i+=y.length-2,_&&i++}return n},C4=.001,Dh=(e,t)=>{let n=Math.min(t.from.x,t.to.x),i=Math.max(t.from.x,t.to.x),o=Math.min(t.from.y,t.to.y),r=Math.max(t.from.y,t.to.y);return e.x>=n&&e.x<=i&&e.y>=o&&e.y<=r},aH=e=>{let t=Math.abs(e.from.x-e.to.x)<C4,n=Math.abs(e.from.y-e.to.y)<C4;return t?"vertical":n?"horizontal":"diagonal"},oIt=(e,t)=>{let n=aH(e),i=aH(t);if(n===i)return null;if(n==="vertical"&&i==="horizontal"||n==="horizontal"&&i==="vertical"){let h=n==="vertical"?e:t,d=n==="horizontal"?e:t,_=h.from.x,y=d.from.y,g={x:_,y};return Dh(g,e)&&Dh(g,t)?g:null}if(n==="vertical"||i==="vertical"){let h=n==="vertical"?e:t,d=n==="vertical"?t:e,_=h.from.x,y=(d.to.y-d.from.y)/(d.to.x-d.from.x),g=d.from.y-y*d.from.x,x=y*_+g,w={x:_,y:x};return Dh(w,e)&&Dh(w,t)?w:null}let o=(e.to.y-e.from.y)/(e.to.x-e.from.x),r=e.from.y-o*e.from.x,s=(t.to.y-t.from.y)/(t.to.x-t.from.x),a=t.from.y-s*t.from.x;if(Math.abs(o-s)<C4)return null;let c=(a-r)/(o-s),l=o*c+r,u={x:c,y:l};return Dh(u,e)&&Dh(u,t)?u:null},rIt=({edges:e,db:t,source_trace_id:n})=>{let i=j4({db:t,source_trace_id:n,sameNetOnly:!0}).flatMap(r=>r.edges),o=new Map;for(let r of e)for(let s of i){let a=oIt(r,s);if(a){let c=`${a.x.toFixed(6)},${a.y.toFixed(6)}`;o.has(c)||o.set(c,a)}}return Array.from(o.values())};function sIt(e,t={}){let{minX:n,maxX:i,minY:o,maxY:r}=e,s=t.padding??1;if(!isFinite(n)||!isFinite(i)||!isFinite(o)||!isFinite(r))return[];let a=n-s,c=i+s,l=r+s,u=o-s,h=.01;return[{type:"rect",layers:["top"],center:{x:(a+c)/2,y:l},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+c)/2,y:u},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(l+u)/2},width:h,height:l-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:c,y:(l+u)/2},width:h,height:l-u,connectedTo:[]}]}var aIt=e=>{let t=e.root.db,n=e._findConnectedPorts().ports??[],i=new Set(n.map(s=>s.schematic_port_id)),o=[];for(let s of t.toArray()){if(s.type==="schematic_component"){let a=!!s.symbol_name,c=s.size.width>s.size.height?"horz":"vert";o.push({type:"rect",layers:["top"],center:s.center,width:s.size.width+(a&&c==="horz"?-.5:0),height:s.size.height+(a&&c==="vert"?-.5:0),connectedTo:[]})}if(s.type==="schematic_port"){if(i.has(s.schematic_port_id))continue;let a=s.facing_direction?ab(s.facing_direction):{x:0,y:0};o.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"&&o.push({type:"rect",layers:["top"],center:s.position,width:(s.text?.length??0)*.1,height:.2,connectedTo:[]}),s.type==="schematic_box"&&o.push({type:"rect",layers:["top"],center:{x:s.x,y:s.y},width:s.width,height:s.height,connectedTo:[]})}let r=NH(t.toArray());return o.push(...sIt(r,{padding:1})),o},cIt=({edges:e,db:t,source_trace_id:n})=>{let i=t.source_trace.get(n),o=j4({db:t,source_trace_id:n,differentNetOnly:!0}).flatMap(s=>s.edges),r=s=>{let{from:a,to:c}=s;return a.x===c.x?"vertical":"horizontal"};for(let s of e){let a=r(s),c=()=>o.find(u=>r(u)===a&&qs([s.from,s.to],[u.from,u.to],{lineThickness:.05})),l=c();for(;l;)a==="horizontal"?(s.from.y+=.1,s.to.y+=.1):(s.from.x+=.1,s.to.x+=.1),l=c()}},E4=e=>{switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},lIt=VD.version??"unknown",Em=class extends Error{constructor(e){super(`${e} (capacity-autorouter@${lIt})`),this.name="AutorouterError"}},Ox=class extends Error{constructor(e){super(e.message),this.errorData=e,this.name="TraceConnectionError"}},uIt=e=>{if(e.root?._featureMspSchematicTraceRouting||e._couldNotFindPort||e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let o,r;try{let X=e._findConnectedPorts();o=X.allPortsFound,r=X.portsWithSelectors??[]}catch(X){if(X instanceof Ox){t.source_trace_not_connected_error.insert({...X.errorData,error_type:"source_trace_not_connected_error"});return}throw X}let{netsWithSelectors:s}=e._findConnectedNets();if(!o)return;let c=r.map(X=>X.port.schematic_port_id).sort().join(","),l=e.root?._getBoard();if(l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.has(c))return;let u={name:e.source_trace_id,pointsToConnect:[]},h=aIt(e),d=r.filter(({port:X})=>X.schematic_port_id!==null).map(({port:X})=>({port:X,position:X._getGlobalSchematicPositionAfterLayout(),schematic_port_id:X.schematic_port_id??void 0,facingDirection:X.facingDirection}));if(d.length===1&&s.length===1){let X=s[0].net,{port:G,position:tt}=d[0],Q=e.getSubcircuit().selectAll("netlabel").find(et=>{let J=et._parsedProps.connection??et._parsedProps.connectsTo;return J?Array.isArray(J)?J.some(ht=>e.getSubcircuit().selectOne(ht,{port:!0})===G):e.getSubcircuit().selectOne(J,{port:!0})===G:!1});if(!Q){let et=t.schematic_net_label.getWhere({source_trace_id:e.source_trace_id});et&&(Q=et)}if(Q){let et="_getGlobalSchematicPositionBeforeLayout"in Q?Q._getGlobalSchematicPositionBeforeLayout():Q.anchor_position,J=[];tt.x===et.x||tt.y===et.y?J.push({from:tt,to:et}):(J.push({from:tt,to:{x:et.x,y:tt.y}}),J.push({from:{x:et.x,y:tt.y},to:et}));let pt=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:J,junctions:[],subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=pt.schematic_trace_id;return}if(e.props.schDisplayLabel){let et=Lm(G.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel,source_net_id:X.source_net_id,anchor_position:tt,center:Ic({anchor_position:tt,anchor_side:et,text:e.props.schDisplayLabel}),anchor_side:et});return}let V=Lm(G.facingDirection)??"bottom",rt=t.schematic_net_label.insert({text:X._parsedProps.name,source_net_id:X.source_net_id,anchor_position:tt,center:Ic({anchor_position:tt,anchor_side:V,text:X._parsedProps.name}),anchor_side:V});return}if(e.props.schDisplayLabel&&("from"in e.props&&"to"in e.props||"path"in e.props)){e._doInitialSchematicTraceRenderWithDisplayLabel();return}if(d.length<2)return;let g=(()=>{let X=[];for(let tt=0;tt<d.length-1;tt++){let Q=d[tt],V=d[tt+1],rt=oc({x:Q.position.x,y:Q.position.y,facingDirection:E4(Q.facingDirection)},{x:V.position.x,y:V.position.y,facingDirection:E4(V.facingDirection)});for(let et=0;et<rt.length-1;et++)X.push({from:rt[et],to:rt[et+1]})}let G=(tt,Q)=>{let V=Q.width/2,rt=Q.height/2,et=Q.center.x-V,J=Q.center.x+V,pt=Q.center.y-rt,ht=Q.center.y+rt,St=lt=>lt.x>=et&&lt.x<=J&&lt.y>=pt&&lt.y<=ht;return St(tt.from)||St(tt.to)?!0:[[{x:et,y:pt},{x:J,y:pt}],[{x:J,y:pt},{x:J,y:ht}],[{x:J,y:ht},{x:et,y:ht}],[{x:et,y:ht},{x:et,y:pt}]].some(lt=>qs([tt.from,tt.to],lt,{lineThickness:0}))};for(let tt of X)for(let Q of h)if(G(tt,Q))return null;return X})();g&&g.length===0&&(g=null),u.pointsToConnect=d.map(({position:X})=>({...X,layer:"top"}));let x=V5t(h),w=2,S={minTraceWidth:.1,obstacles:h,connections:[u],bounds:{minX:x.minX-w,maxX:x.maxX+w,minY:x.minY-w,maxY:x.maxY+w},layerCount:1},T=Ug,I=!1;if(e.getSubcircuit().props._schDirectLineRoutingEnabled&&(T=iH,I=!0),!g){let G=new T({input:S,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(G.length===0){if(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection()){e._doInitialSchematicTraceRenderWithDisplayLabel();return}G=new iH({input:S}).solveAndMapToTraces(),I=!0}let[{route:tt}]=G;g=[];for(let Q=0;Q<tt.length-1;Q++)g.push({from:tt[Q],to:tt[Q+1]})}let E=e.source_trace_id,M=[];if(!I){cIt({edges:g,db:t,source_trace_id:E});let X=j4({db:t,source_trace_id:E,differentNetOnly:!0}).flatMap(G=>G.edges);g=iIt({edges:g,otherEdges:X}),M=rIt({edges:g,db:t,source_trace_id:e.source_trace_id})}if(!g||g.length===0)return;let k=g[g.length-1],N=d[d.length-1],A=rH(k);g.push(...M4({lastEdge:k,lastEdgePort:N,lastDominantDirection:A}));let R=g[0],$=d[0],j=rH(R);if(g.unshift(...M4({firstEdge:R,firstEdgePort:$,firstDominantDirection:j})),!e.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(e.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&q5t(M,g)>=5&&(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection())){e._doInitialSchematicTraceRenderWithDisplayLabel();return}let H=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:g,junctions:M,subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=H.schematic_trace_id;for(let{port:X}of r)X.schematic_port_id&&t.schematic_port.update(X.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function jH(e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];if(i.route_type==="wire"){let o=e[n+1];if(o){let r=o.x-i.x,s=o.y-i.y;t+=Math.sqrt(r*r+s*s)}}else i.route_type==="via"&&(t+=1.6)}return t}var Cx=e=>({...e._getGlobalPcbPositionAfterLayout(),layers:e.getAvailablePcbLayers()}),pIt=!1;function hIt(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e,o=e.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(o._parsedProps.routingDisabled)return;let r=o._parsedProps.pcbRouteCache?.pcbTraces;if(r){let A=t.pcb_trace.insert({route:r.flatMap(R=>R.route),source_trace_id:e.source_trace_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});e.pcb_trace_id=A.pcb_trace_id;return}if(n.pcbPath&&n.pcbPath.length>0||!o._shouldUseTraceByTraceRouting())return;let{allPortsFound:s,ports:a}=e._findConnectedPorts(),c=[];if(!s)return;let l=[];for(let A of a)A._hasMatchedPcbPrimitive()||l.push(A);if(l.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${l.map(A=>A.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(A=>A.pcb_port_id).filter(Boolean)});return}let u=e._findConnectedNets().netsWithSelectors;if(a.length===0&&u.length===2){e.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(a.length===1&&u.length===1){let A=a[0],$=u[0].net.getAllConnectedPorts().filter(H=>H!==A);if($.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let j=U5t(A,$);c.push(j),a.push(j)}else if(a.length>1&&u.length>=1){e.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let h=a.flatMap(A=>A.matchedComponents.filter(R=>R.componentName==="TraceHint")),d=(e._parsedProps.pcbRouteHints??[]).concat(h.flatMap(A=>A.getPcbRouteHints()));if(a.length>2){e.renderError(`Trace has more than two ports (${a.map(A=>A.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(e.getSubcircuit().selectAll("trace").filter(A=>A.renderPhaseStates.PcbTraceRender.initialized).some(A=>A._portsRoutedOnPcb.length===a.length&&A._portsRoutedOnPcb.every(R=>a.includes(R))))return;let g=[];d.length===0?g=[Cx(a[0]),Cx(a[1])]:g=[Cx(a[0]),...d,Cx(a[1])];let x=kx(g);if(pIt&&x.length===0){e.renderError(`Could not find a common layer (using hints) for trace ${e.getString()}`);return}let w=$i(e.root.db.toArray()),[S,T]=W5t(()=>$H(e.root.db.toArray()));if(T){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Error getting obstacles for autorouting: ${T.message}`,source_trace_id:e.source_trace_id,center:{x:0,y:0},pcb_port_ids:a.map(A=>A.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[]});return}for(let A of S)if(A.connectedTo.length>0){let $=w.getNetConnectedToId(A.connectedTo[0]);$&&A.connectedTo.push($)}let I=[];if(x.length===0)I=g;else{let A=x[0].layer_path;I=g.map((R,$)=>R.via?{...R,via_to_layer:A[$]}:{...R,layers:[A[$]]})}I[0].pcb_port_id=a[0].pcb_port_id,I[I.length-1].pcb_port_id=a[1].pcb_port_id;let E=[];for(let[A,R]of EH(I)){let $="via_to_layer"in A?A.via_to_layer:null,j=2,H="layers"in A&&A.layers.length===1?A.layers[0]:$??"top",X="layers"in R&&R.layers.length===1?R.layers[0]:$??"top",G="pcb_port_id"in A?A.pcb_port_id:null,tt="pcb_port_id"in R?R.pcb_port_id:null,Q=e._getExplicitTraceThickness()??e.getSubcircuit()._parsedProps.minTraceWidth??.16,V=new Ug({OBSTACLE_MARGIN:Q*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(G&&tt),connMap:w,input:{obstacles:S,minTraceWidth:Q,connections:[{name:e.source_trace_id,pointsToConnect:[{...A,layer:H,pcb_port_id:G},{...R,layer:X,pcb_port_id:tt}]}],layerCount:e.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(A.x,R.x)-j,maxX:Math.max(A.x,R.x)+j,minY:Math.min(A.y,R.y)-j,maxY:Math.max(A.y,R.y)+j}}}),rt=null;try{rt=V.solveAndMapToTraces()}catch(pt){e.renderError({type:"pcb_trace_error",pcb_trace_error_id:e.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${pt.message}`,source_trace_id:e.pcb_trace_id,center:{x:(A.x+R.x)/2,y:(A.y+R.y)/2},pcb_port_ids:a.map(ht=>ht.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(ht=>ht.pcb_component_id)})}if(!rt)return;if(rt.length===0){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Could not find a route for ${e}`,source_trace_id:e.source_trace_id,center:{x:(A.x+R.x)/2,y:(A.y+R.y)/2},pcb_port_ids:a.map(pt=>pt.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(pt=>pt.pcb_component_id)});return}let[et]=rt;$&&(et.route=et.route.map(pt=>(pt.route_type==="wire"&&!pt.layer&&(pt.layer=$),pt))),G&&et.route[0].route_type==="wire"&&(et.route[0].start_pcb_port_id=G);let J=et.route[et.route.length-1];tt&&J.route_type==="wire"&&(J.end_pcb_port_id=tt),E.push(et.route)}let M=H5t(E),k=jH(M),N=t.pcb_trace.insert({route:M,source_trace_id:e.source_trace_id,subcircuit_id:e.getSubcircuit()?.subcircuit_id,trace_length:k});e._portsRoutedOnPcb=a,e.pcb_trace_id=N.pcb_trace_id;for(let A of M)A.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:N.pcb_trace_id,x:A.x,y:A.y,hole_diameter:.3,outer_diameter:.6,layers:[A.from_layer,A.to_layer],from_layer:A.from_layer,to_layer:A.to_layer});e._insertErrorIfTraceIsOutsideBoard(M,a)}function dIt(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n}=e,i=e.getSubcircuit();if(!n.pcbPath)return;let{allPortsFound:o,ports:r,portsWithSelectors:s}=e._findConnectedPorts();if(!o)return;let a=[];for(let S of r)S._hasMatchedPcbPrimitive()||a.push(S);if(a.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${a.map(S=>S.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:a.map(S=>S.pcb_port_id).filter(Boolean)});return}let c;n.pcbPathRelativeTo&&(c=s.find(S=>S.selector===n.pcbPathRelativeTo)?.port,c||(c=e.getSubcircuit().selectOne(n.pcbPathRelativeTo))),c||(c=r[0]);let l=r.find(S=>S!==c)??r[1],u=c.getAvailablePcbLayers()[0]||"top",h=e._getExplicitTraceThickness()??e.getSubcircuit()._parsedProps.minTraceWidth??.16,d=c._getGlobalPcbPositionAfterLayout(),_=l._getGlobalPcbPositionAfterLayout(),y=[];y.push({route_type:"wire",x:d.x,y:d.y,width:h,layer:u,start_pcb_port_id:c.pcb_port_id});let g=c?._computePcbGlobalTransformBeforeLayout?.()||zi();for(let S of n.pcbPath){let T,I=!1;if(typeof S=="string"){let M=e.getSubcircuit().selectOne(S,{type:"port"});if(!M){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Could not resolve pcbPath selector "${S}" for ${e}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:[]});continue}let k=M._getGlobalPcbPositionAfterLayout();T={x:k.x,y:k.y},I=!0}else T={x:S.x,y:S.y},I=!1;let E=I?T:Ne(g,T);y.push({route_type:"wire",x:E.x,y:E.y,width:h,layer:u})}y.push({route_type:"wire",x:_.x,y:_.y,width:h,layer:u,end_pcb_port_id:l.pcb_port_id});let x=jH(y),w=t.pcb_trace.insert({route:y,source_trace_id:e.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,trace_length:x});e._portsRoutedOnPcb=r,e.pcb_trace_id=w.pcb_trace_id,e._insertErrorIfTraceIsOutsideBoard(y,r)}function fIt(e){if(e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let{allPortsFound:o,portsWithSelectors:r}=e._findConnectedPorts();if(!o)return;let s=r.map(({port:I})=>({port:I,position:I._getGlobalSchematicPositionAfterLayout(),schematic_port_id:I.schematic_port_id,facingDirection:I.facingDirection}));if(s.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let a,c,l=s[0].position,u=s[0].port;if("path"in e.props){if(e.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[a,c]=e.props.path}else{if(!("from"in e.props&&"to"in e.props))throw new Error("Missing 'from' or 'to' properties in props.");a=e.props.from,c=e.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${a}).`);let h=s[1].position,d=s[1].port;if(!d.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);let _=t.schematic_net_label.list().find(I=>I.source_net_id===u.source_port_id),y=t.schematic_net_label.list().find(I=>I.source_net_id===d.source_port_id),[g,x]=r.map(({port:I})=>I),S=g.parent?.config.shouldRenderAsSchematicBox?`${g?.parent?.props.name}_${g?.props.name}`:`${x?.parent?.props.name}_${x?.props.name}`,T=e.props.schDisplayLabel??S;if(_&&_.text!==T&&(_.text=`${T} / ${_.text}`),y&&y?.text!==T&&(y.text=`${T} / ${y.text}`),!y){let I=Lm(d.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:d.source_port_id,anchor_position:h,center:Ic({anchor_position:h,anchor_side:I,text:e.props.schDisplayLabel??S}),anchor_side:I})}if(!_){let I=Lm(u.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:u.source_port_id,anchor_position:l,center:Ic({anchor_position:l,anchor_side:I,text:e.props.schDisplayLabel??S}),anchor_side:I})}}function mIt(e){let{_parsedProps:t,parent:n}=e;if(!n)throw new Error("Trace has no parent");let o=e.getTracePortPathSelectors().map(r=>({selector:r,port:e.getSubcircuit().selectOne(r,{type:"port"})??null}));for(let{selector:r,port:s}of o)if(!s){let a,c,l=r.lastIndexOf(".");if(l!==-1&&l>r.lastIndexOf(" "))a=r.slice(0,l),c=r.slice(l+1);else{let I=r.match(/^(.*[ >])?([^ >]+)$/);a=I?.[1]?.trim()??"",c=I?.[2]??r}let u=a?e.getSubcircuit().selectOne(a):null;if(!u&&a&&!/[.#\[]/.test(a)&&(u=e.getSubcircuit().selectOne(`.${a}`)),!u){let I=a?`Could not find port for selector "${r}". Component "${a}" not found`:`Could not find port for selector "${r}"`,E=e.getSubcircuit(),M=E.getGroup();throw new Ox({error_type:"source_trace_not_connected_error",message:I,subcircuit_id:E.subcircuit_id??void 0,source_group_id:M?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[r]})}let h=u.children.filter(I=>I.componentName==="Port"),d=c.includes(".")?c.split(".").pop()??"":c,_=h.flatMap(I=>I.getNameAndAliases()),y=_.some(I=>!/^(pin\d+|\d+)$/.test(I)),g=Array.from(new Set(_)).join(", "),x;h.length===0?x="It has no ports":y?x=`It has [${g}]`:x=`It has ${h.length} pins and no pinLabels (consider adding pinLabels)`;let w=`Could not find port for selector "${r}". Component "${u.props.name??a}" found, but does not have pin "${d}". ${x}`,S=e.getSubcircuit(),T=S.getGroup();throw new Ox({error_type:"source_trace_not_connected_error",message:w,subcircuit_id:S.subcircuit_id??void 0,source_group_id:T?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[r]})}return o.some(r=>!r.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:o,ports:o.map(({port:r})=>r)}}var $r=class extends xe{constructor(t){super(t);P(this,"source_trace_id",null);P(this,"pcb_trace_id",null);P(this,"schematic_trace_id",null);P(this,"_portsRoutedOnPcb");P(this,"subcircuit_connectivity_map_key",null);P(this,"_traceConnectionHash",null);P(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}_getExplicitTraceThickness(){return this._parsedProps.thickness??this._parsedProps.width}get config(){return{zodProps:Az,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 mIt(this)}_resolveNet(t){let n=this.getSubcircuit().selectOne(t,{type:"net"});if(n)return n;let i=t.match(/^net\.(.+)$/),o=i?i[1]:null;if(!o)return null;let r=this.root?._getBoard();return r?r.getDescendants().find(a=>a.componentName==="Net"&&a._parsedProps.name===o)||null:(this.renderError(`Could not find a <board> ancestor for ${this}, so net "${t}" cannot be resolved`),null)}_findConnectedNets(){let t=this.getTracePathNetSelectors().map(i=>({selector:i,net:this._resolveNet(i)})),n=t.filter(i=>!i.net);return n.length>0&&this.renderError(`Could not find net for selector "${n[0].selector}" inside ${this}`),{netsWithSelectors:t,nets:t.map(i=>i.net)}}_getAllTracesConnectedToSameNet(){let t=this.getSubcircuit().selectAll("trace"),n=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return t.filter(o=>{if(o===this)return!1;let r=o._findConnectedNets().nets,s=o._findConnectedPorts().ports??[];return r.some(a=>n.includes(a))||s.some(a=>i.includes(a))})}_isExplicitlyConnectedToPort(t){let{allPortsFound:n,portsWithSelectors:i}=this._findConnectedPorts();return n?i.map(r=>r.port).includes(t):!1}_isExplicitlyConnectedToNet(t){return this._findConnectedNets().nets.includes(t)}doInitialCreateNetsFromProps(){zx(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();return!t||!n?null:[...n].sort((r,s)=>(r.pcb_port_id||"").localeCompare(s.pcb_port_id||"")).map(r=>r.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}let o,r;try{let h=this._findConnectedPorts();o=h.allPortsFound,r=h.portsWithSelectors??[]}catch(h){if(h instanceof Ox){t.source_trace_not_connected_error.insert({...h.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw h}if(!o)return;this._traceConnectionHash=this._computeTraceConnectionHash();let a=t.source_trace.list().find(h=>h.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&h.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(a){this.source_trace_id=a.source_trace_id;return}let c=this._findConnectedNets().nets,l=K5t({ports:r,nets:c}),u=t.source_trace.insert({connected_source_port_ids:r.map(h=>h.port.source_port_id),connected_source_net_ids:c.map(h=>h.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:Z5t(r.map(h=>h.port),{db:t})??n.maxLength,display_name:l,min_trace_thickness:this._getExplicitTraceThickness()});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(t,n){let{db:i}=this.root;J5t(t,{db:i})&&i.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:n.map(r=>r.pcb_port_id)})}doInitialPcbManualTraceRender(){dIt(this)}doInitialPcbTraceRender(){hIt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){fIt(this)}_isSymbolToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,o]=n;if(!i?.parent||!o?.parent)return!1;let r=i.parent.config.shouldRenderAsSchematicBox,s=o.parent.config.shouldRenderAsSchematicBox;return r&&!s||!r&&s}_isSymbolToSymbolConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,o]=n;if(!i?.parent||!o?.parent)return!1;let r=!i.parent.config.shouldRenderAsSchematicBox,s=!o.parent.config.shouldRenderAsSchematicBox;return r&&s}_isChipToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,o]=n;if(!i?.parent||!o?.parent)return!1;let r=i.parent.config.shouldRenderAsSchematicBox,s=o.parent.config.shouldRenderAsSchematicBox;return r&&s}doInitialSchematicTraceRender(){uIt(this)}},_It=e=>{let{db:t}=e.root;if(e.pcb_component_id){let n=t.pcb_component.get(e.pcb_component_id);return n?{width:n.width,height:n.height}:null}if(e.pcb_group_id){let n=t.pcb_group.get(e.pcb_group_id);if(!n)return null;if(n.outline&&n.outline.length>0){let i=ns(n.outline);return i?{width:i.maxX-i.minX,height:i.maxY-i.minY}:null}return{width:n.width??0,height:n.height??0}}return null},yIt=(e,t)=>{let{db:n}=e.root,i=n.toArray();if(e.pcb_component_id){cb(i,e.pcb_component_id,t);return}if(e.source_group_id){lb(i,e.source_group_id,t);return}throw new Error(`Cannot reposition component ${e.getString()}: no pcb_component_id or source_group_id`)},gIt=e=>{let{db:t}=e.root;if(!e.source_component_id)return;let n=e.selectAll("port"),i=t.source_trace.list(),o=new Set;for(let s of i)for(let a of s.connected_source_port_ids)o.add(a);let r=e._getInternallyConnectedPins();for(let s of r)if(s.some(a=>a.source_port_id&&o.has(a.source_port_id)))for(let a of s)a.source_port_id&&o.add(a.source_port_id);for(let s of n)s.source_port_id&&bIt(e,s)&&(o.has(s.source_port_id)||t.source_pin_missing_trace_warning.insert({message:`Port ${s.getNameAndAliases()[0]} on ${e.props.name} is missing a trace`,source_component_id:e.source_component_id,source_port_id:s.source_port_id,subcircuit_id:e.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},bIt=(e,t)=>{if(e.config.componentName==="Chip"){let n=e.props.pinAttributes;if(!n)return!1;for(let i of t.getNameAndAliases()){let o=n[i];if(o?.requiresPower||o?.requiresGround||o?.requiresVoltage!==void 0)return!0}return!1}return!0};function xIt(e){let t=e.font_size,n=e.text.length*t*.6,i=t,o=e.anchor_alignment||"center",r=e.anchor_position.x,s=e.anchor_position.y;switch(o){case"top_left":r=e.anchor_position.x+n/2,s=e.anchor_position.y+i/2;break;case"top_center":r=e.anchor_position.x,s=e.anchor_position.y+i/2;break;case"top_right":r=e.anchor_position.x-n/2,s=e.anchor_position.y+i/2;break;case"center_left":r=e.anchor_position.x+n/2,s=e.anchor_position.y;break;case"center":r=e.anchor_position.x,s=e.anchor_position.y;break;case"center_right":r=e.anchor_position.x-n/2,s=e.anchor_position.y;break;case"bottom_left":r=e.anchor_position.x+n/2,s=e.anchor_position.y-i/2;break;case"bottom_center":r=e.anchor_position.x,s=e.anchor_position.y-i/2;break;case"bottom_right":r=e.anchor_position.x-n/2,s=e.anchor_position.y-i/2;break;default:r=e.anchor_position.x,s=e.anchor_position.y;break}return{x:r-n/2,y:s-i/2,width:n,height:i}}function vIt(e){if(!e._adjustSilkscreenTextAutomatically||e.root?.pcbDisabled||!e.pcb_component_id)return;let{db:t}=e.root,i=e._getPcbCircuitJsonBounds().center,o=t.pcb_silkscreen_text.list({pcb_component_id:e.pcb_component_id}).filter(c=>c.text===e.name);if(o.length===0)return;let a=e.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(c=>c!==e&&c.pcb_component_id).map(c=>{let l=c._getPcbCircuitJsonBounds(),u={center:l.center,width:l.width,height:l.height};return Or(u)});for(let c of o){let l=c.anchor_position,u=xIt(c),h={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},d=Or(h);if(!a.some(T=>ic(d,T)))continue;let y=2*i.x-l.x,g=2*i.y-l.y,x={center:{x:y,y:g},width:u.width,height:u.height},w=Or(x);a.some(T=>ic(w,T))||t.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:y,y:g}})}}function SIt(e){if(!e)return{validPinLabels:e,invalidPinLabelsMessages:[]};let t={},n=[];for(let[i,o]of Object.entries(e)){let r=Array.isArray(o)?o.slice():[o],s=[];for(let a of r)wIt(i,a)?s.push(a):n.push(`Invalid pin label: ${i} = '${a}' - excluding from component. Please use a valid pin label.`);s.length>0&&(t[i]=Array.isArray(o)?s:s[0])}return{validPinLabels:Object.keys(t).length>0?t:void 0,invalidPinLabelsMessages:n}}function wIt(e,t){try{let n={name:"test",footprint:"test",pinLabels:{[e]:t}};return Jp.safeParse(n).success}catch{return!1}}var Hh=e=>e.startsWith("http://")||e.startsWith("https://"),k4=e=>{if(Hh(e))return null;let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t),i=e.slice(t+1);return!n||!i?null:{footprintLib:n,footprintName:i}},A4=e=>e.startsWith("/"),PIt=(0,BH.default)("tscircuit:core:resolveStaticFileImport");async function YH(e,t){if(!e)return e;let n=t?.resolveProjectStaticFileImportUrl;if(n&&e.startsWith("/"))try{let i=await n(e);if(i)return i}catch(i){PIt("failed to resolve static file via platform resolver",i)}return FH(e,t?.projectBaseUrl)}function IIt(e,t){let{footprint:n}=e.props;if(n??(n=e._getImpliedFootprintString?.()),!n)return;let{pcbRotation:i,pinLabels:o,pcbPinLabels:r}=e.props,s=LH(String(n)),a=s?e.root?.platform?.footprintFileParserMap?.[s]:null;if(typeof n=="string"&&(Hh(n)||A4(n))&&a){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0,t("load-footprint-from-platform-file-parser",async()=>{let c=Hh(n)?n:await YH(n,e.root?.platform);try{let l=await a.loadFromUrl(c),u=Vh({componentName:e.name,componentRotation:i,footprinterString:c,pinLabels:o,pcbPinLabels:r},l.footprintCircuitJson);e.addAll(u),e._markDirty("InitializePortsFromChildren")}catch(l){let u=e.root?.db;if(u&&e.source_component_id&&e.pcb_component_id){let h=e.getSubcircuit(),d=`${e.getString()} failed to load footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Ep.parse({type:"external_footprint_load_error",message:d,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:h.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof n=="string"&&Hh(n)){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let c=n;t("load-footprint-url",async()=>{try{let l=await fetch(c);if(!l.ok)throw new Error(`Failed to fetch footprint: ${l.status}`);let u=await l.json(),h=Vh({componentName:e.name,componentRotation:i,footprinterString:c,pinLabels:o,pcbPinLabels:r},u);e.addAll(h),e._markDirty("InitializePortsFromChildren")}catch(l){let u=e.root?.db;if(u&&e.source_component_id&&e.pcb_component_id){let h=e.getSubcircuit(),d=`${e.getString()} failed to load external footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Ep.parse({type:"external_footprint_load_error",message:d,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:h.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof n=="string"){let c=k4(n);if(!c||e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let u=e.root?.platform?.footprintLibraryMap?.[c.footprintLib],h;if(typeof u=="function"&&(h=u),!h)return;let d=e.getInheritedMergedProperty("pcbStyle");t("load-lib-footprint",async()=>{try{let _=await h(c.footprintName,{resolvedPcbStyle:d}),y=null;if(Array.isArray(_)?y=_:Array.isArray(_.footprintCircuitJson)&&(y=_.footprintCircuitJson),!y)return;let g=Vh({componentName:e.name,componentRotation:i,footprinterString:n,pinLabels:o,pcbPinLabels:r},y);e.addAll(g),!Array.isArray(_)&&_.cadModel&&(e._asyncFootprintCadModel=_.cadModel);for(let x of e.children)x.componentName==="Port"&&x._markDirty?.("PcbPortRender");e._markDirty("InitializePortsFromChildren")}catch(_){let y=e.root?.db;if(y&&e.source_component_id&&e.pcb_component_id){let g=e.getSubcircuit(),x=`${e.getString()} failed to load external footprint "${n}": `+(_ instanceof Error?_.message:String(_)),w=Ep.parse({type:"external_footprint_load_error",message:x,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:g.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:n});y.external_footprint_load_error.insert(w)}throw _}});return}if(!(0,N4.isValidElement)(n)&&n.componentName==="Footprint"&&e.add(n),Array.isArray(n)&&!(0,N4.isValidElement)(n)&&n.length>0){try{let c=Vh({componentName:e.name,componentRotation:i,footprinterString:"",pinLabels:o,pcbPinLabels:r},n);e.addAll(c)}catch(c){let l=e.root?.db;if(l&&e.source_component_id&&e.pcb_component_id){let u=e.getSubcircuit(),h=`${e.getString()} failed to load json footprint: `+(c instanceof Error?c.message:String(c)),d=k_.parse({type:"circuit_json_footprint_load_error",message:h,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:u.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});l.circuit_json_footprint_load_error.insert(d)}throw c}return}}function TIt(e){if(e.root?.pcbDisabled||!e.pcb_component_id)return;let{pcbX:t,pcbY:n}=e._parsedProps,i=e.props?.pcbPositionAnchor;if(!i||t===void 0&&n===void 0)return;let o=$x(e.children);if(o.width===0||o.height===0)return;let s={...{x:(o.minX+o.maxX)/2,y:(o.minY+o.maxY)/2}},a=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(i)){let u={left:o.minX,right:o.maxX,top:o.minY,bottom:o.maxY};switch(i){case"center":a=s;break;case"top_left":a={x:u.left,y:u.top};break;case"top_center":a={x:s.x,y:u.top};break;case"top_right":a={x:u.right,y:u.top};break;case"center_left":a={x:u.left,y:s.y};break;case"center_right":a={x:u.right,y:s.y};break;case"bottom_left":a={x:u.left,y:u.bottom};break;case"bottom_center":a={x:s.x,y:u.bottom};break;case"bottom_right":a={x:u.right,y:u.bottom};break}}else try{let u=e.portMap[i];u&&(a=u._getGlobalPcbPositionBeforeLayout())}catch{}if(!a)return;let l={...s};t!==void 0&&(l.x+=t-a.x),n!==void 0&&(l.y+=n-a.y),(Math.abs(l.x-s.x)>1e-6||Math.abs(l.y-s.y)>1e-6)&&e._repositionOnPcb(l)}var MIt=(0,wH.default)("tscircuit:core"),CIt=p.object({x:Be,y:Be,z:Be}),On=class extends xe{constructor(t){let n={...t},i=[];if(n.pinLabels&&!Array.isArray(n.pinLabels)){let{validPinLabels:o,invalidPinLabelsMessages:r}=SIt(n.pinLabels);n.pinLabels=o,i=r}super(n);P(this,"reactSubtrees",[]);P(this,"_impliedFootprint");P(this,"isPrimitiveContainer",!0);P(this,"_isNormalComponent",!0);P(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});P(this,"_asyncSupplierPartNumbers");P(this,"_asyncFootprintCadModel");P(this,"_isCadModelChild");P(this,"pcb_missing_footprint_error_id");P(this,"_hasStartedFootprintUrlLoad",!1);P(this,"_invalidPinLabelMessages",[]);P(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=i,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(n=>n.map(i=>typeof i=="number"?`pin${i}`:i))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let t=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(o=>o!==this&&o._isNormalComponent&&o.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let o=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:o,schematic_center:r}),this.shouldBeRemoved=!0;let s=[...this.children];for(let a of s)this.remove(a)}}initPorts(t={}){if(this.root?.schematicDisabled)return;let{config:n}=this,i=[],o=this._getSchematicPortArrangement();if(o&&!this._parsedProps.pinLabels){for(let l in o){let u=o[l].pins;if(Array.isArray(u))for(let h of u){let d=Om(h,this._parsedProps.pinLabels);i.push(new Ni({pinNumber:d,aliases:t.additionalAliases?.[`pin${d}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let a=["left","right","top","bottom"],c=1;for(let l of a){let u=o[`${l}Size`];for(let h=0;h<u;h++)i.push(new Ni({pinNumber:c++,aliases:t.additionalAliases?.[`pin${c}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let r=this._parsedProps.pinLabels;if(r)for(let[a,c]of Object.entries(r)){a=a.replace("pin","");let l=i.find(d=>d._parsedProps.pinNumber===Number(a)),u=Array.isArray(c)?c[0]:c,h=Array.isArray(c)?c.slice(1):[];l?(l.externallyAddedAliases.push(u,...h),l.props.name=u):(l=new Ni({pinNumber:parseInt(a),name:u,aliases:[...h,...t.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(n.schematicSymbolName&&!t.ignoreSymbolPorts){let a=ti[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=kH(c.labels);if(!l)continue;let u=i.find(h=>h._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let h=Cm(c.labels.concat(t.additionalAliases?.[`pin${l}`]??[]));h&&(h.originDescription=`schematicSymbol:labels[0]:${c.labels[0]}`,h.schematicSymbolPortDef=c,i.push(h))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){let a=this.getPortsFromFootprint(t);for(let c of a)i.some(l=>l.isMatchingAnyOf(c.getNameAndAliases()))||i.push(c)}let s=t.pinCount??this._getPinCount()??0;for(let a=1;a<=s;a++){if(i.find(l=>l._parsedProps.pinNumber===a))continue;if(!o){i.push(new Ni({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...o.leftSide?.pins??[],...o.rightSide?.pins??[],...o.topSide?.pins??[],...o.bottomSide?.pins??[]].map(l=>Om(l,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(l=>l in o)&&(c=Array.from({length:this._getPinCount()},(l,u)=>u+1)),c.includes(a)&&i.push(new Ni({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${a}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:t,pinLabels:n,pcbPinLabels:i}=this.props,{footprint:o}=this.props;if(o??(o=this._getImpliedFootprintString?.()),!!o&&typeof o=="string"){if(Hh(o)||A4(o)||k4(o))return;let r=GS.string(o).soup(),s=Vh({componentName:this.name??this.componentName,componentRotation:t,footprinterString:o,pinLabels:n,pcbPinLabels:i},r);this.addAll(s)}}get portMap(){return new Proxy({},{get:(t,n)=>{let i=this.children.find(o=>o.componentName==="Port"&&o.isMatchingNameOrAlias(n));if(!i)throw new Error(`There was an issue finding the port "${n.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return i}})}getInstanceForReactElement(t){for(let n of this.reactSubtrees)if(n.element===t)return n.component;return null}doInitialSourceRender(){let t=this.config.sourceFtype;if(!t)return;let{db:n}=this.root,{_parsedProps:i}=this,o=n.source_component.insert({ftype:t,name:this.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=o.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let r of this._invalidPinLabelMessages){let s="pinLabels",a=r.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);a&&(s=`pinLabels['${a[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:s,message:r,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:n}=this.config,{_parsedProps:i}=this;i.symbol&&(0,ca.isValidElement)(i.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(i.symbol):n?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let o=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&o){if(!this.schematic_component_id)return;let r=E_.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});t.schematic_manual_edit_conflict_warning.insert(r)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let t=[];for(let n of this.internallyConnectedPinNames){let i=[];for(let o of n)i.push(this.portMap[o]);t.push(i)}return t}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicSymbolNameOrThrow(),o=ti[i],r=this._getGlobalSchematicPositionBeforeLayout();if(o){let s=t.schematic_component.insert({center:r,size:o.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=s.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(t){if(this.root?.schematicDisabled)return;let{db:n}=this.root,i=this._getGlobalSchematicPositionBeforeLayout(),o=n.schematic_component.insert({center:i,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=o.schematic_component_id}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicBoxDimensions(),o={};if(Array.isArray(n.pinLabels))n.pinLabels.forEach((_,y)=>{o[String(y+1)]=_});else for(let[_,y]of Object.entries(n.pinLabels??{}))o[_]=Array.isArray(y)?y[0]:y;let r=this._getGlobalSchematicPositionBeforeLayout(),s=this._getSchematicPortArrangement(),a=t.schematic_component.insert({center:r,rotation:n.schRotation??0,size:i.getSize(),port_arrangement:E5t(s),pin_spacing:n.schPinSpacing??.2,pin_styles:C5t(n.schPinStyle,n.pinLabels),port_labels:o,source_component_id:this.source_component_id}),c=s?.topSide!==void 0||s?.bottomSide!==void 0,l=i?.getSize().width,u=i?.getSize().height,h=t.schematic_text.insert({text:n.manufacturerPartNumber??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?r.x+(l??0)/2+.1:r.x-(l??0)/2,y:c?r.y+(u??0)/2+.35:r.y-(u??0)/2-.13},color:"#006464",font_size:.18}),d=t.schematic_text.insert({text:n.name??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?r.x+(l??0)/2+.1:r.x-(l??0)/2,y:c?r.y+(u??0)/2+.55:r.y+(u??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=a.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),o=n.layer??"top";if(o!=="top"&&o!=="bottom"){let h=Np.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:i.subcircuit_id??void 0});t.pcb_component_invalid_layer_error.insert(h)}let r=this._computePcbGlobalTransformBeforeLayout(),a=Ar(r).rotation.angle*180/Math.PI,c=t.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:o==="top"||o==="bottom"?o:"top",rotation:n.pcbRotation??a,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});if(!(n.footprint??this._getImpliedFootprintString())&&!this.isGroup){let h=t.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=h.pcb_missing_footprint_error_id}this.pcb_component_id=c.pcb_component_id;let u=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&u){let h=A_.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0});t.pcb_manual_edit_conflict_warning.insert(h)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:t}=this.root,{_parsedProps:n}=this,i=$x(this.children);if(i.width===0||i.height===0)return;let o={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};t.pcb_component.update(this.pcb_component_id,{center:o,width:i.width,height:i.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db:t}=this.root;if(!t.schematic_component.get(this.schematic_component_id))return;let i=[],o=u=>{for(let h of u){if(h.isSchematicPrimitive&&h.componentName==="SchematicLine"){let d=t.schematic_line.get(h.schematic_line_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicRect"){let d=t.schematic_rect.get(h.schematic_rect_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicCircle"){let d=t.schematic_circle.get(h.schematic_circle_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicArc"){let d=t.schematic_arc.get(h.schematic_arc_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicText"){let d=t.schematic_text.get(h.schematic_text_id);d&&i.push(d)}h.children&&h.children.length>0&&o(h.children)}};if(o(this.children),i.length===0)return;let r=NH(i),s=Math.abs(r.maxX-r.minX),a=Math.abs(r.maxY-r.minY);if(s===0&&a===0)return;let c=(r.minX+r.maxX)/2,l=(r.minY+r.maxY)/2;t.schematic_component.update(this.schematic_component_id,{center:{x:c,y:l},size:{width:s,height:a}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){TIt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(t){let n=CH(t);return{element:t,component:n}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let t=this.props.footprint;(0,ca.isValidElement)(t)&&(this.children.some(r=>r.componentName==="Footprint")||this.add(t));let n=this.props.symbol;(0,ca.isValidElement)(n)&&(this.children.some(r=>r.componentName==="Symbol")||this.add(n));let i=this.props.cadModel;if((0,ca.isValidElement)(i)){this._isCadModelChild=!0;let o=this.children.some(s=>s.componentName==="CadAssembly"),r=this.children.some(s=>s.componentName==="CadModel");!o&&!r&&this.add(i)}}doInitialPcbFootprintStringRender(){IIt(this,(t,n)=>this._queueAsyncEffect(t,n))}_hasExistingPortExactly(t){return this.children.filter(i=>i.componentName==="Port").some(i=>{let o=t.getNameAndAliases(),r=i.getNameAndAliases();return o.length===r.length&&o.every(s=>r.includes(s))})}add(t){let n;if((0,ca.isValidElement)(t)){let i=this._renderReactSubtree(t);this.reactSubtrees.push(i),n=i.component}else n=t;if(n.componentName==="Port"){if(this._hasExistingPortExactly(n))return;let o=this.children.filter(r=>r.componentName==="Port").find(r=>r.isMatchingAnyOf(n.getNameAndAliases()));o&&MIt(`Similar ports added. Port 1: ${o}, Port 2: ${n}`)}super.add(n)}getPortsFromFootprint(t){let{footprint:n}=this.props;if((!n||(0,ca.isValidElement)(n))&&(n=this.children.find(o=>o.componentName==="Footprint")),typeof n=="string"){if(Hh(n))return[];if(A4(n))return[];if(k4(n))return[];let o=GS.string(n).soup(),r=[];for(let s of o)if("port_hints"in s&&s.port_hints){let a=Cm(s.port_hints,t);if(!a)continue;a.originDescription=`footprint:string:${n}:port_hints[0]:${s.port_hints[0]}`,r.push(a)}return r}if(!(0,ca.isValidElement)(n)&&n&&n.componentName==="Footprint"){let o=n,r=1,s=[];for(let a of o.children){if(!a.props.portHints)continue;let c=a.props.portHints;c.some(h=>h.startsWith("pin"))||(c=[...c,`pin${r}`]),r++;let u=Cm(c);u&&(u.originDescription=`footprint:${n}`,s.push(u))}return s}let i=[];if(!n){for(let o of this.children)if(o.props.portHints&&o.isPcbPrimitive){let r=Cm(o.props.portHints);r&&i.push(r)}}return i}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:t}=this;if(!t.schematicSymbolName)return[];let n=ti[t.schematicSymbolName];if(!n)return[];let i=[];for(let o of n.ports){let r=Cm(o.labels);r&&(r.schematicSymbolPortDef=o,i.push(r))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:t}=this,n=[];if(t.connections)for(let[i,o]of Object.entries(t.connections)){let r=Array.isArray(o)?o:[o];for(let s of r)n.push(String(s))}return n}_createNetsFromProps(t){zx(this,t)}_getPcbCircuitJsonBounds(){let{db:t}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let n=t.pcb_component.get(this.pcb_component_id);return{center:{x:n.center.x,y:n.center.y},bounds:{left:n.center.x-n.width/2,top:n.center.y-n.height/2,right:n.center.x+n.width/2,bottom:n.center.y+n.height/2},width:n.width,height:n.height}}_getPinCountFromSchematicPortArrangement(){let t=this._getSchematicPortArrangement();if(!t)return 0;if(!AH(t))return(t.leftSize??t.leftPinCount??0)+(t.rightSize??t.rightPinCount??0)+(t.topSize??t.topPinCount??0)+(t.bottomSize??t.bottomPinCount??0);let{leftSide:i,rightSide:o,topSide:r,bottomSide:s}=t;return Math.max(...i?.pins??[],...o?.pins??[],...r?.pins??[],...s?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let n=this.getPortsFromFootprint();if(n.length>0)return n.length;let{pinLabels:i}=this._parsedProps;if(i){if(Array.isArray(i))return i.length;let o=Object.keys(i).map(r=>r.startsWith("pin")?parseInt(r.slice(3)):parseInt(r)).filter(r=>!Number.isNaN(r));return o.length>0?Math.max(...o):Object.keys(i).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getPinLabelsFromPorts(){let t=this.selectAll("port"),n={};for(let i of t){let o=i.props.pinNumber;if(o!==void 0){let r=i._getBestDisplayPinLabel();r&&(n[`pin${o}`]=r)}}return n}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this,n=this._getPinCount(),i=t.schPinSpacing??.2,r={...this._getPinLabelsFromPorts(),...t.pinLabels};return j5t({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:i,numericSchPinStyle:X5t(t.schPinStyle,r),pinCount:n,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:r})}getFootprinterString(){return typeof this._parsedProps.footprint=="string"?this._parsedProps.footprint:null}doInitialCadModelRender(){if(this._isCadModelChild||this.props.doNotPlace)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=this._parsedProps.cadModel,o=i===void 0?this._asyncFootprintCadModel:i,r=this.getFootprinterString()??this._getImpliedFootprintString();if(!this.pcb_component_id||!o&&!r||o===null)return;let s=this._getPcbCircuitJsonBounds();if(typeof o=="string")throw new Error("String cadModel not yet implemented");let a=CIt.parse({x:0,y:0,z:typeof o?.rotationOffset=="number"?o.rotationOffset:0,...typeof o?.rotationOffset=="object"?o.rotationOffset??{}:{}}),c=vl.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?Y.parse(o.zOffsetFromSurface):0,u=this.props.layer==="bottom"?"bottom":"top",h=this._computePcbGlobalTransformBeforeLayout(),_=Ar(h).rotation.angle*180/Math.PI,y=u==="bottom",g=_+(a.z??0),x=Vl(g),w=t.cad_component.insert({position:{x:s.center.x+c.x,y:s.center.y+c.y,z:(u==="bottom"?-n/2:n/2)+(u==="bottom"?-l:l)+c.z},rotation:{x:a.x,y:a.y+(y?180:0),z:Vl(y?-x:x)},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,footprinter_string:typeof r=="string"&&!o?r:void 0});this.cad_component_id=w.cad_component_id}_addCachebustToModelUrl(t){if(!t||!t.includes("modelcdn.tscircuit.com"))return t;let n=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(n)}`}_getPartsEngineCacheKey(t,n){return JSON.stringify({ftype:t.ftype,name:t.name,manufacturer_part_number:t.manufacturer_part_number,footprinterString:n})}async _getSupplierPartNumbers(t,n,i){if(this.props.doNotPlace)return{};let o=this.root?.platform?.localCacheEngine,r=this._getPartsEngineCacheKey(n,i);if(o){let c=await o.getItem(r);if(c)try{return JSON.parse(c)}catch{}}let s=await Promise.resolve(t.findPart({sourceComponent:n,footprinterString:i}));if(typeof s=="string"){if(s.includes("<!DOCTYPE")||s.includes("<html"))throw new Error(`Failed to fetch supplier part numbers: Received HTML response instead of JSON. Response starts with: ${s.substring(0,100)}`);if(s==="Not found")return{};throw new Error(`Invalid supplier part numbers format: Expected object but got string: "${s}"`)}if(!s||Array.isArray(s)||typeof s!="object"){let c=s===null?"null":Array.isArray(s)?"array":typeof s;throw new Error(`Invalid supplier part numbers format: Expected object but got ${c}`)}let a=s;if(o)try{await o.setItem(r,JSON.stringify(a))}catch{}return a}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let t=this.getInheritedProperty("partsEngine");if(!t)return;let{db:n}=this.root,i=n.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let o;this.props.footprint&&typeof this.props.footprint=="string"&&(o=this.props.footprint);let r=this._getSupplierPartNumbers(t,i,o);if(!(r instanceof Promise)){n.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={};let a=M_.parse({type:"unknown_error_finding_part",message:`Failed to fetch supplier part numbers for ${this.getString()}: ${s.message}`,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});n.unknown_error_finding_part.insert(a),this._markDirty("PartsEngineRender")})})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(n&&!n.supplier_part_numbers&&this._asyncSupplierPartNumbers){t.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:t}=this;t.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:t}=this;if(t.connections)for(let[n,i]of Object.entries(t.connections)){let o=Array.isArray(i)?i:[i];for(let r of o)this.add(new $r({from:`.${this.name} > .${n}`,to:String(r)}))}}doInitialSourceDesignRuleChecks(){gIt(this)}_getMinimumFlexContainerSize(){return _It(this)}_repositionOnPcb(t){return yIt(this,t)}doInitialSilkscreenOverlapAdjustment(){return vIt(this)}isRelativelyPositioned(){return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0}},EIt=({boardAnchorPosition:e,boardAnchorAlignment:t,width:n,height:i})=>{let{x:o,y:r}=e,s=o,a=r;switch(t){case"top_left":s=o+n/2,a=r-i/2;break;case"top_right":s=o-n/2,a=r-i/2;break;case"bottom_left":s=o+n/2,a=r+i/2;break;case"bottom_right":s=o-n/2,a=r+i/2;break;case"top":s=o,a=r-i/2;break;case"bottom":s=o,a=r+i/2;break;case"left":s=o+n/2,a=r;break;case"right":s=o-n/2,a=r;break;case"center":default:break}return{x:s,y:a}},NIt=class{constructor(e,t={}){P(this,"input");P(this,"isRouting",!1);P(this,"solver");P(this,"eventHandlers",{complete:[],error:[],progress:[]});P(this,"cycleCount",0);P(this,"stepDelay");P(this,"timeoutId");this.input=e;let{capacityDepth:n,targetMinCapacity:i,stepDelay:o=0,useAssignableViaSolver:r=!1}=t,{AutoroutingPipelineSolver:s,AssignableViaAutoroutingPipelineSolver:a}=bT,c=r?a:s;this.solver=new c(e,{capacityDepth:n,targetMinCapacity:i,cacheProvider:null}),this.stepDelay=o}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new Em(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;let i=this.solver?.preview()||void 0,o=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:o,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(e){this.emitEvent({type:"error",error:e instanceof Error?new Em(e.message):new Em(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(e,t){e==="complete"?this.eventHandlers.complete.push(t):e==="error"?this.eventHandlers.error.push(t):e==="progress"&&this.eventHandlers.progress.push(t)}emitEvent(e){if(e.type==="complete")for(let t of this.eventHandlers.complete)t(e);else if(e.type==="error")for(let t of this.eventHandlers.error)t(e);else if(e.type==="progress")for(let t of this.eventHandlers.progress)t(e)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Em(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},B4=class extends xe{constructor(){super(...arguments);P(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:vD}}doInitialPortMatching(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)return;if(i.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!i)throw new Error("TraceHint has no parent");if(!n.for){this.renderError(`TraceHint has no for property (${this})`);return}let o=i.selectOne(n.for,{type:"port"});o||this.renderError(`${this} could not find port for selector "${n.for}"`),this.matchedPort=o,o.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:t}=this,n=t.offset?[t.offset]:t.offsets;if(!n)return[];let i=this._computePcbGlobalTransformBeforeLayout();return n.map(o=>({...Ne(i,o),via:o.via,to_layer:o.to_layer,trace_width:o.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this;t.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},XH=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,pcb_placements:[...n.pcb_placements??[]]};for(let o of t)if(o.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:r,new_center:s}=o,a=Le(e).pcb_component.get(r);if(!a)continue;let c=Le(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.pcb_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.pcb_placements[l]=u:i.pcb_placements.push(u)}return i},VH=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,schematic_placements:[...n.schematic_placements??[]]};for(let o of t)if(o.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:r,new_center:s}=o,a=Le(e).schematic_component.get(r);if(!a||!a.source_component_id)continue;let c=Le(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.schematic_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.schematic_placements[l]=u:i.schematic_placements.push(u)}return i},kIt=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i=t.filter(s=>s.edit_event_type==="edit_schematic_component_location"),o=t.filter(s=>s.edit_event_type==="edit_pcb_component_location"),r=n;return i.length>0&&(r=VH({circuitJson:e,editEvents:i,manualEditsFile:r})),o.length>0&&(r=XH({circuitJson:e,editEvents:o,manualEditsFile:r})),r},AIt=(e,t)=>{if(Le(e).pcb_trace_hint.get(t.pcb_trace_hint_id))e=e.map(i=>i.pcb_trace_hint_id===t.pcb_trace_hint_id?{...i,route:t.route}:i);else{let i=Le(e).pcb_port.get(t.pcb_port_id);e=e.filter(o=>!(o.type==="pcb_trace_hint"&&o.pcb_port_id===t.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:t.pcb_trace_hint_id,route:t.route,pcb_port_id:t.pcb_port_id,pcb_component_id:i?.pcb_component_id}])}return e},RIt=({circuitJson:e,editEvents:t})=>{e=JSON.parse(JSON.stringify(e));for(let n of t)if(n.edit_event_type==="edit_pcb_component_location"){let i=e.find(r=>r.type==="pcb_component"&&r.pcb_component_id===n.pcb_component_id);if((!i||i.center.x!==n.new_center.x||i.center.y!==n.new_center.y)&&n.original_center){let r=vn(n.new_center.x-n.original_center.x,n.new_center.y-n.original_center.y);e=e.map(s=>s.pcb_component_id!==n.pcb_component_id?s:VI(s,r))}}else n.edit_event_type==="edit_schematic_component_location"?e=e.map(i=>i.type==="schematic_component"&&i.schematic_component_id===n.schematic_component_id?{...i,center:n.new_center}:i):n.edit_event_type==="edit_pcb_trace_hint"&&(e=AIt(e,n));return e},HH=(e,t)=>{let n=e.source_group.list(),i=[],o=r=>{let s=n.filter(a=>a.parent_subcircuit_id===r);for(let a of s)a.subcircuit_id&&(i.push(a.subcircuit_id),o(a.subcircuit_id))};return o(t),i},R4=({db:e,circuitJson:t,subcircuit_id:n,minTraceWidth:i=.1})=>{if(!e&&t&&(e=Le(t)),!e)throw new Error("db or circuitJson is required");let o=e.pcb_trace_hint.list(),r=n?new Set([n]):null;if(n){let k=HH(e,n);for(let N of k)r.add(N)}let s=(t??e.toArray()).filter(k=>!n||"subcircuit_id"in k&&r.has(k.subcircuit_id)),a=e.pcb_board.list()[0];e=Le(s);let c=$i(s),l=$H([...e.pcb_component.list(),...e.pcb_smtpad.list(),...e.pcb_plated_hole.list(),...e.pcb_hole.list(),...e.pcb_via.list(),...e.pcb_cutout.list()].filter(k=>!n||r?.has(k.subcircuit_id)),c);for(let k of l){let N=k.connectedTo.flatMap(A=>c.getIdsConnectedToNet(A));k.connectedTo.push(...N)}let u=l.flatMap(k=>[{x:k.center.x-k.width/2,y:k.center.y-k.height/2},{x:k.center.x+k.width/2,y:k.center.y+k.height/2}]).concat(a?.outline??[]),h;if(a&&!a.outline?h={minX:a.center.x-a.width/2,maxX:a.center.x+a.width/2,minY:a.center.y-a.height/2,maxY:a.center.y+a.height/2}:h={minX:Math.min(...u.map(k=>k.x))-1,maxX:Math.max(...u.map(k=>k.x))+1,minY:Math.min(...u.map(k=>k.y))-1,maxY:Math.max(...u.map(k=>k.y))+1},n){let k=e.pcb_group.getWhere({subcircuit_id:n});if(k?.width&&k.height){let N={minX:k.center.x-k.width/2,maxX:k.center.x+k.width/2,minY:k.center.y-k.height/2,maxY:k.center.y+k.height/2};h={minX:Math.min(h.minX,N.minX),maxX:Math.max(h.maxX,N.maxX),minY:Math.min(h.minY,N.minY),maxY:Math.max(h.maxY,N.maxY)}}}let d=new Set(e.pcb_trace.list().map(k=>k.source_trace_id).filter(k=>!!k)),_=e.source_trace.list().filter(k=>!d.has(k.source_trace_id)).map(k=>{let N=k.connected_source_port_ids.map(G=>{let tt=e.source_port.get(G),Q=e.pcb_port.getWhere({source_port_id:G});return{...tt,...Q}});if(N.length<2)return null;let[A,R]=N,$=A.layers?.[0]??"top",j=R.layers?.[0]??"top",H=o.filter(G=>G.pcb_port_id===A.pcb_port_id||G.pcb_port_id===R.pcb_port_id),X=[];for(let G of H){let Q=e.pcb_port.get(G.pcb_port_id)?.layers?.[0]??"top";for(let V of G.route)X.push({x:V.x,y:V.y,layer:Q})}return{name:k.source_trace_id??c.getNetConnectedToId(k.source_trace_id)??"",source_trace_id:k.source_trace_id,width:k.min_trace_thickness,pointsToConnect:[{x:A.x,y:A.y,layer:$,pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},...X,{x:R.x,y:R.y,layer:j,pointId:R.pcb_port_id,pcb_port_id:R.pcb_port_id}]}}).filter(k=>k!==null),y=new Map(_.map(k=>[k.source_trace_id,k])),g=e.source_net.list().filter(k=>!n||r?.has(k.subcircuit_id)),x=[];for(let k of g){let N=e.source_trace.list().filter(A=>A.connected_source_net_ids?.includes(k.source_net_id));x.push({name:k.source_net_id??c.getNetConnectedToId(k.source_net_id),pointsToConnect:N.flatMap(A=>e.pcb_port.list().filter($=>A.connected_source_port_ids.includes($.source_port_id)).map($=>({x:$.x,y:$.y,layer:$.layers?.[0]??"top",pointId:$.pcb_port_id,pcb_port_id:$.pcb_port_id})))})}let w=e.pcb_breakout_point.list().filter(k=>!n||r?.has(k.subcircuit_id)),S=[],T=new Map;for(let k of w){let N={x:k.x,y:k.y,layer:"top"};if(k.source_trace_id){let A=y.get(k.source_trace_id)??T.get(k.source_trace_id);if(A)A.pointsToConnect.push(N);else{let R={name:k.source_trace_id,source_trace_id:k.source_trace_id,pointsToConnect:[N]};S.push(R),T.set(k.source_trace_id,R)}}else if(k.source_net_id){let A=x.find(R=>R.name===k.source_net_id);A?A.pointsToConnect.push(N):S.push({name:k.source_net_id,pointsToConnect:[N]})}else if(k.source_port_id){let A=e.pcb_port.getWhere({source_port_id:k.source_port_id});A&&S.push({name:k.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:A.x,y:A.y,layer:A.layers?.[0]??"top",pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},N]})}}let I=[..._,...x,...S],E=new Map;for(let k of I)for(let N of k.pointsToConnect)N.pointId&&E.set(N.pointId,k);let M=e.pcb_trace.list().filter(k=>!n||r?.has(k.subcircuit_id));for(let k of M){let N=new Set;for(let $ of k.route)$.start_pcb_port_id&&N.add($.start_pcb_port_id),$.end_pcb_port_id&&N.add($.end_pcb_port_id);if(N.size<2)continue;let A=N.values().next().value;if(!A)continue;let R=E.get(A);R&&[...N].every($=>E.get($)===R)&&(R.externallyConnectedPointIds??(R.externallyConnectedPointIds=[]),R.externallyConnectedPointIds.push([...N]))}return{simpleRouteJson:{bounds:h,obstacles:l,connections:I,layerCount:a?.num_layers??2,minTraceWidth:i,outline:a?.outline?.map(k=>({...k}))},connMap:c}},OIt=e=>{let t={};if(!e)return t;for(let i of aa)t[i]=0;let n=new Map;for(let i of e){let[,,o,r]=i.type.split(":");if(r==="start"){n.set(`${o}:${i.renderId}`,i);continue}if(r==="end"){let s=n.get(`${o}:${i.renderId}`);if(s){let a=i.createdAt-s.createdAt;t[o]=(t[o]||0)+a}}}return t},LIt=e=>{let t=e.map(c=>[...new Set(c)]),n=t.map(()=>[]),i=t.map(()=>null);for(let c=0;c<t.length;c++)for(let l of t[c])if(/^\d+$/.test(l)){i[c]=Number.parseInt(l);break}let o=0,r=new Set;for(let c=0;c<i.length;c++){let l=i[c];if(l===null||l<1)continue;if(!r.has(l)){r.add(l),n[c].push(`pin${l}`),o=Math.max(o,l);continue}let u=0;for(let h of n[c])h.startsWith(`pin${l}_alt`)&&u++;n[c].push(`pin${l}_alt${u+1}`)}for(let c=0;c<n.length;c++)n[c][0]?.includes("_alt")&&(o++,n[c].unshift(`pin${o}`));for(let c=0;c<n.length;c++)n[c].length===0&&(o++,n[c].push(`pin${o}`));let s={};for(let c of t)for(let l of c)/^\d+$/.test(l)||(s[l]=(s[l]??0)+1);let a={};for(let c=0;c<t.length;c++){let l=t[c];for(let u of l)/^\d+$/.test(u)||(s[u]===1?n[c].push(u):(a[u]=(a[u]??0)+1,n[c].push(`${u}${a[u]}`)))}return n};function Y4({db:e,schematicComponentId:t,deltaX:n,deltaY:i}){let o=e.schematic_rect.list({schematic_component_id:t});for(let c of o)c.center.x+=n,c.center.y+=i;let r=e.schematic_line.list({schematic_component_id:t});for(let c of r)c.x1+=n,c.y1+=i,c.x2+=n,c.y2+=i;let s=e.schematic_circle.list({schematic_component_id:t});for(let c of s)c.center.x+=n,c.center.y+=i;let a=e.schematic_arc.list({schematic_component_id:t});for(let c of a)c.center.x+=n,c.center.y+=i}var cH=(0,GH.default)("Group_doInitialSchematicLayoutMatchAdapt");function FIt(e){let{db:t}=e.root,n=If(t.toArray(),{source_group_id:e.source_group_id}),i=xT(n);cH.enabled&&global.debugGraphics?.push(dc(i,{title:`floatingBpcGraph-${e.name}`}));let o=xT(n),r={boxes:o.boxes,pins:o.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:s}=YB([{variantName:"default",floatingGraph:o},{variantName:"noNotConnected",floatingGraph:r}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(o.boxes.filter(c=>o.pins.filter(h=>h.boxId===c.boxId).filter(h=>!h.color.includes("center")).length<=2).map(c=>c.boxId)),corpus:{}});cH.enabled&&global.debugGraphics?.push(dc(s,{title:`laidOutBpcGraph-${e.name}`}));let a=e._getGlobalSchematicPositionBeforeLayout();for(let c of s.boxes){if(!c.center)continue;let l=t.schematic_component.get(c.boxId);if(l){let h={x:c.center.x+a.x,y:c.center.y+a.y},d=t.schematic_port.list({schematic_component_id:l.schematic_component_id}),_=t.schematic_text.list({schematic_component_id:l.schematic_component_id}),y={x:h.x-l.center.x,y:h.y-l.center.y};for(let g of d)g.center.x+=y.x,g.center.y+=y.y;for(let g of _)g.position.x+=y.x,g.position.y+=y.y;Y4({db:t,schematicComponentId:l.schematic_component_id,deltaX:y.x,deltaY:y.y}),l.center=h;continue}let u=t.schematic_net_label.get(c.boxId);if(u){let h=s.pins.find(_=>_.boxId===c.boxId&&_.color==="netlabel_center");if(!h)throw new Error(`No pin found for net label: ${c.boxId}`);let d={x:c.center.x+a.x,y:c.center.y+a.y};u.center=d,u.anchor_position={x:d.x+h.offset.x,y:d.y+h.offset.y};continue}console.error(`No schematic element found for box: ${c.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var de=(0,UH.default)("Group_doInitialSchematicLayoutMatchpack");function lH(e){switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function uH(e,t){let n=["right","up","left","down"],i=n.indexOf(e);if(i===-1)return e;let o=Math.round(t/90),r=(i+o)%4;return n[r<0?r+4:r]}function zIt(e,t,n){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};de(`[${n.name}] Processing ${e.childNodes.length} child nodes for input problem`),e.childNodes.forEach((r,s)=>{if(de(`[${n.name}] Processing child ${s}: nodeType=${r.nodeType}`),r.nodeType==="component"?de(`[${n.name}] - Component: ${r.sourceComponent?.name}`):r.nodeType==="group"&&de(`[${n.name}] - Group: ${r.sourceGroup?.name}`),r.nodeType==="component"&&r.sourceComponent){let a=r.sourceComponent.name||`chip_${s}`,c=t.schematic_component.getWhere({source_component_id:r.sourceComponent.source_component_id});if(!c)return;let l=n.children.find(S=>S.source_component_id===r.sourceComponent?.source_component_id),u=[0,90,180,270];l?._parsedProps?.schOrientation&&(u=[0]),l?._parsedProps?.schRotation!==void 0&&(u=[0]),l?._parsedProps?.facingDirection&&(u=[0]),l?._parsedProps?.schFacingDirection&&(u=[0]),l?.componentName==="Chip"&&(u=[0]);let h=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,d=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,_=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,y=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0;l?.config.shouldRenderAsSchematicBox&&(_+=.4,y+=.4);let g=(d-h)/2,x=(_-y)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+h+d,y:(c.size?.height||1)+_+y},availableRotations:u};let w=t.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let S of w){let T=t.source_port.get(S.source_port_id);if(!T)continue;let I=`${a}.${T.pin_number||T.name||S.schematic_port_id}`;i.chipMap[a].pins.push(I);let E=lH(S.facing_direction);i.chipPinMap[I]={pinId:I,offset:{x:(S.center?.x||0)-(c.center.x||0)+g,y:(S.center?.y||0)-(c.center.y||0)+x},side:E}}}else if(r.nodeType==="group"&&r.sourceGroup){let a=r.sourceGroup.name||`group_${s}`;de(`[${n.name}] Processing nested group: ${a}`);let c=t.schematic_group?.getWhere?.({source_group_id:r.sourceGroup.source_group_id}),l=n.children.find(u=>u.source_group_id===r.sourceGroup?.source_group_id);if(de(`[${n.name}] Found schematic_group for ${a}:`,c),c){de(`[${n.name}] Treating group ${a} as composite chip`);let u=t.schematic_component.list({schematic_group_id:c.schematic_group_id});de(`[${n.name}] Group ${a} has ${u.length} components:`,u.map(A=>A.source_component_id));let h=1/0,d=-1/0,_=1/0,y=-1/0,g=!1;for(let A of u)if(A.center&&A.size){g=!0;let R=A.size.width/2,$=A.size.height/2;h=Math.min(h,A.center.x-R),d=Math.max(d,A.center.x+R),_=Math.min(_,A.center.y-$),y=Math.max(y,A.center.y+$)}let x=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,w=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,S=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,T=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,I=(w-x)/2,E=(S-T)/2,M=(g?d-h:2)+x+w,k=(g?y-_:2)+S+T;de(`[${n.name}] Group ${a} computed size: ${M} x ${k}`);let N=[];for(let A of u){let R=t.schematic_port.list({schematic_component_id:A.schematic_component_id});for(let $ of R){let j=t.source_port.get($.source_port_id);if(!j)continue;let H=`${a}.${j.pin_number||j.name||$.schematic_port_id}`;N.push(H);let X=c.center||{x:0,y:0},G=lH($.facing_direction);i.chipPinMap[H]={pinId:H,offset:{x:($.center?.x||0)-X.x+I,y:($.center?.y||0)-X.y+E},side:G}}}de(`[${n.name}] Group ${a} has ${N.length} pins:`,N),i.chipMap[a]={chipId:a,pins:N,size:{x:M,y:k}},de(`[${n.name}] Added group ${a} to chipMap`)}else de(`[${n.name}] Warning: No schematic_group found for group ${a}`)}}),de(`[${n.name}] Creating connections using connectivity keys`);let o=new Map;for(let[r,s]of Object.entries(i.chipMap))for(let a of s.pins){let c=a.split(".").pop(),l=e.childNodes.find(u=>u.nodeType==="component"&&u.sourceComponent?u.sourceComponent.name===r:u.nodeType==="group"&&u.sourceGroup?`group_${e.childNodes.indexOf(u)}`===r:!1);if(l?.nodeType==="group"&&l.sourceGroup){let u=t.schematic_group?.getWhere?.({source_group_id:l.sourceGroup.source_group_id});if(u){let h=t.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let d of h){let _=t.source_port.list({source_component_id:d.source_component_id});for(let y of _){let g=y.pin_number||y.name;if(String(g)===String(c))if(y.subcircuit_connectivity_map_key){let x=y.subcircuit_connectivity_map_key;o.has(x)||o.set(x,[]),o.get(x).push(a),de(`[${n.name}] \u2713 Pin ${a} has connectivity key: ${x}`)}else de(`[${n.name}] Pin ${a} has no connectivity key`)}}}}else if(l?.nodeType==="component"&&l.sourceComponent){let u=t.source_port.list({source_component_id:l.sourceComponent.source_component_id});for(let h of u){let d=h.pin_number||h.name;if(String(d)===String(c)&&h.subcircuit_connectivity_map_key){let _=h.subcircuit_connectivity_map_key;o.has(_)||o.set(_,[]),o.get(_).push(a),de(`[${n.name}] Pin ${a} has connectivity key: ${_}`)}}}}de(`[${n.name}] Found ${o.size} connectivity groups:`,Array.from(o.entries()).map(([r,s])=>({key:r,pins:s})));for(let[r,s]of o)if(s.length>=2){let a=t.source_trace.list().filter(u=>u.subcircuit_connectivity_map_key===r),c=a.some(u=>u.connected_source_net_ids&&u.connected_source_net_ids.length>0),l=a.some(u=>u.connected_source_port_ids&&u.connected_source_port_ids.length>=2);if(de(`[${n.name}] Connectivity ${r}: hasNetConnections=${c}, hasDirectConnections=${l}`),l){for(let u of a)if(u.connected_source_port_ids&&u.connected_source_port_ids.length>=2){let h=[];for(let d of u.connected_source_port_ids)for(let _ of s){let y=_.split(".").pop(),g=t.source_port.get(d);if(g&&String(g.pin_number||g.name)===String(y)){let x=_.split(".")[0],w=e.childNodes.find(S=>S.nodeType==="component"&&S.sourceComponent?S.sourceComponent.name===x:S.nodeType==="group"&&S.sourceGroup?`group_${e.childNodes.indexOf(S)}`===x:!1);w?.nodeType==="component"&&w.sourceComponent&&t.source_port.list({source_component_id:w.sourceComponent.source_component_id}).some(T=>T.source_port_id===d)&&h.push(_)}}for(let d=0;d<h.length;d++)for(let _=d+1;_<h.length;_++){let y=h[d],g=h[_];i.pinStrongConnMap[`${y}-${g}`]=!0,i.pinStrongConnMap[`${g}-${y}`]=!0,de(`[${n.name}] Created strong connection: ${y} <-> ${g}`)}}}if(c){let u=t.source_net.getWhere({subcircuit_connectivity_map_key:r}),h=u?.is_ground??!1,d=u?.is_power??!1;i.netMap[r]={netId:r,isGround:h,isPositiveVoltageSource:d};for(let _ of s)i.netConnMap[`${_}-${r}`]=!0;de(`[${n.name}] Created net ${r} with ${s.length} pins:`,s)}}return i}function DIt(e){let{db:t}=e.root,n=ih(t.toArray(),{source_group_id:e.source_group_id});if(de(`[${e.name}] Starting matchpack layout with ${n.childNodes.length} children`),de(`[${e.name}] Tree structure:`,JSON.stringify(n,null,2)),n.childNodes.length<=1){de(`[${e.name}] Only ${n.childNodes.length} children, skipping layout`);return}de("Converting circuit tree to InputProblem...");let i=zIt(n,t,e);de.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${e.name}`,content:JSON.stringify(i,null,2)});let o=new GY(i);if(de("Starting LayoutPipelineSolver..."),de.enabled&&global.debugGraphics){let c=o.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${e.name}`})}if(o.solve(),de(`Solver completed in ${o.iterations} iterations`),de(`Solved: ${o.solved}, Failed: ${o.failed}`),o.failed)throw de(`Solver failed with error: ${o.error}`),new Error(`Matchpack layout solver failed: ${o.error}`);let r=o.getOutputLayout();if(de("OutputLayout:",JSON.stringify(r,null,2)),de("Solver completed successfully:",!o.failed),de.enabled&&global.debugGraphics){let c=o.visualize();global.debugGraphics.push({...c,title:`matchpack-final-${e.name}`})}let s=o.checkForOverlaps(r);if(s.length>0){de(`Warning: Found ${s.length} overlapping components:`);for(let c of s)de(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=e._getGlobalSchematicPositionBeforeLayout();de(`Group offset: x=${a.x}, y=${a.y}`),de(`Applying layout results for ${Object.keys(r.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(r.chipPlacements)){de(`Processing placement for chip: ${c} at (${l.x}, ${l.y})`);let u=n.childNodes.find(d=>{if(d.nodeType==="component"&&d.sourceComponent){let _=d.sourceComponent.name===c;return de(` Checking component ${d.sourceComponent.name}: matches=${_}`),_}if(d.nodeType==="group"&&d.sourceGroup){let _=d.sourceGroup.name,y=`group_${n.childNodes.indexOf(d)}`,g=y===c;return de(` Checking group ${_} (expected chipId: ${y}): matches=${g}`),g}return!1});if(!u){de(`Warning: No tree node found for chip: ${c}`),de("Available tree nodes:",n.childNodes.map((d,_)=>({type:d.nodeType,name:d.nodeType==="component"?d.sourceComponent?.name:d.sourceGroup?.name,expectedChipId:d.nodeType==="group"?`group_${_}`:d.sourceComponent?.name})));continue}let h={x:l.x+a.x,y:l.y+a.y};if(u.nodeType==="component"&&u.sourceComponent){let d=t.schematic_component.getWhere({source_component_id:u.sourceComponent.source_component_id});if(d){de(`Moving component ${c} to (${h.x}, ${h.y})`);let _=t.schematic_port.list({schematic_component_id:d.schematic_component_id}),y=t.schematic_text.list({schematic_component_id:d.schematic_component_id}),g={x:h.x-d.center.x,y:h.y-d.center.y};for(let x of _)x.center.x+=g.x,x.center.y+=g.y;for(let x of y)x.position.x+=g.x,x.position.y+=g.y;if(Y4({db:t,schematicComponentId:d.schematic_component_id,deltaX:g.x,deltaY:g.y}),d.center=h,l.ccwRotationDegrees!==0){de(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let x=l.ccwRotationDegrees*Math.PI/180,w=Math.cos(x),S=Math.sin(x);for(let T of _){let I=T.center.x-h.x,E=T.center.y-h.y,M=I*w-E*S,k=I*S+E*w;T.center.x=h.x+M,T.center.y=h.y+k;let N=T.facing_direction||"right";T.facing_direction=uH(N,l.ccwRotationDegrees),T.side_of_component=(T.facing_direction==="up"?"top":T.facing_direction==="down"?"bottom":T.facing_direction)||T.side_of_component}for(let T of y){let I=T.position.x-h.x,E=T.position.y-h.y,M=I*w-E*S,k=I*S+E*w;T.position.x=h.x+M,T.position.y=h.y+k}if(d.symbol_name){let T=d.symbol_name.match(/_(right|left|up|down)$/);T&&(d.symbol_name=d.symbol_name.replace(T[0],`_${uH(T[1],l.ccwRotationDegrees)}`))}}}}else if(u.nodeType==="group"&&u.sourceGroup){let d=t.schematic_group?.getWhere?.({source_group_id:u.sourceGroup.source_group_id});if(d){de(`Moving group ${c} to (${h.x}, ${h.y}) from (${d.center?.x}, ${d.center?.y})`);let _=t.schematic_component.list({schematic_group_id:d.schematic_group_id});de(`Group ${c} has ${_.length} components to move`);let y=d.center||{x:0,y:0},g={x:h.x-y.x,y:h.y-y.y};de(`Position delta for group ${c}: (${g.x}, ${g.y})`);for(let x of _)if(x.center){let w={...x.center};x.center.x+=g.x,x.center.y+=g.y,de(`Moved component ${x.source_component_id} from (${w.x}, ${w.y}) to (${x.center.x}, ${x.center.y})`);let S=t.schematic_port.list({schematic_component_id:x.schematic_component_id}),T=t.schematic_text.list({schematic_component_id:x.schematic_component_id});for(let I of S)I.center&&(I.center.x+=g.x,I.center.y+=g.y);for(let I of T)I.position&&(I.position.x+=g.x,I.position.y+=g.y)}d.center=h,de(`Updated group ${c} center to (${h.x}, ${h.y})`)}}}de("Matchpack layout completed successfully")}function $It(e){if(!e.isSubcircuit)return;let{db:t}=e.root,n=e.selectAll("trace"),i=e.selectAll("via"),o=e.selectAll("net"),r=new qp({});r.addConnections(n.map(u=>{let h=t.source_trace.get(u.source_trace_id);return h?[h.source_trace_id,...h.connected_source_port_ids,...h.connected_source_net_ids]:null}).filter(u=>u!==null));let s=t.source_net.list().filter(u=>u.subcircuit_id===e.subcircuit_id);for(let u of s)r.addConnections([[u.source_net_id]]);let{name:a}=e._parsedProps;for(let u of n){if(!u.source_trace_id)continue;let h=r.getNetConnectedToId(u.source_trace_id);h&&(u.subcircuit_connectivity_map_key=`${a??`unnamedsubcircuit${e._renderId}`}_${h}`,t.source_trace.update(u.source_trace_id,{subcircuit_connectivity_map_key:u.subcircuit_connectivity_map_key}))}let c=new Set;for(let u of n){if(!u.source_trace_id)continue;let h=t.source_trace.get(u.source_trace_id);if(h)for(let d of h.connected_source_port_ids)c.add(d)}for(let u of c){let h=r.getNetConnectedToId(u);if(!h)continue;let d=`${a??`unnamedsubcircuit${e._renderId}`}_${h}`;t.source_port.update(u,{subcircuit_connectivity_map_key:d})}let l=new Set;for(let u of n){if(!u.source_trace_id)continue;let h=t.source_trace.get(u.source_trace_id);if(h)for(let d of h.connected_source_net_ids)l.add(d)}for(let u of s)l.add(u.source_net_id);for(let u of l){let h=r.getNetConnectedToId(u);if(!h)continue;let d=`${a??`unnamedsubcircuit${e._renderId}`}_${h}`;t.source_net.update(u,{subcircuit_connectivity_map_key:d});let _=o.find(y=>y.source_net_id===u);_&&(_.subcircuit_connectivity_map_key=d)}for(let u of i){let h=u._getConnectedNetOrTrace();h&&h.subcircuit_connectivity_map_key&&(u.subcircuit_connectivity_map_key=h.subcircuit_connectivity_map_key)}}function jIt(e){let{db:t}=e.root,n=e._parsedProps,i=e.children.filter(E=>{let M=E._parsedProps?.schX!==void 0||E._parsedProps?.schY!==void 0;return E.schematic_component_id&&!M});if(i.length===0)return;let o=0,r=0;for(let E of i){let M=t.schematic_component.get(E.schematic_component_id);M?.size&&(o=Math.max(o,M.size.width),r=Math.max(r,M.size.height))}o===0&&i.length>0&&(o=1),r===0&&i.length>0&&(r=1);let s=n.gridCols,a,c=n.gridGap,l=n.gridRowGap,u=n.gridColumnGap;n.schLayout?.grid&&(s=n.schLayout.grid.cols??s,a=n.schLayout.grid.rows,c=n.schLayout.gridGap??c,l=n.schLayout.gridRowGap??l,u=n.schLayout.gridColumnGap??u);let h,d;s!==void 0&&a!==void 0?(h=s,d=a):s!==void 0?(h=s,d=Math.ceil(i.length/h)):a!==void 0?(d=a,h=Math.ceil(i.length/d)):(h=Math.ceil(Math.sqrt(i.length)),d=Math.ceil(i.length/h)),h===0&&i.length>0&&(h=1),d===0&&i.length>0&&(d=i.length);let _,y,g=E=>{if(E!==void 0)return typeof E=="number"?E:D.parse(E)};if(l!==void 0||u!==void 0){let E=typeof c=="object"&&c!==null?c.x:c,M=typeof c=="object"&&c!==null?c.y:c;_=g(u??E)??1,y=g(l??M)??1}else if(typeof c=="number")_=c,y=c;else if(typeof c=="string"){let E=D.parse(c);_=E,y=E}else if(typeof c=="object"&&c!==null){let E=c.x,M=c.y;_=typeof E=="number"?E:D.parse(E??"0mm"),y=typeof M=="number"?M:D.parse(M??"0mm")}else _=1,y=1;let x=h*o+Math.max(0,h-1)*_,w=d*r+Math.max(0,d-1)*y,S=e._getGlobalSchematicPositionBeforeLayout(),T=S.x-x/2+o/2,I=S.y+w/2-r/2;for(let E=0;E<i.length;E++){let M=i[E];if(!M.schematic_component_id)continue;let k=Math.floor(E/h),N=E%h;if(k>=d||N>=h){console.warn(`Schematic grid layout: Child ${M.getString()} at index ${E} (row ${k}, col ${N}) exceeds specified grid dimensions (${d}x${h}). Skipping placement.`);continue}let A=T+N*(o+_),R=I-k*(r+y),$=t.schematic_component.get(M.schematic_component_id);if($){let j=$.center,H={x:A,y:R};t.schematic_component.update(M.schematic_component_id,{center:H});let X=H.x-j.x,G=H.y-j.y,tt=t.schematic_port.list({schematic_component_id:M.schematic_component_id});for(let V of tt)t.schematic_port.update(V.schematic_port_id,{center:{x:V.center.x+X,y:V.center.y+G}});let Q=t.schematic_text.list({schematic_component_id:M.schematic_component_id});for(let V of Q)t.schematic_text.update(V.schematic_text_id,{position:{x:V.position.x+X,y:V.position.y+G}});Y4({db:t,schematicComponentId:M.schematic_component_id,deltaX:X,deltaY:G})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:x,height:w,center:S})}var pH=(e,t)=>{let{sourceComponent:n,sourceGroup:i}=t;if(t.nodeType==="component"){let o=e.schematic_component.getWhere({source_component_id:n?.source_component_id});return o?.size?{width:o.size.width,height:o.size.height}:null}if(t.nodeType==="group"){let o=e.schematic_group.getWhere({source_group_id:i?.source_group_id});if(o?.width&&o?.height)return{width:o.width,height:o.height};let r=e.schematic_component.list({schematic_group_id:o?.schematic_group_id}),s=1/0,a=-1/0,c=1/0,l=-1/0;for(let d of r)if(d.center&&d.size){let _=d.size.width/2,y=d.size.height/2;s=Math.min(s,d.center.x-_),a=Math.max(a,d.center.x+_),c=Math.min(c,d.center.y-y),l=Math.max(l,d.center.y+y)}let u=a-s,h=l-c;return{width:u,height:h}}return null},BIt=e=>{let{db:t}=e.root,n=e._parsedProps,i=ih(t.toArray(),{source_group_id:e.source_group_id}),o=n.schJustifyContent??n.justifyContent,r=n.schAlignItems??n.alignItems,s=n.schFlexGap??n.schGap??n.gap,a=n.schFlexDirection??"row",c={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[o??"space-between"],l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[r??"center"];if(!c)throw new Error(`Invalid justifyContent value: "${o}"`);if(!l)throw new Error(`Invalid alignItems value: "${r}"`);let u=0,h=0;typeof s=="object"?(u=s.y??0,h=s.x??0):typeof s=="number"?(u=s,h=s):typeof s=="string"&&(u=D.parse(s),h=D.parse(s));let d,_=n.width??n.schWidth??void 0,y=n.height??n.schHeight??void 0;(_===void 0||y===void 0)&&(d=ub(i.childNodes.map(I=>pH(t,I)).filter(I=>I!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h}),_=d.width,y=d.height);let x=new dx(_,y,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h});for(let I of i.childNodes){let E=pH(t,I);x.addChild({metadata:I,width:E?.width??0,height:E?.height??0,flexBasis:E?a==="row"?E.width:E.height:void 0})}x.build();let w={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let I of x.children)w.minX=Math.min(w.minX,I.position.x),w.minY=Math.min(w.minY,I.position.y),w.maxX=Math.max(w.maxX,I.position.x+I.size.width),w.maxY=Math.max(w.maxY,I.position.y+I.size.height);w.width=w.maxX-w.minX,w.height=w.maxY-w.minY;let S={x:-(w.maxX+w.minX)/2,y:-(w.maxY+w.minY)/2},T=t.toArray();for(let I of x.children){let{sourceComponent:E,sourceGroup:M}=I.metadata;if(E){let k=t.schematic_component.getWhere({source_component_id:E.source_component_id});if(!k)continue;QD(T,k.schematic_component_id,{x:I.position.x+I.size.width/2+S.x,y:I.position.y+I.size.height/2+S.y})}if(M){if(!t.schematic_group.getWhere({source_group_id:M.source_group_id}))continue;e$(T,M.source_group_id,{x:I.position.x+I.size.width/2+S.x,y:I.position.y+I.size.height/2+S.y})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:w.width,height:w.height})},S4=1;function YIt(e){let{db:t}=e.root,n=e._parsedProps,i=XIt(e);if(i.length===0)return;let o=VIt({db:t,pcbChildren:i}),r=HIt(n),s=GIt({props:n,pcbChildren:i,childDimensions:o,gridConfig:r}),a=WIt({pcbChildren:i,childDimensions:o,gridLayout:s,gridConfig:r}),{itemCoordinates:c}=a.layout();ZIt({db:t,group:e,pcbChildren:i,itemCoordinates:c,gridLayout:s}),KIt({db:t,group:e,props:n,gridLayout:s})}function XIt(e){return e.children.filter(t=>t.pcb_component_id||t.pcb_group_id)}function VIt(e){let{db:t,pcbChildren:n}=e,i=0,o=0;for(let r of n){let s=0,a=0;if(r.pcb_group_id){let c=t.pcb_group.get(r.pcb_group_id);s=c?.width??0,a=c?.height??0}else if(r.pcb_component_id){let c=t.pcb_component.get(r.pcb_component_id);s=c?.width??0,a=c?.height??0}i=Math.max(i,s),o=Math.max(o,a)}return{width:i,height:o}}function HIt(e){let t=e.pcbGridCols??e.gridCols??e.pcbLayout?.grid?.cols,n=e.pcbGridRows??e.pcbLayout?.grid?.rows,i=e.pcbGridTemplateColumns,o=e.pcbGridTemplateRows,r=h=>h===void 0?S4:typeof h=="number"?h:D.parse(h),s=e.pcbGridGap??e.gridGap??e.pcbLayout?.gridGap,a=e.pcbGridRowGap??e.gridRowGap??e.pcbLayout?.gridRowGap,c=e.pcbGridColumnGap??e.gridColumnGap??e.pcbLayout?.gridColumnGap,l=S4,u=S4;if(a!==void 0||c!==void 0){let h=typeof s=="object"?s?.x:s,d=typeof s=="object"?s?.y:s;l=r(c??h),u=r(a??d)}else if(typeof s=="object"&&s!==null)l=r(s.x),u=r(s.y);else{let h=r(s);l=h,u=h}return{cols:t,rows:n,gapX:l,gapY:u,templateColumns:i,templateRows:o}}function GIt(e){let{props:t,pcbChildren:n,childDimensions:i,gridConfig:o}=e;return t.pcbGridTemplateColumns||t.pcbGridTemplateRows?UIt({props:t,gridConfig:o,pcbChildren:n,childDimensions:i}):qIt({gridConfig:o,pcbChildren:n,childDimensions:i})}function UIt(e){let{props:t,gridConfig:n,pcbChildren:i,childDimensions:o}=e,r=t.pcbGridTemplateColumns??"",s=t.pcbGridTemplateRows??"",a=d=>{let _=d.match(/repeat\((\d+),/);return _?parseInt(_[1]):Math.ceil(Math.sqrt(i.length))},c=t.pcbGridTemplateColumns?a(r):Math.ceil(Math.sqrt(i.length)),l=t.pcbGridTemplateRows?a(s):Math.ceil(i.length/c),u=c*o.width+Math.max(0,c-1)*n.gapX,h=l*o.height+Math.max(0,l-1)*n.gapY;return{gridTemplateColumns:r,gridTemplateRows:s,containerWidth:u,containerHeight:h}}function qIt(e){let{gridConfig:t,pcbChildren:n,childDimensions:i}=e,o,r;t.cols!==void 0&&t.rows!==void 0?(o=t.cols,r=t.rows):t.cols!==void 0?(o=t.cols,r=Math.ceil(n.length/o)):t.rows!==void 0?(r=t.rows,o=Math.ceil(n.length/r)):(o=Math.ceil(Math.sqrt(n.length)),r=Math.ceil(n.length/o)),o=Math.max(1,o),r=Math.max(1,r);let s=o*i.width+Math.max(0,o-1)*t.gapX,a=r*i.height+Math.max(0,r-1)*t.gapY,c=`repeat(${o}, ${i.width}px)`,l=`repeat(${r}, ${i.height}px)`;return{gridTemplateColumns:c,gridTemplateRows:l,containerWidth:s,containerHeight:a}}function WIt(e){let{pcbChildren:t,childDimensions:n,gridLayout:i,gridConfig:o}=e,r=t.map((s,a)=>({key:s.getString()||`child-${a}`,contentWidth:n.width,contentHeight:n.height}));return new eX({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[o.gapY,o.gapX],children:r})}function ZIt(e){let{db:t,group:n,pcbChildren:i,itemCoordinates:o,gridLayout:r}=e,s=n._getGlobalPcbPositionBeforeLayout(),a=t.toArray();for(let c=0;c<i.length;c++){let l=i[c],u=l.getString()||`child-${c}`,h=o[u];if(!h){console.warn(`PCB grid layout: No coordinates found for child ${u}`);continue}let d=s.x-r.containerWidth/2+h.x+h.width/2,_=s.y+r.containerHeight/2-h.y-h.height/2;if(l.pcb_component_id)cb(a,l.pcb_component_id,{x:d,y:_});else{let y=l;y.pcb_group_id&&y.source_group_id&&lb(a,y.source_group_id,{x:d,y:_})}}}function KIt(e){let{db:t,group:n,props:i,gridLayout:o}=e;if(n.pcb_group_id){let r=n._getGlobalPcbPositionBeforeLayout();t.pcb_group.update(n.pcb_group_id,{width:i.width??o.containerWidth,height:i.height??o.containerHeight,center:r})}}function JIt(e){let t={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof e=="object"&&!e.preset)return{local:!(e.serverUrl||e.serverMode||e.serverCacheEnabled),...t,...e};let n=typeof e=="object"?e.preset:e,i=typeof e=="object"?e:{};switch(typeof n=="string"?n.replace(/_/g,"-"):n){case"auto-local":return{local:!0,groupMode:"subcircuit"};case"sequential-trace":return{local:!0,groupMode:"sequential-trace"};case"subcircuit":return{local:!0,groupMode:"subcircuit"};case"auto-cloud":{let{preset:r,local:s,groupMode:a,...c}=i;return{local:!1,groupMode:"subcircuit",...t,...c}}case"laser-prefab":{let{preset:r,local:s,groupMode:a,...c}=i;return{local:!0,groupMode:"subcircuit",preset:"laser_prefab",...c}}default:return{local:!0,groupMode:"subcircuit"}}}var QIt=(e,t)=>{let n=e.children.filter(h=>h.componentName==="Constraint"&&h._parsedProps.pcb),i=new Map,o={},r=h=>(o[h]!==h&&(o[h]=r(o[h])),o[h]),s=(h,d)=>{let _=r(h),y=r(d);_!==y&&(o[y]=_)},a=h=>{h in o||(o[h]=h)},c=h=>{let d=h.startsWith(".")?h.slice(1):h;return e.children.find(y=>y.name===d)?.pcb_component_id??void 0};for(let h of n){let d=h._parsedProps;if("left"in d&&"right"in d){let _=c(d.left),y=c(d.right);_&&y&&(a(_),a(y),s(_,y))}else if("top"in d&&"bottom"in d){let _=c(d.top),y=c(d.bottom);_&&y&&(a(_),a(y),s(_,y))}else if("for"in d&&Array.isArray(d.for)){let _=d.for.map(y=>c(y)).filter(y=>!!y);for(let y of _)a(y);for(let y=1;y<_.length;y++)s(_[0],_[y])}}for(let h of Object.keys(o)){let d=r(h);i.has(d)||i.set(d,{componentIds:[],constraints:[]}),i.get(d).componentIds.push(h)}for(let h of n){let d=h._parsedProps,_;if("left"in d?_=c(d.left):"top"in d?_=c(d.top):"for"in d&&(_=c(d.for[0])),!_)continue;let y=r(_);i.get(y)?.constraints.push(h)}let l={},u=Object.fromEntries(t.components.map(h=>[h.componentId,h]));for(let[h,d]of i.entries()){if(d.componentIds.length<=1)continue;let _=new Qp,y={},g=(A,R)=>{let $=`${A}_${R}`;return y[$]||(y[$]=new Us($)),y[$]},x=d.componentIds[0];_.addConstraint(new ci(g(x,"x"),Vn.Eq,0,wn.required)),_.addConstraint(new ci(g(x,"y"),Vn.Eq,0,wn.required));for(let A of d.constraints){let R=A._parsedProps;if("xDist"in R){let $=c(R.left),j=c(R.right);$&&j&&_.addConstraint(new ci(new Cn(g(j,"x"),[-1,g($,"x")]),Vn.Eq,R.xDist,wn.required))}else if("yDist"in R){let $=c(R.top),j=c(R.bottom);$&&j&&_.addConstraint(new ci(new Cn(g($,"y"),[-1,g(j,"y")]),Vn.Eq,R.yDist,wn.required))}else if("sameX"in R&&Array.isArray(R.for)){let $=R.for.map(j=>c(j)).filter(j=>!!j);if($.length>1){let j=g($[0],"x");for(let H=1;H<$.length;H++)_.addConstraint(new ci(new Cn(g($[H],"x"),[-1,j]),Vn.Eq,0,wn.required))}}else if("sameY"in R&&Array.isArray(R.for)){let $=R.for.map(j=>c(j)).filter(j=>!!j);if($.length>1){let j=g($[0],"y");for(let H=1;H<$.length;H++)_.addConstraint(new ci(new Cn(g($[H],"y"),[-1,j]),Vn.Eq,0,wn.required))}}}_.updateVariables();let w={};for(let A of d.componentIds)w[A]={x:g(A,"x").value(),y:g(A,"y").value()};let S=1/0,T=1/0,I=-1/0,E=-1/0;for(let A of d.componentIds){let R=u[A],$=w[A];if(R)for(let j of R.pads){let H=$.x+j.offset.x,X=$.y+j.offset.y;S=Math.min(S,H-j.size.x/2),I=Math.max(I,H+j.size.x/2),T=Math.min(T,X-j.size.y/2),E=Math.max(E,X+j.size.y/2)}}let M={x:(S+I)/2,y:(T+E)/2},k=[],N={};for(let A of d.componentIds){let R=u[A],$=w[A];if(R){N[A]={x:$.x-M.x,y:$.y-M.y};for(let j of R.pads)k.push({padId:j.padId,networkId:j.networkId,type:j.type,size:j.size,offset:{x:$.x+j.offset.x-M.x,y:$.y+j.offset.y-M.y}})}}t.components=t.components.filter(A=>!d.componentIds.includes(A.componentId)),t.components.push({componentId:d.componentIds[0],pads:k,availableRotationDegrees:[0]}),d.relativeCenters=N,l[d.componentIds[0]]=d}return l},hH=({db:e,pcbComponentId:t,rotationDegrees:n,layer:i})=>{if(n==null||!e?.cad_component?.list)return;let o=e.cad_component.getWhere({pcb_component_id:t});if(!o)return;let r=i?.toLowerCase?.()==="bottom"?-n:n,s=o.rotation?.z??0,a={...o.rotation??{x:0,y:0,z:0},z:Vl(s+r)};e.cad_component.update(o.cad_component_id,{rotation:a}),o.rotation=a},Nm=(e,t,n)=>{if(t===n)return!0;let i=e.source_group.get(t);return!i||!i.parent_source_group_id?!1:Nm(e,i.parent_source_group_id,n)},tTt=(e,t,n)=>{let{db:i}=e.root;for(let o of t.components){let{center:r,componentId:s,ccwRotationOffset:a,ccwRotationDegrees:c}=o,l=n[s];if(l){let x=c??a??0,w=x*Math.PI/180;for(let S of l.componentIds){let T=l.relativeCenters[S];if(!T)continue;let I={x:T.x*Math.cos(w)-T.y*Math.sin(w),y:T.x*Math.sin(w)+T.y*Math.cos(w)},E=i.pcb_component.get(S);if(!E)continue;let M=E.center,k=Qn(e._computePcbGlobalTransformBeforeLayout(),vn(r.x+I.x,r.y+I.y),Ua(w),vn(-M.x,-M.y)),N=i.toArray().filter(A=>"pcb_component_id"in A&&A.pcb_component_id===S);eh(N,k),hH({db:i,pcbComponentId:S,rotationDegrees:x,layer:E.layer})}continue}let u=i.pcb_component.get(s);if(u){let x=e.source_group_id,S=i.source_component.get(u.source_component_id)?.source_group_id;if(S!==void 0&&!Nm(i,S,x))continue;let T=u.center,I=c??a??0,E=Qn(e._computePcbGlobalTransformBeforeLayout(),vn(r.x,r.y),Ua(I*Math.PI/180),vn(-T.x,-T.y)),M=i.toArray().filter(k=>"pcb_component_id"in k&&k.pcb_component_id===s);eh(M,E),hH({db:i,pcbComponentId:s,rotationDegrees:I,layer:u.layer});continue}let h=i.pcb_group.list().find(x=>x.source_group_id===s);if(!h)continue;let d=h.center,_=c??a??0,y=Qn(e._computePcbGlobalTransformBeforeLayout(),vn(r.x,r.y),Ua(_*Math.PI/180),vn(-d.x,-d.y)),g=i.toArray().filter(x=>{if("source_group_id"in x&&x.source_group_id&&(x.source_group_id===s||Nm(i,x.source_group_id,s)))return!0;if("source_component_id"in x&&x.source_component_id){let w=i.source_component.get(x.source_component_id);if(w?.source_group_id&&(w.source_group_id===s||Nm(i,w.source_group_id,s)))return!0}if("pcb_component_id"in x&&x.pcb_component_id){let w=i.pcb_component.get(x.pcb_component_id);if(w?.source_component_id){let S=i.source_component.get(w.source_component_id);if(S?.source_group_id&&(S.source_group_id===s||Nm(i,S.source_group_id,s)))return!0}}return!1});eh(g,y),i.pcb_group.update(h.pcb_group_id,{center:r})}};function eTt(e){switch(e.shape){case"rect":case"rotated_rect":case"pill":case"rotated_pill":return{width:e.width,height:e.height};case"circle":return{width:e.radius*2,height:e.radius*2};case"polygon":if(!e.points||e.points.length===0)return null;let t=e.points.map(a=>a.x),n=e.points.map(a=>a.y),i=Math.min(...t),o=Math.max(...t),r=Math.min(...n),s=Math.max(...n);return{width:o-i,height:s-r};default:return null}}function nTt(e){switch(e.shape){case"circular_hole_with_rect_pad":case"pill_hole_with_rect_pad":case"rotated_pill_hole_with_rect_pad":return{width:e.rect_pad_width,height:e.rect_pad_height};case"circle":return{width:e.outer_diameter,height:e.outer_diameter};case"oval":return{width:e.outer_width,height:e.outer_height};case"pill":return{width:e.outer_width,height:e.outer_height};default:return null}}var iTt="1mm",dH=(0,qH.default)("Group_doInitialPcbLayoutPack"),oTt=e=>{let{db:t}=e.root,{_parsedProps:n}=e,{packOrderStrategy:i,packPlacementStrategy:o,gap:r,pcbGap:s,pcbPackGap:a}=n,c=a??s??r,l=D.parse(c??iTt),u={},h=new Set,d=I=>{if(I?.pcb_component_id&&I?._parsedProps){let E=I._parsedProps,M=D.parse(E.pcbMarginLeft??E.pcbMarginX??0),k=D.parse(E.pcbMarginRight??E.pcbMarginX??0),N=D.parse(E.pcbMarginTop??E.pcbMarginY??0),A=D.parse(E.pcbMarginBottom??E.pcbMarginY??0);(M||k||N||A)&&(u[I.pcb_component_id]={left:M,right:k,top:N,bottom:A})}I?.children&&I.children.forEach(d)};d(e);let _=new Set;for(let I of e.children){let E=I;E._isNormalComponent&&E.isRelativelyPositioned?.()&&(E.pcb_component_id&&h.add(E.pcb_component_id),E.pcb_group_id&&_.add(E.pcb_group_id))}let y=t.toArray().filter(I=>I.type==="pcb_component"?!h.has(I.pcb_component_id):I.type==="pcb_group"?!_.has(I.pcb_group_id):!0),g=[];for(let I of h){let E=t.toArray().find(R=>R.type==="pcb_component"&&R.pcb_component_id===I);if(!E)continue;let M=E.center.x,k=E.center.y,N=t.toArray().filter(R=>R.type==="pcb_smtpad"&&R.pcb_component_id===I);for(let R of N){let $=eTt(R);if(!$||$.width===0||$.height===0)continue;let j,H;if(R.shape==="polygon"){let X=R.points.map(tt=>tt.x),G=R.points.map(tt=>tt.y);j=M+(Math.min(...X)+Math.max(...X))/2,H=k+(Math.min(...G)+Math.max(...G))/2}else j=M+R.x,H=k+R.y;g.push({obstacleId:R.pcb_smtpad_id,absoluteCenter:{x:j,y:H},width:$.width,height:$.height})}let A=t.toArray().filter(R=>R.type==="pcb_plated_hole"&&R.pcb_component_id===I);for(let R of A){let $=nTt(R);if(!$||$.width===0||$.height===0)continue;let j=M+R.x,H=k+R.y;g.push({obstacleId:R.pcb_plated_hole_id,absoluteCenter:{x:j,y:H},width:$.width,height:$.height})}}let x;if(n.width!==void 0&&n.height!==void 0){let I=D.parse(n.width),E=D.parse(n.height);x={minX:-I/2,maxX:I/2,minY:-E/2,maxY:E/2}}let w={...VY(XY(y,{source_group_id:e.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:u})),orderStrategy:i??"largest_to_smallest",placementStrategy:o??"minimum_sum_squared_distance_to_network",minGap:l,obstacles:g,bounds:x},S=QIt(e,w);dH.enabled&&(e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${e.name}`,content:JSON.stringify(t.toArray())}),e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${e.name}`,content:w}));let T=ux(w);if(dH.enabled){let I=kM(T);I.title=`packOutput-${e.name}`,global.debugGraphics?.push(I)}tTt(e,T,S)},rTt=e=>{let{db:t}=e.root,{_parsedProps:n}=e,i=e.children.filter(E=>E.pcb_component_id||E.pcb_group_id);if(i.some(E=>{let M=E._parsedProps;return M?.pcbX!==void 0||M?.pcbY!==void 0}))return;let r=n.pcbJustifyContent??n.justifyContent,s=n.pcbAlignItems??n.alignItems,a=n.pcbFlexGap??n.pcbGap??n.gap,c=n.pcbFlexDirection??"row",l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[r??"space-between"],u={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[s??"center"];if(!l)throw new Error(`Invalid justifyContent value: "${r}"`);if(!u)throw new Error(`Invalid alignItems value: "${s}"`);let h=0,d=0;typeof a=="object"?(h=a.y??0,d=a.x??0):typeof a=="number"?(h=a,d=a):typeof a=="string"&&(h=D.parse(a),d=D.parse(a));let _,y=n.width??n.pcbWidth??void 0,g=n.height??n.pcbHeight??void 0;(y===void 0||g===void 0)&&(_=ub(i.map(E=>E._getMinimumFlexContainerSize()).filter(E=>E!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d}),y=_.width,g=_.height);let w=new dx(y,g,{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d});for(let E of i){let M=E._getMinimumFlexContainerSize();w.addChild({metadata:E,width:M?.width??0,height:M?.height??0,flexBasis:M?c==="row"?M.width:M.height:void 0})}w.build();let S={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let E of w.children)S.minX=Math.min(S.minX,E.position.x),S.minY=Math.min(S.minY,E.position.y),S.maxX=Math.max(S.maxX,E.position.x+E.size.width),S.maxY=Math.max(S.maxY,E.position.y+E.size.height);S.width=S.maxX-S.minX,S.height=S.maxY-S.minY;let T=e._getGlobalPcbPositionBeforeLayout(),I={x:T.x-(S.maxX+S.minX)/2,y:T.y-(S.maxY+S.minY)/2};for(let E of w.children)E.metadata._repositionOnPcb({x:E.position.x+E.size.width/2+I.x,y:E.position.y+E.size.height/2+I.y});t.pcb_group.update(e.pcb_group_id,{width:S.width,height:S.height,center:T})};function sTt(e){let{db:t}=e.root,n=new Map,i=new Map,o=new Set,s=e.selectAll("trace").filter(R=>R._parsedProps?.schDisplayLabel),a=e.selectAll("group"),c=[e.schematic_group_id,...a.map(R=>R.schematic_group_id)],l=t.schematic_component.list().filter(R=>c.includes(R.schematic_group_id)),u=[],h=new Map,d=new Map;for(let R of l){let $=R.schematic_component_id,j=[],H=t.source_component.getWhere({source_component_id:R.source_component_id}),X=t.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let G of X){let tt=`${H?.name??R.schematic_component_id}.${G.pin_number}`;h.set(tt,G.schematic_port_id),d.set(G.schematic_port_id,tt)}for(let G of X){let tt=d.get(G.schematic_port_id);j.push({pinId:tt,x:G.center.x,y:G.center.y})}u.push({chipId:$,center:R.center,width:R.size.width,height:R.size.height,pins:j})}let _=new Set,y=new Map,g=new Map,x=new Map;for(let R of l){let $=t.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let j of $)_.add(j.schematic_port_id),j.source_port_id&&(y.set(j.schematic_port_id,j.source_port_id),g.set(j.source_port_id,j.schematic_port_id))}let w=new Set;e.subcircuit_id&&w.add(e.subcircuit_id);for(let R of a)R.subcircuit_id&&w.add(R.subcircuit_id);let T=t.source_trace.list().filter(R=>{if(R.subcircuit_id===e.subcircuit_id)return!0;for(let $ of R.connected_source_port_ids)if(g.has($))return!0;return!1}).flatMap(R=>R.connected_source_net_ids);for(let R of T){let $=t.source_net.get(R);$?.subcircuit_id&&w.add($.subcircuit_id)}let I=[],E=new Map;for(let R of t.source_trace.list()){if(R.subcircuit_id&&!w.has(R.subcircuit_id))continue;let $=(R.connected_source_port_ids??[]).map(j=>g.get(j)).filter(j=>!!j&&_.has(j));if($.length>=2){let[j,H]=$.slice(0,2),X=[j,H].sort().join("::");if(!E.has(X)){E.set(X,R.source_trace_id);let G=R.display_name??R.source_trace_id;R.subcircuit_connectivity_map_key&&(o.add(R.subcircuit_connectivity_map_key),x.set(G,R.subcircuit_connectivity_map_key),i.set(R.subcircuit_connectivity_map_key,G)),I.push({pinIds:[j,H].map(tt=>d.get(tt)),netId:G})}}}let M=[];for(let R of t.source_net.list().filter($=>!$.subcircuit_id||w.has($.subcircuit_id)))R.subcircuit_connectivity_map_key&&(o.add(R.subcircuit_connectivity_map_key),n.set(R.subcircuit_connectivity_map_key,R));let k=new Map;for(let[R,$]of y){let j=t.source_port.get($);if(!j?.subcircuit_connectivity_map_key)continue;let H=j.subcircuit_connectivity_map_key;o.add(H),k.has(H)||k.set(H,[]),k.get(H).push(R)}for(let[R,$]of k){let j=n.get(R);if(j&&$.length>=2){let H=String(j.name||j.source_net_id||R);x.set(H,R),i.set(R,H);let G=.1*(.18/.18),tt=Number((String(H).length*G).toFixed(2));M.push({netId:H,pinIds:$.map(Q=>d.get(Q)),netLabelWidth:tt})}}let N=(()=>{let R={},$=new Set(M.map(j=>j.netId));for(let j of t.source_net.list().filter(H=>!H.subcircuit_id||w.has(H.subcircuit_id)))j.name&&$.has(j.name)&&(j.is_ground||j.name.toLowerCase().startsWith("gnd")?R[j.name]=["y-"]:j.is_power||j.name.toLowerCase().startsWith("v")?R[j.name]=["y+"]:R[j.name]=["x-","x+"]);return R})();return{inputProblem:{chips:u,directConnections:I,netConnections:M,availableNetLabelOrientations:N,maxMspPairDistance:e._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:h,pairKeyToSourceTraceId:E,sckToSourceNet:n,sckToUserNetId:i,userNetIdToSck:x,allSourceAndSchematicPortIdsInScope:_,schPortIdToSourcePortId:y,displayLabelTraces:s,allScks:o}}var no=1e-6;function fH(e){let t=Math.abs(e.to.x-e.from.x),n=Math.abs(e.to.y-e.from.y);return t>=n}function Lx(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function mH(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function _H(e,t,n){let i=Lx(e,t);if(i<no)return 0;let o=((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/((t.x-e.x)*(t.x-e.x)+(t.y-e.y)*(t.y-e.y));return Math.max(0,Math.min(1,o))*i}function Ex(e,t,n,i){return e*i-t*n}function aTt(e,t,n,i){let o={x:t.x-e.x,y:t.y-e.y},r={x:i.x-n.x,y:i.y-n.y},s=Ex(o.x,o.y,r.x,r.y),a={x:n.x-e.x,y:n.y-e.y},c=Ex(a.x,a.y,o.x,o.y);if(Math.abs(s)<no&&Math.abs(c)<no||Math.abs(s)<no&&Math.abs(c)>=no)return null;let l=Ex(a.x,a.y,r.x,r.y)/s,u=Ex(a.x,a.y,o.x,o.y)/s;return l<-no||l>1+no||u<-no||u>1+no?null:{x:e.x+l*o.x,y:e.y+l*o.y}}function cTt(e,t=no){if(e.length===0)return e;e.sort((o,r)=>o.start-r.start);let n=[],i={...e[0]};for(let o=1;o<e.length;o++){let r=e[o];r.start<=i.end+t?i.end=Math.max(i.end,r.end):(n.push(i),i={...r})}return n.push(i),n}function lTt(e,t,n){let i=Lx(e.from,e.to);if(i<no||t.length===0)return[e];let o=n/2,r=t.map(h=>({start:Math.max(0,h-o),end:Math.min(i,h+o)})).filter(h=>h.end-h.start>no),s=cTt(r),a=[],c=0,l={x:e.to.x-e.from.x,y:e.to.y-e.from.y},u=(h,d,_)=>{if(d-h<=no)return;let y=h/i,g=d/i;a.push({from:mH(e.from,e.to,y),to:mH(e.from,e.to,g),..._?{is_crossing:!0}:{}})};for(let h of s)h.start-c>no&&u(c,h.start,!1),u(h.start,h.end,!0),c=h.end;return i-c>no&&u(c,i,!1),a.length>0?a:[e]}function uTt(e,t={}){let n=t.crossSegmentLength??.075,i=t.tolerance??no,o=new Map,r=c=>`${c.traceIdx}:${c.edgeIdx}`,s=c=>e[c.traceIdx].edges[c.edgeIdx];for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=l.edges[u];for(let d=c;d<e.length;d++){let _=e[d];for(let y=d===c?u+1:0;y<_.edges.length;y++){let g=_.edges[y],x=aTt(h.from,h.to,g.from,g.to);if(!x)continue;let w=Lx(h.from,h.to),S=Lx(g.from,g.to);if(w<i||S<i)continue;let T=_H(h.from,h.to,x),I=_H(g.from,g.to,x),E=T<=i||Math.abs(w-T)<=i||Number.isNaN(T),M=I<=i||Math.abs(S-I)<=i||Number.isNaN(I);if(!E&&!M){let k=fH(h),N=fH(g),A;if(k!==N)A=k;else{let j=Math.abs(h.to.x-h.from.x),H=Math.abs(h.to.y-h.from.y),X=Math.abs(g.to.x-g.from.x),G=Math.abs(g.to.y-g.from.y),tt=j-H,Q=X-G;A=tt===Q?!0:tt>Q}let R=r({traceIdx:A?c:d,edgeIdx:A?u:y}),$=o.get(R)??[];$.push(A?T:I),o.set(R,$)}}}}}let a=e.map(c=>({source_trace_id:c.source_trace_id,edges:[]}));for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=r({traceIdx:c,edgeIdx:u}),d=o.get(h)??[];if(d.length===0){a[c].edges.push(l.edges[u]);continue}let _=Array.from(new Set(d.map(g=>Number(g.toFixed(6))))).sort((g,x)=>g-x),y=lTt(l.edges[u],_,n);a[c].edges.push(...y)}}return a}var fs=1e-6;function Fx(e,t,n=fs){return Math.abs(e-t)<=n}function Gh(e,t,n=fs){return Fx(e.x,t.x,n)&&Fx(e.y,t.y,n)}function yH(e,t,n,i=fs){let o=Math.min(t.x,n.x)-i,r=Math.max(t.x,n.x)+i,s=Math.min(t.y,n.y)-i,a=Math.max(t.y,n.y)+i;return e.x<o||e.x>r||e.y<s||e.y>a?!1:Math.abs((n.x-t.x)*(e.y-t.y)-(n.y-t.y)*(e.x-t.x))<=i}function gH(e,t=fs){let n=new Map;for(let i of e){let o=`${i.x.toFixed(6)},${i.y.toFixed(6)}`;n.has(o)||n.set(o,i)}return Array.from(n.values())}function bH(e){return{x:e.to.x-e.from.x,y:e.to.y-e.from.y}}function w4(e,t,n=fs){let i=bH(e),o=bH(t),r=Math.hypot(i.x,i.y),s=Math.hypot(o.x,o.y);if(r<n||s<n)return!0;let a=i.x*o.y-i.y*o.x;return Math.abs(a)<=n*r*s}function km(e,t,n=fs){return e.edges.filter(i=>Gh(i.from,t,n)||Gh(i.to,t,n))}function xH(e,t,n=fs){for(let i of e.edges){if(Gh(i.from,t,n))return i.from;if(Gh(i.to,t,n))return i.to}return null}function pTt(e,t,n=fs){let i=Gh(e.from,t,n)||Fx(e.from.x,t.x,n)&&Fx(e.from.y,t.y,n)?e.to:e.from,o=i.x-t.x,r=i.y-t.y;return Math.abs(o)<n&&Math.abs(r)<n?null:Math.abs(o)>=Math.abs(r)?o>=0?"right":"left":r>=0?"up":"down"}function $h(e,t,n=fs){let i=km(e,t,n);if(i.length<2)return null;let o=i.map(h=>pTt(h,t,n)),r=o.includes("up"),s=o.includes("down"),a=o.includes("left"),c=o.includes("right"),l=r?"up":s?"down":null,u=c?"right":a?"left":null;return l&&u?`${l}-${u}`:null}function hTt(e,t={}){let n=t.tolerance??fs,i={};for(let r of e)i[r.source_trace_id]=[];let o=e.map(r=>{let s=[];for(let a of r.edges)s.push(a.from,a.to);return gH(s,n)});for(let r=0;r<e.length;r++){let s=e[r],a=o[r];for(let c=r+1;c<e.length;c++){let l=e[c],u=o[c];for(let h of a)for(let d of u)if(Gh(h,d,n)){let _=km(s,h,n),y=km(l,d,n),g=_.some(T=>y.some(I=>!w4(T,I,n))),x=$h(s,h,n),w=$h(l,d,n);g&&!(x!==null&&w!==null&&x===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(d))}for(let h of a)for(let d of l.edges)if(yH(h,d.from,d.to,n)){let y=km(s,h,n).some(T=>!w4(T,d,n)),g=$h(s,h,n),x=xH(l,h,n*1e3),w=x?$h(l,x,n):null;y&&!(g!==null&&w!==null&&g===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(h))}for(let h of u)for(let d of s.edges)if(yH(h,d.from,d.to,n)){let y=km(l,h,n).some(T=>!w4(d,T,n)),g=$h(l,h,n),x=xH(s,h,n*1e3),w=x?$h(s,x,n):null;y&&!(w!==null&&g!==null&&w===g)&&(i[l.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[s.source_trace_id].push(h))}}}for(let r of Object.keys(i))i[r]=gH(i[r],n);return i}var P4=(0,ZH.default)("Group_doInitialSchematicTraceRender");function dTt(e){let{group:t,solver:n,pinIdToSchematicPortId:i,userNetIdToSck:o}=e,{db:r}=t.root,s=n.traceCleanupSolver?.getOutput().traces??n.traceLabelOverlapAvoidanceSolver?.getOutput().traces??n.schematicTraceLinesSolver?.solvedTracePaths,a=[];P4(`Traces inside SchematicTraceSolver output: ${(s??[]).length}`);for(let u of s??[]){let h=u?.tracePath;if(!Array.isArray(h)||h.length<2){P4(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let d=[];for(let g=0;g<h.length-1;g++)d.push({from:{x:h[g].x,y:h[g].y},to:{x:h[g+1].x,y:h[g+1].y}});let _=null,y;if(Array.isArray(u?.pins)&&u.pins.length===2){let g=i.get(u.pins[0]?.pinId),x=i.get(u.pins[1]?.pinId);if(g&&x){for(let w of[g,x])r.schematic_port.get(w)&&r.schematic_port.update(w,{is_connected:!0});y=o.get(String(u.userNetId))}}_||(_=`solver_${u?.mspPairId}`,y=o.get(String(u.userNetId))),a.push({source_trace_id:_,edges:d,subcircuit_connectivity_map_key:y})}P4(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=uTt(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=hTt(c);for(let u of c)r.schematic_trace.insert({source_trace_id:u.source_trace_id,edges:u.edges,junctions:l[u.source_trace_id]??[],subcircuit_connectivity_map_key:a.find(h=>h.source_trace_id===u.source_trace_id)?.subcircuit_connectivity_map_key})}var fTt=e=>{switch(e){case"x+":return"left";case"x-":return"right";case"y+":return"bottom";case"y-":return"top";case"left":return"right";case"top":return"bottom";case"right":return"left";case"bottom":return"top"}},mTt=e=>{for(let n of e){let i=n._getDirectlyConnectedTraces();for(let o of i){let r=o._parsedProps.schDisplayLabel;if(r)return{name:r,wasAssignedDisplayLabel:!0}}}return{name:e.map(n=>n._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},I4=(0,KH.default)("Group_doInitialSchematicTraceRender");function _Tt(e){let{group:t,solver:n,sckToSourceNet:i,allScks:o,allSourceAndSchematicPortIdsInScope:r,schPortIdToSourcePortId:s,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=e,{db:h}=t.root,d=n.netLabelPlacementSolver?.netLabelPlacements??n.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],_=n.mspConnectionPairSolver.globalConnMap;for(let y of d){I4(`processing placement: ${y.netId}`);let g=_.getIdsConnectedToNet(y.globalConnNetId).find(R=>a.get(R)),x=a.get(g),w=y.anchorPoint,S=y.orientation,T=fTt(S),I=x?i.get(x):void 0,E=y.pinIds.map(R=>c.get(R));if(E.some(R=>l.has(R))){I4(`skipping net label placement for "${y.netId}" REASON:schematic port has pre-existing net label`);continue}if(I){let R=I.name,$=Ic({anchor_position:w,anchor_side:T,text:R});h.schematic_net_label.insert({text:R,anchor_position:w,center:$,anchor_side:T,...I?.source_net_id?{source_net_id:I.source_net_id}:{}});continue}let M=t.selectAll("port").filter(R=>R._getSubcircuitConnectivityKey()===x),{name:k,wasAssignedDisplayLabel:N}=mTt(M);if(!N&&E.some(R=>u.has(R))){I4(`skipping net label placement for "${y.netId}" REASON:schematic port has routed traces and no display label`);continue}let A=Ic({anchor_position:w,anchor_side:T,text:k});h.schematic_net_label.insert({text:k,anchor_position:w,center:A,anchor_side:T})}}var yTt=({allSourceAndSchematicPortIdsInScope:e,group:t,schPortIdToSourcePortId:n,sckToSourceNet:i,pinIdToSchematicPortId:o,schematicPortIdsWithPreExistingNetLabels:r})=>{let{db:s}=t.root;for(let a of Array.from(e)){let c=s.schematic_port.get(a);if(!c||c.is_connected)continue;let l=n.get(a);if(!l)continue;let h=s.source_port.get(l)?.subcircuit_connectivity_map_key;if(!h)continue;let d=i.get(h);if(!d||s.schematic_net_label.list().some(w=>Math.abs(w.anchor_position.x-c.center.x)<.1&&Math.abs(w.anchor_position.y-c.center.y)<.1?d.source_net_id&&w.source_net_id?w.source_net_id===d.source_net_id:w.text===(d.name||h):!1))continue;let y=d.name||d.source_net_id||h,g=Lm(c.facing_direction||"right")||"right",x=Ic({anchor_position:c.center,anchor_side:g,text:y});s.schematic_net_label.insert({text:y,anchor_position:c.center,center:x,anchor_side:g,...d.source_net_id?{source_net_id:d.source_net_id}:{}})}},gTt=e=>{let t=new Set,n=e.selectAll("netlabel");for(let i of n){let o=i._getConnectedPorts();for(let r of o)r.schematic_port_id&&t.add(r.schematic_port_id)}return t},bTt=({solver:e,pinIdToSchematicPortId:t})=>{let n=e.schematicTraceLinesSolver.solvedTracePaths,i=new Set;for(let o of n)for(let r of o.pinIds){let s=t.get(r);s&&i.add(s)}return i},xTt=(0,WH.default)("Group_doInitialSchematicTraceRender"),vTt=e=>{if(!e.root?._featureMspSchematicTraceRouting||!e.isSubcircuit||e.root?.schematicDisabled)return;let{inputProblem:t,pinIdToSchematicPortId:n,pairKeyToSourceTraceId:i,sckToSourceNet:o,allSourceAndSchematicPortIdsInScope:r,schPortIdToSourcePortId:s,displayLabelTraces:a,allScks:c,userNetIdToSck:l}=sTt(e),u=gTt(e);xTt.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(t,null,2)});let h=new bX(t);h.solve();let d=bTt({solver:h,pinIdToSchematicPortId:n});dTt({group:e,solver:h,pinIdToSchematicPortId:n,userNetIdToSck:l}),_Tt({group:e,solver:h,sckToSourceNet:o,allSourceAndSchematicPortIdsInScope:r,schPortIdToSourcePortId:s,pinIdToSchematicPortId:n,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:d}),yTt({group:e,allSourceAndSchematicPortIdsInScope:r,schPortIdToSourcePortId:s,sckToSourceNet:o,pinIdToSchematicPortId:n,schematicPortIdsWithPreExistingNetLabels:u})},STt=()=>({async simulate(e){let t="spice-experiment-1",{circuit:n,tran:i}=SX(e);return{simulationResultCircuitJson:wX(i,n,t)}}}),sa=(0,JH.default)("tscircuit:core:Group_doInitialSimulationSpiceEngineRender");function wTt(e){if(!e.isSubcircuit)return;let{root:t}=e;if(!t)return;let n=e.selectAll("analogsimulation");if(n.length===0)return;let i={...t.platform?.spiceEngineMap};i.spicey||(i.spicey=STt());let o=t.db.toArray(),r;try{r=vX(o).toSpiceString(),sa(`Generated SPICE string:
250
250
  ${r}`)}catch(s){sa(`Failed to convert circuit JSON to SPICE: ${s}`);return}for(let s of n){let a=s._parsedProps.spiceEngine??"spicey",c=i[a];if(!c)throw new Error(`SPICE engine "${a}" not found in platform config. Available engines: ${JSON.stringify(Object.keys(i).filter(u=>u!=="spicey"))}`);let l=`spice-simulation-${a}-${s.source_component_id}`;sa(`Queueing simulation for spice engine: ${a} (id: ${l})`),e._queueAsyncEffect(l,async()=>{try{sa(`Running simulation with engine: ${a}`);let u=await c.simulate(r);sa(`Simulation completed, received ${u.simulationResultCircuitJson.length} elements`);let h=t.db.simulation_experiment.list()[0];if(!h){sa("No simulation experiment found, skipping result insertion");return}for(let d of u.simulationResultCircuitJson){d.type==="simulation_transient_voltage_graph"&&(d.simulation_experiment_id=h.simulation_experiment_id);let _=d.type;_&&t.db[_]?(t.db[_].insert(d),sa(`Inserted ${_} into database`)):(sa(`Warning: Unknown element type ${_}, adding to raw db`),t.db._addElement(d))}e._markDirty("SimulationSpiceEngineRender")}catch(u){sa(`Simulation failed for engine ${a}: ${u}`);let h=t.db.simulation_experiment.list()[0];t.db.simulation_unknown_experiment_error.insert({simulation_experiment_id:h?.simulation_experiment_id,error_type:"simulation_unknown_experiment_error",message:u instanceof Error?u.message:String(u)})}})}}function PTt(e){if(e.root?.pcbDisabled||!e.pcb_group_id)return;let t=e._parsedProps?.pcbPositionAnchor;if(!t)return;let n=e._getGlobalPcbPositionBeforeLayout(),{pcbX:i,pcbY:o}=e._parsedProps;if(i===void 0&&o===void 0)return;let{db:r}=e.root,s=r.pcb_group.get(e.pcb_group_id);if(!s)return;let a=s.width,c=s.height,{center:l}=s;if(s.outline&&s.outline.length>0){let g=ns(s.outline);g&&(a=g.maxX-g.minX,c=g.maxY-g.minY)}if(!a||!c)return;let u={left:l.x-a/2,right:l.x+a/2,top:l.y+c/2,bottom:l.y-c/2},h={...l},d=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(t))switch(t){case"center":d=h;break;case"top_left":d={x:u.left,y:u.top};break;case"top_center":d={x:h.x,y:u.top};break;case"top_right":d={x:u.right,y:u.top};break;case"center_left":d={x:u.left,y:h.y};break;case"center_right":d={x:u.right,y:h.y};break;case"bottom_left":d={x:u.left,y:u.bottom};break;case"bottom_center":d={x:h.x,y:u.bottom};break;case"bottom_right":d={x:u.right,y:u.bottom};break}if(!d)return;let y={...h};n.x!==void 0&&(y.x+=n.x-d.x),n.y!==void 0&&(y.y+=n.y-d.y),(Math.abs(y.x-h.x)>1e-6||Math.abs(y.y-h.y)>1e-6)&&(e._repositionOnPcb(y),r.pcb_group.update(e.pcb_group_id,{center:y})),r.pcb_group.update(e.pcb_group_id,{anchor_position:n,anchor_alignment:t})}var Tc=class extends On{constructor(){super(...arguments);P(this,"pcb_group_id",null);P(this,"schematic_group_id",null);P(this,"subcircuit_id",null);P(this,"_hasStartedAsyncAutorouting",!1);P(this,"_asyncAutoroutingResult",null);P(this,"unnamedElementCounter",{})}get config(){return{zodProps:mz,componentName:"Group"}}doInitialSourceGroupRender(){let{db:t}=this.root,n=typeof this._parsedProps.name=="string"&&this._parsedProps.name.length>0,i=t.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit,was_automatically_named:!n});this.source_group_id=i.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${i.source_group_id}`,t.source_group.update(i.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:t}=this.root;for(let n of this.children)t.source_component.update(n.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:t}=this.root,n=this.parent?.getGroup?.();if(n?.source_group_id&&t.source_group.update(this.source_group_id,{parent_source_group_id:n.source_group_id}),!this.isSubcircuit)return;let i=this.parent?.getSubcircuit?.()?.subcircuit_id;i&&t.source_group.update(this.source_group_id,{parent_subcircuit_id:i})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n,o=i.outline&&i.outline.length>0,r=o?i.outline.map(a=>({x:Y.parse(a.x),y:Y.parse(a.y)})):void 0,s=t.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),...o?{outline:r}:{width:0,height:0},pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:n.autorouter?{trace_clearance:n.autorouter.traceClearance}:void 0});this.pcb_group_id=s.pcb_group_id;for(let a of this.children)t.pcb_component.update(a.pcb_component_id,{pcb_group_id:s.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this._parsedProps,i=n.outline&&n.outline.length>0;if(this.pcb_group_id){let o=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0;if(i){let h=n.outline.map(x=>({x:Y.parse(x.x),y:Y.parse(x.y)})),d=ns(h);if(!d)return;let _=(d.minX+d.maxX)/2,y=(d.minY+d.maxY)/2,g=o?t.pcb_group.get(this.pcb_group_id)?.center??{x:_,y}:{x:_,y};t.pcb_group.update(this.pcb_group_id,{center:g});return}let r=$x(this.children),s=r.width,a=r.height,c=(r.minX+r.maxX)/2,l=(r.minY+r.maxY)/2;if(this.isSubcircuit){let{padLeft:h,padRight:d,padTop:_,padBottom:y}=this._resolvePcbPadding();s+=h+d,a+=_+y,c+=(d-h)/2,l+=(_-y)/2}let u=o?t.pcb_group.get(this.pcb_group_id)?.center??{x:c,y:l}:{x:c,y:l};t.pcb_group.update(this.pcb_group_id,{width:Number(n.width??s),height:Number(n.height??a),center:u})}}getNextAvailableName(t){var n,i;return(n=this.unnamedElementCounter)[i=t.lowercaseComponentName]??(n[i]=1),`unnamed_${t.lowercaseComponentName}${this.unnamedElementCounter[t.lowercaseComponentName]++}`}_resolvePcbPadding(){let t=this._parsedProps,n=t.pcbLayout,i=h=>{let d=n?.[h],_=t[h];if(typeof d=="number")return d;if(typeof _=="number")return _},o=i("padding")??0,r=i("paddingX"),s=i("paddingY"),a=i("paddingLeft")??r??o,c=i("paddingRight")??r??o,l=i("paddingTop")??s??o,u=i("paddingBottom")??s??o;return{padLeft:a,padRight:c,padTop:l,padBottom:u}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:t}=this,{db:n}=this.root,i=t;if(!this.isSubcircuit)return;let o=i.manualEdits?.manual_trace_hints;if(o)for(let r of o)this.add(new B4({for:r.pcb_port_selector,offsets:r.offsets}))}doInitialSourceAddConnectivityMapKey(){$It(this)}_areChildSubcircuitsRouted(){let t=this.selectAll("group").filter(n=>n.isSubcircuit);for(let n of t)if(n._shouldRouteAsync()&&!n._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let t=this._getAutorouterConfig();return t.groupMode==="sequential-trace"?!1:!!(t.local&&t.groupMode==="subcircuit"||!t.local)}_hasTracesToRoute(){let t=(0,jh.default)("tscircuit:core:_hasTracesToRoute"),n=this.selectAll("trace");return t(`[${this.getString()}] has ${n.length} traces to route`),n.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:t}=this.root,n=(0,jh.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),i=this._parsedProps,o=this._getAutorouterConfig(),r=o.serverUrl,s=o.serverMode,a=(u,h)=>(n("fetching",u),h.headers&&(h.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(u,h)),c=this.root.db.toArray().filter(u=>u.type.startsWith("source_")||u.type.startsWith("pcb_"));if(s==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:h}=await a(`${r}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:R4({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(d=>d.json());this._asyncAutoroutingResult=h,this._markDirty("PcbTraceRender");return}let{autorouting_result:u}=await a(`${r}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:c,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());this._asyncAutoroutingResult=u,this._markDirty("PcbTraceRender");return}let{autorouting_job:l}=await a(`${r}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:c,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:o.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(u=>u.json());for(;;){let{autorouting_job:u}=await a(`${r}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());if(u.is_finished){let{autorouting_job_output:h}=await a(`${r}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(d=>d.json());this._asyncAutoroutingResult={output_pcb_traces:h.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(u.has_error){let h=new Em(`Autorouting job failed: ${JSON.stringify(u.error)}`);throw t.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,error_type:"pcb_autorouting_error",message:h.message}),h}await new Promise(h=>setTimeout(h,100))}}async _runLocalAutorouting(){let{db:t}=this.root,n=this._parsedProps,i=(0,jh.default)("tscircuit:core:_runLocalAutorouting");i(`[${this.getString()}] starting local autorouting`);let o=this._getAutorouterConfig(),r=this._isLaserPrefabAutorouter(o),{simpleRouteJson:s}=R4({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(i.enabled&&global.debugOutputArray?.push({name:`simpleroutejson-${this.props.name}.json`,obj:s}),i.enabled){let l=zf(s);l.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(l)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:s});let a;o.algorithmFn?a=await o.algorithmFn(s):a=new NIt(s,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity,useAssignableViaSolver:r});let c=new Promise((l,u)=>{a.on("complete",h=>{i(`[${this.getString()}] local autorouting complete`),l(h.traces)}),a.on("error",h=>{i(`[${this.getString()}] local autorouting error: ${h.error.message}`),u(h.error)})});a.on("progress",l=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...l})}),a.start();try{let l=await c;this._asyncAutoroutingResult={output_pcb_traces:l},this._markDirty("PcbTraceRender")}catch(l){let{db:u}=this.root;throw u.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:l instanceof Error?l.message:String(l)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:l instanceof Error?l.message:String(l)},simpleRouteJson:s}),l}finally{a.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let t=(0,jh.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){t(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}t(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){vTt(this)}updatePcbTraceRender(){let t=(0,jh.default)("tscircuit:core:updatePcbTraceRender");if(t(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(t(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:n}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){t(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){t(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:t}=this.root,{traces:n}=this._asyncAutoroutingResult.output_simple_route_json;if(n)for(let i of n){let o=t.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:t}=this._asyncAutoroutingResult;if(!t)return;let{db:n}=this.root;for(let i of t)if(i.type==="pcb_trace"){if(i.subcircuit_id=this.subcircuit_id,i.connection_name){let o=i.connection_name;i.source_trace_id=o}n.pcb_trace.insert(i)}for(let i of t)if(i.type!=="pcb_via"&&i.type==="pcb_trace")for(let o of i.route)o.route_type==="via"&&n.pcb_via.insert({pcb_trace_id:i.pcb_trace_id,x:o.x,y:o.y,hole_diameter:.3,outer_diameter:.6,layers:[o.from_layer,o.to_layer],from_layer:o.from_layer,to_layer:o.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=i.schematic_group_id;for(let o of this.children)o.schematic_component_id&&t.schematic_component.update(o.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){let t=this._parsedProps;if(t.schLayout?.layoutMode==="none"||t.schLayout?.layoutMode==="relative")return"relative";if(t.schLayout?.matchAdapt)return"match-adapt";if(t.schLayout?.flex)return"flex";if(t.schLayout?.grid)return"grid";if(t.schMatchAdapt)return"match-adapt";if(t.schFlex)return"flex";if(t.schGrid)return"grid";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";if(t.relative||t.schRelative)return"relative";let n=this.children.some(o=>{let r=o._parsedProps;return r?.schX!==void 0||r?.schY!==void 0}),i=(t.manualEdits?.schematic_placements?.length??0)>0;return!n&&!i?"match-adapt":"relative"}doInitialSchematicLayout(){let t=this._getSchematicLayoutMode();t==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),t==="grid"&&this._doInitialSchematicLayoutGrid(),t==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){FIt(this)}_doInitialSchematicLayoutMatchpack(){DIt(this)}_doInitialSchematicLayoutGrid(){jIt(this)}_doInitialSchematicLayoutFlex(){BIt(this)}_getPcbLayoutMode(){let t=this._parsedProps;if(t.pcbRelative)return"none";if(t.pcbLayout?.matchAdapt)return"match-adapt";if(t.pcbLayout?.flex)return"flex";if(t.pcbLayout?.grid)return"grid";if(t.pcbLayout?.pack)return"pack";if(t.pcbFlex)return"flex";if(t.pcbGrid)return"grid";if(t.pcbPack||t.pack)return"pack";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";let n=t.pcbX!==void 0||t.pcbY!==void 0,i=(t.manualEdits?.pcb_placements?.length??0)>0,o=this.children.reduce((r,s)=>{if(!s.pcb_component_id&&!s.pcb_group_id)return r;let a=s._parsedProps,c=a?.pcbX!==void 0||a?.pcbY!==void 0;return r+(c?0:1)},0);return!n&&!i&&o>1?"pack":"none"}doInitialPcbLayout(){let t=this._getPcbLayoutMode();t==="grid"?this._doInitialPcbLayoutGrid():t==="pack"?this._doInitialPcbLayoutPack():t==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){YIt(this)}_doInitialPcbLayoutPack(){oTt(this)}_doInitialPcbLayoutFlex(){rTt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._parsedProps;if(!n.border)return;let i=typeof n.schWidth=="number"?n.schWidth:void 0,o=typeof n.schHeight=="number"?n.schHeight:void 0,r=typeof n.schPadding=="number"?n.schPadding:0,s=typeof n.schPaddingLeft=="number"?n.schPaddingLeft:r,a=typeof n.schPaddingRight=="number"?n.schPaddingRight:r,c=typeof n.schPaddingTop=="number"?n.schPaddingTop:r,l=typeof n.schPaddingBottom=="number"?n.schPaddingBottom:r,u=this.schematic_group_id?t.schematic_group.get(this.schematic_group_id):null;if(u&&(i===void 0&&typeof u.width=="number"&&(i=u.width),o===void 0&&typeof u.height=="number"&&(o=u.height)),i===void 0||o===void 0)return;let h=u?.center??this._getGlobalSchematicPositionBeforeLayout(),d=h.x-i/2-s,_=h.y-o/2-l,y=i+s+a,g=o+c+l;t.schematic_box.insert({width:y,height:g,x:d,y:_,is_dashed:n.border?.dashed??!1})}_determineSideFromPosition(t,n){if(!t.center||!n.center)return"left";let i=t.center.x-n.center.x,o=t.center.y-n.center.y;return Math.abs(i)>Math.abs(o)?i>0?"right":"left":o>0?"bottom":"top"}_calculateSchematicBounds(t){if(t.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let n=1/0,i=-1/0,o=1/0,r=-1/0;for(let a of t)n=Math.min(n,a.centerX),i=Math.max(i,a.centerX),o=Math.min(o,a.centerY),r=Math.max(r,a.centerY);let s=2;return{minX:n-s,maxX:i+s,minY:o-s,maxY:r+s}}_getAutorouterConfig(){let t=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return JIt(t)}_isLaserPrefabAutorouter(t=this._getAutorouterConfig()){let n=this.props.autorouter,i=o=>o?.replace(/-/g,"_")??o;return t.preset==="laser_prefab"?!0:typeof n=="string"?i(n)==="laser_prefab":typeof n=="object"&&n?i(n.preset)==="laser_prefab":!1}_getSubcircuitLayerCount(){let t=this.getInheritedProperty("layers");return typeof t=="number"?t:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(this.isSubcircuit){let n=new Map;for(let i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){let o=n.get(i._parsedProps.name)||[];o.push(i),n.set(i._parsedProps.name,o)}for(let[i,o]of n.entries())o.length>1&&t.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:o.map(r=>r.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:t}=this.root,n=t;for(let i of n.schematic_net_label.list()){let o=n.source_net.get(i.source_net_id),r=i.text||o?.name||"";if(i.anchor_side==="top"&&/^gnd/i.test(r)){n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_down"});continue}i.anchor_side==="bottom"&&/^v/i.test(r)&&n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_up"})}}doInitialSimulationSpiceEngineRender(){wTt(this)}doInitialPcbComponentAnchorAlignment(){PTt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(t){return super._repositionOnPcb(t)}},ITt=.01,vH=(e,t,n)=>{let i=e/2,o=t/2,r=Math.min(n,i,o);if(r<ITt)return[{x:-i,y:-o},{x:i,y:-o},{x:i,y:o},{x:-i,y:o}];let a=Math.max(1,Math.ceil(Math.PI/2*r/.1)),c=Math.PI/2/a,l=[];l.push({x:-i+r,y:-o}),l.push({x:i-r,y:-o});for(let u=1;u<=a;u++){let h=-Math.PI/2+u*c;l.push({x:i-r+r*Math.cos(h),y:-o+r+r*Math.sin(h)})}l.push({x:i,y:o-r});for(let u=1;u<=a;u++){let h=0+u*c;l.push({x:i-r+r*Math.cos(h),y:o-r+r*Math.sin(h)})}l.push({x:-i+r,y:o});for(let u=1;u<=a;u++){let h=Math.PI/2+u*c;l.push({x:-i+r+r*Math.cos(h),y:o-r+r*Math.sin(h)})}l.push({x:-i,y:-o+r});for(let u=1;u<=a;u++){let h=Math.PI+u*c;l.push({x:-i+r+r*Math.cos(h),y:-o+r+r*Math.sin(h)})}return l},QH=class extends Tc{constructor(){super(...arguments);P(this,"pcb_board_id",null);P(this,"source_board_id",null);P(this,"_drcChecksComplete",!1);P(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:LI}}get boardThickness(){let{_parsedProps:t}=this;return t.thickness??1.4}get allLayers(){return(this._parsedProps.layers??2)===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db:t}=this.root,{_parsedProps:n}=this;if(n.width&&n.height||n.outline)return;let i=1/0,o=1/0,r=-1/0,s=-1/0,a=HH(t,this.subcircuit_id),c=new Set([this.subcircuit_id,...a]),l=t.pcb_component.list().filter(E=>E.subcircuit_id&&c.has(E.subcircuit_id)),u=t.pcb_group.list().filter(E=>E.subcircuit_id&&c.has(E.subcircuit_id)),h=!1,d=(E,M,k)=>{M===0||k===0||(h=!0,i=Math.min(i,E.x-M/2),o=Math.min(o,E.y-k/2),r=Math.max(r,E.x+M/2),s=Math.max(s,E.y+k/2))};for(let E of l)d(E.center,E.width,E.height);for(let E of u){let M=E.width??0,k=E.height??0;if(E.outline&&E.outline.length>0){let N=ns(E.outline);N&&(M=N.maxX-N.minX,k=N.maxY-N.minY)}d(E.center,M,k)}if(n.boardAnchorPosition){let{x:E,y:M}=n.boardAnchorPosition;i=Math.min(i,E),o=Math.min(o,M),r=Math.max(r,E),s=Math.max(s,M)}let _=2,y=h?r-i+_*2:0,g=h?s-o+_*2:0,x={x:h?(i+r)/2+(n.outlineOffsetX??0):n.outlineOffsetX??0,y:h?(o+s)/2+(n.outlineOffsetY??0):n.outlineOffsetY??0},w=n.width??y,S=n.height??g,T=n.outline;!T&&n.borderRadius!=null&&w>0&&S>0&&(T=vH(w,S,n.borderRadius));let I={width:w,height:S,center:x};T&&(I.outline=T.map(E=>({x:E.x+(n.outlineOffsetX??0),y:E.y+(n.outlineOffsetY??0)}))),t.pcb_board.update(this.pcb_board_id,I)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let t=this.root?.platform;if(!t?.printBoardInformationToSilkscreen)return;let n=this.root.db.pcb_board.get(this.pcb_board_id);if(!n)return;let i=[];if(t.projectName&&i.push(t.projectName),t.version&&i.push(`v${t.version}`),t.url&&i.push(t.url),i.length===0)return;let o=i.join(`
251
- `),a={x:n.center.x+n.width/2-.25,y:n.center.y-n.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:o,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:t}=this.root,n=t.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=n.source_board_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.width??0,o=n.height??0,r={x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)},{boardAnchorPosition:s,boardAnchorAlignment:a}=n;if(s&&(r=EIt({boardAnchorPosition:s,boardAnchorAlignment:a??"center",width:i,height:o})),n.outline){let u=n.outline.map(x=>x.x),h=n.outline.map(x=>x.y),d=Math.min(...u),_=Math.max(...u),y=Math.min(...h),g=Math.max(...h);i=_-d,o=g-y,r={x:(d+_)/2+(n.outlineOffsetX??0),y:(y+g)/2+(n.outlineOffsetY??0)}}let c=n.outline;!c&&n.borderRadius!=null&&i>0&&o>0&&(c=vH(i,o,n.borderRadius));let l=t.pcb_board.insert({center:r,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:o,outline:c?.map(u=>({x:u.x+(n.outlineOffsetX??0),y:u.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=l.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return zi()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let n=MX(t.toArray());for(let l of n)t.pcb_trace_error.insert(l);let i=TX(t.toArray());for(let l of i)t.pcb_port_not_connected_error.insert(l);let o=NX(t.toArray());for(let l of o)t.pcb_component_outside_board_error.insert(l);let r=RX(t.toArray());for(let l of r)t.pcb_trace_error.insert(l);let s=AX(t.toArray());for(let l of s)t.pcb_via_clearance_error.insert(l);let a=kX(t.toArray());for(let l of a)t.pcb_via_clearance_error.insert(l);let c=OX(t.toArray());for(let l of c)t.pcb_footprint_overlap_error.insert(l)}_emitRenderLifecycleEvent(t,n){super._emitRenderLifecycleEvent(t,n),n==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},tG=class extends Tc{get config(){return{componentName:"Panel",zodProps:_z}}get isGroup(){return!0}add(e){if(e.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(e)}runRenderCycle(){if(!this.children.some(e=>e.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}},TTt=new Proxy({},{get:(e,t)=>t}),la=TTt,jx="rgba(132, 0, 0)",Bx=.12,eG=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:Tz,sourceFtype:la.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let t=this.props.capacitance,n=typeof t=="string"?t:`${ni(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${ni(this._parsedProps.maxVoltageRating)}V`:n}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new $r({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new $r({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,capacitance:n.capacitance,max_voltage_rating:n.maxVoltageRating,max_decoupling_trace_length:n.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!n.polarized});this.source_component_id=i.source_component_id}},Fm=class extends On{constructor(t){super(t);P(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:Jp,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:n}=this;if(n.externallyConnectedPins){let i=new Set;for(let[o,r]of n.externallyConnectedPins)i.add(o),i.add(r);for(let o of i)if(!this.children.find(s=>s instanceof Ni&&s.isMatchingAnyOf([o]))){let s=o.match(/^pin(\d+)$/);if(s){let a=parseInt(s[1]);this.add(new Ni({pinNumber:a,aliases:[o]}))}else this.add(new Ni({name:o,aliases:[o]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.layer??"top";if(i!=="top"&&i!=="bottom"){let r=this.getSubcircuit(),s=Np.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${i}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:i,subcircuit_id:r.subcircuit_id??void 0});t.pcb_component_invalid_layer_error.insert(s)}let o=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:i==="top"||i==="bottom"?i:"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=o.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[n,i]of t.externallyConnectedPins)this.add(new $r({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:n}=this.props;if(!n)return;let i=null,o=null,r,s=this.selectAll("port");for(let h of s)for(let d of h.getNameAndAliases())if(n[d]){let _=n[d];_.providesPower&&(i=h,r=_.providesVoltage),_.providesGround&&(o=h)}if(!i||!o||r===void 0)return;let a=t.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=t.source_port.get(o.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=t.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=t.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||t.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:o.source_port_id,negative_source_net_id:u.source_net_id,voltage:r})}},nG=class extends Fm{constructor(e){super(e)}get config(){return{...super.config,componentName:"Pinout",zodProps:yz}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}},iG=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"anode",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},n=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"diode",componentName:"Diode",zodProps:Xz,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},oG=class extends On{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:bz,sourceFtype:la.simple_fuse}}_getSchematicSymbolDisplayValue(){let e=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,n=typeof e=="string"?parseFloat(e):e,i=typeof t=="string"?parseFloat(t):t;return`${ni(n)}A / ${ni(i)}V`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,i=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,o=e.source_component.insert({name:this.name,ftype:la.simple_fuse,current_rating_amps:n,voltage_rating_volts:i,display_current_rating:`${ni(n)}A`,display_voltage_rating:`${ni(i)}V`});this.source_component_id=o.source_component_id}},rG=class extends On{constructor(){super(...arguments);P(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:FI,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let o=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),r=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of o)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=r(a.start_pcb_port_id),a.end_pcb_port_id=r(a.end_pcb_port_id))}},sG=class extends On{constructor(){super(...arguments);P(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(t){return this.selectOne(`port.${t}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let t=this.children.filter(n=>n.componentName==="Port").map(n=>n.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,n=t.pinCount;if(t.pinCount==null&&!t.footprint&&(n=2),t.pinCount==null){let r=(t.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),s=r.length>0?Math.max(...r):0,a=t.pinLabels?Object.keys(t.pinLabels).length:0,c=Math.max(s,a);(c===2||c===3)&&(n=c),n==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(n=this.getPortsFromFootprint().length)}let i="";n?i+=`solderjumper${n}`:i="solderjumper";let o=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?o=Array.from(new Set(t.bridgedPins.flat().map(r=>this._getPinNumberFromBridgedPinName(r)).filter(r=>r!==null))).sort((r,s)=>r-s):t.bridged&&n&&(o=Array.from({length:n},(r,s)=>s+1)),o.length>0&&(i+=`_bridged${o.join("")}`),{schematicSymbolName:t.symbolName??i,componentName:"SolderJumper",zodProps:gz,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);n==null&&!this._parsedProps.footprint&&(n=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let o=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),r=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of o)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=r(a.start_pcb_port_id),a.end_pcb_port_id=r(a.end_pcb_port_id))}},aG=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"anode",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},n=this.props.laser?"laser":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"led",componentName:"Led",zodProps:Hz,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){let t=super.getFootprinterString();return t&&this.props.color?`${t}_color(${this.props.color})`:t}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:n.wavelength,color:n.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},cG=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"positive",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:rD,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Ni({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Ni({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},MTt=Dn.extend({voltage:ai.optional(),frequency:Wi.optional(),peakToPeakVoltage:ai.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Be.optional(),dutyCycle:p.number().optional()}),lG=class extends On{constructor(){super(...arguments);P(this,"terminal1",this.portMap.terminal1);P(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:MTt,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.portMap.terminal1,o=this.portMap.terminal2;t.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:o.source_port_id,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle})}},X4=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:vz,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${ni(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new $r({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new $r({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new $r({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new $r({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,resistance:n.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},CTt=["leftedge","rightedge","topedge","bottomedge","center"],uG=class extends xe{get config(){return{componentName:"Constraint",zodProps:Cz}}constructor(e){if(super(e),("xdist"in e||"ydist"in e)&&!("edgeToEdge"in e)&&!("centerToCenter"in e))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in e&&e.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let e=[],t=this.getPrimitiveContainer();function n(i){let o=i.split(" ").pop(),r=CTt.includes(o)?o:void 0,s=r?i.replace(` ${r}`,""):i,a=t.selectOne(s,{pcbPrimitive:!0});a&&e.push({selector:i,component:a,componentSelector:s,edge:r})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},pG=class extends xe{constructor(){super(...arguments);P(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:Wz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for FabricationNoteRect. Must be "top" or "bottom".`);let r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,s=this.getSubcircuit(),a=n.hasStroke??(n.strokeWidth!==void 0&&n.strokeWidth!==null),c=t.pcb_fabrication_note_rect.insert({pcb_component_id:r,layer:o,color:n.color,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,stroke_width:n.strokeWidth??1,is_filled:n.isFilled??!1,has_stroke:a,is_stroke_dashed:n.isStrokeDashed??!1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,corner_radius:n.cornerRadius??void 0});this.fabrication_note_rect_id=c.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},hG=class extends xe{constructor(){super(...arguments);P(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:Zz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this.getSubcircuit(),{_parsedProps:i}=this,o=i.layer??"top";if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenPath. Must be "top" or "bottom".`);let 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:o,color:i.color,route:i.route.map(c=>{let l=Ne(r,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:n?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},dG=class extends xe{get config(){return{componentName:"FabricationNoteText",zodProps:qz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit();e.pcb_fabrication_note_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:t.pcbX??0,y:t.pcbY??0},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:"top",color:t.color,text:t.text??"",pcb_component_id:n.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},fG=class extends xe{constructor(){super(...arguments);P(this,"fabrication_note_dimension_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:Kz}}_resolvePoint(t,n){if(typeof t=="string"){let r=this.getSubcircuit().selectOne(t);return r?r._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${t}"`),Ne(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,o=typeof t.y=="string"?parseFloat(t.y):t.y;return Ne(n,{x:i,y:o})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this._resolvePoint(n.from,i),r=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(n.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for FabricationNoteDimension. Must be "top" or "bottom".`);let u=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,h=n.text??this._formatDistanceText({from:o,to:r,units:n.units??"mm"}),d=t.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:o,to:r,text:h,offset:n.offset,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.fabrication_note_dimension_id=d.pcb_fabrication_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}_formatDistanceText({from:t,to:n,units:i}){let o=n.x-t.x,r=n.y-t.y,s=Math.sqrt(o*o+r*r),a=i==="in"?s/25.4:s,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},mG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_line_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:ID}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),o=this.getGroup(),r=this._computePcbGlobalTransformBeforeLayout(),s=Ne(r,{x:n.x1,y:n.y1}),a=Ne(r,{x:n.x2,y:n.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,x1:s.x,y1:s.y,x2:a.x,y2:a.y,stroke_width:n.strokeWidth??.1,color:n.color,is_dashed:n.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:t}=this;return{width:Math.abs(t.x2-t.x1),height:Math.abs(t.y2-t.y1)}}},_G=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_rect_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:wD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=Ne(i,{x:0,y:0}),r=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,center:o,width:n.width,height:n.height,stroke_width:n.strokeWidth??.1,is_filled:n.isFilled??!1,has_stroke:n.hasStroke??!0,is_stroke_dashed:n.isStrokeDashed??!1,color:n.color,corner_radius:n.cornerRadius??void 0});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.width=="string"?parseFloat(t.width):t.width,i=typeof t.height=="string"?parseFloat(t.height):t.height;return{width:n,height:i}}},yG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_text_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:SD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=Ne(i,{x:0,y:0}),r=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_text.insert({pcb_component_id:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,font:n.font??"tscircuit2024",font_size:n.fontSize??1,text:n.text,anchor_position:o,anchor_alignment:n.anchorAlignment??"center",color:n.color});this.pcb_note_text_id=c.pcb_note_text_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.fontSize=="string"?parseFloat(t.fontSize):t.fontSize??1,i=n*.6;return{width:t.text.length*i,height:n}}},gG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_path_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:PD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this.getSubcircuit(),r=this.getGroup(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=typeof u=="string"?parseFloat(u):u,y=typeof h=="string"?parseFloat(h):h,g=Ne(i,{x:_,y});return{...d,x:g.x,y:g.y}}),c=t.pcb_note_path.insert({pcb_component_id:s,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,route:a,stroke_width:n.strokeWidth??.1,color:n.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:t}=this;if(t.route.length===0)return{width:0,height:0};let n=t.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=t.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),o=Math.min(...n),r=Math.max(...n),s=Math.min(...i),a=Math.max(...i);return{width:r-o,height:a-s}}},bG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_dimension_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:TD}}_resolvePoint(t,n){if(typeof t=="string"){let r=this.getSubcircuit().selectOne(`.${t}`);return r?r._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${t}"`),Ne(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,o=typeof t.y=="string"?parseFloat(t.y):t.y;return Ne(n,{x:i,y:o})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this._resolvePoint(n.from,i),r=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=n.text??this._formatDistanceText({from:o,to:r,units:n.units??"mm"}),u=t.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:o,to:r,text:l,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.pcb_note_dimension_id=u.pcb_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}_formatDistanceText({from:t,to:n,units:i}){let o=n.x-t.x,r=n.y-t.y,s=Math.sqrt(o*o+r*r),a=i==="in"?s/25.4:s,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},xG=(e,t)=>{let{injectionDb:n,normalComponent:i}=t;if(!i)return;let o=Vh({componentName:i.name,componentRotation:"0deg"},n.toArray().filter(r=>"pcb_component_id"in r&&r.pcb_component_id===e.pcb_component_id));i.addAll(o)};function ETt(e,t){let{injectionDb:n,subcircuit:i,groupsMap:o}=t,r=n.pcb_component.getWhere({source_component_id:e.source_component_id}),s=n.cad_component.getWhere({source_component_id:e.source_component_id}),a=new X4({name:e.name,resistance:e.resistance});r&&xG(r,{...t,normalComponent:a}),e.source_group_id&&o?.has(e.source_group_id)?o.get(e.source_group_id).add(a):i.add(a)}function NTt(e,t){let{injectionDb:n,subcircuit:i}=t;if(e.source_component_id!==null)return;let o=n.pcb_port.getWhere({source_port_id:e.source_port_id}),r=new Ni({name:e.name,pinNumber:e.pin_number});i.add(r),r.source_port_id=e.source_port_id;let s=i.root;if(s&&o){let{db:a}=s,c=a.pcb_port.insert({pcb_component_id:void 0,layers:o.layers,subcircuit_id:i.subcircuit_id??void 0,pcb_group_id:i.getGroup()?.pcb_group_id??void 0,x:o.x,y:o.y,source_port_id:e.source_port_id,is_board_pinout:!1});r.pcb_port_id=c.pcb_port_id}}function kTt(e,t){let{subcircuit:n,groupsMap:i}=t,o=new Tc({name:e.name});return o.source_group_id=e.source_group_id,n.add(o),i&&i.set(e.source_group_id,o),o}var ATt=(e,t)=>{if(!e||e.length===0)return;let{injectionDb:n}=t,i=e.map(o=>o.map(r=>{let 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(o=>o.length>0);return i.length>0?i:void 0},RTt=(e,t)=>{let{injectionDb:n,subcircuit:i,groupsMap:o}=t,r=n.pcb_component.getWhere({source_component_id:e.source_component_id}),s=n.schematic_component.getWhere({source_component_id:e.source_component_id}),a=n.cad_component.getWhere({source_component_id:e.source_component_id}),c=ATt(e.internally_connected_source_port_ids,t),l=new Fm({name:e.name,manufacturerPartNumber:e.manufacturer_part_number,supplierPartNumbers:e.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:r?.center?.x,pcbY:r?.center?.y,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds,internallyConnectedPins:c}),u=a?.footprinter_string??"soic8";u&&(Object.assign(l.props,{footprint:u}),Object.assign(l._parsedProps,{footprint:u}),a||l._addChildrenFromStringFootprint?.()),r&&xG(r,{...t,normalComponent:l}),e.source_group_id&&o?.has(e.source_group_id)?o.get(e.source_group_id).add(l):i.add(l)},vG=class extends Tc{constructor(e){super({...e,subcircuit:!0})}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:e,children:t}=this._parsedProps;if(!e)return;let n=Ge(e);if(e&&t?.length>0)throw new Error("Subcircuit cannot have both circuitJson and children");let o={injectionDb:n,subcircuit:this,groupsMap:new Map},r=n.source_group.list();for(let c of r)kTt(c,o);let s=n.source_component.list();for(let c of s)switch(c.ftype){case"simple_resistor":ETt(c,o);break;case"simple_chip":RTt(c,o);break;default:throw new Error(`No inflator implemented for source component ftype: "${c.ftype}"`)}let a=n.source_port.list();for(let c of a)NTt(c,o)}},SG=class extends Tc{constructor(e){super({...e,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let n=e.pcb_group.get(this.pcb_group_id),i=t.paddingLeft??t.padding??0,o=t.paddingRight??t.padding??0,r=t.paddingTop??t.padding??0,s=t.paddingBottom??t.padding??0;e.pcb_group.update(this.pcb_group_id,{width:(n.width??0)+i+o,height:(n.height??0)+r+s,center:{x:n.center.x+(o-i)/2,y:n.center.y+(r-s)/2}})}},wG=class extends xe{constructor(){super(...arguments);P(this,"pcb_breakout_point_id",null);P(this,"matchedPort",null);P(this,"matchedNet",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:tD}}_matchConnection(){let{connection:t}=this._parsedProps,n=this.getSubcircuit();n&&(this.matchedPort=n.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=n.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(o=>o.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(o=>o.connected_source_port_ids.includes(t.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;this._matchConnection();let{pcbX:n=0,pcbY:i=0}=this._parsedProps,o=this.parent?.getGroup(),r=this.getSubcircuit();if(!o||!o.pcb_group_id)return;let s=t.pcb_breakout_point.insert({pcb_group_id:o.pcb_group_id,subcircuit_id:r?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:n,y:i});this.pcb_breakout_point_id=s.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:n=0}=this._parsedProps;return{center:{x:t,y:n},bounds:{left:t,top:n,right:t,bottom:n},width:0,height:0}}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_breakout_point_id&&n.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},PG=class extends xe{constructor(){super(...arguments);P(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:zz}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),o=this._getConnectedPorts();if(o.length===0)return"right";let r=o[0]._getGlobalSchematicPositionBeforeLayout(),s=r.x-i.x,a=r.y-i.y;if(Math.abs(s)>Math.abs(a)){if(s>0)return"right";if(s<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let n=[];for(let i of t){let o=this.getSubcircuit().selectOne(i);o&&n.push(o)}return n}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let n=this._getConnectedPorts();if(n.length>0){let i=n[0]._getGlobalSchematicPositionBeforeLayout(),o=Ne(this.parent?.computeSchematicGlobalTransform?.()??zi(),{x:0,y:0});return vn(i.x-o.x,i.y-o.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),r=n.anchorSide??"right",s=Ic({anchor_position:i,anchor_side:r,text:n.net}),a=t.schematic_net_label.insert({text:n.net,source_net_id:o.source_net_id,anchor_position:i,center:s,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo??t.connection;if(Array.isArray(n))return n;if(typeof n=="string")return[n]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&zx(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let n of t)this.add(new $r({from:n,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._resolveConnectsTo();if(!n||n.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),o=this._getAnchorSide(),s={left:"x-",right:"x+",top:"y+",bottom:"y-"}[o],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of n){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id??""));if(w&&(u=t.schematic_trace.list().some(S=>S.source_trace_id===w.source_trace_id)),u)continue}let h=l._getGlobalSchematicPositionAfterLayout(),d=E4(l.facingDirection??"right")??"x+",_=oc({x:h.x,y:h.y,facingDirection:d},{x:i.x,y:i.y,facingDirection:s});if(!Array.isArray(_)||_.length<2)continue;let y=[];for(let w=0;w<_.length-1;w++)y.push({from:{x:_[w].x,y:_[w].y},to:{x:_[w+1].x,y:_[w+1].y}});let g,x;if(a?.source_net_id&&l.source_port_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id));g=w?.source_trace_id,x=w?.subcircuit_connectivity_map_key||t.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}t.schematic_trace.insert({source_trace_id:g,edges:y,junctions:[],subcircuit_connectivity_map_key:x}),t.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},IG=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_circle_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:xD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenCircle. Must be "top" or "bottom".`);let r=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:o,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},TG=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_rect_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:bD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenRect. Must be "top" or "bottom".`);let r=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_rect.insert({pcb_component_id:s,layer:o,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1,is_filled:n.filled??!1,corner_radius:n.cornerRadius??void 0});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},MG=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_line_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:gD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenLine. Must be "top" or "bottom".`);let r=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_line.insert({pcb_component_id:s,layer:o,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:r?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},CG=class extends xe{constructor(t){super(t);P(this,"pcb_via_id",null);P(this,"matchedPort",null);P(this,"isPcbPrimitive",!0);P(this,"source_manually_placed_via_id",null);P(this,"subcircuit_connectivity_map_key",null);let n=this._getLayers();this._parsedProps.layers=n,this.initPorts()}get config(){return{componentName:"Via",zodProps:Jz}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}_getLayers(){let{fromLayer:t="top",toLayer:n="bottom"}=this._parsedProps;return t===n?[t]:[t,n]}initPorts(){let t=this._parsedProps.layers;for(let i of t){let o=new Ni({name:i,layer:i});o.registerMatch(this),this.add(o)}let n=new Ni({name:"pin1"});n.registerMatch(this),this.add(n)}_getConnectedNetOrTrace(){let t=this._parsedProps.connectsTo;if(!t)return null;let n=this.getSubcircuit(),i=Array.isArray(t)?t:[t];for(let o of i)if(o.startsWith("net.")){let r=n.selectOne(o,{type:"net"});if(r)return r}return null}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),o=this.getSubcircuit(),r=t.pcb_component.insert({center:i,width:n.outerDiameter,height:n.outerDiameter,layer:n.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:o?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=r.pcb_component_id}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getGroup(),o=this.getSubcircuit(),r=t.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:n.net??"",subcircuit_id:o?.subcircuit_id??void 0});this.source_component_id=r.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),o=this.getSubcircuit(),r=t.pcb_via.insert({x:i.x,y:i.y,hole_diameter:n.holeDiameter,outer_diameter:n.outerDiameter,layers:["bottom","top"],from_layer:n.fromLayer||"bottom",to_layer:n.toLayer||"top",subcircuit_id:o?.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:n.netIsAssignable??void 0});this.pcb_via_id=r.pcb_via_id}},EG=class extends xe{constructor(){super(...arguments);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:nD}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;zx(this,[t.connectsTo])}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit().selectOne(n.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${n.connectsTo}" not found for copper pour`);return}let o=this.getSubcircuit(),r=t.toArray().filter(h=>h.type==="source_net"&&h.name===i.name)[0]||"",s=n.clearance??.2,a=DX(t.toArray(),{layer:n.layer,pour_connectivity_key:r.subcircuit_connectivity_map_key||"",pad_margin:n.padMargin??s,trace_margin:n.traceMargin??s,board_edge_margin:n.boardEdgeMargin??s,cutout_margin:n.cutoutMargin??s}),c=new zX(a),{brep_shapes:l}=c.getOutput(),u=n.coveredWithSolderMask??!1;for(let h of l)t.pcb_copper_pour.insert({shape:"brep",layer:n.layer,brep_shape:h,source_net_id:i.source_net_id,subcircuit_id:o?.subcircuit_id??void 0,covered_with_solder_mask:u})})}},NG=class extends On{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:Lz,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:t.capacity,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},kG=class extends On{_getPcbRotationBeforeLayout(){let e=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+e}get config(){return{componentName:"PinHeader",zodProps:Fz,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,o=this._parsedProps.showSilkscreenPinLabels;if(e>0){let r;if(i)!t&&!n?r=`pinrow${e}_p${i}`:r=`pinrow${e}_p${i}_id${t}_od${n}`;else if(!t&&!n)r=`pinrow${e}`;else return null;return o!==!0&&(r+="_nopinlabels"),r}return null}initPorts(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let t=1;t<=e;t++){let n=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[t-1]:this._parsedProps.pinLabels?.[`pin${t}`];if(n){let i=Array.isArray(n)?n[0]:n,o=Array.isArray(n)?n.slice(1):[];this.add(new Ni({pinNumber:t,name:i,aliases:[`pin${t}`,...o]}))}else this.add(new Ni({pinNumber:t,name:`pin${t}`}))}}_getSchematicPortArrangement(){let e=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:n?.leftSide?.direction??"top-to-bottom",pins:n?.leftSide?.pins??Array.from({length:e},(i,o)=>`pin${o+1}`)}}:{rightSide:{direction:n?.rightSide?.direction??"top-to-bottom",pins:n?.rightSide?.pins??Array.from({length:e},(i,o)=>`pin${o+1}`)}}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:t.supplierPartNumbers,pin_count:t.pinCount,gender:t.gender,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function OTt(e){switch(e){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var AG=class extends On{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??OTt(this.props.pinVariant),zodProps:Iz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:n,are_pins_interchangeable:n==="no_ground"||n==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let e=`${ni(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ni(this._parsedProps.loadCapacitance)}F`:e}},RG=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:Yz,sourceFtype:la.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${ni(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({name:this.name,ftype:la.simple_inductor,inductance:n.inductance,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function LTt(e){switch(e){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var OG=class extends On{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??LTt(this.props.pinVariant),zodProps:wz,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${ni(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},LG=class extends On{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:Dz,sourceFtype:la.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let e=ti[this._getSchematicSymbolNameOrThrow()],t=e.ports.find(l=>l.labels.includes("1")),n=e.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),o=i.find(l=>l.props.pinNumber===1),r=i.find(l=>l.props.pinNumber===2),s=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;o.schematicSymbolPortDef=t,(!c||c.length===0)&&(r.schematicSymbolPortDef=n);for(let[l,u]of[[2,r],[3,s],[4,a]]){let h=c?.find(([_,y])=>_===`pin${l}`||y===`pin${l}`);if(!h){u.schematicSymbolPortDef=n;break}(h?.[0]===`pin${l}`?h[1]:h?.[0])!=="pin1"&&(u.schematicSymbolPortDef=n)}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:la.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},FG=class extends On{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:Pz,sourceFtype:"simple_crystal"}}initPorts(){let e=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:e})}_getSchematicSymbolDisplayValue(){let e=`${ni(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ni(this._parsedProps.loadCapacitance)}F`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:t.frequency,load_capacitance:t.loadCapacitance,pin_variant:t.pinVariant||"two_pin",are_pins_interchangeable:(t.pinVariant||"two_pin")==="two_pin"});this.source_component_id=n.source_component_id}},zG=class extends On{constructor(){super(...arguments);P(this,"emitter",this.portMap.pin1);P(this,"collector",this.portMap.pin2);P(this,"base",this.portMap.pin3)}get config(){let t=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??t,zodProps:jz,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},DG=class extends On{get config(){let e=this.props.mosfetMode==="depletion"?"d":"e",n=`${this.props.channelType}_channel_${e}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??n,zodProps:Bz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}};function FTt(e){return e.simSwitchFrequency!==void 0||e.simCloseAt!==void 0||e.simOpenAt!==void 0||e.simStartClosed!==void 0||e.simStartOpen!==void 0}var $G=class extends On{_getSwitchType(){let e=this._parsedProps;return e?e.dpdt?"dpdt":e.spst?"spst":e.spdt?"spdt":e.dpst?"dpst":e.type??"spst":"spst"}get config(){let e=this._getSwitchType(),t=this._parsedProps?.isNormallyClosed??!1,n={spst:t?"spst_normally_closed_switch":"spst_switch",spdt:t?"spdt_normally_closed_switch":"spdt_switch",dpst:t?"dpst_normally_closed_switch":"dpst_switch",dpdt:t?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??n[e],zodProps:Uz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,t=this._parsedProps??{},n=e.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=n.source_component_id}doInitialSimulationRender(){let{_parsedProps:e}=this;if(!FTt(e))return;let{db:t}=this.root,n={type:"simulation_switch",source_component_id:this.source_component_id||""};e.simSwitchFrequency!==void 0&&(n.switching_frequency=Wi.parse(e.simSwitchFrequency)),e.simCloseAt!==void 0&&(n.closes_at=qi.parse(e.simCloseAt)),e.simOpenAt!==void 0&&(n.opens_at=qi.parse(e.simOpenAt)),e.simStartOpen!==void 0&&(n.starts_closed=!e.simStartOpen),e.simStartClosed!==void 0&&(n.starts_closed=e.simStartClosed),t.simulation_switch.insert(n)}},T4={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},jG=class extends On{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:Qz,sourceFtype:la.simple_test_point}}_getPropsWithDefaults(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}=this._parsedProps;return!n&&t&&(n="through_hole"),n??(n="through_hole"),e??(e="circle"),n==="pad"?e==="circle"?i??(i=T4.SMT_CIRCLE_DIAMETER):e==="rect"&&(o??(o=T4.SMT_RECT_SIZE),r??(r=o)):n==="through_hole"&&(t??(t=T4.HOLE_DIAMETER)),{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}}_getImpliedFootprintString(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}=this._getPropsWithDefaults();if(n==="through_hole")return`platedhole_d${t}`;if(n==="pad"){if(e==="circle")return`smtpad_circle_d${i}`;if(e==="rect")return`smtpad_rect_w${o}_h${r}`}throw new Error(`Footprint variant "${n}" with pad shape "${e}" not implemented`)}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{padShape:n,holeDiameter:i,footprintVariant:o,padDiameter:r,width:s,height:a}=this._getPropsWithDefaults(),c=e.source_component.insert({ftype:la.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:o,pad_shape:n,pad_diameter:r,hole_diameter:i,width:s,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},BG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:hD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:i.x,y:i.y},rotation:n.schRotation??0})}},YG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:pD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_line.insert({schematic_component_id:o,x1:n.x1+i.x,y1:n.y1+i.y,x2:n.x2+i.x,y2:n.y2+i.y,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=r.schematic_line_id}},XG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:uD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_rect.insert({center:{x:i.x,y:i.y},width:n.width,height:n.height,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_filled:n.isFilled,schematic_component_id:o,is_dashed:n.isDashed,rotation:n.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=r.schematic_rect_id}},VG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:aD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_arc.insert({schematic_component_id:o,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,start_angle_degrees:n.startAngleDegrees,end_angle_degrees:n.endAngleDegrees,direction:n.direction,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=r.schematic_arc_id}},HG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:lD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_circle.insert({schematic_component_id:o,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_filled:n.isFilled,fill_color:n.fillColor,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=r.schematic_circle_id}};function zTt({anchor:e,x:t,y:n,width:i,height:o,isInside:r}){switch(e){case"top_left":return{x:t,y:n+o,textAnchor:r?"top_left":"bottom_left"};case"top_center":return{x:t+i/2,y:n+o,textAnchor:r?"top_center":"bottom_center"};case"top_right":return{x:t+i,y:n+o,textAnchor:r?"top_right":"bottom_right"};case"center_left":return{x:t,y:n+o/2,textAnchor:r?"center_left":"center_right"};case"center":return{x:t+i/2,y:n+o/2,textAnchor:"center"};case"center_right":return{x:t+i,y:n+o/2,textAnchor:r?"center_right":"center_left"};case"bottom_left":return{x:t,y:n,textAnchor:r?"bottom_left":"top_left"};case"bottom_center":return{x:t+i/2,y:n,textAnchor:r?"bottom_center":"top_center"};case"bottom_right":return{x:t+i,y:n,textAnchor:r?"bottom_right":"top_right"};default:return{x:t+i/2,y:n+o,textAnchor:"center"}}}var GG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:cD,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=.6,o=typeof n.padding=="number"?n.padding:0,r=typeof n.paddingTop=="number"?n.paddingTop:o,s=typeof n.paddingBottom=="number"?n.paddingBottom:o,a=typeof n.paddingLeft=="number"?n.paddingLeft:o,c=typeof n.paddingRight=="number"?n.paddingRight:o,l=n.overlay&&n.overlay.length>0,u=typeof n.width=="number"&&typeof n.height=="number",h,d,_,y,g,x;if(l){let S=n.overlay.map(J=>({selector:J,port:this.getSubcircuit().selectOne(J,{type:"port"})})).filter(({port:J})=>J!=null).map(({port:J})=>({position:J._getGlobalSchematicPositionAfterLayout()}));if(S.length===0)return;let T=S.map(J=>J.position.x),I=S.map(J=>J.position.y),E=Math.min(...T),M=Math.max(...T),k=Math.min(...I),N=Math.max(...I),A=M-E,R=N-k,$=A===0?i:0,j=R===0?i:0,H=a+$/2,X=c+$/2,G=r+j/2,tt=s+j/2,Q=E-H,V=M+X,rt=k-tt,et=N+G;h=V-Q,d=et-rt,_=Q+(n.schX??0),y=rt+(n.schY??0),g=_+h/2,x=y+d/2}else if(u){h=n.width,d=n.height;let w=this._getGlobalSchematicPositionBeforeLayout();g=w.x,x=w.y,_=g-h/2,y=x-d/2}else return;if(t.schematic_box.insert({height:d,width:h,x:_,y,is_dashed:n.strokeStyle==="dashed"}),n.title){let w=n.titleInside,S=.1,T=n.titleAlignment,I=zTt({anchor:T,x:_,y,width:h,height:d,isInside:w}),E,M,k=I.textAnchor;w?(E=T.includes("top")?-S:T.includes("bottom")?S:0,M=T.includes("left")?S:T.includes("right")?-S:0):(E=T.includes("top")?S:T.includes("bottom")?-S:0,M=T.includes("center_left")?-S:T.includes("center_right")?S:0);let N=I.x+M,A=I.y+E;t.schematic_text.insert({anchor:k,text:n.title,font_size:n.titleFontSize??.18,color:n.titleColor??"#000000",position:{x:N,y:A},rotation:0})}}},UG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:dD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.children.filter(d=>d.componentName==="SchematicRow");if(i.length===0)return;let o=[],r=0;for(let d of i){let _=d.children.filter(y=>y.componentName==="SchematicCell");r=Math.max(r,_.length)}for(let d=0;d<i.length;d++)o[d]=[];for(let d=0;d<i.length;d++){let y=i[d].children.filter(x=>x.componentName==="SchematicCell"),g=0;for(let x=0;x<y.length;x++){for(;o[d][g];)g++;let w=y[x],S=w._parsedProps.colSpan??1,T=w._parsedProps.rowSpan??1;for(let I=0;I<T;I++)for(let E=0;E<S;E++)o[d+I]||(o[d+I]=[]),o[d+I][g+E]=w;g+=S}}r=Math.max(0,...o.map(d=>d.length));let s=i.map((d,_)=>d._parsedProps.height??1),a=Array.from({length:r},(d,_)=>{let y=0;for(let g=0;g<i.length;g++){let x=o[g]?.[_];if(x){let w=x._parsedProps.text??x._parsedProps.children,S=x._parsedProps.width??(w?.length??2)*.5;S>y&&(y=S)}}return y||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=t.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:s,cell_padding:n.cellPadding,border_width:n.borderWidth,anchor:n.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,h=0;for(let d=0;d<i.length;d++){let _=0;for(let y=0;y<r;y++){let g=o[d]?.[y];if(g&&!u.has(g)){u.add(g);let x=g._parsedProps,w=x.rowSpan??1,S=x.colSpan??1,T=0;for(let E=0;E<S;E++)T+=a[y+E];let I=0;for(let E=0;E<w;E++)I+=s[d+E];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:d,end_row_index:d+w-1,start_column_index:y,end_column_index:y+S-1,text:x.text??x.children,center:{x:c.x+_+T/2,y:c.y-h-I/2},width:T,height:I,horizontal_align:x.horizontalAlign,vertical_align:x.verticalAlign,font_size:x.fontSize??n.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[y]&&(_+=a[y])}h+=s[d]}}},qG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:fD}}},WG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:mD}}},ZG=class extends xe{constructor(){super(...arguments);P(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:Oz}}},KG=class extends xe{get config(){return{componentName:"AnalogSimulation",zodProps:$z}}doInitialSimulationRender(){let{db:e}=this.root,{duration:t,timePerStep:n}=this._parsedProps,i=t||10,o=n||.01;e.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:o})}},JG=class extends xe{constructor(){super(...arguments);P(this,"simulation_voltage_probe_id",null)}get config(){return{componentName:"VoltageProbe",zodProps:sD}}doInitialSimulationRender(){let{db:t}=this.root,{connectsTo:n,name:i}=this._parsedProps,o=this.getSubcircuit();if(!o){this.renderError("VoltageProbe must be inside a subcircuit");return}let r=Array.isArray(n)?n:[n];if(r.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let s=r[0],a=o.selectOne(s,{type:"port"}),c=a?null:o.selectOne(s,{type:"net"});if(c&&c.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${s}" resolved to a non-net component "${c.componentName}".`);return}if(!a&&!c){this.renderError(`VoltageProbe could not find connection target "${s}"`);return}let{simulation_voltage_probe_id:l}=t.simulation_voltage_probe.insert({name:i??this.name,source_port_id:a?.source_port_id??void 0,source_net_id:c?.source_net_id??void 0,subcircuit_id:o.subcircuit_id||void 0});this.simulation_voltage_probe_id=l}},DTt={name:"@tscircuit/core",type:"module",version:"0.0.855",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"',"generate-test-plan":"bun run scripts/generate-test-plan.ts"},devDependencies:{"@biomejs/biome":"^1.8.3","@resvg/resvg-js":"^2.6.2","@tscircuit/capacity-autorouter":"^0.0.140","@tscircuit/checks":"^0.0.85","@tscircuit/circuit-json-util":"^0.0.72","@tscircuit/common":"^0.0.20","@tscircuit/copper-pour-solver":"^0.0.14","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.29","@tscircuit/miniflex":"^0.0.4","@tscircuit/ngspice-spice-engine":"^0.0.2","@tscircuit/props":"^0.0.397","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^v0.0.45","@tscircuit/solver-utils":"^0.0.3","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.306","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.16","circuit-to-svg":"^0.0.265",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6","eecircuit-engine":"^1.5.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.16",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.10","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.50","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Uh=class{constructor({platform:e,projectUrl:t}={}){P(this,"firstChild",null);P(this,"children");P(this,"db");P(this,"root",null);P(this,"isRoot",!0);P(this,"schematicDisabled",!1);P(this,"pcbDisabled",!1);P(this,"pcbRoutingDisabled",!1);P(this,"_featureMspSchematicTraceRouting",!0);P(this,"name");P(this,"platform");P(this,"projectUrl");P(this,"_hasRenderedAtleastOnce",!1);P(this,"_eventListeners",{});this.children=[],this.db=Le([]),this.root=this,this.platform=e,this.projectUrl=t,this.pcbDisabled=e?.pcbDisabled??!1}add(e){let t;(0,QG.isValidElement)(e)?t=CH(e):t=e,this.children.push(t)}setPlatform(e){this.platform={...this.platform,...e}}_getBoard(){let e=this.children.find(t=>t.componentName==="Board");if(e)return e}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");let e=this.children.filter(n=>n.lowercaseComponentName==="panel");if(e.length>1)throw new Error("Only one <panel> is allowed per circuit");if(e.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=e[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let t=new Tc({subcircuit:!0});t.parent=this,t.addAll(this.children),this.children=[t],this.firstChild=t}render(){this.firstChild||this._guessRootComponent();let{firstChild:e,db:t}=this;if(!e)throw new Error("RootCircuit has no root component");e.parent=this,e.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(t=>setTimeout(t,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(e=>e._hasIncompleteAsyncEffects()?!0:e.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(e){let t=await Promise.resolve().then(()=>(ZV(),WV)).catch(n=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
251
+ `),a={x:n.center.x+n.width/2-.25,y:n.center.y-n.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:o,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:t}=this.root,n=t.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=n.source_board_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.width??0,o=n.height??0,r={x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)},{boardAnchorPosition:s,boardAnchorAlignment:a}=n;if(s&&(r=EIt({boardAnchorPosition:s,boardAnchorAlignment:a??"center",width:i,height:o})),n.outline){let u=n.outline.map(x=>x.x),h=n.outline.map(x=>x.y),d=Math.min(...u),_=Math.max(...u),y=Math.min(...h),g=Math.max(...h);i=_-d,o=g-y,r={x:(d+_)/2+(n.outlineOffsetX??0),y:(y+g)/2+(n.outlineOffsetY??0)}}let c=n.outline;!c&&n.borderRadius!=null&&i>0&&o>0&&(c=vH(i,o,n.borderRadius));let l=t.pcb_board.insert({center:r,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:o,outline:c?.map(u=>({x:u.x+(n.outlineOffsetX??0),y:u.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=l.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return zi()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let n=MX(t.toArray());for(let l of n)t.pcb_trace_error.insert(l);let i=TX(t.toArray());for(let l of i)t.pcb_port_not_connected_error.insert(l);let o=NX(t.toArray());for(let l of o)t.pcb_component_outside_board_error.insert(l);let r=RX(t.toArray());for(let l of r)t.pcb_trace_error.insert(l);let s=AX(t.toArray());for(let l of s)t.pcb_via_clearance_error.insert(l);let a=kX(t.toArray());for(let l of a)t.pcb_via_clearance_error.insert(l);let c=OX(t.toArray());for(let l of c)t.pcb_footprint_overlap_error.insert(l)}_emitRenderLifecycleEvent(t,n){super._emitRenderLifecycleEvent(t,n),n==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},tG=class extends Tc{get config(){return{componentName:"Panel",zodProps:_z}}get isGroup(){return!0}add(e){if(e.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(e)}runRenderCycle(){if(!this.children.some(e=>e.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}},TTt=new Proxy({},{get:(e,t)=>t}),la=TTt,jx="rgba(132, 0, 0)",Bx=.12,eG=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:Tz,sourceFtype:la.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let t=this.props.capacitance,n=typeof t=="string"?t:`${ni(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${ni(this._parsedProps.maxVoltageRating)}V`:n}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new $r({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new $r({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,capacitance:n.capacitance,max_voltage_rating:n.maxVoltageRating,max_decoupling_trace_length:n.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!n.polarized});this.source_component_id=i.source_component_id}},Fm=class extends On{constructor(t){super(t);P(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:Jp,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:n}=this;if(n.externallyConnectedPins){let i=new Set;for(let[o,r]of n.externallyConnectedPins)i.add(o),i.add(r);for(let o of i)if(!this.children.find(s=>s instanceof Ni&&s.isMatchingAnyOf([o]))){let s=o.match(/^pin(\d+)$/);if(s){let a=parseInt(s[1]);this.add(new Ni({pinNumber:a,aliases:[o]}))}else this.add(new Ni({name:o,aliases:[o]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.layer??"top";if(i!=="top"&&i!=="bottom"){let r=this.getSubcircuit(),s=Np.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${i}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:i,subcircuit_id:r.subcircuit_id??void 0});t.pcb_component_invalid_layer_error.insert(s)}let o=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:i==="top"||i==="bottom"?i:"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=o.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[n,i]of t.externallyConnectedPins)this.add(new $r({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:n}=this.props;if(!n)return;let i=null,o=null,r,s=this.selectAll("port");for(let h of s)for(let d of h.getNameAndAliases())if(n[d]){let _=n[d];_.providesPower&&(i=h,r=_.providesVoltage),_.providesGround&&(o=h)}if(!i||!o||r===void 0)return;let a=t.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=t.source_port.get(o.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=t.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=t.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||t.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:o.source_port_id,negative_source_net_id:u.source_net_id,voltage:r})}},nG=class extends Fm{constructor(e){super(e)}get config(){return{...super.config,componentName:"Pinout",zodProps:yz}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}},iG=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"anode",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},n=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"diode",componentName:"Diode",zodProps:Xz,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},oG=class extends On{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:bz,sourceFtype:la.simple_fuse}}_getSchematicSymbolDisplayValue(){let e=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,n=typeof e=="string"?parseFloat(e):e,i=typeof t=="string"?parseFloat(t):t;return`${ni(n)}A / ${ni(i)}V`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,i=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,o=e.source_component.insert({name:this.name,ftype:la.simple_fuse,current_rating_amps:n,voltage_rating_volts:i,display_current_rating:`${ni(n)}A`,display_voltage_rating:`${ni(i)}V`});this.source_component_id=o.source_component_id}},rG=class extends On{constructor(){super(...arguments);P(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:FI,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let o=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),r=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of o)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=r(a.start_pcb_port_id),a.end_pcb_port_id=r(a.end_pcb_port_id))}},sG=class extends On{constructor(){super(...arguments);P(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(t){return this.selectOne(`port.${t}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let t=this.children.filter(n=>n.componentName==="Port").map(n=>n.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,n=t.pinCount;if(t.pinCount==null&&!t.footprint&&(n=2),t.pinCount==null){let r=(t.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),s=r.length>0?Math.max(...r):0,a=t.pinLabels?Object.keys(t.pinLabels).length:0,c=Math.max(s,a);(c===2||c===3)&&(n=c),n==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(n=this.getPortsFromFootprint().length)}let i="";n?i+=`solderjumper${n}`:i="solderjumper";let o=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?o=Array.from(new Set(t.bridgedPins.flat().map(r=>this._getPinNumberFromBridgedPinName(r)).filter(r=>r!==null))).sort((r,s)=>r-s):t.bridged&&n&&(o=Array.from({length:n},(r,s)=>s+1)),o.length>0&&(i+=`_bridged${o.join("")}`),{schematicSymbolName:t.symbolName??i,componentName:"SolderJumper",zodProps:gz,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);n==null&&!this._parsedProps.footprint&&(n=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let o=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),r=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of o)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=r(a.start_pcb_port_id),a.end_pcb_port_id=r(a.end_pcb_port_id))}},aG=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"anode",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},n=this.props.laser?"laser":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"led",componentName:"Led",zodProps:Hz,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){let t=super.getFootprinterString();return t&&this.props.color?`${t}_color(${this.props.color})`:t}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:n.wavelength,color:n.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},cG=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"positive",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:rD,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Ni({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Ni({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},MTt=Dn.extend({voltage:ai.optional(),frequency:Wi.optional(),peakToPeakVoltage:ai.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Be.optional(),dutyCycle:p.number().optional()}),lG=class extends On{constructor(){super(...arguments);P(this,"terminal1",this.portMap.terminal1);P(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:MTt,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.portMap.terminal1,o=this.portMap.terminal2;t.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:o.source_port_id,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle})}},X4=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:vz,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${ni(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new $r({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new $r({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new $r({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new $r({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,resistance:n.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},CTt=["leftedge","rightedge","topedge","bottomedge","center"],uG=class extends xe{get config(){return{componentName:"Constraint",zodProps:Cz}}constructor(e){if(super(e),("xdist"in e||"ydist"in e)&&!("edgeToEdge"in e)&&!("centerToCenter"in e))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in e&&e.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let e=[],t=this.getPrimitiveContainer();function n(i){let o=i.split(" ").pop(),r=CTt.includes(o)?o:void 0,s=r?i.replace(` ${r}`,""):i,a=t.selectOne(s,{pcbPrimitive:!0});a&&e.push({selector:i,component:a,componentSelector:s,edge:r})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},pG=class extends xe{constructor(){super(...arguments);P(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:Wz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for FabricationNoteRect. Must be "top" or "bottom".`);let r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,s=this.getSubcircuit(),a=n.hasStroke??(n.strokeWidth!==void 0&&n.strokeWidth!==null),c=t.pcb_fabrication_note_rect.insert({pcb_component_id:r,layer:o,color:n.color,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,stroke_width:n.strokeWidth??1,is_filled:n.isFilled??!1,has_stroke:a,is_stroke_dashed:n.isStrokeDashed??!1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,corner_radius:n.cornerRadius??void 0});this.fabrication_note_rect_id=c.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},hG=class extends xe{constructor(){super(...arguments);P(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:Zz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this.getSubcircuit(),{_parsedProps:i}=this,o=i.layer??"top";if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenPath. Must be "top" or "bottom".`);let 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:o,color:i.color,route:i.route.map(c=>{let l=Ne(r,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:n?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},dG=class extends xe{get config(){return{componentName:"FabricationNoteText",zodProps:qz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit();e.pcb_fabrication_note_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:t.pcbX??0,y:t.pcbY??0},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:"top",color:t.color,text:t.text??"",pcb_component_id:n.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},fG=class extends xe{constructor(){super(...arguments);P(this,"fabrication_note_dimension_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:Kz}}_resolvePoint(t,n){if(typeof t=="string"){let r=this.getSubcircuit().selectOne(t);return r?r._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${t}"`),Ne(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,o=typeof t.y=="string"?parseFloat(t.y):t.y;return Ne(n,{x:i,y:o})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this._resolvePoint(n.from,i),r=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(n.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for FabricationNoteDimension. Must be "top" or "bottom".`);let u=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,h=n.text??this._formatDistanceText({from:o,to:r,units:n.units??"mm"}),d=t.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:o,to:r,text:h,offset:n.offset,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.fabrication_note_dimension_id=d.pcb_fabrication_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}_formatDistanceText({from:t,to:n,units:i}){let o=n.x-t.x,r=n.y-t.y,s=Math.sqrt(o*o+r*r),a=i==="in"?s/25.4:s,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},mG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_line_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:ID}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),o=this.getGroup(),r=this._computePcbGlobalTransformBeforeLayout(),s=Ne(r,{x:n.x1,y:n.y1}),a=Ne(r,{x:n.x2,y:n.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,x1:s.x,y1:s.y,x2:a.x,y2:a.y,stroke_width:n.strokeWidth??.1,color:n.color,is_dashed:n.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:t}=this;return{width:Math.abs(t.x2-t.x1),height:Math.abs(t.y2-t.y1)}}},_G=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_rect_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:wD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=Ne(i,{x:0,y:0}),r=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,center:o,width:n.width,height:n.height,stroke_width:n.strokeWidth??.1,is_filled:n.isFilled??!1,has_stroke:n.hasStroke??!0,is_stroke_dashed:n.isStrokeDashed??!1,color:n.color,corner_radius:n.cornerRadius??void 0});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.width=="string"?parseFloat(t.width):t.width,i=typeof t.height=="string"?parseFloat(t.height):t.height;return{width:n,height:i}}},yG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_text_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:SD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=Ne(i,{x:0,y:0}),r=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_text.insert({pcb_component_id:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,font:n.font??"tscircuit2024",font_size:n.fontSize??1,text:n.text,anchor_position:o,anchor_alignment:n.anchorAlignment??"center",color:n.color});this.pcb_note_text_id=c.pcb_note_text_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.fontSize=="string"?parseFloat(t.fontSize):t.fontSize??1,i=n*.6;return{width:t.text.length*i,height:n}}},gG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_path_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:PD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this.getSubcircuit(),r=this.getGroup(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=typeof u=="string"?parseFloat(u):u,y=typeof h=="string"?parseFloat(h):h,g=Ne(i,{x:_,y});return{...d,x:g.x,y:g.y}}),c=t.pcb_note_path.insert({pcb_component_id:s,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,route:a,stroke_width:n.strokeWidth??.1,color:n.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:t}=this;if(t.route.length===0)return{width:0,height:0};let n=t.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=t.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),o=Math.min(...n),r=Math.max(...n),s=Math.min(...i),a=Math.max(...i);return{width:r-o,height:a-s}}},bG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_dimension_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:TD}}_resolvePoint(t,n){if(typeof t=="string"){let r=this.getSubcircuit().selectOne(`.${t}`);return r?r._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${t}"`),Ne(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,o=typeof t.y=="string"?parseFloat(t.y):t.y;return Ne(n,{x:i,y:o})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this._resolvePoint(n.from,i),r=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=n.text??this._formatDistanceText({from:o,to:r,units:n.units??"mm"}),u=t.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:o,to:r,text:l,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.pcb_note_dimension_id=u.pcb_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}_formatDistanceText({from:t,to:n,units:i}){let o=n.x-t.x,r=n.y-t.y,s=Math.sqrt(o*o+r*r),a=i==="in"?s/25.4:s,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},xG=(e,t)=>{let{injectionDb:n,normalComponent:i}=t;if(!i)return;let o=Vh({componentName:i.name,componentRotation:"0deg"},n.toArray().filter(r=>"pcb_component_id"in r&&r.pcb_component_id===e.pcb_component_id));i.addAll(o)};function ETt(e,t){let{injectionDb:n,subcircuit:i,groupsMap:o}=t,r=n.pcb_component.getWhere({source_component_id:e.source_component_id}),s=n.cad_component.getWhere({source_component_id:e.source_component_id}),a=new X4({name:e.name,resistance:e.resistance});r&&xG(r,{...t,normalComponent:a}),e.source_group_id&&o?.has(e.source_group_id)?o.get(e.source_group_id).add(a):i.add(a)}function NTt(e,t){let{injectionDb:n,subcircuit:i}=t;if(e.source_component_id!==null)return;let o=n.pcb_port.getWhere({source_port_id:e.source_port_id}),r=new Ni({name:e.name,pinNumber:e.pin_number});i.add(r),r.source_port_id=e.source_port_id;let s=i.root;if(s&&o){let{db:a}=s,c=a.pcb_port.insert({pcb_component_id:void 0,layers:o.layers,subcircuit_id:i.subcircuit_id??void 0,pcb_group_id:i.getGroup()?.pcb_group_id??void 0,x:o.x,y:o.y,source_port_id:e.source_port_id,is_board_pinout:!1});r.pcb_port_id=c.pcb_port_id}}function kTt(e,t){let{subcircuit:n,groupsMap:i}=t,o=new Tc({name:e.name});return o.source_group_id=e.source_group_id,n.add(o),i&&i.set(e.source_group_id,o),o}var ATt=(e,t)=>{if(!e||e.length===0)return;let{injectionDb:n}=t,i=e.map(o=>o.map(r=>{let 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(o=>o.length>0);return i.length>0?i:void 0},RTt=(e,t)=>{let{injectionDb:n,subcircuit:i,groupsMap:o}=t,r=n.pcb_component.getWhere({source_component_id:e.source_component_id}),s=n.schematic_component.getWhere({source_component_id:e.source_component_id}),a=n.cad_component.getWhere({source_component_id:e.source_component_id}),c=ATt(e.internally_connected_source_port_ids,t),l=new Fm({name:e.name,manufacturerPartNumber:e.manufacturer_part_number,supplierPartNumbers:e.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:r?.center?.x,pcbY:r?.center?.y,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds,internallyConnectedPins:c}),u=a?.footprinter_string??"soic8";u&&(Object.assign(l.props,{footprint:u}),Object.assign(l._parsedProps,{footprint:u}),a||l._addChildrenFromStringFootprint?.()),r&&xG(r,{...t,normalComponent:l}),e.source_group_id&&o?.has(e.source_group_id)?o.get(e.source_group_id).add(l):i.add(l)},vG=class extends Tc{constructor(e){super({...e,subcircuit:!0})}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:e,children:t}=this._parsedProps;if(!e)return;let n=Ge(e);if(e&&t?.length>0)throw new Error("Subcircuit cannot have both circuitJson and children");let o={injectionDb:n,subcircuit:this,groupsMap:new Map},r=n.source_group.list();for(let c of r)kTt(c,o);let s=n.source_component.list();for(let c of s)switch(c.ftype){case"simple_resistor":ETt(c,o);break;case"simple_chip":RTt(c,o);break;default:throw new Error(`No inflator implemented for source component ftype: "${c.ftype}"`)}let a=n.source_port.list();for(let c of a)NTt(c,o)}},SG=class extends Tc{constructor(e){super({...e,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let n=e.pcb_group.get(this.pcb_group_id),i=t.paddingLeft??t.padding??0,o=t.paddingRight??t.padding??0,r=t.paddingTop??t.padding??0,s=t.paddingBottom??t.padding??0;e.pcb_group.update(this.pcb_group_id,{width:(n.width??0)+i+o,height:(n.height??0)+r+s,center:{x:n.center.x+(o-i)/2,y:n.center.y+(r-s)/2}})}},wG=class extends xe{constructor(){super(...arguments);P(this,"pcb_breakout_point_id",null);P(this,"matchedPort",null);P(this,"matchedNet",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:tD}}_matchConnection(){let{connection:t}=this._parsedProps,n=this.getSubcircuit();n&&(this.matchedPort=n.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=n.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(o=>o.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(o=>o.connected_source_port_ids.includes(t.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;this._matchConnection();let{pcbX:n=0,pcbY:i=0}=this._parsedProps,o=this.parent?.getGroup(),r=this.getSubcircuit();if(!o||!o.pcb_group_id)return;let s=t.pcb_breakout_point.insert({pcb_group_id:o.pcb_group_id,subcircuit_id:r?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:n,y:i});this.pcb_breakout_point_id=s.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:n=0}=this._parsedProps;return{center:{x:t,y:n},bounds:{left:t,top:n,right:t,bottom:n},width:0,height:0}}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_breakout_point_id&&n.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},PG=class extends xe{constructor(){super(...arguments);P(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:zz}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),o=this._getConnectedPorts();if(o.length===0)return"right";let r=o[0]._getGlobalSchematicPositionBeforeLayout(),s=r.x-i.x,a=r.y-i.y;if(Math.abs(s)>Math.abs(a)){if(s>0)return"right";if(s<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let n=[];for(let i of t){let o=this.getSubcircuit().selectOne(i);o&&n.push(o)}return n}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let n=this._getConnectedPorts();if(n.length>0){let i=n[0]._getGlobalSchematicPositionBeforeLayout(),o=Ne(this.parent?.computeSchematicGlobalTransform?.()??zi(),{x:0,y:0});return vn(i.x-o.x,i.y-o.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),r=n.anchorSide??"right",s=Ic({anchor_position:i,anchor_side:r,text:n.net}),a=t.schematic_net_label.insert({text:n.net,source_net_id:o.source_net_id,anchor_position:i,center:s,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo??t.connection;if(Array.isArray(n))return n;if(typeof n=="string")return[n]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&zx(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let n of t)this.add(new $r({from:n,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._resolveConnectsTo();if(!n||n.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),o=this._getAnchorSide(),s={left:"x-",right:"x+",top:"y+",bottom:"y-"}[o],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of n){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id??""));if(w&&(u=t.schematic_trace.list().some(S=>S.source_trace_id===w.source_trace_id)),u)continue}let h=l._getGlobalSchematicPositionAfterLayout(),d=E4(l.facingDirection??"right")??"x+",_=oc({x:h.x,y:h.y,facingDirection:d},{x:i.x,y:i.y,facingDirection:s});if(!Array.isArray(_)||_.length<2)continue;let y=[];for(let w=0;w<_.length-1;w++)y.push({from:{x:_[w].x,y:_[w].y},to:{x:_[w+1].x,y:_[w+1].y}});let g,x;if(a?.source_net_id&&l.source_port_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id));g=w?.source_trace_id,x=w?.subcircuit_connectivity_map_key||t.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}t.schematic_trace.insert({source_trace_id:g,edges:y,junctions:[],subcircuit_connectivity_map_key:x}),t.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},IG=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_circle_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:xD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenCircle. Must be "top" or "bottom".`);let r=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:o,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},TG=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_rect_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:bD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenRect. Must be "top" or "bottom".`);let r=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_rect.insert({pcb_component_id:s,layer:o,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1,is_filled:n.filled??!1,corner_radius:n.cornerRadius??void 0});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},MG=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_line_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:gD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenLine. Must be "top" or "bottom".`);let r=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_line.insert({pcb_component_id:s,layer:o,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:r?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},CG=class extends xe{constructor(t){super(t);P(this,"pcb_via_id",null);P(this,"matchedPort",null);P(this,"isPcbPrimitive",!0);P(this,"source_manually_placed_via_id",null);P(this,"subcircuit_connectivity_map_key",null);let n=this._getLayers();this._parsedProps.layers=n,this.initPorts()}get config(){return{componentName:"Via",zodProps:Jz}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}_getLayers(){let{fromLayer:t="top",toLayer:n="bottom"}=this._parsedProps;return t===n?[t]:[t,n]}initPorts(){let t=this._parsedProps.layers;for(let i of t){let o=new Ni({name:i,layer:i});o.registerMatch(this),this.add(o)}let n=new Ni({name:"pin1"});n.registerMatch(this),this.add(n)}_getConnectedNetOrTrace(){let t=this._parsedProps.connectsTo;if(!t)return null;let n=this.getSubcircuit(),i=Array.isArray(t)?t:[t];for(let o of i)if(o.startsWith("net.")){let r=n.selectOne(o,{type:"net"});if(r)return r}return null}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),o=this.getSubcircuit(),r=t.pcb_component.insert({center:i,width:n.outerDiameter,height:n.outerDiameter,layer:n.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:o?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=r.pcb_component_id}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getGroup(),o=this.getSubcircuit(),r=t.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:n.net??"",subcircuit_id:o?.subcircuit_id??void 0});this.source_component_id=r.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),o=this.getSubcircuit(),r=t.pcb_via.insert({x:i.x,y:i.y,hole_diameter:n.holeDiameter,outer_diameter:n.outerDiameter,layers:["bottom","top"],from_layer:n.fromLayer||"bottom",to_layer:n.toLayer||"top",subcircuit_id:o?.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:n.netIsAssignable??void 0});this.pcb_via_id=r.pcb_via_id}},EG=class extends xe{constructor(){super(...arguments);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:nD}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;zx(this,[t.connectsTo])}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit().selectOne(n.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${n.connectsTo}" not found for copper pour`);return}let o=this.getSubcircuit(),r=t.toArray().filter(h=>h.type==="source_net"&&h.name===i.name)[0]||"",s=n.clearance??.2,a=DX(t.toArray(),{layer:n.layer,pour_connectivity_key:r.subcircuit_connectivity_map_key||"",pad_margin:n.padMargin??s,trace_margin:n.traceMargin??s,board_edge_margin:n.boardEdgeMargin??s,cutout_margin:n.cutoutMargin??s}),c=new zX(a),{brep_shapes:l}=c.getOutput(),u=n.coveredWithSolderMask??!1;for(let h of l)t.pcb_copper_pour.insert({shape:"brep",layer:n.layer,brep_shape:h,source_net_id:i.source_net_id,subcircuit_id:o?.subcircuit_id??void 0,covered_with_solder_mask:u})})}},NG=class extends On{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:Lz,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:t.capacity,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},kG=class extends On{_getPcbRotationBeforeLayout(){let e=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+e}get config(){return{componentName:"PinHeader",zodProps:Fz,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,o=this._parsedProps.showSilkscreenPinLabels;if(e>0){let r;if(i)!t&&!n?r=`pinrow${e}_p${i}`:r=`pinrow${e}_p${i}_id${t}_od${n}`;else if(!t&&!n)r=`pinrow${e}`;else return null;return o!==!0&&(r+="_nopinlabels"),r}return null}initPorts(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let t=1;t<=e;t++){let n=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[t-1]:this._parsedProps.pinLabels?.[`pin${t}`];if(n){let i=Array.isArray(n)?n[0]:n,o=Array.isArray(n)?n.slice(1):[];this.add(new Ni({pinNumber:t,name:i,aliases:[`pin${t}`,...o]}))}else this.add(new Ni({pinNumber:t,name:`pin${t}`}))}}_getSchematicPortArrangement(){let e=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:n?.leftSide?.direction??"top-to-bottom",pins:n?.leftSide?.pins??Array.from({length:e},(i,o)=>`pin${o+1}`)}}:{rightSide:{direction:n?.rightSide?.direction??"top-to-bottom",pins:n?.rightSide?.pins??Array.from({length:e},(i,o)=>`pin${o+1}`)}}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:t.supplierPartNumbers,pin_count:t.pinCount,gender:t.gender,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function OTt(e){switch(e){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var AG=class extends On{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??OTt(this.props.pinVariant),zodProps:Iz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:n,are_pins_interchangeable:n==="no_ground"||n==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let e=`${ni(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ni(this._parsedProps.loadCapacitance)}F`:e}},RG=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:Yz,sourceFtype:la.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${ni(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({name:this.name,ftype:la.simple_inductor,inductance:n.inductance,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function LTt(e){switch(e){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var OG=class extends On{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??LTt(this.props.pinVariant),zodProps:wz,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${ni(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},LG=class extends On{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:Dz,sourceFtype:la.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let e=ti[this._getSchematicSymbolNameOrThrow()],t=e.ports.find(l=>l.labels.includes("1")),n=e.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),o=i.find(l=>l.props.pinNumber===1),r=i.find(l=>l.props.pinNumber===2),s=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;o.schematicSymbolPortDef=t,(!c||c.length===0)&&(r.schematicSymbolPortDef=n);for(let[l,u]of[[2,r],[3,s],[4,a]]){let h=c?.find(([_,y])=>_===`pin${l}`||y===`pin${l}`);if(!h){u.schematicSymbolPortDef=n;break}(h?.[0]===`pin${l}`?h[1]:h?.[0])!=="pin1"&&(u.schematicSymbolPortDef=n)}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:la.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},FG=class extends On{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:Pz,sourceFtype:"simple_crystal"}}initPorts(){let e=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:e})}_getSchematicSymbolDisplayValue(){let e=`${ni(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ni(this._parsedProps.loadCapacitance)}F`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:t.frequency,load_capacitance:t.loadCapacitance,pin_variant:t.pinVariant||"two_pin",are_pins_interchangeable:(t.pinVariant||"two_pin")==="two_pin"});this.source_component_id=n.source_component_id}},zG=class extends On{constructor(){super(...arguments);P(this,"emitter",this.portMap.pin1);P(this,"collector",this.portMap.pin2);P(this,"base",this.portMap.pin3)}get config(){let t=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??t,zodProps:jz,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},DG=class extends On{get config(){let e=this.props.mosfetMode==="depletion"?"d":"e",n=`${this.props.channelType}_channel_${e}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??n,zodProps:Bz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}};function FTt(e){return e.simSwitchFrequency!==void 0||e.simCloseAt!==void 0||e.simOpenAt!==void 0||e.simStartClosed!==void 0||e.simStartOpen!==void 0}var $G=class extends On{_getSwitchType(){let e=this._parsedProps;return e?e.dpdt?"dpdt":e.spst?"spst":e.spdt?"spdt":e.dpst?"dpst":e.type??"spst":"spst"}get config(){let e=this._getSwitchType(),t=this._parsedProps?.isNormallyClosed??!1,n={spst:t?"spst_normally_closed_switch":"spst_switch",spdt:t?"spdt_normally_closed_switch":"spdt_switch",dpst:t?"dpst_normally_closed_switch":"dpst_switch",dpdt:t?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??n[e],zodProps:Uz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,t=this._parsedProps??{},n=e.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=n.source_component_id}doInitialSimulationRender(){let{_parsedProps:e}=this;if(!FTt(e))return;let{db:t}=this.root,n={type:"simulation_switch",source_component_id:this.source_component_id||""};e.simSwitchFrequency!==void 0&&(n.switching_frequency=Wi.parse(e.simSwitchFrequency)),e.simCloseAt!==void 0&&(n.closes_at=qi.parse(e.simCloseAt)),e.simOpenAt!==void 0&&(n.opens_at=qi.parse(e.simOpenAt)),e.simStartOpen!==void 0&&(n.starts_closed=!e.simStartOpen),e.simStartClosed!==void 0&&(n.starts_closed=e.simStartClosed),t.simulation_switch.insert(n)}},T4={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},jG=class extends On{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:Qz,sourceFtype:la.simple_test_point}}_getPropsWithDefaults(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}=this._parsedProps;return!n&&t&&(n="through_hole"),n??(n="through_hole"),e??(e="circle"),n==="pad"?e==="circle"?i??(i=T4.SMT_CIRCLE_DIAMETER):e==="rect"&&(o??(o=T4.SMT_RECT_SIZE),r??(r=o)):n==="through_hole"&&(t??(t=T4.HOLE_DIAMETER)),{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}}_getImpliedFootprintString(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}=this._getPropsWithDefaults();if(n==="through_hole")return`platedhole_d${t}`;if(n==="pad"){if(e==="circle")return`smtpad_circle_d${i}`;if(e==="rect")return`smtpad_rect_w${o}_h${r}`}throw new Error(`Footprint variant "${n}" with pad shape "${e}" not implemented`)}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{padShape:n,holeDiameter:i,footprintVariant:o,padDiameter:r,width:s,height:a}=this._getPropsWithDefaults(),c=e.source_component.insert({ftype:la.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:o,pad_shape:n,pad_diameter:r,hole_diameter:i,width:s,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},BG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:hD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:i.x,y:i.y},rotation:n.schRotation??0})}},YG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:pD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_line.insert({schematic_component_id:o,x1:n.x1+i.x,y1:n.y1+i.y,x2:n.x2+i.x,y2:n.y2+i.y,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=r.schematic_line_id}},XG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:uD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_rect.insert({center:{x:i.x,y:i.y},width:n.width,height:n.height,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_filled:n.isFilled,schematic_component_id:o,is_dashed:n.isDashed,rotation:n.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=r.schematic_rect_id}},VG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:aD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_arc.insert({schematic_component_id:o,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,start_angle_degrees:n.startAngleDegrees,end_angle_degrees:n.endAngleDegrees,direction:n.direction,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=r.schematic_arc_id}},HG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:lD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_circle.insert({schematic_component_id:o,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_filled:n.isFilled,fill_color:n.fillColor,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=r.schematic_circle_id}};function zTt({anchor:e,x:t,y:n,width:i,height:o,isInside:r}){switch(e){case"top_left":return{x:t,y:n+o,textAnchor:r?"top_left":"bottom_left"};case"top_center":return{x:t+i/2,y:n+o,textAnchor:r?"top_center":"bottom_center"};case"top_right":return{x:t+i,y:n+o,textAnchor:r?"top_right":"bottom_right"};case"center_left":return{x:t,y:n+o/2,textAnchor:r?"center_left":"center_right"};case"center":return{x:t+i/2,y:n+o/2,textAnchor:"center"};case"center_right":return{x:t+i,y:n+o/2,textAnchor:r?"center_right":"center_left"};case"bottom_left":return{x:t,y:n,textAnchor:r?"bottom_left":"top_left"};case"bottom_center":return{x:t+i/2,y:n,textAnchor:r?"bottom_center":"top_center"};case"bottom_right":return{x:t+i,y:n,textAnchor:r?"bottom_right":"top_right"};default:return{x:t+i/2,y:n+o,textAnchor:"center"}}}var GG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:cD,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=.6,o=typeof n.padding=="number"?n.padding:0,r=typeof n.paddingTop=="number"?n.paddingTop:o,s=typeof n.paddingBottom=="number"?n.paddingBottom:o,a=typeof n.paddingLeft=="number"?n.paddingLeft:o,c=typeof n.paddingRight=="number"?n.paddingRight:o,l=n.overlay&&n.overlay.length>0,u=typeof n.width=="number"&&typeof n.height=="number",h,d,_,y,g,x;if(l){let S=n.overlay.map(J=>({selector:J,port:this.getSubcircuit().selectOne(J,{type:"port"})})).filter(({port:J})=>J!=null).map(({port:J})=>({position:J._getGlobalSchematicPositionAfterLayout()}));if(S.length===0)return;let T=S.map(J=>J.position.x),I=S.map(J=>J.position.y),E=Math.min(...T),M=Math.max(...T),k=Math.min(...I),N=Math.max(...I),A=M-E,R=N-k,$=A===0?i:0,j=R===0?i:0,H=a+$/2,X=c+$/2,G=r+j/2,tt=s+j/2,Q=E-H,V=M+X,rt=k-tt,et=N+G;h=V-Q,d=et-rt,_=Q+(n.schX??0),y=rt+(n.schY??0),g=_+h/2,x=y+d/2}else if(u){h=n.width,d=n.height;let w=this._getGlobalSchematicPositionBeforeLayout();g=w.x,x=w.y,_=g-h/2,y=x-d/2}else return;if(t.schematic_box.insert({height:d,width:h,x:_,y,is_dashed:n.strokeStyle==="dashed"}),n.title){let w=n.titleInside,S=.1,T=n.titleAlignment,I=zTt({anchor:T,x:_,y,width:h,height:d,isInside:w}),E,M,k=I.textAnchor;w?(E=T.includes("top")?-S:T.includes("bottom")?S:0,M=T.includes("left")?S:T.includes("right")?-S:0):(E=T.includes("top")?S:T.includes("bottom")?-S:0,M=T.includes("center_left")?-S:T.includes("center_right")?S:0);let N=I.x+M,A=I.y+E;t.schematic_text.insert({anchor:k,text:n.title,font_size:n.titleFontSize??.18,color:n.titleColor??"#000000",position:{x:N,y:A},rotation:0})}}},UG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:dD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.children.filter(d=>d.componentName==="SchematicRow");if(i.length===0)return;let o=[],r=0;for(let d of i){let _=d.children.filter(y=>y.componentName==="SchematicCell");r=Math.max(r,_.length)}for(let d=0;d<i.length;d++)o[d]=[];for(let d=0;d<i.length;d++){let y=i[d].children.filter(x=>x.componentName==="SchematicCell"),g=0;for(let x=0;x<y.length;x++){for(;o[d][g];)g++;let w=y[x],S=w._parsedProps.colSpan??1,T=w._parsedProps.rowSpan??1;for(let I=0;I<T;I++)for(let E=0;E<S;E++)o[d+I]||(o[d+I]=[]),o[d+I][g+E]=w;g+=S}}r=Math.max(0,...o.map(d=>d.length));let s=i.map((d,_)=>d._parsedProps.height??1),a=Array.from({length:r},(d,_)=>{let y=0;for(let g=0;g<i.length;g++){let x=o[g]?.[_];if(x){let w=x._parsedProps.text??x._parsedProps.children,S=x._parsedProps.width??(w?.length??2)*.5;S>y&&(y=S)}}return y||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=t.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:s,cell_padding:n.cellPadding,border_width:n.borderWidth,anchor:n.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,h=0;for(let d=0;d<i.length;d++){let _=0;for(let y=0;y<r;y++){let g=o[d]?.[y];if(g&&!u.has(g)){u.add(g);let x=g._parsedProps,w=x.rowSpan??1,S=x.colSpan??1,T=0;for(let E=0;E<S;E++)T+=a[y+E];let I=0;for(let E=0;E<w;E++)I+=s[d+E];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:d,end_row_index:d+w-1,start_column_index:y,end_column_index:y+S-1,text:x.text??x.children,center:{x:c.x+_+T/2,y:c.y-h-I/2},width:T,height:I,horizontal_align:x.horizontalAlign,vertical_align:x.verticalAlign,font_size:x.fontSize??n.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[y]&&(_+=a[y])}h+=s[d]}}},qG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:fD}}},WG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:mD}}},ZG=class extends xe{constructor(){super(...arguments);P(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:Oz}}},KG=class extends xe{get config(){return{componentName:"AnalogSimulation",zodProps:$z}}doInitialSimulationRender(){let{db:e}=this.root,{duration:t,timePerStep:n}=this._parsedProps,i=t||10,o=n||.01;e.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:o})}},JG=class extends xe{constructor(){super(...arguments);P(this,"simulation_voltage_probe_id",null)}get config(){return{componentName:"VoltageProbe",zodProps:sD}}doInitialSimulationRender(){let{db:t}=this.root,{connectsTo:n,name:i}=this._parsedProps,o=this.getSubcircuit();if(!o){this.renderError("VoltageProbe must be inside a subcircuit");return}let r=Array.isArray(n)?n:[n];if(r.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let s=r[0],a=o.selectOne(s,{type:"port"}),c=a?null:o.selectOne(s,{type:"net"});if(c&&c.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${s}" resolved to a non-net component "${c.componentName}".`);return}if(!a&&!c){this.renderError(`VoltageProbe could not find connection target "${s}"`);return}let{simulation_voltage_probe_id:l}=t.simulation_voltage_probe.insert({name:i??this.name,source_port_id:a?.source_port_id??void 0,source_net_id:c?.source_net_id??void 0,subcircuit_id:o.subcircuit_id||void 0});this.simulation_voltage_probe_id=l}},DTt={name:"@tscircuit/core",type:"module",version:"0.0.856",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"',"generate-test-plan":"bun run scripts/generate-test-plan.ts"},devDependencies:{"@biomejs/biome":"^1.8.3","@resvg/resvg-js":"^2.6.2","@tscircuit/capacity-autorouter":"^0.0.140","@tscircuit/checks":"^0.0.85","@tscircuit/circuit-json-util":"^0.0.72","@tscircuit/common":"^0.0.20","@tscircuit/copper-pour-solver":"^0.0.14","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.29","@tscircuit/miniflex":"^0.0.4","@tscircuit/ngspice-spice-engine":"^0.0.2","@tscircuit/props":"^0.0.398","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^v0.0.45","@tscircuit/solver-utils":"^0.0.3","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.306","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.16","circuit-to-svg":"^0.0.265",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6","eecircuit-engine":"^1.5.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.16",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.10","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.50","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Uh=class{constructor({platform:e,projectUrl:t}={}){P(this,"firstChild",null);P(this,"children");P(this,"db");P(this,"root",null);P(this,"isRoot",!0);P(this,"_schematicDisabledOverride");P(this,"pcbDisabled",!1);P(this,"pcbRoutingDisabled",!1);P(this,"_featureMspSchematicTraceRouting",!0);P(this,"name");P(this,"platform");P(this,"projectUrl");P(this,"_hasRenderedAtleastOnce",!1);P(this,"_eventListeners",{});this.children=[],this.db=Le([]),this.root=this,this.platform=e,this.projectUrl=t,this.pcbDisabled=e?.pcbDisabled??!1}get schematicDisabled(){return this._schematicDisabledOverride!==void 0?this._schematicDisabledOverride:this._getBoard()?._parsedProps?.schematicDisabled??!1}set schematicDisabled(e){this._schematicDisabledOverride=e}add(e){let t;(0,QG.isValidElement)(e)?t=CH(e):t=e,this.children.push(t)}setPlatform(e){this.platform={...this.platform,...e}}_getBoard(){let e=this.children.find(t=>t.componentName==="Board");if(e)return e}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");let e=this.children.filter(n=>n.lowercaseComponentName==="panel");if(e.length>1)throw new Error("Only one <panel> is allowed per circuit");if(e.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=e[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let t=new Tc({subcircuit:!0});t.parent=this,t.addAll(this.children),this.children=[t],this.firstChild=t}render(){this.firstChild||this._guessRootComponent();let{firstChild:e,db:t}=this;if(!e)throw new Error("RootCircuit has no root component");e.parent=this,e.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(t=>setTimeout(t,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(e=>e._hasIncompleteAsyncEffects()?!0:e.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(e){let t=await Promise.resolve().then(()=>(ZV(),WV)).catch(n=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
252
252
 
253
253
  "${n.message}"`)});if(e.view==="pcb")return t.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(e.view==="schematic")return t.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${e.view}`)}getCoreVersion(){let[e,t,n]=DTt.version.split(".").map(Number);return`${e}.${t}.${n+1}`}async preview(e){let t=typeof e=="object"?e:{previewName:e};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return zi()}_computePcbGlobalTransformBeforeLayout(){return zi()}selectAll(e){return this._guessRootComponent(),this.firstChild?.selectAll(e)??[]}selectOne(e,t){return this._guessRootComponent(),this.firstChild?.selectOne(e,t)??null}emit(e,...t){if(this._eventListeners[e])for(let n of this._eventListeners[e])n(...t)}on(e,t){this._eventListeners[e]||(this._eventListeners[e]=[]),this._eventListeners[e].push(t)}removeListener(e,t){this._eventListeners[e]&&(this._eventListeners[e]=this._eventListeners[e].filter(n=>n!==t))}enableDebug(e){typeof e=="string"?O4.default.enable(e):(e===null||e===!1)&&O4.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},$Tt=Uh,jTt=Uh,BTt=e=>{let[t,n]=Bh.default.useState(!0),[i,o]=Bh.default.useState(null),[r,s]=Bh.default.useState(),[a,c]=Bh.default.useState();return Bh.default.useEffect(()=>{n(!0),o(null),e&&setTimeout(()=>{try{let l=new Uh;l.add(e),s(l),c(l.toJson())}catch(l){o(l)}n(!1)},1)},[e]),{isLoading:t,error:i,circuit:r,circuitJson:a}},qh=(e,t)=>(n,i)=>{let o=[];Array.isArray(t)?o.push(...t.flat()):typeof t=="object"&&o.push(...Object.values(t).flat(),...Object.keys(t));let r=s=>{if(s?.name&&s.name!==n)throw new Error(`Component name mismatch. Hook name: ${n}, Component prop name: ${s.name}`);let a={...i,...s,name:n},c=[];for(let l of o)if(a[l]){let u=`.${n} > .${l}`,h=a[l];c.push({from:u,to:h}),delete a[l]}return(0,mu.jsxs)(mu.Fragment,{children:[(0,mu.jsx)(e,{...a}),c.map((l,u)=>(0,mu.jsx)("trace",{...l},u))]})};for(let s of o)r[s]=`.${n} > .${s}`;return r},YTt=qh(e=>(0,tU.jsx)("capacitor",{...e}),Mz),XTt=e=>qh(t=>(0,eU.jsx)("chip",{pinLabels:e,...t}),e),VTt=qh(e=>(0,nU.jsx)("diode",{...e}),Vz),HTt=qh(e=>(0,iU.jsx)("led",{...e}),Gz),GTt=qh(e=>(0,oU.jsx)("resistor",{...e}),Sz),UTt=new Proxy(e=>new Proxy({},{get:(t,n)=>`.${e} > .${n}`}),{get:(e,t)=>{let n=(...i)=>{let o=i[0];return new Proxy({},{get:(r,s)=>`.${t} > .${s}`})};return new Proxy(n,{get:(i,o)=>t==="net"?`net.${o}`:t==="subcircuit"?new Proxy({},{get:(r,s)=>new Proxy({},{get:(a,c)=>`subcircuit.${o} > .${s} > .${c}`})}):`.${t} > .${o}`,apply:(i,o,r)=>t==="net"?new Proxy({},{get:(s,a)=>`net.${a}`}):new Proxy({},{get:(s,a)=>{let c=`.${t} > .${a}`;return["U","J","CN"].some(u=>t.startsWith(u))?c:new Proxy(new String(c),{get:(u,h)=>typeof h=="symbol"||h==="toString"?()=>c:`.${t} > .${a} > .${h}`})}})})}});MH(SH);MH({Bug:Fm});var PU=Xt(Mr(),1);var sU=e=>{let t=e.match(/:[RC]_(\d{4})_/);if(t||(t=e.match(/:(SOIC-\d+|SOT-\d+|SOD-\d+|SSOP-\d+|TSSOP-\d+|QFP-\d+|QFN-\d+)/),t))return t[1]};var V4=e=>e.includes("cap")?e.replace(/cap/g,""):e;var aU=e=>{if(e){if(e.startsWith("kicad:")){let t=sU(e);return t?V4(t):e}return V4(e)}};var H4=new Map,lo=async(e,t)=>{let n=new URLSearchParams({...t,json:"true"}).toString();if(H4.has(n))return H4.get(n);let o=await(await fetch(`https://jlcsearch.tscircuit.com/${e}/list?${n}`)).json();return H4.set(n,o),o},uo=e=>e?[...e].sort((t,n)=>Number(n.is_basic??!1)-Number(t.is_basic??!1)):[],cU={findPart:async({sourceComponent:e,footprinterString:t})=>{let n=aU(t);if(e.type==="source_component"&&e.ftype==="simple_resistor"){let{resistors:i}=await lo("resistors",{resistance:e.resistance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_capacitor"){let{capacitors:i}=await lo("capacitors",{capacitance:e.capacitance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_pin_header"){let i;t?.includes("_p")&&(i=Number(t.split("_p")[1]));let{headers:o}=await lo("headers",i?{pitch:i,num_pins:e.pin_count,gender:e.gender}:{num_pins:e.pin_count,gender:e.gender});return{jlcpcb:uo(o).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_potentiometer"){let{potentiometers:i}=await lo("potentiometers",{resistance:e.max_resistance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_diode"){let{diodes:i}=await lo("diodes",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_chip"){let{chips:i}=await lo("chips",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_transistor"){let{transistors:i}=await lo("transistors",{package:n,transistor_type:e.transistor_type});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_power_source"){let{power_sources:i}=await lo("power_sources",{voltage:e.voltage,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_inductor"){let{inductors:i}=await lo("inductors",{inductance:e.inductance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_crystal"){let{crystals:i}=await lo("crystals",{frequency:e.frequency,load_capacitance:e.load_capacitance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_mosfet"){let{mosfets:i}=await lo("mosfets",{package:n,mosfet_mode:e.mosfet_mode,channel_type:e.channel_type});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_resonator"){let{resonators:i}=await lo("resonators",{frequency:e.frequency,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_switch"){let{switches:i}=await lo("switches",{switch_type:e.type,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_led"){let{leds:i}=await lo("leds",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_fuse"){let{fuses:i}=await lo("fuses",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}return{}}};var hU=Xt(lU(),1);K();var yU=Xt(Sn(),1),gU=Xt(Sn(),1),ii=p.tuple([p.coerce.number(),p.coerce.number()]),iMt=p.tuple([p.number(),p.number(),p.number()]),Ux=p.union([ii,iMt]),oMt=p.object({kind:p.literal("arc"),start:ii,mid:ii,end:ii}),rMt=p.union([ii,oMt]),dU=p.object({at:Ux,size:ii,layer:p.string(),layers:p.array(p.string()),roundrect_rratio:p.number(),uuid:p.string()}).partial(),sMt=p.object({key:p.string(),val:p.string(),attributes:dU}),Vx=p.object({oval:p.boolean().default(!1),width:p.number().optional(),height:p.number().optional(),offset:ii.optional()}),fU=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:Ux,drill:p.union([p.number(),p.array(p.any()),Vx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:ii.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?ii.parse(e[3].slice(1)):void 0}:e).pipe(Vx),size:p.union([p.array(p.number()).length(2).transform(([e,t])=>({width:e,height:t})),p.object({width:p.number(),height:p.number()})]),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),uuid:p.string().optional()}),mU=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:Ux,size:ii,drill:p.union([p.number(),p.array(p.any()),Vx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:ii.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?ii.parse(e[3].slice(1)):void 0}:e).pipe(Vx).optional(),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),chamfer_ratio:p.number().optional(),solder_paste_margin:p.number().optional(),solder_paste_margin_ratio:p.number().optional(),clearance:p.number().optional(),zone_connection:p.union([p.literal(0).describe("Pad is not connect to zone"),p.literal(1).describe("Pad is connected to zone using thermal relief"),p.literal(2).describe("Pad is connected to zone using solid fill")]).optional(),thermal_width:p.number().optional(),thermal_gap:p.number().optional(),uuid:p.string().optional()}),_U=p.object({font:p.object({size:ii,thickness:p.number().optional()})}).partial(),aMt=p.object({fp_text_type:p.literal("user"),text:p.string(),at:Ux,layer:p.string(),uuid:p.string().optional(),effects:_U.partial()}),cMt=p.object({start:ii,mid:ii,end:ii,stroke:p.object({width:p.number(),type:p.string()}),layer:p.string(),uuid:p.string().optional()}),lMt=p.object({center:ii,end:ii,stroke:p.object({width:p.number(),type:p.string()}),fill:p.string().optional(),layer:p.string(),uuid:p.string().optional()}),uMt=p.object({pts:p.array(rMt),stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional(),fill:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),pMt=p.object({start:ii,end:ii,stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),uU=p.object({footprint_name:p.string(),version:p.string().optional(),generator:p.string().optional(),generator_version:p.string().optional(),layer:p.string(),descr:p.string().default(""),tags:p.array(p.string()).optional(),properties:p.array(sMt),fp_lines:p.array(pMt),fp_texts:p.array(aMt),fp_arcs:p.array(cMt),fp_circles:p.array(lMt).optional(),fp_polys:p.array(uMt).optional(),pads:p.array(mU),holes:p.array(fU).optional()}),Hx=(e,t)=>{if(t==="effects"&&Array.isArray(e)){let n={};for(let i of e)if(i[0]==="font"){let o={};for(let r of i.slice(1))r.length===2?o[r[0].valueOf()]=Number.parseFloat(r[1].valueOf()):o[r[0].valueOf()]=r.slice(1).map(s=>Number.parseFloat(s.valueOf()));n.font=o}return _U.parse(n)}if(t==="pts")return e.map(n=>{let i=n[0]?.valueOf?.()??n[0];if(i==="xy")return n.slice(1).map(o=>Number.parseFloat(o.valueOf()));if(i==="arc"){let o={kind:"arc"};for(let r of n.slice(1)){let s=r[0].valueOf();o[s]=r.slice(1).map(a=>Number.parseFloat(a.valueOf()))}return o}return n});if(t==="stroke"){let n={};for(let i of e){let o=i[0].valueOf();n[o]=Hx(i.slice(1),o)}return n}return t==="at"||t==="size"||t==="start"||t==="mid"||t==="end"?(Array.isArray(e)?e:[e]).map(i=>i?.valueOf?.()??i).filter(i=>typeof i=="number"||typeof i=="string"&&/^[-+]?\d*\.?\d+(e[-+]?\d+)?$/i.test(i)).map(i=>typeof i=="number"?i:Number.parseFloat(i)):t==="tags"?e.map(n=>n.valueOf()):t==="generator_version"||t==="version"?e[0].valueOf():e.length===2?e.valueOf():t==="uuid"?Array.isArray(e)?e[0].valueOf():e.valueOf():/^[\d\.]+$/.test(e)&&!Number.isNaN(Number.parseFloat(e))?Number.parseFloat(e):Array.isArray(e)&&e.length===1?e[0].valueOf():Array.isArray(e)?e.map(n=>n.valueOf()):e},Re=(e,t)=>{for(let n of e)if(Array.isArray(n)&&n[0]===t)return Hx(n.slice(1),t)},G4=(0,yU.default)("kicad-mod-converter"),hMt=e=>{let t=(0,hU.default)(e),n=t[1].valueOf(),i={},o=Object.entries(uU.shape).filter(([T,I])=>I._def.typeName==="ZodString"||T==="tags").map(([T])=>T);for(let T of t.slice(2)){if(!o.includes(T[0]))continue;let I=T[0].valueOf(),E=Hx(T.slice(1),I);i[I]=E}let r=t.slice(2).filter(T=>T[0]==="property").map(T=>{let I=T[1].valueOf(),E=T[2].valueOf(),M=dU.parse(T.slice(3).reduce((k,N)=>{let A=N[0].valueOf();return k[A]=Hx(N.slice(1),A),k},{}));return{key:I,val:E,attributes:M}}),s=t.slice(2).filter(T=>T[0]==="pad"),a=[];for(let T of s){let I=Re(T,"at"),E=Re(T,"size"),M=Re(T,"drill"),k=Re(T,"layers");if(Array.isArray(k)?k=k.map($=>$.valueOf()):typeof k=="string"?k=[k]:k||(k=[]),!k.includes("F.Cu")){G4(`Skipping pad without F.Cu layer: layers=${k.join(", ")}`);continue}let N=Re(T,"roundrect_rratio"),A=Re(T,"uuid"),R={name:T[1].valueOf(),pad_type:T[2].valueOf(),pad_shape:T[3].valueOf(),at:I,drill:M,size:E,layers:k,roundrect_rratio:N,uuid:A};G4(`attempting to parse pad: ${JSON.stringify(R,null," ")}`),a.push(mU.parse(R))}let c=t.slice(2).filter(T=>T[0]==="fp_text"),l=[];for(let T of c){let I=T[2].valueOf(),E=Re(T,"at"),M=Re(T,"layer"),k=Re(T,"uuid"),N=Re(T,"effects");l.push({fp_text_type:"user",text:I,at:E,layer:M,uuid:k,effects:N})}let u=[],h=t.slice(2).filter(T=>T[0]==="fp_line");for(let T of h){let I=Re(T,"start"),E=Re(T,"end"),M=Re(T,"stroke"),k=Re(T,"layer"),N=Re(T,"uuid");u.push({start:I,end:E,stroke:M,layer:k,uuid:N})}let d=[],_=t.slice(2).filter(T=>T[0]==="fp_arc");for(let T of _){let I=Re(T,"start"),E=Re(T,"mid"),M=Re(T,"end"),k=Re(T,"stroke"),N=Re(T,"layer"),A=Re(T,"uuid");!I||!M||!E||!k||!N||d.push({start:I,mid:E,end:M,stroke:k,layer:N,uuid:A})}let y=[],g=t.slice(2).filter(T=>T[0]==="fp_circle");for(let T of g){let I=Re(T,"center"),E=Re(T,"end"),M=Re(T,"stroke"),k=Re(T,"fill"),N=Re(T,"layer"),A=Re(T,"uuid");!I||!E||!M||!N||y.push({center:I,end:E,stroke:M,fill:k,layer:N,uuid:A})}let x=[],w=t.slice(2).filter(T=>T[0]==="fp_poly");for(let T of w){let I=Re(T,"pts"),E=Re(T,"stroke"),M=Re(T,"width"),k=Re(T,"layer"),N=Re(T,"uuid"),A=Re(T,"fill"),R=E;!R&&typeof M=="number"?R={width:M,type:"solid"}:R&&typeof R=="object"&&typeof M=="number"&&R.width===void 0&&(R={...R,width:M}),x.push({pts:I,stroke:R,layer:k,uuid:N,fill:A})}let S=[];for(let T of t.slice(2)){if(T[0]!=="pad"||T[2]?.valueOf?.()!=="thru_hole")continue;let I=T[1]?.valueOf?.(),E=T[2]?.valueOf?.(),M=T[3]?.valueOf?.(),k=Re(T,"at"),N=Re(T,"drill"),A=Re(T,"size");Array.isArray(A)&&(A[0]==="size"&&(A=A.slice(1)),A={width:Number(A[0]),height:Number(A[1])});let R=Re(T,"uuid"),$=Re(T,"roundrect_rratio"),j=Re(T,"layers");Array.isArray(j)?j=j.map(X=>X.valueOf()):typeof j=="string"?j=[j]:j||(j=[]);let H={name:I,pad_type:E,pad_shape:M,at:k,drill:N,size:A,layers:j,roundrect_rratio:$,uuid:R};G4(`attempting to parse holes: ${JSON.stringify(H,null,2)}`),S.push(fU.parse(H))}return uU.parse({footprint_name:n,...i,properties:r,fp_lines:u,fp_texts:l,fp_arcs:d,fp_circles:y,pads:a,holes:S,fp_polys:x})},zm=Math.PI*2,pU=e=>{let t=e%zm;return t<0&&(t+=zm),t},Gx=(e,t)=>{let n=pU(e),o=pU(t)-n;return o<0&&(o+=zm),o};function bU(e,t,n){let i={x:(e.x+t.x)/2,y:(e.y+t.y)/2},o={x:(t.x+n.x)/2,y:(t.y+n.y)/2},r=-(e.x-t.x)/(e.y-t.y),s=-(t.x-n.x)/(t.y-n.y),a=(i.y-o.y+s*o.x-r*i.x)/(s-r),c=i.y+r*(a-i.x);return{x:a,y:c}}function xU(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Zh(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var Z4=(e,t,n)=>{let i=bU(e,t,n),o=xU(i,e),r=Zh(i,e),s=Zh(i,t),a=Zh(i,n),c=Gx(r,s),l=Gx(r,a),u=l;return c>l&&(u=l-zm),Math.abs(o*u)};function K4(e,t,n,i){let o=bU(e,t,n),r=xU(o,e),s=Zh(o,e),a=Zh(o,t),c=Zh(o,n),l=Gx(s,a),u=Gx(s,c),h=u;l>u&&(h=u-zm);let d=[];for(let _=0;_<=i;_++){let y=s+_/i*h,g=o.x+r*Math.cos(y),x=o.y+r*Math.sin(y);d.push({x:g,y:x})}return d}var Mc=e=>Array.isArray(e)?{x:e[0],y:e[1]}:e,U4=(e,t,n=1e-4)=>Math.abs(e.x-t.x)<n&&Math.abs(e.y-t.y)<n,dMt=e=>{let t=[],n=new Set;for(let i=0;i<e.length;i++){if(n.has(i))continue;let o=[e[i]];n.add(i);let r=e[i].end,s=!0;for(;s;){if(s=!1,o.length>1&&U4(r,o[0].start)){t.push(o);break}for(let a=0;a<e.length;a++)if(!n.has(a)){if(U4(r,e[a].start)){o.push(e[a]),n.add(a),r=e[a].end,s=!0;break}else if(U4(r,e[a].end)){e[a].type==="arc"?o.push({...e[a],reversed:!0}):o.push({...e[a],start:e[a].end,end:e[a].start}),n.add(a),r=e[a].start,s=!0;break}}if(!s){for(let a=o.length-1;a>=0;a--){let c=e.indexOf(o[a]);c!==-1&&n.delete(c)}break}}}return t},fMt=e=>{let t=[];for(let n of e)if(n.type==="line")t.push(n.start);else if(n.type==="arc"&&n.mid){let i=Z4(n.start,n.mid,n.end),o=Math.max(3,Math.ceil(i)),r=K4(n.start,n.mid,n.end,o);n.reversed&&(r=r.reverse()),t.push(...r.slice(0,-1))}return t};function mMt(e){if(!Array.isArray(e))return null;let t=e.find(s=>s.layer?.toLowerCase()==="f.silks"&&(s.text?.includes("${REFERENCE}")||s.fp_text_type?.toLowerCase()==="reference"||s.text?.match(/^R\d+|C\d+|U\d+/))),n=t||e.find(s=>s.layer?.toLowerCase()==="f.fab"&&(s.text?.includes("${REFERENCE}")||s.fp_text_type?.toLowerCase()==="reference")),i=t||n;if(!i?.effects?.font?.size)return null;let[o,r]=i.effects.font.size;return r??o??1}var _Mt=e=>e*Math.PI/180,q4=(e,t,n)=>{let i=_Mt(n),o=Math.cos(i),r=Math.sin(i);return{x:e*o-t*r,y:e*r+t*o}},yMt=e=>{let t=[...new Map(e.map(u=>[`${u.x},${u.y}`,u])).values()];if(t.length!==4)return null;let n=t.map(u=>u.x),i=t.map(u=>u.y),o=[...new Set(n)],r=[...new Set(i)];if(o.length!==2||r.length!==2)return null;let[s,a]=o.sort((u,h)=>u-h),[c,l]=r.sort((u,h)=>u-h);return s===void 0||a===void 0||c===void 0||l===void 0?null:{x:(s+a)/2,y:(c+l)/2,width:a-s,height:l-c}},gMt=e=>{if(!e)return!1;let t=e.toLowerCase();return t!=="no"&&t!=="none"&&t!=="outline"},W4=e=>e&&Array.isArray(e)&&e.length>=3&&typeof e[2]=="number"?e[2]:0,Co=e=>{let t=(e%360+360)%360;return t===90||t===270},Wh=(0,gU.default)("kicad-mod-converter"),_r=e=>{switch(e.toLowerCase()){case"f.cu":case"f.fab":case"f.silks":case"edge.cuts":return"top";case"b.cu":case"b.fab":case"b.silks":return"bottom"}},bMt=async e=>{let{fp_lines:t,fp_texts:n,fp_arcs:i,fp_circles:o,pads:r,properties:s,holes:a,fp_polys:c}=e,l=[];l.push({type:"source_component",source_component_id:"source_component_0",supplier_part_numbers:{}}),l.push({type:"schematic_component",schematic_component_id:"schematic_component_0",source_component_id:"source_component_0",center:{x:0,y:0},rotation:0,size:{width:0,height:0}});let u=new Set;for(let V of r)V.name&&u.add(V.name);if(a)for(let V of a)V.name&&u.add(V.name);let h=0,d=new Map;for(let V of u){let rt=`source_port_${h++}`;d.set(V,rt),l.push({type:"source_port",source_port_id:rt,source_component_id:"source_component_0",name:V,port_hints:[V]}),l.push({type:"schematic_port",schematic_port_id:`schematic_port_${h++}`,source_port_id:rt,schematic_component_id:"schematic_component_0",center:{x:0,y:0}})}let _=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,g=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY;for(let V of r){let rt=V.at[0],et=-V.at[1],J=V.size[0],pt=V.size[1];_=Math.min(_,rt-J/2),y=Math.max(y,rt+J/2),g=Math.min(g,et-pt/2),x=Math.max(x,et+pt/2)}let w="pcb_component_0";l.push({type:"pcb_component",source_component_id:"source_component_0",pcb_component_id:w,layer:"top",center:{x:0,y:0},rotation:0,width:Number.isFinite(_)?y-_:0,height:Number.isFinite(g)?x-g:0});let S=0,T=new Map;for(let V of u){let rt=`pcb_port_${S++}`,et=d.get(V);T.set(V,rt);let J=0,pt=0,ht=["top","bottom"],St=r.find(wt=>wt.name===V);if(St)J=St.at[0],pt=-St.at[1],ht=St.layers?St.layers.map(wt=>_r(wt)).filter(Boolean):["top","bottom"];else if(a){let wt=a.find(lt=>lt.name===V);wt&&(J=wt.at[0],pt=-wt.at[1],ht=wt.layers?wt.layers.map(lt=>_r(lt)).filter(Boolean):["top","bottom"])}l.push({type:"pcb_port",pcb_port_id:rt,source_port_id:et,pcb_component_id:w,x:J,y:pt,layers:ht})}let I=0,E=0,M=0;for(let V of r)if(V.pad_type==="smd"){let rt=W4(V.at),et=Co(rt)?V.size[1]:V.size[0],J=Co(rt)?V.size[0]:V.size[1],pt=V.name?T.get(V.name):void 0;l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${I++}`,shape:"rect",x:V.at[0],y:-V.at[1],width:et,height:J,layer:_r(V.layers?.[0]??"F.Cu"),pcb_component_id:w,port_hints:[V.name],pcb_port_id:pt})}else if(V.pad_type==="thru_hole"){if(V.pad_shape==="rect"){let rt=W4(V.at),et=Co(rt)?V.size[1]:V.size[0],J=Co(rt)?V.size[0]:V.size[1],pt=V.drill?.offset?.[0]??0,ht=V.drill?.offset?.[1]??0,St=q4(pt,ht,rt),wt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:V.at[0],y:-V.at[1],hole_offset_x:St.x,hole_offset_y:-St.y,hole_diameter:V.drill?.width,rect_pad_width:et,rect_pad_height:J,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:wt})}else if(V.pad_shape==="circle"){let rt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circle",x:V.at[0],y:-V.at[1],outer_diameter:V.size[0],hole_diameter:V.drill?.width,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:rt})}else if(V.pad_shape==="oval"){let rt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"pill",x:V.at[0],y:-V.at[1],outer_width:V.size[0],outer_height:V.size[1],hole_width:V.drill?.width,hole_height:V.drill?.height,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:rt})}}else V.pad_type==="np_thru_hole"&&l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${M++}`,x:V.at[0],y:-V.at[1],hole_diameter:V.drill?.width,pcb_component_id:w});if(a)for(let V of a){let rt=V.layers?.some(ut=>ut.endsWith(".Cu")||ut==="*.Cu"),et=W4(V.at),J=V.drill?.offset?.[0]??0,pt=V.drill?.offset?.[1]??0,ht=q4(J,pt,et),St=V.at[0]+ht.x,wt=-(V.at[1]+ht.y),lt=V.drill?.width??0,B=V.size?.width??lt,q=V.roundrect_rratio??0,it=q>0?Math.min(Co(et)?V.size?.height??B:V.size?.width??B,Co(et)?V.size?.width??B:V.size?.height??B)/2*q:0;if(rt)if(V.pad_shape==="rect"){let ut=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:V.at[0],y:-V.at[1],hole_offset_x:ht.x,hole_offset_y:-ht.y,hole_diameter:lt,rect_pad_width:Co(et)?V.size?.height??B:V.size?.width??B,rect_pad_height:Co(et)?V.size?.width??B:V.size?.height??B,rect_border_radius:it,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ut})}else if(V.pad_shape==="oval"){let ut=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"pill",x:St,y:wt,outer_width:Co(et)?V.size?.height??B:V.size?.width??B,outer_height:Co(et)?V.size?.width??B:V.size?.height??B,hole_width:Co(et)?V.drill?.height??lt:V.drill?.width??lt,hole_height:Co(et)?V.drill?.width??lt:V.drill?.height??lt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ut})}else if(V.pad_shape==="roundrect"){let ut=V.name?T.get(V.name):void 0,_t=V.drill?.offset?.[0]??0,W=V.drill?.offset?.[1]??0,at=q4(_t,W,et),Mt=Co(et)?V.size?.height??B:V.size?.width??B,Ot=Co(et)?V.size?.width??B:V.size?.height??B;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:St,y:wt,hole_offset_x:at.x,hole_offset_y:-at.y,hole_diameter:lt,rect_pad_width:Mt,rect_pad_height:Ot,rect_border_radius:it,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ut})}else{let ut=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circle",x:St,y:wt,outer_diameter:B,hole_diameter:lt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ut})}else l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${M++}`,x:St,y:wt,hole_diameter:B,hole_shape:"circle",pcb_component_id:w})}let k=[];for(let V of t)V.layer.toLowerCase()==="edge.cuts"&&k.push({type:"line",start:{x:V.start[0],y:V.start[1]},end:{x:V.end[0],y:V.end[1]},strokeWidth:V.stroke.width});for(let V of i)V.layer.toLowerCase()==="edge.cuts"&&k.push({type:"arc",start:{x:V.start[0],y:V.start[1]},mid:{x:V.mid[0],y:V.mid[1]},end:{x:V.end[0],y:V.end[1]},strokeWidth:V.stroke.width});let N=dMt(k),A=0;for(let V of N){let rt=fMt(V);rt.length>=3&&l.push({type:"pcb_cutout",pcb_cutout_id:`pcb_cutout_${A++}`,shape:"polygon",points:rt.map(et=>({x:et.x,y:-et.y})),pcb_component_id:w})}let R=0,$=0,j=0,H=0;for(let V of t){let rt=[{x:V.start[0],y:-V.start[1]},{x:V.end[0],y:-V.end[1]}],et=V.layer.toLowerCase();et==="f.cu"?l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:w,layer:_r(V.layer),route:rt,thickness:V.stroke.width}):et==="f.silks"?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,pcb_component_id:w,layer:"top",route:rt,stroke_width:V.stroke.width}):et==="edge.cuts"?Wh("Skipping Edge.Cuts fp_line (converted to pcb_cutout)",V.layer):et==="f.fab"?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${j++}`,pcb_component_id:w,layer:"top",route:rt,stroke_width:V.stroke.width,port_hints:[]}):et.startsWith("user.")?l.push({type:"pcb_note_line",pcb_note_line_id:`pcb_note_line_${H++}`,pcb_component_id:w,x1:V.start[0],y1:-V.start[1],x2:V.end[0],y2:-V.end[1],stroke_width:V.stroke.width}):Wh("Unhandled layer for fp_line",V.layer)}if(c)for(let V of c){let rt=[],et=wt=>{!Number.isFinite(wt.x)||!Number.isFinite(wt.y)||rt.push(wt)};for(let wt of V.pts){if(Array.isArray(wt)){et({x:wt[0],y:-wt[1]});continue}if(wt&&typeof wt=="object"&&"kind"in wt){if(wt.kind==="arc"){let lt=Mc(wt.start),B=Mc(wt.mid),q=Mc(wt.end),it=Z4(lt,B,q),ut=Math.max(8,Math.ceil(it)),_t=Math.max(2,Math.ceil(it/.1)),W=K4(lt,B,q,_t).map(at=>({x:at.x,y:-at.y}));for(let at of W)et(at)}continue}}let J=rt,ht=J.length>2&&J[0].x===J[J.length-1].x&&J[0].y===J[J.length-1].y?J.slice(0,-1):J;if(J.length===0)continue;let St=V.stroke?.width??0;if(V.layer.endsWith(".Cu")){let wt=yMt(ht);wt?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${I++}`,shape:"rect",x:wt.x,y:wt.y,width:wt.width,height:wt.height,layer:_r(V.layer),pcb_component_id:w}):gMt(V.fill)?ht.length>=3?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${I++}`,shape:"polygon",points:ht,layer:_r(V.layer),pcb_component_id:w}):ht.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:w,layer:_r(V.layer),route:ht,thickness:St}):ht.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:w,layer:_r(V.layer),route:ht,thickness:St})}else V.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,pcb_component_id:w,layer:_r(V.layer),route:J,stroke_width:St}):V.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${j++}`,pcb_component_id:w,layer:_r(V.layer),route:ht,stroke_width:St,port_hints:[]}):Wh("Unhandled layer for fp_poly",V.layer)}let X=0;for(let V of i){let rt=V.layer.toLowerCase();if(rt==="edge.cuts"){Wh("Skipping Edge.Cuts fp_arc (converted to pcb_cutout)",V.layer);continue}let et=Mc(V.start),J=Mc(V.mid),pt=Mc(V.end),ht=Z4(et,J,pt),St=K4(et,J,pt,Math.ceil(ht));if(rt.startsWith("user.")){l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${X++}`,pcb_component_id:w,route:St.map(lt=>({x:lt.x,y:-lt.y})),stroke_width:V.stroke.width});continue}let wt=_r(V.layer);if(!wt){Wh("Unable to convert layer for fp_arc",V.layer);continue}l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,layer:wt,pcb_component_id:w,route:St.map(lt=>({x:lt.x,y:-lt.y})),stroke_width:V.stroke.width})}if(o)for(let V of o){let rt=V.layer.toLowerCase(),et=Mc(V.center),J=Mc(V.end),pt=Math.sqrt((J.x-et.x)**2+(J.y-et.y)**2),ht=Math.max(16,Math.ceil(2*Math.PI*pt)),St=[];for(let wt=0;wt<=ht;wt++){let lt=wt/ht*2*Math.PI;St.push({x:et.x+pt*Math.cos(lt),y:et.y+pt*Math.sin(lt)})}rt.startsWith("user.")&&l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${X++}`,pcb_component_id:w,route:St.map(wt=>({x:wt.x,y:-wt.y})),stroke_width:V.stroke.width})}for(let V of n){let rt=_r(V.layer);V.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_text",layer:rt,font:"tscircuit2024",font_size:V.effects?.font?.size[0]??1,pcb_component_id:w,anchor_position:{x:V.at[0],y:-V.at[1]},anchor_alignment:"center",text:V.text}):V.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_text",layer:rt,font:"tscircuit2024",font_size:V.effects?.font?.size[0]??1,pcb_component_id:w,anchor_position:{x:V.at[0],y:-V.at[1]},anchor_alignment:"center",text:V.text}):Wh("Unhandled layer for fp_text",V.layer)}let G=s.find(V=>V.key==="Reference"),tt=s.find(V=>V.key==="Value"),Q=[G,tt].filter(V=>V&&!!V.val);for(let V of Q){let rt=V.attributes.at;if(!rt)continue;let J=V.attributes.layer?.toLowerCase()?.endsWith(".fab"),pt=mMt(n);l.push({type:J?"pcb_fabrication_note_text":"pcb_silkscreen_text",layer:"top",font:"tscircuit2024",font_size:pt,pcb_component_id:w,anchor_position:{x:rt[0],y:-rt[1]},anchor_alignment:"center",text:V.val})}return l},vU=async e=>{let t=hMt(e);return await bMt(t)};var SU=async e=>{try{return(await import(e)).default}catch{console.log(`Failed to load ${e} locally, trying CDN fallback...`);try{let n=await fetch(`https://cdn.jsdelivr.net/npm/${e}/+esm`);if(!n.ok)throw new Error(`Failed to fetch ${e} from CDN: ${n.statusText}`);let i=await n.text(),o=new Blob([i],{type:"application/javascript"}),r=URL.createObjectURL(o);try{let{default:s}=await import(r);return s}finally{URL.revokeObjectURL(r)}}catch(n){throw console.error(`CDN fallback for ${e} also failed:`,n),n}}};var xMt="https://kicad-mod-cache.tscircuit.com",qx=null,wU=()=>({partsEngine:cU,spiceEngineMap:{ngspice:{simulate:async e=>{if(!qx){let t=await SU("@tscircuit/ngspice-spice-engine").catch(n=>{throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.",{cause:n})});t&&(qx=await t())}if(!qx)throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.");return qx.simulate(e)}}},footprintLibraryMap:{kicad:async e=>{let t=`${xMt}/${e}`,n=`${t}.circuit.json`,o=await(await fetch(n)).json(),r=Array.isArray(o)?o.filter(a=>a?.type==="pcb_silkscreen_text"?a?.text==="REF**":!0):o,s=`${t}.wrl`;return{footprintCircuitJson:r,cadModel:{wrlUrl:s,modelUnitToMmScale:2.54}}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async e=>{let t=await fetch(e).then(i=>i.text()),n=await vU(t);return{footprintCircuitJson:Array.isArray(n)?n:[n]}}}}});var J4=Xt(Sn(),1),Ooe=(0,J4.default)("tsci:eval:execution-context");function Wx(e,t={}){globalThis.React=PU;let n=t.platform||wU(),i=t.projectConfig?{...n,...t.projectConfig}:n;i.partsEngineDisabled&&(i.partsEngine=void 0);let o=new Uh({platform:i});t.name&&(o.name=t.name),t.debugNamespace&&o.enableDebug(t.debugNamespace);let r=[];return{fsMap:{},entrypoint:"",logger:{info:s=>{r.push({msg:s})},getLogs:()=>r,stringifyLogs:()=>r.map(s=>s.msg).join(`
254
254
  `)},preSuppliedImports:{"@tscircuit/core":Yx,tscircuit:Yx,"@tscircuit/math-utils":YI,react:PU,debug:J4.default,"@tscircuit/props":{}},circuit:o,tsConfig:null,importStack:[],currentlyImporting:new Set,...e}}function Cc(e){let t=e;return t=t.replace(/\\/g,"/"),t=t.trim(),t.startsWith("./")&&(t=t.slice(2)),t.startsWith("/")&&(t=t.slice(1)),t}function IU(e){let t={};for(let[n,i]of Object.entries(e))t[Cc(n)]=i;return t}function jr(e){if(!e)return".";let n=e.replace(/\\/g,"/").replace(/\/+$/,"");return n.indexOf("/")===-1?".":n.substring(0,n.lastIndexOf("/"))||"/"}function Zx(e,t){if(e.startsWith("../")){let n=jr(t);return Zx(e.slice(3),n)}return e.startsWith("./")?Zx(e.slice(2),t):e.startsWith("/")?e.slice(1):`${t}/${e}`}function Dm(e){if(Array.isArray(e))return null;let t=e["tsconfig.json"];if(!t)return null;try{let n=t.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,"");return JSON.parse(n)}catch(n){throw new Error(`Failed to parse tsconfig.json: ${n.message}`)}}function TU(e){let{importPath:t,normalizedFilePathMap:n,extensions:i,tsConfig:o}=e,r=o?.compilerOptions?.paths;if(!r)return null;let s=o?.compilerOptions?.baseUrl||".",a=l=>{let u=Cc(l);if(n.has(u))return n.get(u);for(let h of i){let d=`${u}.${h}`;if(n.has(d))return n.get(d)}return null};for(let[l,u]of Object.entries(r))if(l.includes("*")){let[d,_]=l.split("*");if(!t.startsWith(d)||!t.endsWith(_||""))continue;let y=t.slice(d.length,t.length-(_?_.length:0));for(let g of u){let x=g.replace("*",y),w=s&&!x.startsWith("./")&&!x.startsWith("/")?`${s}/${x}`:x,S=a(w);if(S)return S}}else{if(t!==l)continue;for(let d of u){let _=s&&!d.startsWith("./")&&!d.startsWith("/")?`${s}/${d}`:d,y=a(_);if(y)return y}}let c=Q4({importPath:t,normalizedFilePathMap:n,extensions:i,tsConfig:o});return c||null}function Q4(e){let{importPath:t,normalizedFilePathMap:n,extensions:i,tsConfig:o}=e,r=o?.compilerOptions?.baseUrl;if(!r)return null;let s=`${r}/${t}`,a=Cc(s);if(n.has(a))return n.get(a);for(let c of i){let l=`${a}.${c}`;if(n.has(l))return n.get(l)}return null}function MU(e,t){let n=t?.compilerOptions?.paths;if(!n)return!1;for(let[i]of Object.entries(n))if(i.includes("*")){let[r,s]=i.split("*");if(e.startsWith(r)&&e.endsWith(s||""))return!0}else if(e===i)return!0;return!1}var $m=(e,t,n,i={})=>{let o=n?Zx(e,n):e,r=new Set(Array.isArray(t)?t:Object.keys(t));if(r.has(o))return o;let s=new Map;for(let u of r)s.set(Cc(u),u);let a=Cc(o);if(s.has(a))return s.get(a);let c=["tsx","ts","json","js","jsx","obj","gltf","glb"];for(let u of c){let h=`${a}.${u}`;if(s.has(h))return s.get(h)}let l=i.tsConfig??null;if(!e.startsWith("./")&&!e.startsWith("../")){let u=TU({importPath:e,normalizedFilePathMap:s,extensions:c,tsConfig:l});if(u)return u;let h=Q4({importPath:e,normalizedFilePathMap:s,extensions:c,tsConfig:l});if(h)return h}if(!e.startsWith("./")&&!e.startsWith("../")){let u=Cc(e);if(s.has(u))return s.get(u);for(let h of c){let d=`${u}.${h}`;if(s.has(d))return s.get(d)}}return null},Kx=(e,t,n,i={})=>{let o=$m(e,t,n,i);if(!o)throw new Error(`File not found "${e}", available paths: