@tscircuit/eval 0.0.535 → 0.0.536

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.
@@ -156,7 +156,7 @@ svg { font-family: 'Inter', 'Helvetica Neue', Arial, sans-serif; }
156
156
  :is(button, input, select, textarea, optgroup, option)[disabled],
157
157
  optgroup[disabled] > option,
158
158
  fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *)
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 Is=Vt(id(),1);var s4={};function o4(n,e){return n===Is.default.falseFunc?Is.default.falseFunc:t=>e.isTag(t)&&n(t)}function a4(n,e){let t=e.getSiblings(n);if(t.length<=1)return[];let i=t.indexOf(n);return i<0||i===t.length-1?[]:t.slice(i+1).filter(e.isTag)}function r4(n){return{xmlMode:!!n.xmlMode,lowerCaseAttributeNames:!!n.lowerCaseAttributeNames,lowerCaseTags:!!n.lowerCaseTags,quirksMode:!!n.quirksMode,cacheResults:!!n.cacheResults,pseudos:n.pseudos,adapter:n.adapter,equals:n.equals}}var i4=(n,e,t,i,r)=>{let s=r(e,r4(t),i);return s===Is.default.trueFunc?n:s===Is.default.falseFunc?Is.default.falseFunc:o=>s(o)&&n(o)},yS={is:i4,matches:i4,where:i4,not(n,e,t,i,r){let s=r(e,r4(t),i);return s===Is.default.falseFunc?n:s===Is.default.trueFunc?Is.default.falseFunc:o=>!s(o)&&n(o)},has(n,e,t,i,r){let{adapter:s}=t,o=r4(t);o.relativeSelector=!0;let a=e.some(u=>u.some(Mg))?[s4]:void 0,c=r(e,o,a);if(c===Is.default.falseFunc)return Is.default.falseFunc;let l=o4(c,s);if(a&&c!==Is.default.trueFunc){let{shouldTestNextSiblings:u=!1}=c;return p=>{if(!n(p))return!1;a[0]=p;let d=s.getChildren(p),_=u?[...d,...a4(p,s)]:d;return s.existsOne(l,_)}}return u=>n(u)&&s.existsOne(l,s.getChildren(u))}};function oW(n,e,t,i,r){var s;let{name:o,data:a}=e;if(Array.isArray(a)){if(!(o in yS))throw new Error(`Unknown pseudo-class :${o}(${a})`);return yS[o](n,a,t,i,r)}let c=(s=t.pseudos)===null||s===void 0?void 0:s[o],l=typeof c=="string"?c:n4[o];if(typeof l=="string"){if(a!=null)throw new Error(`Pseudo ${o} doesn't have any arguments`);let u=Tg(l);return yS.is(n,u,t,i,r)}if(typeof c=="function")return e4(c,o,a,1),u=>c(u,a)&&n(u);if(o in Cg)return Cg[o](n,a,t,i);if(o in _S){let u=_S[o];return e4(u,o,a,2),p=>u(p,t,a)&&n(p)}throw new Error(`Unknown pseudo-class :${o}`)}function c4(n,e){let t=e.getParent(n);return t&&e.isTag(t)?t:null}function aW(n,e,t,i,r){let{adapter:s,equals:o}=t;switch(e.type){case me.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case me.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case me.Attribute:{if(e.namespace!=null)throw new Error("Namespaced attributes are not yet supported by css-select");return(!t.xmlMode||t.lowerCaseAttributeNames)&&(e.name=e.name.toLowerCase()),nW[e.action](n,e,t)}case me.Pseudo:return oW(n,e,t,i,r);case me.Tag:{if(e.namespace!=null)throw new Error("Namespaced tag names are not yet supported by css-select");let{name:a}=e;return(!t.xmlMode||t.lowerCaseTags)&&(a=a.toLowerCase()),function(l){return s.getName(l)===a&&n(l)}}case me.Descendant:{if(t.cacheResults===!1||typeof WeakSet>"u")return function(l){let u=l;for(;u=c4(u,s);)if(n(u))return!0;return!1};let a=new WeakSet;return function(l){let u=l;for(;u=c4(u,s);)if(!a.has(u)){if(s.isTag(u)&&n(u))return!0;a.add(u)}return!1}}case"_flexibleDescendant":return function(c){let l=c;do if(n(l))return!0;while(l=c4(l,s));return!1};case me.Parent:return function(c){return s.getChildren(c).some(l=>s.isTag(l)&&n(l))};case me.Child:return function(c){let l=s.getParent(c);return l!=null&&s.isTag(l)&&n(l)};case me.Sibling:return function(c){let l=s.getSiblings(c);for(let u=0;u<l.length;u++){let p=l[u];if(o(c,p))break;if(s.isTag(p)&&n(p))return!0}return!1};case me.Adjacent:return s.prevElementSibling?function(c){let l=s.prevElementSibling(c);return l!=null&&n(l)}:function(c){let l=s.getSiblings(c),u;for(let p=0;p<l.length;p++){let d=l[p];if(o(c,d))break;s.isTag(d)&&(u=d)}return!!u&&n(u)};case me.Universal:{if(e.namespace!=null&&e.namespace!=="*")throw new Error("Namespaced universal selectors are not yet supported by css-select");return n}}}function cW(n,e,t){let i=gS(n,e,t);return o4(i,e.adapter)}function gS(n,e,t){let i=typeof n=="string"?Tg(n):n;return xS(i,e,t)}function lW(n){return n.type===me.Pseudo&&(n.name==="scope"||Array.isArray(n.data)&&n.data.some(e=>e.some(lW)))}var WEt={type:me.Descendant},HEt={type:"_flexibleDescendant"},qEt={type:me.Pseudo,name:"scope",data:null};function ZEt(n,{adapter:e},t){let i=!!t?.every(r=>{let s=e.isTag(r)&&e.getParent(r);return r===s4||s&&e.isTag(s)});for(let r of n){if(!(r.length>0&&Mg(r[0])&&r[0].type!==me.Descendant))if(i&&!r.some(lW))r.unshift(WEt);else continue;r.unshift(qEt)}}function xS(n,e,t){var i;n.forEach(J5),t=(i=e.context)!==null&&i!==void 0?i:t;let r=Array.isArray(t),s=t&&(Array.isArray(t)?t:[t]);if(e.relativeSelector!==!1)ZEt(n,e,s);else if(n.some(c=>c.length>0&&Mg(c[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let o=!1,a=n.map(c=>{if(c.length>=2){let[l,u]=c;l.type!==me.Pseudo||l.name!=="scope"||(r&&u.type===me.Descendant?c[1]=HEt:(u.type===me.Adjacent||u.type===me.Sibling)&&(o=!0))}return KEt(c,e,s)}).reduce(JEt,Ra.default.falseFunc);return a.shouldTestNextSiblings=o,a}function KEt(n,e,t){var i;return n.reduce((r,s)=>r===Ra.default.falseFunc?Ra.default.falseFunc:aW(r,s,e,t,xS),(i=e.rootFunc)!==null&&i!==void 0?i:Ra.default.trueFunc)}function JEt(n,e){return e===Ra.default.falseFunc||n===Ra.default.trueFunc?n:n===Ra.default.falseFunc||e===Ra.default.trueFunc?e:function(i){return n(i)||e(i)}}var uW=(n,e)=>n===e,QEt={adapter:fS,equals:uW};function pW(n){var e,t,i,r;let s=n??QEt;return(e=s.adapter)!==null&&e!==void 0||(s.adapter=fS),(t=s.equals)!==null&&t!==void 0||(s.equals=(r=(i=s.adapter)===null||i===void 0?void 0:i.equals)!==null&&r!==void 0?r:uW),s}function u4(n){return function(t,i,r){let s=pW(i);return n(t,s,r)}}var Sne=u4(cW),wne=u4(gS),Pne=u4(xS);function hW(n){return function(t,i,r){let s=pW(r);typeof t!="function"&&(t=gS(t,s,i));let o=tCt(i,s.adapter,t.shouldTestNextSiblings);return n(t,o,s)}}function tCt(n,e,t=!1){return t&&(n=eCt(n,e)),Array.isArray(n)?e.removeSubsets(n):e.getChildren(n)}function eCt(n,e){let t=Array.isArray(n)?n.slice(0):[n],i=t.length;for(let r=0;r<i;r++){let s=a4(t[r],e);t.push(...s)}return t}var p4=hW((n,e,t)=>n===l4.default.falseFunc||!e||e.length===0?[]:t.adapter.findAll(n,e)),bS=hW((n,e,t)=>n===l4.default.falseFunc||!e||e.length===0?null:t.adapter.findOne(n,e));tt();vt();tt();var UW=Vt(Nn(),1);vt();var WW=Vt(Nn(),1),qW=Vt(Nn(),1);vt();li();g4();var x4=(n,e={})=>{let t=n._internal_store;if(!t){t={counts:{}},n._internal_store=t;for(let r of n){let s=r.type,o=r[`${s}_id`];if(!o)continue;let a=Number.parseInt(o.split("_").pop());Number.isNaN(a)||(t.counts[s]=Math.max(t.counts[s]??0,a))}}return new Proxy({},{get:(r,s)=>s==="toArray"?()=>n:{get:o=>n.find(a=>a.type===s&&a[`${s}_id`]===o),getUsing:o=>{let a=Object.keys(o);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=n.find(p=>p.type===l&&p[c]===o[c]);return u?n.find(p=>p.type===s&&p[`${s}_id`]===u[`${s}_id`]):null},getWhere:o=>{let a=Object.keys(o);return n.find(c=>c.type===s&&a.every(l=>c[l]===o[l]))},list:o=>{let a=o?Object.keys(o):[];return n.filter(c=>c.type===s&&a.every(l=>c[l]===o[l]))},insert:o=>{var l;(l=t.counts)[s]??(l[s]=-1),t.counts[s]++;let a=t.counts[s],c={type:s,[`${s}_id`]:`${s}_${a}`,...o};return e.validateInserts&&(Zh[s]??qh).parse(c),n.push(c),c},delete:o=>{let a=n.find(c=>c[`${s}_id`]===o);a&&n.splice(n.indexOf(a),1)},update:(o,a)=>{let c=n.find(l=>l.type===s&&l[`${s}_id`]===o);if(c)return Object.assign(c,a),c},select:o=>{if(s==="source_component")return n.find(a=>a.type==="source_component"&&a.name===o.replace(/\./g,""));if(s==="pcb_port"||s==="source_port"||s==="schematic_port"){let[a,c]=o.replace(/\./g,"").split(/[\s\>]+/),l=n.find(p=>p.type==="source_component"&&p.name===a);if(!l)return null;let u=n.find(p=>p.type==="source_port"&&p.source_component_id===l.source_component_id&&(p.name===c||(p.port_hints??[]).includes(c)));if(!u)return null;if(s==="source_port")return u;if(s==="pcb_port")return n.find(p=>p.type==="pcb_port"&&p.source_port_id===u.source_port_id);if(s==="schematic_port")return n.find(p=>p.type==="schematic_port"&&p.source_port_id===u.source_port_id)}}}})};x4.unparsed=x4;var TW=x4;var Mre=Vt(EW(),1);mr();function oo(n){let e=n.width/2,t=n.height/2;return{minX:n.center.x-e,maxX:n.center.x+e,minY:n.center.y-t,maxY:n.center.y+t}}function Lg(n,e){let t=oo(n),i=oo(e),r=Math.max(t.minX-i.maxX,i.minX-t.maxX,0),s=Math.max(t.minY-i.maxY,i.minY-t.maxY,0),o={x:0,y:0},a={x:0,y:0};return r===0&&s===0?{distance:0,pointA:n.center,pointB:e.center}:(o.x=Hn(n.center.x,i.minX,i.maxX),o.y=Hn(n.center.y,i.minY,i.maxY),a.x=Hn(e.center.x,t.minX,t.maxX),a.y=Hn(e.center.y,t.minY,t.maxY),{distance:Math.hypot(o.x-a.x,o.y-a.y),pointA:o,pointB:a})}function Fo(n,e){return Lg(n,e)}function w4(n,e){let t=oo(n),i=oo(e),r=Math.max(t.minX-i.maxX,i.minX-t.maxX,0),s=Math.max(t.minY-i.maxY,i.minY-t.maxY,0);return Math.hypot(r,s)}function Hn(n,e,t){return Math.max(e,Math.min(t,n))}function Fg(n,e){let t=Number.POSITIVE_INFINITY,i={x:0,y:0},r={x:0,y:0};for(let s of n)for(let o of e){let{distance:a,pointA:c,pointB:l}=Lg(s,o);a<t&&(t=a,i=c,r=l)}return{pointA:i,pointB:r,distance:t}}mr();mr();var LW="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var FW=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=LW[t[n]&63];return e};mr();var ud=(n,e)=>Math.abs(n.x-e.x)+Math.abs(n.y-e.y),zW=(n,e)=>{let t=e.x-n.x,i=e.y-n.y;return Math.abs(t)>Math.abs(i)?{dx:Math.sign(t),dy:0}:{dx:0,dy:Math.sign(i)}},YW=(n,e,t)=>Math.abs(n.x-e.x)*Math.abs(t.dx)+Math.abs(n.y-e.y)*Math.abs(t.dy),XW=(n,e=.1)=>`${Math.round(n.x/e)},${Math.round(n.y/e)}`,$W=(n,e)=>Math.abs(n-e)<1e-4,VW=(n,e,{viaDiameter:t=.5}={})=>{let i=[];for(let r=0;r<n.length-1;r++){let[s,o]=[n[r],n[r+1]],a=r-1>=0?n[r-1]:null,c=$W(s.y,o.y),l=$W(s.x,o.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${s.x}, ${s.y}), end: (${o.x}, ${o.y})`);let u={type:"rect",layers:[s.layer],center:{x:(s.x+o.x)/2,y:(s.y+o.y)/2},width:c?Math.abs(s.x-o.x):.1,height:l?Math.abs(s.y-o.y):.1,connectedTo:[e]};if(i.push(u),a&&a.layer===s.layer&&s.layer!==o.layer){let p={type:"rect",layers:[s.layer,o.layer],center:{x:s.x,y:s.y},connectedTo:[e],width:t,height:t};i.push(p)}}return i},GW=class{constructor(n){f(this,"obstacles");f(this,"GRID_STEP",.1);this.obstacles=n.map(e=>({...e,left:e.center.x-e.width/2,right:e.center.x+e.width/2,top:e.center.y+e.height/2,bottom:e.center.y-e.height/2}))}getObstacleAt(n,e,t){t??(t=this.GRID_STEP);for(let i of this.obstacles){let r=i.width/2+t,s=i.height/2+t;if(n>=i.center.x-r&&n<=i.center.x+r&&e>=i.center.y-s&&e<=i.center.y+s)return i}return null}isObstacleAt(n,e,t){return this.getObstacleAt(n,e,t)!==null}getDirectionDistancesToNearestObstacle(n,e){let{GRID_STEP:t}=this,i={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let r of this.obstacles)if(r.type==="rect"){let s=r.center.x-r.width/2-t,o=r.center.x+r.width/2+t,a=r.center.y+r.height/2+t,c=r.center.y-r.height/2-t;e>=c&&e<=a&&n>s&&(i.left=Math.min(i.left,n-o)),e>=c&&e<=a&&n<o&&(i.right=Math.min(i.right,s-n)),n>=s&&n<=o&&e<a&&(i.top=Math.min(i.top,c-e)),n>=s&&n<=o&&e>c&&(i.bottom=Math.min(i.bottom,e-a))}return i}getOrthoDirectionCollisionInfo(n,e,{margin:t=0}={}){let{x:i,y:r}=n,{dx:s,dy:o}=e,a=1/0,c=null;for(let l of this.obstacles){let u=l.left-t,p=l.right+t,d=l.top+t,_=l.bottom-t,g=null;s===1&&o===0?r>_&&r<d&&i<l.left&&(g=l.left-i):s===-1&&o===0?r>_&&r<d&&i>l.right&&(g=i-l.right):s===0&&o===1?i>u&&i<p&&r<l.bottom&&(g=l.bottom-r):s===0&&o===-1&&i>u&&i<p&&r>l.top&&(g=r-l.top),g!==null&&g<a&&(a=g,c=l)}return{dx:s,dy:o,wallDistance:a,obstacle:c}}getObstaclesOverlappingRegion(n){let e=[];for(let t of this.obstacles){let{left:i,right:r,top:s,bottom:o}=t;i<=n.maxX&&r>=n.minX&&s<=n.maxY&&o>=n.minY&&e.push(t)}return e}};function aCt(n){if(n.length<4)return n;let e=[{...n[0]}],t=n[0].layer;for(let i=1;i<n.length;i++){let r={start:n[i-1],end:n[i]},s=n[i].route_type==="via"||n[i-1].route_type==="via";if(n[i].layer!==t||s){e.push({...n[i]}),t=n[i].layer;continue}let o=!1,a=null,c=-1;for(let u=0;u<e.length-1;u++){let p={start:e[u],end:e[u+1]};if(p.start.layer===r.start.layer&&p.start.layer===r.start.layer){let d=cCt(p,r);if(d){o=!0,a={...d,layer:t},c=u;break}}}o&&a&&(e.splice(c+1),e.push(a));let l=e[e.length-1];(l.x!==n[i].x||l.y!==n[i].y)&&e.push(n[i])}return e}function cCt(n,e){if(n.start.x===n.end.x&&e.start.x===e.end.x||n.start.y===n.end.y&&e.start.y===e.end.y)return null;let t;if(n.start.x===n.end.x){let i=n.start.x,r=e.start.y;t={...n.start,x:i,y:r}}else{let i=e.start.x,r=n.start.y;t={...n.start,x:i,y:r}}return DW(t,n)&&DW(t,e)?t:null}function DW(n,e){return n.x>=Math.min(e.start.x,e.end.x)&&n.x<=Math.max(e.start.x,e.end.x)&&n.y>=Math.min(e.start.y,e.end.y)&&n.y<=Math.max(e.start.y,e.end.y)}function lCt(n){let e=[n[0]];for(let t=1;t<n.length-1;t++){let[i,r,s]=[n[t-1],n[t],n[t+1]];e.push(r),!(r.route_type!=="wire"||i.route_type!=="wire"||s.route_type!=="wire")&&i.layer===r.layer&&r.layer!==s.layer&&e.push({route_type:"via",from_layer:r.layer,to_layer:s.layer,x:r.x,y:r.y})}return e.push(n[n.length-1]),e}var kre=(0,WW.default)("autorouter:shortenPathWithShortcuts");function uCt(n,e){if(n.length<=2)return n;let t=[n[0]];for(let i=1;i<n.length;i++){let r={start:t[t.length-1],end:n[i]},s=-1,o=r.start.x===r.end.x,a=r.start.y===r.end.y;for(let c=i+1;c<n.length;c++){if(c<=s)continue;let l={start:n[c],end:n[c+1]};if(!l.end)continue;let u=l.start.x===l.end.x,p=l.start.y===l.end.y,d=o&&u,_=a&&p;if(_&&d||!(d||_))continue;let x=!1,b=Math.min(r.start.x,r.end.x),S=Math.max(r.start.x,r.end.x),P=Math.min(l.start.x,l.end.x),T=Math.max(l.start.x,l.end.x),k=Math.min(r.start.y,r.end.y),N=Math.max(r.start.y,r.end.y),M=Math.min(l.start.y,l.end.y),C=Math.max(l.start.y,l.end.y);if(_?x=b<=T&&S>=P:d&&(x=k<=C&&N>=M),!x)continue;let E=[],R=t[t.length-1],A=n[c+2];if(!A)continue;_&&P<S&&A.x===P&&E.push({x:P,y:r.start.y,layer:r.start.layer}),_&&T>b&&A.x===T&&E.push({x:T,y:r.start.y,layer:r.start.layer}),d&&M<N&&A.y===M&&E.push({x:r.start.x,y:M,layer:r.start.layer}),d&&C>k&&A.y===C&&E.push({x:r.start.x,y:C,layer:r.start.layer});let j=null;for(let D of E)if(!(e(R,D)||e(A,D))){j=D;break}if(j){t.push(j),i=c+1,s=c+1;break}}s===-1&&t.push(n[i])}return t[t.length-1]!==n[n.length-1]&&t.push(n[n.length-1]),t}var ld=(0,UW.default)("autorouting-dataset:astar"),HW=class{constructor(n){f(this,"openSet",[]);f(this,"closedSet",new Set);f(this,"debug",!1);f(this,"debugSolutions");f(this,"debugMessage",null);f(this,"debugTraceCount",0);f(this,"input");f(this,"obstacles");f(this,"allObstacles");f(this,"startNode");f(this,"goalPoint");f(this,"GRID_STEP");f(this,"OBSTACLE_MARGIN");f(this,"MAX_ITERATIONS");f(this,"isRemovePathLoopsEnabled");f(this,"isShortenPathWithShortcutsEnabled");f(this,"GREEDY_MULTIPLIER",1.1);f(this,"iterations",-1);this.input=n.input,this.allObstacles=n.input.obstacles,this.startNode=n.startNode,this.goalPoint=n.goalPoint?{l:0,...n.goalPoint}:void 0,this.GRID_STEP=n.GRID_STEP??.1,this.OBSTACLE_MARGIN=n.OBSTACLE_MARGIN??.15,this.MAX_ITERATIONS=n.MAX_ITERATIONS??100,this.debug=n.debug??ld.enabled,this.isRemovePathLoopsEnabled=n.isRemovePathLoopsEnabled??!1,this.isShortenPathWithShortcutsEnabled=n.isShortenPathWithShortcutsEnabled??!1,this.debug&&(ld.enabled=!0),ld.enabled&&(this.debugSolutions={},this.debugMessage="")}getNeighbors(n){return[]}isSameNode(n,e){return ud(n,e)<this.GRID_STEP}computeG(n,e){return n.g+ud(n,e)}computeH(n){return ud(n,this.goalPoint)}getNodeName(n){return XW(n,this.GRID_STEP)}solveOneStep(){this.iterations+=1;let{openSet:n,closedSet:e,GRID_STEP:t,goalPoint:i}=this;n.sort((a,c)=>a.f-c.f);let r=n.shift();if(this.computeH(r)<=t*2)return{solved:!0,current:r,newNeighbors:[]};this.closedSet.add(this.getNodeName(r));let o=[];for(let a of this.getNeighbors(r)){if(e.has(this.getNodeName(a)))continue;let c=this.computeG(r,a),l=this.openSet.find(u=>this.isSameNode(u,a));if(!l||c<l.g){let u=this.computeH(a),p=c+u*this.GREEDY_MULTIPLIER,d={...a,g:c,h:u,f:p,obstacleHit:a.obstacleHit??void 0,manDistFromParent:ud(r,a),nodesInPath:r.nodesInPath+1,parent:r,enterMarginCost:a.enterMarginCost,travelMarginCostFactor:a.travelMarginCostFactor};n.push(d),o.push(d)}}return ld.enabled&&(n.sort((a,c)=>a.f-c.f),this.drawDebugSolution({current:r,newNeighbors:o})),{solved:!1,current:r,newNeighbors:o}}getStartNode(n){return{x:n.pointsToConnect[0].x,y:n.pointsToConnect[0].y,manDistFromParent:0,f:0,g:0,h:0,nodesInPath:0,parent:null}}layerToIndex(n){return 0}indexToLayer(n){return"top"}preprocessConnectionBeforeSolving(n){return n}solveConnection(n){if(n.pointsToConnect.length>2)throw new Error("GeneralizedAstarAutorouter doesn't currently support 2+ points in a connection");n=this.preprocessConnectionBeforeSolving(n);let{pointsToConnect:e}=n;for(this.iterations=0,this.closedSet=new Set,this.startNode=this.getStartNode(n),this.goalPoint={...e[e.length-1],l:this.layerToIndex(e[e.length-1].layer)},this.openSet=[this.startNode];this.iterations<this.MAX_ITERATIONS;){let{solved:t,current:i}=this.solveOneStep();if(t){let r=[],s=i;for(;s;){let o=s.l;r.unshift({x:s.x,y:s.y,layer:o!==void 0?this.indexToLayer(o):e[0].layer}),s=s.parent}return ld.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations
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 Is=Vt(id(),1);var s4={};function o4(n,e){return n===Is.default.falseFunc?Is.default.falseFunc:t=>e.isTag(t)&&n(t)}function a4(n,e){let t=e.getSiblings(n);if(t.length<=1)return[];let i=t.indexOf(n);return i<0||i===t.length-1?[]:t.slice(i+1).filter(e.isTag)}function r4(n){return{xmlMode:!!n.xmlMode,lowerCaseAttributeNames:!!n.lowerCaseAttributeNames,lowerCaseTags:!!n.lowerCaseTags,quirksMode:!!n.quirksMode,cacheResults:!!n.cacheResults,pseudos:n.pseudos,adapter:n.adapter,equals:n.equals}}var i4=(n,e,t,i,r)=>{let s=r(e,r4(t),i);return s===Is.default.trueFunc?n:s===Is.default.falseFunc?Is.default.falseFunc:o=>s(o)&&n(o)},yS={is:i4,matches:i4,where:i4,not(n,e,t,i,r){let s=r(e,r4(t),i);return s===Is.default.falseFunc?n:s===Is.default.trueFunc?Is.default.falseFunc:o=>!s(o)&&n(o)},has(n,e,t,i,r){let{adapter:s}=t,o=r4(t);o.relativeSelector=!0;let a=e.some(u=>u.some(Mg))?[s4]:void 0,c=r(e,o,a);if(c===Is.default.falseFunc)return Is.default.falseFunc;let l=o4(c,s);if(a&&c!==Is.default.trueFunc){let{shouldTestNextSiblings:u=!1}=c;return p=>{if(!n(p))return!1;a[0]=p;let d=s.getChildren(p),_=u?[...d,...a4(p,s)]:d;return s.existsOne(l,_)}}return u=>n(u)&&s.existsOne(l,s.getChildren(u))}};function oW(n,e,t,i,r){var s;let{name:o,data:a}=e;if(Array.isArray(a)){if(!(o in yS))throw new Error(`Unknown pseudo-class :${o}(${a})`);return yS[o](n,a,t,i,r)}let c=(s=t.pseudos)===null||s===void 0?void 0:s[o],l=typeof c=="string"?c:n4[o];if(typeof l=="string"){if(a!=null)throw new Error(`Pseudo ${o} doesn't have any arguments`);let u=Tg(l);return yS.is(n,u,t,i,r)}if(typeof c=="function")return e4(c,o,a,1),u=>c(u,a)&&n(u);if(o in Cg)return Cg[o](n,a,t,i);if(o in _S){let u=_S[o];return e4(u,o,a,2),p=>u(p,t,a)&&n(p)}throw new Error(`Unknown pseudo-class :${o}`)}function c4(n,e){let t=e.getParent(n);return t&&e.isTag(t)?t:null}function aW(n,e,t,i,r){let{adapter:s,equals:o}=t;switch(e.type){case me.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case me.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case me.Attribute:{if(e.namespace!=null)throw new Error("Namespaced attributes are not yet supported by css-select");return(!t.xmlMode||t.lowerCaseAttributeNames)&&(e.name=e.name.toLowerCase()),nW[e.action](n,e,t)}case me.Pseudo:return oW(n,e,t,i,r);case me.Tag:{if(e.namespace!=null)throw new Error("Namespaced tag names are not yet supported by css-select");let{name:a}=e;return(!t.xmlMode||t.lowerCaseTags)&&(a=a.toLowerCase()),function(l){return s.getName(l)===a&&n(l)}}case me.Descendant:{if(t.cacheResults===!1||typeof WeakSet>"u")return function(l){let u=l;for(;u=c4(u,s);)if(n(u))return!0;return!1};let a=new WeakSet;return function(l){let u=l;for(;u=c4(u,s);)if(!a.has(u)){if(s.isTag(u)&&n(u))return!0;a.add(u)}return!1}}case"_flexibleDescendant":return function(c){let l=c;do if(n(l))return!0;while(l=c4(l,s));return!1};case me.Parent:return function(c){return s.getChildren(c).some(l=>s.isTag(l)&&n(l))};case me.Child:return function(c){let l=s.getParent(c);return l!=null&&s.isTag(l)&&n(l)};case me.Sibling:return function(c){let l=s.getSiblings(c);for(let u=0;u<l.length;u++){let p=l[u];if(o(c,p))break;if(s.isTag(p)&&n(p))return!0}return!1};case me.Adjacent:return s.prevElementSibling?function(c){let l=s.prevElementSibling(c);return l!=null&&n(l)}:function(c){let l=s.getSiblings(c),u;for(let p=0;p<l.length;p++){let d=l[p];if(o(c,d))break;s.isTag(d)&&(u=d)}return!!u&&n(u)};case me.Universal:{if(e.namespace!=null&&e.namespace!=="*")throw new Error("Namespaced universal selectors are not yet supported by css-select");return n}}}function cW(n,e,t){let i=gS(n,e,t);return o4(i,e.adapter)}function gS(n,e,t){let i=typeof n=="string"?Tg(n):n;return xS(i,e,t)}function lW(n){return n.type===me.Pseudo&&(n.name==="scope"||Array.isArray(n.data)&&n.data.some(e=>e.some(lW)))}var WEt={type:me.Descendant},HEt={type:"_flexibleDescendant"},qEt={type:me.Pseudo,name:"scope",data:null};function ZEt(n,{adapter:e},t){let i=!!t?.every(r=>{let s=e.isTag(r)&&e.getParent(r);return r===s4||s&&e.isTag(s)});for(let r of n){if(!(r.length>0&&Mg(r[0])&&r[0].type!==me.Descendant))if(i&&!r.some(lW))r.unshift(WEt);else continue;r.unshift(qEt)}}function xS(n,e,t){var i;n.forEach(J5),t=(i=e.context)!==null&&i!==void 0?i:t;let r=Array.isArray(t),s=t&&(Array.isArray(t)?t:[t]);if(e.relativeSelector!==!1)ZEt(n,e,s);else if(n.some(c=>c.length>0&&Mg(c[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let o=!1,a=n.map(c=>{if(c.length>=2){let[l,u]=c;l.type!==me.Pseudo||l.name!=="scope"||(r&&u.type===me.Descendant?c[1]=HEt:(u.type===me.Adjacent||u.type===me.Sibling)&&(o=!0))}return KEt(c,e,s)}).reduce(JEt,Ra.default.falseFunc);return a.shouldTestNextSiblings=o,a}function KEt(n,e,t){var i;return n.reduce((r,s)=>r===Ra.default.falseFunc?Ra.default.falseFunc:aW(r,s,e,t,xS),(i=e.rootFunc)!==null&&i!==void 0?i:Ra.default.trueFunc)}function JEt(n,e){return e===Ra.default.falseFunc||n===Ra.default.trueFunc?n:n===Ra.default.falseFunc||e===Ra.default.trueFunc?e:function(i){return n(i)||e(i)}}var uW=(n,e)=>n===e,QEt={adapter:fS,equals:uW};function pW(n){var e,t,i,r;let s=n??QEt;return(e=s.adapter)!==null&&e!==void 0||(s.adapter=fS),(t=s.equals)!==null&&t!==void 0||(s.equals=(r=(i=s.adapter)===null||i===void 0?void 0:i.equals)!==null&&r!==void 0?r:uW),s}function u4(n){return function(t,i,r){let s=pW(i);return n(t,s,r)}}var Sne=u4(cW),wne=u4(gS),Pne=u4(xS);function hW(n){return function(t,i,r){let s=pW(r);typeof t!="function"&&(t=gS(t,s,i));let o=tCt(i,s.adapter,t.shouldTestNextSiblings);return n(t,o,s)}}function tCt(n,e,t=!1){return t&&(n=eCt(n,e)),Array.isArray(n)?e.removeSubsets(n):e.getChildren(n)}function eCt(n,e){let t=Array.isArray(n)?n.slice(0):[n],i=t.length;for(let r=0;r<i;r++){let s=a4(t[r],e);t.push(...s)}return t}var p4=hW((n,e,t)=>n===l4.default.falseFunc||!e||e.length===0?[]:t.adapter.findAll(n,e)),bS=hW((n,e,t)=>n===l4.default.falseFunc||!e||e.length===0?null:t.adapter.findOne(n,e));tt();vt();tt();var UW=Vt(Nn(),1);vt();var WW=Vt(Nn(),1),qW=Vt(Nn(),1);vt();li();g4();var x4=(n,e={})=>{let t=n._internal_store;if(!t){t={counts:{}},n._internal_store=t;for(let r of n){let s=r.type,o=r[`${s}_id`];if(!o)continue;let a=Number.parseInt(o.split("_").pop());Number.isNaN(a)||(t.counts[s]=Math.max(t.counts[s]??0,a))}}return new Proxy({},{get:(r,s)=>s==="toArray"?()=>n:{get:o=>n.find(a=>a.type===s&&a[`${s}_id`]===o),getUsing:o=>{let a=Object.keys(o);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=n.find(p=>p.type===l&&p[c]===o[c]);return u?n.find(p=>p.type===s&&p[`${s}_id`]===u[`${s}_id`]):null},getWhere:o=>{let a=Object.keys(o);return n.find(c=>c.type===s&&a.every(l=>c[l]===o[l]))},list:o=>{let a=o?Object.keys(o):[];return n.filter(c=>c.type===s&&a.every(l=>c[l]===o[l]))},insert:o=>{var l;(l=t.counts)[s]??(l[s]=-1),t.counts[s]++;let a=t.counts[s],c={type:s,[`${s}_id`]:`${s}_${a}`,...o};return e.validateInserts&&(Zh[s]??qh).parse(c),n.push(c),c},delete:o=>{let a=n.find(c=>c[`${s}_id`]===o);a&&n.splice(n.indexOf(a),1)},update:(o,a)=>{let c=n.find(l=>l[`${s}_id`]===o);if(c)return Object.assign(c,a),c},select:o=>{if(s==="source_component")return n.find(a=>a.type==="source_component"&&a.name===o.replace(/\./g,""));if(s==="pcb_port"||s==="source_port"||s==="schematic_port"){let[a,c]=o.replace(/\./g,"").split(/[\s\>]+/),l=n.find(p=>p.type==="source_component"&&p.name===a);if(!l)return null;let u=n.find(p=>p.type==="source_port"&&p.source_component_id===l.source_component_id&&(p.name===c||(p.port_hints??[]).includes(c)));if(!u)return null;if(s==="source_port")return u;if(s==="pcb_port")return n.find(p=>p.type==="pcb_port"&&p.source_port_id===u.source_port_id);if(s==="schematic_port")return n.find(p=>p.type==="schematic_port"&&p.source_port_id===u.source_port_id)}}}})};x4.unparsed=x4;var TW=x4;var Mre=Vt(EW(),1);mr();function oo(n){let e=n.width/2,t=n.height/2;return{minX:n.center.x-e,maxX:n.center.x+e,minY:n.center.y-t,maxY:n.center.y+t}}function Lg(n,e){let t=oo(n),i=oo(e),r=Math.max(t.minX-i.maxX,i.minX-t.maxX,0),s=Math.max(t.minY-i.maxY,i.minY-t.maxY,0),o={x:0,y:0},a={x:0,y:0};return r===0&&s===0?{distance:0,pointA:n.center,pointB:e.center}:(o.x=Hn(n.center.x,i.minX,i.maxX),o.y=Hn(n.center.y,i.minY,i.maxY),a.x=Hn(e.center.x,t.minX,t.maxX),a.y=Hn(e.center.y,t.minY,t.maxY),{distance:Math.hypot(o.x-a.x,o.y-a.y),pointA:o,pointB:a})}function Fo(n,e){return Lg(n,e)}function w4(n,e){let t=oo(n),i=oo(e),r=Math.max(t.minX-i.maxX,i.minX-t.maxX,0),s=Math.max(t.minY-i.maxY,i.minY-t.maxY,0);return Math.hypot(r,s)}function Hn(n,e,t){return Math.max(e,Math.min(t,n))}function Fg(n,e){let t=Number.POSITIVE_INFINITY,i={x:0,y:0},r={x:0,y:0};for(let s of n)for(let o of e){let{distance:a,pointA:c,pointB:l}=Lg(s,o);a<t&&(t=a,i=c,r=l)}return{pointA:i,pointB:r,distance:t}}mr();mr();var LW="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var FW=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=LW[t[n]&63];return e};mr();var ud=(n,e)=>Math.abs(n.x-e.x)+Math.abs(n.y-e.y),zW=(n,e)=>{let t=e.x-n.x,i=e.y-n.y;return Math.abs(t)>Math.abs(i)?{dx:Math.sign(t),dy:0}:{dx:0,dy:Math.sign(i)}},YW=(n,e,t)=>Math.abs(n.x-e.x)*Math.abs(t.dx)+Math.abs(n.y-e.y)*Math.abs(t.dy),XW=(n,e=.1)=>`${Math.round(n.x/e)},${Math.round(n.y/e)}`,$W=(n,e)=>Math.abs(n-e)<1e-4,VW=(n,e,{viaDiameter:t=.5}={})=>{let i=[];for(let r=0;r<n.length-1;r++){let[s,o]=[n[r],n[r+1]],a=r-1>=0?n[r-1]:null,c=$W(s.y,o.y),l=$W(s.x,o.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${s.x}, ${s.y}), end: (${o.x}, ${o.y})`);let u={type:"rect",layers:[s.layer],center:{x:(s.x+o.x)/2,y:(s.y+o.y)/2},width:c?Math.abs(s.x-o.x):.1,height:l?Math.abs(s.y-o.y):.1,connectedTo:[e]};if(i.push(u),a&&a.layer===s.layer&&s.layer!==o.layer){let p={type:"rect",layers:[s.layer,o.layer],center:{x:s.x,y:s.y},connectedTo:[e],width:t,height:t};i.push(p)}}return i},GW=class{constructor(n){f(this,"obstacles");f(this,"GRID_STEP",.1);this.obstacles=n.map(e=>({...e,left:e.center.x-e.width/2,right:e.center.x+e.width/2,top:e.center.y+e.height/2,bottom:e.center.y-e.height/2}))}getObstacleAt(n,e,t){t??(t=this.GRID_STEP);for(let i of this.obstacles){let r=i.width/2+t,s=i.height/2+t;if(n>=i.center.x-r&&n<=i.center.x+r&&e>=i.center.y-s&&e<=i.center.y+s)return i}return null}isObstacleAt(n,e,t){return this.getObstacleAt(n,e,t)!==null}getDirectionDistancesToNearestObstacle(n,e){let{GRID_STEP:t}=this,i={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let r of this.obstacles)if(r.type==="rect"){let s=r.center.x-r.width/2-t,o=r.center.x+r.width/2+t,a=r.center.y+r.height/2+t,c=r.center.y-r.height/2-t;e>=c&&e<=a&&n>s&&(i.left=Math.min(i.left,n-o)),e>=c&&e<=a&&n<o&&(i.right=Math.min(i.right,s-n)),n>=s&&n<=o&&e<a&&(i.top=Math.min(i.top,c-e)),n>=s&&n<=o&&e>c&&(i.bottom=Math.min(i.bottom,e-a))}return i}getOrthoDirectionCollisionInfo(n,e,{margin:t=0}={}){let{x:i,y:r}=n,{dx:s,dy:o}=e,a=1/0,c=null;for(let l of this.obstacles){let u=l.left-t,p=l.right+t,d=l.top+t,_=l.bottom-t,g=null;s===1&&o===0?r>_&&r<d&&i<l.left&&(g=l.left-i):s===-1&&o===0?r>_&&r<d&&i>l.right&&(g=i-l.right):s===0&&o===1?i>u&&i<p&&r<l.bottom&&(g=l.bottom-r):s===0&&o===-1&&i>u&&i<p&&r>l.top&&(g=r-l.top),g!==null&&g<a&&(a=g,c=l)}return{dx:s,dy:o,wallDistance:a,obstacle:c}}getObstaclesOverlappingRegion(n){let e=[];for(let t of this.obstacles){let{left:i,right:r,top:s,bottom:o}=t;i<=n.maxX&&r>=n.minX&&s<=n.maxY&&o>=n.minY&&e.push(t)}return e}};function aCt(n){if(n.length<4)return n;let e=[{...n[0]}],t=n[0].layer;for(let i=1;i<n.length;i++){let r={start:n[i-1],end:n[i]},s=n[i].route_type==="via"||n[i-1].route_type==="via";if(n[i].layer!==t||s){e.push({...n[i]}),t=n[i].layer;continue}let o=!1,a=null,c=-1;for(let u=0;u<e.length-1;u++){let p={start:e[u],end:e[u+1]};if(p.start.layer===r.start.layer&&p.start.layer===r.start.layer){let d=cCt(p,r);if(d){o=!0,a={...d,layer:t},c=u;break}}}o&&a&&(e.splice(c+1),e.push(a));let l=e[e.length-1];(l.x!==n[i].x||l.y!==n[i].y)&&e.push(n[i])}return e}function cCt(n,e){if(n.start.x===n.end.x&&e.start.x===e.end.x||n.start.y===n.end.y&&e.start.y===e.end.y)return null;let t;if(n.start.x===n.end.x){let i=n.start.x,r=e.start.y;t={...n.start,x:i,y:r}}else{let i=e.start.x,r=n.start.y;t={...n.start,x:i,y:r}}return DW(t,n)&&DW(t,e)?t:null}function DW(n,e){return n.x>=Math.min(e.start.x,e.end.x)&&n.x<=Math.max(e.start.x,e.end.x)&&n.y>=Math.min(e.start.y,e.end.y)&&n.y<=Math.max(e.start.y,e.end.y)}function lCt(n){let e=[n[0]];for(let t=1;t<n.length-1;t++){let[i,r,s]=[n[t-1],n[t],n[t+1]];e.push(r),!(r.route_type!=="wire"||i.route_type!=="wire"||s.route_type!=="wire")&&i.layer===r.layer&&r.layer!==s.layer&&e.push({route_type:"via",from_layer:r.layer,to_layer:s.layer,x:r.x,y:r.y})}return e.push(n[n.length-1]),e}var kre=(0,WW.default)("autorouter:shortenPathWithShortcuts");function uCt(n,e){if(n.length<=2)return n;let t=[n[0]];for(let i=1;i<n.length;i++){let r={start:t[t.length-1],end:n[i]},s=-1,o=r.start.x===r.end.x,a=r.start.y===r.end.y;for(let c=i+1;c<n.length;c++){if(c<=s)continue;let l={start:n[c],end:n[c+1]};if(!l.end)continue;let u=l.start.x===l.end.x,p=l.start.y===l.end.y,d=o&&u,_=a&&p;if(_&&d||!(d||_))continue;let x=!1,b=Math.min(r.start.x,r.end.x),S=Math.max(r.start.x,r.end.x),P=Math.min(l.start.x,l.end.x),T=Math.max(l.start.x,l.end.x),k=Math.min(r.start.y,r.end.y),N=Math.max(r.start.y,r.end.y),M=Math.min(l.start.y,l.end.y),C=Math.max(l.start.y,l.end.y);if(_?x=b<=T&&S>=P:d&&(x=k<=C&&N>=M),!x)continue;let E=[],R=t[t.length-1],A=n[c+2];if(!A)continue;_&&P<S&&A.x===P&&E.push({x:P,y:r.start.y,layer:r.start.layer}),_&&T>b&&A.x===T&&E.push({x:T,y:r.start.y,layer:r.start.layer}),d&&M<N&&A.y===M&&E.push({x:r.start.x,y:M,layer:r.start.layer}),d&&C>k&&A.y===C&&E.push({x:r.start.x,y:C,layer:r.start.layer});let j=null;for(let D of E)if(!(e(R,D)||e(A,D))){j=D;break}if(j){t.push(j),i=c+1,s=c+1;break}}s===-1&&t.push(n[i])}return t[t.length-1]!==n[n.length-1]&&t.push(n[n.length-1]),t}var ld=(0,UW.default)("autorouting-dataset:astar"),HW=class{constructor(n){f(this,"openSet",[]);f(this,"closedSet",new Set);f(this,"debug",!1);f(this,"debugSolutions");f(this,"debugMessage",null);f(this,"debugTraceCount",0);f(this,"input");f(this,"obstacles");f(this,"allObstacles");f(this,"startNode");f(this,"goalPoint");f(this,"GRID_STEP");f(this,"OBSTACLE_MARGIN");f(this,"MAX_ITERATIONS");f(this,"isRemovePathLoopsEnabled");f(this,"isShortenPathWithShortcutsEnabled");f(this,"GREEDY_MULTIPLIER",1.1);f(this,"iterations",-1);this.input=n.input,this.allObstacles=n.input.obstacles,this.startNode=n.startNode,this.goalPoint=n.goalPoint?{l:0,...n.goalPoint}:void 0,this.GRID_STEP=n.GRID_STEP??.1,this.OBSTACLE_MARGIN=n.OBSTACLE_MARGIN??.15,this.MAX_ITERATIONS=n.MAX_ITERATIONS??100,this.debug=n.debug??ld.enabled,this.isRemovePathLoopsEnabled=n.isRemovePathLoopsEnabled??!1,this.isShortenPathWithShortcutsEnabled=n.isShortenPathWithShortcutsEnabled??!1,this.debug&&(ld.enabled=!0),ld.enabled&&(this.debugSolutions={},this.debugMessage="")}getNeighbors(n){return[]}isSameNode(n,e){return ud(n,e)<this.GRID_STEP}computeG(n,e){return n.g+ud(n,e)}computeH(n){return ud(n,this.goalPoint)}getNodeName(n){return XW(n,this.GRID_STEP)}solveOneStep(){this.iterations+=1;let{openSet:n,closedSet:e,GRID_STEP:t,goalPoint:i}=this;n.sort((a,c)=>a.f-c.f);let r=n.shift();if(this.computeH(r)<=t*2)return{solved:!0,current:r,newNeighbors:[]};this.closedSet.add(this.getNodeName(r));let o=[];for(let a of this.getNeighbors(r)){if(e.has(this.getNodeName(a)))continue;let c=this.computeG(r,a),l=this.openSet.find(u=>this.isSameNode(u,a));if(!l||c<l.g){let u=this.computeH(a),p=c+u*this.GREEDY_MULTIPLIER,d={...a,g:c,h:u,f:p,obstacleHit:a.obstacleHit??void 0,manDistFromParent:ud(r,a),nodesInPath:r.nodesInPath+1,parent:r,enterMarginCost:a.enterMarginCost,travelMarginCostFactor:a.travelMarginCostFactor};n.push(d),o.push(d)}}return ld.enabled&&(n.sort((a,c)=>a.f-c.f),this.drawDebugSolution({current:r,newNeighbors:o})),{solved:!1,current:r,newNeighbors:o}}getStartNode(n){return{x:n.pointsToConnect[0].x,y:n.pointsToConnect[0].y,manDistFromParent:0,f:0,g:0,h:0,nodesInPath:0,parent:null}}layerToIndex(n){return 0}indexToLayer(n){return"top"}preprocessConnectionBeforeSolving(n){return n}solveConnection(n){if(n.pointsToConnect.length>2)throw new Error("GeneralizedAstarAutorouter doesn't currently support 2+ points in a connection");n=this.preprocessConnectionBeforeSolving(n);let{pointsToConnect:e}=n;for(this.iterations=0,this.closedSet=new Set,this.startNode=this.getStartNode(n),this.goalPoint={...e[e.length-1],l:this.layerToIndex(e[e.length-1].layer)},this.openSet=[this.startNode];this.iterations<this.MAX_ITERATIONS;){let{solved:t,current:i}=this.solveOneStep();if(t){let r=[],s=i;for(;s;){let o=s.l;r.unshift({x:s.x,y:s.y,layer:o!==void 0?this.indexToLayer(o):e[0].layer}),s=s.parent}return ld.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations
160
160
  `),this.isRemovePathLoopsEnabled&&(r=aCt(r)),this.isShortenPathWithShortcutsEnabled&&(r=uCt(r,(o,a)=>{if(o.x===a.x&&o.y===a.y)return!1;let c=this.obstacles.getOrthoDirectionCollisionInfo({x:o.x,y:o.y,l:this.layerToIndex(o.layer)??0},{dx:Math.sign(a.x-o.x),dy:Math.sign(a.y-o.y),dl:0},{margin:.05}),l=Math.sqrt((o.x-a.x)**2+(o.y-a.y)**2);return c.wallDistance<l})),{solved:!0,route:r,connectionName:n.name}}if(this.openSet.length===0)break}return ld.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations (failed)
161
161
  `),{solved:!1,connectionName:n.name}}createObstacleList({dominantLayer:n,connection:e,obstaclesFromTraces:t}){return new GW(this.allObstacles.filter(i=>!i.connectedTo.includes(e.name)).filter(i=>i.layers.includes(n)).concat(t??[]))}postprocessConnectionSolveResult(n,e){return e}solve(){let n=[],e=[];this.debugTraceCount=0;for(let t of this.input.connections){let i=t.pointsToConnect[0].layer??"top";this.debugTraceCount+=1,this.obstacles=this.createObstacleList({dominantLayer:i,connection:t,obstaclesFromTraces:e});let r=this.solveConnection(t);r=this.postprocessConnectionSolveResult(t,r),n.push(r),ld.enabled&&this.drawDebugTraceObstacles(e),r.solved&&e.push(...VW(r.route.map(s=>({x:s.x,y:s.y,layer:s.layer??i})),t.name))}return n}solveAndMapToTraces(){return this.solve().flatMap(e=>e.solved?[{type:"pcb_trace",pcb_trace_id:`pcb_trace_for_${e.connectionName}`,route:lCt(e.route.map(t=>({route_type:"wire",x:t.x,y:t.y,width:this.input.minTraceWidth,layer:t.layer})))}]:[])}getDebugGroup(){let n=`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?n:null}drawDebugTraceObstacles(n){let{debugTraceCount:e,debugSolutions:t}=this;for(let i in t)i.startsWith(`t${e}_`)&&t[i].push(...n.map((r,s)=>({type:"pcb_smtpad",pcb_component_id:"",layer:r.layers[0],width:r.width,shape:"rect",x:r.center.x,y:r.center.y,pcb_smtpad_id:`trace_obstacle_${s}`,height:r.height})))}drawDebugSolution({current:n,newNeighbors:e}){let t=this.getDebugGroup();if(!t)return;let{openSet:i,debugTraceCount:r,debugSolutions:s}=this;s[t]??(s[t]=[]);let o=s[t];o.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${n.x}_${n.y}`,font:"tscircuit2024",font_size:.25,text:"X"+(n.l!==void 0?n.l:""),pcb_component_id:"",layer:"top",anchor_position:{x:n.x,y:n.y},anchor_alignment:"center"});for(let a=0;a<i.length;a++){let c=i[a];o.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}),o.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(n.parent){let a=[],c=n;for(;c;)a.unshift(c),c=c.parent;o.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${n.x}_${n.y}`,layer:"top",route:a,stroke_width:.01})}}},pCt=(0,qW.default)("autorouting-dataset:infinite-grid-ijump-astar:get-distance-to-overcome-obstacle");function P4({node:n,travelDir:e,wallDir:t,obstacle:i,obstacles:r,obstaclesInRow:s=0,OBSTACLE_MARGIN:o=.15,SHOULD_DETECT_CONJOINED_OBSTACLES:a=!1,MAX_CONJOINED_OBSTACLES:c=20}){let l;if(e.dx===0?e.dy>0?l=i.center.y+i.height/2-n.y:l=n.y-(i.center.y-i.height/2):e.dx>0?l=i.center.x+i.width/2-n.x:l=n.x-(i.center.x-i.width/2),l+=o,a&&s<c){let u=r.getObstacleAt(n.x+e.dx*l+t.dx*(t.wallDistance+.001),n.y+e.dy*l+t.dy*(t.wallDistance+.001));if(u===i)return l;if(u&&u.type==="rect"){let p=e.dy===0,d=p?i.height:i.width;if((p?u.height:u.width)>d)return pCt("next obstacle on path is bigger, not trying to overcome it"),l;let g=P4({node:{x:n.x+e.dx*l,y:n.y+e.dy*l},travelDir:e,wallDir:t,obstacle:u,obstacles:r,obstaclesInRow:s+1,SHOULD_DETECT_CONJOINED_OBSTACLES:a,MAX_CONJOINED_OBSTACLES:c,OBSTACLE_MARGIN:o});l+=g}}return l}var hCt=class extends HW{constructor(){super(...arguments);f(this,"MAX_ITERATIONS",200)}getNeighbors(e){let t=this.obstacles,i=this.goalPoint,r;e.parent?r=zW(e.parent,e):r=zW(e,i);let s=[{dx:0,dy:1},{dx:1,dy:0},{dx:0,dy:-1},{dx:-1,dy:0}].filter(a=>a.dx===r.dx*-1&&a.dy===r.dy*-1?!1:!(a.dx===r.dx&&a.dy===r.dy&&e.parent?.obstacleHit)).map(a=>t.getOrthoDirectionCollisionInfo(e,a,{margin:this.OBSTACLE_MARGIN})).filter(a=>a.wallDistance>=this.OBSTACLE_MARGIN),o=[];for(let a of s){let c=null;e?.obstacleHit&&(c=P4({node:e,travelDir:a,wallDir:{...r,wallDistance:this.OBSTACLE_MARGIN},obstacle:e.obstacleHit,obstacles:t,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let l=YW(e,i,a),u=(a.dx===0||Math.sign(i.x-e.x)===a.dx)&&(a.dy===0||Math.sign(i.y-e.y)===a.dy);l<a.wallDistance&&l>0&&u?o.push({...a,travelDistance:l}):c!==null&&c<a.wallDistance?o.push({...a,travelDistance:c}):a.wallDistance!==1/0&&o.push({...a,travelDistance:a.wallDistance-this.OBSTACLE_MARGIN})}return o.filter(a=>!t.isObstacleAt(e.x+a.dx*a.travelDistance,e.y+a.dy*a.travelDistance)).map(a=>({x:e.x+a.dx*a.travelDistance,y:e.y+a.dy*a.travelDistance,obstacleHit:a.obstacle}))}};function dCt(n,e=4){let{center:t,width:i,height:r,rotation:s}=n,o=[],a=s*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(s%360+360)%360;if(r<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/e;for(let _=0;_<e;_++){let g=(_-e/2+.5)*d,x=-g*c,b=-g*l,S=d*1.1,P=Math.abs(r*c)+Math.abs(d*l);o.push({center:{x:t.x+x,y:t.y+b},width:S,height:P})}}else{let d=r/e;for(let _=0;_<e;_++){let g=(_-e/2+.5)*d,x=-g*l,b=g*c,S=Math.abs(i*c)+Math.abs(d*l),P=d*1.1;o.push({center:{x:t.x+x,y:t.y+b},width:S,height:P})}}return o}var TS=["top","inner1","inner2","bottom"],ZW=(n,e)=>{let t=r=>e?r.concat(r.map(s=>e?.getNetConnectedToId(s)).filter(Boolean)):r,i=[];for(let r of n)if(r.type==="pcb_smtpad"){if(r.shape==="circle")i.push({type:"oval",layers:[r.layer],center:{x:r.x,y:r.y},width:r.radius*2,height:r.radius*2,connectedTo:t([r.pcb_smtpad_id])});else if(r.shape==="rect")i.push({type:"rect",layers:[r.layer],center:{x:r.x,y:r.y},width:r.width,height:r.height,connectedTo:t([r.pcb_smtpad_id])});else if(r.shape==="rotated_rect"){let s={center:{x:r.x,y:r.y},width:r.width,height:r.height,rotation:r.ccw_rotation},o=dCt(s);for(let a of o)i.push({type:"rect",layers:[r.layer],center:a.center,width:a.width,height:a.height,connectedTo:t([r.pcb_smtpad_id])})}}else if(r.type==="pcb_keepout")r.shape==="circle"?i.push({type:"oval",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.radius*2,height:r.radius*2,connectedTo:[]}):r.shape==="rect"&&i.push({type:"rect",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.type==="pcb_hole")r.hole_shape==="oval"?i.push({type:"oval",center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="square"?i.push({type:"rect",layers:TS,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]}):(r.hole_shape==="round"||r.hole_shape==="circle")&&i.push({type:"rect",layers:TS,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]});else if(r.type==="pcb_plated_hole")r.shape==="circle"?i.push({type:"oval",layers:TS,center:{x:r.x,y:r.y},width:r.outer_diameter,height:r.outer_diameter,connectedTo:t([r.pcb_plated_hole_id])}):(r.shape==="oval"||r.shape==="pill")&&i.push({type:"oval",layers:TS,center:{x:r.x,y:r.y},width:r.outer_width,height:r.outer_height,connectedTo:t([r.pcb_plated_hole_id])});else if(r.type==="pcb_trace"){let s=VW(r.route.map(o=>({x:o.x,y:o.y,layer:"layer"in o?o.layer:o.from_layer})),r.source_trace_id);i.push(...s)}else r.type==="pcb_via"&&i.push({type:"rect",layers:r.layers,center:{x:r.x,y:r.y},connectedTo:[],width:r.outer_diameter,height:r.outer_diameter});return i};function jW(n){let{pcbConnMap:e,goalElementId:t}=n;if(!t.startsWith("pcb_port_"))throw new Error(`Currently alternative goal boxes must have a goal id with prefix "pcb_port_" (got ${t})`);let i=e.getAllTracesConnectedToPort(t);return ZW(i).map(r=>({...r,connectedTo:[t]}))}var KW=n=>{let{connection:e,pcbConnMap:t}=n;if(e.pointsToConnect.length!==2)throw new Error(`Connection must have exactly 2 points for alternative goal boxes (got ${e.pointsToConnect.length})`);let[i,r]=e.pointsToConnect;if(!i.pcb_port_id||!r.pcb_port_id)throw new Error(`Connection points must have pcb_port_id for alternative goal box calculation (got ${i.pcb_port_id} and ${r.pcb_port_id})`);let s=jW({goalElementId:i.pcb_port_id,pcbConnMap:t}).concat([{center:i,width:.01,height:.01,connectedTo:[i.pcb_port_id],layers:[i.layer],type:"rect"}]),o=jW({goalElementId:r.pcb_port_id,pcbConnMap:t}).concat([{center:r,width:.01,height:.01,connectedTo:[r.pcb_port_id],layers:[r.layer],type:"rect"}]);if(s.length<=1&&o.length<=1)return{...e,startPoint:i,endPoint:r,goalBoxes:[]};let a=Fg(s,o),c,l,u;return s.length>=o.length?(c={...r,...a.pointB},l={...i,...a.pointA},u=s):(c={...i,...a.pointA},l={...r,...a.pointB},u=o),{startPoint:c,endPoint:l,goalBoxes:u,name:e.name,pointsToConnect:[c,l]}},fCt=(n,e={})=>{let t={minTraceWidth:.1};t.layerCount=e.layerCount??1,t.obstacles=ZW(n,e.connMap),t.connections=[];for(let r of n)if(r.type==="source_trace"){let s={name:r.source_trace_id,pointsToConnect:r.connected_source_port_ids.map(o=>{let a=TW(n).pcb_port.getWhere({source_port_id:o});if(!a)throw new Error(`Could not find pcb_port for source_port_id "${o}"`);return{x:a.x,y:a.y,layer:a.layers?.[0]??"top",pcb_port_id:a.pcb_port_id}})};if(e.optimizeWithGoalBoxes){let o=new kS(n);s=KW({connection:s,pcbConnMap:o})}t.connections.push(s),mCt(t.obstacles,s.pointsToConnect,s.name)}let i={minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0};for(let r of t.obstacles)i.minX=Math.min(i.minX,r.center.x-r.width/2),i.maxX=Math.max(i.maxX,r.center.x+r.width/2),i.minY=Math.min(i.minY,r.center.y-r.height/2),i.maxY=Math.max(i.maxY,r.center.y+r.height/2);for(let r of t.connections)for(let s of r.pointsToConnect)i.minX=Math.min(i.minX,s.x),i.maxX=Math.max(i.maxX,s.x),i.minY=Math.min(i.minY,s.y),i.maxY=Math.max(i.maxY,s.y);return t.bounds=i,t},mCt=(n,e,t)=>{for(let i of e)for(let r of n)_Ct(i,r)&&r.connectedTo.push(t)};function _Ct(n,e){let t=e.width/2,i=e.height/2;if(e.type==="rect")return n.x>=e.center.x-t&&n.x<=e.center.x+t&&n.y>=e.center.y-i&&n.y<=e.center.y+i;if(e.type==="oval"){let r=(n.x-e.center.x)/t,s=(n.y-e.center.y)/i;return r*r+s*s<=1}return!1}function BW(n,e){let t=e.x>n.x?1:e.x<n.x?-1:0,i=e.y>n.y?1:e.y<n.y?-1:0,r=e.l>n.l?1:e.l<n.l?-1:0;return{dx:t,dy:i,dl:r}}var k4={1:["top"],2:["top","bottom"],4:["top","inner1","inner2","bottom"]},yCt=n=>k4[n];function JW(n,e){let i=k4[n].indexOf(e);if(i===-1)throw new Error(`Invalid layer for getLayerIndex (for layerCount === ${n}): "${e}"`);return i}function gCt(n,e){let i=k4[n][e];if(!i)throw new Error(`Invalid index for indexToLayer (for layerCount === ${n}): "${e}"`);return i}var xCt=class extends GW{constructor(e,t){super([]);f(this,"obstacles");f(this,"GRID_STEP",.1);f(this,"layerCount");this.layerCount=e;let i=yCt(e);this.obstacles=t.flatMap(r=>r.layers.filter(s=>i.includes(s)).map(s=>({...r,left:r.center.x-r.width/2,right:r.center.x+r.width/2,top:r.center.y+r.height/2,bottom:r.center.y-r.height/2,l:JW(e,s)})))}getObstacleAt(e,t,i,r){r??(r=this.GRID_STEP);for(let s of this.obstacles){if(s.l!==i)continue;let o=s.width/2+r,a=s.height/2+r;if(e>=s.center.x-o&&e<=s.center.x+o&&t>=s.center.y-a&&t<=s.center.y+a)return s}return null}isObstacleAt(e,t,i,r){return this.getObstacleAt(e,t,i,r)!==null}getDirectionDistancesToNearestObstacle3d(e,t,i){let{GRID_STEP:r}=this,s={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let o of this.obstacles)if(o.l===i&&o.type==="rect"){let a=o.center.x-o.width/2-r,c=o.center.x+o.width/2+r,l=o.center.y+o.height/2+r,u=o.center.y-o.height/2-r;t>=u&&t<=l&&e>a&&(s.left=Math.min(s.left,e-c)),t>=u&&t<=l&&e<c&&(s.right=Math.min(s.right,a-e)),e>=a&&e<=c&&t<l&&(s.top=Math.min(s.top,u-t)),e>=a&&e<=c&&t>u&&(s.bottom=Math.min(s.bottom,t-l))}return s}getOrthoDirectionCollisionInfo(e,t,{margin:i=0}={}){let{x:r,y:s,l:o}=e,{dx:a,dy:c,dl:l}=t,u=1/0,p=null;if(l!==0){let d=o+l;return this.isObstacleAt(r,s,d,i)?(u=1,p=this.getObstacleAt(r,s,d,i)):u=1,{dx:a,dy:c,dl:l,wallDistance:u,obstacle:p}}else{for(let d of this.obstacles){if(d.l!==o)continue;let _=d.left-i,g=d.right+i,x=d.top+i,b=d.bottom-i,S=null;a===1&&c===0?s>b&&s<x&&r<d.left&&(S=d.left-r):a===-1&&c===0?s>b&&s<x&&r>d.right&&(S=r-d.right):a===0&&c===1?r>_&&r<g&&s<d.bottom&&(S=d.bottom-s):a===0&&c===-1&&r>_&&r<g&&s>d.top&&(S=s-d.top),S!==null&&S<u&&(u=S,p=d)}return{dx:a,dy:c,dl:0,wallDistance:u,obstacle:p}}}getObstaclesOverlappingRegion(e){let t=[];for(let i of this.obstacles){if(i.l!==e.l)continue;let{left:r,right:s,top:o,bottom:a}=i;r<=e.maxX&&s>=e.minX&&o>=e.minY&&a<=e.maxY&&t.push(i)}return t}},MS=class extends HW{constructor(e){super(e);f(this,"MAX_ITERATIONS",500);f(this,"VIA_COST",4);f(this,"VIA_DIAMETER",.5);f(this,"allowLayerChange",!0);f(this,"layerCount");f(this,"obstacles");f(this,"optimizeWithGoalBoxes");f(this,"connMap");f(this,"pcbConnMap");f(this,"GOAL_RUSH_FACTOR",1.1);f(this,"defaultGoalViaMargin",.5);f(this,"marginsWithCosts");this.layerCount=e.input.layerCount??2,this.MAX_ITERATIONS=e.MAX_ITERATIONS??this.MAX_ITERATIONS,this.VIA_COST=e.VIA_COST??this.VIA_COST,this.connMap=e.connMap,this.pcbConnMap=e.pcbConnMap??new kS,this.optimizeWithGoalBoxes=e.optimizeWithGoalBoxes??!1,this.obstacles=null,this.marginsWithCosts=e.marginsWithCosts??[{margin:1,enterCost:0,travelCostFactor:1},{margin:this.OBSTACLE_MARGIN,enterCost:10,travelCostFactor:2}]}get largestMargin(){return this.marginsWithCosts[0].margin}preprocessConnectionBeforeSolving(e){return this.optimizeWithGoalBoxes?KW({connection:e,pcbConnMap:this.pcbConnMap}):e}postprocessConnectionSolveResult(e,t){if(!t.solved)return t;if(this.optimizeWithGoalBoxes){let i=t.route.map(r=>({x:r.x,y:r.y,route_type:"wire",layer:r.layer,width:this.input.minTraceWidth}));i[0].start_pcb_port_id=e.pointsToConnect[0].pcb_port_id,i[i.length-1].end_pcb_port_id=e.pointsToConnect[1].pcb_port_id,this.pcbConnMap.addTrace({type:"pcb_trace",pcb_trace_id:`postprocess_trace_${FW(8)}`,route:i})}return t}createObstacleList({dominantLayer:e,connection:t,obstaclesFromTraces:i}){let r=this.connMap?this.connMap.getNetConnectedToId(t.name):t.name;if(!r)throw new Error(`The connection.name "${t.name}" wasn't present in the full connectivity map`);return new xCt(this.layerCount,this.allObstacles.filter(s=>!s.connectedTo.includes(r)).concat(i??[]))}computeG(e,t){let i=e.g+ud(e,t)*(e.travelMarginCostFactor??1)+(t.enterMarginCost??0);return(t.l??e.l!==-1??-1)&&(i+=this.VIA_COST),i}computeH(e){let t=Math.abs(e.x-this.goalPoint.x),i=Math.abs(e.y-this.goalPoint.y),r=Math.abs(e.l-this.goalPoint.l);return(t+i)**this.GOAL_RUSH_FACTOR+r*this.VIA_COST}getStartNode(e){return{...super.getStartNode(e),l:this.layerToIndex(e.pointsToConnect[0].layer)}}layerToIndex(e){return JW(this.layerCount,e)}indexToLayer(e){return gCt(this.layerCount,e)}getNodeName(e){return`${XW(e,this.GRID_STEP)}-${e.l??0}`}hasSpaceForVia(e,t){return e.every(i=>this.obstacles.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:i}).length===0)}getNeighborsSurroundingGoal(e){let t=this.obstacles,i=this.goalPoint,r=[],s=[{dx:1,dy:0,dl:0},{dx:-1,dy:0,dl:0},{dx:0,dy:1,dl:0},{dx:0,dy:-1,dl:0}],o=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin;for(let a of s){let c={x:e.x+a.dx*o,y:e.y+a.dy*o,l:e.l+a.dl,obstacleHit:null};this.hasSpaceForVia([e.l,i.l],c)&&r.push(c)}return r}getNeighbors(e){let t=this.obstacles,i=this.goalPoint,r=ud(e,i);if(r<=this.OBSTACLE_MARGIN)return this.getNeighborsSurroundingGoal(e);let s;e.parent?s=BW(e.parent,e):s=BW(e,i);let o=[{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=r>this.VIA_DIAMETER+this.OBSTACLE_MARGIN,c=ud(e,this.startNode)>this.VIA_DIAMETER+this.OBSTACLE_MARGIN;this.allowLayerChange&&a&&c&&(e.l<this.layerCount-1&&o.push({dx:0,dy:0,dl:1}),e.l>0&&o.push({dx:0,dy:0,dl:-1}));let l=o.filter(p=>p.dx===s.dx*-1&&p.dy===s.dy*-1&&p.dl===s.dl*-1?!1:!(p.dx===s.dx&&p.dy===s.dy&&p.dl===s.dl&&e.parent?.obstacleHit)).map(p=>t.getOrthoDirectionCollisionInfo(e,p,{margin:this.OBSTACLE_MARGIN})).filter(p=>!(p.wallDistance<this.OBSTACLE_MARGIN)),u=[];for(let p of l){let d=p.dx===0&&p.dy===0&&p.dl===1,_=p.dx===0&&p.dy===0&&p.dl===-1;if((d||_)&&![e.l,e.l+p.dl].every(P=>t.getObstaclesOverlappingRegion({minX:e.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:e.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:e.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:e.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:P}).length===0))continue;if(d){e.l<this.layerCount-1&&u.push({...p,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}if(_){e.l>0&&u.push({...p,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}let g=null;e?.obstacleHit&&(g=P4({node:e,travelDir:p,wallDir:{...s,wallDistance:this.OBSTACLE_MARGIN},obstacle:e.obstacleHit,obstacles:t,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let x=YW(e,i,p),b=(p.dx===0||Math.sign(i.x-e.x)===p.dx)&&(p.dy===0||Math.sign(i.y-e.y)===p.dy);if(x<p.wallDistance&&x>0&&b){let S=e.l===i.l,P=0;!S&&Math.abs(x-r)<this.GRID_STEP&&(P=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin),u.push({...p,travelDistance:x-P,enterMarginCost:0,travelMarginCostFactor:1})}else if(g!==null&&g<p.wallDistance){for(let{margin:S,enterCost:P,travelCostFactor:T}of this.marginsWithCosts)g-this.OBSTACLE_MARGIN+S*2<p.wallDistance&&u.push({...p,travelDistance:g-this.OBSTACLE_MARGIN+S,enterMarginCost:P,travelMarginCostFactor:T});if(p.wallDistance===1/0)u.push({...p,travelDistance:x,enterMarginCost:0,travelMarginCostFactor:1});else if(p.wallDistance>this.largestMargin)for(let{margin:S,enterCost:P,travelCostFactor:T}of this.marginsWithCosts)p.wallDistance>this.largestMargin+S&&u.push({...p,travelDistance:p.wallDistance-S,enterMarginCost:P,travelMarginCostFactor:T})}else if(p.wallDistance!==1/0)for(let{margin:S,enterCost:P,travelCostFactor:T}of this.marginsWithCosts)p.wallDistance>S&&u.push({...p,travelDistance:p.wallDistance-S,enterMarginCost:P,travelMarginCostFactor:T})}return u.map(p=>({x:e.x+p.dx*p.travelDistance,y:e.y+p.dy*p.travelDistance,l:e.l+p.dl,obstacleHit:p.obstacle,travelMarginCostFactor:p.travelMarginCostFactor,enterMarginCost:p.enterMarginCost}))}};function QW(n){let e=fCt(n),t=new hCt({input:e});return{solution:t.solveAndMapToTraces(),debugSolutions:t.debugSolutions,debugMessage:t.debugMessage}}tt();tt();vt();vt();tt();tt();tt();vt();tt();tt();vt();tt();vt();tt();tt();tt();tt();vt();tt();tt();vt();tt();tt();vt();tt();tt();vt();tt();tt();tt();tt();tt();tt();tt();tt();tt();tt();vt();tt();vt();tt();vt();tt();tt();vt();vt();tt();vt();tt();tt();vt();tt();tt();tt();vt();tt();vt();tt();vt();tt();vt();tt();vt();tt();vt();tt();vt();tt();tt();tt();tt();tt();tt();tt();tt();vt();tt();vt();tt();tt();vt();tt();vt();tt();tt();tt();vt();tt();vt();vt();tt();tt();tt();vt();tt();tt();tt();vt();tt();vt();tt();vt();tt();vt();tt();vt();tt();vt();tt();vt();tt();vt();tt();tt();vt();tt();vt();tt();vt();tt();tt();vt();vt();tt();tt();vt();vt();tt();tt();vt();tt();tt();vt();tt();vt();tt();vt();tt();vt();tt();vt();tt();tt();vt();tt();vt();tt();vt();tt();vt();tt();vt();tt();vt();tt();vt();tt();vt();vt();tt();vt();tt();vt();tt();tt();vt();tt();vt();tt();vt();tt();vt();tt();vt();tt();tt();var Ct=n=>{};Ct("extra props b");Ct("missing props b");Ct(!0);Ct("property a has mismatched types");var bCt=h.enum(["up","down","left","right"]),Xre=h.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);Ct(!0);Ct(!0);var ao=h.array(h.string().or(h.number()));Ct(!0);var vCt=h.string().regex(/^calc\(.*\)$/),se=V,$i=vCt.or(V),IS=h.object({x:V,y:V,z:V}),SCt=h.object({x:h.union([h.number(),h.string()]),y:h.union([h.number(),h.string()]),z:h.union([h.number(),h.string()])}),qc=h.object({rotationOffset:h.number().or(SCt).optional(),positionOffset:IS.optional(),size:IS.optional(),modelUnitToMmScale:se.optional(),zOffsetFromSurface:se.optional()});Ct(!0);var wCt=qc.extend({stlUrl:h.string()}),PCt=qc.extend({objUrl:h.string(),mtlUrl:h.string().optional()}),kCt=qc.extend({gltfUrl:h.string()}),TCt=qc.extend({glbUrl:h.string()}),MCt=qc.extend({stepUrl:h.string()}),ECt=qc.extend({wrlUrl:h.string()}),CCt=qc.extend({jscad:h.record(h.any())}),aH=h.union([h.null(),h.string(),h.custom(n=>n&&typeof n=="object"&&"type"in n&&"props"in n),wCt,PCt,kCt,TCt,MCt,ECt,CCt]);Ct(!0);var ICt=h.custom(n=>!0),E4=h.object({silkscreenFontSize:V.optional(),viaPadDiameter:V.optional(),viaHoleDiameter:V.optional(),silkscreenTextPosition:h.union([h.enum(["centered","outside","none"]),h.object({offsetX:h.number(),offsetY:h.number()})]).optional(),silkscreenTextVisibility:h.enum(["hidden","visible","inherit"]).optional()});Ct(!0);var NCt=h.object({defaultPassiveSize:h.union([h.enum(["xs","sm","md"]),V]).optional(),defaultCapacitorOrientation:h.enum(["vertical","none"]).optional()});Ct(!0);var ACt=h.custom(n=>!0),Ye=h.object({pcbX:$i.optional(),pcbY:$i.optional(),pcbLeftEdgeX:$i.optional(),pcbRightEdgeX:$i.optional(),pcbTopEdgeY:$i.optional(),pcbBottomEdgeY:$i.optional(),pcbOffsetX:V.optional(),pcbOffsetY:V.optional(),pcbRotation:en.optional(),pcbPositionAnchor:h.string().optional(),pcbPositionMode:h.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),layer:de.optional(),pcbMarginTop:V.optional(),pcbMarginRight:V.optional(),pcbMarginBottom:V.optional(),pcbMarginLeft:V.optional(),pcbMarginX:V.optional(),pcbMarginY:V.optional(),pcbStyle:E4.optional(),pcbRelative:h.boolean().optional(),relative:h.boolean().optional()});Ct(!0);var NS=h.object({pcbX:$i.optional(),pcbY:$i.optional(),pcbLeftEdgeX:$i.optional(),pcbRightEdgeX:$i.optional(),pcbTopEdgeY:$i.optional(),pcbBottomEdgeY:$i.optional(),pcbOffsetX:V.optional(),pcbOffsetY:V.optional(),pcbRotation:en.optional(),pcbPositionAnchor:h.string().optional(),pcbPositionMode:h.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),pcbMarginTop:V.optional(),pcbMarginRight:V.optional(),pcbMarginBottom:V.optional(),pcbMarginLeft:V.optional(),pcbMarginX:V.optional(),pcbMarginY:V.optional(),pcbStyle:E4.optional(),schMarginTop:V.optional(),schMarginRight:V.optional(),schMarginBottom:V.optional(),schMarginLeft:V.optional(),schMarginX:V.optional(),schMarginY:V.optional(),schX:V.optional(),schY:V.optional(),schRotation:en.optional(),layer:de.optional(),footprint:ICt.optional(),symbol:ACt.optional(),schStyle:NCt.optional(),relative:h.boolean().optional(),schRelative:h.boolean().optional(),pcbRelative:h.boolean().optional()});Ct(!0);var RCt=h.object({supplierPartNumbers:h.record(Dm,h.array(h.string())).optional()});Ct(!0);var OCt=h.object({providesPower:h.boolean().optional(),requiresPower:h.boolean().optional(),providesGround:h.boolean().optional(),requiresGround:h.boolean().optional(),providesVoltage:h.union([h.string(),h.number()]).optional(),requiresVoltage:h.union([h.string(),h.number()]).optional(),doNotConnect:h.boolean().optional(),includeInBoardPinout:h.boolean().optional(),highlightColor:h.string().optional(),mustBeConnected:h.boolean().optional()});Ct(!0);var Qn=NS.merge(RCt).extend({key:h.any().optional(),name:h.string(),cadModel:aH.optional(),children:h.any().optional(),symbolName:h.string().optional(),doNotPlace:h.boolean().optional(),obstructsWithinBounds:h.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"),showAsTranslucentModel:h.boolean().optional().describe("Whether to show this component's CAD model as translucent in the 3D viewer."),pinAttributes:h.record(h.string(),OCt).optional()});Ct(!0);var C4=["pin1","left","pin2","right"],AS=["pin1","left","anode","pos","pin2","right","cathode","neg"],sse=V.or(h.enum(["2x","3x","4x"]));var Zc=h.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 ES=h.object({pins:h.array(h.union([h.number(),h.string()])),direction:h.union([h.literal("top-to-bottom"),h.literal("left-to-right"),h.literal("bottom-to-top"),h.literal("right-to-left")])}),$g=h.object({leftSize:h.number().optional().describe("@deprecated, use leftPinCount"),topSize:h.number().optional().describe("@deprecated, use topPinCount"),rightSize:h.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:h.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:h.number().optional(),rightPinCount:h.number().optional(),topPinCount:h.number().optional(),bottomPinCount:h.number().optional(),leftSide:ES.optional(),rightSide:ES.optional(),topSide:ES.optional(),bottomSide:ES.optional()}),I4=$g;Ct(!0);var Dg=h.record(h.object({marginLeft:V.optional(),marginRight:V.optional(),marginTop:V.optional(),marginBottom:V.optional(),leftMargin:V.optional(),rightMargin:V.optional(),topMargin:V.optional(),bottomMargin:V.optional()}));Ct(!0);var As=h.string().regex(/^[A-Za-z0-9_]+$/),cH=V.or(h.enum(["xs","sm","default","md"])).describe("distance between pin1 and pin2 of the schematic symbol"),a_=h.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),zo=h.object({x:V,y:V}),jg=h.object({edit_event_id:h.string(),in_progress:h.boolean().optional(),created_at:h.number()});Ct(!0);var LCt=jg.extend({pcb_edit_event_type:h.literal("edit_component_location").describe("deprecated"),edit_event_type:h.literal("edit_pcb_component_location"),pcb_component_id:h.string(),original_center:h.object({x:h.number(),y:h.number()}),new_center:h.object({x:h.number(),y:h.number()})});Ct(!0);var FCt=jg.extend({pcb_edit_event_type:h.literal("edit_trace_hint").describe("deprecated"),edit_event_type:h.literal("edit_pcb_trace_hint").optional(),pcb_port_id:h.string(),pcb_trace_hint_id:h.string().optional(),route:h.array(h.object({x:h.number(),y:h.number(),via:h.boolean().optional()}))});Ct(!0);var zCt=jg.extend({edit_event_type:h.literal("edit_schematic_component_location"),schematic_component_id:h.string(),original_center:h.object({x:h.number(),y:h.number()}),new_center:h.object({x:h.number(),y:h.number()})});Ct(!0);var Pse=jg.extend({edit_event_type:h.literal("edit_pcb_group_location"),pcb_group_id:h.string(),original_center:h.object({x:h.number(),y:h.number()}),new_center:h.object({x:h.number(),y:h.number()})});Ct(!0);var Tse=jg.extend({edit_event_type:h.literal("edit_schematic_group_location"),schematic_group_id:h.string(),original_center:h.object({x:h.number(),y:h.number()}),new_center:h.object({x:h.number(),y:h.number()})});Ct(!0);var Ese=h.union([LCt,FCt,zCt]);Ct(!0);var $Ct=h.object({selector:h.string(),relative_to:h.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Jt});Ct(!0);var DCt=h.object({pcb_port_selector:h.string(),offsets:h.array(nr)});Ct(!0);var jCt=h.object({selector:h.string(),relative_to:h.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Jt});Ct(!0);var BCt=h.object({pcb_placements:h.array($Ct).optional(),manual_trace_hints:h.array(DCt).optional(),schematic_placements:h.array(jCt).optional()});Ct(!0);var c_=h.string().or(h.array(h.string()).readonly()).or(h.array(h.string())),pd=n=>h.record(h.enum(n),c_),zg=h.object({layoutMode:h.enum(["grid","flex","match-adapt","relative","none"]).optional(),position:h.enum(["absolute","relative"]).optional(),grid:h.boolean().optional(),gridCols:h.number().or(h.string()).optional(),gridRows:h.number().or(h.string()).optional(),gridTemplateRows:h.string().optional(),gridTemplateColumns:h.string().optional(),gridTemplate:h.string().optional(),gridGap:h.number().or(h.string()).optional(),gridRowGap:h.number().or(h.string()).optional(),gridColumnGap:h.number().or(h.string()).optional(),flex:h.boolean().or(h.string()).optional(),flexDirection:h.enum(["row","column"]).optional(),alignItems:h.enum(["start","center","end","stretch"]).optional(),justifyContent:h.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),flexRow:h.boolean().optional(),flexColumn:h.boolean().optional(),gap:h.number().or(h.string()).optional(),pack:h.boolean().optional().describe("Pack the contents of this group using a packing strategy"),packOrderStrategy:h.enum(["largest_to_smallest","first_to_last","highest_to_lowest_pin_count"]).optional(),packPlacementStrategy:h.enum(["shortest_connection_along_outline"]).optional(),padding:B.optional(),paddingLeft:B.optional(),paddingRight:B.optional(),paddingTop:B.optional(),paddingBottom:B.optional(),paddingX:B.optional(),paddingY:B.optional(),width:B.optional(),height:B.optional(),matchAdapt:h.boolean().optional(),matchAdaptTemplate:h.any().optional()});Ct(!0);var tH=h.object({strokeWidth:B.optional(),dashed:h.boolean().optional(),solid:h.boolean().optional()}),YCt=h.custom(n=>typeof n=="string"),XCt=h.object({serverUrl:h.string().optional(),inputFormat:h.enum(["simplified","circuit-json"]).optional(),serverMode:h.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:h.boolean().optional(),cache:h.custom(n=>!0).optional(),traceClearance:B.optional(),groupMode:h.enum(["sequential_trace","subcircuit","sequential-trace"]).optional(),algorithmFn:h.custom(n=>typeof n=="function"||n===void 0).optional(),preset:h.enum(["sequential_trace","subcircuit","auto","auto_local","auto_cloud","freerouting","laser_prefab","sequential-trace","auto-local","auto-cloud"]).optional(),local:h.boolean().optional()}),UCt=h.union([h.literal("sequential_trace"),h.literal("subcircuit"),h.literal("auto"),h.literal("auto_local"),h.literal("auto_cloud"),h.literal("freerouting"),h.literal("laser_prefab"),h.literal("sequential-trace"),h.literal("auto-local"),h.literal("auto-cloud")]),VCt=h.string(),lH=h.union([XCt,UCt,VCt]),N4=NS.extend({name:h.string().optional(),children:h.any().optional(),schTitle:h.string().optional(),key:h.any().optional(),showAsSchematicBox:h.boolean().optional(),connections:h.record(h.string(),c_.optional()).optional(),schPinArrangement:I4.optional(),schPinSpacing:B.optional(),schPinStyle:Dg.optional(),...zg.shape,grid:zg.shape.grid.describe("@deprecated use pcbGrid"),flex:zg.shape.flex.describe("@deprecated use pcbFlex"),pcbGrid:h.boolean().optional(),pcbGridCols:h.number().or(h.string()).optional(),pcbGridRows:h.number().or(h.string()).optional(),pcbGridTemplateRows:h.string().optional(),pcbGridTemplateColumns:h.string().optional(),pcbGridTemplate:h.string().optional(),pcbGridGap:h.number().or(h.string()).optional(),pcbGridRowGap:h.number().or(h.string()).optional(),pcbGridColumnGap:h.number().or(h.string()).optional(),pcbFlex:h.boolean().or(h.string()).optional(),pcbFlexGap:h.number().or(h.string()).optional(),pcbFlexDirection:h.enum(["row","column"]).optional(),pcbAlignItems:h.enum(["start","center","end","stretch"]).optional(),pcbJustifyContent:h.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),pcbFlexRow:h.boolean().optional(),pcbFlexColumn:h.boolean().optional(),pcbGap:h.number().or(h.string()).optional(),pcbPack:h.boolean().optional(),pcbPackGap:h.number().or(h.string()).optional(),schGrid:h.boolean().optional(),schGridCols:h.number().or(h.string()).optional(),schGridRows:h.number().or(h.string()).optional(),schGridTemplateRows:h.string().optional(),schGridTemplateColumns:h.string().optional(),schGridTemplate:h.string().optional(),schGridGap:h.number().or(h.string()).optional(),schGridRowGap:h.number().or(h.string()).optional(),schGridColumnGap:h.number().or(h.string()).optional(),schFlex:h.boolean().or(h.string()).optional(),schFlexGap:h.number().or(h.string()).optional(),schFlexDirection:h.enum(["row","column"]).optional(),schAlignItems:h.enum(["start","center","end","stretch"]).optional(),schJustifyContent:h.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),schFlexRow:h.boolean().optional(),schFlexColumn:h.boolean().optional(),schGap:h.number().or(h.string()).optional(),schPack:h.boolean().optional(),schMatchAdapt:h.boolean().optional(),pcbWidth:B.optional(),pcbHeight:B.optional(),minTraceWidth:B.optional(),schWidth:B.optional(),schHeight:B.optional(),pcbLayout:zg.optional(),schLayout:zg.optional(),cellBorder:tH.nullable().optional(),border:tH.nullable().optional(),schPadding:B.optional(),schPaddingLeft:B.optional(),schPaddingRight:B.optional(),schPaddingTop:B.optional(),schPaddingBottom:B.optional(),pcbPadding:B.optional(),pcbPaddingLeft:B.optional(),pcbPaddingRight:B.optional(),pcbPaddingTop:B.optional(),pcbPaddingBottom:B.optional(),pcbPositionAnchor:YCt.optional()}),uH=h.custom(n=>"findPart"in n),A4=N4.extend({manualEdits:BCt.optional(),schAutoLayoutEnabled:h.boolean().optional(),schTraceAutoLabelEnabled:h.boolean().optional(),schMaxTraceDistance:V.optional(),routingDisabled:h.boolean().optional(),defaultTraceWidth:B.optional(),minTraceWidth:B.optional(),partsEngine:uH.optional(),pcbRouteCache:h.custom(n=>!0).optional(),autorouter:lH.optional(),square:h.boolean().optional(),emptyArea:h.string().optional(),filledArea:h.string().optional(),width:V.optional(),height:V.optional(),outline:h.array(zo).optional(),outlineOffsetX:V.optional(),outlineOffsetY:V.optional(),circuitJson:h.array(h.any()).optional()}),GCt=A4.extend({subcircuit:h.literal(!0)}),pH=h.discriminatedUnion("subcircuit",[N4.extend({subcircuit:h.literal(!1).optional()}),GCt]);Ct(!0);Ct(!0);Ct(!0);Ct(!0);var o_=h.custom(n=>typeof n=="string"),R4=A4.omit({connections:!0}).extend({material:h.enum(["fr4","fr1"]).default("fr4"),layers:h.union([h.literal(1),h.literal(2),h.literal(4),h.literal(6),h.literal(8)]).default(2),borderRadius:se.optional(),thickness:se.optional(),boardAnchorPosition:zo.optional(),boardAnchorAlignment:a_.optional(),title:h.string().optional(),solderMaskColor:o_.optional(),topSolderMaskColor:o_.optional(),bottomSolderMaskColor:o_.optional(),silkscreenColor:o_.optional(),topSilkscreenColor:o_.optional(),bottomSilkscreenColor:o_.optional(),doubleSidedAssembly:h.boolean().optional().default(!1),schematicDisabled:h.boolean().optional()});Ct(!0);var hH=N4.omit({width:!0,height:!0,layoutMode:!0,children:!0}).extend({width:se.optional(),height:se.optional(),children:h.any().optional(),noSolderMask:h.boolean().optional(),panelizationMethod:h.enum(["tab-routing","none"]).optional(),boardGap:se.optional(),layoutMode:h.enum(["grid","pack","none"]).optional(),row:h.number().optional(),col:h.number().optional(),cellWidth:se.optional(),cellHeight:se.optional(),tabWidth:se.optional(),tabLength:se.optional(),mouseBites:h.boolean().optional(),edgePadding:se.optional(),edgePaddingLeft:se.optional(),edgePaddingRight:se.optional(),edgePaddingTop:se.optional(),edgePaddingBottom:se.optional()});Ct(!0);Ct(!0);var Dse=A4.extend({padding:V.optional(),paddingLeft:V.optional(),paddingRight:V.optional(),paddingTop:V.optional(),paddingBottom:V.optional()});Ct(!0);var WCt=h.string().or(h.array(h.string()).readonly()).or(h.array(h.string())),HCt=h.custom().pipe(h.record(h.string(),WCt)),qCt=h.record(As,As.or(h.array(As).readonly()).or(h.array(As)));Ct(!0);var ZCt=h.object({manufacturerPartNumber:h.string().optional(),supplierPartNumber:h.record(Dm,h.array(h.string())).optional()}),l_=Qn.extend({manufacturerPartNumber:h.string().optional(),pinLabels:qCt.optional(),showPinAliases:h.boolean().optional(),pcbPinLabels:h.record(h.string(),h.string()).optional(),internallyConnectedPins:h.array(h.array(h.union([h.string(),h.number()]))).optional(),externallyConnectedPins:h.array(h.array(h.string())).optional(),schPinArrangement:$g.optional(),schPortArrangement:$g.optional(),pinCompatibleVariants:h.array(ZCt).optional(),schPinStyle:Dg.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional(),noSchematicRepresentation:h.boolean().optional(),connections:HCt.optional()});Ct(!0);var dH=l_;Ct(!0);var O4=Qn.extend({manufacturerPartNumber:h.string().optional(),pinLabels:h.record(h.number().or(As),As.or(h.array(As))).optional(),schPinStyle:Dg.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional(),schDirection:h.enum(["left","right"]).optional(),schPinArrangement:I4.optional(),schPortArrangement:$g.optional(),pcbPinLabels:h.record(h.string(),h.string()).optional(),pinCount:h.union([h.literal(2),h.literal(3)]).optional(),internallyConnectedPins:h.array(h.array(h.union([h.string(),h.number()]))).optional(),connections:h.custom().pipe(h.record(h.string(),c_)).optional()});Ct(!0);var fH=O4.extend({bridgedPins:h.array(h.array(h.string())).optional(),bridged:h.boolean().optional()});Ct(!0);var Wse=Qn.extend({manufacturerPartNumber:h.string().optional(),pinLabels:h.record(h.number().or(As),As.or(h.array(As))).optional(),schPinStyle:Dg.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional(),schDirection:h.enum(["left","right"]).optional(),schPortArrangement:$g.optional(),internallyConnectedPins:h.array(h.array(h.union([h.string(),h.number()]))).optional(),standard:h.enum(["usb_c","m2"]).optional()});Ct(!0);var mH=Qn.extend({standard:h.enum(["TSC0001_36P_XALT_2025_11","0805","0603","1206"]).optional()});Ct(!0);var _H=Qn.extend({currentRating:h.union([h.number(),h.string()]),voltageRating:h.union([h.number(),h.string()]).optional(),schShowRatings:h.boolean().optional(),schOrientation:Zc.optional(),connections:h.record(h.string(),h.union([h.string(),h.array(h.string()).readonly(),h.array(h.string())])).optional()}),CS=h.custom().transform(n=>{if(n!==void 0)return V.parse(n)}),yH=h.discriminatedUnion("shape",[Ye.omit({pcbRotation:!0,layer:!0}).extend({name:h.string().optional(),connectsTo:h.string().or(h.array(h.string())).optional(),shape:h.literal("circle"),holeDiameter:V,outerDiameter:V,padDiameter:V.optional().describe("Diameter of the copper pad"),portHints:ao.optional(),solderMaskMargin:V.optional(),coveredWithSolderMask:h.boolean().optional()}),Ye.omit({layer:!0}).extend({name:h.string().optional(),connectsTo:h.string().or(h.array(h.string())).optional(),shape:h.literal("oval"),outerWidth:V,outerHeight:V,holeWidth:CS,holeHeight:CS,innerWidth:V.optional().describe("DEPRECATED use holeWidth"),innerHeight:V.optional().describe("DEPRECATED use holeHeight"),portHints:ao.optional(),solderMaskMargin:V.optional(),coveredWithSolderMask:h.boolean().optional()}),Ye.omit({layer:!0}).extend({name:h.string().optional(),connectsTo:h.string().or(h.array(h.string())).optional(),shape:h.literal("pill"),rectPad:h.boolean().optional(),outerWidth:V,outerHeight:V,holeWidth:CS,holeHeight:CS,innerWidth:V.optional().describe("DEPRECATED use holeWidth"),innerHeight:V.optional().describe("DEPRECATED use holeHeight"),portHints:ao.optional(),holeOffsetX:V.optional(),holeOffsetY:V.optional(),solderMaskMargin:V.optional(),coveredWithSolderMask:h.boolean().optional()}),Ye.omit({pcbRotation:!0,layer:!0}).extend({name:h.string().optional(),connectsTo:h.string().or(h.array(h.string())).optional(),shape:h.literal("circular_hole_with_rect_pad"),holeDiameter:V,rectPadWidth:V,rectPadHeight:V,rectBorderRadius:V.optional(),holeShape:h.literal("circle").optional(),padShape:h.literal("rect").optional(),portHints:ao.optional(),holeOffsetX:V.optional(),holeOffsetY:V.optional(),solderMaskMargin:V.optional(),coveredWithSolderMask:h.boolean().optional()}),Ye.omit({pcbRotation:!0,layer:!0}).extend({name:h.string().optional(),connectsTo:h.string().or(h.array(h.string())).optional(),shape:h.literal("pill_hole_with_rect_pad"),holeShape:h.literal("pill"),padShape:h.literal("rect"),holeWidth:V,holeHeight:V,rectPadWidth:V,rectPadHeight:V,portHints:ao.optional(),holeOffsetX:V.optional(),holeOffsetY:V.optional(),solderMaskMargin:V.optional(),coveredWithSolderMask:h.boolean().optional()}),Ye.omit({pcbRotation:!0,layer:!0}).extend({name:h.string().optional(),connectsTo:h.string().or(h.array(h.string())).optional(),shape:h.literal("hole_with_polygon_pad"),holeShape:h.enum(["circle","oval","pill","rotated_pill"]),holeDiameter:V.optional(),holeWidth:V.optional(),holeHeight:V.optional(),padOutline:h.array(zo),holeOffsetX:V,holeOffsetY:V,portHints:ao.optional(),solderMaskMargin:V.optional(),coveredWithSolderMask:h.boolean().optional()})]).refine(n=>("innerWidth"in n&&n.innerWidth!==void 0&&(n.holeWidth??(n.holeWidth=n.innerWidth)),"innerHeight"in n&&n.innerHeight!==void 0&&(n.holeHeight??(n.holeHeight=n.innerHeight)),n));Ct(!0);var KCt=["pin1","pin2","pos","neg"],gH=Qn.extend({resistance:Xc,pullupFor:h.string().optional(),pullupTo:h.string().optional(),pulldownFor:h.string().optional(),pulldownTo:h.string().optional(),schOrientation:Zc.optional(),schSize:cH.optional(),connections:pd(KCt).optional()}),xH=C4;Ct(!0);var bH=Qn.extend({maxResistance:Xc,pinVariant:h.enum(["two_pin","three_pin"]).optional()});Ct(!0);var JCt=C4,vH=Qn.extend({frequency:$r,loadCapacitance:ka,manufacturerPartNumber:h.string().optional(),mpn:h.string().optional(),pinVariant:h.enum(["two_pin","four_pin"]).optional(),schOrientation:Zc.optional(),connections:pd(JCt).optional()});Ct(!0);var SH=Qn.extend({frequency:$r,loadCapacitance:ka,pinVariant:h.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});Ct(!0);var coe=R4.extend({leftPinCount:h.number().optional(),rightPinCount:h.number().optional(),topPinCount:h.number().optional(),bottomPinCount:h.number().optional(),leftPins:h.array(h.string()).optional(),rightPins:h.array(h.string()).optional(),topPins:h.array(h.string()).optional(),bottomPins:h.array(h.string()).optional(),pinPitch:V.optional(),innerHoles:h.boolean().optional()});Ct(!0);var QCt=["pin1","pin2","pos","neg","anode","cathode"],wH=Qn.extend({capacitance:ka,maxVoltageRating:pr.optional(),schShowRatings:h.boolean().optional().default(!1),polarized:h.boolean().optional().default(!1),decouplingFor:h.string().optional(),decouplingTo:h.string().optional(),bypassFor:h.string().optional(),bypassTo:h.string().optional(),maxDecouplingTraceLength:h.number().optional(),schOrientation:Zc.optional(),schSize:cH.optional(),connections:pd(QCt).optional()}),PH=AS;Ct(!0);var hoe=h.object({name:h.string(),connectsTo:h.string().or(h.array(h.string())).optional(),highlightColor:h.string().optional(),isPowerNet:h.boolean().optional(),isGroundNet:h.boolean().optional()});Ct(!0);var doe=Qn.extend({soldermaskPullback:se.optional(),padDiameter:se.optional()});Ct(!0);var moe=h.object({name:h.string().optional(),pcbOnly:h.boolean().optional(),schOnly:h.boolean().optional()});Ct(!0);var t3t=h.object({pcb:h.literal(!0).optional(),xDist:se,left:h.string(),right:h.string(),edgeToEdge:h.literal(!0).optional(),centerToCenter:h.literal(!0).optional()});Ct(!0);var e3t=h.object({pcb:h.literal(!0).optional(),yDist:se,top:h.string(),bottom:h.string(),edgeToEdge:h.literal(!0).optional(),centerToCenter:h.literal(!0).optional()});Ct(!0);var n3t=h.object({pcb:h.literal(!0).optional(),sameY:h.literal(!0).optional(),for:h.array(h.string())});Ct(!0);var i3t=h.object({pcb:h.literal(!0).optional(),sameX:h.literal(!0).optional(),for:h.array(h.string())});Ct(!0);var kH=h.union([t3t,e3t,n3t,i3t]);Ct(!0);var r3t=Ye.omit({layer:!0,pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("rect"),width:se,height:se});Ct(!0);var s3t=Ye.omit({layer:!0,pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("circle"),radius:se});Ct(!0);var o3t=Ye.omit({layer:!0,pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("polygon"),points:h.array(zo)});Ct(!0);var TH=h.discriminatedUnion("shape",[r3t,s3t,o3t]),a3t=Ye.omit({pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("rect"),width:se,height:se,rectBorderRadius:se.optional(),cornerRadius:se.optional(),portHints:ao.optional(),coveredWithSolderMask:h.boolean().optional(),solderMaskMargin:se.optional()});Ct(!0);var c3t=Ye.omit({pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("rotated_rect"),width:se,height:se,ccwRotation:h.number(),cornerRadius:se.optional(),portHints:ao.optional(),coveredWithSolderMask:h.boolean().optional(),solderMaskMargin:se.optional()});Ct(!0);var l3t=Ye.omit({pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("circle"),radius:se,portHints:ao.optional(),coveredWithSolderMask:h.boolean().optional(),solderMaskMargin:se.optional()});Ct(!0);var u3t=Ye.omit({pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("pill"),width:se,height:se,radius:se,portHints:ao.optional(),coveredWithSolderMask:h.boolean().optional(),solderMaskMargin:se.optional()});Ct(!0);var p3t=Ye.omit({pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("polygon"),points:h.array(zo),portHints:ao.optional(),coveredWithSolderMask:h.boolean().optional(),solderMaskMargin:se.optional()});Ct(!0);var MH=h.discriminatedUnion("shape",[l3t,a3t,c3t,u3t,p3t]);Ct(!0);var h3t=Ye.omit({pcbRotation:!0}).extend({shape:h.literal("rect"),width:se,height:se});Ct(!0);var d3t=Ye.omit({pcbRotation:!0}).extend({shape:h.literal("circle"),radius:se});Ct(!0);var boe=h.union([d3t,h3t]);Ct(!0);var f3t=Ye.extend({name:h.string().optional(),shape:h.literal("circle").optional(),diameter:se.optional(),radius:se.optional(),solderMaskMargin:se.optional(),coveredWithSolderMask:h.boolean().optional()}).transform(n=>({...n,diameter:n.diameter??2*n.radius,radius:n.radius??n.diameter/2})),m3t=Ye.extend({name:h.string().optional(),shape:h.literal("pill"),width:se,height:se,solderMaskMargin:se.optional(),coveredWithSolderMask:h.boolean().optional()}),_3t=Ye.extend({name:h.string().optional(),shape:h.literal("rect"),width:se,height:se,solderMaskMargin:se.optional(),coveredWithSolderMask:h.boolean().optional()}),EH=h.union([f3t,m3t,_3t]);Ct(!0);var T4=h.union([h.string(),h.custom(n=>!!n.getPortSelector)]),eH=h.object({key:h.string().optional(),thickness:V.optional(),width:V.optional().describe("Alias for trace thickness"),schematicRouteHints:h.array(zo).optional(),pcbRouteHints:h.array(nr).optional(),pcbPathRelativeTo:h.string().optional(),pcbPath:h.array(h.union([zo,h.string()])).optional(),pcbStraightLine:h.boolean().optional().describe("Draw a straight pcb trace between the connected points"),schDisplayLabel:h.string().optional(),schStroke:h.string().optional(),highlightColor:h.string().optional(),maxLength:V.optional()}),CH=h.union([eH.extend({path:h.array(T4)}),eH.extend({from:T4,to:T4})]),IH=h.object({children:h.any().optional(),originalLayer:de.default("top").optional(),circuitJson:h.array(h.any()).optional()});Ct(!0);var NH=h.object({originalFacingDirection:h.enum(["up","down","left","right"]).default("right").optional()});Ct(!0);var y3t=h.number().or(h.string().endsWith("mAh")).transform(n=>{if(typeof n=="string"){let e=n.replace("mAh",""),t=Number.parseFloat(e);if(Number.isNaN(t))throw new Error("Invalid capacity");return t}return n}).describe("Battery capacity in mAh"),AH=Qn.extend({capacity:y3t.optional(),voltage:pr.optional(),standard:h.enum(["AA","AAA","9V","CR2032","18650","C"]).optional(),schOrientation:Zc.optional()});Ct(!0);var g3t=h.enum(["vertical","horizontal"]).describe("vertical means pins go 1->2 downward and horizontal means pins go 1->2 rightward");Ct(!0);var RH=Qn.extend({pinCount:h.number(),pitch:V.optional(),schFacingDirection:h.enum(["up","down","left","right"]).optional(),gender:h.enum(["male","female","unpopulated"]).optional().default("male"),showSilkscreenPinLabels:h.boolean().optional(),pcbPinLabels:h.record(h.string(),h.string()).optional(),doubleRow:h.boolean().optional(),rightAngle:h.boolean().optional(),pcbOrientation:g3t.optional(),holeDiameter:V.optional(),platedDiameter:V.optional(),pinLabels:h.record(h.string(),As).or(h.array(As)).optional(),connections:h.custom().pipe(h.record(h.string(),c_)).optional(),facingDirection:h.enum(["left","right"]).optional(),schPinArrangement:I4.optional(),schPinStyle:Dg.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional()});Ct(!0);var Ooe=h.object({net:h.string().optional(),connection:h.string().optional(),schX:se.optional(),schY:se.optional(),schRotation:en.optional(),anchorSide:h.enum(["left","top","right","bottom"]).optional()});Ct(!0);var OH=h.object({net:h.string().optional(),connection:h.string().optional(),connectsTo:h.string().or(h.array(h.string())).optional(),schX:se.optional(),schY:se.optional(),schRotation:en.optional(),anchorSide:h.enum(["left","top","right","bottom"]).optional()});Ct(!0);var LH=l_.extend({});Ct(!0);Ct(!0);var x3t=h.custom(n=>typeof n=="string"),FH=h.object({simulationType:h.literal("spice_transient_analysis").default("spice_transient_analysis"),duration:hr.optional(),timePerStep:hr.optional(),spiceEngine:x3t.optional()});Ct(!0);var b3t=["pin1","pin2","pin3","emitter","collector","base","gate","source","drain"],zH=Qn.extend({type:h.enum(["npn","pnp","bjt","jfet","mosfet","igbt"]),connections:pd(b3t).optional()});Ct(!0);var $H=Qn.extend({channelType:h.enum(["n","p"]),mosfetMode:h.enum(["enhancement","depletion"])});Ct(!0);var v3t=C4,DH=Qn.extend({inductance:rb,maxCurrentRating:h.union([h.string(),h.number()]).optional(),schOrientation:Zc.optional(),connections:pd(v3t).optional()});Ct(!0);var S3t=h.enum(["anode","cathode","pin1","pin2","pos","neg"]),w3t=h.string().or(h.array(h.string()).readonly()).or(h.array(h.string())),P3t=h.record(S3t,w3t),k3t=h.enum(["standard","schottky","zener","avalanche","photo","tvs"]),jH=Qn.extend({connections:P3t.optional(),variant:k3t.optional().default("standard"),standard:h.boolean().optional(),schottky:h.boolean().optional(),zener:h.boolean().optional(),avalanche:h.boolean().optional(),photo:h.boolean().optional(),tvs:h.boolean().optional(),schOrientation:Zc.optional()}).superRefine((n,e)=>{if([n.standard,n.schottky,n.zener,n.avalanche,n.photo,n.tvs].filter(Boolean).length>1)return e.addIssue({code:h.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),h.INVALID}).transform(n=>{let e={...n,standard:!1,schottky:!1,zener:!1,avalanche:!1,photo:!1,tvs:!1};if(n.standard)e.standard=!0;else if(n.schottky)e.schottky=!0;else if(n.zener)e.zener=!0;else if(n.photo)e.photo=!0;else if(n.tvs)e.tvs=!0;else switch(n.variant){case"standard":e.standard=!0;break;case"schottky":e.schottky=!0;break;case"zener":e.zener=!0;break;case"avalanche":e.avalanche=!0;break;case"photo":e.photo=!0;break;case"tvs":e.tvs=!0;break;default:e.standard=!0}return e}),BH=AS;Ct(!0);var YH=Qn.extend({color:h.string().optional(),wavelength:h.string().optional(),schDisplayValue:h.string().optional(),schOrientation:Zc.optional(),connections:pd(AS).optional(),laser:h.boolean().optional()}),XH=AS,UH=Qn.extend({type:h.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:h.boolean().optional().default(!1),spst:h.boolean().optional(),spdt:h.boolean().optional(),dpst:h.boolean().optional(),dpdt:h.boolean().optional(),simSwitchFrequency:$r.optional(),simCloseAt:hr.optional(),simOpenAt:hr.optional(),simStartClosed:h.boolean().optional(),simStartOpen:h.boolean().optional(),connections:h.custom().pipe(h.record(h.string(),c_)).optional()}).transform(n=>{let e={...n};switch(e.dpdt?e.type="dpdt":e.spst?e.type="spst":e.spdt?e.type="spdt":e.dpst&&(e.type="dpst"),e.type){case"spdt":e.spdt=!0;break;case"spst":e.spst=!0;break;case"dpst":e.dpst=!0;break;case"dpdt":e.dpdt=!0;break}return e});Ct(!0);var VH=Ye.extend({text:h.string(),anchorAlignment:h.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:h.enum(["tscircuit2024"]).optional(),fontSize:B.optional(),color:h.string().optional()});Ct(!0);var GH=Ye.omit({pcbRotation:!0}).extend({width:V,height:V,strokeWidth:V.optional(),isFilled:h.boolean().optional(),hasStroke:h.boolean().optional(),isStrokeDashed:h.boolean().optional(),color:h.string().optional(),cornerRadius:V.optional()}),WH=Ye.omit({pcbLeftEdgeX:!0,pcbRightEdgeX:!0,pcbTopEdgeY:!0,pcbBottomEdgeY:!0,pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:h.array(nr),strokeWidth:B.optional(),color:h.string().optional()}),nH=h.union([h.string(),zo]),HH=Ye.omit({pcbLeftEdgeX:!0,pcbRightEdgeX:!0,pcbTopEdgeY:!0,pcbBottomEdgeY:!0,pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:nH,to:nH,text:h.string().optional(),offset:V.optional(),font:h.enum(["tscircuit2024"]).optional(),fontSize:B.optional(),color:h.string().optional(),arrowSize:V.optional(),units:h.enum(["in","mm"]).optional(),outerEdgeToEdge:h.literal(!0).optional(),centerToCenter:h.literal(!0).optional(),innerEdgeToEdge:h.literal(!0).optional()});Ct(!0);var iae=h.object({layer:h.string().optional(),thickness:V.optional(),route:h.array(nr)}),qH=NS.extend({name:h.string().optional(),fromLayer:de,toLayer:de,holeDiameter:V.optional(),outerDiameter:V.optional(),connectsTo:h.string().or(h.array(h.string())).optional(),netIsAssignable:h.boolean().optional()});Ct(!0);var T3t=h.object({pin1:c_}).strict(),ZH=Qn.extend({connections:T3t.optional(),footprintVariant:h.enum(["pad","through_hole"]).optional(),padShape:h.enum(["rect","circle"]).optional().default("circle"),padDiameter:V.optional(),holeDiameter:V.optional(),width:V.optional(),height:V.optional()}).refine(n=>n.footprintVariant!=="through_hole"||n.holeDiameter!==void 0,{message:"holeDiameter is required for through_hole testpoints"});Ct(!0);var KH=Ye.omit({pcbRotation:!0,layer:!0}).extend({connection:h.string()});Ct(!0);var JH=h.union([Ye.omit({pcbRotation:!0}).extend({shape:h.literal("circle"),radius:V}),Ye.extend({shape:h.literal("rect"),width:V,height:V})]),dae=Ye.omit({pcbRotation:!0}).extend({width:V,height:V,strokeWidth:V.optional(),isFilled:h.boolean().optional(),hasStroke:h.boolean().optional(),isStrokeDashed:h.boolean().optional(),color:h.string().optional()}),_ae=Ye.omit({pcbLeftEdgeX:!0,pcbRightEdgeX:!0,pcbTopEdgeY:!0,pcbBottomEdgeY:!0,pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({outline:h.array(zo),strokeWidth:B.optional(),isClosed:h.boolean().optional(),isStrokeDashed:h.boolean().optional(),color:h.string().optional()}),QH=h.object({name:h.string().optional(),layer:de,connectsTo:h.string(),padMargin:se.optional(),traceMargin:se.optional(),clearance:se.optional(),boardEdgeMargin:se.optional(),cutoutMargin:se.optional(),coveredWithSolderMask:h.boolean().optional().default(!0)});Ct(!0);var tq=h.object({originalLayer:de.default("top").optional(),children:h.any().optional()});Ct(!0);var M3t=h.object({pcbX:$i.optional(),pcbY:$i.optional(),pcbLeftEdgeX:$i.optional(),pcbRightEdgeX:$i.optional(),pcbTopEdgeY:$i.optional(),pcbBottomEdgeY:$i.optional(),pcbOffsetX:se.optional(),pcbOffsetY:se.optional(),pcbZ:se.optional()}),E3t=qc.extend({modelUrl:h.string(),stepUrl:h.string().optional()}),C3t=E3t.merge(M3t);Ct(!0);var eq=h.union([h.null(),h.string(),C3t]),nq=Qn.extend({voltage:pr}),I3t=["pin1","pin2","pos","neg"],N3t=h.union([h.string(),h.number()]).transform(n=>typeof n=="string"?n.endsWith("%")?parseFloat(n.slice(0,-1))/100:parseFloat(n):n).pipe(h.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),iq=Qn.extend({voltage:pr.optional(),frequency:$r.optional(),peakToPeakVoltage:pr.optional(),waveShape:h.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:en.optional(),dutyCycle:N3t.optional(),connections:pd(I3t).optional()});Ct(!0);var rq=Qn.omit({name:!0}).extend({name:h.string().optional(),connectsTo:h.string(),referenceTo:h.string().optional(),color:h.string().optional()});Ct(!0);var sq=h.object({center:Jt,radius:V,startAngleDegrees:en,endAngleDegrees:en,direction:h.enum(["clockwise","counterclockwise"]).default("counterclockwise"),strokeWidth:V.optional(),color:h.string().optional(),isDashed:h.boolean().optional().default(!1)}),Cae=h.object({children:h.any().optional()});Ct(!0);var oq=h.object({schX:V.optional(),schY:V.optional(),width:V.optional(),height:V.optional(),overlay:h.array(h.string()).optional(),padding:V.optional(),paddingLeft:V.optional(),paddingRight:V.optional(),paddingTop:V.optional(),paddingBottom:V.optional(),title:h.string().optional(),titleAlignment:a_.default("top_left"),titleColor:h.string().optional(),titleFontSize:V.optional(),titleInside:h.boolean().default(!1),strokeStyle:h.enum(["solid","dashed"]).default("solid")}).refine(n=>n.width!==void 0&&n.height!==void 0||Array.isArray(n.overlay)&&n.overlay.length>0,{message:"Must provide either both `width` and `height`, or a non-empty `overlay` array."}).refine(n=>!(n.width!==void 0&&n.height!==void 0&&Array.isArray(n.overlay)&&n.overlay.length>0),{message:"Cannot provide both `width`/`height` and `overlay` at the same time."}),aq=h.object({center:Jt,radius:V,strokeWidth:V.optional(),color:h.string().optional(),isFilled:h.boolean().optional().default(!1),fillColor:h.string().optional(),isDashed:h.boolean().optional().default(!1)}),cq=h.object({schX:V.optional(),schY:V.optional(),width:V,height:V,rotation:en.default(0),strokeWidth:V.optional(),color:h.string().optional(),isFilled:h.boolean().optional().default(!1),fillColor:h.string().optional(),isDashed:h.boolean().optional().default(!1),cornerRadius:V.optional()}),lq=h.object({x1:V,y1:V,x2:V,y2:V,strokeWidth:V.optional(),color:h.string().optional(),isDashed:h.boolean().optional().default(!1)}),A3t=h.enum(["center","left","right","top","bottom"]),uq=h.object({schX:V.optional(),schY:V.optional(),text:h.string(),fontSize:h.number().default(1),anchor:h.union([A3t.describe("legacy"),a_]).default("center"),color:h.string().default("#000000"),schRotation:en.default(0)}),Xae=h.object({points:h.array(Jt),isFilled:h.boolean().optional().default(!1),fillColor:h.enum(["red","blue"]).optional()}),pq=h.object({schX:V.optional(),schY:V.optional(),children:h.any().optional(),cellPadding:V.optional(),borderWidth:V.optional(),anchor:a_.optional(),fontSize:V.optional()});Ct(!0);var hq=h.object({children:h.any().optional(),height:V.optional()});Ct(!0);var dq=h.object({children:h.string().optional(),horizontalAlign:h.enum(["left","center","right"]).optional(),verticalAlign:h.enum(["top","middle","bottom"]).optional(),fontSize:V.optional(),rowSpan:h.number().optional(),colSpan:h.number().optional(),width:V.optional(),text:h.string().optional()});Ct(!0);var Jae=Ye.extend({text:h.string(),anchorAlignment:a_.default("center"),font:h.enum(["tscircuit2024"]).optional(),fontSize:B.optional(),layers:h.array(de).optional()}),fq=Ye.extend({text:h.string(),anchorAlignment:a_.default("center"),font:h.enum(["tscircuit2024"]).optional(),fontSize:B.optional(),isKnockout:h.boolean().optional(),knockoutPadding:B.optional(),knockoutPaddingLeft:B.optional(),knockoutPaddingRight:B.optional(),knockoutPaddingTop:B.optional(),knockoutPaddingBottom:B.optional(),layers:h.array(de).optional()}),mq=Ye.omit({pcbLeftEdgeX:!0,pcbRightEdgeX:!0,pcbTopEdgeY:!0,pcbBottomEdgeY:!0,pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:h.array(nr),strokeWidth:B.optional()}),_q=Ye.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({strokeWidth:V,x1:V,y1:V,x2:V,y2:V}),yq=Ye.omit({pcbRotation:!0}).extend({filled:h.boolean().default(!0).optional(),stroke:h.enum(["dashed","solid","none"]).optional(),strokeWidth:V.optional(),width:V,height:V,cornerRadius:V.optional()}),gq=Ye.omit({pcbRotation:!0}).extend({isFilled:h.boolean().optional(),isOutline:h.boolean().optional(),strokeWidth:V.optional(),radius:V}),iH=h.object({x:V,y:V,via:h.boolean().optional(),toLayer:de.optional()}),xq=h.object({for:h.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:h.number().optional(),offset:nr.or(iH).optional(),offsets:h.array(nr).or(h.array(iH)).optional(),traceWidth:h.number().optional()}),pce=NS.extend({name:h.string(),pinNumber:h.number().optional(),aliases:h.array(h.string()).optional(),direction:bCt,connectsTo:h.string().or(h.array(h.string())).optional()}),bq=Ye.extend({text:h.string(),anchorAlignment:h.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:h.enum(["tscircuit2024"]).optional(),fontSize:B.optional(),color:h.string().optional()});Ct(!0);var vq=Ye.omit({pcbRotation:!0}).extend({width:V,height:V,strokeWidth:V.optional(),isFilled:h.boolean().optional(),hasStroke:h.boolean().optional(),isStrokeDashed:h.boolean().optional(),color:h.string().optional(),cornerRadius:V.optional()});Ct(!0);var Sq=Ye.omit({pcbLeftEdgeX:!0,pcbRightEdgeX:!0,pcbTopEdgeY:!0,pcbBottomEdgeY:!0,pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:h.array(nr),strokeWidth:B.optional(),color:h.string().optional()});Ct(!0);var wq=Ye.omit({pcbLeftEdgeX:!0,pcbRightEdgeX:!0,pcbTopEdgeY:!0,pcbBottomEdgeY:!0,pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({x1:V,y1:V,x2:V,y2:V,strokeWidth:V.optional(),color:h.string().optional(),isDashed:h.boolean().optional()});Ct(!0);var rH=h.union([h.string(),zo]),Pq=Ye.omit({pcbLeftEdgeX:!0,pcbRightEdgeX:!0,pcbTopEdgeY:!0,pcbBottomEdgeY:!0,pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:rH,to:rH,text:h.string().optional(),offset:V.optional(),font:h.enum(["tscircuit2024"]).optional(),fontSize:B.optional(),color:h.string().optional(),arrowSize:V.optional(),units:h.enum(["in","mm"]).optional(),outerEdgeToEdge:h.literal(!0).optional(),centerToCenter:h.literal(!0).optional(),innerEdgeToEdge:h.literal(!0).optional()});Ct(!0);var kq=h.array(h.any()).describe("Circuit JSON"),M4=h.object({footprintCircuitJson:h.array(h.any()),cadModel:aH.optional()}),sH=h.function().args(h.string()).returns(h.promise(M4)).or(h.function().args(h.string(),h.object({resolvedPcbStyle:E4.optional()}).optional()).returns(h.promise(M4))).describe("A function that takes a path and returns Circuit JSON"),R3t=h.object({loadFromUrl:h.function().args(h.string()).returns(h.promise(M4)).describe("A function that takes a footprint file URL and returns Circuit JSON")}),O3t=h.object({engineVersionString:h.string().optional(),simulationResultCircuitJson:kq}),L3t=h.object({simulate:h.function().args(h.string()).returns(h.promise(O3t)).describe("A function that takes a SPICE string and returns a simulation result")}),F3t=h.custom(n=>typeof n=="string"),oH=h.object({run:h.function().args().returns(h.promise(h.unknown())).describe("Run the autorouter"),getOutputSimpleRouteJson:h.function().args().returns(h.promise(h.any())).describe("Get the resulting SimpleRouteJson")}),z3t=h.object({createAutorouter:h.function().args(h.any(),h.any().optional()).returns(h.union([oH,h.promise(oH)])).describe("Create an autorouter instance")}),$3t=h.object({partsEngine:uH.optional(),autorouter:lH.optional(),autorouterMap:h.record(h.string(),z3t).optional(),registryApiUrl:h.string().optional(),cloudAutorouterUrl:h.string().optional(),projectName:h.string().optional(),projectBaseUrl:h.string().optional(),version:h.string().optional(),url:h.string().optional(),printBoardInformationToSilkscreen:h.boolean().optional(),includeBoardFiles:h.array(h.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:h.string().describe('The directory where snapshots are stored for "tsci snapshot", defaults to "tests/__snapshots__"').optional(),defaultSpiceEngine:F3t.optional(),localCacheEngine:h.any().optional(),pcbDisabled:h.boolean().optional(),schematicDisabled:h.boolean().optional(),partsEngineDisabled:h.boolean().optional(),spiceEngineMap:h.record(h.string(),L3t).optional(),footprintLibraryMap:h.record(h.string(),h.union([sH,h.record(h.string(),h.union([kq,sH]))])).optional(),footprintFileParserMap:h.record(h.string(),R3t).optional(),resolveProjectStaticFileImportUrl:h.function().args(h.string()).returns(h.promise(h.string())).describe("A function that returns a string URL for static files for the project").optional()});Ct(!0);var D3t=$3t,wce=D3t.pick({projectName:!0,projectBaseUrl:!0,version:!0,url:!0,printBoardInformationToSilkscreen:!0,includeBoardFiles:!0,snapshotsDir:!0,defaultSpiceEngine:!0});Ct(!0);vt();tt();vt();vt();vt();Ia();tt();var Ha=Vt(Qs(),1);Ia();tt();function Kc(){return new L4}var L4=class n{constructor(){f(this,"index",{});f(this,"array",[])}size(){return this.array.length}empty(){return this.array.length===0}itemAt(e){return this.array[e]}contains(e){return this.index[e.id()]!==void 0}find(e){let t=this.index[e.id()];return t===void 0?void 0:this.array[t]}setDefault(e,t){let i=this.index[e.id()];if(i===void 0){let r=new RS(e,t());return this.index[e.id()]=this.array.length,this.array.push(r),r}else return this.array[i]}insert(e,t){let i=new RS(e,t),r=this.index[e.id()];return r===void 0?(this.index[e.id()]=this.array.length,this.array.push(i)):this.array[r]=i,i}erase(e){let t=this.index[e.id()];if(t===void 0)return;this.index[e.id()]=void 0;let i=this.array[t],r=this.array.pop();return i!==r&&(this.array[t]=r,this.index[r.first.id()]=t),i}copy(){let e=new n;for(let t=0;t<this.array.length;t++){let i=this.array[t].copy();e.array[t]=i,e.index[i.first.id()]=t}return e}},RS=class n{constructor(e,t){f(this,"first");f(this,"second");this.first=e,this.second=t}copy(){return new n(this.first,this.second)}};var Oa=class{constructor(e=""){f(this,"_name");f(this,"_value",0);f(this,"_context",null);f(this,"_id",j3t++);this._name=e}id(){return this._id}name(){return this._name}setName(e){this._name=e}context(){return this._context}setContext(e){this._context=e}value(){return this._value}setValue(e){this._value=e}plus(e){return new jn(this,e)}minus(e){return new jn(this,typeof e=="number"?-e:[-1,e])}multiply(e){return new jn([e,this])}divide(e){return new jn([1/e,this])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},j3t=0;var jn=class n{constructor(){f(this,"_terms");f(this,"_constant");let e=B3t(arguments);this._terms=e.terms,this._constant=e.constant}terms(){return this._terms}constant(){return this._constant}value(){let e=this._constant;for(let t=0,i=this._terms.size();t<i;t++){let r=this._terms.itemAt(t);e+=r.first.value()*r.second}return e}plus(e){return new n(this,e)}minus(e){return new n(this,typeof e=="number"?-e:[-1,e])}multiply(e){return new n([e,this])}divide(e){return new n([1/e,this])}isConstant(){return this._terms.size()==0}toString(){let e=this._terms.array.map(function(t){return t.second+"*"+t.first.toString()}).join(" + ");return!this.isConstant()&&this._constant!==0&&(e+=" + "),e+=this._constant,e}};function B3t(n){let e=0,t=()=>0,i=Kc();for(let r=0,s=n.length;r<s;++r){let o=n[r];if(typeof o=="number")e+=o;else if(o instanceof Oa)i.setDefault(o,t).second+=1;else if(o instanceof jn){e+=o.constant();let a=o.terms();for(let c=0,l=a.size();c<l;c++){let u=a.itemAt(c);i.setDefault(u.first,t).second+=u.second}}else if(o instanceof Array){if(o.length!==2)throw new Error("array must have length 2");let a=o[0],c=o[1];if(typeof a!="number")throw new Error("array item 0 must be a number");if(c instanceof Oa)i.setDefault(c,t).second+=a;else if(c instanceof jn){e+=c.constant()*a;let l=c.terms();for(let u=0,p=l.size();u<p;u++){let d=l.itemAt(u);i.setDefault(d.first,t).second+=d.second*a}}else throw new Error("array item 1 must be a variable or expression")}else throw new Error("invalid Expression argument: "+o)}return{terms:i,constant:e}}var co=class co{static create(e,t,i,r=1){let s=0;return s+=Math.max(0,Math.min(1e3,e*r))*1e6,s+=Math.max(0,Math.min(1e3,t*r))*1e3,s+=Math.max(0,Math.min(1e3,i*r)),s}static clip(e){return Math.max(0,Math.min(co.required,e))}};f(co,"required",co.create(1e3,1e3,1e3)),f(co,"strong",co.create(1,0,0)),f(co,"medium",co.create(0,1,0)),f(co,"weak",co.create(0,0,1));var Ln=co;var ui;(function(n){n[n.Le=0]="Le",n[n.Ge=1]="Ge",n[n.Eq=2]="Eq"})(ui||(ui={}));var Mi=class{constructor(e,t,i,r=Ln.required){f(this,"_expression");f(this,"_operator");f(this,"_strength");f(this,"_id",Y3t++);this._operator=t,this._strength=Ln.clip(r),i===void 0&&e instanceof jn?this._expression=e:this._expression=e.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()+")"}},Y3t=0;var u_=class{constructor(){f(this,"maxIterations",1e3);f(this,"_cnMap",X3t());f(this,"_rowMap",U3t());f(this,"_varMap",V3t());f(this,"_editMap",G3t());f(this,"_infeasibleRows",[]);f(this,"_objective",new FS);f(this,"_artificial",null);f(this,"_idTick",0)}createConstraint(e,t,i,r=Ln.required){let s=new Mi(e,t,i,r);return this.addConstraint(s),s}addConstraint(e){if(this._cnMap.find(e)!==void 0)throw new Error("duplicate constraint");let i=this._createRow(e),r=i.row,s=i.tag,o=this._chooseSubject(r,s);if(o.type()===on.Invalid&&r.allDummies())if(OS(r.constant()))o=s.marker;else throw new Error("unsatisfiable constraint");if(o.type()===on.Invalid){if(!this._addWithArtificialVariable(r))throw new Error("unsatisfiable constraint")}else r.solveFor(o),this._substitute(o,r),this._rowMap.insert(o,r);this._cnMap.insert(e,s),this._optimize(this._objective)}removeConstraint(e){let t=this._cnMap.erase(e);if(t===void 0)throw new Error("unknown constraint");this._removeConstraintEffects(e,t.second);let i=t.second.marker,r=this._rowMap.erase(i);if(r===void 0){let s=this._getMarkerLeavingSymbol(i);if(s.type()===on.Invalid)throw new Error("failed to find leaving row");r=this._rowMap.erase(s),r.second.solveForEx(s,i),this._substitute(i,r.second)}this._optimize(this._objective)}hasConstraint(e){return this._cnMap.contains(e)}getConstraints(){return this._cnMap.array.map(({first:e})=>e)}addEditVariable(e,t){if(this._editMap.find(e)!==void 0)throw new Error("duplicate edit variable");if(t=Ln.clip(t),t===Ln.required)throw new Error("bad required strength");let r=new jn(e),s=new Mi(r,ui.Eq,void 0,t);this.addConstraint(s);let a={tag:this._cnMap.find(s).second,constraint:s,constant:0};this._editMap.insert(e,a)}removeEditVariable(e){let t=this._editMap.erase(e);if(t===void 0)throw new Error("unknown edit variable");this.removeConstraint(t.second.constraint)}hasEditVariable(e){return this._editMap.contains(e)}suggestValue(e,t){let i=this._editMap.find(e);if(i===void 0)throw new Error("unknown edit variable");let r=this._rowMap,s=i.second,o=t-s.constant;s.constant=t;let a=s.tag.marker,c=r.find(a);if(c!==void 0){c.second.add(-o)<0&&this._infeasibleRows.push(a),this._dualOptimize();return}let l=s.tag.other;if(c=r.find(l),c!==void 0){c.second.add(o)<0&&this._infeasibleRows.push(l),this._dualOptimize();return}for(let u=0,p=r.size();u<p;++u){let d=r.itemAt(u),_=d.second,g=_.coefficientFor(a);g!==0&&_.add(o*g)<0&&d.first.type()!==on.External&&this._infeasibleRows.push(d.first)}this._dualOptimize()}updateVariables(){let e=this._varMap,t=this._rowMap;for(let i=0,r=e.size();i<r;++i){let s=e.itemAt(i),o=t.find(s.second);o!==void 0?s.first.setValue(o.second.constant()):s.first.setValue(0)}}_getVarSymbol(e){let t=()=>this._makeSymbol(on.External);return this._varMap.setDefault(e,t).second}_createRow(e){let t=e.expression(),i=new FS(t.constant()),r=t.terms();for(let c=0,l=r.size();c<l;++c){let u=r.itemAt(c);if(!OS(u.second)){let p=this._getVarSymbol(u.first),d=this._rowMap.find(p);d!==void 0?i.insertRow(d.second,u.second):i.insertSymbol(p,u.second)}}let s=this._objective,o=e.strength(),a={marker:Jc,other:Jc};switch(e.op()){case ui.Le:case ui.Ge:{let c=e.op()===ui.Le?1:-1,l=this._makeSymbol(on.Slack);if(a.marker=l,i.insertSymbol(l,c),o<Ln.required){let u=this._makeSymbol(on.Error);a.other=u,i.insertSymbol(u,-c),s.insertSymbol(u,o)}break}case ui.Eq:{if(o<Ln.required){let c=this._makeSymbol(on.Error),l=this._makeSymbol(on.Error);a.marker=c,a.other=l,i.insertSymbol(c,-1),i.insertSymbol(l,1),s.insertSymbol(c,o),s.insertSymbol(l,o)}else{let c=this._makeSymbol(on.Dummy);a.marker=c,i.insertSymbol(c)}break}}return i.constant()<0&&i.reverseSign(),{row:i,tag:a}}_chooseSubject(e,t){let i=e.cells();for(let s=0,o=i.size();s<o;++s){let a=i.itemAt(s);if(a.first.type()===on.External)return a.first}let r=t.marker.type();return(r===on.Slack||r===on.Error)&&e.coefficientFor(t.marker)<0?t.marker:(r=t.other.type(),(r===on.Slack||r===on.Error)&&e.coefficientFor(t.other)<0?t.other:Jc)}_addWithArtificialVariable(e){let t=this._makeSymbol(on.Slack);this._rowMap.insert(t,e.copy()),this._artificial=e.copy(),this._optimize(this._artificial);let i=OS(this._artificial.constant());this._artificial=null;let r=this._rowMap.erase(t);if(r!==void 0){let o=r.second;if(o.isConstant())return i;let a=this._anyPivotableSymbol(o);if(a.type()===on.Invalid)return!1;o.solveForEx(t,a),this._substitute(a,o),this._rowMap.insert(a,o)}let s=this._rowMap;for(let o=0,a=s.size();o<a;++o)s.itemAt(o).second.removeSymbol(t);return this._objective.removeSymbol(t),i}_substitute(e,t){let i=this._rowMap;for(let r=0,s=i.size();r<s;++r){let o=i.itemAt(r);o.second.substitute(e,t),o.second.constant()<0&&o.first.type()!==on.External&&this._infeasibleRows.push(o.first)}this._objective.substitute(e,t),this._artificial&&this._artificial.substitute(e,t)}_optimize(e){let t=0;for(;t<this.maxIterations;){let i=this._getEnteringSymbol(e);if(i.type()===on.Invalid)return;let r=this._getLeavingSymbol(i);if(r.type()===on.Invalid)throw new Error("the objective is unbounded");let s=this._rowMap.erase(r).second;s.solveForEx(r,i),this._substitute(i,s),this._rowMap.insert(i,s),t++}throw new Error("solver iterations exceeded")}_dualOptimize(){let e=this._rowMap,t=this._infeasibleRows;for(;t.length!==0;){let i=t.pop(),r=e.find(i);if(r!==void 0&&r.second.constant()<0){let s=this._getDualEnteringSymbol(r.second);if(s.type()===on.Invalid)throw new Error("dual optimize failed");let o=r.second;e.erase(i),o.solveForEx(i,s),this._substitute(s,o),e.insert(s,o)}}}_getEnteringSymbol(e){let t=e.cells();for(let i=0,r=t.size();i<r;++i){let s=t.itemAt(i),o=s.first;if(s.second<0&&o.type()!==on.Dummy)return o}return Jc}_getDualEnteringSymbol(e){let t=Number.MAX_VALUE,i=Jc,r=e.cells();for(let s=0,o=r.size();s<o;++s){let a=r.itemAt(s),c=a.first,l=a.second;if(l>0&&c.type()!==on.Dummy){let p=this._objective.coefficientFor(c)/l;p<t&&(t=p,i=c)}}return i}_getLeavingSymbol(e){let t=Number.MAX_VALUE,i=Jc,r=this._rowMap;for(let s=0,o=r.size();s<o;++s){let a=r.itemAt(s),c=a.first;if(c.type()!==on.External){let l=a.second,u=l.coefficientFor(e);if(u<0){let p=-l.constant()/u;p<t&&(t=p,i=c)}}}return i}_getMarkerLeavingSymbol(e){let t=Number.MAX_VALUE,i=t,r=t,s=Jc,o=s,a=s,c=s,l=this._rowMap;for(let u=0,p=l.size();u<p;++u){let d=l.itemAt(u),_=d.second,g=_.coefficientFor(e);if(g===0)continue;let x=d.first;if(x.type()===on.External)c=x;else if(g<0){let b=-_.constant()/g;b<i&&(i=b,o=x)}else{let b=_.constant()/g;b<r&&(r=b,a=x)}}return o!==s?o:a!==s?a:c}_removeConstraintEffects(e,t){t.marker.type()===on.Error&&this._removeMarkerEffects(t.marker,e.strength()),t.other.type()===on.Error&&this._removeMarkerEffects(t.other,e.strength())}_removeMarkerEffects(e,t){let i=this._rowMap.find(e);i!==void 0?this._objective.insertRow(i.second,-t):this._objective.insertSymbol(e,-t)}_anyPivotableSymbol(e){let t=e.cells();for(let i=0,r=t.size();i<r;++i){let s=t.itemAt(i),o=s.first.type();if(o===on.Slack||o===on.Error)return s.first}return Jc}_makeSymbol(e){return new LS(e,this._idTick++)}};function OS(n){let e=1e-8;return n<0?-n<e:n<e}function X3t(){return Kc()}function U3t(){return Kc()}function V3t(){return Kc()}function G3t(){return Kc()}var on;(function(n){n[n.Invalid=0]="Invalid",n[n.External=1]="External",n[n.Slack=2]="Slack",n[n.Error=3]="Error",n[n.Dummy=4]="Dummy"})(on||(on={}));var LS=class{constructor(e,t){f(this,"_id");f(this,"_type");this._id=t,this._type=e}id(){return this._id}type(){return this._type}},Jc=new LS(on.Invalid,-1),FS=class n{constructor(e=0){f(this,"_cellMap",Kc());f(this,"_constant");this._constant=e}cells(){return this._cellMap}constant(){return this._constant}isConstant(){return this._cellMap.empty()}allDummies(){let e=this._cellMap;for(let t=0,i=e.size();t<i;++t)if(e.itemAt(t).first.type()!==on.Dummy)return!1;return!0}copy(){let e=new n(this._constant);return e._cellMap=this._cellMap.copy(),e}add(e){return this._constant+=e}insertSymbol(e,t=1){let i=this._cellMap.setDefault(e,()=>0);OS(i.second+=t)&&this._cellMap.erase(e)}insertRow(e,t=1){this._constant+=e._constant*t;let i=e._cellMap;for(let r=0,s=i.size();r<s;++r){let o=i.itemAt(r);this.insertSymbol(o.first,o.second*t)}}removeSymbol(e){this._cellMap.erase(e)}reverseSign(){this._constant=-this._constant;let e=this._cellMap;for(let t=0,i=e.size();t<i;++t){let r=e.itemAt(t);r.second=-r.second}}solveFor(e){let t=this._cellMap,r=-1/t.erase(e).second;this._constant*=r;for(let s=0,o=t.size();s<o;++s)t.itemAt(s).second*=r}solveForEx(e,t){this.insertSymbol(e,-1),this.solveFor(t)}coefficientFor(e){let t=this._cellMap.find(e);return t!==void 0?t.second:0}substitute(e,t){let i=this._cellMap.erase(e);i!==void 0&&this.insertRow(t,i.second)}};var ait=Vt(Nn(),1);tt();vt();vt();mr();var j4={};$c(j4,{areBoundsCompletelyInsidePolygon:()=>D4,areBoundsOverlappingPolygon:()=>$4,boundsAreaOverlap:()=>$q,boundsDistance:()=>Dq,boundsIntersection:()=>jq,clamp:()=>Hn,computeDistanceBetweenBoxes:()=>Fo,computeGapBetweenBoxes:()=>w4,computeManhattanDistanceBetweenBoxes:()=>Lg,distSq:()=>Nq,distance:()=>Di,doBoundsOverlap:()=>Qc,doSegmentsIntersect:()=>Ei,doesLineIntersectLine:()=>La,doesSegmentIntersectRect:()=>F4,findNearestPointsBetweenBoxSets:()=>Fg,getBoundingBox:()=>oo,getBoundsFromPoints:()=>lo,getSegmentIntersection:()=>fd,getUnitVectorFromDirection:()=>BS,getUnitVectorFromPointAToB:()=>jS,grid:()=>Bq,isPointInsidePolygon:()=>DS,isRectCompletelyInsidePolygon:()=>Fq,isRectOverlappingPolygon:()=>Lq,midpoint:()=>Iq,normalizeDegrees:()=>md,onSegment:()=>dd,orientation:()=>hd,pointToBoundsDistance:()=>Cq,pointToBoxDistance:()=>Eq,pointToSegmentClosestPoint:()=>Mq,pointToSegmentDistance:()=>vi,range:()=>zq,segmentToBoundsMinDistance:()=>Bg,segmentToBoxMinDistance:()=>zS,segmentToCircleMinDistance:()=>$S,segmentToSegmentMinDistance:()=>p_});function La([n,e],[t,i],{lineThickness:r=0}={}){return r===0?Ei(n,e,t,i):W3t(n,e,t,i)<=r}function Ei(n,e,t,i){let r=hd(n,e,t),s=hd(n,e,i),o=hd(t,i,n),a=hd(t,i,e);return!!(r!==s&&o!==a||r===0&&dd(n,t,e)||s===0&&dd(n,i,e)||o===0&&dd(t,n,i)||a===0&&dd(t,e,i))}function hd(n,e,t){let i=(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y);return i===0?0:i>0?1:2}function dd(n,e,t){return e.x<=Math.max(n.x,t.x)&&e.x>=Math.min(n.x,t.x)&&e.y<=Math.max(n.y,t.y)&&e.y>=Math.min(n.y,t.y)}function W3t(n,e,t,i){if(n.x===e.x&&n.y===e.y)return vi(n,t,i);if(t.x===i.x&&t.y===i.y)return vi(t,n,e);if(Ei(n,e,t,i))return 0;let r=[vi(n,t,i),vi(e,t,i),vi(t,n,e),vi(i,n,e)];return Math.min(...r)}function vi(n,e,t){let i=(t.x-e.x)**2+(t.y-e.y)**2;if(i===0)return Di(n,e);let r=((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/i;r=Math.max(0,Math.min(1,r));let s={x:e.x+r*(t.x-e.x),y:e.y+r*(t.y-e.y)};return Di(n,s)}function Di(n,e){let t=n.x-e.x,i=n.y-e.y;return Math.sqrt(t*t+i*i)}function fd(n,e,t,i){let r=e.x-n.x,s=e.y-n.y,o=i.x-t.x,a=i.y-t.y,c=n.x-t.x,l=n.y-t.y,u=r*a-s*o;if(Math.abs(u)<1e-10)return null;let p=(l*o-c*a)/u,d=(r*l-s*c)/u,_=1e-9;if(p>=-_&&p<=1+_&&d>=-_&&d<=1+_){let g=n.x+p*r,x=n.y+p*s;return{x:g,y:x}}return null}function F4(n,e,t){let i=c=>c.x>=t.minX&&c.x<=t.maxX&&c.y>=t.minY&&c.y<=t.maxY;if(i(n)||i(e))return!0;let r={x:t.minX,y:t.minY},s={x:t.maxX,y:t.minY},o={x:t.minX,y:t.maxY},a={x:t.maxX,y:t.maxY};return Ei(n,e,r,s)||Ei(n,e,s,a)||Ei(n,e,a,o)||Ei(n,e,o,r)}function p_(n,e,t,i){if(n.x===e.x&&n.y===e.y)return vi(n,t,i);if(t.x===i.x&&t.y===i.y)return vi(t,n,e);if(Ei(n,e,t,i))return 0;let r=[vi(n,t,i),vi(e,t,i),vi(t,n,e),vi(i,n,e)];return Math.min(...r)}function Bg(n,e,t){let i={x:t.minX,y:t.minY},r={x:t.maxX,y:t.minY},s={x:t.minX,y:t.maxY},o={x:t.maxX,y:t.maxY};if(Ei(n,e,i,r)||Ei(n,e,r,o)||Ei(n,e,o,s)||Ei(n,e,s,i)||n.x>=t.minX&&n.x<=t.maxX&&n.y>=t.minY&&n.y<=t.maxY&&e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)return 0;let a=[vi(i,n,e),vi(r,n,e),vi(s,n,e),vi(o,n,e)];if(n.x>=t.minX&&n.x<=t.maxX&&n.y>=t.minY&&n.y<=t.maxY||e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)return 0;if(n.x<t.minX||n.x>t.maxX||n.y<t.minY||n.y>t.maxY){let c=Hn(n.x,t.minX,t.maxX),l=Hn(n.y,t.minY,t.maxY);a.push(Di(n,{x:c,y:l}))}if(e.x<t.minX||e.x>t.maxX||e.y<t.minY||e.y>t.maxY){let c=Hn(e.x,t.minX,t.maxX),l=Hn(e.y,t.minY,t.maxY);a.push(Di(e,{x:c,y:l}))}return Math.min(...a)}function zS(n,e,t){let i=t.width/2,r=t.height/2,s={minX:t.center.x-i,maxX:t.center.x+i,minY:t.center.y-r,maxY:t.center.y+r};return Bg(n,e,s)}function $S(n,e,t){let i={x:t.x,y:t.y};if(n.x===e.x&&n.y===e.y)return Math.max(0,Di(n,i)-t.radius);let r={x:e.x-n.x,y:e.y-n.y},s={x:i.x-n.x,y:i.y-n.y},o=r.x*r.x+r.y*r.y,a=Math.max(0,Math.min(1,(r.x*s.x+r.y*s.y)/o)),c={x:n.x+a*r.x,y:n.y+a*r.y},l=Di(c,i);return Math.max(0,l-t.radius)}function Mq(n,e,t){let i=t.x-e.x,r=t.y-e.y,s=i*i+r*r;if(s===0)return{x:e.x,y:e.y};let o=((n.x-e.x)*i+(n.y-e.y)*r)/s;return o=Math.max(0,Math.min(1,o)),{x:e.x+o*i,y:e.y+o*r}}function md(n){return(n%360+360)%360}function Eq(n,e){let t=e.width/2,i=e.height/2,r=e.center.x-t,s=e.center.x+t,o=e.center.y-i,a=e.center.y+i;if(n.x>=r&&n.x<=s&&n.y>=o&&n.y<=a)return 0;let c=Hn(n.x,r,s),l=Hn(n.y,o,a);return Di(n,{x:c,y:l})}function Cq(n,e){if(n.x>=e.minX&&n.x<=e.maxX&&n.y>=e.minY&&n.y<=e.maxY)return 0;let t=Hn(n.x,e.minX,e.maxX),i=Hn(n.y,e.minY,e.maxY);return Di(n,{x:t,y:i})}function Iq(n,e){return{x:(n.x+e.x)/2,y:(n.y+e.y)/2}}function Nq(n,e){let t=n.x-e.x,i=n.y-e.y;return t*t+i*i}var Aq=n=>{if("minX"in n)return n;let e=n.width/2,t=n.height/2;return{minX:n.center.x-e,minY:n.center.y-t,maxX:n.center.x+e,maxY:n.center.y+t}},z4=n=>[{x:n.minX,y:n.minY},{x:n.maxX,y:n.minY},{x:n.maxX,y:n.maxY},{x:n.minX,y:n.maxY}],Rq=n=>{let e=[];for(let t=0;t<n.length;t++){let i=n[t],r=n[(t+1)%n.length];e.push([i,r])}return e},H3t=(n,e,t)=>{let i=(n.y-e.y)*(t.x-e.x)-(n.x-e.x)*(t.y-e.y);if(Math.abs(i)>1e-9)return!1;let r=(n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y);if(r<0)return!1;let s=(t.x-e.x)**2+(t.y-e.y)**2;return!(r>s)},q3t=(n,e)=>n.x>=e.minX&&n.x<=e.maxX&&n.y>=e.minY&&n.y<=e.maxY,DS=(n,e)=>{if(e.length<3)return!1;let t=Rq(e);for(let[r,s]of t)if(H3t(n,r,s))return!0;let i=!1;for(let r=0,s=e.length-1;r<e.length;s=r++){let o=e[r].x,a=e[r].y,c=e[s].x,l=e[s].y;a>n.y!=l>n.y&&n.x<(c-o)*(n.y-a)/(l-a)+o&&(i=!i)}return i},Oq=(n,e)=>{let t=z4(n),i=[[t[0],t[1]],[t[1],t[2]],[t[2],t[3]],[t[3],t[0]]],r=Rq(e);for(let[s,o]of r)for(let[a,c]of i)if(Ei(s,o,a,c))return!0;return!1},$4=(n,e)=>e.length<3?!1:e.some(i=>q3t(i,n))||z4(n).some(i=>DS(i,e))?!0:Oq(n,e),D4=(n,e)=>e.length<3||!z4(n).every(i=>DS(i,e))?!1:!Oq(n,e),Lq=(n,e)=>$4(Aq(n),e),Fq=(n,e)=>D4(Aq(n),e);function zq(n,e,t=1){if(t===0)throw new Error("step cannot be 0");let i,r;e===void 0?(i=0,r=n):(i=n,r=e);let s=[];if(t>0)for(let o=i;o<r;o+=t)s.push(o);else for(let o=i;o>r;o+=t)s.push(o);return s}var $q=(n,e)=>{let t=Math.max(0,Math.min(n.maxX,e.maxX)-Math.max(n.minX,e.minX)),i=Math.max(0,Math.min(n.maxY,e.maxY)-Math.max(n.minY,e.minY));return t*i};var Dq=(n,e)=>{let t=n.maxX<e.minX?e.minX-n.maxX:e.maxX<n.minX?n.minX-e.maxX:0,i=n.maxY<e.minY?e.minY-n.maxY:e.maxY<n.minY?n.minY-e.maxY:0;return Math.sqrt(t*t+i*i)};var jq=(n,e)=>{let t=Math.max(n.minX,e.minX),i=Math.max(n.minY,e.minY),r=Math.min(n.maxX,e.maxX),s=Math.min(n.maxY,e.maxY);return t>r||i>s?null:{minX:t,minY:i,maxX:r,maxY:s}};var Qc=(n,e)=>!(n.maxX<e.minX||e.maxX<n.minX||n.maxY<e.minY||e.maxY<n.minY);var lo=n=>{if(n.length===0)return null;let e=n[0].x,t=n[0].y,i=n[0].x,r=n[0].y;for(let s=1;s<n.length;s++){let o=n[s];o.x<e&&(e=o.x),o.y<t&&(t=o.y),o.x>i&&(i=o.x),o.y>r&&(r=o.y)}return{minX:e,minY:t,maxX:i,maxY:r}};var jS=(n,e)=>{let t={x:e.x-n.x,y:e.y-n.y},i=Math.sqrt(t.x**2+t.y**2);return{x:t.x/i,y:t.y/i}},BS=n=>{switch(n){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 Bq({rows:n,cols:e,xSpacing:t,ySpacing:i,width:r,height:s,offsetX:o=0,offsetY:a=0,yDirection:c="cartesian",centered:l=!0}){let u=t??1,p=i??1,d=r??e*u,_=s??n*p,g=l?-d/2:0,x=l?-_/2:0,b=r?r/e:u,S=s?s/n:p,P=[];for(let T=0;T<n;T++)for(let k=0;k<e;k++){let N=T*e+k,M=o+g+k*b+b/2,C=a+T*S+S/2,E=c==="cartesian"?a+x+(n-1-T)*S+S/2:a+x+T*S+S/2;P.push({index:N,center:{x:M,y:E},topLeft:{x:M-b/2,y:E+S/2},bottomRight:{x:M+b/2,y:E-S/2},row:T,col:k})}return P}vt();Yg();var Yq={name:"@tscircuit/capacity-autorouter",main:"./dist/index.js",version:"0.0.178",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","@tscircuit/rectdiff":"^0.0.7","@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.70","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:{"bun-match-svg":"^0.0.14","fast-json-stable-stringify":"^2.1.0","object-hash":"^3.0.0"}};vt();mr();Re();var F9=Vt(Qs(),1);vt();var fit=Vt(Nn(),1);var PN={};$c(PN,{AssignableViaAutoroutingPipelineSolver:()=>a4t,AutoroutingPipelineSolver:()=>TK,CapacityMeshSolver:()=>H5t,InMemoryCache:()=>YZ,LocalStorageCache:()=>XZ,calculateOptimalCapacityDepth:()=>xN,convertSrjToGraphicsObject:()=>r1,getGlobalInMemoryCache:()=>S_,getGlobalLocalStorageCache:()=>UZ,getTunedTotalCapacity1:()=>uo,setupGlobalCaches:()=>i1});var BZ=Vt(VS(),1),oK=Vt(VS(),1),lK=Vt(VS(),1);var bd=(...n)=>{let e={points:[],lines:[],circles:[],rects:[]};return n.forEach((t,i)=>{t&&(t.lines&&(e.lines=[...e.lines||[],...t.lines.map(r=>({...r,step:i}))]),t.points&&(e.points=[...e.points||[],...t.points.map(r=>({...r,step:i}))]),t.circles&&(e.circles=[...e.circles||[],...t.circles.map(r=>({...r,step:i}))]),t.rects&&(e.rects=[...e.rects||[],...t.rects.map(r=>({...r,step:i}))]))}),e},nn=class{constructor(){f(this,"MAX_ITERATIONS",1e3);f(this,"solved",!1);f(this,"failed",!1);f(this,"iterations",0);f(this,"progress",0);f(this,"error",null);f(this,"activeSubSolver");f(this,"failedSubSolvers");f(this,"timeToSolve");f(this,"stats",{});f(this,"cacheHit");f(this,"cacheKey");f(this,"cacheToSolveSpaceTransform")}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(n){throw this.error=`${this.constructor.name} error: ${n}`,console.error(this.error),this.failed=!0,n}!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 (MAX_ITERATIONS=${this.MAX_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 n=Date.now();for(;!this.solved&&!this.failed;)this.step();let e=Date.now();this.timeToSolve=e-n}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function g_(n){let e=new Map;for(let t of n)for(let i of t.nodeIds)e.set(i,[...e.get(i)??[],t]);return e}function Xr(){return Xr=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(n[i]=t[i])}return n},Xr.apply(null,arguments)}function cw(n,e){return(cw=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,i){return t.__proto__=i,t})(n,e)}function LZ(n){return(LZ=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(n)}function FZ(){try{var n=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(FZ=function(){return!!n})()}function eN(n){var e=typeof Map=="function"?new Map:void 0;return eN=function(t){if(t===null||!(function(r){try{return Function.toString.call(r).indexOf("[native code]")!==-1}catch{return typeof r=="function"}})(t))return t;if(typeof t!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return(function(r,s,o){if(FZ())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,s);var c=new(r.bind.apply(r,a));return o&&cw(c,o.prototype),c})(t,arguments,LZ(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),cw(i,t)},eN(n)}var Yr=(function(n){var e,t;function i(r){var s;if(1)s=n.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+r+" for more information.")||this;else for(var o,a,c;c<o;c++);return(function(l){if(l===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return l})(s)}return t=n,(e=i).prototype=Object.create(t.prototype),e.prototype.constructor=e,cw(e,t),i})(eN(Error));function nZ(n,e){return n.substr(-e.length)===e}var cIt=/^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;function iZ(n){return typeof n!="string"?n:n.match(cIt)?parseFloat(n):n}var rZ=function(n){return function(e,t){t===void 0&&(t="16px");var i=e,r=t;if(typeof e=="string"){if(!nZ(e,"px"))throw new Yr(69,n,e);i=iZ(e)}if(typeof t=="string"){if(!nZ(t,"px"))throw new Yr(70,n,t);r=iZ(t)}if(typeof i=="string")throw new Yr(71,e,n);if(typeof r=="string")throw new Yr(72,t,n);return""+i/r+n}};rZ("em"),rZ("rem");function U4(n){return Math.round(255*n)}function lIt(n,e,t){return U4(n)+","+U4(e)+","+U4(t)}function Qg(n,e,t,i){if(i===void 0&&(i=lIt),e===0)return i(t,t,t);var r=(n%360+360)%360/60,s=(1-Math.abs(2*t-1))*e,o=s*(1-Math.abs(r%2-1)),a=0,c=0,l=0;r>=0&&r<1?(a=s,c=o):r>=1&&r<2?(a=o,c=s):r>=2&&r<3?(c=s,l=o):r>=3&&r<4?(c=o,l=s):r>=4&&r<5?(a=o,l=s):r>=5&&r<6&&(a=s,l=o);var u=t-s/2;return i(a+u,c+u,l+u)}var sZ={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"},uIt=/^#[a-fA-F0-9]{6}$/,pIt=/^#[a-fA-F0-9]{8}$/,hIt=/^#[a-fA-F0-9]{3}$/,dIt=/^#[a-fA-F0-9]{4}$/,V4=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,fIt=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,mIt=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,_It=/^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 x_(n){if(typeof n!="string")throw new Yr(3);var e=(function(d){if(typeof d!="string")return d;var _=d.toLowerCase();return sZ[_]?"#"+sZ[_]:d})(n);if(e.match(uIt))return{red:parseInt(""+e[1]+e[2],16),green:parseInt(""+e[3]+e[4],16),blue:parseInt(""+e[5]+e[6],16)};if(e.match(pIt)){var t=parseFloat((parseInt(""+e[7]+e[8],16)/255).toFixed(2));return{red:parseInt(""+e[1]+e[2],16),green:parseInt(""+e[3]+e[4],16),blue:parseInt(""+e[5]+e[6],16),alpha:t}}if(e.match(hIt))return{red:parseInt(""+e[1]+e[1],16),green:parseInt(""+e[2]+e[2],16),blue:parseInt(""+e[3]+e[3],16)};if(e.match(dIt)){var i=parseFloat((parseInt(""+e[4]+e[4],16)/255).toFixed(2));return{red:parseInt(""+e[1]+e[1],16),green:parseInt(""+e[2]+e[2],16),blue:parseInt(""+e[3]+e[3],16),alpha:i}}var r=V4.exec(e);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var s=fIt.exec(e.substring(0,50));if(s)return{red:parseInt(""+s[1],10),green:parseInt(""+s[2],10),blue:parseInt(""+s[3],10),alpha:parseFloat(""+s[4])>1?parseFloat(""+s[4])/100:parseFloat(""+s[4])};var o=mIt.exec(e);if(o){var a="rgb("+Qg(parseInt(""+o[1],10),parseInt(""+o[2],10)/100,parseInt(""+o[3],10)/100)+")",c=V4.exec(a);if(!c)throw new Yr(4,e,a);return{red:parseInt(""+c[1],10),green:parseInt(""+c[2],10),blue:parseInt(""+c[3],10)}}var l=_It.exec(e.substring(0,50));if(l){var u="rgb("+Qg(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",p=V4.exec(u);if(!p)throw new Yr(4,e,u);return{red:parseInt(""+p[1],10),green:parseInt(""+p[2],10),blue:parseInt(""+p[3],10),alpha:parseFloat(""+l[4])>1?parseFloat(""+l[4])/100:parseFloat(""+l[4])}}throw new Yr(5)}function ol(n){return(function(e){var t,i=e.red/255,r=e.green/255,s=e.blue/255,o=Math.max(i,r,s),a=Math.min(i,r,s),c=(o+a)/2;if(o===a)return e.alpha!==void 0?{hue:0,saturation:0,lightness:c,alpha:e.alpha}:{hue:0,saturation:0,lightness:c};var l=o-a,u=c>.5?l/(2-o-a):l/(o+a);switch(o){case i:t=(r-s)/l+(r<s?6:0);break;case r:t=(s-i)/l+2;break;default:t=(i-r)/l+4}return t*=60,e.alpha!==void 0?{hue:t,saturation:u,lightness:c,alpha:e.alpha}:{hue:t,saturation:u,lightness:c}})(x_(n))}var nN=function(n){return n.length===7&&n[1]===n[2]&&n[3]===n[4]&&n[5]===n[6]?"#"+n[1]+n[3]+n[5]:n};function gd(n){var e=n.toString(16);return e.length===1?"0"+e:e}function G4(n){return gd(Math.round(255*n))}function yIt(n,e,t){return nN("#"+G4(n)+G4(e)+G4(t))}function GS(n,e,t){return Qg(n,e,t,yIt)}function iN(n,e,t){if(typeof n=="number"&&typeof e=="number"&&typeof t=="number")return nN("#"+gd(n)+gd(e)+gd(t));if(typeof n=="object"&&e===void 0&&t===void 0)return nN("#"+gd(n.red)+gd(n.green)+gd(n.blue));throw new Yr(6)}function fw(n,e,t,i){if(typeof n=="string"&&typeof e=="number"){var r=x_(n);return"rgba("+r.red+","+r.green+","+r.blue+","+e+")"}if(typeof n=="number"&&typeof e=="number"&&typeof t=="number"&&typeof i=="number")return i>=1?iN(n,e,t):"rgba("+n+","+e+","+t+","+i+")";if(typeof n=="object"&&e===void 0&&t===void 0&&i===void 0)return n.alpha>=1?iN(n.red,n.green,n.blue):"rgba("+n.red+","+n.green+","+n.blue+","+n.alpha+")";throw new Yr(7)}function al(n){if(typeof n!="object")throw new Yr(8);if((function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&typeof e.alpha=="number"})(n))return fw(n);if((function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&(typeof e.alpha!="number"||e.alpha===void 0)})(n))return iN(n);if((function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&typeof e.alpha=="number"})(n))return(function(e,t,i,r){if(typeof e=="number"&&typeof t=="number"&&typeof i=="number"&&typeof r=="number")return r>=1?GS(e,t,i):"rgba("+Qg(e,t,i)+","+r+")";if(typeof e=="object"&&t===void 0&&i===void 0&&r===void 0)return e.alpha>=1?GS(e.hue,e.saturation,e.lightness):"rgba("+Qg(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new Yr(2)})(n);if((function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&(typeof e.alpha!="number"||e.alpha===void 0)})(n))return(function(e,t,i){if(typeof e=="number"&&typeof t=="number"&&typeof i=="number")return GS(e,t,i);if(typeof e=="object"&&t===void 0&&i===void 0)return GS(e.hue,e.saturation,e.lightness);throw new Yr(1)})(n);throw new Yr(8)}function zZ(n,e,t){return function(){var i=t.concat(Array.prototype.slice.call(arguments));return i.length>=e?n.apply(this,i):zZ(n,e,i)}}function cs(n){return zZ(n,n.length,[])}cs(function(n,e){if(e==="transparent")return e;var t=ol(e);return al(Xr({},t,{hue:t.hue+parseFloat(n)}))});function v_(n,e,t){return Math.max(n,Math.min(e,t))}cs(function(n,e){if(e==="transparent")return e;var t=ol(e);return al(Xr({},t,{lightness:v_(0,1,t.lightness-parseFloat(n))}))});cs(function(n,e){if(e==="transparent")return e;var t=ol(e);return al(Xr({},t,{saturation:v_(0,1,t.saturation-parseFloat(n))}))});cs(function(n,e){if(e==="transparent")return e;var t=ol(e);return al(Xr({},t,{lightness:v_(0,1,t.lightness+parseFloat(n))}))});var $Z=cs(function(n,e,t){if(e==="transparent")return t;if(t==="transparent")return e;if(n===0)return t;var i=x_(e),r=Xr({},i,{alpha:typeof i.alpha=="number"?i.alpha:1}),s=x_(t),o=Xr({},s,{alpha:typeof s.alpha=="number"?s.alpha:1}),a=r.alpha-o.alpha,c=2*parseFloat(n)-1,l=((c*a===-1?c:c+a)/(1+c*a)+1)/2,u=1-l;return fw({red:Math.floor(r.red*l+o.red*u),green:Math.floor(r.green*l+o.green*u),blue:Math.floor(r.blue*l+o.blue*u),alpha:r.alpha*parseFloat(n)+o.alpha*(1-parseFloat(n))})});cs(function(n,e){if(e==="transparent")return e;var t=x_(e);return fw(Xr({},t,{alpha:v_(0,1,(100*(typeof t.alpha=="number"?t.alpha:1)+100*parseFloat(n))/100)}))});cs(function(n,e){if(e==="transparent")return e;var t=ol(e);return al(Xr({},t,{saturation:v_(0,1,t.saturation+parseFloat(n))}))});cs(function(n,e){return e==="transparent"?e:al(Xr({},ol(e),{hue:parseFloat(n)}))});cs(function(n,e){return e==="transparent"?e:al(Xr({},ol(e),{lightness:parseFloat(n)}))});cs(function(n,e){return e==="transparent"?e:al(Xr({},ol(e),{saturation:parseFloat(n)}))});cs(function(n,e){return e==="transparent"?e:$Z(parseFloat(n),"rgb(0, 0, 0)",e)});cs(function(n,e){return e==="transparent"?e:$Z(parseFloat(n),"rgb(255, 255, 255)",e)});var gIt=cs(function(n,e){if(e==="transparent")return e;var t=x_(e);return fw(Xr({},t,{alpha:v_(0,1,+(100*(typeof t.alpha=="number"?t.alpha:1)-100*parseFloat(n)).toFixed(2)/100)}))}),oZ=["blue","orange","purple","cyan","magenta","yellowgreen","darkgoldenrod","deeppink"],t1=(n,e)=>{let t={};for(let i=0;i<n.connections.length;i++){let r=n.connections[i],s=e?.getNetConnectedToId(r.name);s&&!t[s]&&(t[s]=`hsl(${300*i/n.connections.length}, 100%, 50%)`),t[r.name]=(s?t[s]:null)??`hsl(${340*i/n.connections.length}, 100%, 50%)`}return t},ti=(n,e)=>{try{return gIt(e,n)}catch(t){return console.error(t),n}},DZ=class extends nn{constructor({nodes:e,edges:t,capacityPaths:i,colorMap:r}){super();f(this,"nodes");f(this,"edges");f(this,"capacityPaths");f(this,"nodeMap");f(this,"nodeEdgeMap");f(this,"unprocessedNodeIds");f(this,"nodePortSegments");f(this,"colorMap");this.nodes=e,this.edges=t,this.nodeMap=new Map(e.map(s=>[s.capacityMeshNodeId,s])),this.nodeEdgeMap=g_(t),this.capacityPaths=i,this.colorMap=r??{},this.unprocessedNodeIds=[...new Set(i.flatMap(s=>s.nodeIds))],this.nodePortSegments=new Map}step(){let e=this.unprocessedNodeIds.pop();if(!e)return void(this.solved=!0);let t=[];for(let o of this.capacityPaths){let a=o.nodeIds.indexOf(e);a!==-1&&t.push({path:o,indexOfNodeInPath:a})}let i=this.nodeMap.get(e),r=[];for(let{path:o,indexOfNodeInPath:a}of t){let c=o.nodeIds[a-1],l=o.nodeIds[a+1];for(let u of[c,l]){let p=this.nodeMap.get(u);if(!p)continue;let d=xIt(i,p),_=p.availableZ.filter(x=>i.availableZ.includes(x));if(_.length===0)continue;let g={capacityMeshNodeId:e,start:d.start,end:d.end,connectionNames:[o.connectionName],availableZ:_};r.push(g)}}let s=(function(o){let a=[],c=o.map(l=>({...l,connectionNames:[...l.connectionNames],availableZ:[...l.availableZ].sort((u,p)=>u-p)}));for(;c.length>0;){let l=c.pop(),u=!1;for(let p=0;p<a.length;p++){let d=a[p],_=WS(d.start,l.start)&&WS(d.end,l.end)||WS(d.start,l.end)&&WS(d.end,l.start),g=bIt(d.availableZ,l.availableZ);if(_&&g){let x=new Set(d.connectionNames);l.connectionNames.forEach(b=>x.add(b)),d.connectionNames=Array.from(x),u=!0;break}}u||a.push(l)}return a})(r);this.nodePortSegments.set(e,s)}visualize(){let e={lines:[],points:[],rects:[],circles:[]};return this.nodePortSegments.forEach((t,i)=>{this.nodeMap.get(i),t.forEach(r=>{r.start.x,r.end.x;for(let s=0;s<r.connectionNames.length;s++){let o={x:.05*Math.max(...r.availableZ),y:.05*Math.max(...r.availableZ)},a={x:(r.start.x+r.end.x)/2,y:(r.start.y+r.end.y)/2},c={x:a.x+o.x,y:a.y+o.y};o.x>0&&e.lines.push({points:[a,c],strokeColor:"rgba(0, 0, 0, 0.25)",strokeDash:"5 5"}),e.points.push({x:c.x,y:c.y,label:`${i}: ${r.connectionNames.join(", ")}
162
162
  availableZ: ${r.availableZ.join(",")}
@@ -250,8 +250,8 @@ ${_.message}`):_}}let o=i.nodes.count()-1;for(let a=0;a<i.V.length;a++){let c=i.
250
250
  ${r.stack}`),i.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:i.phase,error:r.toString()})})}_emitRenderLifecycleEvent(e,t){l7t(`${e}:${t} ${this.getString()}`);let i=`renderable:renderLifecycle:${e}:${t}`,r={renderId:this._renderId,componentDisplayName:this.getString(),type:i};"root"in this&&this.root&&(this.root.emit(i,r),this.root.emit("renderable:renderLifecycle:anyEvent",{...r,type:i}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(e=>!e.complete)?!0:this.children.some(e=>typeof e._hasIncompleteAsyncEffects=="function"?e._hasIncompleteAsyncEffects():!1)}_hasIncompleteAsyncEffectsInSubtreeForPhase(e){for(let t of this._asyncEffects)if(!t.complete&&t.phase===e)return!0;for(let t of this.children)if(t._hasIncompleteAsyncEffectsInSubtreeForPhase(e))return!0;return!1}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(e=>e.getRenderGraph())}}getTopLevelRenderable(){let e=this;for(;e.parent&&e.parent instanceof tit;)e=e.parent;return e}runRenderCycle(){for(let e of Wa)this.runRenderPhaseForChildren(e),this.runRenderPhase(e)}runRenderPhase(e){this._currentRenderPhase=e;let t=this.renderPhaseStates[e],i=t.initialized,r=t.dirty;if(!i&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&i){this._emitRenderLifecycleEvent(e,"start"),this?.[`remove${e}`]?.(),t.initialized=!1,t.dirty=!1,this._emitRenderLifecycleEvent(e,"end");return}let s=Wa.indexOf(e)-1;if(s>=0){let a=Wa[s];if(this._asyncEffects.filter(l=>l.phase===a).some(l=>!l.complete))return}let o=u7t[e]||[];if(o.length>0){let a=this.getTopLevelRenderable();for(let c of o)if(a._hasIncompleteAsyncEffectsInSubtreeForPhase(c))return}if(this._emitRenderLifecycleEvent(e,"start"),i){r&&(this?.[`update${e}`]?.(),t.dirty=!1),this._emitRenderLifecycleEvent(e,"end");return}t.dirty=!1,this?.[`doInitial${e}`]?.(),t.initialized=!0,this._emitRenderLifecycleEvent(e,"end")}runRenderPhaseForChildren(e){for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}renderError(e){throw typeof e=="string"?new Error(e):new Error(JSON.stringify(e,null,2))}},mP={},eit=n=>{let e=Object.fromEntries(Object.entries(n).map(([t,i])=>[t.toLowerCase(),i]));Object.assign(mP,n),Object.assign(mP,e)},h7t=class extends Error{constructor(n,e,t){let i,r=Object.keys(t).filter(c=>c!=="_errors"),s=[],o=e.pinLabels;if(o)for(let[c,l]of Object.entries(o)){let u=Array.isArray(l)?l:[l];for(let p of u)typeof p=="string"&&(p.startsWith(" ")||p.endsWith(" "))&&s.push(`pinLabels.${c} ("${p}" has leading or trailing spaces)`)}let a=r.map(c=>c==="pinLabels"&&s.length>0?s.join(", "):t[c]._errors[0]?`${c} (${t[c]._errors[0]})`:`${c} (${JSON.stringify(t[c])})`).join(", ");"name"in e?i=`Invalid props for ${n} "${e.name}": ${a}`:"footprint"in e&&typeof e.footprint=="string"?i=`Invalid props for ${n} (unnamed ${e.footprint} component): ${a}`:i=`Invalid props for ${n} (unnamed): ${a}`,super(i),this.componentName=n,this.originalProps=e,this.formattedError=t}};function P9(n,e){let t=e.match(/^#(\w+)/);if(t)return n.props.id===t[1];let i=e.match(/^\.(\w+)/);if(i)return n.isMatchingNameOrAlias(i[1]);let[r,...s]=e.split(/(?=[#.[])/);return r==="pin"&&(r="port"),r&&r!=="*"&&n.lowercaseComponentName!==r.toLowerCase()?!1:s.every(o=>{if(o.startsWith("#"))return n.props.id===o.slice(1);if(o.startsWith("."))return n.isMatchingNameOrAlias(o.slice(1));let a=o.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!a)return!0;let[,c,l]=a;return n.props[c].toString()===l})}var d7t={mm:1};function f7t(n,e){let{knownVariables:t,units:i}=e,r={...d7t,...i??{}},s=m7t(n),o=_7t(s,r);return y7t(o,t)}function m7t(n){let e=n.trim();if(!e.toLowerCase().startsWith("calc"))return e;let t=e.match(/^calc\s*\((.*)\)$/is);if(!t)throw new Error(`Invalid calc() expression: "${n}"`);return t[1].trim()}function _7t(n,e){let t=[],i=0,r=a=>a>="0"&&a<="9",s=a=>a>="A"&&a<="Z"||a>="a"&&a<="z"||a==="_",o=a=>s(a)||r(a)||a===".";for(;i<n.length;){let a=n[i];if(a===" "||a===" "||a===`
251
251
  `||a==="\r"){i++;continue}if(r(a)||a==="."&&i+1<n.length&&r(n[i+1])){let c=i;for(i++;i<n.length;){let d=n[i];if(r(d)||d===".")i++;else break}let l=n.slice(c,i),u=Number(l);if(Number.isNaN(u))throw new Error(`Invalid number: "${l}"`);let p=i;for(;i<n.length&&/[A-Za-z]/.test(n[i]);)i++;if(i>p){let d=n.slice(p,i),_=e[d];if(_==null)throw new Error(`Unknown unit: "${d}"`);u*=_}t.push({type:"number",value:u});continue}if(s(a)){let c=i;for(i++;i<n.length&&o(n[i]);)i++;let l=n.slice(c,i);t.push({type:"identifier",value:l});continue}if(a==="("||a===")"){t.push({type:"paren",value:a}),i++;continue}if(a==="+"||a==="-"||a==="*"||a==="/"){t.push({type:"operator",value:a}),i++;continue}throw new Error(`Unexpected character "${a}" in expression "${n}"`)}return t}function y7t(n,e){let t=0,i=()=>n[t],r=()=>n[t++],s=()=>{let u=i();if(!u)throw new Error("Unexpected end of expression");if(u.type==="number")return r(),u.value;if(u.type==="identifier"){r();let p=e[u.value];if(p==null)throw new Error(`Unknown variable: "${u.value}"`);return p}if(u.type==="paren"&&u.value==="("){r();let p=c(),d=i();if(!d||d.type!=="paren"||d.value!==")")throw new Error('Expected ")"');return r(),p}throw new Error(`Unexpected token "${u.value}"`)},o=()=>{let u=i();if(u&&u.type==="operator"&&(u.value==="+"||u.value==="-")){r();let p=o();return u.value==="+"?p:-p}return s()},a=()=>{let u=o();for(;;){let p=i();if(!p||p.type!=="operator"||p.value!=="*"&&p.value!=="/")break;r();let d=o();p.value==="*"?u*=d:u/=d}return u},c=()=>{let u=a();for(;;){let p=i();if(!p||p.type!=="operator"||p.value!=="+"&&p.value!=="-")break;r();let d=a();p.value==="+"?u+=d:u-=d}return u},l=c();if(t<n.length){let u=n.slice(t).map(p=>"value"in p?p.value:"?").join(" ");throw new Error(`Unexpected tokens at end of expression: ${u}`)}return l}var Y9={isTag:n=>!0,getParent:n=>n.parent,getChildren:n=>n.children,getName:n=>n.lowercaseComponentName,getAttributeValue:(n,e)=>{if(e==="class"&&"getNameAndAliases"in n)return n.getNameAndAliases().join(" ");if(e==="name"&&n._parsedProps?.name)return n._parsedProps.name;if(n._parsedProps&&e in n._parsedProps){let i=n._parsedProps[e];return typeof i=="string"?i:i!=null?String(i):null}if(e in n){let i=n[e];return typeof i=="string"?i:i!=null?String(i):null}let t=n._attributeLowerToCamelNameMap;if(t){let i=t[e];if(i&&i in n){let r=n[i];return typeof r=="string"?r:r!=null?String(r):null}}return null},hasAttrib:(n,e)=>{if(e==="class")return!!n._parsedProps?.name;if(n._parsedProps&&e in n._parsedProps||e in n)return!0;let t=n._attributeLowerToCamelNameMap;if(t){let i=t[e];if(i&&i in n)return!0}return!1},getSiblings:n=>n.parent?n.parent.children:[],prevElementSibling:n=>{if(!n.parent)return null;let e=n.parent.children,t=e.indexOf(n);return t>0?e[t-1]:null},getText:()=>"",removeSubsets:n=>n.filter((e,t)=>!n.some((i,r)=>t!==r&&i!==e&&i.getDescendants().includes(e))),existsOne:(n,e)=>e.some(n),findAll:(n,e)=>{let t=[],i=r=>{n(r)&&t.push(r);for(let s of r.children)i(s)};for(let r of e)i(r);return t},findOne:(n,e)=>{for(let t of e){if(n(t))return t;let i=t.children;if(i.length>0){let r=Y9.findOne(n,i);if(r)return r}}return null},equals:(n,e)=>n._renderId===e._renderId,isHovered:n=>!1,isVisited:n=>!1,isActive:n=>!1},g7t={...Y9,getChildren:n=>n.children.filter(e=>!e.isSubcircuit)},gnt={...Y9,getChildren:n=>n.children.filter(e=>e.isSubcircuit)},x7t=(n,e)=>{let t=n.split("net.")[1]?.split(/[ >]/)[0]??n;return`Net names cannot contain "+" or "-" (component "${e?.componentName??"Unknown component"}" received "${t}" via "${n}"). Try using underscores instead, e.g. VCC_P`},xnt=(n,e)=>{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(x7t(n,e));if(/net\.[0-9]/.test(n)){let t=n.match(/net\.([^ >]+)/),i=t?t[1]:"";throw new Error(`Net name "${i}" cannot start with a number, try using a prefix like "VBUS1"`)}return n.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(t,i,r,s)=>{let o=/^\d+$/.test(s)?`pin${s}`:s;return`${i}.${r} > .${o}`}).trim()},k9={adapter:g7t,cacheResults:!0},Ce=class extends B9{constructor(e){super(e);f(this,"parent",null);f(this,"children");f(this,"childrenPendingRemoval");f(this,"props");f(this,"_parsedProps");f(this,"externallyAddedAliases");f(this,"isPrimitiveContainer",!1);f(this,"canHaveTextChildren",!1);f(this,"source_group_id",null);f(this,"source_component_id",null);f(this,"schematic_component_id",null);f(this,"pcb_component_id",null);f(this,"cad_component_id",null);f(this,"fallbackUnassignedName");f(this,"_cachedSelectAllQueries",new Map);f(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=e??{},this.externallyAddedAliases=[];let i=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(e??{});if(i.success)this._parsedProps=i.data;else throw new h7t(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:h.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(e){let t=this;for(;t;){if(t._parsedProps&&e in t._parsedProps)return t._parsedProps[e];t=t.parent}if(this.root?.platform&&e in this.root.platform)return this.root.platform[e]}getInheritedMergedProperty(e){let t=this.parent?.getInheritedMergedProperty?.(e),i=this._parsedProps?.[e];return{...t,...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(e){let t=this.config.zodProps.parse({...this.props,...e}),i=this.props;this.props=t,this._parsedProps=this.config.zodProps.parse(e),this.onPropsChange({oldProps:i,newProps:t,changedProps:Object.keys(e)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:e}=this.props;return typeof e=="string"?parseFloat(e):e??null}getResolvedPcbPositionProp(){return{pcbX:this._resolvePcbCoordinate(this._parsedProps.pcbX,"pcbX"),pcbY:this._resolvePcbCoordinate(this._parsedProps.pcbY,"pcbY")}}_resolvePcbCoordinate(e,t,i={}){if(e==null)return 0;if(typeof e=="number")return e;if(typeof e!="string")throw new Error(`Invalid ${t} value for ${this.componentName}: ${String(e)}`);let r=i.allowBoardVariables??this._isNormalComponent===!0,s=e.includes("board."),o={};if(r){let a=this._getBoard(),c=a?._getBoardCalcVariables()??{};if(s&&!a)throw new Error(`Cannot resolve ${t} for ${this.componentName}: no board found for board.* variables`);if(s&&a&&Object.keys(c).length===0)throw new Error("Cannot do calculations based on board size when the board is auto-sized");Object.assign(o,c)}try{return f7t(e,{knownVariables:o})}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Invalid ${t} value for ${this.componentName}: ${c}`)}}computePcbPropsTransform(){let e=this._getPcbRotationBeforeLayout()??0,{pcbX:t,pcbY:i}=this.getResolvedPcbPositionProp();return ai(Tn(t,i),Oo(e*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let e=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(e&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let t=this._getPcbRotationBeforeLayout()??0;return ai(this.parent?._computePcbGlobalTransformBeforeLayout()??Pr(),ai(Tn(e.x,e.y),Oo(t*Math.PI/180)))}if(this.isPcbPrimitive){let t=this.getPrimitiveContainer();if(t&&t._parsedProps.layer==="bottom")return ai(this.parent?._computePcbGlobalTransformBeforeLayout()??Pr(),pY(),this.computePcbPropsTransform())}return ai(this.parent?._computePcbGlobalTransformBeforeLayout()??Pr(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}getParentNormalComponent(){let e=this.parent;for(;e;){if(e.isPrimitiveContainer&&e.doInitialPcbComponentRender)return e;e=e.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 e=this.getPrimitiveContainer(),t=e?e._parsedProps.layer==="bottom":!1;return{isFlipped:t,maybeFlipLayer:r=>t?r==="top"?"bottom":"top":r}}_setPositionFromLayout(e){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:e}=this;return ai(Tn(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){let e=this._getSchematicGlobalManualPlacementTransform(this);return e||ai(this.parent?.computeSchematicGlobalTransform?.()??Pr(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:e}=this,t=this.config.schematicSymbolName,i={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},r=e.schOrientation!==void 0?i[e.schOrientation]:e.schRotation;if(r===void 0&&(r=0),r=r%360,r<0&&(r+=360),e.schRotation!==void 0&&r%90!==0)throw new Error(`Schematic rotation ${e.schRotation} is not supported for ${this.componentName}`);let s=`${t}_horz`,o=`${t}_vert`,a=`${t}_up`,c=`${t}_down`,l=`${t}_left`,u=`${t}_right`;if(u in bi&&r===0)return u;if(a in bi&&r===90)return a;if(l in bi&&r===180)return l;if(c in bi&&r===270)return c;if(s in bi&&(r===0||r===180))return s;if(o in bi&&(r===90||r===270))return o;if(t in bi)return t}_getSchematicSymbolNameOrThrow(){let e=this._getSchematicSymbolName();if(!e)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return e}getSchematicSymbol(){let e=this._getSchematicSymbolName();return e?bi[e]??null:null}_getPcbManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let t=this.props.manualEdits;if(!t)return null;let i=t?.pcb_placements;if(!i)return null;for(let r of i)if(P9(e,r.selector)||e.props.name===r.selector)return je(this._computePcbGlobalTransformBeforeLayout(),r.center);return null}_getSchematicManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let t=this.props.manualEdits;if(!t)return null;let i=t.schematic_placements;if(!i)return null;for(let r of i)if(P9(e,r.selector)||e.props.name===r.selector)return je(this.computeSchematicGlobalTransform(),r.center);return null}_getSchematicGlobalManualPlacementTransform(e){let t=this.getSubcircuit()?._parsedProps.manualEdits;if(!t)return null;for(let i of t.schematic_placements??[])if((P9(e,i.selector)||e.props.name===i.selector)&&i.relative_to==="group_center")return ai(this.parent?._computePcbGlobalTransformBeforeLayout()??Pr(),Tn(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return je(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return je(this.computeSchematicGlobalTransform(),{x:0,y:0})}_getBoard(){let e=this;for(;e;){let t=e;if(t.componentName==="Board")return t;e=e.parent??null}return this.root?._getBoard()}get root(){return this.parent?.root??null}onAddToParent(e){this.parent=e}onPropsChange(e){}onChildChanged(e){this.parent?.onChildChanged?.(e)}add(e){let t=e.__text;if(typeof t=="string"){if(this.canHaveTextChildren||t.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${t}"`)}if(Object.keys(e).length!==0){if(this.lowercaseComponentName==="board"&&e.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(e.lowercaseComponentName==="panel")throw new Error("<panel> must be a root-level element");if(!e.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(e)}"`);e.onAddToParent(this),e.parent=this,this.children.push(e)}}addAll(e){for(let t of e)this.add(t)}remove(e){this.children=this.children.filter(t=>t!==e),this.childrenPendingRemoval.push(e),e.shouldBeRemoved=!0}getSubcircuitSelector(){let e=this.name,t=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?t:`${this.parent.getSubcircuitSelector()} > ${t}`}getFullPathSelector(){let e=this.name,t=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName,i=this.parent?.getFullPathSelector?.();return i?`${i} > ${t}`:t}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(e){return this.getNameAndAliases().includes(e)}isMatchingAnyOf(e){return this.getNameAndAliases().some(t=>e.map(i=>i.toString()).includes(t))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(e){let t=[this.componentName,this.lowercaseComponentName],i=[this.name].filter(Boolean),r=e.trim().split(/\> /)[0],s=r[0];return r.length>1?!1:!!(e==="*"||e[0]==="#"&&e.slice(1)===this.props.id||e[0]==="."&&i.includes(e.slice(1))||/^[a-zA-Z0-9_]/.test(s)&&t.includes(s))}getSubcircuit(){if(this.isSubcircuit)return this;let e=this.parent?.getSubcircuit?.();if(!e)throw new Error("Component is not inside an opaque group (no board?)");return e}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 e=this.selectAll("port");for(let t of e){let r=(t.getParentNormalComponent?.()??t.parent)?.getNameAndAliases(),s=t.getNameAndAliases();if(r)for(let o of r)for(let a of s){let c=[`.${o} > .${a}`,`.${o} .${a}`];for(let l of c){let u=this._cachedSelectAllQueries.get(l);u?u.push(t):this._cachedSelectAllQueries.set(l,[t])}}}for(let[t,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(t,i[0])}selectAll(e){if(this._cachedSelectAllQueries.has(e))return this._cachedSelectAllQueries.get(e);let t=xnt(e,this),i=p4(t,this,k9);if(i.length>0)return this._cachedSelectAllQueries.set(e,i),i;let[r,...s]=t.split(" "),o=bS(r,this,{adapter:gnt});if(!o)return[];let a=o.selectAll(s.join(" "));return this._cachedSelectAllQueries.set(e,a),a}selectOne(e,t){if(this._cachedSelectOneQueries.has(e))return this._cachedSelectOneQueries.get(e);let i=xnt(e,this);t?.port&&(t.type="port");let r=null;if(t?.type&&(r=p4(i,this,k9).find(l=>l.lowercaseComponentName===t.type)),r??(r=bS(i,this,k9)),r)return this._cachedSelectOneQueries.set(e,r),r;let[s,...o]=i.split(" "),a=bS(s,this,{adapter:gnt});return a?(r=a.selectOne(o.join(" "),t),this._cachedSelectOneQueries.set(e,r),r):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:e}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[e(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?[...this.root?._getBoard()?.allLayers??["top","bottom"]]:[]}return[]}getDescendants(){let e=[];for(let t of this.children)e.push(t),e.push(...t.getDescendants());return e}getSelectableDescendants(){let e=[];for(let t of this.children)t.isSubcircuit?e.push(t):(e.push(t),e.push(...t.getSelectableDescendants()));return e}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this;return{schWidth:e.schWidth,schHeight:e.schHeight}}renderError(e){if(typeof e=="string")return super.renderError(e);switch(e.type){case"pcb_placement_error":this.root?.db.pcb_placement_error.insert(e);break;case"pcb_via_clearance_error":this.root?.db.pcb_via_clearance_error.insert(e);break;case"pcb_trace_error":this.root?.db.pcb_trace_error.insert(e);break;case"pcb_manual_edit_conflict_warning":this.root?.db.pcb_manual_edit_conflict_warning.insert(e);break;default:this.root?.db.pcb_placement_error.insert(e)}}getString(){let{lowercaseComponentName:e,_parsedProps:t,parent:i}=this;return t?.pinNumber!==void 0&&i?.props?.name&&t?.name?`<${e}#${this._renderId}(pin:${t.pinNumber} .${i?.props.name}>.${t.name}) />`:i?.props?.name&&t?.name?`<${e}#${this._renderId}(.${i?.props.name}>.${t?.name}) />`:t?.from&&t?.to?`<${e}#${this._renderId}(from:${t.from} to:${t?.to}) />`:t?.name?`<${e}#${this._renderId} name=".${t?.name}" />`:t?.portHints?`<${e}#${this._renderId}(${t.portHints.map(r=>`.${r}`).join(", ")}) />`:`<${e}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},b7t=class extends Ce{constructor(n,e){super(n);let t=(i,r)=>{if(typeof i=="number")return i;if(typeof i=="string")try{return this._resolvePcbCoordinate(i,r,{allowBoardVariables:!1})}catch{return 0}return 0};this._parsedProps={...n,error:e,type:n.type||"unknown",component_name:n.name,error_type:"source_failed_to_create_component_error",message:e instanceof Error?e.message:String(e),pcbX:t(n.pcbX,"pcbX"),pcbY:t(n.pcbY,"pcbY"),schX:n.schX,schY:n.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:h.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let n=this._getGlobalPcbPositionBeforeLayout(),e=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:n,schematic_center:e})}}};function v7t(n,e){return new b7t(n,e)}function S7t(n,e){let t=n;return t.__tsci={...e},n}var w7t={supportsMutation:!0,createInstance(n,e){let t=mP[n];if(!t)throw Object.keys(mP).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type "${n}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return S7t(new t(e),{})}catch(i){return v7t({...e,componentType:n},i)}},createTextInstance(n){return{__text:n}},appendInitialChild(n,e){n.add(e)},appendChild(n,e){n.add(e)},appendChildToContainer(n,e){n.add(e)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(n){return n},preparePortalMount(n){throw new Error("Function not implemented.")},scheduleTimeout(n,e){throw new Error("Function not implemented.")},cancelTimeout(n){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(n){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(n,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:n=>{throw new Error("Function not implemented.")},detachDeletedInstance:n=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>pP.DefaultEventPriority,getCurrentUpdatePriority:()=>pP.DefaultEventPriority,resolveUpdatePriority:()=>pP.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},aP=(0,Jnt.default)(w7t),nit=n=>{let e={children:[],props:{name:"$root"},add(s){s.parent=this,this.children.push(s)},computePcbGlobalTransform(){return Pr()}},t=[],i=aP.createContainer(e,0,null,!1,null,"tsci",s=>{console.log("Error in createContainer"),console.error(s),t.push(s)},null);if(aP.updateContainerSync(n,i,null,()=>{}),aP.flushSyncWork(),t.length>0)throw t[0];let r=aP.getPublicRootInstance(i);return r||e.children[0]},t0=(n,e)=>{if(typeof n=="number")return n;if(n.startsWith("pin"))return Number(n.slice(3));if(!e)throw new Error(`No pin labels provided and pin number or label is not a number: "${n}"`);for(let t in e)if((Array.isArray(e[t])?e[t]:[e[t]]).includes(n))return Number(t.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${n}"`)},P7t=(n,e)=>{if(!n)return;let t={},i={};for(let[r,s]of Object.entries(n)){let o=t0(r,e);i[o]={...i[o],...s}}for(let[r,s]of Object.entries(i)){let o=`pin${r}`;t[o]={bottom_margin:s.bottomMargin,left_margin:s.leftMargin,right_margin:s.rightMargin,top_margin:s.topMargin}}return t},k7t=n=>{if(n){if("leftSide"in n||"rightSide"in n||"topSide"in n||"bottomSide"in n)return{left_side:n.leftSide,right_side:n.rightSide,top_side:n.topSide,bottom_side:n.bottomSide};if("leftPinCount"in n||"rightPinCount"in n||"topPinCount"in n||"bottomPinCount"in n)return{left_size:n.leftPinCount,right_size:n.rightPinCount,top_size:n.topPinCount,bottom_size:n.bottomPinCount};if("leftSize"in n||"rightSize"in n||"topSize"in n||"bottomSize"in n)return{left_size:n.leftSize,right_size:n.rightSize,top_size:n.topSize,bottom_size:n.bottomSize}}};function iit(n){let e=[];for(let t=0;t<n.length-1;t++)e.push([n[t],n[t+1]]);return e}var T7t=h.object({name:h.string().refine(n=>!/[+-]/.test(n),n=>({message:`Net names cannot contain "+" or "-" (component "Net" received "${n}"). Try using underscores instead, e.g. VCC_P`}))}),X9=class extends Ce{constructor(){super(...arguments);f(this,"source_net_id");f(this,"subcircuit_connectivity_map_key",null)}get config(){return{componentName:"Net",zodProps:T7t}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=t.name.startsWith("GND"),r=t.name.startsWith("V"),s=e.source_net.insert({name:t.name,member_source_group_ids:[],is_ground:i,is_power:r,is_positive_voltage_source:r});this.source_net_id=s.source_net_id}doInitialSourceParentAttachment(){let e=this.getSubcircuit();if(!e)return;let{db:t}=this.root;t.source_net.update(this.source_net_id,{subcircuit_id:e.subcircuit_id})}getAllConnectedPorts(){let e=this.getSubcircuit().selectAll("port"),t=[];for(let i of e){let r=i._getDirectlyConnectedTraces();for(let s of r)if(s._isExplicitlyConnectedToNet(this)){t.push(i);break}}return t}_getAllDirectlyConnectedTraces(){let e=this.getSubcircuit().selectAll("trace"),t=[];for(let i of e)i._isExplicitlyConnectedToNet(this)&&t.push(i);return t}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getAllDirectlyConnectedTraces().filter(o=>(o._portsRoutedOnPcb?.length??0)>0),r=[];for(let o of i){let a=o._portsRoutedOnPcb,c=r.find(l=>a.some(u=>l.ports.includes(u)));if(!c){r.push({ports:[...a],traces:[o]});continue}c.traces.push(o),c.ports.push(...a)}if(r.length===0)return;let s=iit(r);for(let[o,a]of s){let c=o.ports.map(S=>S._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(S=>S._getGlobalPcbPositionBeforeLayout()),u=1/0,p=[-1,-1];for(let S=0;S<c.length;S++){let P=c[S];for(let T=0;T<l.length;T++){let k=l[T],N=Math.sqrt((P.x-k.x)**2+(P.y-k.y)**2);N<u&&(u=N,p=[S,T])}}let d=o.ports[p[0]],_=a.ports[p[1]],g=e.toArray().filter(S=>S.type==="pcb_smtpad"||S.type==="pcb_trace"||S.type==="pcb_plated_hole"||S.type==="pcb_hole"||S.type==="source_port"||S.type==="pcb_port"),{solution:x}=QW(g.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[d.source_port_id,_.source_port_id]}])),b=x[0];if(!b){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}e.pcb_trace.insert(b)}}renderError(e){if(typeof e=="string")return super.renderError(e);this.root?.db.pcb_trace_error.insert(e)}},bP=(n,e)=>{for(let t of e)if(typeof t=="string"&&t.startsWith("net.")){if(/net\.[^\s>]*\./.test(t))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(t)){let r=t.split("net.")[1],s=`Net names cannot contain "+" or "-" (component "${n.componentName}" received "${r}" via "${t}"). Try using underscores instead, e.g. VCC_P`;throw new Error(s)}if(/net\.[0-9]/.test(t)){let r=t.split("net.")[1];throw new Error(`Net name "${r}" cannot start with a number, try using a prefix like "VBUS1"`)}let i=n.getSubcircuit();if(!i.selectOne(t)){let r=new X9({name:t.split("net.")[1]});i.add(r)}}},J1=class extends Ce{constructor(){super(...arguments);f(this,"pcb_smtpad_id",null);f(this,"matchedPort",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:MH}}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="rotated_rect"){let i=(e.ccwRotation??0)*Math.PI/180,r=Math.cos(i),s=Math.sin(i),o=Math.abs(e.width*r)+Math.abs(e.height*s),a=Math.abs(e.width*s)+Math.abs(e.height*r);return{width:o,height:a}}if(e.shape==="polygon"){let t=e.points,i=t.map(l=>l.x),r=t.map(l=>l.y),s=Math.min(...i),o=Math.max(...i),a=Math.min(...r),c=Math.max(...r);return{width:o-s,height:c-a}}if(e.shape==="pill")return{width:e.width,height:e.height};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let t of e)if(t.isMatchingAnyOf(this.props.portHints)){this.matchedPort=t,t.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t.coveredWithSolderMask??!1,r=!i,s=t.solderMaskMargin,o=this.getSubcircuit(),a=this._getGlobalPcbPositionBeforeLayout(),c=this._computePcbGlobalTransformBeforeLayout(),p=(ro(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,d=.01,_=Math.abs(p)<d||Math.abs(p-180)<d||Math.abs(p-360)<d,g=Math.abs(p-90)<d||Math.abs(p-270)<d,x=Math.abs(p-360)<d?0:p,b=x,{maybeFlipLayer:S,isFlipped:P}=this._getPcbPrimitiveFlippedHelpers();P&&(x=(360-x+360)%360);let T=t.portHints?.map(M=>M.toString())??[],k=null,N=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(t.shape==="circle")k=e.pcb_smtpad.insert({pcb_component_id:N,pcb_port_id:this.matchedPort?.pcb_port_id,layer:S(t.layer??"top"),shape:"circle",radius:t.radius,port_hints:T,is_covered_with_solder_mask:i,soldermask_margin:s,x:a.x,y:a.y,subcircuit_id:o?.subcircuit_id??void 0}),r&&e.pcb_solder_paste.insert({layer:k.layer,shape:"circle",radius:k.radius*.7,x:k.x,y:k.y,pcb_component_id:k.pcb_component_id,pcb_smtpad_id:k.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});else if(t.shape==="rect")!_&&!g?k=e.pcb_smtpad.insert({pcb_component_id:N,pcb_port_id:this.matchedPort?.pcb_port_id,layer:S(t.layer??"top"),shape:"rotated_rect",width:t.width,height:t.height,corner_radius:t.cornerRadius??void 0,x:a.x,y:a.y,ccw_rotation:x,port_hints:T,is_covered_with_solder_mask:i,soldermask_margin:s,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):k=e.pcb_smtpad.insert({pcb_component_id:N,pcb_port_id:this.matchedPort?.pcb_port_id,layer:S(t.layer??"top"),shape:"rect",width:g?t.height:t.width,height:g?t.width:t.height,corner_radius:t.cornerRadius??void 0,port_hints:T,is_covered_with_solder_mask:i,soldermask_margin:s,x:a.x,y:a.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&(k.shape==="rect"?e.pcb_solder_paste.insert({layer:S(t.layer??"top"),shape:"rect",width:k.width*.7,height:k.height*.7,x:k.x,y:k.y,pcb_component_id:k.pcb_component_id,pcb_smtpad_id:k.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):k.shape==="rotated_rect"&&e.pcb_solder_paste.insert({layer:S(t.layer??"top"),shape:"rotated_rect",width:k.width*.7,height:k.height*.7,x:k.x,y:k.y,ccw_rotation:k.ccw_rotation,pcb_component_id:k.pcb_component_id,pcb_smtpad_id:k.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));else if(t.shape==="rotated_rect"){let M=t.ccwRotation??0,C=(b+M+360)%360,E=P?(360-C+360)%360:C;k=e.pcb_smtpad.insert({pcb_component_id:N,pcb_port_id:this.matchedPort?.pcb_port_id,layer:S(t.layer??"top"),shape:"rotated_rect",width:t.width,height:t.height,corner_radius:t.cornerRadius??void 0,x:a.x,y:a.y,ccw_rotation:E,port_hints:T,is_covered_with_solder_mask:i,soldermask_margin:s,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&e.pcb_solder_paste.insert({layer:S(t.layer??"top"),shape:"rotated_rect",width:k.width*.7,height:k.height*.7,x:a.x,y:a.y,ccw_rotation:E,pcb_component_id:N,pcb_smtpad_id:k.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(t.shape==="polygon"){let M=t.points.map(C=>{let E=je(c,{x:V.parse(C.x),y:V.parse(C.y)});return{x:E.x,y:E.y}});k=e.pcb_smtpad.insert({pcb_component_id:N,pcb_port_id:this.matchedPort?.pcb_port_id,layer:S(t.layer??"top"),shape:"polygon",points:M,port_hints:T,is_covered_with_solder_mask:i,soldermask_margin:s,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else t.shape==="pill"&&(k=e.pcb_smtpad.insert({pcb_component_id:N,pcb_port_id:this.matchedPort?.pcb_port_id,layer:S(t.layer??"top"),shape:"pill",x:a.x,y:a.y,radius:t.radius,height:t.height,width:t.width,port_hints:T,is_covered_with_solder_mask:i,soldermask_margin:s,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));k&&(this.pcb_smtpad_id=k.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_smtpad.get(this.pcb_smtpad_id);if(t.shape==="rect")return{center:{x:t.x,y:t.y},bounds:{left:t.x-t.width/2,top:t.y+t.height/2,right:t.x+t.width/2,bottom:t.y-t.height/2},width:t.width,height:t.height};if(t.shape==="rotated_rect"){let i=t.ccw_rotation*Math.PI/180,r=Math.cos(i),s=Math.sin(i),o=t.width/2,a=t.height/2,c=Math.abs(o*r)+Math.abs(a*s),l=Math.abs(o*s)+Math.abs(a*r);return{center:{x:t.x,y:t.y},bounds:{left:t.x-c,right:t.x+c,top:t.y-l,bottom:t.y+l},width:c*2,height:l*2}}if(t.shape==="circle")return{center:{x:t.x,y:t.y},bounds:{left:t.x-t.radius,top:t.y-t.radius,right:t.x+t.radius,bottom:t.y+t.radius},width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){let i=t.points,r=i.map(u=>u.x),s=i.map(u=>u.y),o=Math.min(...r),a=Math.max(...r),c=Math.min(...s),l=Math.max(...s);return{center:{x:(o+a)/2,y:(c+l)/2},bounds:{left:o,top:l,right:a,bottom:c},width:a-o,height:l-c}}if(t.shape==="pill"){let i=t.width/2,r=t.height/2;return{center:{x:t.x,y:t.y},bounds:{left:t.x-i,top:t.y-r,right:t.x+i,bottom:t.y+r},width:t.width,height:t.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${t.shape}"`)}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{x:e.x,y:e.y});let i=t.pcb_solder_paste.list().find(r=>r.pcb_smtpad_id===this.pcb_smtpad_id);i&&t.pcb_solder_paste.update(i.pcb_solder_paste_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}},U9=class extends Ce{constructor(){super(...arguments);f(this,"pcb_silkscreen_path_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:mq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let s=this._computePcbGlobalTransformBeforeLayout(),o=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=e.pcb_silkscreen_path.insert({pcb_component_id:a,layer:r,route:t.route.map(l=>{let u=je(s,{x:l.x,y:l.y});return{...l,x:u.x,y:u.y}}),stroke_width:t.strokeWidth??.1,subcircuit_id:o?.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(e){let{db:t}=this.root,{_parsedProps:i}=this,r=t.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!r)return;let s=0,o=0;for(let u of r.route)s+=u.x,o+=u.y;s/=r.route.length,o/=r.route.length;let a=e.x-s,c=e.y-o,l=r.route.map(u=>({...u,x:u.x+a,y:u.y+c}));t.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:l})}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let o of e.route)t=Math.min(t,o.x),i=Math.max(i,o.x),r=Math.min(r,o.y),s=Math.max(s,o.y);return{width:i-t,height:s-r}}},M7t=h.object({route:h.array(lb),source_trace_id:h.string().optional()}),V9=class extends Ce{constructor(){super(...arguments);f(this,"pcb_trace_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:M7t}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getPrimitiveContainer(),r=this.getSubcircuit(),{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),o=this._computePcbGlobalTransformBeforeLayout(),a=t.route.map(l=>{let{x:u,y:p,...d}=l,_=je(o,{x:u,y:p});return l.route_type==="wire"&&l.layer?{..._,...d,layer:s(l.layer)}:{..._,...d}}),c=e.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:t.source_trace_id,route:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let o of e.route)t=Math.min(t,o.x),i=Math.max(i,o.x),r=Math.min(r,o.y),s=Math.max(s,o.y),o.route_type==="wire"&&(t=Math.min(t,o.x-o.width/2),i=Math.max(i,o.x+o.width/2),r=Math.min(r,o.y-o.width/2),s=Math.max(s,o.y+o.width/2));return t===1/0||i===-1/0||r===1/0||s===-1/0?{width:0,height:0}:{width:i-t,height:s-r}}},jd=class extends Ce{constructor(){super(...arguments);f(this,"pcb_plated_hole_id",null);f(this,"matchedPort",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:yH}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.outerDiameter,height:e.outerDiameter};if(e.shape==="oval"||e.shape==="pill")return{width:e.outerWidth,height:e.outerHeight};if(e.shape==="circular_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};if(e.shape==="pill_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};if(e.shape==="hole_with_polygon_pad"){if(!e.padOutline||e.padOutline.length===0)throw new Error("padOutline is required for hole_with_polygon_pad shape");let t=e.padOutline.map(c=>typeof c.x=="number"?c.x:parseFloat(String(c.x))),i=e.padOutline.map(c=>typeof c.y=="number"?c.y:parseFloat(String(c.y))),r=Math.min(...t),s=Math.max(...t),o=Math.min(...i),a=Math.max(...i);return{width:s-r,height:a-o}}throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_plated_hole.get(this.pcb_plated_hole_id),i=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-i.width/2,top:t.y+i.height/2,right:t.x+i.width/2,bottom:t.y-i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let t of e)if(t.isMatchingAnyOf(this.props.portHints)){this.matchedPort=t,t.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,s=this.getSubcircuit(),o=t.solderMaskMargin,a=t.coveredWithSolderMask??!1;if(t.shape==="circle"){let c=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:t.outerDiameter,hole_diameter:t.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],soldermask_margin:o,is_covered_with_solder_mask:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=c.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:t.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:t.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(t.shape==="pill"&&t.rectPad){let c=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:t.outerWidth,outer_height:t.outerHeight,hole_width:t.holeWidth,hole_height:t.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"],soldermask_margin:o,is_covered_with_solder_mask:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:t.pcbRotation??0,rect_ccw_rotation:t.pcbRotation??0,rect_pad_width:t.outerWidth,rect_pad_height:t.outerHeight,hole_offset_x:t.holeOffsetX,hole_offset_y:t.holeOffsetY});this.pcb_plated_hole_id=c.pcb_plated_hole_id}else if(t.shape==="pill"||t.shape==="oval"){let c=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:t.outerWidth,outer_height:t.outerHeight,hole_width:t.holeWidth,hole_height:t.holeHeight,shape:t.shape,port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],soldermask_margin:o,is_covered_with_solder_mask:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:t.pcbRotation??0});this.pcb_plated_hole_id=c.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:t.shape,width:t.outerWidth,height:t.outerHeight,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:t.shape,width:t.outerWidth,height:t.outerHeight,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(t.shape==="circular_hole_with_rect_pad"){let c=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:t.holeDiameter,rect_pad_width:t.rectPadWidth,rect_pad_height:t.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],soldermask_margin:o,is_covered_with_solder_mask:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:t.holeOffsetX,hole_offset_y:t.holeOffsetY,rect_border_radius:t.rectBorderRadius??0});this.pcb_plated_hole_id=c.pcb_plated_hole_id}else if(t.shape==="pill_hole_with_rect_pad"){let c=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:t.holeWidth,hole_height:t.holeHeight,rect_pad_width:t.rectPadWidth,rect_pad_height:t.rectPadHeight,hole_offset_x:t.holeOffsetX,hole_offset_y:t.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],soldermask_margin:o,is_covered_with_solder_mask:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=c.pcb_plated_hole_id}else if(t.shape==="hole_with_polygon_pad"){let c=(t.padOutline||[]).map(u=>{let p=typeof u.x=="number"?u.x:parseFloat(String(u.x)),d=typeof u.y=="number"?u.y:parseFloat(String(u.y));return{x:p,y:d}}),l=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,shape:"hole_with_polygon_pad",hole_shape:t.holeShape||"circle",hole_diameter:t.holeDiameter,hole_width:t.holeWidth,hole_height:t.holeHeight,pad_outline:c,hole_offset_x:typeof t.holeOffsetX=="number"?t.holeOffsetX:parseFloat(String(t.holeOffsetX||0)),hole_offset_y:typeof t.holeOffsetY=="number"?t.holeOffsetY:parseFloat(String(t.holeOffsetY||0)),port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],soldermask_margin:o,is_covered_with_solder_mask:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=l.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},_P=class extends Ce{constructor(){super(...arguments);f(this,"pcb_keepout_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:JH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let e=this.getSubcircuit(),{db:t}=this.root,{_parsedProps:i}=this,r=this._getGlobalPcbPositionBeforeLayout(),s=ro(this._computePcbGlobalTransformBeforeLayout()),o=Math.abs(s.rotation.angle*(180/Math.PI)-90)%180<.01,a=null;i.shape==="circle"?a=t.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:r.x,y:r.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0}):i.shape==="rect"&&(a=t.pcb_keepout.insert({layers:["top"],shape:"rect",...o?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:r.x,y:r.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0})),a&&(this.pcb_keepout_id=a.pcb_keepout_id)}},K_=class extends Ce{constructor(){super(...arguments);f(this,"pcb_hole_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:EH}}getPcbSize(){let{_parsedProps:e}=this,t=e.shape==="pill",i=e.shape==="rect";return t?{width:e.width,height:e.height}:i?{width:e.width,height:e.height}:{width:e.diameter,height:e.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this._getGlobalPcbPositionBeforeLayout(),s=t.solderMaskMargin,o=t.coveredWithSolderMask??!1;if(t.shape==="pill")if(t.pcbRotation&&t.pcbRotation!==0){let a=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"rotated_pill",hole_width:t.width,hole_height:t.height,x:r.x,y:r.y,ccw_rotation:t.pcbRotation,soldermask_margin:s,is_covered_with_solder_mask:o,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=a.pcb_hole_id}else{let a=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"pill",hole_width:t.width,hole_height:t.height,x:r.x,y:r.y,soldermask_margin:s,is_covered_with_solder_mask:o,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=a.pcb_hole_id}else if(t.shape==="rect"){let a=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"rect",hole_width:t.width,hole_height:t.height,x:r.x,y:r.y,soldermask_margin:s,is_covered_with_solder_mask:o,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=a.pcb_hole_id}else{let a=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"circle",hole_diameter:t.diameter,x:r.x,y:r.y,soldermask_margin:s,is_covered_with_solder_mask:o,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=a.pcb_hole_id}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_hole.get(this.pcb_hole_id),i=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-i.width/2,top:t.y-i.height/2,right:t.x+i.width/2,bottom:t.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_hole.update(this.pcb_hole_id,{x:e.x,y:e.y})}};function vP(n){return n.replace(/\\n/g,`
252
252
  `)}var SP=class extends Ce{constructor(){super(...arguments);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:fq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getPrimitiveContainer(),r=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:s,isFlipped:o}=this._getPcbPrimitiveFlippedHelpers(),a=this.getSubcircuit(),c=0;if(t.pcbRotation!==void 0&&t.pcbRotation!==0)c=t.pcbRotation;else{let d=this._computePcbGlobalTransformBeforeLayout();c=ro(d).rotation.angle*180/Math.PI}o&&(c=(c+180)%360);let l=new Set(t.layers);t.layer&&l.add(t.layer);let u=l.size>0?Array.from(l):["top"],p=t.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1;for(let d of u)e.pcb_silkscreen_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:r.x,y:r.y},font:t.font??"tscircuit2024",font_size:p,layer:s(d),text:vP(t.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:e}=this,t=e.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1,r=(e.text??"").length*t,s=t;return{width:r*t,height:s*t}}},Q1=class extends Ce{constructor(){super(...arguments);f(this,"pcb_cutout_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:TH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this.getGroup()?.pcb_group_id??void 0,s=this._getGlobalPcbPositionBeforeLayout(),a=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,c;if(t.shape==="rect"){let l=typeof a=="string"?parseInt(a.replace("deg",""),10):a,u=Math.abs(l%180)===90,p={shape:"rect",center:s,width:u?t.height:t.width,height:u?t.width:t.height,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=e.pcb_cutout.insert(p)}else if(t.shape==="circle"){let l={shape:"circle",center:s,radius:t.radius,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=e.pcb_cutout.insert(l)}else if(t.shape==="polygon"){let l=this._computePcbGlobalTransformBeforeLayout(),p={shape:"polygon",points:t.points.map(d=>je(l,d)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=e.pcb_cutout.insert(p)}c&&(this.pcb_cutout_id=c.pcb_cutout_id)}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="polygon"){if(e.points.length===0)return{width:0,height:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let o of e.points)t=Math.min(t,o.x),i=Math.max(i,o.x),r=Math.min(r,o.y),s=Math.max(s,o.y);return{width:i-t,height:s-r}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,t=e.pcb_cutout.get(this.pcb_cutout_id);if(!t)return super._getPcbCircuitJsonBounds();if(t.shape==="rect")return{center:t.center,bounds:{left:t.center.x-t.width/2,top:t.center.y+t.height/2,right:t.center.x+t.width/2,bottom:t.center.y-t.height/2},width:t.width,height:t.height};if(t.shape==="circle")return{center:t.center,bounds:{left:t.center.x-t.radius,top:t.center.y+t.radius,right:t.center.x+t.radius,bottom:t.center.y-t.radius},width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return super._getPcbCircuitJsonBounds();let i=1/0,r=-1/0,s=1/0,o=-1/0;for(let a of t.points)i=Math.min(i,a.x),r=Math.max(r,a.x),s=Math.min(s,a.y),o=Math.max(o,a.y);return{center:{x:(i+r)/2,y:(s+o)/2},bounds:{left:i,top:o,right:r,bottom:s},width:r-i,height:o-s}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(e){if(!this.pcb_cutout_id)return;let{db:t}=this.root,i=t.pcb_cutout.get(this.pcb_cutout_id);if(i){if(i.shape==="rect"||i.shape==="circle")t.pcb_cutout.update(this.pcb_cutout_id,{...i,center:e});else if(i.shape==="polygon"){let r=this._getPcbCircuitJsonBounds().center,s=e.x-r.x,o=e.y-r.y,a=i.points.map(c=>({x:c.x+s,y:c.y+o}));t.pcb_cutout.update(this.pcb_cutout_id,{...i,points:a})}}}},E7t=({elm:n,pinLabels:e,layer:t,readableRotation:i,anchorAlignment:r})=>{let s=n.text.replace(/[{}]/g,"").toLowerCase(),o=s;if(Array.isArray(e)){let a=parseInt(s.replace(/[^\d]/g,""),10)-1;o=String(e[a]??s)}else typeof e=="object"&&(o=String(e[s]??s));return new SP({anchorAlignment:r||"center",text:o??s,layer:t||"top",fontSize:n.font_size+.2,pcbX:isNaN(n.anchor_position.x)?0:n.anchor_position.x,pcbY:n.anchor_position.y,pcbRotation:i??0})},C7t=(n,e)=>{let t=parseInt(n||"0",10),i;return e!=null?i=e-t:i=t,(i%360+360)%360},J_=({componentName:n,componentRotation:e,footprinterString:t,pinLabels:i,pcbPinLabels:r},s)=>{let o=[];for(let a of s)if(a.type==="pcb_smtpad"&&a.shape==="rect")o.push(new J1({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")o.push(new J1({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")o.push(new J1({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")o.push(new U9({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?o.push(new jd({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"?o.push(new jd({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"?o.push(new jd({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"?o.push(new jd({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})):a.shape==="hole_with_polygon_pad"&&o.push(new jd({pcbX:a.x,pcbY:a.y,shape:"hole_with_polygon_pad",holeShape:a.hole_shape||"circle",holeDiameter:a.hole_diameter,holeWidth:a.hole_width,holeHeight:a.hole_height,padOutline:a.pad_outline||[],holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y,portHints:a.port_hints}));else if(a.type==="pcb_keepout"&&a.shape==="circle")o.push(new _P({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius}));else if(a.type==="pcb_keepout"&&a.shape==="rect")o.push(new _P({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")o.push(new K_({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_hole"&&a.hole_shape==="rect")o.push(new K_({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")o.push(new K_({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")o.push(new K_({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"?o.push(new Q1({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?o.push(new Q1({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&o.push(new Q1({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=C7t(e,a.ccw_rotation);t?.includes("pinrow")&&a.text.includes("PIN")?o.push(E7t({elm:a,pinLabels:r??i??{},layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):o.push(new SP({anchorAlignment:a.anchor_alignment||"center",text:n||a.text,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"&&o.push(new V9({route:a.route}));return o};function wP(n){let e=1/0,t=1/0,i=-1/0,r=-1/0,s=!1;for(let c of n)if(c.isPcbPrimitive&&!c.componentName.startsWith("Silkscreen")){let{x:l,y:u}=c._getGlobalPcbPositionBeforeLayout(),{width:p,height:d}=c.getPcbSize();e=Math.min(e,l-p/2),t=Math.min(t,u-d/2),i=Math.max(i,l+p/2),r=Math.max(r,u+d/2),s=!0}else if(c.children.length>0){let l=wP(c.children);(l.width>0||l.height>0)&&(e=Math.min(e,l.minX),t=Math.min(t,l.minY),i=Math.max(i,l.maxX),r=Math.max(r,l.maxY),s=!0)}if(!s)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let o=i-e,a=r-t;return o<0&&(o=0),a<0&&(a=0),{minX:e,minY:t,maxX:i,maxY:r,width:o,height:a}}function bnt(n){let e=n%360;return e<0?e+360:e}function I7t(n,e,t,i){return i==="counterclockwise"?t>=e?n>=e&&n<=t:n>=e||n<=t:t<=e?n<=e&&n>=t:n<=e||n>=t}function N7t(n){let e=n.center,t=n.radius,i=n.start_angle_degrees,r=n.end_angle_degrees,s=n.direction??"counterclockwise";if(!e||typeof e.x!="number"||typeof e.y!="number"||typeof t!="number"||typeof i!="number"||typeof r!="number")return null;let o=bnt(i),a=bnt(r),c=new Set([o,a]),l=[0,90,180,270];for(let g of l)I7t(g,o,a,s)&&c.add(g);let u=1/0,p=1/0,d=-1/0,_=-1/0;for(let g of c){let x=g*Math.PI/180,b=e.x+t*Math.cos(x),S=e.y+t*Math.sin(x);u=Math.min(u,b),d=Math.max(d,b),p=Math.min(p,S),_=Math.max(_,S)}return!Number.isFinite(u)||!Number.isFinite(p)?null:{minX:u,maxX:d,minY:p,maxY:_}}function rit(n){let e=1/0,t=1/0,i=-1/0,r=-1/0;for(let s of n){let o,a,c,l;if(s.type==="schematic_component")o=s.center?.x,a=s.center?.y,c=s.size?.width,l=s.size?.height;else if(s.type==="schematic_box")o=s.x,a=s.y,c=s.width,l=s.height;else if(s.type==="schematic_port")o=s.center?.x,a=s.center?.y,c=.2,l=.2;else if(s.type==="schematic_text")o=s.position?.x,a=s.position?.y,c=(s.text?.length??0)*.1,l=.2;else if(s.type==="schematic_line"){let u=s.x1??0,p=s.y1??0,d=s.x2??0,_=s.y2??0;o=(u+d)/2,a=(p+_)/2,c=Math.abs(d-u),l=Math.abs(_-p)}else if(s.type==="schematic_rect")o=s.center?.x,a=s.center?.y,c=s.width,l=s.height;else if(s.type==="schematic_circle"){o=s.center?.x,a=s.center?.y;let u=s.radius;typeof u=="number"&&(c=u*2,l=u*2)}else if(s.type==="schematic_arc"){let u=N7t(s);u&&(e=Math.min(e,u.minX),i=Math.max(i,u.maxX),t=Math.min(t,u.minY),r=Math.max(r,u.maxY));continue}typeof o=="number"&&typeof a=="number"&&typeof c=="number"&&typeof l=="number"&&(e=Math.min(e,o-c/2),i=Math.max(i,o+c/2),t=Math.min(t,a-l/2),r=Math.max(r,a+l/2))}return{minX:e,maxX:i,minY:t,maxY:r}}function A7t(n,e){let t=e.x-n.x,i=e.y-n.y;return Math.abs(t)>Math.abs(i)?t>=0?"right":"left":i>=0?"up":"down"}var vnt=n=>{if(n.length<=1)return!0;let e=n.map(s=>{let o=s._getPcbCircuitJsonBounds();return{left:o.bounds.left,right:o.bounds.right,top:o.bounds.top,bottom:o.bounds.bottom}}),t=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let s=0;s<e.length;s++)for(let o=s+1;o<e.length;o++){let a=e[s],c=e[o];t[s][o]=t[o][s]=!(a.right<c.left||a.left>c.right||a.bottom>c.top||a.top<c.bottom)}let i=new Set,r=s=>{i.add(s);for(let o=0;o<e.length;o++)t[s][o]&&!i.has(o)&&r(o)};return r(0),i.size===e.length},Snt=n=>{if(n.length===0)throw new Error("Cannot get center of empty PCB primitives array");let e=n.map(r=>r._getPcbCircuitJsonBounds().center).filter(Boolean),t=e.reduce((r,s)=>r+s.x,0),i=e.reduce((r,s)=>r+s.y,0);return{x:t/e.length,y:i/e.length}},R7t=h.object({name:h.string().optional(),pinNumber:h.number().optional(),aliases:h.array(h.string()).optional(),layer:h.string().optional(),layers:h.array(h.string()).optional(),schX:h.number().optional(),schY:h.number().optional(),direction:h.enum(["up","down","left","right"]).optional(),connectsTo:h.union([h.string(),h.array(h.string())]).optional()}),qi=class extends Ce{constructor(e,t={}){if(!e.name&&e.pinNumber!==void 0&&(e.name=`pin${e.pinNumber}`),!e.name)throw new Error("Port must have a name or a pinNumber");super(e);f(this,"source_port_id",null);f(this,"pcb_port_id",null);f(this,"schematic_port_id",null);f(this,"schematicSymbolPortDef",null);f(this,"matchedComponents");f(this,"facingDirection",null);f(this,"originDescription",null);t.originDescription&&(this.originDescription=t.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:R7t}}isGroupPort(){return this.parent?.componentName==="Group"}isComponentPort(){return!this.isGroupPort()}_getConnectedPortsFromConnectsTo(){let{_parsedProps:e}=this,t=e.connectsTo;if(!t)return[];let i=[],r=Array.isArray(t)?t:[t];for(let s of r){let o=this.getSubcircuit().selectOne(s,{type:"port"});o&&i.push(o)}return i}_isBoardPinoutFromAttributes(){let e=this.parent;if(e?._parsedProps?.pinAttributes){let t=e._parsedProps.pinAttributes;for(let i of this.getNameAndAliases())if(t[i]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let e=this.matchedComponents.find(i=>i.isPcbPrimitive),t=this.parent;if(t&&!t.props.footprint)throw new Error(`${t.componentName} "${t.props.name}" does not have a footprint. Add a footprint prop, e.g. <${t.componentName.toLowerCase()} footprint="..." />`);if(!e)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return e?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,t=e.pcb_port.get(this.pcb_port_id);return{center:{x:t.x,y:t.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let e=this.parent;if(!e||!e._getInternallyConnectedPins)return[];let t=e._getInternallyConnectedPins();for(let i of t)if(i.some(r=>r===this))return i;return[]}_hasSchematicPort(){let{schX:e,schY:t}=this._parsedProps;if(e!==void 0&&t!==void 0)return!0;let i=this.getParentNormalComponent();if(i?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(a=>a.schematicSymbolPortDef));let s=i?._getSchematicBoxDimensions();return!!(s&&this.props.pinNumber!==void 0&&s.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let{schX:e,schY:t}=this._parsedProps;if(e!==void 0&&t!==void 0)return{x:e,y:t};let i=this.getParentNormalComponent(),r=i?.getSchematicSymbol();if(r){let o=this.schematicSymbolPortDef;if(!o&&(o=this._getPortsInternallyConnectedToThisPort().find(c=>c.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!o))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let a=ai(i.computeSchematicGlobalTransform(),Tn(-r.center.x,-r.center.y));return je(a,o)}let s=i?._getSchematicBoxDimensions();if(s&&this.props.pinNumber!==void 0){let o=s.getPortPositionByPinNumber(this.props.pinNumber);if(!o)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return je(i.computeSchematicGlobalTransform(),o)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:e}=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 t=e.schematic_port.get(this.schematic_port_id);if(!t)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return t.center}registerMatch(e){this.matchedComponents.push(e)}getNameAndAliases(){let{_parsedProps:e}=this;return Array.from(new Set([...e.name?[e.name]:[],...e.aliases??[],...typeof e.pinNumber=="number"?[`pin${e.pinNumber}`,e.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let e=this.parent?._parsedProps?.pinAttributes;if(!e)return[];let t=[];for(let i of this.getNameAndAliases()){let r=e[i];r&&t.push(r)}return t}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(e=>e.includeInBoardPinout===!0)}isMatchingPort(e){return this.isMatchingAnyOf(e.getNameAndAliases())}getPortSelector(){return`.${(this.getParentNormalComponent()??this.parent)?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:e,layers:t}=this._parsedProps;return t||(e?[e]: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:e}=this.root,{_parsedProps:t}=this,i=this.getNameAndAliases(),r=this.getParentNormalComponent(),o=(this.parent?.source_component_id?this.parent:r)?.source_component_id??null,a=this._getMatchingPinAttributes(),c={};for(let u of a)u.mustBeConnected!==void 0&&(c.must_be_connected=u.mustBeConnected);let l=e.source_port.insert({name:t.name,pin_number:t.pinNumber,port_hints:i,source_component_id:o,subcircuit_id:this.getSubcircuit()?.subcircuit_id,...c});this.source_port_id=l.source_port_id}doInitialSourceParentAttachment(){let{db:e}=this.root,t=this.getParentNormalComponent(),i=this.parent?.source_component_id?this.parent:t;if(this.isGroupPort()){e.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()})`);e.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:e}=this.root,{matchedComponents:t}=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=e.pcb_port.get(c.pcb_port_id),u={x:l.x,y:l.y},p=this.getSubcircuit(),d=e.pcb_port.insert({pcb_component_id:void 0,layers:c.getAvailablePcbLayers(),subcircuit_id:p?.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(),r=this.parent?.pcb_component_id?this.parent:i;if(!r?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()}, parentNormalComponent: ${i?.getString()})`);let s=t.filter(a=>a.isPcbPrimitive);if(s.length===0)return;let o=null;if(s.length===1&&(o=s[0]._getPcbCircuitJsonBounds().center),s.length>1){if(!vnt(s))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${s.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)`);o=Snt(s)}if(o){let a=this.getSubcircuit(),c=this._shouldIncludeInBoardPinout(),l=e.pcb_port.insert({pcb_component_id:r.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...c?{is_board_pinout:!0}:{},...o,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=l.pcb_port_id}else{let a=s[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:e}=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 p=e.pcb_port.get(u.pcb_port_id),d={x:p.x,y:p.y},_=this.getSubcircuit(),g=e.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=g.pcb_port_id;return}let t=this.matchedComponents.filter(l=>l.isPcbPrimitive);if(t.length===0)return;let i=null;if(t.length===1&&(i=t[0]._getPcbCircuitJsonBounds().center),t.length>1)try{vnt(t)&&(i=Snt(t))}catch{}if(!i)return;let r=this.getParentNormalComponent(),s=this.parent?.pcb_component_id?this.parent:r,o=this.getSubcircuit(),a=this._shouldIncludeInBoardPinout(),c=e.pcb_port.insert({pcb_component_id:s?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:o?.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:e}=this.root,t=e.source_port.get(this.source_port_id),i=[];for(let o of t?.port_hints??[])o.match(/^(pin)?\d+$/)||o.match(/^(left|right)/)&&!t?.name.match(/^(left|right)/)||i.push(o);if(this.getParentNormalComponent()?.props?.showPinAliases&&i.length>0)return i.join("/");if(i.length>0)return i[0]}doInitialSchematicPortRender(){let{db:e}=this.root,{_parsedProps:t}=this,{schX:i,schY:r}=t,s=i!==void 0&&r!==void 0?this.getParentNormalComponent():this.getPrimitiveContainer();if(!s||!this._hasSchematicPort())return;let o=s._getGlobalSchematicPositionBeforeLayout(),a=this._getGlobalSchematicPositionBeforeLayout(),c=null,l=s._getSchematicBoxDimensions();l&&t.pinNumber!==void 0&&(c=l.getPortPositionByPinNumber(t.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&e.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=A7t(o,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:t.pinNumber,true_ccw_index:c?.trueIndex,display_pin_label:u,is_connected:!1};for(let g of this._getMatchingPinAttributes())g.requiresPower&&(d.has_input_arrow=!0),g.providesPower&&(d.has_output_arrow=!0);let _=e.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(e){let{db:t}=this.root;this.pcb_port_id&&t.pcb_port.update(this.pcb_port_id,{x:e.x,y:e.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(e=>e.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},sit=n=>{let e=n.find(t=>/^(pin)?\d+$/.test(t));return e?Number.parseInt(e.replace(/^pin/,"")):null};function H1(n,e){let t=sit(n);if(!t)return null;let r=[...n.filter(s=>s.toString()!==t.toString()&&s!==`pin${t}`),...e?.additionalAliases?.[`pin${t}`]??[]];return new qi({pinNumber:t,aliases:r})}var O7t=n=>{for(let e of["leftSide","rightSide","topSide","bottomSide"])if(e in n&&typeof n[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in n||"rightSide"in n||"topSide"in n||"bottomSide"in n},L7t=n=>{if(O7t(n))return{leftSize:n.leftSide?.pins.length??0,rightSize:n.rightSide?.pins.length??0,topSize:n.topSide?.pins.length??0,bottomSize:n.bottomSide?.pins.length??0};let{leftSize:e=0,rightSize:t=0,topSize:i=0,bottomSize:r=0}=n;return{leftSize:e,rightSize:t,topSize:i,bottomSize:r}},cP=.4;function oit(n){let e=n;return e.leftSide!==void 0||e.rightSide!==void 0||e.topSide!==void 0||e.bottomSide!==void 0}var F7t=n=>{let e=n.portDistanceFromEdge??.4,t=n.schPortArrangement?L7t(n.schPortArrangement):null,i={left:0,right:0,top:0,bottom:0},r=n.pinCount??null;if(r===null)if(t)r=t.leftSize+t.rightSize+t.topSize;else throw new Error("Could not determine pin count for the schematic box");if(r&&!t){let g=Math.floor(r/2);t={leftSize:r-g,rightSize:g,topSize:0,bottomSize:0}}t||(t={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let s=({side:g,sideIndex:x,truePinIndex:b})=>{if(!n.schPortArrangement||!oit(n.schPortArrangement))return b+1;let S={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[g],P=n.schPortArrangement?.[`${g}Side`]?.direction??S,T=n.schPortArrangement?.[`${g}Side`]?.pins,k=x;return P!==S&&(k=T.length-x-1),t0(T[k],n.pinLabels)},o=[],a=0,c=0;for(let g=0;g<t.leftSize;g++){let x=s({side:"left",sideIndex:g,truePinIndex:c}),b=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];b?.topMargin&&(a+=b.topMargin),o.push({trueIndex:c,pinNumber:x,side:"left",distanceFromOrthogonalEdge:a}),b?.bottomMargin&&(a+=b.bottomMargin),g===t.leftSize-1?i.left=a:a+=n.schPinSpacing,c++}a=0;for(let g=0;g<t.bottomSize;g++){let x=s({side:"bottom",sideIndex:g,truePinIndex:c}),b=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];b?.leftMargin&&(a+=b.leftMargin),o.push({trueIndex:c,pinNumber:x,side:"bottom",distanceFromOrthogonalEdge:a}),b?.rightMargin&&(a+=b.rightMargin),g===t.bottomSize-1?i.bottom=a:a+=n.schPinSpacing,c++}a=0;for(let g=0;g<t.rightSize;g++){let x=s({side:"right",sideIndex:g,truePinIndex:c}),b=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];b?.bottomMargin&&(a+=b.bottomMargin),o.push({trueIndex:c,pinNumber:x,side:"right",distanceFromOrthogonalEdge:a}),b?.topMargin&&(a+=b.topMargin),g===t.rightSize-1?i.right=a:a+=n.schPinSpacing,c++}a=0;for(let g=0;g<t.topSize;g++){let x=s({side:"top",sideIndex:g,truePinIndex:c}),b=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];b?.rightMargin&&(a+=b.rightMargin),o.push({trueIndex:c,pinNumber:x,side:"top",distanceFromOrthogonalEdge:a}),b?.leftMargin&&(a+=b.leftMargin),g===t.topSize-1?i.top=a:a+=n.schPinSpacing,c++}let l=n.schWidth;if(l===void 0){l=Math.max(i.top+cP,i.bottom+cP),n.pinLabels&&o.filter(P=>P.side==="left"||P.side==="right").some(P=>n.pinLabels?.[`pin${P.pinNumber}`]||n.pinLabels?.[P.pinNumber])&&(l=Math.max(l,.5));let g=n.pinLabels?Math.max(...Object.values(n.pinLabels).map(b=>b.length*.1)):0,x=g>0?1.1:0;l=Math.max(l,g+x)}let u=n.schHeight;u||(u=Math.max(i.left+cP,i.right+cP));let p={left:{x:-l/2-e,y:i.left/2},bottom:{x:-i.bottom/2,y:-u/2-e},right:{x:l/2+e,y:-i.right/2},top:{x:i.top/2,y:u/2+e}},d={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},_=o.map(g=>{let{distanceFromOrthogonalEdge:x,side:b}=g,S=p[b],P=d[b];return{x:S.x+x*P.x,y:S.y+x*P.y,...g}});return{getPortPositionByPinNumber(g){let x=_.find(b=>b.pinNumber.toString()===g.toString());return x||null},getSize(){return{width:l,height:u}},getSizeIncludingPins(){return{width:l+(t.leftSize||t.rightSize?.4:0),height:u+(t.topSize||t.bottomSize?.4:0)}},pinCount:r}},z7t=(0,ait.default)("tscircuit:core:footprint"),cit=class extends Ce{get config(){return{componentName:"Footprint",zodProps:IH}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let n=this.children.filter(p=>p.componentName==="Constraint");if(n.length===0)return;let{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),t=p=>e&&"left"in p&&"right"in p?{...p,left:p.right,right:p.left}:p,i=n.flatMap(p=>p._getAllReferencedComponents().componentsWithSelectors).map(({component:p,selector:d,componentSelector:_,edge:g})=>({component:p,selector:d,componentSelector:_,edge:g,bounds:p._getPcbCircuitJsonBounds()}));if(i.some(p=>p.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function r(p){return i.find(({selector:d})=>d===p)}let s=new u_,o={};function a(p){return p in o||(o[p]=new Oa(p),s.addEditVariable(o[p],Ln.weak)),o[p]}for(let{selector:p,bounds:d}of i){let _=a(`${p}_x`),g=a(`${p}_y`);s.suggestValue(_,d.center.x),s.suggestValue(g,d.center.y)}for(let p of n){let d=p._parsedProps;if("xDist"in d){let{xDist:_,left:g,right:x,edgeToEdge:b,centerToCenter:S}=t(d),P=a(`${g}_x`),T=a(`${x}_x`),k=r(g)?.bounds,N=r(x)?.bounds;if(S){let M=new jn(T,[-1,P]);s.addConstraint(new Mi(M,ui.Eq,d.xDist,Ln.required))}else if(b){let M=new jn(T,-N.width/2,[-1,P],-k.width/2);s.addConstraint(new Mi(M,ui.Eq,d.xDist,Ln.required))}}else if("yDist"in d){let{yDist:_,top:g,bottom:x,edgeToEdge:b,centerToCenter:S}=d,P=a(`${g}_y`),T=a(`${x}_y`),k=r(g)?.bounds,N=r(x)?.bounds;if(S){let M=new jn(P,[-1,T]);s.addConstraint(new Mi(M,ui.Eq,d.yDist,Ln.required))}else if(b){let M=new jn(P,k.height/2,[-1,T],-N.height/2);s.addConstraint(new Mi(M,ui.Eq,d.yDist,Ln.required))}}else if("sameY"in d){let{for:_}=d;if(_.length<2)continue;let g=_.map(b=>a(`${b}_y`)),x=new jn(...g.slice(1));s.addConstraint(new Mi(x,ui.Eq,g[0],Ln.required))}else if("sameX"in d){let{for:_}=d;if(_.length<2)continue;let g=_.map(b=>a(`${b}_x`)),x=new jn(...g.slice(1));s.addConstraint(new Mi(x,ui.Eq,g[0],Ln.required))}}s.updateVariables(),z7t.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(o).map(([p,d])=>({var:p,val:d.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:p,bounds:{width:d,height:_}}of i){let g=a(`${p}_x`),x=a(`${p}_y`),b=g.value()-d/2,S=g.value()+d/2,P=x.value()+_/2,T=x.value()-_/2;c.left=Math.min(c.left,b),c.right=Math.max(c.right,S),c.top=Math.max(c.top,P),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:p,selector:d}of i){let _=a(`${d}_x`),g=a(`${d}_y`);p._setPositionFromLayout({x:_.value()+l.x,y:g.value()+l.y})}}},lit=n=>{if(!n)return null;let t=n.split("?")[0].split("#")[0],i=t.split("/").pop()??t;return i.includes(".")?i.split(".").pop()?.toLowerCase()??null:null},$7t=(n,e)=>{let t=n.replace(/\/+$/,""),i=e.replace(/^\/+/,"");return`${t}/${i}`},uit=(n,e)=>{if(!e||!n.startsWith("/"))return n;try{let t=new URL(e);return t.pathname!=="/"&&n.startsWith(t.pathname)?new URL(n,t.origin).toString():$7t(e,n)}catch{return n}},T9=h.union([h.number(),h.string()]),wnt=h.object({x:T9,y:T9,z:T9}),pit=class extends Ce{get config(){return{componentName:"CadModel",zodProps:eq}}doInitialCadModelRender(){let n=this._findParentWithPcbComponent();if(!n||!n.pcb_component_id)return;let{db:e}=this.root,{boardThickness:t=0}=this.root?._getBoard()??{},i=n._getPcbCircuitJsonBounds(),r=e.pcb_component.get(n.pcb_component_id),s=this._parsedProps;if(!s||typeof s.modelUrl!="string"&&typeof s.stepUrl!="string")return;let o=n._computePcbGlobalTransformBeforeLayout(),c=ro(o).rotation.angle*180/Math.PI,l=wnt.parse({x:0,y:0,z:0});if(typeof s.rotationOffset=="number")l.z=Number(s.rotationOffset);else if(typeof s.rotationOffset=="object"){let P=wnt.parse(s.rotationOffset);l.x=Number(P.x),l.y=Number(P.y),l.z=Number(P.z)}let{pcbX:u,pcbY:p}=this.getResolvedPcbPositionProp(),d=IS.parse({x:u,y:p,z:s.pcbZ??0,...typeof s.positionOffset=="object"?s.positionOffset:{}}),_=s.zOffsetFromSurface!==void 0?V.parse(s.zOffsetFromSurface):0,g=n.props.layer==="bottom"?"bottom":"top",x=s.modelUrl?lit(s.modelUrl):void 0,b={};if(x==="stl"?b.model_stl_url=this._addCachebustToModelUrl(s.modelUrl):x==="obj"?b.model_obj_url=this._addCachebustToModelUrl(s.modelUrl):x==="gltf"?b.model_gltf_url=this._addCachebustToModelUrl(s.modelUrl):x==="glb"?b.model_glb_url=this._addCachebustToModelUrl(s.modelUrl):x==="step"||x==="stp"?b.model_step_url=this._addCachebustToModelUrl(s.modelUrl):x==="wrl"||x==="vrml"?b.model_wrl_url=this._addCachebustToModelUrl(s.modelUrl):b.model_stl_url=this._addCachebustToModelUrl(s.modelUrl),s.stepUrl){let P=this._addCachebustToModelUrl(s.stepUrl);P&&(b.model_step_url=P)}let S=e.cad_component.insert({position:{x:i.center.x+Number(d.x),y:i.center.y+Number(d.y),z:(g==="bottom"?-t/2:t/2)+(g==="bottom"?-_:_)+Number(d.z)},rotation:{x:Number(l.x),y:(g==="top"?0:180)+Number(l.y),z:g==="bottom"?-(c+Number(l.z))+180:c+Number(l.z)},pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,model_unit_to_mm_scale_factor:typeof s.modelUnitToMmScale=="number"?s.modelUnitToMmScale:void 0,show_as_translucent_model:n._parsedProps.showAsTranslucentModel,...b});this.cad_component_id=S.cad_component_id}_findParentWithPcbComponent(){let n=this.parent;for(;n&&!n.pcb_component_id;)n=n.parent;return n}_addCachebustToModelUrl(n){if(!n)return n;let e=this.root?.platform?.projectBaseUrl,t=uit(n,e);if(!t.includes("modelcdn.tscircuit.com"))return t;let i=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(i)}`}},hit=class extends Ce{constructor(){super(...arguments);f(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:tq}}},D7t=(n,e)=>{if(!n)return;let t={};for(let[i,r]of Object.entries(n)){let s=t0(i,e),o={leftMargin:r.marginLeft??r.leftMargin,rightMargin:r.marginRight??r.rightMargin,topMargin:r.marginTop??r.topMargin,bottomMargin:r.marginBottom??r.bottomMargin};t[`pin${s}`]={...t[`pin${s}`],...o}}return t},Pnt=class{constructor({input:n}){f(this,"input");this.input=n}solveAndMapToTraces(){let n=[];for(let e of this.input.connections){if(e.pointsToConnect.length!==2)continue;let[t,i]=e.pointsToConnect,r={type:"pcb_trace",pcb_trace_id:"",connection_name:e.name,route:[{route_type:"wire",x:t.x,y:t.y,layer:"top",width:.1},{route_type:"wire",x:i.x,y:i.y,layer:"top",width:.1}]};n.push(r)}return n}},j7t=n=>{let e=Math.min(...n.map(s=>s.center.x)),t=Math.max(...n.map(s=>s.center.x)),i=Math.min(...n.map(s=>s.center.y)),r=Math.max(...n.map(s=>s.center.y));return{minX:e,maxX:t,minY:i,maxY:r}},knt=["top","bottom","inner1","inner2"],hP=(n,e=[])=>{let t=[];if(e.length===0){let a=n[0].layers;for(let c of a)t.push(...hP(n.slice(1),[c]));return t}if(n.length===0)return[];let i=n[0],r=i.via||i.optional_via,s=e[e.length-1];if(n.length===1){let a=i;return a.layers&&r?a.layers.map(c=>({layer_path:[...e,c]})):a.layers?.includes(s)?[{layer_path:[...e,s]}]:[]}if(!r)return i.layers&&!i.layers.includes(s)?[]:hP(n.slice(1),e.concat([s]));let o=(i.optional_via?knt:knt.filter(a=>a!==s)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of o)t.push(...hP(n.slice(1),e.concat(a)));return t};function Tnt(n){let e={x:n.to.x-n.from.x,y:n.to.y-n.from.y},t=Math.abs(e.x),i=Math.abs(e.y);return t>i?e.x>0?"right":"left":e.y>0?"down":"up"}function G_(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}var B7t=n=>{if(n.length===1)return n[0];if(n.some(c=>c.length===0))throw new Error("Cannot merge routes with zero length");let e=[],t=n[0][0],i=n[0][n[0].length-1],r=n[1][0],s=n[1][n[1].length-1],o=Math.min(G_(t,r),G_(t,s)),a=Math.min(G_(i,r),G_(i,s));o<a?e.push(...n[0].reverse()):e.push(...n[0]);for(let c=1;c<n.length;c++){let l=e[e.length-1],u=n[c],p=u[0],d=u[u.length-1],_=G_(l,p),g=G_(l,d);_<g?e.push(...u):e.push(...u.reverse())}for(let c=1;c<e.length-1;c++){let l=e[c-1],u=e[c];l.route_type==="wire"&&u.route_type==="wire"&&l.layer!==u.layer&&e.splice(c,0,{x:l.x,y:l.y,from_layer:l.layer,to_layer:u.layer,route_type:"via"})}return e},Y7t=(n,e)=>{let t="_getGlobalPcbPositionBeforeLayout"in n?n._getGlobalPcbPositionBeforeLayout():n,i="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((t.x-i.x)**2+(t.y-i.y)**2)};function X7t(n,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let t=e[0],i=1/0;for(let r of e){let s=Y7t(n,r);s<i&&(t=r,i=s)}return t}var U7t=(n,e)=>{let t=0;t+=n.length??0,t+=e.filter(i=>i.is_crossing).length;for(let i=1;i<e.length;i++){let r=e[i-1],s=e[i],o=Math.abs(r.from.x-r.to.x)<.01,a=Math.abs(s.from.x-s.to.x)<.01;o!==a&&t++}return t},e0=n=>({up:"bottom",down:"top",left:"right",right:"left"})[n]??null,A9=({firstEdge:n,firstEdgePort:e,firstDominantDirection:t,lastEdge:i,lastEdgePort:r,lastDominantDirection:s})=>{if(n&&e)return A9({lastEdge:{from:n.to,to:n.from},lastEdgePort:e,lastDominantDirection:t}).reverse().map(a=>({from:a.to,to:a.from}));let o=[];if(i&&r){let a={x:i.to.x,y:i.to.y};s==="left"||s==="right"?(a.x=r.position.x,o.push({from:i.to,to:{...a}}),o.push({from:a,to:{...r.position}})):(a.y=r.position.y,o.push({from:i.to,to:{...a}}),o.push({from:a,to:{...r.position}}))}return o=o.filter(a=>Di(a.from,a.to)>.01),o};function V7t(n){try{return[n(),null]}catch(e){return[null,e]}}var G7t=(n,{db:e})=>{let t=n.map(i=>{let r=e.source_port.get(i.source_port_id);if(!r?.source_component_id)return null;let s=e.source_component.get(r.source_component_id);return s?.ftype==="simple_capacitor"?s.max_decoupling_trace_length:null}).filter(i=>i!==null);if(t.length!==0)return Math.min(...t)};function W7t({ports:n,nets:e}){if(n.length>=2)return`${n[0]?.selector} to ${n[1]?.selector}`;if(n.length===1&&e.length===1)return`${n[0]?.selector} to net.${e[0]._parsedProps.name}`}var H7t=(n,{db:e})=>{let t=e.pcb_board.list()[0];if(t.outline){let c=t.outline,l=(u,p)=>{let d=!1;for(let _=0,g=p.length-1;_<p.length;g=_++){let x=p[_].x,b=p[_].y,S=p[g].x,P=p[g].y;b>u.y!=P>u.y&&u.x<(S-x)*(u.y-b)/(P-b)+x&&(d=!d)}return d};return n.some(u=>!l(u,c))}let i=t.width,r=t.height,s=t.center.x,o=t.center.y;return n.some(c=>c.x<s-i/2||c.y<o-r/2||c.x>s+i/2||c.y>o+r/2)},Mnt=(n,e)=>Math.abs(n-e)<1e-4,q7t=(n,e,{viaDiameter:t=.5}={})=>{let i=[];for(let r=0;r<n.length-1;r++){let[s,o]=[n[r],n[r+1]],a=r-1>=0?n[r-1]:null,c=Mnt(s.y,o.y),l=Mnt(s.x,o.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${s.x}, ${s.y}), end: (${o.x}, ${o.y})`);let u={type:"rect",layers:[s.layer],center:{x:(s.x+o.x)/2,y:(s.y+o.y)/2},width:c?Math.abs(s.x-o.x):.1,height:l?Math.abs(s.y-o.y):.1,connectedTo:[e]};if(i.push(u),a&&a.layer===s.layer&&s.layer!==o.layer){let p={type:"rect",layers:[s.layer,o.layer],center:{x:s.x,y:s.y},connectedTo:[e],width:t,height:t};i.push(p)}}return i};function Z7t(n,e=4){let{center:t,width:i,height:r,rotation:s}=n,o=[],a=s*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(s%360+360)%360;if(r<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/e;for(let _=0;_<e;_++){let g=(_-e/2+.5)*d,x=-g*c,b=-g*l,S=d*1.1,P=Math.abs(r*c)+Math.abs(d*l);o.push({center:{x:t.x+x,y:t.y+b},width:S,height:P})}}else{let d=r/e;for(let _=0;_<e;_++){let g=(_-e/2+.5)*d,x=-g*l,b=g*c,S=Math.abs(i*c)+Math.abs(d*l),P=d*1.1;o.push({center:{x:t.x+x,y:t.y+b},width:S,height:P})}}return o}function K7t(n,e={}){if(n.length<3)return[];let{rectHeight:t=.1}=e,i=[],r=n.map(a=>a.y),s=Math.min(...r),o=Math.max(...r);for(let a=s;a<o;a+=t){let c=a+t/2,l=[];for(let u=0;u<n.length;u++){let p=n[u],d=n[(u+1)%n.length];if(p.y<=c&&d.y>c||d.y<=c&&p.y>c){let _=(c-p.y)*(d.x-p.x)/(d.y-p.y)+p.x;l.push(_)}}l.sort((u,p)=>u-p);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let p=l[u],_=l[u+1]-p;_>1e-6&&i.push({center:{x:p+_/2,y:c},width:_,height:t})}}return i}function J7t(n,e={}){let{center:t,radius:i}=n,{rectHeight:r=.1}=e,s=[],o=Math.ceil(i*2/r);for(let a=0;a<o;a++){let c=t.y-i+(a+.5)*r,l=c-t.y,u=Math.sqrt(i*i-l*l);u>0&&s.push({center:{x:t.x,y:c},width:u*2,height:r})}return s}var Zo=["top","inner1","inner2","bottom"],dit=(n,e)=>{let t=r=>e?r.concat(r.map(s=>e?.getNetConnectedToId(s)).filter(Boolean)):r,i=[];for(let r of n)if(r.type==="pcb_smtpad"){if(r.shape==="circle")i.push({type:"oval",layers:[r.layer],center:{x:r.x,y:r.y},width:r.radius*2,height:r.radius*2,connectedTo:t([r.pcb_smtpad_id])});else if(r.shape==="rect")i.push({type:"rect",layers:[r.layer],center:{x:r.x,y:r.y},width:r.width,height:r.height,connectedTo:t([r.pcb_smtpad_id])});else if(r.shape==="rotated_rect"){let s={center:{x:r.x,y:r.y},width:r.width,height:r.height,rotation:r.ccw_rotation},o=Z7t(s);for(let a of o)i.push({type:"rect",layers:[r.layer],center:a.center,width:a.width,height:a.height,connectedTo:t([r.pcb_smtpad_id])})}}else if(r.type==="pcb_keepout")r.shape==="circle"?i.push({type:"oval",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.radius*2,height:r.radius*2,connectedTo:[]}):r.shape==="rect"&&i.push({type:"rect",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.type==="pcb_cutout"){if(r.shape==="rect")i.push({type:"rect",layers:Zo,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.shape==="circle"){let s=J7t({center:r.center,radius:r.radius},{rectHeight:.6});for(let o of s)i.push({type:"rect",layers:Zo,center:o.center,width:o.width,height:o.height,connectedTo:[]})}else if(r.shape==="polygon"){let s=K7t(r.points,{rectHeight:.6});for(let o of s)i.push({type:"rect",layers:Zo,center:o.center,width:o.width,height:o.height,connectedTo:[]})}}else if(r.type==="pcb_hole")r.hole_shape==="oval"?i.push({type:"oval",center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="rect"?i.push({type:"rect",layers:Zo,center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="square"?i.push({type:"rect",layers:Zo,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]}):(r.hole_shape==="round"||r.hole_shape==="circle")&&i.push({type:"rect",layers:Zo,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]});else if(r.type==="pcb_plated_hole"){if(r.shape==="circle")i.push({type:"oval",layers:Zo,center:{x:r.x,y:r.y},width:r.outer_diameter,height:r.outer_diameter,connectedTo:t([r.pcb_plated_hole_id])});else if(r.shape==="circular_hole_with_rect_pad")i.push({type:"rect",layers:Zo,center:{x:r.x,y:r.y},width:r.rect_pad_width,height:r.rect_pad_height,connectedTo:t([r.pcb_plated_hole_id])});else if(r.shape==="oval"||r.shape==="pill")i.push({type:"oval",layers:Zo,center:{x:r.x,y:r.y},width:r.outer_width,height:r.outer_height,connectedTo:t([r.pcb_plated_hole_id])});else if(r.shape==="hole_with_polygon_pad"&&"pad_outline"in r&&r.pad_outline&&r.pad_outline.length>0){let s=r.pad_outline.map(_=>r.x+_.x),o=r.pad_outline.map(_=>r.y+_.y),a=Math.min(...s),c=Math.max(...s),l=Math.min(...o),u=Math.max(...o),p=(a+c)/2,d=(l+u)/2;i.push({type:"rect",layers:Zo,center:{x:p,y:d},width:c-a,height:u-l,connectedTo:t([r.pcb_plated_hole_id])})}}else if(r.type==="pcb_trace"){let s=q7t(r.route.map(o=>({x:o.x,y:o.y,layer:"layer"in o?o.layer:o.from_layer})),r.source_trace_id);i.push(...s)}else if(r.type==="pcb_via"){let s=!!(r.net_is_assignable??r.netIsAssignable);i.push({type:"rect",layers:r.layers,center:{x:r.x,y:r.y},connectedTo:[],width:r.outer_diameter,height:r.outer_diameter,netIsAssignable:s||void 0})}return i},kl=({anchor_position:n,anchor_side:e,text:t,font_size:i=.18})=>{let r=.1*(i/.18),s=t.length*r,o=i,a={...n};switch(e){case"right":a.x-=s/2;break;case"left":a.x+=s/2;break;case"top":a.y-=o/2;break;case"bottom":a.y+=o/2;break}return a},G9=({db:n,source_trace_id:e,sameNetOnly:t,differentNetOnly:i})=>{!t&&!i&&(i=!0);let r=n.source_trace.get(e),s=[];for(let o of n.schematic_trace.list()){if(o.source_trace_id===e)continue;let c=n.source_trace.get(o.source_trace_id)?.subcircuit_connectivity_map_key===r.subcircuit_connectivity_map_key;i&&c||t&&!c||s.push(o)}return s},Q7t=({edges:n,otherEdges:e})=>{let t=[...n];for(let i=0;i<t.length;i++){if(i>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let r=t[i],s=Math.abs(r.from.x-r.to.x)<.01?"vertical":r.from.y===r.to.y?"horizontal":"not-orthogonal";if(s==="not-orthogonal")continue;let o=[];for(let x of e){let b=x.from.x===x.to.x?"vertical":x.from.y===x.to.y?"horizontal":"not-orthogonal";if(b==="not-orthogonal"||s===b)continue;if(La([r.from,r.to],[x.from,x.to],{lineThickness:.01})){let P=s==="vertical"?r.from.x:x.from.x,T=s==="vertical"?x.from.y:r.from.y,k={x:P,y:T};o.push({otherEdge:x,crossingPoint:k,distanceFromEdgeFrom:Di(r.from,k)})}}if(o.length===0)continue;let a=o[0];for(let x of o)x.distanceFromEdgeFrom<a.distanceFromEdgeFrom&&(a=x);let c=a.crossingPoint,l=.075;if(c.x===r.from.x&&c.y===r.from.y)continue;let u=jS(r.from,c),p={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},_=Di(d,r.to)<l,g=[{from:r.from,to:p},{from:p,to:d,is_crossing:!0},{from:d,to:r.to}];t.splice(i,1,...g),i+=g.length-2,_&&i++}return t},R9=.001,W_=(n,e)=>{let t=Math.min(e.from.x,e.to.x),i=Math.max(e.from.x,e.to.x),r=Math.min(e.from.y,e.to.y),s=Math.max(e.from.y,e.to.y);return n.x>=t&&n.x<=i&&n.y>=r&&n.y<=s},Ent=n=>{let e=Math.abs(n.from.x-n.to.x)<R9,t=Math.abs(n.from.y-n.to.y)<R9;return e?"vertical":t?"horizontal":"diagonal"},tFt=(n,e)=>{let t=Ent(n),i=Ent(e);if(t===i)return null;if(t==="vertical"&&i==="horizontal"||t==="horizontal"&&i==="vertical"){let p=t==="vertical"?n:e,d=t==="horizontal"?n:e,_=p.from.x,g=d.from.y,x={x:_,y:g};return W_(x,n)&&W_(x,e)?x:null}if(t==="vertical"||i==="vertical"){let p=t==="vertical"?n:e,d=t==="vertical"?e:n,_=p.from.x,g=(d.to.y-d.from.y)/(d.to.x-d.from.x),x=d.from.y-g*d.from.x,b=g*_+x,S={x:_,y:b};return W_(S,n)&&W_(S,e)?S:null}let r=(n.to.y-n.from.y)/(n.to.x-n.from.x),s=n.from.y-r*n.from.x,o=(e.to.y-e.from.y)/(e.to.x-e.from.x),a=e.from.y-o*e.from.x;if(Math.abs(r-o)<R9)return null;let c=(a-s)/(r-o),l=r*c+s,u={x:c,y:l};return W_(u,n)&&W_(u,e)?u:null},eFt=({edges:n,db:e,source_trace_id:t})=>{let i=G9({db:e,source_trace_id:t,sameNetOnly:!0}).flatMap(s=>s.edges),r=new Map;for(let s of n)for(let o of i){let a=tFt(s,o);if(a){let c=`${a.x.toFixed(6)},${a.y.toFixed(6)}`;r.has(c)||r.set(c,a)}}return Array.from(r.values())};function nFt(n,e={}){let{minX:t,maxX:i,minY:r,maxY:s}=n,o=e.padding??1;if(!isFinite(t)||!isFinite(i)||!isFinite(r)||!isFinite(s))return[];let a=t-o,c=i+o,l=s+o,u=r-o,p=.01;return[{type:"rect",layers:["top"],center:{x:(a+c)/2,y:l},width:c-a,height:p,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+c)/2,y:u},width:c-a,height:p,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(l+u)/2},width:p,height:l-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:c,y:(l+u)/2},width:p,height:l-u,connectedTo:[]}]}var iFt=n=>{let e=n.root.db,t=n._findConnectedPorts().ports??[],i=new Set(t.map(o=>o.schematic_port_id)),r=[];for(let o of e.toArray()){if(o.type==="schematic_component"){let a=!!o.symbol_name,c=o.size.width>o.size.height?"horz":"vert";r.push({type:"rect",layers:["top"],center:o.center,width:o.size.width+(a&&c==="horz"?-.5:0),height:o.size.height+(a&&c==="vert"?-.5:0),connectedTo:[]})}if(o.type==="schematic_port"){if(i.has(o.schematic_port_id))continue;let a=o.facing_direction?BS(o.facing_direction):{x:0,y:0};r.push({type:"rect",layers:["top"],center:{x:o.center.x-a.x*.1,y:o.center.y-a.y*.1},width:.1+Math.abs(a.x)*.3,height:.1+Math.abs(a.y)*.3,connectedTo:[]})}o.type==="schematic_text"&&r.push({type:"rect",layers:["top"],center:o.position,width:(o.text?.length??0)*.1,height:.2,connectedTo:[]}),o.type==="schematic_box"&&r.push({type:"rect",layers:["top"],center:{x:o.x,y:o.y},width:o.width,height:o.height,connectedTo:[]})}let s=rit(e.toArray());return r.push(...nFt(s,{padding:1})),r},rFt=({edges:n,db:e,source_trace_id:t})=>{let i=e.source_trace.get(t),r=G9({db:e,source_trace_id:t,differentNetOnly:!0}).flatMap(o=>o.edges),s=o=>{let{from:a,to:c}=o;return a.x===c.x?"vertical":"horizontal"};for(let o of n){let a=s(o),c=()=>r.find(u=>s(u)===a&&La([o.from,o.to],[u.from,u.to],{lineThickness:.05})),l=c();for(;l;)a==="horizontal"?(o.from.y+=.1,o.to.y+=.1):(o.from.x+=.1,o.to.x+=.1),l=c()}},O9=n=>{switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},sFt=Yq.version??"unknown",q1=class extends Error{constructor(n){super(`${n} (capacity-autorouter@${sFt})`),this.name="AutorouterError"}},yP=class extends Error{constructor(n){super(n.message),this.errorData=n,this.name="TraceConnectionError"}},oFt=n=>{if(n.root?._featureMspSchematicTraceRouting||n._couldNotFindPort||n.root?.schematicDisabled)return;let{db:e}=n.root,{_parsedProps:t,parent:i}=n;if(!i)throw new Error("Trace has no parent");let r,s;try{let X=n._findConnectedPorts();r=X.allPortsFound,s=X.portsWithSelectors??[]}catch(X){if(X instanceof yP){e.source_trace_not_connected_error.insert({...X.errorData,error_type:"source_trace_not_connected_error"});return}throw X}let{netsWithSelectors:o}=n._findConnectedNets();if(!r)return;let c=s.map(X=>X.port.schematic_port_id).sort().join(","),l=n.root?._getBoard();if(l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.has(c))return;let u={name:n.source_trace_id,pointsToConnect:[]},p=iFt(n),d=s.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&&o.length===1){let X=o[0].net,{port:W,position:et}=d[0],H=n.getSubcircuit().selectAll("netlabel").find(nt=>{let J=nt._parsedProps.connection??nt._parsedProps.connectsTo;return J?Array.isArray(J)?J.some(ut=>n.getSubcircuit().selectOne(ut,{port:!0})===W):n.getSubcircuit().selectOne(J,{port:!0})===W:!1});if(!H){let nt=e.schematic_net_label.getWhere({source_trace_id:n.source_trace_id});nt&&(H=nt)}if(H){let nt="_getGlobalSchematicPositionBeforeLayout"in H?H._getGlobalSchematicPositionBeforeLayout():H.anchor_position,J=[];et.x===nt.x||et.y===nt.y?J.push({from:et,to:nt}):(J.push({from:et,to:{x:nt.x,y:et.y}}),J.push({from:{x:nt.x,y:et.y},to:nt}));let pt=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:J,junctions:[],subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=pt.schematic_trace_id;return}if(n.props.schDisplayLabel){let nt=e0(W.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel,source_net_id:X.source_net_id,anchor_position:et,center:kl({anchor_position:et,anchor_side:nt,text:n.props.schDisplayLabel}),anchor_side:nt});return}let dt=e0(W.facingDirection)??"bottom",G=e.schematic_net_label.insert({text:X._parsedProps.name,source_net_id:X.source_net_id,anchor_position:et,center:kl({anchor_position:et,anchor_side:dt,text:X._parsedProps.name}),anchor_side:dt});return}if(n.props.schDisplayLabel&&("from"in n.props&&"to"in n.props||"path"in n.props)){n._doInitialSchematicTraceRenderWithDisplayLabel();return}if(d.length<2)return;let x=(()=>{let X=[];for(let et=0;et<d.length-1;et++){let H=d[et],dt=d[et+1],G=tl({x:H.position.x,y:H.position.y,facingDirection:O9(H.facingDirection)},{x:dt.position.x,y:dt.position.y,facingDirection:O9(dt.facingDirection)});for(let nt=0;nt<G.length-1;nt++)X.push({from:G[nt],to:G[nt+1]})}let W=(et,H)=>{let dt=H.width/2,G=H.height/2,nt=H.center.x-dt,J=H.center.x+dt,pt=H.center.y-G,ut=H.center.y+G,wt=ot=>ot.x>=nt&&ot.x<=J&&ot.y>=pt&&ot.y<=ut;return wt(et.from)||wt(et.to)?!0:[[{x:nt,y:pt},{x:J,y:pt}],[{x:J,y:pt},{x:J,y:ut}],[{x:J,y:ut},{x:nt,y:ut}],[{x:nt,y:ut},{x:nt,y:pt}]].some(ot=>La([et.from,et.to],ot,{lineThickness:0}))};for(let et of X)for(let H of p)if(W(et,H))return null;return X})();x&&x.length===0&&(x=null),u.pointsToConnect=d.map(({position:X})=>({...X,layer:"top"}));let b=j7t(p),S=2,P={minTraceWidth:.1,obstacles:p,connections:[u],bounds:{minX:b.minX-S,maxX:b.maxX+S,minY:b.minY-S,maxY:b.maxY+S},layerCount:1},T=MS,k=!1;if(n.getSubcircuit().props._schDirectLineRoutingEnabled&&(T=Pnt,k=!0),!x){let W=new T({input:P,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(W.length===0){if(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection()){n._doInitialSchematicTraceRenderWithDisplayLabel();return}W=new Pnt({input:P}).solveAndMapToTraces(),k=!0}let[{route:et}]=W;x=[];for(let H=0;H<et.length-1;H++)x.push({from:et[H],to:et[H+1]})}let N=n.source_trace_id,M=[];if(!k){rFt({edges:x,db:e,source_trace_id:N});let X=G9({db:e,source_trace_id:N,differentNetOnly:!0}).flatMap(W=>W.edges);x=Q7t({edges:x,otherEdges:X}),M=eFt({edges:x,db:e,source_trace_id:n.source_trace_id})}if(!x||x.length===0)return;let C=x[x.length-1],E=d[d.length-1],R=Tnt(C);x.push(...A9({lastEdge:C,lastEdgePort:E,lastDominantDirection:R}));let A=x[0],j=d[0],D=Tnt(A);if(x.unshift(...A9({firstEdge:A,firstEdgePort:j,firstDominantDirection:D})),!n.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(n.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&U7t(M,x)>=5&&(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection())){n._doInitialSchematicTraceRenderWithDisplayLabel();return}let Y=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:x,junctions:M,subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=Y.schematic_trace_id;for(let{port:X}of s)X.schematic_port_id&&e.schematic_port.update(X.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function L9(n){let e=0;for(let t=0;t<n.length;t++){let i=n[t];if(i.route_type==="wire"){let r=n[t+1];if(r){let s=r.x-i.x,o=r.y-i.y;e+=Math.sqrt(s*s+o*o)}}else i.route_type==="via"&&(e+=1.6)}return e}var aFt=.3,cFt=.6,Cnt=(n,e)=>{if(n===void 0)return e;if(typeof n=="number")return n;let t=parseFloat(n);return Number.isFinite(t)?t:e},W9=n=>({holeDiameter:Cnt(n?.viaHoleDiameter,aFt),padDiameter:Cnt(n?.viaPadDiameter,cFt)}),lFt=(n,e)=>{let t=W9(e);return{holeDiameter:n.holeDiameter??t.holeDiameter,padDiameter:n.padDiameter??t.padDiameter}},lP=n=>({...n._getGlobalPcbPositionAfterLayout(),layers:n.getAvailablePcbLayers()}),uFt=!1;function pFt(n){if(n.root?.pcbDisabled)return;let{db:e}=n.root,{_parsedProps:t,parent:i}=n,r=n.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(r._parsedProps.routingDisabled)return;let s=r._parsedProps.pcbRouteCache?.pcbTraces;if(s){let D=e.pcb_trace.insert({route:s.flatMap(Y=>Y.route),source_trace_id:n.source_trace_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0});n.pcb_trace_id=D.pcb_trace_id;return}if(t.pcbPath&&t.pcbPath.length>0||t.pcbStraightLine||!r._shouldUseTraceByTraceRouting())return;let{allPortsFound:o,ports:a}=n._findConnectedPorts(),c=[];if(!o)return;let l=[];for(let D of a)D._hasMatchedPcbPrimitive()||l.push(D);if(l.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${n} wasn't routed. Missing ports: ${l.map(D=>D.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(D=>D.pcb_port_id).filter(Boolean)});return}let u=n._findConnectedNets().netsWithSelectors;if(a.length===0&&u.length===2){n.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 D=a[0],X=u[0].net.getAllConnectedPorts().filter(et=>et!==D);if(X.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let W=X7t(D,X);c.push(W),a.push(W)}else if(a.length>1&&u.length>=1){n.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let p=a.flatMap(D=>D.matchedComponents.filter(Y=>Y.componentName==="TraceHint")),d=(n._parsedProps.pcbRouteHints??[]).concat(p.flatMap(D=>D.getPcbRouteHints()));if(a.length>2){n.renderError(`Trace has more than two ports (${a.map(D=>D.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(n.getSubcircuit().selectAll("trace").filter(D=>D.renderPhaseStates.PcbTraceRender.initialized).some(D=>D._portsRoutedOnPcb.length===a.length&&D._portsRoutedOnPcb.every(Y=>a.includes(Y))))return;let x=[];d.length===0?x=[lP(a[0]),lP(a[1])]:x=[lP(a[0]),...d,lP(a[1])];let b=hP(x);if(uFt&&b.length===0){n.renderError(`Could not find a common layer (using hints) for trace ${n.getString()}`);return}let S=rr(n.root.db.toArray()),[P,T]=V7t(()=>dit(n.root.db.toArray()));if(T){n.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:n.pcb_trace_id,message:`Error getting obstacles for autorouting: ${T.message}`,source_trace_id:n.source_trace_id,center:{x:0,y:0},pcb_port_ids:a.map(D=>D.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[]});return}for(let D of P)if(D.connectedTo.length>0){let X=S.getNetConnectedToId(D.connectedTo[0]);X&&D.connectedTo.push(X)}let k=[];if(b.length===0)k=x;else{let D=b[0].layer_path;k=x.map((Y,X)=>Y.via?{...Y,via_to_layer:D[X]}:{...Y,layers:[D[X]]})}k[0].pcb_port_id=a[0].pcb_port_id,k[k.length-1].pcb_port_id=a[1].pcb_port_id;let N=[];for(let[D,Y]of iit(k)){let X="via_to_layer"in D?D.via_to_layer:null,W=2,et="layers"in D&&D.layers.length===1?D.layers[0]:X??"top",H="layers"in Y&&Y.layers.length===1?Y.layers[0]:X??"top",dt="pcb_port_id"in D?D.pcb_port_id:null,G="pcb_port_id"in Y?Y.pcb_port_id:null,nt=n._getExplicitTraceThickness()??n.getSubcircuit()._parsedProps.minTraceWidth??.16,J=new MS({OBSTACLE_MARGIN:nt*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(dt&&G),connMap:S,input:{obstacles:P,minTraceWidth:nt,connections:[{name:n.source_trace_id,pointsToConnect:[{...D,layer:et,pcb_port_id:dt},{...Y,layer:H,pcb_port_id:G}]}],layerCount:n.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(D.x,Y.x)-W,maxX:Math.max(D.x,Y.x)+W,minY:Math.min(D.y,Y.y)-W,maxY:Math.max(D.y,Y.y)+W}}}),pt=null;try{pt=J.solveAndMapToTraces()}catch(Et){n.renderError({type:"pcb_trace_error",pcb_trace_error_id:n.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${Et.message}`,source_trace_id:n.pcb_trace_id,center:{x:(D.x+Y.x)/2,y:(D.y+Y.y)/2},pcb_port_ids:a.map(ot=>ot.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:a.map(ot=>ot.pcb_component_id)})}if(!pt)return;if(pt.length===0){n.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:n.pcb_trace_id,message:`Could not find a route for ${n}`,source_trace_id:n.source_trace_id,center:{x:(D.x+Y.x)/2,y:(D.y+Y.y)/2},pcb_port_ids:a.map(Et=>Et.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:a.map(Et=>Et.pcb_component_id)});return}let[ut]=pt;X&&(ut.route=ut.route.map(Et=>(Et.route_type==="wire"&&!Et.layer&&(Et.layer=X),Et))),dt&&ut.route[0].route_type==="wire"&&(ut.route[0].start_pcb_port_id=dt);let wt=ut.route[ut.route.length-1];G&&wt.route_type==="wire"&&(wt.end_pcb_port_id=G),N.push(ut.route)}let M=B7t(N),C=L9(M),E=n.getInheritedMergedProperty("pcbStyle"),{holeDiameter:R,padDiameter:A}=W9(E),j=e.pcb_trace.insert({route:M,source_trace_id:n.source_trace_id,subcircuit_id:n.getSubcircuit()?.subcircuit_id,trace_length:C});n._portsRoutedOnPcb=a,n.pcb_trace_id=j.pcb_trace_id;for(let D of M)D.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:j.pcb_trace_id,x:D.x,y:D.y,hole_diameter:R,outer_diameter:A,layers:[D.from_layer,D.to_layer],from_layer:D.from_layer,to_layer:D.to_layer});n._insertErrorIfTraceIsOutsideBoard(M,a)}function Int(n){let{lineStart:e,lineEnd:t,rectCenter:i,rectWidth:r,rectHeight:s}=n,o=i.x-r/2,a=i.x+r/2,c=i.y+s/2,l=i.y-s/2,u=t.x-e.x,p=t.y-e.y,d=[];if(u!==0){let _=(o-e.x)/u;if(_>=0&&_<=1){let g=e.y+_*p;g>=l&&g<=c&&d.push({x:o,y:g,t:_})}}if(u!==0){let _=(a-e.x)/u;if(_>=0&&_<=1){let g=e.y+_*p;g>=l&&g<=c&&d.push({x:a,y:g,t:_})}}if(p!==0){let _=(l-e.y)/p;if(_>=0&&_<=1){let g=e.x+_*u;g>=o&&g<=a&&d.push({x:g,y:l,t:_})}}if(p!==0){let _=(c-e.y)/p;if(_>=0&&_<=1){let g=e.x+_*u;g>=o&&g<=a&&d.push({x:g,y:c,t:_})}}return d.length===0?null:(d.sort((_,g)=>_.t-g.t),{x:d[0].x,y:d[0].y})}function Nnt(n){let{lineStart:e,lineEnd:t,circleCenter:i,circleRadius:r}=n,s=e.x-i.x,o=e.y-i.y,a=t.x-i.x,c=t.y-i.y,l=a-s,u=c-o,p=l*l+u*u,d=2*(s*l+o*u),_=s*s+o*o-r*r,g=d*d-4*p*_;if(g<0)return null;let x=Math.sqrt(g),b=(-d-x)/(2*p),S=(-d+x)/(2*p),P=null;return b>=0&&b<=1?P=b:S>=0&&S<=1&&(P=S),P===null?null:{x:e.x+P*l,y:e.y+P*u}}function Ant(n){let{traceStart:e,traceEnd:t,traceWidth:i,port:r}=n,s=r.matchedComponents.find(d=>d.isPcbPrimitive);if(!s)return t;let o=s._getPcbCircuitJsonBounds(),a=o.width,c=o.height,l=o.center,u=Math.min(a,c);if(i<=u/2)return t;let p=null;if(s.componentName==="SmtPad"){let d=s,_=d._parsedProps.shape;if(_==="circle"){let g=d._parsedProps.radius;p=Nnt({lineStart:e,lineEnd:t,circleCenter:l,circleRadius:g})}else(_==="rect"||_==="rotated_rect"||_==="pill"||_==="polygon")&&(p=Int({lineStart:e,lineEnd:t,rectCenter:l,rectWidth:a,rectHeight:c}))}else if(s.componentName==="PlatedHole"){let d=s;if(d._parsedProps.shape==="circle"){let g=d._parsedProps.outerDiameter;p=Nnt({lineStart:e,lineEnd:t,circleCenter:l,circleRadius:g/2})}else p=Int({lineStart:e,lineEnd:t,rectCenter:l,rectWidth:a,rectHeight:c})}return p??t}function hFt(n){if(n.root?.pcbDisabled)return;let{db:e}=n.root,{_parsedProps:t}=n,i=n.getSubcircuit(),r=t.pcbPath!==void 0,s=!!t.pcbStraightLine;if(!r&&!s)return;let{allPortsFound:o,ports:a,portsWithSelectors:c}=n._findConnectedPorts();if(!o)return;let l=[];for(let k of a)k._hasMatchedPcbPrimitive()||l.push(k);if(l.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${n} wasn't routed. Missing ports: ${l.map(k=>k.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(k=>k.pcb_port_id).filter(Boolean)});return}let u=n._getExplicitTraceThickness()??n.getSubcircuit()._parsedProps.minTraceWidth??.16;if(s&&!r){if(!a||a.length<2){n.renderError("pcbStraightLine requires exactly two connected ports");return}let[k,N]=a,M=k.getAvailablePcbLayers(),C=N.getAvailablePcbLayers(),R=M.find(H=>C.includes(H))??M[0]??C[0]??"top",A=k._getGlobalPcbPositionAfterLayout(),j=N._getGlobalPcbPositionAfterLayout(),D=Ant({traceStart:j,traceEnd:A,traceWidth:u,port:k}),Y=Ant({traceStart:A,traceEnd:j,traceWidth:u,port:N}),X=[{route_type:"wire",x:D.x,y:D.y,width:u,layer:R,start_pcb_port_id:k.pcb_port_id},{route_type:"wire",x:Y.x,y:Y.y,width:u,layer:R,end_pcb_port_id:N.pcb_port_id}],W=L9(X),et=e.pcb_trace.insert({route:X,source_trace_id:n.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,trace_length:W});n._portsRoutedOnPcb=a,n.pcb_trace_id=et.pcb_trace_id,n._insertErrorIfTraceIsOutsideBoard(X,a);return}if(!t.pcbPath)return;let p;t.pcbPathRelativeTo&&(p=c.find(k=>k.selector===t.pcbPathRelativeTo)?.port,p||(p=n.getSubcircuit().selectOne(t.pcbPathRelativeTo))),p||(p=a[0]);let d=a.find(k=>k!==p)??a[1],_=p.getAvailablePcbLayers()[0]||"top",g=p._getGlobalPcbPositionAfterLayout(),x=d._getGlobalPcbPositionAfterLayout(),b=[];b.push({route_type:"wire",x:g.x,y:g.y,width:u,layer:_,start_pcb_port_id:p.pcb_port_id});let S=p?._computePcbGlobalTransformBeforeLayout?.()||Pr();for(let k of t.pcbPath){let N,M=!1;if(typeof k=="string"){let E=n.getSubcircuit().selectOne(k,{type:"port"});if(!E){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.source_trace_id,message:`Could not resolve pcbPath selector "${k}" for ${n}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:[]});continue}let R=E._getGlobalPcbPositionAfterLayout();N={x:R.x,y:R.y},M=!0}else N={x:k.x,y:k.y},M=!1;let C=M?N:je(S,N);b.push({route_type:"wire",x:C.x,y:C.y,width:u,layer:_})}b.push({route_type:"wire",x:x.x,y:x.y,width:u,layer:_,end_pcb_port_id:d.pcb_port_id});let P=L9(b),T=e.pcb_trace.insert({route:b,source_trace_id:n.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,trace_length:P});n._portsRoutedOnPcb=a,n.pcb_trace_id=T.pcb_trace_id,n._insertErrorIfTraceIsOutsideBoard(b,a)}function dFt(n){if(n.root?.schematicDisabled)return;let{db:e}=n.root,{_parsedProps:t,parent:i}=n;if(!i)throw new Error("Trace has no parent");let{allPortsFound:r,portsWithSelectors:s}=n._findConnectedPorts();if(!r)return;let o=s.map(({port:k})=>({port:k,position:k._getGlobalSchematicPositionAfterLayout(),schematic_port_id:k.schematic_port_id,facingDirection:k.facingDirection}));if(o.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let a,c,l=o[0].position,u=o[0].port;if("path"in n.props){if(n.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[a,c]=n.props.path}else{if(!("from"in n.props&&"to"in n.props))throw new Error("Missing 'from' or 'to' properties in props.");a=n.props.from,c=n.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${a}).`);let p=o[1].position,d=o[1].port;if(!d.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);let _=e.schematic_net_label.list().find(k=>k.source_net_id===u.source_port_id),g=e.schematic_net_label.list().find(k=>k.source_net_id===d.source_port_id),[x,b]=s.map(({port:k})=>k),P=x.parent?.config.shouldRenderAsSchematicBox?`${x?.parent?.props.name}_${x?.props.name}`:`${b?.parent?.props.name}_${b?.props.name}`,T=n.props.schDisplayLabel??P;if(_&&_.text!==T&&(_.text=`${T} / ${_.text}`),g&&g?.text!==T&&(g.text=`${T} / ${g.text}`),!g){let k=e0(d.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??P,source_net_id:d.source_port_id,anchor_position:p,center:kl({anchor_position:p,anchor_side:k,text:n.props.schDisplayLabel??P}),anchor_side:k})}if(!_){let k=e0(u.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??P,source_net_id:u.source_port_id,anchor_position:l,center:kl({anchor_position:l,anchor_side:k,text:n.props.schDisplayLabel??P}),anchor_side:k})}}function fFt(n){let{_parsedProps:e,parent:t}=n;if(!t)throw new Error("Trace has no parent");let r=n.getTracePortPathSelectors().map(s=>({selector:s,port:n.getSubcircuit().selectOne(s,{type:"port"})??null}));for(let{selector:s,port:o}of r)if(!o){let a,c,l=s.lastIndexOf(".");if(l!==-1&&l>s.lastIndexOf(" "))a=s.slice(0,l),c=s.slice(l+1);else{let k=s.match(/^(.*[ >])?([^ >]+)$/);a=k?.[1]?.trim()??"",c=k?.[2]??s}let u=a?n.getSubcircuit().selectOne(a):null;if(!u&&a&&!/[.#\[]/.test(a)&&(u=n.getSubcircuit().selectOne(`.${a}`)),!u){let k=a?`Could not find port for selector "${s}". Component "${a}" not found`:`Could not find port for selector "${s}"`,N=n.getSubcircuit(),M=N.getGroup();throw new yP({error_type:"source_trace_not_connected_error",message:k,subcircuit_id:N.subcircuit_id??void 0,source_group_id:M?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[s]})}let p=u.children.filter(k=>k.componentName==="Port"),d=c.includes(".")?c.split(".").pop()??"":c,_=p.flatMap(k=>k.getNameAndAliases()),g=_.some(k=>!/^(pin\d+|\d+)$/.test(k)),x=Array.from(new Set(_)).join(", "),b;p.length===0?b="It has no ports":g?b=`It has [${x}]`:b=`It has ${p.length} pins and no pinLabels (consider adding pinLabels)`;let S=`Could not find port for selector "${s}". Component "${u.props.name??a}" found, but does not have pin "${d}". ${b}`,P=n.getSubcircuit(),T=P.getGroup();throw new yP({error_type:"source_trace_not_connected_error",message:S,subcircuit_id:P.subcircuit_id??void 0,source_group_id:T?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[s]})}return r.some(s=>!s.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:r,ports:r.map(({port:s})=>s)}}var Ds=class extends Ce{constructor(e){super(e);f(this,"source_trace_id",null);f(this,"pcb_trace_id",null);f(this,"schematic_trace_id",null);f(this,"_portsRoutedOnPcb");f(this,"subcircuit_connectivity_map_key",null);f(this,"_traceConnectionHash",null);f(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}_getExplicitTraceThickness(){return this._parsedProps.thickness??this._parsedProps.width}get config(){return{zodProps:CH,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(e=>typeof e=="string"?e:e.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>!e.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>e.includes("net."))}_findConnectedPorts(){return fFt(this)}_resolveNet(e){let t=this.getSubcircuit().selectOne(e,{type:"net"});if(t)return t;let i=e.match(/^net\.(.+)$/),r=i?i[1]:null;if(!r)return null;let s=this.root?._getBoard();return s?s.getDescendants().find(a=>a.componentName==="Net"&&a._parsedProps.name===r)||null:(this.renderError(`Could not find a <board> ancestor for ${this}, so net "${e}" cannot be resolved`),null)}_findConnectedNets(){let e=this.getTracePathNetSelectors().map(i=>({selector:i,net:this._resolveNet(i)})),t=e.filter(i=>!i.net);return t.length>0&&this.renderError(`Could not find net for selector "${t[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(i=>i.net)}}_getAllTracesConnectedToSameNet(){let e=this.getSubcircuit().selectAll("trace"),t=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return e.filter(r=>{if(r===this)return!1;let s=r._findConnectedNets().nets,o=r._findConnectedPorts().ports??[];return s.some(a=>t.includes(a))||o.some(a=>i.includes(a))})}_isExplicitlyConnectedToPort(e){let{allPortsFound:t,portsWithSelectors:i}=this._findConnectedPorts();return t?i.map(s=>s.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){bP(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();return!e||!t?null:[...t].sort((s,o)=>(s.pcb_port_id||"").localeCompare(o.pcb_port_id||"")).map(s=>s.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:e}=this.root,{_parsedProps:t,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}let r,s;try{let p=this._findConnectedPorts();r=p.allPortsFound,s=p.portsWithSelectors??[]}catch(p){if(p instanceof yP){e.source_trace_not_connected_error.insert({...p.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw p}if(!r)return;this._traceConnectionHash=this._computeTraceConnectionHash();let a=e.source_trace.list().find(p=>p.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&p.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=W7t({ports:s,nets:c}),u=e.source_trace.insert({connected_source_port_ids:s.map(p=>p.port.source_port_id),connected_source_net_ids:c.map(p=>p.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:G7t(s.map(p=>p.port),{db:e})??t.maxLength,display_name:l,min_trace_thickness:this._getExplicitTraceThickness()});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,t){let{db:i}=this.root;H7t(e,{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:t.map(s=>s.pcb_port_id)})}doInitialPcbManualTraceRender(){hFt(this)}doInitialPcbTraceRender(){pFt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){dFt(this)}_isSymbolToChipConnection(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;let[i,r]=t;if(!i?.parent||!r?.parent)return!1;let s=i.parent.config.shouldRenderAsSchematicBox,o=r.parent.config.shouldRenderAsSchematicBox;return s&&!o||!s&&o}_isSymbolToSymbolConnection(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;let[i,r]=t;if(!i?.parent||!r?.parent)return!1;let s=!i.parent.config.shouldRenderAsSchematicBox,o=!r.parent.config.shouldRenderAsSchematicBox;return s&&o}_isChipToChipConnection(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;let[i,r]=t;if(!i?.parent||!r?.parent)return!1;let s=i.parent.config.shouldRenderAsSchematicBox,o=r.parent.config.shouldRenderAsSchematicBox;return s&&o}doInitialSchematicTraceRender(){oFt(this)}},mFt=n=>{let{db:e}=n.root;if(n.pcb_component_id){let t=e.pcb_component.get(n.pcb_component_id);return t?{width:t.width,height:t.height}:null}if(n.pcb_group_id){let t=e.pcb_group.get(n.pcb_group_id);if(!t)return null;if(t.outline&&t.outline.length>0){let i=lo(t.outline);return i?{width:i.maxX-i.minX,height:i.maxY-i.minY}:null}return{width:t.width??0,height:t.height??0}}return null},_Ft=(n,e)=>{let{db:t}=n.root,i=t.toArray();if(n.pcb_component_id){YS(i,n.pcb_component_id,e);return}if(n.source_group_id){XS(i,n.source_group_id,e);return}throw new Error(`Cannot reposition component ${n.getString()}: no pcb_component_id or source_group_id`)},yFt=n=>{let{db:e}=n.root;if(!n.source_component_id)return;let t=n.selectAll("port"),i=e.source_trace.list(),r=new Set;for(let o of i)for(let a of o.connected_source_port_ids)r.add(a);let s=n._getInternallyConnectedPins();for(let o of s)if(o.some(a=>a.source_port_id&&r.has(a.source_port_id)))for(let a of o)a.source_port_id&&r.add(a.source_port_id);for(let o of t)o.source_port_id&&gFt(n,o)&&(r.has(o.source_port_id)||e.source_pin_missing_trace_warning.insert({message:`Port ${o.getNameAndAliases()[0]} on ${n.props.name} is missing a trace`,source_component_id:n.source_component_id,source_port_id:o.source_port_id,subcircuit_id:n.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},gFt=(n,e)=>{if(n.config.componentName==="Chip"){let t=n.props.pinAttributes;if(!t)return!1;for(let i of e.getNameAndAliases()){let r=t[i];if(r?.requiresPower||r?.requiresGround||r?.requiresVoltage!==void 0)return!0}return!1}return!0};function xFt(n){let e=n.font_size,t=n.text.length*e*.6,i=e,r=n.anchor_alignment||"center",s=n.anchor_position.x,o=n.anchor_position.y;switch(r){case"top_left":s=n.anchor_position.x+t/2,o=n.anchor_position.y+i/2;break;case"top_center":s=n.anchor_position.x,o=n.anchor_position.y+i/2;break;case"top_right":s=n.anchor_position.x-t/2,o=n.anchor_position.y+i/2;break;case"center_left":s=n.anchor_position.x+t/2,o=n.anchor_position.y;break;case"center":s=n.anchor_position.x,o=n.anchor_position.y;break;case"center_right":s=n.anchor_position.x-t/2,o=n.anchor_position.y;break;case"bottom_left":s=n.anchor_position.x+t/2,o=n.anchor_position.y-i/2;break;case"bottom_center":s=n.anchor_position.x,o=n.anchor_position.y-i/2;break;case"bottom_right":s=n.anchor_position.x-t/2,o=n.anchor_position.y-i/2;break;default:s=n.anchor_position.x,o=n.anchor_position.y;break}return{x:s-t/2,y:o-i/2,width:t,height:i}}function bFt(n){if(!n._adjustSilkscreenTextAutomatically||n.root?.pcbDisabled||!n.pcb_component_id)return;let{db:e}=n.root,i=n._getPcbCircuitJsonBounds().center,r=e.pcb_silkscreen_text.list({pcb_component_id:n.pcb_component_id}).filter(c=>c.text===n.name);if(r.length===0)return;let a=n.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(c=>c!==n&&c.pcb_component_id).map(c=>{let l=c._getPcbCircuitJsonBounds(),u={center:l.center,width:l.width,height:l.height};return oo(u)});for(let c of r){let l=c.anchor_position,u=xFt(c),p={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},d=oo(p);if(!a.some(T=>Qc(d,T)))continue;let g=2*i.x-l.x,x=2*i.y-l.y,b={center:{x:g,y:x},width:u.width,height:u.height},S=oo(b);a.some(T=>Qc(S,T))||e.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:g,y:x}})}}function vFt(n){if(!n)return{validPinLabels:n,invalidPinLabelsMessages:[]};let e={},t=[];for(let[i,r]of Object.entries(n)){let s=Array.isArray(r)?r.slice():[r],o=[];for(let a of s)SFt(i,a)?o.push(a):t.push(`Invalid pin label: ${i} = '${a}' - excluding from component. Please use a valid pin label.`);o.length>0&&(e[i]=Array.isArray(r)?o:o[0])}return{validPinLabels:Object.keys(e).length>0?e:void 0,invalidPinLabelsMessages:t}}function SFt(n,e){try{let t={name:"test",footprint:"test",pinLabels:{[n]:e}};return l_.safeParse(t).success}catch{return!1}}var Q_=n=>n.startsWith("http://")||n.startsWith("https://"),z9=n=>{if(Q_(n))return null;let e=n.indexOf(":");if(e<=0)return null;let t=n.slice(0,e),i=n.slice(e+1);return!t||!i?null:{footprintLib:t,footprintName:i}},$9=n=>n.startsWith("/"),wFt=(0,fit.default)("tscircuit:core:resolveStaticFileImport");async function mit(n,e){if(!n)return n;let t=e?.resolveProjectStaticFileImportUrl;if(t&&n.startsWith("/"))try{let i=await t(n);if(i)return i}catch(i){wFt("failed to resolve static file via platform resolver",i)}return uit(n,e?.projectBaseUrl)}function PFt(n,e){let{footprint:t}=n.props;if(t??(t=n._getImpliedFootprintString?.()),!t)return;let{pcbRotation:i,pinLabels:r,pcbPinLabels:s}=n.props,o=lit(String(t)),a=o?n.root?.platform?.footprintFileParserMap?.[o]:null;if(typeof t=="string"&&(Q_(t)||$9(t))&&a){if(n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0,e("load-footprint-from-platform-file-parser",async()=>{let c=Q_(t)?t:await mit(t,n.root?.platform);try{let l=await a.loadFromUrl(c),u=J_({componentName:n.name,componentRotation:i,footprinterString:c,pinLabels:r,pcbPinLabels:s},l.footprintCircuitJson);n.addAll(u),n._markDirty("InitializePortsFromChildren")}catch(l){let u=n.root?.db;if(u&&n.source_component_id&&n.pcb_component_id){let p=n.getSubcircuit(),d=`${n.getString()} failed to load footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Bm.parse({type:"external_footprint_load_error",message:d,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:p.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof t=="string"&&Q_(t)){if(n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let c=t;e("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(),p=J_({componentName:n.name,componentRotation:i,footprinterString:c,pinLabels:r,pcbPinLabels:s},u);n.addAll(p),n._markDirty("InitializePortsFromChildren")}catch(l){let u=n.root?.db;if(u&&n.source_component_id&&n.pcb_component_id){let p=n.getSubcircuit(),d=`${n.getString()} failed to load external footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Bm.parse({type:"external_footprint_load_error",message:d,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:p.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof t=="string"){let c=z9(t);if(!c||n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let u=n.root?.platform?.footprintLibraryMap?.[c.footprintLib],p;if(typeof u=="function"&&(p=u),!p)return;let d=n.getInheritedMergedProperty("pcbStyle");e("load-lib-footprint",async()=>{try{let _=await p(c.footprintName,{resolvedPcbStyle:d}),g=null;if(Array.isArray(_)?g=_:Array.isArray(_.footprintCircuitJson)&&(g=_.footprintCircuitJson),!g)return;let x=J_({componentName:n.name,componentRotation:i,footprinterString:t,pinLabels:r,pcbPinLabels:s},g);n.addAll(x),!Array.isArray(_)&&_.cadModel&&(n._asyncFootprintCadModel=_.cadModel);for(let b of n.children)b.componentName==="Port"&&b._markDirty?.("PcbPortRender");n._markDirty("InitializePortsFromChildren")}catch(_){let g=n.root?.db;if(g&&n.source_component_id&&n.pcb_component_id){let x=n.getSubcircuit(),b=`${n.getString()} failed to load external footprint "${t}": `+(_ instanceof Error?_.message:String(_)),S=Bm.parse({type:"external_footprint_load_error",message:b,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:x.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,footprinter_string:t});g.external_footprint_load_error.insert(S)}throw _}});return}if(!(0,F9.isValidElement)(t)&&t.componentName==="Footprint"&&n.add(t),Array.isArray(t)&&!(0,F9.isValidElement)(t)&&t.length>0){try{let c=J_({componentName:n.name,componentRotation:i,footprinterString:"",pinLabels:r,pcbPinLabels:s},t);n.addAll(c)}catch(c){let l=n.root?.db;if(l&&n.source_component_id&&n.pcb_component_id){let u=n.getSubcircuit(),p=`${n.getString()} failed to load json footprint: `+(c instanceof Error?c.message:String(c)),d=pb.parse({type:"circuit_json_footprint_load_error",message:p,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:u.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0});l.circuit_json_footprint_load_error.insert(d)}throw c}return}}function kFt(n){if(n.root?.pcbDisabled||!n.pcb_component_id)return;let{pcbX:e,pcbY:t}=n._parsedProps,i=n.props?.pcbPositionAnchor;if(!i||e===void 0&&t===void 0)return;let r=wP(n.children);if(r.width===0||r.height===0)return;let o={...{x:(r.minX+r.maxX)/2,y:(r.minY+r.maxY)/2}},a=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(i)){let u={left:r.minX,right:r.maxX,top:r.minY,bottom:r.maxY};switch(i){case"center":a=o;break;case"top_left":a={x:u.left,y:u.top};break;case"top_center":a={x:o.x,y:u.top};break;case"top_right":a={x:u.right,y:u.top};break;case"center_left":a={x:u.left,y:o.y};break;case"center_right":a={x:u.right,y:o.y};break;case"bottom_left":a={x:u.left,y:u.bottom};break;case"bottom_center":a={x:o.x,y:u.bottom};break;case"bottom_right":a={x:u.right,y:u.bottom};break}}else try{let u=n.portMap[i];u&&(a=u._getGlobalPcbPositionBeforeLayout())}catch{}if(!a)return;let l={...o};e!==void 0&&(l.x+=e-a.x),t!==void 0&&(l.y+=t-a.y),(Math.abs(l.x-o.x)>1e-6||Math.abs(l.y-o.y)>1e-6)&&n._repositionOnPcb(l)}var TFt=(0,Knt.default)("tscircuit:core"),MFt=h.object({x:en,y:en,z:en}),Yn=class extends Ce{constructor(e){let t={...e},i=[];if(t.pinLabels&&!Array.isArray(t.pinLabels)){let{validPinLabels:r,invalidPinLabelsMessages:s}=vFt(t.pinLabels);t.pinLabels=r,i=s}super(t);f(this,"reactSubtrees",[]);f(this,"_impliedFootprint");f(this,"isPrimitiveContainer",!0);f(this,"_isNormalComponent",!0);f(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});f(this,"_asyncSupplierPartNumbers");f(this,"_asyncFootprintCadModel");f(this,"_isCadModelChild");f(this,"pcb_missing_footprint_error_id");f(this,"_hasStartedFootprintUrlLoad",!1);f(this,"_invalidPinLabelMessages",[]);f(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=i,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(t=>t.map(i=>typeof i=="number"?`pin${i}`:i))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let e=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(r=>r!==this&&r._isNormalComponent&&r.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let r=this._getGlobalPcbPositionBeforeLayout(),s=this._getGlobalSchematicPositionBeforeLayout();e.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:r,schematic_center:s}),this.shouldBeRemoved=!0;let o=[...this.children];for(let a of o)this.remove(a)}}initPorts(e={}){if(this.root?.schematicDisabled)return;let{config:t}=this,i=[],r=this._getSchematicPortArrangement();if(r&&!this._parsedProps.pinLabels){for(let l in r){let u=r[l].pins;if(Array.isArray(u))for(let p of u){let d=t0(p,this._parsedProps.pinLabels);i.push(new qi({pinNumber:d,aliases:e.additionalAliases?.[`pin${d}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let a=["left","right","top","bottom"],c=1;for(let l of a){let u=r[`${l}Size`];for(let p=0;p<u;p++)i.push(new qi({pinNumber:c++,aliases:e.additionalAliases?.[`pin${c}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let s=this._parsedProps.pinLabels;if(s)for(let[a,c]of Object.entries(s)){a=a.replace("pin","");let l=i.find(d=>d._parsedProps.pinNumber===Number(a)),u=Array.isArray(c)?c[0]:c,p=Array.isArray(c)?c.slice(1):[];l?(l.externallyAddedAliases.push(u,...p),l.props.name=u):(l=new qi({pinNumber:parseInt(a),name:u,aliases:[...p,...e.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(t.schematicSymbolName&&!e.ignoreSymbolPorts){let a=bi[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=sit(c.labels);if(!l)continue;let u=i.find(p=>p._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let p=H1(c.labels.concat(e.additionalAliases?.[`pin${l}`]??[]));p&&(p.originDescription=`schematicSymbol:labels[0]:${c.labels[0]}`,p.schematicSymbolPortDef=c,i.push(p))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){let a=this.getPortsFromFootprint(e);for(let c of a)i.some(l=>l.isMatchingAnyOf(c.getNameAndAliases()))||i.push(c)}let o=e.pinCount??this._getPinCount()??0;for(let a=1;a<=o;a++){if(i.find(l=>l._parsedProps.pinNumber===a))continue;if(!r){i.push(new qi({pinNumber:a,aliases:e.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...r.leftSide?.pins??[],...r.rightSide?.pins??[],...r.topSide?.pins??[],...r.bottomSide?.pins??[]].map(l=>t0(l,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(l=>l in r)&&(c=Array.from({length:this._getPinCount()},(l,u)=>u+1)),c.includes(a)&&i.push(new qi({pinNumber:a,aliases:e.additionalAliases?.[`pin${a}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${a}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:e,pinLabels:t,pcbPinLabels:i}=this.props,{footprint:r}=this.props;if(r??(r=this._getImpliedFootprintString?.()),!!r&&typeof r=="string"){if(Q_(r)||$9(r)||z9(r))return;let s=UE.string(r).soup(),o=J_({componentName:this.name??this.componentName,componentRotation:e,footprinterString:r,pinLabels:t,pcbPinLabels:i},s);this.addAll(o)}}get portMap(){return new Proxy({},{get:(e,t)=>{let i=this.children.find(r=>r.componentName==="Port"&&r.isMatchingNameOrAlias(t));if(!i)throw new Error(`There was an issue finding the port "${t.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return i}})}getInstanceForReactElement(e){for(let t of this.reactSubtrees)if(t.element===e)return t.component;return null}doInitialSourceRender(){let e=this.config.sourceFtype;if(!e)return;let{db:t}=this.root,{_parsedProps:i}=this,r=t.source_component.insert({ftype:e,name:this.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=r.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let s of this._invalidPinLabelMessages){let o="pinLabels",a=s.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);a&&(o=`pinLabels['${a[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:o,message:s,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:t}=this.config,{_parsedProps:i}=this;i.symbol&&(0,Ha.isValidElement)(i.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(i.symbol):t?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let r=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&r){if(!this.schematic_component_id)return;let s=cb.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});e.schematic_manual_edit_conflict_warning.insert(s)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let e=[];for(let t of this.internallyConnectedPinNames){let i=[];for(let r of t)i.push(this.portMap[r]);e.push(i)}return e}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getSchematicSymbolNameOrThrow(),r=bi[i],s=this._getGlobalSchematicPositionBeforeLayout();if(r){let o=e.schematic_component.insert({center:s,size:r.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=o.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(e){if(this.root?.schematicDisabled)return;let{db:t}=this.root,i=this._getGlobalSchematicPositionBeforeLayout(),r=t.schematic_component.insert({center:i,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=r.schematic_component_id}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getSchematicBoxDimensions(),r={};if(Array.isArray(t.pinLabels))t.pinLabels.forEach((_,g)=>{r[String(g+1)]=_});else for(let[_,g]of Object.entries(t.pinLabels??{}))r[_]=Array.isArray(g)?g[0]:g;let s=this._getGlobalSchematicPositionBeforeLayout(),o=this._getSchematicPortArrangement(),a=e.schematic_component.insert({center:s,rotation:t.schRotation??0,size:i.getSize(),port_arrangement:k7t(o),pin_spacing:t.schPinSpacing??.2,pin_styles:P7t(t.schPinStyle,t.pinLabels),port_labels:r,source_component_id:this.source_component_id}),c=o?.topSide!==void 0||o?.bottomSide!==void 0,l=i?.getSize().width,u=i?.getSize().height,p=e.schematic_text.insert({text:t.manufacturerPartNumber??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?s.x+(l??0)/2+.1:s.x-(l??0)/2,y:c?s.y+(u??0)/2+.35:s.y-(u??0)/2-.13},color:"#006464",font_size:.18}),d=e.schematic_text.insert({text:t.name??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?s.x+(l??0)/2+.1:s.x-(l??0)/2,y:c?s.y+(u??0)/2+.55:s.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:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=t.layer??"top";if(r!=="top"&&r!=="bottom"){let p=Ym.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${r}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:r,subcircuit_id:i.subcircuit_id??void 0});e.pcb_component_invalid_layer_error.insert(p)}let s=this._computePcbGlobalTransformBeforeLayout(),a=ro(s).rotation.angle*180/Math.PI,c=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:r==="top"||r==="bottom"?r:"top",rotation:t.pcbRotation??a,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});if(!(t.footprint??this._getImpliedFootprintString())&&!this.isGroup){let p=e.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=p.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 p=hb.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});e.pcb_manual_edit_conflict_warning.insert(p)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:e}=this.root,{_parsedProps:t}=this,i=wP(this.children);if(i.width===0||i.height===0)return;let r={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:r,width:i.width,height:i.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db:e}=this.root;if(!e.schematic_component.get(this.schematic_component_id))return;let i=[],r=u=>{for(let p of u){if(p.isSchematicPrimitive&&p.componentName==="SchematicLine"){let d=e.schematic_line.get(p.schematic_line_id);d&&i.push(d)}if(p.isSchematicPrimitive&&p.componentName==="SchematicRect"){let d=e.schematic_rect.get(p.schematic_rect_id);d&&i.push(d)}if(p.isSchematicPrimitive&&p.componentName==="SchematicCircle"){let d=e.schematic_circle.get(p.schematic_circle_id);d&&i.push(d)}if(p.isSchematicPrimitive&&p.componentName==="SchematicArc"){let d=e.schematic_arc.get(p.schematic_arc_id);d&&i.push(d)}if(p.isSchematicPrimitive&&p.componentName==="SchematicText"){let d=e.schematic_text.get(p.schematic_text_id);d&&i.push(d)}p.children&&p.children.length>0&&r(p.children)}};if(r(this.children),i.length===0)return;let s=rit(i),o=Math.abs(s.maxX-s.minX),a=Math.abs(s.maxY-s.minY);if(o===0&&a===0)return;let c=(s.minX+s.maxX)/2,l=(s.minY+s.maxY)/2;e.schematic_component.update(this.schematic_component_id,{center:{x:c,y:l},size:{width:o,height:a}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){kFt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(e){let t=nit(e);return{element:e,component:t}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let e=this.props.footprint;(0,Ha.isValidElement)(e)&&(this.children.some(s=>s.componentName==="Footprint")||this.add(e));let t=this.props.symbol;(0,Ha.isValidElement)(t)&&(this.children.some(s=>s.componentName==="Symbol")||this.add(t));let i=this.props.cadModel;if((0,Ha.isValidElement)(i)){this._isCadModelChild=!0;let r=this.children.some(o=>o.componentName==="CadAssembly"),s=this.children.some(o=>o.componentName==="CadModel");!r&&!s&&this.add(i)}}doInitialPcbFootprintStringRender(){PFt(this,(e,t)=>this._queueAsyncEffect(e,t))}_hasExistingPortExactly(e){return this.children.filter(i=>i.componentName==="Port").some(i=>{let r=e.getNameAndAliases(),s=i.getNameAndAliases();return r.length===s.length&&r.every(o=>s.includes(o))})}add(e){let t;if((0,Ha.isValidElement)(e)){let i=this._renderReactSubtree(e);this.reactSubtrees.push(i),t=i.component}else t=e;if(t.componentName==="Port"){if(this._hasExistingPortExactly(t))return;let r=this.children.filter(s=>s.componentName==="Port").find(s=>s.isMatchingAnyOf(t.getNameAndAliases()));r&&TFt(`Similar ports added. Port 1: ${r}, Port 2: ${t}`)}super.add(t)}getPortsFromFootprint(e){let{footprint:t}=this.props;if((!t||(0,Ha.isValidElement)(t))&&(t=this.children.find(r=>r.componentName==="Footprint")),typeof t=="string"){if(Q_(t))return[];if($9(t))return[];if(z9(t))return[];let r=UE.string(t).soup(),s=[];for(let o of r)if("port_hints"in o&&o.port_hints){let a=H1(o.port_hints,e);if(!a)continue;a.originDescription=`footprint:string:${t}:port_hints[0]:${o.port_hints[0]}`,s.push(a)}return s}if(!(0,Ha.isValidElement)(t)&&t&&t.componentName==="Footprint"){let r=t,s=1,o=[];for(let a of r.children){if(!a.props.portHints)continue;let c=a.props.portHints;c.some(p=>p.startsWith("pin"))||(c=[...c,`pin${s}`]),s++;let u=H1(c);u&&(u.originDescription=`footprint:${t}`,o.push(u))}return o}let i=[];if(!t){for(let r of this.children)if(r.props.portHints&&r.isPcbPrimitive){let s=H1(r.props.portHints);s&&i.push(s)}}return i}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:e}=this;if(!e.schematicSymbolName)return[];let t=bi[e.schematicSymbolName];if(!t)return[];let i=[];for(let r of t.ports){let s=H1(r.labels);s&&(s.schematicSymbolPortDef=r,i.push(s))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:e}=this,t=[];if(e.connections)for(let[i,r]of Object.entries(e.connections)){let s=Array.isArray(r)?r:[r];for(let o of s)t.push(String(o))}return t}_createNetsFromProps(e){bP(this,e)}_getPcbCircuitJsonBounds(){let{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let t=e.pcb_component.get(this.pcb_component_id);return{center:{x:t.center.x,y:t.center.y},bounds:{left:t.center.x-t.width/2,top:t.center.y-t.height/2,right:t.center.x+t.width/2,bottom:t.center.y+t.height/2},width:t.width,height:t.height}}_getPinCountFromSchematicPortArrangement(){let e=this._getSchematicPortArrangement();if(!e)return 0;if(!oit(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);let{leftSide:i,rightSide:r,topSide:s,bottomSide:o}=e;return Math.max(...i?.pins??[],...r?.pins??[],...s?.pins??[],...o?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let t=this.getPortsFromFootprint();if(t.length>0)return t.length;let{pinLabels:i}=this._parsedProps;if(i){if(Array.isArray(i))return i.length;let r=Object.keys(i).map(s=>s.startsWith("pin")?parseInt(s.slice(3)):parseInt(s)).filter(s=>!Number.isNaN(s));return r.length>0?Math.max(...r):Object.keys(i).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getPinLabelsFromPorts(){let e=this.selectAll("port"),t={};for(let i of e){let r=i.props.pinNumber;if(r!==void 0){let s=i._getBestDisplayPinLabel();s&&(t[`pin${r}`]=s)}}return t}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this,t=this._getPinCount(),i=e.schPinSpacing??.2,s={...this._getPinLabelsFromPorts(),...e.pinLabels};return F7t({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:i,numericSchPinStyle:D7t(e.schPinStyle,s),pinCount:t,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:s})}getFootprinterString(){return typeof this._parsedProps.footprint=="string"?this._parsedProps.footprint:null}doInitialCadModelRender(){if(this._isCadModelChild||this.props.doNotPlace)return;let{db:e}=this.root,{boardThickness:t=0}=this.root?._getBoard()??{},i=this._parsedProps.cadModel,r=i===void 0?this._asyncFootprintCadModel:i,s=this.getFootprinterString()??this._getImpliedFootprintString();if(!this.pcb_component_id||!r&&!s||r===null)return;let o=this._getPcbCircuitJsonBounds();if(typeof r=="string")throw new Error("String cadModel not yet implemented");let a=MFt.parse({x:0,y:0,z:typeof r?.rotationOffset=="number"?r.rotationOffset:0,...typeof r?.rotationOffset=="object"?r.rotationOffset??{}:{}}),c=Wh.parse({x:0,y:0,z:0,...typeof r?.positionOffset=="object"?r.positionOffset:{}}),l=r&&typeof r=="object"&&"zOffsetFromSurface"in r&&r.zOffsetFromSurface!==void 0?V.parse(r.zOffsetFromSurface):0,u=this.props.layer==="bottom"?"bottom":"top",p=this._computePcbGlobalTransformBeforeLayout(),_=ro(p).rotation.angle*180/Math.PI,g=u==="bottom",x=_+(a.z??0),b=md(x),S=e.cad_component.insert({position:{x:o.center.x+c.x,y:o.center.y+c.y,z:(u==="bottom"?-t/2:t/2)+(u==="bottom"?-l:l)+c.z},rotation:{x:a.x,y:a.y+(g?180:0),z:md(g?-b:b)},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(r??{})?this._addCachebustToModelUrl(r.stlUrl):void 0,model_obj_url:"objUrl"in(r??{})?this._addCachebustToModelUrl(r.objUrl):void 0,model_mtl_url:"mtlUrl"in(r??{})?this._addCachebustToModelUrl(r.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(r??{})?this._addCachebustToModelUrl(r.gltfUrl):void 0,model_glb_url:"glbUrl"in(r??{})?this._addCachebustToModelUrl(r.glbUrl):void 0,model_step_url:"stepUrl"in(r??{})?this._addCachebustToModelUrl(r.stepUrl):void 0,model_wrl_url:"wrlUrl"in(r??{})?this._addCachebustToModelUrl(r.wrlUrl):void 0,model_jscad:"jscad"in(r??{})?r.jscad:void 0,model_unit_to_mm_scale_factor:typeof r?.modelUnitToMmScale=="number"?r.modelUnitToMmScale:void 0,footprinter_string:typeof s=="string"&&!r?s:void 0,show_as_translucent_model:this._parsedProps.showAsTranslucentModel});this.cad_component_id=S.cad_component_id}_addCachebustToModelUrl(e){if(!e||!e.includes("modelcdn.tscircuit.com"))return e;let t=this.root?.getClientOrigin()??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(t)}`}_getPartsEngineCacheKey(e,t){return JSON.stringify({ftype:e.ftype,name:e.name,manufacturer_part_number:e.manufacturer_part_number,footprinterString:t})}async _getSupplierPartNumbers(e,t,i){if(this.props.doNotPlace)return{};let r=this.root?.platform?.localCacheEngine,s=this._getPartsEngineCacheKey(t,i);if(r){let c=await r.getItem(s);if(c)try{return JSON.parse(c)}catch{}}let o=await Promise.resolve(e.findPart({sourceComponent:t,footprinterString:i}));if(typeof o=="string"){if(o.includes("<!DOCTYPE")||o.includes("<html"))throw new Error(`Failed to fetch supplier part numbers: Received HTML response instead of JSON. Response starts with: ${o.substring(0,100)}`);if(o==="Not found")return{};throw new Error(`Invalid supplier part numbers format: Expected object but got string: "${o}"`)}if(!o||Array.isArray(o)||typeof o!="object"){let c=o===null?"null":Array.isArray(o)?"array":typeof o;throw new Error(`Invalid supplier part numbers format: Expected object but got ${c}`)}let a=o;if(r)try{await r.setItem(s,JSON.stringify(a))}catch{}return a}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let e=this.getInheritedProperty("partsEngine");if(!e)return;let{db:t}=this.root,i=t.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let r;this.props.footprint&&typeof this.props.footprint=="string"&&(r=this.props.footprint);let s=this._getSupplierPartNumbers(e,i,r);if(!(s instanceof Promise)){t.source_component.update(this.source_component_id,{supplier_part_numbers:s});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{await s.then(o=>{this._asyncSupplierPartNumbers=o,this._markDirty("PartsEngineRender")}).catch(o=>{this._asyncSupplierPartNumbers={};let a=ob.parse({type:"unknown_error_finding_part",message:`Failed to fetch supplier part numbers for ${this.getString()}: ${o.message}`,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});t.unknown_error_finding_part.insert(a),this._markDirty("PartsEngineRender")})})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:e}=this.root,t=e.source_component.get(this.source_component_id);if(t&&!t.supplier_part_numbers&&this._asyncSupplierPartNumbers){e.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:e}=this;e.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:e}=this;if(e.connections)for(let[t,i]of Object.entries(e.connections)){let r=Array.isArray(i)?i:[i];for(let s of r)this.add(new Ds({from:`.${this.name} > .${t}`,to:String(s)}))}}doInitialSourceDesignRuleChecks(){yFt(this)}_getMinimumFlexContainerSize(){return mFt(this)}_repositionOnPcb(e){return _Ft(this,e)}doInitialSilkscreenOverlapAdjustment(){return bFt(this)}isRelativelyPositioned(){return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0}},EFt=({boardAnchorPosition:n,boardAnchorAlignment:e,width:t,height:i})=>{let{x:r,y:s}=n,o=r,a=s;switch(e){case"top_left":o=r+t/2,a=s-i/2;break;case"top_right":o=r-t/2,a=s-i/2;break;case"bottom_left":o=r+t/2,a=s+i/2;break;case"bottom_right":o=r-t/2,a=s+i/2;break;case"top":o=r,a=s-i/2;break;case"bottom":o=r,a=s+i/2;break;case"left":o=r+t/2,a=s;break;case"right":o=r-t/2,a=s;break;case"center":default:break}return{x:o,y:a}},CFt=class{constructor(n,e={}){f(this,"input");f(this,"isRouting",!1);f(this,"solver");f(this,"eventHandlers",{complete:[],error:[],progress:[]});f(this,"cycleCount",0);f(this,"stepDelay");f(this,"timeoutId");this.input=n;let{capacityDepth:t,targetMinCapacity:i,stepDelay:r=0,useAssignableViaSolver:s=!1}=e,{AutoroutingPipelineSolver:o,AssignableViaAutoroutingPipelineSolver:a}=PN,c=s?a:o;this.solver=new c(n,{capacityDepth:t,targetMinCapacity:i,cacheProvider:null}),this.stepDelay=r}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new q1(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let n=Date.now(),e=this.solver.iterations;for(;Date.now()-n<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let t=(this.solver.iterations-e)/(Date.now()-n)*1e3;this.cycleCount++;let i=this.solver?.preview()||void 0,r=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:t,progress:r,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(n){this.emitEvent({type:"error",error:n instanceof Error?new q1(n.message):new q1(String(n))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(n,e){n==="complete"?this.eventHandlers.complete.push(e):n==="error"?this.eventHandlers.error.push(e):n==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(n){if(n.type==="complete")for(let e of this.eventHandlers.complete)e(n);else if(n.type==="error")for(let e of this.eventHandlers.error)e(n);else if(n.type==="progress")for(let e of this.eventHandlers.progress)e(n)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new q1(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},H9=class extends Ce{constructor(){super(...arguments);f(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:xq}}doInitialPortMatching(){let{db:e}=this.root,{_parsedProps:t,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(!t.for){this.renderError(`TraceHint has no for property (${this})`);return}let r=i.selectOne(t.for,{type:"port"});r||this.renderError(`${this} could not find port for selector "${t.for}"`),this.matchedPort=r,r.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:e}=this,t=e.offset?[e.offset]:e.offsets;if(!t)return[];let i=this._computePcbGlobalTransformBeforeLayout();return t.map(r=>({...je(i,r),via:r.via,to_layer:r.to_layer,trace_width:r.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this;e.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},_it=({circuitJson:n,editEvents:e,manualEditsFile:t})=>{let i={...t,pcb_placements:[...t.pcb_placements??[]]};for(let r of e)if(r.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:s,new_center:o}=r,a=Ie(n).pcb_component.get(s);if(!a)continue;let c=Ie(n).source_component.get(a.source_component_id);if(!c)continue;let l=i.pcb_placements?.findIndex(p=>p.selector===c.name),u={selector:c.name,center:o,relative_to:"group_center"};l>=0?i.pcb_placements[l]=u:i.pcb_placements.push(u)}return i},yit=({circuitJson:n,editEvents:e,manualEditsFile:t})=>{let i={...t,schematic_placements:[...t.schematic_placements??[]]};for(let r of e)if(r.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:s,new_center:o}=r,a=Ie(n).schematic_component.get(s);if(!a||!a.source_component_id)continue;let c=Ie(n).source_component.get(a.source_component_id);if(!c)continue;let l=i.schematic_placements?.findIndex(p=>p.selector===c.name),u={selector:c.name,center:o,relative_to:"group_center"};l>=0?i.schematic_placements[l]=u:i.schematic_placements.push(u)}return i},IFt=({circuitJson:n,editEvents:e,manualEditsFile:t})=>{let i=e.filter(o=>o.edit_event_type==="edit_schematic_component_location"),r=e.filter(o=>o.edit_event_type==="edit_pcb_component_location"),s=t;return i.length>0&&(s=yit({circuitJson:n,editEvents:i,manualEditsFile:s})),r.length>0&&(s=_it({circuitJson:n,editEvents:r,manualEditsFile:s})),s},NFt=(n,e)=>{if(Ie(n).pcb_trace_hint.get(e.pcb_trace_hint_id))n=n.map(i=>i.pcb_trace_hint_id===e.pcb_trace_hint_id?{...i,route:e.route}:i);else{let i=Ie(n).pcb_port.get(e.pcb_port_id);n=n.filter(r=>!(r.type==="pcb_trace_hint"&&r.pcb_port_id===e.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:e.pcb_trace_hint_id,route:e.route,pcb_port_id:e.pcb_port_id,pcb_component_id:i?.pcb_component_id}])}return n},AFt=({circuitJson:n,editEvents:e})=>{n=JSON.parse(JSON.stringify(n));for(let t of e)if(t.edit_event_type==="edit_pcb_component_location"){let i=n.find(s=>s.type==="pcb_component"&&s.pcb_component_id===t.pcb_component_id);if((!i||i.center.x!==t.new_center.x||i.center.y!==t.new_center.y)&&t.original_center){let s=Tn(t.new_center.x-t.original_center.x,t.new_center.y-t.original_center.y);n=n.map(o=>o.pcb_component_id!==t.pcb_component_id?o:Y4(o,s))}}else t.edit_event_type==="edit_schematic_component_location"?n=n.map(i=>i.type==="schematic_component"&&i.schematic_component_id===t.schematic_component_id?{...i,center:t.new_center}:i):t.edit_event_type==="edit_pcb_trace_hint"&&(n=NFt(n,t));return n},git=(n,e)=>{let t=n.source_group.list(),i=[],r=s=>{let o=t.filter(a=>a.parent_subcircuit_id===s);for(let a of o)a.subcircuit_id&&(i.push(a.subcircuit_id),r(a.subcircuit_id))};return r(e),i},D9=({db:n,circuitJson:e,subcircuit_id:t,minTraceWidth:i=.1})=>{if(!n&&e&&(n=Ie(e)),!n)throw new Error("db or circuitJson is required");let r=n.pcb_trace_hint.list(),s=t?new Set([t]):null;if(t){let A=git(n,t);for(let j of A)s.add(j)}let o=(e??n.toArray()).filter(A=>!t||"subcircuit_id"in A&&s.has(A.subcircuit_id)),a=n.pcb_board.list()[0];n=Ie(o);let c=rr(o),l=dit([...n.pcb_component.list(),...n.pcb_smtpad.list(),...n.pcb_plated_hole.list(),...n.pcb_hole.list(),...n.pcb_via.list(),...n.pcb_cutout.list()].filter(A=>!t||s?.has(A.subcircuit_id)),c);for(let A of l){let j=A.connectedTo.flatMap(D=>c.getIdsConnectedToNet(D));A.connectedTo.push(...j)}let u=n.source_component_internal_connection.list(),p=new Map;for(let A of u)for(let j of A.source_port_ids)p.set(j,A.source_component_internal_connection_id);let d=new Map;for(let A of n.pcb_port.list())if(A.source_port_id){let j=n.pcb_smtpad.getWhere({pcb_port_id:A.pcb_port_id});j&&d.set(j.pcb_smtpad_id,A.source_port_id);let D=n.pcb_plated_hole.getWhere({pcb_port_id:A.pcb_port_id});D&&d.set(D.pcb_plated_hole_id,A.source_port_id)}for(let A of l)for(let j of A.connectedTo){let D=d.get(j);if(D){let Y=p.get(D);if(Y){A.offBoardConnectsTo=[Y],A.netIsAssignable=!0;break}}}let _=l.flatMap(A=>[{x:A.center.x-A.width/2,y:A.center.y-A.height/2},{x:A.center.x+A.width/2,y:A.center.y+A.height/2}]).concat(a?.outline??[]),g;if(a&&!a.outline?g={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}:g={minX:Math.min(..._.map(A=>A.x))-1,maxX:Math.max(..._.map(A=>A.x))+1,minY:Math.min(..._.map(A=>A.y))-1,maxY:Math.max(..._.map(A=>A.y))+1},t){let A=n.pcb_group.getWhere({subcircuit_id:t});if(A?.width&&A.height){let j={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};g={minX:Math.min(g.minX,j.minX),maxX:Math.max(g.maxX,j.maxX),minY:Math.min(g.minY,j.minY),maxY:Math.max(g.maxY,j.maxY)}}}let x=new Set(n.pcb_trace.list().map(A=>A.source_trace_id).filter(A=>!!A)),b=n.source_trace.list().filter(A=>!x.has(A.source_trace_id)).map(A=>{let j=A.connected_source_port_ids.map(dt=>{let G=n.source_port.get(dt),nt=n.pcb_port.getWhere({source_port_id:dt});return{...G,...nt}});if(j.length<2)return null;let[D,Y]=j;if(D.x===void 0||D.y===void 0)return console.error(`(source_port_id: ${D.source_port_id}) for trace ${A.source_trace_id} does not have x/y coordinates. Skipping this trace.`),null;if(Y.x===void 0||Y.y===void 0)return console.error(`(source_port_id: ${Y.source_port_id}) for trace ${A.source_trace_id} does not have x/y coordinates. Skipping this trace.`),null;let X=D.layers?.[0]??"top",W=Y.layers?.[0]??"top",et=r.filter(dt=>dt.pcb_port_id===D.pcb_port_id||dt.pcb_port_id===Y.pcb_port_id),H=[];for(let dt of et){let nt=n.pcb_port.get(dt.pcb_port_id)?.layers?.[0]??"top";for(let J of dt.route)H.push({x:J.x,y:J.y,layer:nt})}return{name:A.source_trace_id??c.getNetConnectedToId(A.source_trace_id)??"",source_trace_id:A.source_trace_id,width:A.min_trace_thickness,pointsToConnect:[{x:D.x,y:D.y,layer:X,pointId:D.pcb_port_id,pcb_port_id:D.pcb_port_id},...H,{x:Y.x,y:Y.y,layer:W,pointId:Y.pcb_port_id,pcb_port_id:Y.pcb_port_id}]}}).filter(A=>A!==null),S=new Map(b.map(A=>[A.source_trace_id,A])),P=n.source_net.list().filter(A=>!t||s?.has(A.subcircuit_id)),T=[];for(let A of P){let j=n.source_trace.list().filter(D=>D.connected_source_net_ids?.includes(A.source_net_id));T.push({name:A.source_net_id??c.getNetConnectedToId(A.source_net_id),pointsToConnect:j.flatMap(D=>n.pcb_port.list().filter(X=>D.connected_source_port_ids.includes(X.source_port_id)).map(X=>({x:X.x,y:X.y,layer:X.layers?.[0]??"top",pointId:X.pcb_port_id,pcb_port_id:X.pcb_port_id})))})}let k=n.pcb_breakout_point.list().filter(A=>!t||s?.has(A.subcircuit_id)),N=[],M=new Map;for(let A of k){let j={x:A.x,y:A.y,layer:"top"};if(A.source_trace_id){let D=S.get(A.source_trace_id)??M.get(A.source_trace_id);if(D)D.pointsToConnect.push(j);else{let Y={name:A.source_trace_id,source_trace_id:A.source_trace_id,pointsToConnect:[j]};N.push(Y),M.set(A.source_trace_id,Y)}}else if(A.source_net_id){let D=T.find(Y=>Y.name===A.source_net_id);D?D.pointsToConnect.push(j):N.push({name:A.source_net_id,pointsToConnect:[j]})}else if(A.source_port_id){let D=n.pcb_port.getWhere({source_port_id:A.source_port_id});D&&N.push({name:A.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:D.x,y:D.y,layer:D.layers?.[0]??"top",pointId:D.pcb_port_id,pcb_port_id:D.pcb_port_id},j]})}}let C=[...b,...T,...N],E=new Map;for(let A of C)for(let j of A.pointsToConnect)j.pointId&&E.set(j.pointId,A);let R=n.pcb_trace.list().filter(A=>!t||s?.has(A.subcircuit_id));for(let A of R){let j=new Set;for(let X of A.route)X.start_pcb_port_id&&j.add(X.start_pcb_port_id),X.end_pcb_port_id&&j.add(X.end_pcb_port_id);if(j.size<2)continue;let D=j.values().next().value;if(!D)continue;let Y=E.get(D);Y&&[...j].every(X=>E.get(X)===Y)&&(Y.externallyConnectedPointIds??(Y.externallyConnectedPointIds=[]),Y.externallyConnectedPointIds.push([...j]))}return{simpleRouteJson:{bounds:g,obstacles:l,connections:C,layerCount:a?.num_layers??2,minTraceWidth:i,outline:a?.outline?.map(A=>({...A}))},connMap:c}},RFt=n=>{let e={};if(!n)return e;for(let i of Wa)e[i]=0;let t=new Map;for(let i of n){let[,,r,s]=i.type.split(":");if(s==="start"){t.set(`${r}:${i.renderId}`,i);continue}if(s==="end"){let o=t.get(`${r}:${i.renderId}`);if(o){let a=i.createdAt-o.createdAt;e[r]=(e[r]||0)+a}}}return e},OFt=n=>{let e=n.map(c=>[...new Set(c)]),t=e.map(()=>[]),i=e.map(()=>null);for(let c=0;c<e.length;c++)for(let l of e[c])if(/^\d+$/.test(l)){i[c]=Number.parseInt(l);break}let r=0,s=new Set;for(let c=0;c<i.length;c++){let l=i[c];if(l===null||l<1)continue;if(!s.has(l)){s.add(l),t[c].push(`pin${l}`),r=Math.max(r,l);continue}let u=0;for(let p of t[c])p.startsWith(`pin${l}_alt`)&&u++;t[c].push(`pin${l}_alt${u+1}`)}for(let c=0;c<t.length;c++)t[c][0]?.includes("_alt")&&(r++,t[c].unshift(`pin${r}`));for(let c=0;c<t.length;c++)t[c].length===0&&(r++,t[c].push(`pin${r}`));let o={};for(let c of e)for(let l of c)/^\d+$/.test(l)||(o[l]=(o[l]??0)+1);let a={};for(let c=0;c<e.length;c++){let l=e[c];for(let u of l)/^\d+$/.test(u)||(o[u]===1?t[c].push(u):(a[u]=(a[u]??0)+1,t[c].push(`${u}${a[u]}`)))}return t};function q9({db:n,schematicComponentId:e,deltaX:t,deltaY:i}){let r=n.schematic_rect.list({schematic_component_id:e});for(let c of r)c.center.x+=t,c.center.y+=i;let s=n.schematic_line.list({schematic_component_id:e});for(let c of s)c.x1+=t,c.y1+=i,c.x2+=t,c.y2+=i;let o=n.schematic_circle.list({schematic_component_id:e});for(let c of o)c.center.x+=t,c.center.y+=i;let a=n.schematic_arc.list({schematic_component_id:e});for(let c of a)c.center.x+=t,c.center.y+=i}var Rnt=(0,xit.default)("Group_doInitialSchematicLayoutMatchAdapt");function LFt(n){let{db:e}=n.root,t=Xg(e.toArray(),{source_group_id:n.source_group_id}),i=kN(t);Rnt.enabled&&global?.debugGraphics&&global.debugGraphics?.push(hl(i,{title:`floatingBpcGraph-${n.name}`}));let r=kN(t),s={boxes:r.boxes,pins:r.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:o}=nQ([{variantName:"default",floatingGraph:r},{variantName:"noNotConnected",floatingGraph:s}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(r.boxes.filter(c=>r.pins.filter(p=>p.boxId===c.boxId).filter(p=>!p.color.includes("center")).length<=2).map(c=>c.boxId)),corpus:{}});Rnt.enabled&&global?.debugGraphics&&global.debugGraphics?.push(hl(o,{title:`laidOutBpcGraph-${n.name}`}));let a=n._getGlobalSchematicPositionBeforeLayout();for(let c of o.boxes){if(!c.center)continue;let l=e.schematic_component.get(c.boxId);if(l){let p={x:c.center.x+a.x,y:c.center.y+a.y},d=e.schematic_port.list({schematic_component_id:l.schematic_component_id}),_=e.schematic_text.list({schematic_component_id:l.schematic_component_id}),g={x:p.x-l.center.x,y:p.y-l.center.y};for(let x of d)x.center.x+=g.x,x.center.y+=g.y;for(let x of _)x.position.x+=g.x,x.position.y+=g.y;q9({db:e,schematicComponentId:l.schematic_component_id,deltaX:g.x,deltaY:g.y}),l.center=p;continue}let u=e.schematic_net_label.get(c.boxId);if(u){let p=o.pins.find(_=>_.boxId===c.boxId&&_.color==="netlabel_center");if(!p)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+p.offset.x,y:d.y+p.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 ve=(0,bit.default)("Group_doInitialSchematicLayoutMatchpack");function Ont(n){switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function Lnt(n,e){let t=["right","up","left","down"],i=t.indexOf(n);if(i===-1)return n;let r=Math.round(e/90),s=(i+r)%4;return t[s<0?s+4:s]}function FFt(n,e,t){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};ve(`[${t.name}] Processing ${n.childNodes.length} child nodes for input problem`),n.childNodes.forEach((s,o)=>{if(ve(`[${t.name}] Processing child ${o}: nodeType=${s.nodeType}`),s.nodeType==="component"?ve(`[${t.name}] - Component: ${s.sourceComponent?.name}`):s.nodeType==="group"&&ve(`[${t.name}] - Group: ${s.sourceGroup?.name}`),s.nodeType==="component"&&s.sourceComponent){let a=s.sourceComponent.name||`chip_${o}`,c=e.schematic_component.getWhere({source_component_id:s.sourceComponent.source_component_id});if(!c)return;let l=t.children.find(P=>P.source_component_id===s.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 p=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,d=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,_=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,g=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0;l?.config.shouldRenderAsSchematicBox&&(_+=.4,g+=.4);let x=(d-p)/2,b=(_-g)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+p+d,y:(c.size?.height||1)+_+g},availableRotations:u};let S=e.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let P of S){let T=e.source_port.get(P.source_port_id);if(!T)continue;let k=`${a}.${T.pin_number||T.name||P.schematic_port_id}`;i.chipMap[a].pins.push(k);let N=Ont(P.facing_direction);i.chipPinMap[k]={pinId:k,offset:{x:(P.center?.x||0)-(c.center.x||0)+x,y:(P.center?.y||0)-(c.center.y||0)+b},side:N}}}else if(s.nodeType==="group"&&s.sourceGroup){let a=s.sourceGroup.name||`group_${o}`;ve(`[${t.name}] Processing nested group: ${a}`);let c=e.schematic_group?.getWhere?.({source_group_id:s.sourceGroup.source_group_id}),l=t.children.find(u=>u.source_group_id===s.sourceGroup?.source_group_id);if(ve(`[${t.name}] Found schematic_group for ${a}:`,c),c){ve(`[${t.name}] Treating group ${a} as composite chip`);let u=e.schematic_component.list({schematic_group_id:c.schematic_group_id});ve(`[${t.name}] Group ${a} has ${u.length} components:`,u.map(R=>R.source_component_id));let p=1/0,d=-1/0,_=1/0,g=-1/0,x=!1;for(let R of u)if(R.center&&R.size){x=!0;let A=R.size.width/2,j=R.size.height/2;p=Math.min(p,R.center.x-A),d=Math.max(d,R.center.x+A),_=Math.min(_,R.center.y-j),g=Math.max(g,R.center.y+j)}let b=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,S=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,P=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,T=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,k=(S-b)/2,N=(P-T)/2,M=(x?d-p:2)+b+S,C=(x?g-_:2)+P+T;ve(`[${t.name}] Group ${a} computed size: ${M} x ${C}`);let E=[];for(let R of u){let A=e.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let j of A){let D=e.source_port.get(j.source_port_id);if(!D)continue;let Y=`${a}.${D.pin_number||D.name||j.schematic_port_id}`;E.push(Y);let X=c.center||{x:0,y:0},W=Ont(j.facing_direction);i.chipPinMap[Y]={pinId:Y,offset:{x:(j.center?.x||0)-X.x+k,y:(j.center?.y||0)-X.y+N},side:W}}}ve(`[${t.name}] Group ${a} has ${E.length} pins:`,E),i.chipMap[a]={chipId:a,pins:E,size:{x:M,y:C}},ve(`[${t.name}] Added group ${a} to chipMap`)}else ve(`[${t.name}] Warning: No schematic_group found for group ${a}`)}}),ve(`[${t.name}] Creating connections using connectivity keys`);let r=new Map;for(let[s,o]of Object.entries(i.chipMap))for(let a of o.pins){let c=a.split(".").pop(),l=n.childNodes.find(u=>u.nodeType==="component"&&u.sourceComponent?u.sourceComponent.name===s:u.nodeType==="group"&&u.sourceGroup?`group_${n.childNodes.indexOf(u)}`===s:!1);if(l?.nodeType==="group"&&l.sourceGroup){let u=e.schematic_group?.getWhere?.({source_group_id:l.sourceGroup.source_group_id});if(u){let p=e.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let d of p){let _=e.source_port.list({source_component_id:d.source_component_id});for(let g of _){let x=g.pin_number||g.name;if(String(x)===String(c))if(g.subcircuit_connectivity_map_key){let b=g.subcircuit_connectivity_map_key;r.has(b)||r.set(b,[]),r.get(b).push(a),ve(`[${t.name}] \u2713 Pin ${a} has connectivity key: ${b}`)}else ve(`[${t.name}] Pin ${a} has no connectivity key`)}}}}else if(l?.nodeType==="component"&&l.sourceComponent){let u=e.source_port.list({source_component_id:l.sourceComponent.source_component_id});for(let p of u){let d=p.pin_number||p.name;if(String(d)===String(c)&&p.subcircuit_connectivity_map_key){let _=p.subcircuit_connectivity_map_key;r.has(_)||r.set(_,[]),r.get(_).push(a),ve(`[${t.name}] Pin ${a} has connectivity key: ${_}`)}}}}ve(`[${t.name}] Found ${r.size} connectivity groups:`,Array.from(r.entries()).map(([s,o])=>({key:s,pins:o})));for(let[s,o]of r)if(o.length>=2){let a=e.source_trace.list().filter(u=>u.subcircuit_connectivity_map_key===s),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(ve(`[${t.name}] Connectivity ${s}: hasNetConnections=${c}, hasDirectConnections=${l}`),l){for(let u of a)if(u.connected_source_port_ids&&u.connected_source_port_ids.length>=2){let p=[];for(let d of u.connected_source_port_ids)for(let _ of o){let g=_.split(".").pop(),x=e.source_port.get(d);if(x&&String(x.pin_number||x.name)===String(g)){let b=_.split(".")[0],S=n.childNodes.find(P=>P.nodeType==="component"&&P.sourceComponent?P.sourceComponent.name===b:P.nodeType==="group"&&P.sourceGroup?`group_${n.childNodes.indexOf(P)}`===b:!1);S?.nodeType==="component"&&S.sourceComponent&&e.source_port.list({source_component_id:S.sourceComponent.source_component_id}).some(T=>T.source_port_id===d)&&p.push(_)}}for(let d=0;d<p.length;d++)for(let _=d+1;_<p.length;_++){let g=p[d],x=p[_];i.pinStrongConnMap[`${g}-${x}`]=!0,i.pinStrongConnMap[`${x}-${g}`]=!0,ve(`[${t.name}] Created strong connection: ${g} <-> ${x}`)}}}if(c){let u=e.source_net.getWhere({subcircuit_connectivity_map_key:s}),p=u?.is_ground??!1,d=u?.is_power??!1;i.netMap[s]={netId:s,isGround:p,isPositiveVoltageSource:d};for(let _ of o)i.netConnMap[`${_}-${s}`]=!0;ve(`[${t.name}] Created net ${s} with ${o.length} pins:`,o)}}return i}function zFt(n){let{db:e}=n.root,t=d_(e.toArray(),{source_group_id:n.source_group_id});if(ve(`[${n.name}] Starting matchpack layout with ${t.childNodes.length} children`),ve(`[${n.name}] Tree structure:`,JSON.stringify(t,null,2)),t.childNodes.length<=1){ve(`[${n.name}] Only ${t.childNodes.length} children, skipping layout`);return}ve("Converting circuit tree to InputProblem...");let i=FFt(t,e,n);ve.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${n.name}`,content:JSON.stringify(i,null,2)});let r=new utt(i);if(ve("Starting LayoutPipelineSolver..."),ve.enabled&&global?.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${n.name}`})}if(r.solve(),ve(`Solver completed in ${r.iterations} iterations`),ve(`Solved: ${r.solved}, Failed: ${r.failed}`),r.failed)throw ve(`Solver failed with error: ${r.error}`),new Error(`Matchpack layout solver failed: ${r.error}`);let s=r.getOutputLayout();if(ve("OutputLayout:",JSON.stringify(s,null,2)),ve("Solver completed successfully:",!r.failed),ve.enabled&&global?.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-final-${n.name}`})}let o=r.checkForOverlaps(s);if(o.length>0){ve(`Warning: Found ${o.length} overlapping components:`);for(let c of o)ve(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=n._getGlobalSchematicPositionBeforeLayout();ve(`Group offset: x=${a.x}, y=${a.y}`),ve(`Applying layout results for ${Object.keys(s.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(s.chipPlacements)){ve(`Processing placement for chip: ${c} at (${l.x}, ${l.y})`);let u=t.childNodes.find(d=>{if(d.nodeType==="component"&&d.sourceComponent){let _=d.sourceComponent.name===c;return ve(` Checking component ${d.sourceComponent.name}: matches=${_}`),_}if(d.nodeType==="group"&&d.sourceGroup){let _=d.sourceGroup.name,g=`group_${t.childNodes.indexOf(d)}`,x=g===c;return ve(` Checking group ${_} (expected chipId: ${g}): matches=${x}`),x}return!1});if(!u){ve(`Warning: No tree node found for chip: ${c}`),ve("Available tree nodes:",t.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 p={x:l.x+a.x,y:l.y+a.y};if(u.nodeType==="component"&&u.sourceComponent){let d=e.schematic_component.getWhere({source_component_id:u.sourceComponent.source_component_id});if(d){ve(`Moving component ${c} to (${p.x}, ${p.y})`);let _=e.schematic_port.list({schematic_component_id:d.schematic_component_id}),g=e.schematic_text.list({schematic_component_id:d.schematic_component_id}),x={x:p.x-d.center.x,y:p.y-d.center.y};for(let b of _)b.center.x+=x.x,b.center.y+=x.y;for(let b of g)b.position.x+=x.x,b.position.y+=x.y;if(q9({db:e,schematicComponentId:d.schematic_component_id,deltaX:x.x,deltaY:x.y}),d.center=p,l.ccwRotationDegrees!==0){ve(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let b=l.ccwRotationDegrees*Math.PI/180,S=Math.cos(b),P=Math.sin(b);for(let T of _){let k=T.center.x-p.x,N=T.center.y-p.y,M=k*S-N*P,C=k*P+N*S;T.center.x=p.x+M,T.center.y=p.y+C;let E=T.facing_direction||"right";T.facing_direction=Lnt(E,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 g){let k=T.position.x-p.x,N=T.position.y-p.y,M=k*S-N*P,C=k*P+N*S;T.position.x=p.x+M,T.position.y=p.y+C}if(d.symbol_name){let T=d.symbol_name.match(/_(right|left|up|down)$/);T&&(d.symbol_name=d.symbol_name.replace(T[0],`_${Lnt(T[1],l.ccwRotationDegrees)}`))}}}}else if(u.nodeType==="group"&&u.sourceGroup){let d=e.schematic_group?.getWhere?.({source_group_id:u.sourceGroup.source_group_id});if(d){ve(`Moving group ${c} to (${p.x}, ${p.y}) from (${d.center?.x}, ${d.center?.y})`);let _=e.schematic_component.list({schematic_group_id:d.schematic_group_id});ve(`Group ${c} has ${_.length} components to move`);let g=d.center||{x:0,y:0},x={x:p.x-g.x,y:p.y-g.y};ve(`Position delta for group ${c}: (${x.x}, ${x.y})`);for(let b of _)if(b.center){let S={...b.center};b.center.x+=x.x,b.center.y+=x.y,ve(`Moved component ${b.source_component_id} from (${S.x}, ${S.y}) to (${b.center.x}, ${b.center.y})`);let P=e.schematic_port.list({schematic_component_id:b.schematic_component_id}),T=e.schematic_text.list({schematic_component_id:b.schematic_component_id});for(let k of P)k.center&&(k.center.x+=x.x,k.center.y+=x.y);for(let k of T)k.position&&(k.position.x+=x.x,k.position.y+=x.y)}d.center=p,ve(`Updated group ${c} center to (${p.x}, ${p.y})`)}}}ve("Matchpack layout completed successfully")}function $Ft(n){if(!n.isSubcircuit)return;let{db:e}=n.root,t=n.selectAll("trace"),i=n.selectAll("via"),r=n.selectAll("net"),s=new Og({});s.addConnections(t.map(u=>{let p=e.source_trace.get(u.source_trace_id);return p?[p.source_trace_id,...p.connected_source_port_ids,...p.connected_source_net_ids]:null}).filter(u=>u!==null));let o=e.source_net.list().filter(u=>u.subcircuit_id===n.subcircuit_id);for(let u of o)s.addConnections([[u.source_net_id]]);let{name:a}=n._parsedProps;for(let u of t){if(!u.source_trace_id)continue;let p=s.getNetConnectedToId(u.source_trace_id);p&&(u.subcircuit_connectivity_map_key=`${a??`unnamedsubcircuit${n._renderId}`}_${p}`,e.source_trace.update(u.source_trace_id,{subcircuit_connectivity_map_key:u.subcircuit_connectivity_map_key}))}let c=new Set;for(let u of t){if(!u.source_trace_id)continue;let p=e.source_trace.get(u.source_trace_id);if(p)for(let d of p.connected_source_port_ids)c.add(d)}for(let u of c){let p=s.getNetConnectedToId(u);if(!p)continue;let d=`${a??`unnamedsubcircuit${n._renderId}`}_${p}`;e.source_port.update(u,{subcircuit_connectivity_map_key:d})}let l=new Set;for(let u of t){if(!u.source_trace_id)continue;let p=e.source_trace.get(u.source_trace_id);if(p)for(let d of p.connected_source_net_ids)l.add(d)}for(let u of o)l.add(u.source_net_id);for(let u of l){let p=s.getNetConnectedToId(u);if(!p)continue;let d=`${a??`unnamedsubcircuit${n._renderId}`}_${p}`;e.source_net.update(u,{subcircuit_connectivity_map_key:d});let _=r.find(g=>g.source_net_id===u);_&&(_.subcircuit_connectivity_map_key=d)}for(let u of i){let p=u._getConnectedNetOrTrace();p&&p.subcircuit_connectivity_map_key&&(u.subcircuit_connectivity_map_key=p.subcircuit_connectivity_map_key)}}function DFt(n){let{db:e}=n.root,t=n._parsedProps,i=n.children.filter(N=>{let M=N._parsedProps?.schX!==void 0||N._parsedProps?.schY!==void 0;return N.schematic_component_id&&!M});if(i.length===0)return;let r=0,s=0;for(let N of i){let M=e.schematic_component.get(N.schematic_component_id);M?.size&&(r=Math.max(r,M.size.width),s=Math.max(s,M.size.height))}r===0&&i.length>0&&(r=1),s===0&&i.length>0&&(s=1);let o=t.gridCols,a,c=t.gridGap,l=t.gridRowGap,u=t.gridColumnGap;t.schLayout?.grid&&(o=t.schLayout.grid.cols??o,a=t.schLayout.grid.rows,c=t.schLayout.gridGap??c,l=t.schLayout.gridRowGap??l,u=t.schLayout.gridColumnGap??u);let p,d;o!==void 0&&a!==void 0?(p=o,d=a):o!==void 0?(p=o,d=Math.ceil(i.length/p)):a!==void 0?(d=a,p=Math.ceil(i.length/d)):(p=Math.ceil(Math.sqrt(i.length)),d=Math.ceil(i.length/p)),p===0&&i.length>0&&(p=1),d===0&&i.length>0&&(d=i.length);let _,g,x=N=>{if(N!==void 0)return typeof N=="number"?N:B.parse(N)};if(l!==void 0||u!==void 0){let N=typeof c=="object"&&c!==null?c.x:c,M=typeof c=="object"&&c!==null?c.y:c;_=x(u??N)??1,g=x(l??M)??1}else if(typeof c=="number")_=c,g=c;else if(typeof c=="string"){let N=B.parse(c);_=N,g=N}else if(typeof c=="object"&&c!==null){let N=c.x,M=c.y;_=typeof N=="number"?N:B.parse(N??"0mm"),g=typeof M=="number"?M:B.parse(M??"0mm")}else _=1,g=1;let b=p*r+Math.max(0,p-1)*_,S=d*s+Math.max(0,d-1)*g,P=n._getGlobalSchematicPositionBeforeLayout(),T=P.x-b/2+r/2,k=P.y+S/2-s/2;for(let N=0;N<i.length;N++){let M=i[N];if(!M.schematic_component_id)continue;let C=Math.floor(N/p),E=N%p;if(C>=d||E>=p){console.warn(`Schematic grid layout: Child ${M.getString()} at index ${N} (row ${C}, col ${E}) exceeds specified grid dimensions (${d}x${p}). Skipping placement.`);continue}let R=T+E*(r+_),A=k-C*(s+g),j=e.schematic_component.get(M.schematic_component_id);if(j){let D=j.center,Y={x:R,y:A};e.schematic_component.update(M.schematic_component_id,{center:Y});let X=Y.x-D.x,W=Y.y-D.y,et=e.schematic_port.list({schematic_component_id:M.schematic_component_id});for(let dt of et)e.schematic_port.update(dt.schematic_port_id,{center:{x:dt.center.x+X,y:dt.center.y+W}});let H=e.schematic_text.list({schematic_component_id:M.schematic_component_id});for(let dt of H)e.schematic_text.update(dt.schematic_text_id,{position:{x:dt.position.x+X,y:dt.position.y+W}});q9({db:e,schematicComponentId:M.schematic_component_id,deltaX:X,deltaY:W})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:b,height:S,center:P})}var Fnt=(n,e)=>{let{sourceComponent:t,sourceGroup:i}=e;if(e.nodeType==="component"){let r=n.schematic_component.getWhere({source_component_id:t?.source_component_id});return r?.size?{width:r.size.width,height:r.size.height}:null}if(e.nodeType==="group"){let r=n.schematic_group.getWhere({source_group_id:i?.source_group_id});if(r?.width&&r?.height)return{width:r.width,height:r.height};let s=n.schematic_component.list({schematic_group_id:r?.schematic_group_id}),o=1/0,a=-1/0,c=1/0,l=-1/0;for(let d of s)if(d.center&&d.size){let _=d.size.width/2,g=d.size.height/2;o=Math.min(o,d.center.x-_),a=Math.max(a,d.center.x+_),c=Math.min(c,d.center.y-g),l=Math.max(l,d.center.y+g)}let u=a-o,p=l-c;return{width:u,height:p}}return null},jFt=n=>{let{db:e}=n.root,t=n._parsedProps,i=d_(e.toArray(),{source_group_id:n.source_group_id}),r=t.schJustifyContent??t.justifyContent,s=t.schAlignItems??t.alignItems,o=t.schFlexGap??t.schGap??t.gap,a=t.schFlexDirection??"row",c={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[r??"space-between"],l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[s??"center"];if(!c)throw new Error(`Invalid justifyContent value: "${r}"`);if(!l)throw new Error(`Invalid alignItems value: "${s}"`);let u=0,p=0;typeof o=="object"?(u=o.y??0,p=o.x??0):typeof o=="number"?(u=o,p=o):typeof o=="string"&&(u=B.parse(o),p=B.parse(o));let d,_=t.width??t.schWidth??void 0,g=t.height??t.schHeight??void 0;(_===void 0||g===void 0)&&(d=US(i.childNodes.map(k=>Fnt(e,k)).filter(k=>k!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:p}),_=d.width,g=d.height);let b=new Hw(_,g,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:p});for(let k of i.childNodes){let N=Fnt(e,k);b.addChild({metadata:k,width:N?.width??0,height:N?.height??0,flexBasis:N?a==="row"?N.width:N.height:void 0})}b.build();let S={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let k of b.children)S.minX=Math.min(S.minX,k.position.x),S.minY=Math.min(S.minY,k.position.y),S.maxX=Math.max(S.maxX,k.position.x+k.size.width),S.maxY=Math.max(S.maxY,k.position.y+k.size.height);S.width=S.maxX-S.minX,S.height=S.maxY-S.minY;let P={x:-(S.maxX+S.minX)/2,y:-(S.maxY+S.minY)/2},T=e.toArray();for(let k of b.children){let{sourceComponent:N,sourceGroup:M}=k.metadata;if(N){let C=e.schematic_component.getWhere({source_component_id:N.source_component_id});if(!C)continue;Kq(T,C.schematic_component_id,{x:k.position.x+k.size.width/2+P.x,y:k.position.y+k.size.height/2+P.y})}if(M){if(!e.schematic_group.getWhere({source_group_id:M.source_group_id}))continue;Qq(T,M.source_group_id,{x:k.position.x+k.size.width/2+P.x,y:k.position.y+k.size.height/2+P.y})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:S.width,height:S.height})},M9=1;function BFt(n){let{db:e}=n.root,t=n._parsedProps,i=YFt(n);if(i.length===0)return;let r=XFt({db:e,pcbChildren:i}),s=UFt(t),o=VFt({props:t,pcbChildren:i,childDimensions:r,gridConfig:s}),a=HFt({pcbChildren:i,childDimensions:r,gridLayout:o,gridConfig:s}),{itemCoordinates:c}=a.layout();qFt({db:e,group:n,pcbChildren:i,itemCoordinates:c,gridLayout:o}),ZFt({db:e,group:n,props:t,gridLayout:o})}function YFt(n){return n.children.filter(e=>e.pcb_component_id||e.pcb_group_id)}function XFt(n){let{db:e,pcbChildren:t}=n,i=0,r=0;for(let s of t){let o=0,a=0;if(s.pcb_group_id){let c=e.pcb_group.get(s.pcb_group_id);o=c?.width??0,a=c?.height??0}else if(s.pcb_component_id){let c=e.pcb_component.get(s.pcb_component_id);o=c?.width??0,a=c?.height??0}i=Math.max(i,o),r=Math.max(r,a)}return{width:i,height:r}}function UFt(n){let e=n.pcbGridCols??n.gridCols??n.pcbLayout?.grid?.cols,t=n.pcbGridRows??n.pcbLayout?.grid?.rows,i=n.pcbGridTemplateColumns,r=n.pcbGridTemplateRows,s=p=>p===void 0?M9:typeof p=="number"?p:B.parse(p),o=n.pcbGridGap??n.gridGap??n.pcbLayout?.gridGap,a=n.pcbGridRowGap??n.gridRowGap??n.pcbLayout?.gridRowGap,c=n.pcbGridColumnGap??n.gridColumnGap??n.pcbLayout?.gridColumnGap,l=M9,u=M9;if(a!==void 0||c!==void 0){let p=typeof o=="object"?o?.x:o,d=typeof o=="object"?o?.y:o;l=s(c??p),u=s(a??d)}else if(typeof o=="object"&&o!==null)l=s(o.x),u=s(o.y);else{let p=s(o);l=p,u=p}return{cols:e,rows:t,gapX:l,gapY:u,templateColumns:i,templateRows:r}}function VFt(n){let{props:e,pcbChildren:t,childDimensions:i,gridConfig:r}=n;return e.pcbGridTemplateColumns||e.pcbGridTemplateRows?GFt({props:e,gridConfig:r,pcbChildren:t,childDimensions:i}):WFt({gridConfig:r,pcbChildren:t,childDimensions:i})}function GFt(n){let{props:e,gridConfig:t,pcbChildren:i,childDimensions:r}=n,s=e.pcbGridTemplateColumns??"",o=e.pcbGridTemplateRows??"",a=d=>{let _=d.match(/repeat\((\d+),/);return _?parseInt(_[1]):Math.ceil(Math.sqrt(i.length))},c=e.pcbGridTemplateColumns?a(s):Math.ceil(Math.sqrt(i.length)),l=e.pcbGridTemplateRows?a(o):Math.ceil(i.length/c),u=c*r.width+Math.max(0,c-1)*t.gapX,p=l*r.height+Math.max(0,l-1)*t.gapY;return{gridTemplateColumns:s,gridTemplateRows:o,containerWidth:u,containerHeight:p}}function WFt(n){let{gridConfig:e,pcbChildren:t,childDimensions:i}=n,r,s;e.cols!==void 0&&e.rows!==void 0?(r=e.cols,s=e.rows):e.cols!==void 0?(r=e.cols,s=Math.ceil(t.length/r)):e.rows!==void 0?(s=e.rows,r=Math.ceil(t.length/s)):(r=Math.ceil(Math.sqrt(t.length)),s=Math.ceil(t.length/r)),r=Math.max(1,r),s=Math.max(1,s);let o=r*i.width+Math.max(0,r-1)*e.gapX,a=s*i.height+Math.max(0,s-1)*e.gapY,c=`repeat(${r}, ${i.width}px)`,l=`repeat(${s}, ${i.height}px)`;return{gridTemplateColumns:c,gridTemplateRows:l,containerWidth:o,containerHeight:a}}function HFt(n){let{pcbChildren:e,childDimensions:t,gridLayout:i,gridConfig:r}=n,s=e.map((o,a)=>({key:o.getString()||`child-${a}`,contentWidth:t.width,contentHeight:t.height}));return new xtt({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[r.gapY,r.gapX],children:s})}function qFt(n){let{db:e,group:t,pcbChildren:i,itemCoordinates:r,gridLayout:s}=n,o=t._getGlobalPcbPositionBeforeLayout(),a=e.toArray();for(let c=0;c<i.length;c++){let l=i[c],u=l.getString()||`child-${c}`,p=r[u];if(!p){console.warn(`PCB grid layout: No coordinates found for child ${u}`);continue}let d=o.x-s.containerWidth/2+p.x+p.width/2,_=o.y+s.containerHeight/2-p.y-p.height/2;if(l.pcb_component_id)YS(a,l.pcb_component_id,{x:d,y:_});else{let g=l;g.pcb_group_id&&g.source_group_id&&XS(a,g.source_group_id,{x:d,y:_})}}}function ZFt(n){let{db:e,group:t,props:i,gridLayout:r}=n;if(t.pcb_group_id){let s=t._getGlobalPcbPositionBeforeLayout();e.pcb_group.update(t.pcb_group_id,{width:i.width??r.containerWidth,height:i.height??r.containerHeight,center:s})}}function KFt(n){let e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof n=="object"&&!n.preset)return{local:!(n.serverUrl||n.serverMode||n.serverCacheEnabled),...e,...n};let t=typeof n=="object"?n.preset:n,i=typeof n=="object"?n:{};switch(typeof t=="string"?t.replace(/_/g,"-"):t){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:s,local:o,groupMode:a,...c}=i;return{local:!1,groupMode:"subcircuit",...e,...c}}case"laser-prefab":{let{preset:s,local:o,groupMode:a,...c}=i;return{local:!0,groupMode:"subcircuit",preset:"laser_prefab",...c}}default:return{local:!0,groupMode:"subcircuit"}}}var JFt=(n,e)=>{let t=n.children.filter(p=>p.componentName==="Constraint"&&p._parsedProps.pcb),i=new Map,r={},s=p=>(r[p]!==p&&(r[p]=s(r[p])),r[p]),o=(p,d)=>{let _=s(p),g=s(d);_!==g&&(r[g]=_)},a=p=>{p in r||(r[p]=p)},c=p=>{let d=p.startsWith(".")?p.slice(1):p;return n.children.find(g=>g.name===d)?.pcb_component_id??void 0};for(let p of t){let d=p._parsedProps;if("left"in d&&"right"in d){let _=c(d.left),g=c(d.right);_&&g&&(a(_),a(g),o(_,g))}else if("top"in d&&"bottom"in d){let _=c(d.top),g=c(d.bottom);_&&g&&(a(_),a(g),o(_,g))}else if("for"in d&&Array.isArray(d.for)){let _=d.for.map(g=>c(g)).filter(g=>!!g);for(let g of _)a(g);for(let g=1;g<_.length;g++)o(_[0],_[g])}}for(let p of Object.keys(r)){let d=s(p);i.has(d)||i.set(d,{componentIds:[],constraints:[]}),i.get(d).componentIds.push(p)}for(let p of t){let d=p._parsedProps,_;if("left"in d?_=c(d.left):"top"in d?_=c(d.top):"for"in d&&(_=c(d.for[0])),!_)continue;let g=s(_);i.get(g)?.constraints.push(p)}let l={},u=Object.fromEntries(e.components.map(p=>[p.componentId,p]));for(let[p,d]of i.entries()){if(d.componentIds.length<=1)continue;let _=new u_,g={},x=(R,A)=>{let j=`${R}_${A}`;return g[j]||(g[j]=new Oa(j)),g[j]},b=d.componentIds[0];_.addConstraint(new Mi(x(b,"x"),ui.Eq,0,Ln.required)),_.addConstraint(new Mi(x(b,"y"),ui.Eq,0,Ln.required));for(let R of d.constraints){let A=R._parsedProps;if("xDist"in A){let j=c(A.left),D=c(A.right);j&&D&&_.addConstraint(new Mi(new jn(x(D,"x"),[-1,x(j,"x")]),ui.Eq,A.xDist,Ln.required))}else if("yDist"in A){let j=c(A.top),D=c(A.bottom);j&&D&&_.addConstraint(new Mi(new jn(x(j,"y"),[-1,x(D,"y")]),ui.Eq,A.yDist,Ln.required))}else if("sameX"in A&&Array.isArray(A.for)){let j=A.for.map(D=>c(D)).filter(D=>!!D);if(j.length>1){let D=x(j[0],"x");for(let Y=1;Y<j.length;Y++)_.addConstraint(new Mi(new jn(x(j[Y],"x"),[-1,D]),ui.Eq,0,Ln.required))}}else if("sameY"in A&&Array.isArray(A.for)){let j=A.for.map(D=>c(D)).filter(D=>!!D);if(j.length>1){let D=x(j[0],"y");for(let Y=1;Y<j.length;Y++)_.addConstraint(new Mi(new jn(x(j[Y],"y"),[-1,D]),ui.Eq,0,Ln.required))}}}_.updateVariables();let S={};for(let R of d.componentIds)S[R]={x:x(R,"x").value(),y:x(R,"y").value()};let P=1/0,T=1/0,k=-1/0,N=-1/0;for(let R of d.componentIds){let A=u[R],j=S[R];if(A)for(let D of A.pads){let Y=j.x+D.offset.x,X=j.y+D.offset.y;P=Math.min(P,Y-D.size.x/2),k=Math.max(k,Y+D.size.x/2),T=Math.min(T,X-D.size.y/2),N=Math.max(N,X+D.size.y/2)}}let M={x:(P+k)/2,y:(T+N)/2},C=[],E={};for(let R of d.componentIds){let A=u[R],j=S[R];if(A){E[R]={x:j.x-M.x,y:j.y-M.y};for(let D of A.pads)C.push({padId:D.padId,networkId:D.networkId,type:D.type,size:D.size,offset:{x:j.x+D.offset.x-M.x,y:j.y+D.offset.y-M.y}})}}e.components=e.components.filter(R=>!d.componentIds.includes(R.componentId)),e.components.push({componentId:d.componentIds[0],pads:C,availableRotationDegrees:[0]}),d.relativeCenters=E,l[d.componentIds[0]]=d}return l},znt=({db:n,pcbComponentId:e,rotationDegrees:t,layer:i})=>{if(t==null||!n?.cad_component?.list)return;let r=n.cad_component.getWhere({pcb_component_id:e});if(!r)return;let s=i?.toLowerCase?.()==="bottom"?-t:t,o=r.rotation?.z??0,a={...r.rotation??{x:0,y:0,z:0},z:md(o+s)};n.cad_component.update(r.cad_component_id,{rotation:a}),r.rotation=a},Z1=(n,e,t)=>{if(e===t)return!0;let i=n.source_group.get(e);return!i||!i.parent_source_group_id?!1:Z1(n,i.parent_source_group_id,t)},QFt=(n,e,t)=>{let{db:i}=n.root;for(let r of e.components){let{center:s,componentId:o,ccwRotationOffset:a,ccwRotationDegrees:c}=r,l=t[o];if(l){let b=c??a??0,S=b*Math.PI/180;for(let P of l.componentIds){let T=l.relativeCenters[P];if(!T)continue;let k={x:T.x*Math.cos(S)-T.y*Math.sin(S),y:T.x*Math.sin(S)+T.y*Math.cos(S)},N=i.pcb_component.get(P);if(!N)continue;let M=N.center,C=ai(n._computePcbGlobalTransformBeforeLayout(),Tn(s.x+k.x,s.y+k.y),Oo(S),Tn(-M.x,-M.y)),E=i.toArray().filter(R=>"pcb_component_id"in R&&R.pcb_component_id===P);el(E,C),znt({db:i,pcbComponentId:P,rotationDegrees:b,layer:N.layer})}continue}let u=i.pcb_component.get(o);if(u){let b=n.source_group_id,P=i.source_component.get(u.source_component_id)?.source_group_id;if(P!==void 0&&!Z1(i,P,b))continue;let T=u.center,k=c??a??0,N=ai(n._computePcbGlobalTransformBeforeLayout(),Tn(s.x,s.y),Oo(k*Math.PI/180),Tn(-T.x,-T.y)),M=i.toArray().filter(C=>"pcb_component_id"in C&&C.pcb_component_id===o);el(M,N),znt({db:i,pcbComponentId:o,rotationDegrees:k,layer:u.layer});continue}let p=i.pcb_group.list().find(b=>b.source_group_id===o);if(!p)continue;let d=p.center,_=c??a??0,g=ai(n._computePcbGlobalTransformBeforeLayout(),Tn(s.x,s.y),Oo(_*Math.PI/180),Tn(-d.x,-d.y)),x=i.toArray().filter(b=>{if("source_group_id"in b&&b.source_group_id&&(b.source_group_id===o||Z1(i,b.source_group_id,o)))return!0;if("source_component_id"in b&&b.source_component_id){let S=i.source_component.get(b.source_component_id);if(S?.source_group_id&&(S.source_group_id===o||Z1(i,S.source_group_id,o)))return!0}if("pcb_component_id"in b&&b.pcb_component_id){let S=i.pcb_component.get(b.pcb_component_id);if(S?.source_component_id){let P=i.source_component.get(S.source_component_id);if(P?.source_group_id&&(P.source_group_id===o||Z1(i,P.source_group_id,o)))return!0}}return!1});el(x,g),i.pcb_group.update(p.pcb_group_id,{center:s})}},tzt="1mm",$nt=(0,vit.default)("Group_doInitialPcbLayoutPack"),ezt=n=>{let{db:e}=n.root,{_parsedProps:t}=n;n.root?.emit("packing:start",{subcircuit_id:n.subcircuit_id,componentDisplayName:n.getString()});let{packOrderStrategy:i,packPlacementStrategy:r,gap:s,pcbGap:o,pcbPackGap:a}=t,c=a??o??s,l=B.parse(c??tzt),u={},p=new Set,d=k=>{if(k?.pcb_component_id&&k?._parsedProps){let N=k._parsedProps,M=B.parse(N.pcbMarginLeft??N.pcbMarginX??0),C=B.parse(N.pcbMarginRight??N.pcbMarginX??0),E=B.parse(N.pcbMarginTop??N.pcbMarginY??0),R=B.parse(N.pcbMarginBottom??N.pcbMarginY??0);(M||C||E||R)&&(u[k.pcb_component_id]={left:M,right:C,top:E,bottom:R})}k?.children&&k.children.forEach(d)};d(n);let _=new Set;for(let k of n.children){let N=k;N._isNormalComponent&&N.isRelativelyPositioned?.()&&(N.pcb_component_id&&p.add(N.pcb_component_id),N.pcb_group_id&&_.add(N.pcb_group_id))}let g=(k,N,M)=>{if(N===M)return!0;let C=k.source_group.get(N);return!C||!C.parent_source_group_id?!1:g(k,C.parent_source_group_id,M)};if(_.size>0)for(let k of e.toArray()){if(k.type!=="pcb_component")continue;let N=e.source_component.get(k.source_component_id);if(N?.source_group_id)for(let M of _)g(e,N.source_group_id,M)&&p.add(k.pcb_component_id)}let x=e.toArray(),b;if(t.width!==void 0&&t.height!==void 0){let k=B.parse(t.width),N=B.parse(t.height);b={minX:-k/2,maxX:k/2,minY:-N/2,maxY:N/2}}let S={...ctt(att(x,{source_group_id:n.source_group_id,chipMarginsMap:u,staticPcbComponentIds:Array.from(p)})),orderStrategy:i??"largest_to_smallest",placementStrategy:r??"minimum_sum_squared_distance_to_network",minGap:l,bounds:b},P=JFt(n,S);$nt.enabled&&(n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${n.name}`,content:JSON.stringify(e.toArray())}),n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${n.name}`,content:S}));let T;try{T=Vw(S)}catch(k){throw n.root?.emit("packing:error",{subcircuit_id:n.subcircuit_id,componentDisplayName:n.getString(),error:{message:k instanceof Error?k.message:String(k)}}),k}if($nt.enabled&&global?.debugGraphics){let k=OA(T);k.title=`packOutput-${n.name}`,global.debugGraphics?.push(k)}QFt(n,T,P),n.root?.emit("packing:end",{subcircuit_id:n.subcircuit_id,componentDisplayName:n.getString()})},nzt=n=>{let{db:e}=n.root,{_parsedProps:t}=n,i=n.children.filter(N=>N.pcb_component_id||N.pcb_group_id);if(i.some(N=>{let M=N._parsedProps;return M?.pcbX!==void 0||M?.pcbY!==void 0}))return;let s=t.pcbJustifyContent??t.justifyContent,o=t.pcbAlignItems??t.alignItems,a=t.pcbFlexGap??t.pcbGap??t.gap,c=t.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"}[s??"space-between"],u={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[o??"center"];if(!l)throw new Error(`Invalid justifyContent value: "${s}"`);if(!u)throw new Error(`Invalid alignItems value: "${o}"`);let p=0,d=0;typeof a=="object"?(p=a.y??0,d=a.x??0):typeof a=="number"?(p=a,d=a):typeof a=="string"&&(p=B.parse(a),d=B.parse(a));let _,g=t.width??t.pcbWidth??void 0,x=t.height??t.pcbHeight??void 0;(g===void 0||x===void 0)&&(_=US(i.map(N=>N._getMinimumFlexContainerSize()).filter(N=>N!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:p,columnGap:d}),g=_.width,x=_.height);let S=new Hw(g,x,{alignItems:u,justifyContent:l,direction:c,rowGap:p,columnGap:d});for(let N of i){let M=N._getMinimumFlexContainerSize();S.addChild({metadata:N,width:M?.width??0,height:M?.height??0,flexBasis:M?c==="row"?M.width:M.height:void 0})}S.build();let P={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let N of S.children)P.minX=Math.min(P.minX,N.position.x),P.minY=Math.min(P.minY,N.position.y),P.maxX=Math.max(P.maxX,N.position.x+N.size.width),P.maxY=Math.max(P.maxY,N.position.y+N.size.height);P.width=P.maxX-P.minX,P.height=P.maxY-P.minY;let T=n._getGlobalPcbPositionBeforeLayout(),k={x:T.x-(P.maxX+P.minX)/2,y:T.y-(P.maxY+P.minY)/2};for(let N of S.children)N.metadata._repositionOnPcb({x:N.position.x+N.size.width/2+k.x,y:N.position.y+N.size.height/2+k.y});e.pcb_group.update(n.pcb_group_id,{width:P.width,height:P.height,center:T})};function izt(n){let{db:e}=n.root,t=new Map,i=new Map,r=new Set,o=n.selectAll("trace").filter(A=>A._parsedProps?.schDisplayLabel),a=n.selectAll("group"),c=[n.schematic_group_id,...a.map(A=>A.schematic_group_id)],l=e.schematic_component.list().filter(A=>c.includes(A.schematic_group_id)),u=[],p=new Map,d=new Map;for(let A of l){let j=A.schematic_component_id,D=[],Y=e.source_component.getWhere({source_component_id:A.source_component_id}),X=e.schematic_port.list({schematic_component_id:A.schematic_component_id});for(let W of X){let et=`${Y?.name??A.schematic_component_id}.${W.pin_number}`;p.set(et,W.schematic_port_id),d.set(W.schematic_port_id,et)}for(let W of X){let et=d.get(W.schematic_port_id);D.push({pinId:et,x:W.center.x,y:W.center.y})}u.push({chipId:j,center:A.center,width:A.size.width,height:A.size.height,pins:D})}let _=new Set,g=new Map,x=new Map,b=new Map;for(let A of l){let j=e.schematic_port.list({schematic_component_id:A.schematic_component_id});for(let D of j)_.add(D.schematic_port_id),D.source_port_id&&(g.set(D.schematic_port_id,D.source_port_id),x.set(D.source_port_id,D.schematic_port_id))}let S=new Set;n.subcircuit_id&&S.add(n.subcircuit_id);for(let A of a)A.subcircuit_id&&S.add(A.subcircuit_id);let T=e.source_trace.list().filter(A=>{if(A.subcircuit_id===n.subcircuit_id)return!0;for(let j of A.connected_source_port_ids)if(x.has(j))return!0;return!1}).flatMap(A=>A.connected_source_net_ids);for(let A of T){let j=e.source_net.get(A);j?.subcircuit_id&&S.add(j.subcircuit_id)}let k=[],N=new Map;for(let A of e.source_trace.list()){if(A.subcircuit_id&&!S.has(A.subcircuit_id))continue;let j=(A.connected_source_port_ids??[]).map(D=>x.get(D)).filter(D=>!!D&&_.has(D));if(j.length>=2){let[D,Y]=j.slice(0,2),X=[D,Y].sort().join("::");if(!N.has(X)){N.set(X,A.source_trace_id);let W=A.display_name??A.source_trace_id;A.subcircuit_connectivity_map_key&&(r.add(A.subcircuit_connectivity_map_key),b.set(W,A.subcircuit_connectivity_map_key),i.set(A.subcircuit_connectivity_map_key,W)),k.push({pinIds:[D,Y].map(et=>d.get(et)),netId:W})}}}let M=[];for(let A of e.source_net.list().filter(j=>!j.subcircuit_id||S.has(j.subcircuit_id)))A.subcircuit_connectivity_map_key&&(r.add(A.subcircuit_connectivity_map_key),t.set(A.subcircuit_connectivity_map_key,A));let C=new Map;for(let[A,j]of g){let D=e.source_port.get(j);if(!D?.subcircuit_connectivity_map_key)continue;let Y=D.subcircuit_connectivity_map_key;r.add(Y),C.has(Y)||C.set(Y,[]),C.get(Y).push(A)}for(let[A,j]of C){let D=t.get(A);if(D&&j.length>=2){let Y=String(D.name||D.source_net_id||A);b.set(Y,A),i.set(A,Y);let W=.1*(.18/.18),et=Number((String(Y).length*W).toFixed(2));M.push({netId:Y,pinIds:j.map(H=>d.get(H)),netLabelWidth:et})}}let E=(()=>{let A={},j=new Set(M.map(D=>D.netId));for(let D of e.source_net.list().filter(Y=>!Y.subcircuit_id||S.has(Y.subcircuit_id)))D.name&&j.has(D.name)&&(D.is_ground||D.name.toLowerCase().startsWith("gnd")?A[D.name]=["y-"]:D.is_power||D.name.toLowerCase().startsWith("v")?A[D.name]=["y+"]:A[D.name]=["x-","x+"]);return A})();return{inputProblem:{chips:u,directConnections:k,netConnections:M,availableNetLabelOrientations:E,maxMspPairDistance:n._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:p,pairKeyToSourceTraceId:N,sckToSourceNet:t,sckToUserNetId:i,userNetIdToSck:b,allSourceAndSchematicPortIdsInScope:_,schPortIdToSourcePortId:g,displayLabelTraces:o,allScks:r}}var gr=1e-6;function Dnt(n){let e=Math.abs(n.to.x-n.from.x),t=Math.abs(n.to.y-n.from.y);return e>=t}function gP(n,e){return Math.hypot(e.x-n.x,e.y-n.y)}function jnt(n,e,t){return{x:n.x+(e.x-n.x)*t,y:n.y+(e.y-n.y)*t}}function Bnt(n,e,t){let i=gP(n,e);if(i<gr)return 0;let r=((t.x-n.x)*(e.x-n.x)+(t.y-n.y)*(e.y-n.y))/((e.x-n.x)*(e.x-n.x)+(e.y-n.y)*(e.y-n.y));return Math.max(0,Math.min(1,r))*i}function uP(n,e,t,i){return n*i-e*t}function rzt(n,e,t,i){let r={x:e.x-n.x,y:e.y-n.y},s={x:i.x-t.x,y:i.y-t.y},o=uP(r.x,r.y,s.x,s.y),a={x:t.x-n.x,y:t.y-n.y},c=uP(a.x,a.y,r.x,r.y);if(Math.abs(o)<gr&&Math.abs(c)<gr||Math.abs(o)<gr&&Math.abs(c)>=gr)return null;let l=uP(a.x,a.y,s.x,s.y)/o,u=uP(a.x,a.y,r.x,r.y)/o;return l<-gr||l>1+gr||u<-gr||u>1+gr?null:{x:n.x+l*r.x,y:n.y+l*r.y}}function szt(n,e=gr){if(n.length===0)return n;n.sort((r,s)=>r.start-s.start);let t=[],i={...n[0]};for(let r=1;r<n.length;r++){let s=n[r];s.start<=i.end+e?i.end=Math.max(i.end,s.end):(t.push(i),i={...s})}return t.push(i),t}function ozt(n,e,t){let i=gP(n.from,n.to);if(i<gr||e.length===0)return[n];let r=t/2,s=e.map(p=>({start:Math.max(0,p-r),end:Math.min(i,p+r)})).filter(p=>p.end-p.start>gr),o=szt(s),a=[],c=0,l={x:n.to.x-n.from.x,y:n.to.y-n.from.y},u=(p,d,_)=>{if(d-p<=gr)return;let g=p/i,x=d/i;a.push({from:jnt(n.from,n.to,g),to:jnt(n.from,n.to,x),..._?{is_crossing:!0}:{}})};for(let p of o)p.start-c>gr&&u(c,p.start,!1),u(p.start,p.end,!0),c=p.end;return i-c>gr&&u(c,i,!1),a.length>0?a:[n]}function azt(n,e={}){let t=e.crossSegmentLength??.075,i=e.tolerance??gr,r=new Map,s=c=>`${c.traceIdx}:${c.edgeIdx}`,o=c=>n[c.traceIdx].edges[c.edgeIdx];for(let c=0;c<n.length;c++){let l=n[c];for(let u=0;u<l.edges.length;u++){let p=l.edges[u];for(let d=c;d<n.length;d++){let _=n[d];for(let g=d===c?u+1:0;g<_.edges.length;g++){let x=_.edges[g],b=rzt(p.from,p.to,x.from,x.to);if(!b)continue;let S=gP(p.from,p.to),P=gP(x.from,x.to);if(S<i||P<i)continue;let T=Bnt(p.from,p.to,b),k=Bnt(x.from,x.to,b),N=T<=i||Math.abs(S-T)<=i||Number.isNaN(T),M=k<=i||Math.abs(P-k)<=i||Number.isNaN(k);if(!N&&!M){let C=Dnt(p),E=Dnt(x),R;if(C!==E)R=C;else{let D=Math.abs(p.to.x-p.from.x),Y=Math.abs(p.to.y-p.from.y),X=Math.abs(x.to.x-x.from.x),W=Math.abs(x.to.y-x.from.y),et=D-Y,H=X-W;R=et===H?!0:et>H}let A=s({traceIdx:R?c:d,edgeIdx:R?u:g}),j=r.get(A)??[];j.push(R?T:k),r.set(A,j)}}}}}let a=n.map(c=>({source_trace_id:c.source_trace_id,edges:[]}));for(let c=0;c<n.length;c++){let l=n[c];for(let u=0;u<l.edges.length;u++){let p=s({traceIdx:c,edgeIdx:u}),d=r.get(p)??[];if(d.length===0){a[c].edges.push(l.edges[u]);continue}let _=Array.from(new Set(d.map(x=>Number(x.toFixed(6))))).sort((x,b)=>x-b),g=ozt(l.edges[u],_,t);a[c].edges.push(...g)}}return a}var Ko=1e-6;function xP(n,e,t=Ko){return Math.abs(n-e)<=t}function ty(n,e,t=Ko){return xP(n.x,e.x,t)&&xP(n.y,e.y,t)}function Ynt(n,e,t,i=Ko){let r=Math.min(e.x,t.x)-i,s=Math.max(e.x,t.x)+i,o=Math.min(e.y,t.y)-i,a=Math.max(e.y,t.y)+i;return n.x<r||n.x>s||n.y<o||n.y>a?!1:Math.abs((t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x))<=i}function Xnt(n,e=Ko){let t=new Map;for(let i of n){let r=`${i.x.toFixed(6)},${i.y.toFixed(6)}`;t.has(r)||t.set(r,i)}return Array.from(t.values())}function Unt(n){return{x:n.to.x-n.from.x,y:n.to.y-n.from.y}}function E9(n,e,t=Ko){let i=Unt(n),r=Unt(e),s=Math.hypot(i.x,i.y),o=Math.hypot(r.x,r.y);if(s<t||o<t)return!0;let a=i.x*r.y-i.y*r.x;return Math.abs(a)<=t*s*o}function K1(n,e,t=Ko){return n.edges.filter(i=>ty(i.from,e,t)||ty(i.to,e,t))}function Vnt(n,e,t=Ko){for(let i of n.edges){if(ty(i.from,e,t))return i.from;if(ty(i.to,e,t))return i.to}return null}function czt(n,e,t=Ko){let i=ty(n.from,e,t)||xP(n.from.x,e.x,t)&&xP(n.from.y,e.y,t)?n.to:n.from,r=i.x-e.x,s=i.y-e.y;return Math.abs(r)<t&&Math.abs(s)<t?null:Math.abs(r)>=Math.abs(s)?r>=0?"right":"left":s>=0?"up":"down"}function H_(n,e,t=Ko){let i=K1(n,e,t);if(i.length<2)return null;let r=i.map(p=>czt(p,e,t)),s=r.includes("up"),o=r.includes("down"),a=r.includes("left"),c=r.includes("right"),l=s?"up":o?"down":null,u=c?"right":a?"left":null;return l&&u?`${l}-${u}`:null}function lzt(n,e={}){let t=e.tolerance??Ko,i={};for(let s of n)i[s.source_trace_id]=[];let r=n.map(s=>{let o=[];for(let a of s.edges)o.push(a.from,a.to);return Xnt(o,t)});for(let s=0;s<n.length;s++){let o=n[s],a=r[s];for(let c=s+1;c<n.length;c++){let l=n[c],u=r[c];for(let p of a)for(let d of u)if(ty(p,d,t)){let _=K1(o,p,t),g=K1(l,d,t),x=_.some(T=>g.some(k=>!E9(T,k,t))),b=H_(o,p,t),S=H_(l,d,t);x&&!(b!==null&&S!==null&&b===S)&&(i[o.source_trace_id].push(p),o.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(d))}for(let p of a)for(let d of l.edges)if(Ynt(p,d.from,d.to,t)){let g=K1(o,p,t).some(T=>!E9(T,d,t)),x=H_(o,p,t),b=Vnt(l,p,t*1e3),S=b?H_(l,b,t):null;g&&!(x!==null&&S!==null&&x===S)&&(i[o.source_trace_id].push(p),o.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(p))}for(let p of u)for(let d of o.edges)if(Ynt(p,d.from,d.to,t)){let g=K1(l,p,t).some(T=>!E9(d,T,t)),x=H_(l,p,t),b=Vnt(o,p,t*1e3),S=b?H_(o,b,t):null;g&&!(S!==null&&x!==null&&S===x)&&(i[l.source_trace_id].push(p),o.source_trace_id!==l.source_trace_id&&i[o.source_trace_id].push(p))}}}for(let s of Object.keys(i))i[s]=Xnt(i[s],t);return i}var C9=(0,wit.default)("Group_doInitialSchematicTraceRender");function uzt(n){let{group:e,solver:t,pinIdToSchematicPortId:i,userNetIdToSck:r}=n,{db:s}=e.root,o=t.traceCleanupSolver?.getOutput().traces??t.traceLabelOverlapAvoidanceSolver?.getOutput().traces??t.schematicTraceLinesSolver?.solvedTracePaths,a=[];C9(`Traces inside SchematicTraceSolver output: ${(o??[]).length}`);for(let u of o??[]){let p=u?.tracePath;if(!Array.isArray(p)||p.length<2){C9(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let d=[];for(let x=0;x<p.length-1;x++)d.push({from:{x:p[x].x,y:p[x].y},to:{x:p[x+1].x,y:p[x+1].y}});let _=null,g;if(Array.isArray(u?.pins)&&u.pins.length===2){let x=i.get(u.pins[0]?.pinId),b=i.get(u.pins[1]?.pinId);if(x&&b){for(let S of[x,b])s.schematic_port.get(S)&&s.schematic_port.update(S,{is_connected:!0});g=r.get(String(u.userNetId))}}_||(_=`solver_${u?.mspPairId}`,g=r.get(String(u.userNetId))),a.push({source_trace_id:_,edges:d,subcircuit_connectivity_map_key:g})}C9(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=azt(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=lzt(c);for(let u of c)s.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(p=>p.source_trace_id===u.source_trace_id)?.subcircuit_connectivity_map_key})}var pzt=n=>{switch(n){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"}},hzt=n=>{for(let t of n){let i=t._getDirectlyConnectedTraces();for(let r of i){let s=r._parsedProps.schDisplayLabel;if(s)return{name:s,wasAssignedDisplayLabel:!0}}}return{name:n.map(t=>t._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},I9=(0,Pit.default)("Group_doInitialSchematicTraceRender");function dzt(n){let{group:e,solver:t,sckToSourceNet:i,allScks:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=n,{db:p}=e.root,d=t.netLabelPlacementSolver?.netLabelPlacements??t.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],_=t.mspConnectionPairSolver.globalConnMap;for(let g of d){I9(`processing placement: ${g.netId}`);let x=_.getIdsConnectedToNet(g.globalConnNetId).find(A=>a.get(A)),b=a.get(x),S=g.anchorPoint,P=g.orientation,T=pzt(P),k=b?i.get(b):void 0,N=g.pinIds.map(A=>c.get(A));if(N.some(A=>l.has(A))){I9(`skipping net label placement for "${g.netId}" REASON:schematic port has pre-existing net label`);continue}if(k){let A=k.name,j=kl({anchor_position:S,anchor_side:T,text:A});p.schematic_net_label.insert({text:A,anchor_position:S,center:j,anchor_side:T,...k?.source_net_id?{source_net_id:k.source_net_id}:{}});continue}let M=e.selectAll("port").filter(A=>A._getSubcircuitConnectivityKey()===b),{name:C,wasAssignedDisplayLabel:E}=hzt(M);if(!E&&N.some(A=>u.has(A))){I9(`skipping net label placement for "${g.netId}" REASON:schematic port has routed traces and no display label`);continue}let R=kl({anchor_position:S,anchor_side:T,text:C});p.schematic_net_label.insert({text:C,anchor_position:S,center:R,anchor_side:T})}}var fzt=({allSourceAndSchematicPortIdsInScope:n,group:e,schPortIdToSourcePortId:t,sckToSourceNet:i,pinIdToSchematicPortId:r,schematicPortIdsWithPreExistingNetLabels:s})=>{let{db:o}=e.root;for(let a of Array.from(n)){let c=o.schematic_port.get(a);if(!c||c.is_connected)continue;let l=t.get(a);if(!l)continue;let p=o.source_port.get(l)?.subcircuit_connectivity_map_key;if(!p)continue;let d=i.get(p);if(!d||o.schematic_net_label.list().some(S=>Math.abs(S.anchor_position.x-c.center.x)<.1&&Math.abs(S.anchor_position.y-c.center.y)<.1?d.source_net_id&&S.source_net_id?S.source_net_id===d.source_net_id:S.text===(d.name||p):!1))continue;let g=d.name||d.source_net_id||p,x=e0(c.facing_direction||"right")||"right",b=kl({anchor_position:c.center,anchor_side:x,text:g});o.schematic_net_label.insert({text:g,anchor_position:c.center,center:b,anchor_side:x,...d.source_net_id?{source_net_id:d.source_net_id}:{}})}},mzt=n=>{let e=new Set,t=n.selectAll("netlabel");for(let i of t){let r=i._getConnectedPorts();for(let s of r)s.schematic_port_id&&e.add(s.schematic_port_id)}return e},_zt=({solver:n,pinIdToSchematicPortId:e})=>{let t=n.schematicTraceLinesSolver.solvedTracePaths,i=new Set;for(let r of t)for(let s of r.pinIds){let o=e.get(s);o&&i.add(o)}return i},yzt=(0,Sit.default)("Group_doInitialSchematicTraceRender"),gzt=n=>{if(!n.root?._featureMspSchematicTraceRouting||!n.isSubcircuit||n.root?.schematicDisabled)return;let{inputProblem:e,pinIdToSchematicPortId:t,pairKeyToSourceTraceId:i,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,displayLabelTraces:a,allScks:c,userNetIdToSck:l}=izt(n),u=mzt(n);yzt.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(e,null,2)});let p=new ztt(e);p.solve();let d=_zt({solver:p,pinIdToSchematicPortId:t});uzt({group:n,solver:p,pinIdToSchematicPortId:t,userNetIdToSck:l}),dzt({group:n,solver:p,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,pinIdToSchematicPortId:t,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:d}),fzt({group:n,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,sckToSourceNet:r,pinIdToSchematicPortId:t,schematicPortIdsWithPreExistingNetLabels:u})},xzt=()=>({async simulate(n){let e="spice-experiment-1",{circuit:t,tran:i}=Btt(n);return{simulationResultCircuitJson:Ytt(i,t,e)}}}),Gnt=["rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)"],dP=new Map,fP=0;function bzt(n){if(dP.has(n))return dP.get(n);let e=Gnt[fP];return fP=(fP+1)%Gnt.length,dP.set(n,e),e}function vzt(){dP.clear(),fP=0}var Ga=(0,kit.default)("tscircuit:core:Group_doInitialSimulationSpiceEngineRender");function Szt(n){if(!n.isSubcircuit)return;let{root:e}=n;if(!e)return;let t=n.selectAll("analogsimulation");if(t.length===0)return;let i=n.selectAll("voltageprobe");vzt();let r={...e.platform?.spiceEngineMap};r.spicey||(r.spicey=xzt());let s=e.db.toArray(),o,a;try{a=Dtt(s),o=a.toSpiceString(),Ga(`Generated SPICE string:
253
- ${o}`)}catch(c){Ga(`Failed to convert circuit JSON to SPICE: ${c}`);return}for(let c of t){let l=c._parsedProps.spiceEngine??"spicey",u=r[l];if(!u)throw new Error(`SPICE engine "${l}" not found in platform config. Available engines: ${JSON.stringify(Object.keys(r).filter(d=>d!=="spicey"))}`);let p=`spice-simulation-${l}-${c.source_component_id}`;Ga(`Queueing simulation for spice engine: ${l} (id: ${p})`),n._queueAsyncEffect(p,async()=>{try{Ga(`Running simulation with engine: ${l}`);let d=await u.simulate(o);Ga(`Simulation completed, received ${d.simulationResultCircuitJson.length} elements`);let _=e.db.simulation_experiment.list()[0];if(!_){Ga("No simulation experiment found, skipping result insertion");return}for(let g of d.simulationResultCircuitJson){if(g.type==="simulation_transient_voltage_graph"){g.simulation_experiment_id=_.simulation_experiment_id;let b=i.find(S=>S.finalProbeName===g.name);b&&(g.color=b.color)}let x=g.type;x&&e.db[x]?(e.db[x].insert(g),Ga(`Inserted ${x} into database`)):(Ga(`Warning: Unknown element type ${x}, adding to raw db`),e.db._addElement(g))}n._markDirty("SimulationSpiceEngineRender")}catch(d){Ga(`Simulation failed for engine ${l}: ${d}`);let _=e.db.simulation_experiment.list()[0];e.db.simulation_unknown_experiment_error.insert({simulation_experiment_id:_?.simulation_experiment_id,error_type:"simulation_unknown_experiment_error",message:d instanceof Error?d.message:String(d)})}})}}function wzt(n){if(n.root?.pcbDisabled||!n.pcb_group_id)return;let e=n._parsedProps?.pcbPositionAnchor;if(!e)return;let t=n._getGlobalPcbPositionBeforeLayout(),{pcbX:i,pcbY:r}=n._parsedProps;if(i===void 0&&r===void 0)return;let{db:s}=n.root,o=s.pcb_group.get(n.pcb_group_id);if(!o)return;let a=o.width,c=o.height,{center:l}=o;if(o.outline&&o.outline.length>0){let x=lo(o.outline);x&&(a=x.maxX-x.minX,c=x.maxY-x.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},p={...l},d=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(e))switch(e){case"center":d=p;break;case"top_left":d={x:u.left,y:u.top};break;case"top_center":d={x:p.x,y:u.top};break;case"top_right":d={x:u.right,y:u.top};break;case"center_left":d={x:u.left,y:p.y};break;case"center_right":d={x:u.right,y:p.y};break;case"bottom_left":d={x:u.left,y:u.bottom};break;case"bottom_center":d={x:p.x,y:u.bottom};break;case"bottom_right":d={x:u.right,y:u.bottom};break}if(!d)return;let g={...p};t.x!==void 0&&(g.x+=t.x-d.x),t.y!==void 0&&(g.y+=t.y-d.y),(Math.abs(g.x-p.x)>1e-6||Math.abs(g.y-p.y)>1e-6)&&(n._repositionOnPcb(g),s.pcb_group.update(n.pcb_group_id,{center:g})),s.pcb_group.update(n.pcb_group_id,{anchor_position:t,anchor_alignment:e})}var Tl=class extends Yn{constructor(){super(...arguments);f(this,"pcb_group_id",null);f(this,"schematic_group_id",null);f(this,"subcircuit_id",null);f(this,"_hasStartedAsyncAutorouting",!1);f(this,"_asyncAutoroutingResult",null);f(this,"unnamedElementCounter",{})}get config(){return{zodProps:pH,componentName:"Group"}}doInitialSourceGroupRender(){let{db:e}=this.root,t=typeof this._parsedProps.name=="string"&&this._parsedProps.name.length>0,i=e.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit,was_automatically_named:!t});this.source_group_id=i.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${i.source_group_id}`,e.source_group.update(i.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:e}=this.root;for(let t of this.children)e.source_component.update(t.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:e}=this.root,t=this.parent?.getGroup?.();if(t?.source_group_id&&e.source_group.update(this.source_group_id,{parent_source_group_id:t.source_group_id}),!this.isSubcircuit)return;let i=this.parent?.getSubcircuit?.()?.subcircuit_id;i&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:i})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t,r=i.outline&&i.outline.length>0,s=r?i.outline.map(a=>({x:V.parse(a.x),y:V.parse(a.y)})):void 0,o=e.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),...r?{outline:s}:{width:0,height:0},pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:t.autorouter?{trace_clearance:t.autorouter.traceClearance}:void 0});this.pcb_group_id=o.pcb_group_id;for(let a of this.children)e.pcb_component.update(a.pcb_component_id,{pcb_group_id:o.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps,i=t.outline&&t.outline.length>0;if(this.pcb_group_id){let r=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0;if(i){let p=t.outline.map(b=>({x:V.parse(b.x),y:V.parse(b.y)})),d=lo(p);if(!d)return;let _=(d.minX+d.maxX)/2,g=(d.minY+d.maxY)/2,x=r?e.pcb_group.get(this.pcb_group_id)?.center??{x:_,y:g}:{x:_,y:g};e.pcb_group.update(this.pcb_group_id,{center:x});return}let s=wP(this.children),o=s.width,a=s.height,c=(s.minX+s.maxX)/2,l=(s.minY+s.maxY)/2;if(this.isSubcircuit){let{padLeft:p,padRight:d,padTop:_,padBottom:g}=this._resolvePcbPadding();o+=p+d,a+=_+g,c+=(d-p)/2,l+=(_-g)/2}let u=r?e.pcb_group.get(this.pcb_group_id)?.center??{x:c,y:l}:{x:c,y:l};e.pcb_group.update(this.pcb_group_id,{width:Number(t.width??o),height:Number(t.height??a),center:u})}}getNextAvailableName(e){var t,i;return(t=this.unnamedElementCounter)[i=e.lowercaseComponentName]??(t[i]=1),`unnamed_${e.lowercaseComponentName}${this.unnamedElementCounter[e.lowercaseComponentName]++}`}_resolvePcbPadding(){let e=this._parsedProps,t=e.pcbLayout,i=p=>{let d=t?.[p],_=e[p];if(typeof d=="number")return d;if(typeof _=="number")return _},r=i("padding")??0,s=i("paddingX"),o=i("paddingY"),a=i("paddingLeft")??s??r,c=i("paddingRight")??s??r,l=i("paddingTop")??o??r,u=i("paddingBottom")??o??r;return{padLeft:a,padRight:c,padTop:l,padBottom:u}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:e}=this,{db:t}=this.root,i=e;if(!this.isSubcircuit)return;let r=i.manualEdits?.manual_trace_hints;if(r)for(let s of r)this.add(new H9({for:s.pcb_port_selector,offsets:s.offsets}))}doInitialSourceAddConnectivityMapKey(){$Ft(this)}_areChildSubcircuitsRouted(){let e=this.selectAll("group").filter(t=>t.isSubcircuit);for(let t of e)if(t._shouldRouteAsync()&&!t._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let e=this._getAutorouterConfig();return e.groupMode==="sequential-trace"?!1:!!(e.local&&e.groupMode==="subcircuit"||!e.local)}_hasTracesToRoute(){let e=(0,q_.default)("tscircuit:core:_hasTracesToRoute"),t=this.selectAll("trace");return e(`[${this.getString()}] has ${t.length} traces to route`),t.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:e}=this.root,t=(0,q_.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),i=this._parsedProps,r=this._getAutorouterConfig(),s=r.serverUrl,o=r.serverMode,a=(u,p)=>(t("fetching",u),p.headers&&(p.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(u,p)),c=this.root.db.toArray().filter(u=>u.type.startsWith("source_")||u.type.startsWith("pcb_"));if(o==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:p}=await a(`${s}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:D9({db:e,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=p,this._markDirty("PcbTraceRender");return}let{autorouting_result:u}=await a(`${s}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:c,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(p=>p.json());this._asyncAutoroutingResult=u,this._markDirty("PcbTraceRender");return}let{autorouting_job:l}=await a(`${s}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:c,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:r.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(u=>u.json());for(;;){let{autorouting_job:u}=await a(`${s}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(p=>p.json());if(u.is_finished){let{autorouting_job_output:p}=await a(`${s}/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:p.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(u.has_error){let p=new q1(`Autorouting job failed: ${JSON.stringify(u.error)}`);throw e.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,error_type:"pcb_autorouting_error",message:p.message}),p}await new Promise(p=>setTimeout(p,100))}}async _runLocalAutorouting(){let{db:e}=this.root,t=this._parsedProps,i=(0,q_.default)("tscircuit:core:_runLocalAutorouting");i(`[${this.getString()}] starting local autorouting`);let r=this._getAutorouterConfig(),s=this._isLaserPrefabAutorouter(r),{simpleRouteJson:o}=D9({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(i.enabled&&global.debugOutputArray?.push({name:`simpleroutejson-${this.props.name}.json`,obj:o}),i.enabled){let l=r1(o);l.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(l)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:o});let a;r.algorithmFn?a=await r.algorithmFn(o):a=new CFt(o,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity,useAssignableViaSolver:s});let c=new Promise((l,u)=>{a.on("complete",p=>{i(`[${this.getString()}] local autorouting complete`),l(p.traces)}),a.on("error",p=>{i(`[${this.getString()}] local autorouting error: ${p.error.message}`),u(p.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:o}),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 e=(0,q_.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){e(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}e(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){gzt(this)}updatePcbTraceRender(){let e=(0,q_.default)("tscircuit:core:updatePcbTraceRender");if(e(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(e(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:t}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){e(`[${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){e(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:e}=this.root,{traces:t}=this._asyncAutoroutingResult.output_simple_route_json;if(t)for(let i of t){let r=e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;let{db:t}=this.root,i=this.getInheritedMergedProperty("pcbStyle"),{holeDiameter:r,padDiameter:s}=W9(i);for(let o of e)if(o.type==="pcb_trace"){if(o.subcircuit_id=this.subcircuit_id,o.connection_name){let a=o.connection_name;o.source_trace_id=a}t.pcb_trace.insert(o)}for(let o of e)if(o.type!=="pcb_via"&&o.type==="pcb_trace")for(let a of o.route)a.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:o.pcb_trace_id,x:a.x,y:a.y,hole_diameter:r,outer_diameter:s,layers:[a.from_layer,a.to_layer],from_layer:a.from_layer,to_layer:a.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=e.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=i.schematic_group_id;for(let r of this.children)r.schematic_component_id&&e.schematic_component.update(r.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){let e=this._parsedProps;if(e.schLayout?.layoutMode==="none"||e.schLayout?.layoutMode==="relative")return"relative";if(e.schLayout?.matchAdapt)return"match-adapt";if(e.schLayout?.flex)return"flex";if(e.schLayout?.grid)return"grid";if(e.schMatchAdapt)return"match-adapt";if(e.schFlex)return"flex";if(e.schGrid)return"grid";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";if(e.relative||e.schRelative)return"relative";let t=this.children.some(r=>{let s=r._parsedProps;return s?.schX!==void 0||s?.schY!==void 0}),i=(e.manualEdits?.schematic_placements?.length??0)>0;return!t&&!i?"match-adapt":"relative"}doInitialSchematicLayout(){let e=this._getSchematicLayoutMode();e==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),e==="grid"&&this._doInitialSchematicLayoutGrid(),e==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){LFt(this)}_doInitialSchematicLayoutMatchpack(){zFt(this)}_doInitialSchematicLayoutGrid(){DFt(this)}_doInitialSchematicLayoutFlex(){jFt(this)}_getPcbLayoutMode(){let e=this._parsedProps;if(e.pcbRelative)return"none";if(e.pcbLayout?.matchAdapt)return"match-adapt";if(e.pcbLayout?.flex)return"flex";if(e.pcbLayout?.grid)return"grid";if(e.pcbLayout?.pack)return"pack";if(e.pcbFlex)return"flex";if(e.pcbGrid)return"grid";if(e.pcbPack||e.pack)return"pack";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";let t=e.pcbX!==void 0||e.pcbY!==void 0,i=(e.manualEdits?.pcb_placements?.length??0)>0,r=this.children.reduce((s,o)=>{if(!o.pcb_component_id&&!o.pcb_group_id)return s;let a=o._parsedProps,c=a?.pcbX!==void 0||a?.pcbY!==void 0;return s+(c?0:1)},0);return!t&&!i&&r>1?"pack":"none"}doInitialPcbLayout(){let e=this._getPcbLayoutMode();e==="grid"?this._doInitialPcbLayoutGrid():e==="pack"?this._doInitialPcbLayoutPack():e==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){BFt(this)}_doInitialPcbLayoutPack(){ezt(this)}_doInitialPcbLayoutFlex(){nzt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!t.border)return;let i=typeof t.schWidth=="number"?t.schWidth:void 0,r=typeof t.schHeight=="number"?t.schHeight:void 0,s=typeof t.schPadding=="number"?t.schPadding:0,o=typeof t.schPaddingLeft=="number"?t.schPaddingLeft:s,a=typeof t.schPaddingRight=="number"?t.schPaddingRight:s,c=typeof t.schPaddingTop=="number"?t.schPaddingTop:s,l=typeof t.schPaddingBottom=="number"?t.schPaddingBottom:s,u=this.schematic_group_id?e.schematic_group.get(this.schematic_group_id):null;if(u&&(i===void 0&&typeof u.width=="number"&&(i=u.width),r===void 0&&typeof u.height=="number"&&(r=u.height)),i===void 0||r===void 0)return;let p=u?.center??this._getGlobalSchematicPositionBeforeLayout(),d=p.x-i/2-o,_=p.y-r/2-l,g=i+o+a,x=r+c+l;e.schematic_box.insert({width:g,height:x,x:d,y:_,is_dashed:t.border?.dashed??!1})}_determineSideFromPosition(e,t){if(!e.center||!t.center)return"left";let i=e.center.x-t.center.x,r=e.center.y-t.center.y;return Math.abs(i)>Math.abs(r)?i>0?"right":"left":r>0?"bottom":"top"}_calculateSchematicBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let a of e)t=Math.min(t,a.centerX),i=Math.max(i,a.centerX),r=Math.min(r,a.centerY),s=Math.max(s,a.centerY);let o=2;return{minX:t-o,maxX:i+o,minY:r-o,maxY:s+o}}_getAutorouterConfig(){let e=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return KFt(e)}_isLaserPrefabAutorouter(e=this._getAutorouterConfig()){let t=this.props.autorouter,i=r=>r?.replace(/-/g,"_")??r;return e.preset==="laser_prefab"?!0:typeof t=="string"?i(t)==="laser_prefab":typeof t=="object"&&t?i(t.preset)==="laser_prefab":!1}_getSubcircuitLayerCount(){let e=this.getInheritedProperty("layers");return typeof e=="number"?e:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(this.isSubcircuit){let t=new Map;for(let i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){let r=t.get(i._parsedProps.name)||[];r.push(i),t.set(i._parsedProps.name,r)}for(let[i,r]of t.entries())r.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:r.map(s=>s.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:e}=this.root,t=e;for(let i of t.schematic_net_label.list()){let r=t.source_net.get(i.source_net_id),s=i.text||r?.name||"";if(i.anchor_side==="top"&&/^gnd/i.test(s)){t.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_down"});continue}i.anchor_side==="bottom"&&/^v/i.test(s)&&t.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_up"})}}doInitialSimulationSpiceEngineRender(){Szt(this)}doInitialPcbComponentAnchorAlignment(){wzt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(e){return super._repositionOnPcb(e)}};function Pzt(n,e){let{subcircuit:t}=e;if(t.lowercaseComponentName==="board"||t.parent?.lowercaseComponentName==="board")return;let i={name:"inflated_board"};n.width&&(i.width=n.width),n.height&&(i.height=n.height),n.center&&(i.pcbX=n.center.x,i.pcbY=n.center.y),n.outline&&(i.outline=n.outline),n.thickness&&(i.thickness=n.thickness),n.material&&(i.material=n.material);let r=new TP(i);return r.pcb_board_id=n.pcb_board_id,t.add(r),r}var kzt=new Proxy({},{get:(n,e)=>e}),qa=kzt,PP="rgba(132, 0, 0)",kP=.12,Z9=class extends Yn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:wH,sourceFtype:qa.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let e=this.props.capacitance,t=typeof e=="string"?e:`${ei(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${t}/${ei(this._parsedProps.maxVoltageRating)}V`:t}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new Ds({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new Ds({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,capacitance:t.capacitance,max_voltage_rating:t.maxVoltageRating,max_decoupling_trace_length:t.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!t.polarized});this.source_component_id=i.source_component_id}},ey=(n,e)=>{let{injectionDb:t,normalComponent:i}=e;if(!i)return;let r=n.center||{x:0,y:0},s=n.rotation||0,o=VE(ai(Tn(r.x,r.y),Oo(s*Math.PI/180))),a=t.toArray().filter(u=>"pcb_component_id"in u&&u.pcb_component_id===n.pcb_component_id),c=structuredClone(a);el(c,o);let l=J_({componentName:i.name,componentRotation:"0deg"},c);i.addAll(l)};function Tzt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new Z9({name:n.name,capacitance:n.capacitance,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&ey(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var n0=class extends Yn{constructor(e){super(e);f(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:l_,shouldRenderAsSchematicBox:!0}}initPorts(e={}){super.initPorts(e);let{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp();if(t.externallyConnectedPins){let s=new Set;for(let[o,a]of t.externallyConnectedPins)s.add(o),s.add(a);for(let o of s)if(!this.children.find(c=>c instanceof qi&&c.isMatchingAnyOf([o]))){let c=o.match(/^pin(\d+)$/);if(c){let l=parseInt(c[1]);this.add(new qi({pinNumber:l,aliases:[o]}))}else this.add(new qi({name:o,aliases:[o]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:e}=this;e?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=t.layer??"top";if(s!=="top"&&s!=="bottom"){let a=this.getSubcircuit(),c=Ym.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${s}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:s,subcircuit_id:a.subcircuit_id??void 0});e.pcb_component_invalid_layer_error.insert(c)}let o=e.pcb_component.insert({center:{x:i,y:r},width:2,height:3,layer:s==="top"||s==="bottom"?s:"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=o.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:e}=this;if(e.externallyConnectedPins)for(let[t,i]of e.externallyConnectedPins)this.add(new Ds({from:`${this.getSubcircuitSelector()} > port.${t}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:e}=this.root,{pinAttributes:t}=this.props;if(!t)return;let i=null,r=null,s,o=this.selectAll("port");for(let p of o)for(let d of p.getNameAndAliases())if(t[d]){let _=t[d];_.providesPower&&(i=p,s=_.providesVoltage),_.providesGround&&(r=p)}if(!i||!r||s===void 0)return;let a=e.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=e.source_port.get(r.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=e.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=e.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||e.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:r.source_port_id,negative_source_net_id:u.source_net_id,voltage:s})}},Mzt=(n,e)=>{if(!n||n.length===0)return;let{injectionDb:t}=e,i=n.map(r=>r.map(s=>{let o=t.source_port.get(s);return o?o.pin_number!==void 0&&o.pin_number!==null?`pin${o.pin_number}`:o.name:null}).filter(s=>s!==null)).filter(r=>r.length>0);return i.length>0?i:void 0},Ezt=(n,e)=>{let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.schematic_component.getWhere({source_component_id:n.source_component_id}),a=t.cad_component.getWhere({source_component_id:n.source_component_id}),c=Mzt(n.internally_connected_source_port_ids,e),l=new n0({name:n.name,manufacturerPartNumber:n.manufacturer_part_number,supplierPartNumbers:n.supplier_part_numbers??void 0,pinLabels:o?.port_labels??void 0,schWidth:o?.size?.width,schHeight:o?.size?.height,schPinSpacing:o?.pin_spacing,schX:o?.center?.x,schY:o?.center?.y,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds,internallyConnectedPins:c}),u=a?.footprinter_string??null;u&&(Object.assign(l.props,{footprint:u}),Object.assign(l._parsedProps,{footprint:u}),a||l._addChildrenFromStringFootprint?.()),s&&ey(s,{...e,normalComponent:l}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(l):i.add(l)},K9=class extends Yn{constructor(){super(...arguments);f(this,"pos",this.portMap.pin1);f(this,"anode",this.portMap.pin1);f(this,"neg",this.portMap.pin2);f(this,"cathode",this.portMap.pin2)}get config(){let e={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},t=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:t?e[t]:this.props.symbolName??"diode",componentName:"Diode",zodProps:jH,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}};function Czt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new K9({name:n.name,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&ey(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}function Izt(n,e){let{subcircuit:t,groupsMap:i}=e,r=new Tl({name:n.name??`inflated_group_${n.source_group_id}`});return r.source_group_id=n.source_group_id,i&&i.set(n.source_group_id,r),n.parent_source_group_id&&i?.has(n.parent_source_group_id)?i.get(n.parent_source_group_id).add(r):t.add(r),r}var J9=class extends Yn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:DH,sourceFtype:qa.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${ei(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({name:this.name,ftype:qa.simple_inductor,inductance:this.props.inductance,display_inductance:this._getSchematicSymbolDisplayValue(),supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function Nzt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new J9({name:n.name,inductance:n.inductance,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&ey(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}function Azt(n,e){let{injectionDb:t,subcircuit:i}=e;if(n.source_component_id!==null)return;let r=t.pcb_port.getWhere({source_port_id:n.source_port_id}),s=new qi({name:n.name,pinNumber:n.pin_number});i.add(s),s.source_port_id=n.source_port_id;let o=i.root;if(o&&r){let{db:a}=o,c=a.pcb_port.insert({pcb_component_id:void 0,layers:r.layers,subcircuit_id:i.subcircuit_id??void 0,pcb_group_id:i.getGroup()?.pcb_group_id??void 0,x:r.x,y:r.y,source_port_id:n.source_port_id,is_board_pinout:!1});s.pcb_port_id=c.pcb_port_id}}var Q9=class extends Yn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:gH,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${ei(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 Ds({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new Ds({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new Ds({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new Ds({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,resistance:t.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function Rzt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new Q9({name:n.name,resistance:n.resistance,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&ey(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var Ozt=(n,e)=>{let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=[],o=n.source_group_id;for(;o&&o!==i.source_group_id;){let a=t.source_group.get(o),c=r?.get(o);if(!a||!c)break;let l=c.props.name??c.fallbackUnassignedName;s.unshift(`.${l}`),o=a.parent_source_group_id}return s.push(`.${n.name}`),s.join(" > ")};function Lzt(n,e){let{injectionDb:t,subcircuit:i}=e,r=[];for(let o of n.connected_source_port_ids){let a=t.source_port.get(o);if(!a)continue;let c;if(a.source_component_id){let l=t.source_component.get(a.source_component_id);l&&(c=`${Ozt({name:l.name,source_group_id:l.source_group_id},e)} > .${a.name}`)}else c=`.${a.name}`;c&&r.push(c)}for(let o of n.connected_source_net_ids){let a=t.source_net.get(o);a&&r.push(`net.${a.name}`)}if(r.length<2)return;let s=new Ds({path:r});s.source_trace_id=n.source_trace_id,i.add(s)}var t6=class extends Yn{constructor(){super(...arguments);f(this,"emitter",this.portMap.pin1);f(this,"collector",this.portMap.pin2);f(this,"base",this.portMap.pin3)}get config(){let e=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??e,zodProps:zH,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let e={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:e})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:t.type});this.source_component_id=i.source_component_id}};function Fzt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new t6({name:n.name,type:n.transistor_type,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&ey(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var Tit=(n,e,t)=>{if(!e)return;let i=Je(e);if(e&&t?.length>0)throw new Error("Component cannot have both circuitJson and children");let s={injectionDb:i,subcircuit:n,groupsMap:new Map},o=i.source_group.list();for(let p of o)Izt(p,s);let a=i.pcb_board.list();for(let p of a)Pzt(p,s);let c=i.source_component.list();for(let p of c)switch(p.ftype){case"simple_resistor":Rzt(p,s);break;case"simple_capacitor":Tzt(p,s);break;case"simple_inductor":Nzt(p,s);break;case"simple_diode":Czt(p,s);break;case"simple_chip":Ezt(p,s);break;case"simple_transistor":Fzt(p,s);break;default:throw new Error(`No inflator implemented for source component ftype: "${p.ftype}"`)}let l=i.source_port.list();for(let p of l)Azt(p,s);let u=i.source_trace.list();for(let p of u)Lzt(p,s)},zzt=.01,Wnt=(n,e,t)=>{let i=n/2,r=e/2,s=Math.min(t,i,r);if(s<zzt)return[{x:-i,y:-r},{x:i,y:-r},{x:i,y:r},{x:-i,y:r}];let a=Math.max(1,Math.ceil(Math.PI/2*s/.1)),c=Math.PI/2/a,l=[];l.push({x:-i+s,y:-r}),l.push({x:i-s,y:-r});for(let u=1;u<=a;u++){let p=-Math.PI/2+u*c;l.push({x:i-s+s*Math.cos(p),y:-r+s+s*Math.sin(p)})}l.push({x:i,y:r-s});for(let u=1;u<=a;u++){let p=0+u*c;l.push({x:i-s+s*Math.cos(p),y:r-s+s*Math.sin(p)})}l.push({x:-i+s,y:r});for(let u=1;u<=a;u++){let p=Math.PI/2+u*c;l.push({x:-i+s+s*Math.cos(p),y:r-s+s*Math.sin(p)})}l.push({x:-i,y:-r+s});for(let u=1;u<=a;u++){let p=Math.PI+u*c;l.push({x:-i+s+s*Math.cos(p),y:-r+s+s*Math.sin(p)})}return l},TP=class extends Tl{constructor(){super(...arguments);f(this,"pcb_board_id",null);f(this,"source_board_id",null);f(this,"_drcChecksComplete",!1);f(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:R4}}get boardThickness(){return this._parsedProps.thickness??1.4}get allLayers(){return(this._parsedProps.layers??2)===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}_getBoardCalcVariables(){let{_parsedProps:e}=this;if((e.width==null||e.height==null)&&!e.outline)return{};let i=this.pcb_board_id?this.root?.db.pcb_board.get(this.pcb_board_id):null,r=i?.width??e.width,s=i?.height??e.height;if((r==null||s==null)&&e.outline?.length){let p=lo(e.outline);p&&(r??(r=p.maxX-p.minX),s??(s=p.maxY-p.minY))}let{pcbX:o,pcbY:a}=this.getResolvedPcbPositionProp(),c=i?.center??{x:o+(e.outlineOffsetX??0),y:a+(e.outlineOffsetY??0)},l=r??0,u=s??0;return{"board.minx":c.x-l/2,"board.maxx":c.x+l/2,"board.miny":c.y-u/2,"board.maxy":c.y+u/2}}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=e.pcb_board.get(this.pcb_board_id);if(r?.width&&r?.height||r?.outline&&r.outline.length>0)return;let s=1/0,o=1/0,a=-1/0,c=-1/0,l=git(e,this.subcircuit_id),u=new Set([this.subcircuit_id,...l]),p=e.pcb_component.list().filter(C=>C.subcircuit_id&&u.has(C.subcircuit_id)),d=e.pcb_group.list().filter(C=>C.subcircuit_id&&u.has(C.subcircuit_id)),_=!1,g=(C,E,R)=>{E===0||R===0||(_=!0,s=Math.min(s,C.x-E/2),o=Math.min(o,C.y-R/2),a=Math.max(a,C.x+E/2),c=Math.max(c,C.y+R/2))};for(let C of p)g(C.center,C.width,C.height);for(let C of d){let E=C.width??0,R=C.height??0;if(C.outline&&C.outline.length>0){let A=lo(C.outline);A&&(E=A.maxX-A.minX,R=A.maxY-A.minY)}g(C.center,E,R)}if(t.boardAnchorPosition){let{x:C,y:E}=t.boardAnchorPosition;s=Math.min(s,C),o=Math.min(o,E),a=Math.max(a,C),c=Math.max(c,E)}let x=2,b=_?a-s+x*2:0,S=_?c-o+x*2:0,P={x:_?(s+a)/2+(t.outlineOffsetX??0):(t.outlineOffsetX??0)+i.x,y:_?(o+c)/2+(t.outlineOffsetY??0):(t.outlineOffsetY??0)+i.y},T=t.width??b,k=t.height??S,N=t.outline;!N&&t.borderRadius!=null&&T>0&&k>0&&(N=Wnt(T,k,t.borderRadius));let M={width:T,height:k,center:P};N&&(M.outline=N.map(C=>({x:C.x+(t.outlineOffsetX??0),y:C.y+(t.outlineOffsetY??0)}))),e.pcb_board.update(this.pcb_board_id,M)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let e=this.root?.platform;if(!e?.printBoardInformationToSilkscreen)return;let t=this.root.db.pcb_board.get(this.pcb_board_id);if(!t)return;let i=[];if(e.projectName&&i.push(e.projectName),e.version&&i.push(`v${e.version}`),e.url&&i.push(e.url),i.length===0)return;let r=i.join(`
254
- `),a={x:t.center.x+t.width/2-.25,y:t.center.y-t.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:r,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:e}=this.root,t=e.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=t.source_board_id}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:e,children:t}=this._parsedProps;Tit(this,e,t)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,r=t.circuitJson?.find(_=>_.type==="pcb_board"),s=t.width??r?.width??0,o=t.height??r?.height??0,a=this._getGlobalPcbPositionBeforeLayout(),c={x:a.x+(t.outlineOffsetX??0),y:a.y+(t.outlineOffsetY??0)},{boardAnchorPosition:l,boardAnchorAlignment:u}=t;if(l&&(c=EFt({boardAnchorPosition:l,boardAnchorAlignment:u??"center",width:s,height:o})),t.outline){let _=t.outline.map(N=>N.x),g=t.outline.map(N=>N.y),x=Math.min(..._),b=Math.max(..._),S=Math.min(...g),P=Math.max(...g),T=(x+b)/2,k=(S+P)/2;s=b-x,o=P-S,c={x:T+(t.outlineOffsetX??0),y:k+(t.outlineOffsetY??0)}}let p=t.outline;!p&&t.borderRadius!=null&&s>0&&o>0&&(p=Wnt(s,o,t.borderRadius));let d=e.pcb_board.insert({center:c,thickness:this.boardThickness,num_layers:this.allLayers.length,width:s,height:o,outline:p?.map(_=>({x:_.x+(t.outlineOffsetX??0),y:_.y+(t.outlineOffsetY??0)})),material:t.material});this.pcb_board_id=d.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let t=Gtt(e.toArray());for(let u of t)e.pcb_trace_error.insert(u);let i=Vtt(e.toArray());for(let u of i)e.pcb_port_not_connected_error.insert(u);let r=qtt(e.toArray());for(let u of r)e.pcb_component_outside_board_error.insert(u);let s=Jtt(e.toArray());for(let u of s)e.pcb_trace_error.insert(u);let o=Ktt(e.toArray());for(let u of o)e.pcb_via_clearance_error.insert(u);let a=Ztt(e.toArray());for(let u of a)e.pcb_via_clearance_error.insert(u);let c=Qtt(e.toArray());for(let u of c)e.pcb_footprint_overlap_error.insert(u);let l=tet(e.toArray());for(let u of l)e.source_pin_must_be_connected_error.insert(u)}_emitRenderLifecycleEvent(e,t){super._emitRenderLifecycleEvent(e,t),t==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e})}_repositionOnPcb(e){if(super._repositionOnPcb(e),this.pcb_board_id){let{db:t}=this.root,i=t.pcb_board.get(this.pcb_board_id);if(i?.center&&i.outline){let r=e.x-i.center.x,s=e.y-i.center.y,o=i.outline.map(a=>({x:a.x+r,y:a.y+s}));t.pcb_board.update(this.pcb_board_id,{outline:o})}}}},$zt=5,Hnt=2,Dzt=(n,e)=>{let{gapLength:t,cutoutWidth:i,mouseBites:r,mouseBiteHoleDiameter:s,mouseBiteHoleSpacing:o}=e,a=[],c=[];if(n.length<2)return{tabCutouts:a,mouseBiteHoles:c};let l=new Od(n.map(p=>Da(p.x,p.y))),u;if(n.length>2){let p=Da(n[0].x,n[0].y),d=Da(n[1].x,n[1].y),_=Rd(p,d).normalize(),g=_.rotate(Math.PI/2),b=p.translate(_.multiply(Yw(p,d).length/2)).translate(g.multiply(.01));u=l.contains(b)}else u=l.area()>0;for(let p=0;p<n.length;p++){let d=n[p],_=n[(p+1)%n.length];if(!d||!_)continue;let g=Da(d.x,d.y),x=Da(_.x,_.y),b=Yw(g,x),S=b.length;if(S<1e-6)continue;let P=Rd(g,x),T=P.normalize(),k=T.rotate(Math.PI/2),M=b.middle().translate(k.multiply(.01));l.contains(M)&&(k=k.multiply(-1));let C=2,E=C*s+(C-1)*o,R;r?R=E:R=t,R=Math.min(R,S*.9);let A=(S-R)/2,j=A+R;if(r){let dt=s+o;if(R>=E&&dt>0){let G=(R-E)/2+s/2,nt=A+G;for(let J=0;J<C;J++){let pt=nt+J*dt,ut=g.translate(T.multiply(pt));c.push({x:ut.x,y:ut.y})}}}let D=n[(p-1+n.length)%n.length],Y=n[(p+2)%n.length],X=0,W=0;if(D&&Y){let G=Rd(Da(D.x,D.y),g).cross(P),nt=u?G>1e-9:G<-1e-9,J=Rd(x,Da(Y.x,Y.y)),pt=P.cross(J),ut=u?pt>1e-9:pt<-1e-9;X=nt?i:0,W=ut?i:0}let et=[{start:0-X,end:A},{start:j,end:S+W}],H=k.multiply(i);for(let dt of et){let G=dt.end-dt.start;if(G<1e-6)continue;let J=g.translate(T.multiply(dt.start+G/2)).translate(H.multiply(.5)),pt=G,ut=i,wt=T.slope*180/Math.PI;a.push({type:"pcb_cutout",shape:"rect",center:{x:J.x,y:J.y},width:pt,height:ut,rotation:wt,corner_radius:i/2})}}return{tabCutouts:a,mouseBiteHoles:c}};function jzt(n,e){let t=[],i=[],{tabWidth:r,tabLength:s,mouseBites:o}=e,a=n.map(p=>{if((!p.outline||p.outline.length===0)&&p.width&&p.height){let d=p.width/2,_=p.height/2;return{...p,outline:[{x:p.center.x-d,y:p.center.y-_},{x:p.center.x+d,y:p.center.y-_},{x:p.center.x+d,y:p.center.y+_},{x:p.center.x-d,y:p.center.y+_}]}}return p});for(let p of a)if(p.outline&&p.outline.length>0){let d=r*.45,_=d*.1,g=Dzt(p.outline,{gapLength:s,cutoutWidth:r,mouseBites:o,mouseBiteHoleDiameter:d,mouseBiteHoleSpacing:_});t.push(...g.tabCutouts),i.push(...g.mouseBiteHoles)}let c=t.map((p,d)=>({...p,pcb_cutout_id:`panel_tab_${d}`})),l=r*.45,u=i.map((p,d)=>({type:"pcb_hole",pcb_hole_id:`panel_mouse_bite_${d}`,hole_shape:"circle",hole_diameter:l,x:p.x,y:p.y}));return{tabCutouts:c,mouseBiteHoles:u}}var Bzt=({boards:n,db:e,row:t,col:i,cellWidth:r,cellHeight:s,boardGap:o})=>{let a=n.map(C=>{let E=e.pcb_board.get(C.pcb_board_id);return!E||E.width===void 0||E.height===void 0?null:{board:C,width:E.width,height:E.height}}).filter(C=>C!==null);if(a.length===0)return{positions:[],gridWidth:0,gridHeight:0};let c=t,u=i??Math.ceil(c?a.length/c:Math.sqrt(a.length)),p=c??Math.ceil(a.length/u),d=Array(u).fill(0),_=Array(p).fill(0);a.forEach((C,E)=>{let R=E%u,A=Math.floor(E/u);A<_.length&&C.height>_[A]&&(_[A]=C.height),R<d.length&&C.width>d[R]&&(d[R]=C.width)});let g=r?V.parse(r):0,x=s?V.parse(s):0;for(let C=0;C<d.length;C++)d[C]=Math.max(d[C],g);for(let C=0;C<_.length;C++)_[C]=Math.max(_[C],x);let b=d.reduce((C,E)=>C+E,0)+(u>1?(u-1)*o:0),S=_.reduce((C,E)=>C+E,0)+(p>1?(p-1)*o:0),P=-b/2,k=[-S/2];for(let C=1;C<p;C++)k.push(k[C-1]+_[C-1]+o);let N=[P];for(let C=1;C<u;C++)N.push(N[C-1]+d[C-1]+o);let M=[];return a.forEach((C,E)=>{let R=E%u,A=Math.floor(E/u);if(A>=k.length||R>=N.length)return;let j=N[R],D=k[A],Y=d[R],X=_[A],W=j+Y/2,et=D+X/2;M.push({board:C.board,pos:{x:W,y:et}})}),{positions:M,gridWidth:b,gridHeight:S}},Mit=class extends Tl{constructor(){super(...arguments);f(this,"pcb_panel_id",null);f(this,"_tabsAndMouseBitesGenerated",!1)}get config(){return{componentName:"Panel",zodProps:hH}}get isGroup(){return!0}get isSubcircuit(){return!0}add(e){if(e.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(e)}doInitialPanelLayout(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.children.filter(a=>a instanceof TP),i=t.some(a=>a.props.pcbX!==void 0||a.props.pcbY!==void 0),r=t.filter(a=>a.props.pcbX===void 0&&a.props.pcbY===void 0);if(r.length>0&&!i){let a=this._parsedProps.tabWidth??Hnt,c=this._parsedProps.boardGap??a,{positions:l,gridWidth:u,gridHeight:p}=Bzt({boards:r,db:e,row:this._parsedProps.row,col:this._parsedProps.col,cellWidth:this._parsedProps.cellWidth,cellHeight:this._parsedProps.cellHeight,boardGap:c}),d=this._getGlobalPcbPositionBeforeLayout();for(let{board:x,pos:b}of l){let S=d.x+b.x,P=d.y+b.y;x._repositionOnPcb({x:S,y:P}),e.pcb_board.update(x.pcb_board_id,{center:{x:S,y:P}})}let _=this._parsedProps.width!==void 0,g=this._parsedProps.height!==void 0;if(_&&g)e.pcb_panel.update(this.pcb_panel_id,{width:V.parse(this._parsedProps.width),height:V.parse(this._parsedProps.height)});else if(u>0||p>0){let{edgePadding:x,edgePaddingLeft:b,edgePaddingRight:S,edgePaddingTop:P,edgePaddingBottom:T}=this._parsedProps,k=V.parse(x??5),N=V.parse(b??k),M=V.parse(S??k),C=V.parse(P??k),E=V.parse(T??k);e.pcb_panel.update(this.pcb_panel_id,{width:_?V.parse(this._parsedProps.width):u+N+M,height:g?V.parse(this._parsedProps.height):p+C+E})}}if(this._tabsAndMouseBitesGenerated)return;let s=this._parsedProps;if((s.panelizationMethod??"none")!=="none"){let a=t.map(_=>_.pcb_board_id).filter(_=>!!_),c=e.pcb_board.list().filter(_=>a.includes(_.pcb_board_id));if(c.length===0)return;let l=s.tabWidth??Hnt,u=s.boardGap??l,{tabCutouts:p,mouseBiteHoles:d}=jzt(c,{boardGap:u,tabWidth:l,tabLength:s.tabLength??$zt,mouseBites:s.mouseBites??!0});for(let _ of p)e.pcb_cutout.insert(_);for(let _ of d)e.pcb_hole.insert(_)}this._tabsAndMouseBitesGenerated=!0}runRenderCycle(){if(!this.children.some(e=>e.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}doInitialPcbComponentRender(){if(super.doInitialPcbComponentRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps,i=e.pcb_panel.insert({width:t.width!==void 0?V.parse(t.width):0,height:t.height!==void 0?V.parse(t.height):0,center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(t.noSolderMask??!1)});this.pcb_panel_id=i.pcb_panel_id}updatePcbComponentRender(){if(this.root?.pcbDisabled||!this.pcb_panel_id)return;let{db:e}=this.root,t=this._parsedProps,i=e.pcb_panel.get(this.pcb_panel_id);e.pcb_panel.update(this.pcb_panel_id,{width:t.width!==void 0?V.parse(t.width):i?.width,height:t.height!==void 0?V.parse(t.height):i?.height,center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(t.noSolderMask??!1)})}removePcbComponentRender(){this.pcb_panel_id&&(this.root?.db.pcb_panel.delete(this.pcb_panel_id),this.pcb_panel_id=null)}},Eit=class extends n0{constructor(n){super(n)}get config(){return{...super.config,componentName:"Pinout",zodProps:dH}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=t.source_component_id}},Cit=class extends Yn{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:_H,sourceFtype:qa.simple_fuse}}_getSchematicSymbolDisplayValue(){let n=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,t=typeof n=="string"?parseFloat(n):n,i=typeof e=="string"?parseFloat(e):e;return`${ei(t)}A / ${ei(i)}V`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=typeof e.currentRating=="string"?parseFloat(e.currentRating):e.currentRating,i=typeof e.voltageRating=="string"?parseFloat(e.voltageRating):e.voltageRating,r=n.source_component.insert({name:this.name,ftype:qa.simple_fuse,current_rating_amps:t,voltage_rating_volts:i,display_current_rating:`${ei(t)}A`,display_voltage_rating:`${ei(i)}V`});this.source_component_id=r.source_component_id}},Iit=class extends Yn{constructor(){super(...arguments);f(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:O4,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let t=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"?t:0,rightSize:i==="right"?t:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.pcb_component.insert({center:{x:i,y:r},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let o=0;o<t.length;o++){let a=t[o],c=e.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(p=>/^(pin)?\d+$/.test(p));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),s=o=>{if(o&&typeof o=="string"&&o.startsWith("{PIN")){let a=o.replace("{PIN","").replace("}","");return i[a]||o}return o};for(let o of r)if(o.route)for(let a of o.route)a.route_type==="wire"&&(a.start_pcb_port_id=s(a.start_pcb_port_id),a.end_pcb_port_id=s(a.end_pcb_port_id))}},qnt={"0402":"0402","0603":"0603","0805":"0805",1206:"1206"},Nit=class extends Yn{get config(){return{componentName:"Interconnect",zodProps:mH,shouldRenderAsSchematicBox:!0,sourceFtype:"interconnect"}}get defaultInternallyConnectedPinNames(){let{standard:n}=this._parsedProps;return n&&qnt[n]?[["pin1","pin2"]]:[]}_getImpliedFootprintString(){let{standard:n}=this._parsedProps;return n?qnt[n]??null:null}doInitialSourceRender(){let{db:n}=this.root,e=n.source_component.insert({ftype:"interconnect",name:this.name,are_pins_interchangeable:!0});this.source_component_id=e.source_component_id}doInitialSourceParentAttachment(){let{db:n}=this.root,e=this._getInternallyConnectedPins();for(let t of e){let i=t.map(r=>r.source_port_id).filter(r=>r!==null);i.length>=2&&n.source_component_internal_connection.insert({source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id,source_port_ids:i})}}},Ait=class extends Yn{constructor(){super(...arguments);f(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(e){return this.selectOne(`port.${e}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let e=this.children.filter(t=>t.componentName==="Port").map(t=>t.name);return e.length>0?[e]:[]}return this._parsedProps.bridgedPins??[]}get config(){let e=this._parsedProps??this.props,t=e.pinCount;if(e.pinCount==null&&!e.footprint&&(t=2),e.pinCount==null){let s=(e.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),o=s.length>0?Math.max(...s):0,a=e.pinLabels?Object.keys(e.pinLabels).length:0,c=Math.max(o,a);(c===2||c===3)&&(t=c),t==null&&e.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(t=this.getPortsFromFootprint().length)}let i="";t?i+=`solderjumper${t}`:i="solderjumper";let r=[];return Array.isArray(e.bridgedPins)&&e.bridgedPins.length>0?r=Array.from(new Set(e.bridgedPins.flat().map(s=>this._getPinNumberFromBridgedPinName(s)).filter(s=>s!==null))).sort((s,o)=>s-o):e.bridged&&t&&(r=Array.from({length:t},(s,o)=>o+1)),r.length>0&&(i+=`_bridged${r.join("")}`),{schematicSymbolName:e.symbolName??i,componentName:"SolderJumper",zodProps:fH,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let t=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);t==null&&!this._parsedProps.footprint&&(t=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?t:0,rightSize:i==="right"?t:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.pcb_component.insert({center:{x:i,y:r},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let o=0;o<t.length;o++){let a=t[o],c=e.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(p=>/^(pin)?\d+$/.test(p));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),s=o=>{if(o&&typeof o=="string"&&o.startsWith("{PIN")){let a=o.replace("{PIN","").replace("}","");return i[a]||o}return o};for(let o of r)if(o.route)for(let a of o.route)a.route_type==="wire"&&(a.start_pcb_port_id=s(a.start_pcb_port_id),a.end_pcb_port_id=s(a.end_pcb_port_id))}},Rit=class extends Yn{constructor(){super(...arguments);f(this,"pos",this.portMap.pin1);f(this,"anode",this.portMap.pin1);f(this,"neg",this.portMap.pin2);f(this,"cathode",this.portMap.pin2)}get config(){let e={laser:"laser_diode"},t=this.props.laser?"laser":null;return{schematicSymbolName:t?e[t]:this.props.symbolName??"led",componentName:"Led",zodProps:YH,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 e=super.getFootprinterString();return e&&this.props.color?`${e}_color(${this.props.color})`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_led",name:this.name,wave_length:t.wavelength,color:t.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},Oit=class extends Yn{constructor(){super(...arguments);f(this,"pos",this.portMap.pin1);f(this,"positive",this.portMap.pin1);f(this,"neg",this.portMap.pin2);f(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:nq,sourceFtype:"simple_power_source"}}initPorts(){this.add(new qi({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new qi({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:t.voltage,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},Lit=class extends Yn{constructor(){super(...arguments);f(this,"terminal1",this.portMap.terminal1);f(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:iq,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(e){if(!e.startsWith("Pcb"))for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}_getSchematicSymbolDisplayValue(){let{voltage:e,frequency:t}=this._parsedProps,i=[];return e!==void 0&&i.push(`${ei(e)}V`),t!==void 0&&i.push(`${ei(t)}Hz`),i.length>0?i.join(" "):void 0}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:t.voltage,frequency:t.frequency,peak_to_peak_voltage:t.peakToPeakVoltage,wave_shape:t.waveShape,phase:t.phase,duty_cycle:t.dutyCycle,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.portMap.terminal1,r=this.portMap.terminal2;e.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:r.source_port_id,voltage:t.voltage,frequency:t.frequency,peak_to_peak_voltage:t.peakToPeakVoltage,wave_shape:t.waveShape,phase:t.phase,duty_cycle:t.dutyCycle})}},Yzt=["leftedge","rightedge","topedge","bottomedge","center"],Fit=class extends Ce{get config(){return{componentName:"Constraint",zodProps:kH}}constructor(n){if(super(n),("xdist"in n||"ydist"in n)&&!("edgeToEdge"in n)&&!("centerToCenter"in n))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in n&&n.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let n=[],e=this.getPrimitiveContainer();function t(i){let r=i.split(" ").pop(),s=Yzt.includes(r)?r:void 0,o=s?i.replace(` ${s}`,""):i,a=e.selectOne(o,{pcbPrimitive:!0});a&&n.push({selector:i,component:a,componentSelector:o,edge:s})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&t(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)t(i);return{componentsWithSelectors:n}}},zit=class extends Ce{constructor(){super(...arguments);f(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:GH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),o=s(t.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for FabricationNoteRect. Must be "top" or "bottom".`);let a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=this.getSubcircuit(),l=t.hasStroke??(t.strokeWidth!==void 0&&t.strokeWidth!==null),u=e.pcb_fabrication_note_rect.insert({pcb_component_id:a,layer:o,color:t.color,center:{x:i,y:r},width:t.width,height:t.height,stroke_width:t.strokeWidth??1,is_filled:t.isFilled??!1,has_stroke:l,is_stroke_dashed:t.isStrokeDashed??!1,subcircuit_id:c?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,corner_radius:t.cornerRadius??void 0});this.fabrication_note_rect_id=u.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},$it=class extends Ce{constructor(){super(...arguments);f(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:WH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.getSubcircuit(),{_parsedProps:i}=this,r=i.layer??"top";if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let s=this._computePcbGlobalTransformBeforeLayout(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_fabrication_note_path.insert({pcb_component_id:o,layer:r,color:i.color,route:i.route.map(c=>{let l=je(s,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:t?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},Dit=class extends Ce{get config(){return{componentName:"FabricationNoteText",zodProps:VH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:n}=this.root,{_parsedProps:e}=this,{pcbX:t,pcbY:i}=this.getResolvedPcbPositionProp(),r=this.getPrimitiveContainer(),s=this.getSubcircuit();n.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:t,y:i},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:vP(e.text??""),pcb_component_id:r.pcb_component_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},jit=class extends Ce{constructor(){super(...arguments);f(this,"fabrication_note_dimension_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:HH}}_resolvePoint(e,t){if(typeof e=="string"){let s=this.getSubcircuit().selectOne(e);return s?s._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${e}"`),je(t,{x:0,y:0}))}let i=typeof e.x=="string"?parseFloat(e.x):e.x,r=typeof e.y=="string"?parseFloat(e.y):e.y;return je(t,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(t.from,i),s=this._resolvePoint(t.to,i),o=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(t.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,p=t.text??this._formatDistanceText({from:r,to:s,units:t.units??"mm"}),d=e.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:r,to:s,text:p,offset:t.offset,font:t.font??"tscircuit2024",font_size:t.fontSize??1,color:t.color,arrow_size:t.arrowSize??1});this.fabrication_note_dimension_id=d.pcb_fabrication_note_dimension_id}getPcbSize(){let e=this._computePcbGlobalTransformBeforeLayout(),t=this._resolvePoint(this._parsedProps.from,e),i=this._resolvePoint(this._parsedProps.to,e);return{width:Math.abs(i.x-t.x),height:Math.abs(i.y-t.y)}}_formatDistanceText({from:e,to:t,units:i}){let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s),a=i==="in"?o/25.4:o,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}`}},Bit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_note_line_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:wq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this.getGroup(),s=this._computePcbGlobalTransformBeforeLayout(),o=je(s,{x:t.x1,y:t.y1}),a=je(s,{x:t.x2,y:t.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=e.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,x1:o.x,y1:o.y,x2:a.x,y2:a.y,stroke_width:t.strokeWidth??.1,color:t.color,is_dashed:t.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:e}=this;return{width:Math.abs(e.x2-e.x1),height:Math.abs(e.y2-e.y1)}}},Yit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_note_rect_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:vq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=je(i,{x:0,y:0}),s=this.getSubcircuit(),o=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=e.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,center:r,width:t.width,height:t.height,stroke_width:t.strokeWidth??.1,is_filled:t.isFilled??!1,has_stroke:t.hasStroke??!0,is_stroke_dashed:t.isStrokeDashed??!1,color:t.color,corner_radius:t.cornerRadius??void 0});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:e}=this,t=typeof e.width=="string"?parseFloat(e.width):e.width,i=typeof e.height=="string"?parseFloat(e.height):e.height;return{width:t,height:i}}},Xit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_note_text_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:bq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=je(i,{x:0,y:0}),s=this.getSubcircuit(),o=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=e.pcb_note_text.insert({pcb_component_id:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,font:t.font??"tscircuit2024",font_size:t.fontSize??1,text:vP(t.text),anchor_position:r,anchor_alignment:t.anchorAlignment??"center",color:t.color});this.pcb_note_text_id=c.pcb_note_text_id}getPcbSize(){let{_parsedProps:e}=this,t=typeof e.fontSize=="string"?parseFloat(e.fontSize):e.fontSize??1,i=t*.6;return{width:e.text.length*i,height:t}}},Uit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_note_path_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:Sq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this.getSubcircuit(),s=this.getGroup(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=t.route.map(l=>{let{x:u,y:p,...d}=l,_=typeof u=="string"?parseFloat(u):u,g=typeof p=="string"?parseFloat(p):p,x=je(i,{x:_,y:g});return{...d,x:x.x,y:x.y}}),c=e.pcb_note_path.insert({pcb_component_id:o,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,route:a,stroke_width:t.strokeWidth??.1,color:t.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:e}=this;if(e.route.length===0)return{width:0,height:0};let t=e.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=e.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),r=Math.min(...t),s=Math.max(...t),o=Math.min(...i),a=Math.max(...i);return{width:s-r,height:a-o}}},Vit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_note_dimension_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:Pq}}_resolvePoint(e,t){if(typeof e=="string"){let s=this.getSubcircuit().selectOne(`.${e}`);return s?s._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${e}"`),je(t,{x:0,y:0}))}let i=typeof e.x=="string"?parseFloat(e.x):e.x,r=typeof e.y=="string"?parseFloat(e.y):e.y;return je(t,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(t.from,i),s=this._resolvePoint(t.to,i),o=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.text??this._formatDistanceText({from:r,to:s,units:t.units??"mm"}),u=e.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:r,to:s,text:l,font:t.font??"tscircuit2024",font_size:t.fontSize??1,color:t.color,arrow_size:t.arrowSize??1});this.pcb_note_dimension_id=u.pcb_note_dimension_id}getPcbSize(){let e=this._computePcbGlobalTransformBeforeLayout(),t=this._resolvePoint(this._parsedProps.from,e),i=this._resolvePoint(this._parsedProps.to,e);return{width:Math.abs(i.x-t.x),height:Math.abs(i.y-t.y)}}_formatDistanceText({from:e,to:t,units:i}){let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s),a=i==="in"?o/25.4:o,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}`}},Git=class extends Tl{constructor(n){super({...n,subcircuit:!0})}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:n,children:e}=this._parsedProps;Tit(this,n,e)}},Wit=class extends Tl{constructor(n){super({...n,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:n}=this.root,e=this._parsedProps;if(!this.pcb_group_id)return;let t=n.pcb_group.get(this.pcb_group_id),i=e.paddingLeft??e.padding??0,r=e.paddingRight??e.padding??0,s=e.paddingTop??e.padding??0,o=e.paddingBottom??e.padding??0;n.pcb_group.update(this.pcb_group_id,{width:(t.width??0)+i+r,height:(t.height??0)+s+o,center:{x:t.center.x+(r-i)/2,y:t.center.y+(s-o)/2}})}},Hit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_breakout_point_id",null);f(this,"matchedPort",null);f(this,"matchedNet",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:KH}}_matchConnection(){let{connection:e}=this._parsedProps,t=this.getSubcircuit();t&&(this.matchedPort=t.selectOne(e,{type:"port"}),this.matchedPort||(this.matchedNet=t.selectOne(e,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${e}"`))}_getSourceTraceIdForPort(e){let{db:t}=this.root;return t.source_trace.list().find(r=>r.connected_source_port_ids.includes(e.source_port_id))?.source_trace_id}_getSourceNetIdForPort(e){let{db:t}=this.root;return t.source_trace.list().find(r=>r.connected_source_port_ids.includes(e.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;this._matchConnection();let{pcbX:t,pcbY:i}=this.getResolvedPcbPositionProp(),r=this.parent?.getGroup(),s=this.getSubcircuit();if(!r||!r.pcb_group_id)return;let o=e.pcb_breakout_point.insert({pcb_group_id:r.pcb_group_id,subcircuit_id:s?.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:t,y:i});this.pcb_breakout_point_id=o.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:e,pcbY:t}=this.getResolvedPcbPositionProp();return{center:{x:e,y:t},bounds:{left:e,top:t,right:e,bottom:t},width:0,height:0}}_setPositionFromLayout(e){let{db:t}=this.root;this.pcb_breakout_point_id&&t.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:e.x,y:e.y})}getPcbSize(){return{width:0,height:0}}},qit=class extends Ce{constructor(){super(...arguments);f(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:OH}}_getAnchorSide(){let{_parsedProps:e}=this;if(e.anchorSide)return e.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";let s=r[0]._getGlobalSchematicPositionBeforeLayout(),o=s.x-i.x,a=s.y-i.y;if(Math.abs(o)>Math.abs(a)){if(o>0)return"right";if(o<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let e=this._resolveConnectsTo();if(!e)return[];let t=[];for(let i of e){let r=this.getSubcircuit().selectOne(i);r&&t.push(r)}return t}computeSchematicPropsTransform(){let{_parsedProps:e}=this;if(e.schX===void 0&&e.schY===void 0){let t=this._getConnectedPorts();if(t.length>0){let i=t[0]._getGlobalSchematicPositionBeforeLayout(),r=je(this.parent?.computeSchematicGlobalTransform?.()??Pr(),{x:0,y:0});return Tn(i.x-r.x,i.y-r.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),s=t.anchorSide??"right",o=kl({anchor_position:i,anchor_side:s,text:t.net}),a=e.schematic_net_label.insert({text:t.net,source_net_id:r.source_net_id,anchor_position:i,center:o,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:e}=this,t=e.connectsTo??e.connection;if(Array.isArray(t))return t;if(typeof t=="string")return[t]}_getNetName(){let{_parsedProps:e}=this;return e.net}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;e.net&&bP(this,[`net.${e.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let e=this._resolveConnectsTo();if(e)for(let t of e)this.add(new Ds({from:t,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:e}=this.root,t=this._resolveConnectsTo();if(!t||t.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),o={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of t){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let S=e.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id??""));if(S&&(u=e.schematic_trace.list().some(P=>P.source_trace_id===S.source_trace_id)),u)continue}let p=l._getGlobalSchematicPositionAfterLayout(),d=O9(l.facingDirection??"right")??"x+",_=tl({x:p.x,y:p.y,facingDirection:d},{x:i.x,y:i.y,facingDirection:o});if(!Array.isArray(_)||_.length<2)continue;let g=[];for(let S=0;S<_.length-1;S++)g.push({from:{x:_[S].x,y:_[S].y},to:{x:_[S+1].x,y:_[S+1].y}});let x,b;if(a?.source_net_id&&l.source_port_id){let S=e.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id));x=S?.source_trace_id,b=S?.subcircuit_connectivity_map_key||e.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}e.schematic_trace.insert({source_trace_id:x,edges:g,junctions:[],subcircuit_connectivity_map_key:b}),e.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},Zit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_silkscreen_circle_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:gq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),o=s(t.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenCircle. Must be "top" or "bottom".`);let a=this._computePcbGlobalTransformBeforeLayout(),c=this.getSubcircuit(),l=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,u=e.pcb_silkscreen_circle.insert({pcb_component_id:l,layer:o,center:{x:i,y:r},radius:t.radius,subcircuit_id:c?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_circle_id=u.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:e}=this,t=e.radius*2;return{width:t,height:t}}},Kit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_silkscreen_rect_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:yq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenRect. Must be "top" or "bottom".`);let s=this.getSubcircuit(),{pcbX:o,pcbY:a}=this.getResolvedPcbPositionProp(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,l=e.pcb_silkscreen_rect.insert({pcb_component_id:c,layer:r,center:{x:o,y:a},width:t.width,height:t.height,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:t.strokeWidth??.1,is_filled:t.filled??!1,corner_radius:t.cornerRadius??void 0});this.pcb_silkscreen_rect_id=l.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},Jit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_silkscreen_line_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:_q}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenLine. Must be "top" or "bottom".`);let s=this.getSubcircuit(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_silkscreen_line.insert({pcb_component_id:o,layer:r,x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,stroke_width:t.strokeWidth??.1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:s?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:e}=this,t=Math.abs(e.x2-e.x1),i=Math.abs(e.y2-e.y1);return{width:t,height:i}}},Qit=class extends Ce{constructor(e){super(e);f(this,"pcb_via_id",null);f(this,"matchedPort",null);f(this,"isPcbPrimitive",!0);f(this,"source_manually_placed_via_id",null);f(this,"subcircuit_connectivity_map_key",null);let t=this._getLayers();this._parsedProps.layers=t,this.initPorts()}get config(){return{componentName:"Via",zodProps:qH}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}_getResolvedViaDiameters(e){return lFt({holeDiameter:this._parsedProps.holeDiameter,padDiameter:this._parsedProps.outerDiameter},e)}getPcbSize(){let e=this.getInheritedMergedProperty("pcbStyle"),{padDiameter:t}=this._getResolvedViaDiameters(e);return{width:t,height:t}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-i.width/2,top:t.y-i.height/2,right:t.x+i.width/2,bottom:t.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}_getLayers(){let{fromLayer:e="top",toLayer:t="bottom"}=this._parsedProps;return e===t?[e]:[e,t]}initPorts(){let e=this._parsedProps.layers;for(let i of e){let r=new qi({name:i,layer:i});r.registerMatch(this),this.add(r)}let t=new qi({name:"pin1"});t.registerMatch(this),this.add(t)}_getConnectedNetOrTrace(){let e=this._parsedProps.connectsTo;if(!e)return null;let t=this.getSubcircuit(),i=Array.isArray(e)?e:[e];for(let r of i)if(r.startsWith("net.")){let s=t.selectOne(r,{type:"net"});if(s)return s}return null}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.getInheritedMergedProperty("pcbStyle"),{padDiameter:i}=this._getResolvedViaDiameters(t),r=this._getGlobalPcbPositionBeforeLayout(),s=this.getSubcircuit(),o=e.pcb_component.insert({center:r,width:i,height:i,layer:this._parsedProps.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:s?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=o.pcb_component_id}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.getGroup(),r=this.getSubcircuit(),s=e.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:t.net??"",subcircuit_id:r?.subcircuit_id??void 0});this.source_component_id=s.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.getInheritedMergedProperty("pcbStyle"),{holeDiameter:i,padDiameter:r}=this._getResolvedViaDiameters(t),s=this._getGlobalPcbPositionBeforeLayout(),o=this.getSubcircuit(),a=e.pcb_via.insert({x:s.x,y:s.y,hole_diameter:i,outer_diameter:r,layers:["bottom","top"],from_layer:this._parsedProps.fromLayer||"bottom",to_layer:this._parsedProps.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:this._parsedProps.netIsAssignable??void 0});this.pcb_via_id=a.pcb_via_id}},trt=class extends Ce{constructor(){super(...arguments);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:QH}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;bP(this,[e.connectsTo])}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit().selectOne(t.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${t.connectsTo}" not found for copper pour`);return}let r=this.getSubcircuit(),s=e.toArray().filter(p=>p.type==="source_net"&&p.name===i.name)[0]||"",o=t.clearance??.2,a=iet(e.toArray(),{layer:t.layer,pour_connectivity_key:s.subcircuit_connectivity_map_key||"",pad_margin:t.padMargin??o,trace_margin:t.traceMargin??o,board_edge_margin:t.boardEdgeMargin??o,cutout_margin:t.cutoutMargin??o}),c=new net(a),{brep_shapes:l}=c.getOutput(),u=t.coveredWithSolderMask??!1;for(let p of l)e.pcb_copper_pour.insert({shape:"brep",layer:t.layer,brep_shape:p,source_net_id:i.source_net_id,subcircuit_id:r?.subcircuit_id??void 0,covered_with_solder_mask:u})})}},ert=class extends Yn{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:AH,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=t.source_component_id}},nrt=class extends Yn{_getPcbRotationBeforeLayout(){let n=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+n}get config(){return{componentName:"PinHeader",zodProps:RH,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),e=this._parsedProps.holeDiameter,t=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels,s=this._parsedProps.doubleRow?2:1;if(n>0){let o;if(i)!e&&!t?o=`pinrow${n}_p${i}`:o=`pinrow${n}_p${i}_id${e}_od${t}`;else if(!e&&!t)o=`pinrow${n}`;else return null;return r!==!0&&(o+="_nopinlabels"),s>1&&(o+=`_rows${s}`),o}return null}initPorts(){let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let e=1;e<=n;e++){let t=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[e-1]:this._parsedProps.pinLabels?.[`pin${e}`];if(t){let i=Array.isArray(t)?t[0]:t,r=Array.isArray(t)?t.slice(1):[];this.add(new qi({pinNumber:e,name:i,aliases:[`pin${e}`,...r]}))}else this.add(new qi({pinNumber:e,name:`pin${e}`}))}}_getSchematicPortArrangement(){let n=this._parsedProps.pinCount??1,e=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",t=this._parsedProps.schPinArrangement;return e==="left"?{leftSide:{direction:t?.leftSide?.direction??"top-to-bottom",pins:t?.leftSide?.pins??Array.from({length:n},(i,r)=>`pin${r+1}`)}}:{rightSide:{direction:t?.rightSide?.direction??"top-to-bottom",pins:t?.rightSide?.pins??Array.from({length:n},(i,r)=>`pin${r+1}`)}}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}};function Xzt(n){switch(n){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var irt=class extends Yn{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??Xzt(this.props.pinVariant),zodProps:SH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"no_ground",i=n.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:t,are_pins_interchangeable:t==="no_ground"||t==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let n=`${ei(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${ei(this._parsedProps.loadCapacitance)}F`:n}};function Uzt(n){switch(n){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var rrt=class extends Yn{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??Uzt(this.props.pinVariant),zodProps:bH,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${ei(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"two_pin",i=n.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:e.maxResistance,pin_variant:t,are_pins_interchangeable:t==="two_pin"});this.source_component_id=i.source_component_id}},srt=class extends Yn{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:LH,sourceFtype:qa.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let n=bi[this._getSchematicSymbolNameOrThrow()],e=n.ports.find(l=>l.labels.includes("1")),t=n.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),r=i.find(l=>l.props.pinNumber===1),s=i.find(l=>l.props.pinNumber===2),o=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;r.schematicSymbolPortDef=e,(!c||c.length===0)&&(s.schematicSymbolPortDef=t);for(let[l,u]of[[2,s],[3,o],[4,a]]){let p=c?.find(([_,g])=>_===`pin${l}`||g===`pin${l}`);if(!p){u.schematicSymbolPortDef=t;break}(p?.[0]===`pin${l}`?p[1]:p?.[0])!=="pin1"&&(u.schematicSymbolPortDef=t)}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:qa.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},ort=class extends Yn{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:vH,sourceFtype:"simple_crystal"}}initPorts(){let n=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:n})}_getSchematicSymbolDisplayValue(){let n=`${ei(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${ei(this._parsedProps.loadCapacitance)}F`:n}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin",are_pins_interchangeable:(e.pinVariant||"two_pin")==="two_pin"});this.source_component_id=t.source_component_id}},art=class extends Yn{get config(){let n=this.props.mosfetMode==="depletion"?"d":"e",t=`${this.props.channelType}_channel_${n}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??t,zodProps:$H,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=t.source_component_id}};function Vzt(n){return n.simSwitchFrequency!==void 0||n.simCloseAt!==void 0||n.simOpenAt!==void 0||n.simStartClosed!==void 0||n.simStartOpen!==void 0}var crt=class extends Yn{_getSwitchType(){let n=this._parsedProps;return n?n.dpdt?"dpdt":n.spst?"spst":n.spdt?"spdt":n.dpst?"dpst":n.type??"spst":"spst"}get config(){let n=this._getSwitchType(),e=this._parsedProps?.isNormallyClosed??!1,t={spst:e?"spst_normally_closed_switch":"spst_switch",spdt:e?"spdt_normally_closed_switch":"spdt_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??t[n],zodProps:UH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,e=this._parsedProps??{},t=n.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=t.source_component_id}doInitialSimulationRender(){let{_parsedProps:n}=this;if(!Vzt(n))return;let{db:e}=this.root,t={type:"simulation_switch",source_component_id:this.source_component_id||""};n.simSwitchFrequency!==void 0&&(t.switching_frequency=$r.parse(n.simSwitchFrequency)),n.simCloseAt!==void 0&&(t.closes_at=hr.parse(n.simCloseAt)),n.simOpenAt!==void 0&&(t.opens_at=hr.parse(n.simOpenAt)),n.simStartOpen!==void 0&&(t.starts_closed=!n.simStartOpen),n.simStartClosed!==void 0&&(t.starts_closed=n.simStartClosed),e.simulation_switch.insert(t)}},N9={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},lrt=class extends Yn{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:ZH,sourceFtype:qa.simple_test_point}}_getPropsWithDefaults(){let{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}=this._parsedProps;return!t&&e&&(t="through_hole"),t??(t="through_hole"),n??(n="circle"),t==="pad"?n==="circle"?i??(i=N9.SMT_CIRCLE_DIAMETER):n==="rect"&&(r??(r=N9.SMT_RECT_SIZE),s??(s=r)):t==="through_hole"&&(e??(e=N9.HOLE_DIAMETER)),{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}}_getImpliedFootprintString(){let{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}=this._getPropsWithDefaults();if(t==="through_hole")return`platedhole_d${e}`;if(t==="pad"){if(n==="circle")return`smtpad_circle_d${i}`;if(n==="rect")return`smtpad_rect_w${r}_h${s}`}throw new Error(`Footprint variant "${t}" with pad shape "${n}" not implemented`)}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,{padShape:t,holeDiameter:i,footprintVariant:r,padDiameter:s,width:o,height:a}=this._getPropsWithDefaults(),c=n.source_component.insert({ftype:qa.simple_test_point,name:this.name,supplier_part_numbers:e.supplierPartNumbers,footprint_variant:r,pad_shape:t,pad_diameter:s,hole_diameter:i,width:o,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},urt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:uq}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout();e.schematic_text.insert({anchor:t.anchor??"center",text:vP(t.text),font_size:t.fontSize,color:t.color||"#000000",position:{x:i.x,y:i.y},rotation:t.schRotation??0})}},prt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:lq}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_line.insert({schematic_component_id:r,x1:t.x1+i.x,y1:t.y1+i.y,x2:t.x2+i.x,y2:t.y2+i.y,stroke_width:t.strokeWidth??kP,color:t.color??PP,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=s.schematic_line_id}},hrt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:cq}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_rect.insert({center:{x:i.x,y:i.y},width:t.width,height:t.height,stroke_width:t.strokeWidth??kP,color:t.color??PP,is_filled:t.isFilled,schematic_component_id:r,is_dashed:t.isDashed,rotation:t.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=s.schematic_rect_id}},drt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:sq}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_arc.insert({schematic_component_id:r,center:{x:t.center.x+i.x,y:t.center.y+i.y},radius:t.radius,start_angle_degrees:t.startAngleDegrees,end_angle_degrees:t.endAngleDegrees,direction:t.direction,stroke_width:t.strokeWidth??kP,color:t.color??PP,is_dashed:t.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=s.schematic_arc_id}},frt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:aq}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_circle.insert({schematic_component_id:r,center:{x:t.center.x+i.x,y:t.center.y+i.y},radius:t.radius,stroke_width:t.strokeWidth??kP,color:t.color??PP,is_filled:t.isFilled,fill_color:t.fillColor,is_dashed:t.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=s.schematic_circle_id}};function Gzt({anchor:n,x:e,y:t,width:i,height:r,isInside:s}){switch(n){case"top_left":return{x:e,y:t+r,textAnchor:s?"top_left":"bottom_left"};case"top_center":return{x:e+i/2,y:t+r,textAnchor:s?"top_center":"bottom_center"};case"top_right":return{x:e+i,y:t+r,textAnchor:s?"top_right":"bottom_right"};case"center_left":return{x:e,y:t+r/2,textAnchor:s?"center_left":"center_right"};case"center":return{x:e+i/2,y:t+r/2,textAnchor:"center"};case"center_right":return{x:e+i,y:t+r/2,textAnchor:s?"center_right":"center_left"};case"bottom_left":return{x:e,y:t,textAnchor:s?"bottom_left":"top_left"};case"bottom_center":return{x:e+i/2,y:t,textAnchor:s?"bottom_center":"top_center"};case"bottom_right":return{x:e+i,y:t,textAnchor:s?"bottom_right":"top_right"};default:return{x:e+i/2,y:t+r,textAnchor:"center"}}}var mrt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:oq,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=.6,r=typeof t.padding=="number"?t.padding:0,s=typeof t.paddingTop=="number"?t.paddingTop:r,o=typeof t.paddingBottom=="number"?t.paddingBottom:r,a=typeof t.paddingLeft=="number"?t.paddingLeft:r,c=typeof t.paddingRight=="number"?t.paddingRight:r,l=t.overlay&&t.overlay.length>0,u=typeof t.width=="number"&&typeof t.height=="number",p,d,_,g,x,b;if(l){let P=t.overlay.map(J=>({selector:J,port:this.getSubcircuit().selectOne(J,{type:"port"})})).filter(({port:J})=>J!=null).map(({port:J})=>({position:J._getGlobalSchematicPositionAfterLayout()}));if(P.length===0)return;let T=P.map(J=>J.position.x),k=P.map(J=>J.position.y),N=Math.min(...T),M=Math.max(...T),C=Math.min(...k),E=Math.max(...k),R=M-N,A=E-C,j=R===0?i:0,D=A===0?i:0,Y=a+j/2,X=c+j/2,W=s+D/2,et=o+D/2,H=N-Y,dt=M+X,G=C-et,nt=E+W;p=dt-H,d=nt-G,_=H+(t.schX??0),g=G+(t.schY??0),x=_+p/2,b=g+d/2}else if(u){p=t.width,d=t.height;let S=this._getGlobalSchematicPositionBeforeLayout();x=S.x,b=S.y,_=x-p/2,g=b-d/2}else return;if(e.schematic_box.insert({height:d,width:p,x:_,y:g,is_dashed:t.strokeStyle==="dashed"}),t.title){let S=t.titleInside,P=.1,T=t.titleAlignment,k=Gzt({anchor:T,x:_,y:g,width:p,height:d,isInside:S}),N,M,C=k.textAnchor;S?(N=T.includes("top")?-P:T.includes("bottom")?P:0,M=T.includes("left")?P:T.includes("right")?-P:0):(N=T.includes("top")?P:T.includes("bottom")?-P:0,M=T.includes("center_left")?-P:T.includes("center_right")?P:0);let E=k.x+M,R=k.y+N;e.schematic_text.insert({anchor:C,text:t.title,font_size:t.titleFontSize??.18,color:t.titleColor??"#000000",position:{x:E,y:R},rotation:0})}}},_rt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:pq}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.children.filter(d=>d.componentName==="SchematicRow");if(i.length===0)return;let r=[],s=0;for(let d of i){let _=d.children.filter(g=>g.componentName==="SchematicCell");s=Math.max(s,_.length)}for(let d=0;d<i.length;d++)r[d]=[];for(let d=0;d<i.length;d++){let g=i[d].children.filter(b=>b.componentName==="SchematicCell"),x=0;for(let b=0;b<g.length;b++){for(;r[d][x];)x++;let S=g[b],P=S._parsedProps.colSpan??1,T=S._parsedProps.rowSpan??1;for(let k=0;k<T;k++)for(let N=0;N<P;N++)r[d+k]||(r[d+k]=[]),r[d+k][x+N]=S;x+=P}}s=Math.max(0,...r.map(d=>d.length));let o=i.map((d,_)=>d._parsedProps.height??1),a=Array.from({length:s},(d,_)=>{let g=0;for(let x=0;x<i.length;x++){let b=r[x]?.[_];if(b){let S=b._parsedProps.text??b._parsedProps.children,P=b._parsedProps.width??(S?.length??2)*.5;P>g&&(g=P)}}return g||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=e.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:o,cell_padding:t.cellPadding,border_width:t.borderWidth,anchor:t.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,p=0;for(let d=0;d<i.length;d++){let _=0;for(let g=0;g<s;g++){let x=r[d]?.[g];if(x&&!u.has(x)){u.add(x);let b=x._parsedProps,S=b.rowSpan??1,P=b.colSpan??1,T=0;for(let N=0;N<P;N++)T+=a[g+N];let k=0;for(let N=0;N<S;N++)k+=o[d+N];e.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:d,end_row_index:d+S-1,start_column_index:g,end_column_index:g+P-1,text:b.text??b.children,center:{x:c.x+_+T/2,y:c.y-p-k/2},width:T,height:k,horizontal_align:b.horizontalAlign,vertical_align:b.verticalAlign,font_size:b.fontSize??t.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[g]&&(_+=a[g])}p+=o[d]}}},yrt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:hq}}},grt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:dq}}},xrt=class extends Ce{constructor(){super(...arguments);f(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:NH}}},brt=class extends Ce{get config(){return{componentName:"AnalogSimulation",zodProps:FH}}doInitialSimulationRender(){let{db:n}=this.root,{duration:e,timePerStep:t}=this._parsedProps,i=e||10,r=t||.01;n.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:r})}},vrt=class extends Ce{constructor(){super(...arguments);f(this,"simulation_voltage_probe_id",null);f(this,"schematic_voltage_probe_id",null);f(this,"finalProbeName",null);f(this,"color",null)}get config(){return{componentName:"VoltageProbe",zodProps:rq}}doInitialSimulationRender(){let{db:e}=this.root,{connectsTo:t,name:i,referenceTo:r,color:s}=this._parsedProps,o=this.getSubcircuit();if(!o){this.renderError("VoltageProbe must be inside a subcircuit");return}let a=Array.isArray(t)?t:[t];if(a.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let c=a[0],l=o.selectOne(c,{type:"port"}),u=l?null:o.selectOne(c,{type:"net"});if(u&&u.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${c}" resolved to a non-net component "${u.componentName}".`);return}if(!l&&!u){this.renderError(`VoltageProbe could not find connection target "${c}"`);return}let p=l?.source_port_id??u?.source_net_id;if(!p){this.renderError("Could not identify connected source for VoltageProbe");return}let d=null,_=null;if(r){let b=Array.isArray(r)?r:[r];if(b.length!==1){this.renderError("VoltageProbe must reference exactly one port or net");return}let S=b[0];if(d=o.selectOne(S,{type:"port"}),_=d?null:o.selectOne(S,{type:"net"}),_&&_.componentName!=="Net"){this.renderError(`VoltageProbe reference target "${S}" resolved to a non-net component "${_.componentName}".`);return}if(!d&&!_){this.renderError(`VoltageProbe could not find reference target "${S}"`);return}}this.color=s??bzt(p);let g=i;g||(g=a[0].split(" > ").map(b=>b.replace(/^\./,"")).join(".")),this.finalProbeName=g??null;let{simulation_voltage_probe_id:x}=e.simulation_voltage_probe.insert({name:g,signal_input_source_port_id:l?.source_port_id??void 0,signal_input_source_net_id:u?.source_net_id??void 0,reference_input_source_port_id:d?.source_port_id??void 0,reference_input_source_net_id:_?.source_net_id??void 0,subcircuit_id:o.subcircuit_id||void 0,color:this.color});this.simulation_voltage_probe_id=x}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{connectsTo:t,name:i}=this._parsedProps,r=this.getSubcircuit();if(!r)return;let s=Array.isArray(t)?t:[t];if(s.length!==1)return;let o=s[0],a=r.selectOne(o,{type:"port"});if(!a||!a.schematic_port_id)return;let c=a._getGlobalSchematicPositionAfterLayout(),l=null;for(let d of e.schematic_trace.list()){for(let _ of d.edges)if(Math.abs(_.from.x-c.x)<1e-6&&Math.abs(_.from.y-c.y)<1e-6||Math.abs(_.to.x-c.x)<1e-6&&Math.abs(_.to.y-c.y)<1e-6){l=d.schematic_trace_id;break}if(l)break}if(!l)return;let u=this.finalProbeName,p=e.schematic_voltage_probe.insert({name:u,position:c,schematic_trace_id:l,subcircuit_id:r.subcircuit_id||void 0,color:this.color??void 0});this.schematic_voltage_probe_id=p.schematic_voltage_probe_id}},Wzt={name:"@tscircuit/core",type:"module",version:"0.0.915",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.178","@tscircuit/checks":"^0.0.87","@tscircuit/circuit-json-util":"^0.0.73","@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.8","@tscircuit/props":"^0.0.426","@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.328","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.23","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.30","circuit-to-svg":"^0.0.284",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.14","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.66","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"}},ny=class{constructor({platform:n,projectUrl:e}={}){f(this,"firstChild",null);f(this,"children");f(this,"db");f(this,"root",null);f(this,"isRoot",!0);f(this,"_schematicDisabledOverride");f(this,"pcbDisabled",!1);f(this,"pcbRoutingDisabled",!1);f(this,"_featureMspSchematicTraceRouting",!0);f(this,"name");f(this,"platform");f(this,"projectUrl");f(this,"_hasRenderedAtleastOnce",!1);f(this,"_eventListeners",{});this.children=[],this.db=Ie([]),this.root=this,this.platform=n,this.projectUrl=e,this.pcbDisabled=n?.pcbDisabled??!1}get schematicDisabled(){return this._schematicDisabledOverride!==void 0?this._schematicDisabledOverride:this._getBoard()?._parsedProps?.schematicDisabled??!1}set schematicDisabled(n){this._schematicDisabledOverride=n}add(n){let e;(0,Srt.isValidElement)(n)?e=nit(n):e=n,this.children.push(e)}setPlatform(n){this.platform={...this.platform,...n}}_getBoard(){let n=this.children.find(e=>e.componentName==="Board");if(n)return n}_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 n=this.children.filter(t=>t.lowercaseComponentName==="panel");if(n.length>1)throw new Error("Only one <panel> is allowed per circuit");if(n.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=n[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let e=new Tl({subcircuit:!0});e.parent=this,e.addAll(this.children),this.children=[e],this.firstChild=e}render(){this.firstChild||this._guessRootComponent();let{firstChild:n,db:e}=this;if(!n)throw new Error("RootCircuit has no root component");n.parent=this,n.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(e=>setTimeout(e,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(n=>n._hasIncompleteAsyncEffects())}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(n){let e=await Promise.resolve().then(()=>(ynt(),_nt)).catch(t=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
253
+ ${o}`)}catch(c){Ga(`Failed to convert circuit JSON to SPICE: ${c}`);return}for(let c of t){let l=c._parsedProps.spiceEngine??"spicey",u=r[l];if(!u)throw new Error(`SPICE engine "${l}" not found in platform config. Available engines: ${JSON.stringify(Object.keys(r).filter(d=>d!=="spicey"))}`);let p=`spice-simulation-${l}-${c.source_component_id}`;Ga(`Queueing simulation for spice engine: ${l} (id: ${p})`),n._queueAsyncEffect(p,async()=>{try{Ga(`Running simulation with engine: ${l}`);let d=await u.simulate(o);Ga(`Simulation completed, received ${d.simulationResultCircuitJson.length} elements`);let _=e.db.simulation_experiment.list()[0];if(!_){Ga("No simulation experiment found, skipping result insertion");return}for(let g of d.simulationResultCircuitJson){if(g.type==="simulation_transient_voltage_graph"){g.simulation_experiment_id=_.simulation_experiment_id;let b=i.find(S=>S.finalProbeName===g.name);b&&(g.color=b.color)}let x=g.type;x&&e.db[x]?(e.db[x].insert(g),Ga(`Inserted ${x} into database`)):(Ga(`Warning: Unknown element type ${x}, adding to raw db`),e.db._addElement(g))}n._markDirty("SimulationSpiceEngineRender")}catch(d){Ga(`Simulation failed for engine ${l}: ${d}`);let _=e.db.simulation_experiment.list()[0];e.db.simulation_unknown_experiment_error.insert({simulation_experiment_id:_?.simulation_experiment_id,error_type:"simulation_unknown_experiment_error",message:d instanceof Error?d.message:String(d)})}})}}function wzt(n){if(n.root?.pcbDisabled||!n.pcb_group_id)return;let e=n._parsedProps?.pcbPositionAnchor;if(!e)return;let t=n._getGlobalPcbPositionBeforeLayout(),{pcbX:i,pcbY:r}=n._parsedProps;if(i===void 0&&r===void 0)return;let{db:s}=n.root,o=s.pcb_group.get(n.pcb_group_id);if(!o)return;let a=o.width,c=o.height,{center:l}=o;if(o.outline&&o.outline.length>0){let x=lo(o.outline);x&&(a=x.maxX-x.minX,c=x.maxY-x.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},p={...l},d=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(e))switch(e){case"center":d=p;break;case"top_left":d={x:u.left,y:u.top};break;case"top_center":d={x:p.x,y:u.top};break;case"top_right":d={x:u.right,y:u.top};break;case"center_left":d={x:u.left,y:p.y};break;case"center_right":d={x:u.right,y:p.y};break;case"bottom_left":d={x:u.left,y:u.bottom};break;case"bottom_center":d={x:p.x,y:u.bottom};break;case"bottom_right":d={x:u.right,y:u.bottom};break}if(!d)return;let g={...p};t.x!==void 0&&(g.x+=t.x-d.x),t.y!==void 0&&(g.y+=t.y-d.y),(Math.abs(g.x-p.x)>1e-6||Math.abs(g.y-p.y)>1e-6)&&(n._repositionOnPcb(g),s.pcb_group.update(n.pcb_group_id,{center:g})),s.pcb_group.update(n.pcb_group_id,{anchor_position:t,anchor_alignment:e})}var Tl=class extends Yn{constructor(){super(...arguments);f(this,"pcb_group_id",null);f(this,"schematic_group_id",null);f(this,"subcircuit_id",null);f(this,"_hasStartedAsyncAutorouting",!1);f(this,"_asyncAutoroutingResult",null);f(this,"unnamedElementCounter",{})}get config(){return{zodProps:pH,componentName:"Group"}}doInitialSourceGroupRender(){let{db:e}=this.root,t=typeof this._parsedProps.name=="string"&&this._parsedProps.name.length>0,i=e.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit,was_automatically_named:!t});this.source_group_id=i.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${i.source_group_id}`,e.source_group.update(i.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:e}=this.root;for(let t of this.children)e.source_component.update(t.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:e}=this.root,t=this.parent?.getGroup?.();if(t?.source_group_id&&e.source_group.update(this.source_group_id,{parent_source_group_id:t.source_group_id}),!this.isSubcircuit)return;let i=this.parent?.getSubcircuit?.()?.subcircuit_id;i&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:i})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t,r=i.outline&&i.outline.length>0,s=r?i.outline.map(a=>({x:V.parse(a.x),y:V.parse(a.y)})):void 0,o=e.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),...r?{outline:s}:{width:0,height:0},pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:t.autorouter?{trace_clearance:t.autorouter.traceClearance}:void 0});this.pcb_group_id=o.pcb_group_id;for(let a of this.children)e.pcb_component.update(a.pcb_component_id,{pcb_group_id:o.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps,i=t.outline&&t.outline.length>0;if(this.pcb_group_id){let r=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0;if(i){let p=t.outline.map(b=>({x:V.parse(b.x),y:V.parse(b.y)})),d=lo(p);if(!d)return;let _=(d.minX+d.maxX)/2,g=(d.minY+d.maxY)/2,x=r?e.pcb_group.get(this.pcb_group_id)?.center??{x:_,y:g}:{x:_,y:g};e.pcb_group.update(this.pcb_group_id,{center:x});return}let s=wP(this.children),o=s.width,a=s.height,c=(s.minX+s.maxX)/2,l=(s.minY+s.maxY)/2;if(this.isSubcircuit){let{padLeft:p,padRight:d,padTop:_,padBottom:g}=this._resolvePcbPadding();o+=p+d,a+=_+g,c+=(d-p)/2,l+=(_-g)/2}let u=r?e.pcb_group.get(this.pcb_group_id)?.center??{x:c,y:l}:{x:c,y:l};e.pcb_group.update(this.pcb_group_id,{width:Number(t.width??o),height:Number(t.height??a),center:u})}}getNextAvailableName(e){var t,i;return(t=this.unnamedElementCounter)[i=e.lowercaseComponentName]??(t[i]=1),`unnamed_${e.lowercaseComponentName}${this.unnamedElementCounter[e.lowercaseComponentName]++}`}_resolvePcbPadding(){let e=this._parsedProps,t=e.pcbLayout,i=p=>{let d=t?.[p],_=e[p];if(typeof d=="number")return d;if(typeof _=="number")return _},r=i("padding")??0,s=i("paddingX"),o=i("paddingY"),a=i("paddingLeft")??s??r,c=i("paddingRight")??s??r,l=i("paddingTop")??o??r,u=i("paddingBottom")??o??r;return{padLeft:a,padRight:c,padTop:l,padBottom:u}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:e}=this,{db:t}=this.root,i=e;if(!this.isSubcircuit)return;let r=i.manualEdits?.manual_trace_hints;if(r)for(let s of r)this.add(new H9({for:s.pcb_port_selector,offsets:s.offsets}))}doInitialSourceAddConnectivityMapKey(){$Ft(this)}_areChildSubcircuitsRouted(){let e=this.selectAll("group").filter(t=>t.isSubcircuit);for(let t of e)if(t._shouldRouteAsync()&&!t._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let e=this._getAutorouterConfig();return e.groupMode==="sequential-trace"?!1:!!(e.local&&e.groupMode==="subcircuit"||!e.local)}_hasTracesToRoute(){let e=(0,q_.default)("tscircuit:core:_hasTracesToRoute"),t=this.selectAll("trace");return e(`[${this.getString()}] has ${t.length} traces to route`),t.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:e}=this.root,t=(0,q_.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),i=this._parsedProps,r=this._getAutorouterConfig(),s=r.serverUrl,o=r.serverMode,a=(u,p)=>(t("fetching",u),p.headers&&(p.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(u,p)),c=this.root.db.toArray().filter(u=>u.type.startsWith("source_")||u.type.startsWith("pcb_"));if(o==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:p}=await a(`${s}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:D9({db:e,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=p,this._markDirty("PcbTraceRender");return}let{autorouting_result:u}=await a(`${s}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:c,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(p=>p.json());this._asyncAutoroutingResult=u,this._markDirty("PcbTraceRender");return}let{autorouting_job:l}=await a(`${s}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:c,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:r.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(u=>u.json());for(;;){let{autorouting_job:u}=await a(`${s}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(p=>p.json());if(u.is_finished){let{autorouting_job_output:p}=await a(`${s}/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:p.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(u.has_error){let p=new q1(`Autorouting job failed: ${JSON.stringify(u.error)}`);throw e.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,error_type:"pcb_autorouting_error",message:p.message}),p}await new Promise(p=>setTimeout(p,100))}}async _runLocalAutorouting(){let{db:e}=this.root,t=this._parsedProps,i=(0,q_.default)("tscircuit:core:_runLocalAutorouting");i(`[${this.getString()}] starting local autorouting`);let r=this._getAutorouterConfig(),s=this._isLaserPrefabAutorouter(r),o=this._getSubcircuitLayerCount()===1,{simpleRouteJson:a}=D9({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(i.enabled&&global.debugOutputArray?.push({name:`simpleroutejson-${this.props.name}.json`,obj:a}),i.enabled){let u=r1(a);u.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(u)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:a});let c;r.algorithmFn?c=await r.algorithmFn(a):c=new CFt(a,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity,useAssignableViaSolver:s||o});let l=new Promise((u,p)=>{c.on("complete",d=>{i(`[${this.getString()}] local autorouting complete`),u(d.traces)}),c.on("error",d=>{i(`[${this.getString()}] local autorouting error: ${d.error.message}`),p(d.error)})});c.on("progress",u=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...u})}),c.start();try{let u=await l;this._asyncAutoroutingResult={output_pcb_traces:u},this._markDirty("PcbTraceRender")}catch(u){let{db:p}=this.root;throw p.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:u instanceof Error?u.message:String(u)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:u instanceof Error?u.message:String(u)},simpleRouteJson:a}),u}finally{c.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 e=(0,q_.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){e(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}e(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){gzt(this)}updatePcbTraceRender(){let e=(0,q_.default)("tscircuit:core:updatePcbTraceRender");if(e(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(e(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:t}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){e(`[${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){e(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:e}=this.root,{traces:t}=this._asyncAutoroutingResult.output_simple_route_json;if(t)for(let i of t){let r=e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;let{db:t}=this.root,i=this.getInheritedMergedProperty("pcbStyle"),{holeDiameter:r,padDiameter:s}=W9(i);for(let o of e)if(o.type==="pcb_trace"){if(o.subcircuit_id=this.subcircuit_id,o.connection_name){let a=o.connection_name;o.source_trace_id=a}t.pcb_trace.insert(o)}for(let o of e)if(o.type!=="pcb_via"&&o.type==="pcb_trace")for(let a of o.route)a.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:o.pcb_trace_id,x:a.x,y:a.y,hole_diameter:r,outer_diameter:s,layers:[a.from_layer,a.to_layer],from_layer:a.from_layer,to_layer:a.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=e.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=i.schematic_group_id;for(let r of this.children)r.schematic_component_id&&e.schematic_component.update(r.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){let e=this._parsedProps;if(e.schLayout?.layoutMode==="none"||e.schLayout?.layoutMode==="relative")return"relative";if(e.schLayout?.matchAdapt)return"match-adapt";if(e.schLayout?.flex)return"flex";if(e.schLayout?.grid)return"grid";if(e.schMatchAdapt)return"match-adapt";if(e.schFlex)return"flex";if(e.schGrid)return"grid";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";if(e.relative||e.schRelative)return"relative";let t=this.children.some(r=>{let s=r._parsedProps;return s?.schX!==void 0||s?.schY!==void 0}),i=(e.manualEdits?.schematic_placements?.length??0)>0;return!t&&!i?"match-adapt":"relative"}doInitialSchematicLayout(){let e=this._getSchematicLayoutMode();e==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),e==="grid"&&this._doInitialSchematicLayoutGrid(),e==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){LFt(this)}_doInitialSchematicLayoutMatchpack(){zFt(this)}_doInitialSchematicLayoutGrid(){DFt(this)}_doInitialSchematicLayoutFlex(){jFt(this)}_getPcbLayoutMode(){let e=this._parsedProps;if(e.pcbRelative)return"none";if(e.pcbLayout?.matchAdapt)return"match-adapt";if(e.pcbLayout?.flex)return"flex";if(e.pcbLayout?.grid)return"grid";if(e.pcbLayout?.pack)return"pack";if(e.pcbFlex)return"flex";if(e.pcbGrid)return"grid";if(e.pcbPack||e.pack)return"pack";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";let t=e.pcbX!==void 0||e.pcbY!==void 0,i=(e.manualEdits?.pcb_placements?.length??0)>0,r=this.children.reduce((s,o)=>{if(!o.pcb_component_id&&!o.pcb_group_id)return s;let a=o._parsedProps,c=a?.pcbX!==void 0||a?.pcbY!==void 0;return s+(c?0:1)},0);return!t&&!i&&r>1?"pack":"none"}doInitialPcbLayout(){let e=this._getPcbLayoutMode();e==="grid"?this._doInitialPcbLayoutGrid():e==="pack"?this._doInitialPcbLayoutPack():e==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){BFt(this)}_doInitialPcbLayoutPack(){ezt(this)}_doInitialPcbLayoutFlex(){nzt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!t.border)return;let i=typeof t.schWidth=="number"?t.schWidth:void 0,r=typeof t.schHeight=="number"?t.schHeight:void 0,s=typeof t.schPadding=="number"?t.schPadding:0,o=typeof t.schPaddingLeft=="number"?t.schPaddingLeft:s,a=typeof t.schPaddingRight=="number"?t.schPaddingRight:s,c=typeof t.schPaddingTop=="number"?t.schPaddingTop:s,l=typeof t.schPaddingBottom=="number"?t.schPaddingBottom:s,u=this.schematic_group_id?e.schematic_group.get(this.schematic_group_id):null;if(u&&(i===void 0&&typeof u.width=="number"&&(i=u.width),r===void 0&&typeof u.height=="number"&&(r=u.height)),i===void 0||r===void 0)return;let p=u?.center??this._getGlobalSchematicPositionBeforeLayout(),d=p.x-i/2-o,_=p.y-r/2-l,g=i+o+a,x=r+c+l;e.schematic_box.insert({width:g,height:x,x:d,y:_,is_dashed:t.border?.dashed??!1})}_determineSideFromPosition(e,t){if(!e.center||!t.center)return"left";let i=e.center.x-t.center.x,r=e.center.y-t.center.y;return Math.abs(i)>Math.abs(r)?i>0?"right":"left":r>0?"bottom":"top"}_calculateSchematicBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let a of e)t=Math.min(t,a.centerX),i=Math.max(i,a.centerX),r=Math.min(r,a.centerY),s=Math.max(s,a.centerY);let o=2;return{minX:t-o,maxX:i+o,minY:r-o,maxY:s+o}}_getAutorouterConfig(){let e=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return KFt(e)}_isLaserPrefabAutorouter(e=this._getAutorouterConfig()){let t=this.props.autorouter,i=r=>r?.replace(/-/g,"_")??r;return e.preset==="laser_prefab"?!0:typeof t=="string"?i(t)==="laser_prefab":typeof t=="object"&&t?i(t.preset)==="laser_prefab":!1}_getSubcircuitLayerCount(){let e=this.getInheritedProperty("layers");return typeof e=="number"?e:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(this.isSubcircuit){let t=new Map;for(let i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){let r=t.get(i._parsedProps.name)||[];r.push(i),t.set(i._parsedProps.name,r)}for(let[i,r]of t.entries())r.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:r.map(s=>s.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:e}=this.root,t=e;for(let i of t.schematic_net_label.list()){let r=t.source_net.get(i.source_net_id),s=i.text||r?.name||"";if(i.anchor_side==="top"&&/^gnd/i.test(s)){t.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_down"});continue}i.anchor_side==="bottom"&&/^v/i.test(s)&&t.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_up"})}}doInitialSimulationSpiceEngineRender(){Szt(this)}doInitialPcbComponentAnchorAlignment(){wzt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(e){return super._repositionOnPcb(e)}};function Pzt(n,e){let{subcircuit:t}=e;if(t.lowercaseComponentName==="board"||t.parent?.lowercaseComponentName==="board")return;let i={name:"inflated_board"};n.width&&(i.width=n.width),n.height&&(i.height=n.height),n.center&&(i.pcbX=n.center.x,i.pcbY=n.center.y),n.outline&&(i.outline=n.outline),n.thickness&&(i.thickness=n.thickness),n.material&&(i.material=n.material);let r=new TP(i);return r.pcb_board_id=n.pcb_board_id,t.add(r),r}var kzt=new Proxy({},{get:(n,e)=>e}),qa=kzt,PP="rgba(132, 0, 0)",kP=.12,Z9=class extends Yn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:wH,sourceFtype:qa.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let e=this.props.capacitance,t=typeof e=="string"?e:`${ei(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${t}/${ei(this._parsedProps.maxVoltageRating)}V`:t}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new Ds({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new Ds({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,capacitance:t.capacitance,max_voltage_rating:t.maxVoltageRating,max_decoupling_trace_length:t.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!t.polarized});this.source_component_id=i.source_component_id}},ey=(n,e)=>{let{injectionDb:t,normalComponent:i}=e;if(!i)return;let r=n.center||{x:0,y:0},s=n.rotation||0,o=VE(ai(Tn(r.x,r.y),Oo(s*Math.PI/180))),a=t.toArray().filter(u=>"pcb_component_id"in u&&u.pcb_component_id===n.pcb_component_id),c=structuredClone(a);el(c,o);let l=J_({componentName:i.name,componentRotation:"0deg"},c);i.addAll(l)};function Tzt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new Z9({name:n.name,capacitance:n.capacitance,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&ey(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var n0=class extends Yn{constructor(e){super(e);f(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:l_,shouldRenderAsSchematicBox:!0}}initPorts(e={}){super.initPorts(e);let{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp();if(t.externallyConnectedPins){let s=new Set;for(let[o,a]of t.externallyConnectedPins)s.add(o),s.add(a);for(let o of s)if(!this.children.find(c=>c instanceof qi&&c.isMatchingAnyOf([o]))){let c=o.match(/^pin(\d+)$/);if(c){let l=parseInt(c[1]);this.add(new qi({pinNumber:l,aliases:[o]}))}else this.add(new qi({name:o,aliases:[o]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:e}=this;e?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=t.layer??"top";if(s!=="top"&&s!=="bottom"){let a=this.getSubcircuit(),c=Ym.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${s}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:s,subcircuit_id:a.subcircuit_id??void 0});e.pcb_component_invalid_layer_error.insert(c)}let o=e.pcb_component.insert({center:{x:i,y:r},width:2,height:3,layer:s==="top"||s==="bottom"?s:"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=o.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:e}=this;if(e.externallyConnectedPins)for(let[t,i]of e.externallyConnectedPins)this.add(new Ds({from:`${this.getSubcircuitSelector()} > port.${t}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:e}=this.root,{pinAttributes:t}=this.props;if(!t)return;let i=null,r=null,s,o=this.selectAll("port");for(let p of o)for(let d of p.getNameAndAliases())if(t[d]){let _=t[d];_.providesPower&&(i=p,s=_.providesVoltage),_.providesGround&&(r=p)}if(!i||!r||s===void 0)return;let a=e.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=e.source_port.get(r.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=e.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=e.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||e.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:r.source_port_id,negative_source_net_id:u.source_net_id,voltage:s})}},Mzt=(n,e)=>{if(!n||n.length===0)return;let{injectionDb:t}=e,i=n.map(r=>r.map(s=>{let o=t.source_port.get(s);return o?o.pin_number!==void 0&&o.pin_number!==null?`pin${o.pin_number}`:o.name:null}).filter(s=>s!==null)).filter(r=>r.length>0);return i.length>0?i:void 0},Ezt=(n,e)=>{let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.schematic_component.getWhere({source_component_id:n.source_component_id}),a=t.cad_component.getWhere({source_component_id:n.source_component_id}),c=Mzt(n.internally_connected_source_port_ids,e),l=new n0({name:n.name,manufacturerPartNumber:n.manufacturer_part_number,supplierPartNumbers:n.supplier_part_numbers??void 0,pinLabels:o?.port_labels??void 0,schWidth:o?.size?.width,schHeight:o?.size?.height,schPinSpacing:o?.pin_spacing,schX:o?.center?.x,schY:o?.center?.y,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds,internallyConnectedPins:c}),u=a?.footprinter_string??null;u&&(Object.assign(l.props,{footprint:u}),Object.assign(l._parsedProps,{footprint:u}),a||l._addChildrenFromStringFootprint?.()),s&&ey(s,{...e,normalComponent:l}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(l):i.add(l)},K9=class extends Yn{constructor(){super(...arguments);f(this,"pos",this.portMap.pin1);f(this,"anode",this.portMap.pin1);f(this,"neg",this.portMap.pin2);f(this,"cathode",this.portMap.pin2)}get config(){let e={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},t=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:t?e[t]:this.props.symbolName??"diode",componentName:"Diode",zodProps:jH,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}};function Czt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new K9({name:n.name,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&ey(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}function Izt(n,e){let{subcircuit:t,groupsMap:i}=e,r=new Tl({name:n.name??`inflated_group_${n.source_group_id}`});return r.source_group_id=n.source_group_id,i&&i.set(n.source_group_id,r),n.parent_source_group_id&&i?.has(n.parent_source_group_id)?i.get(n.parent_source_group_id).add(r):t.add(r),r}var J9=class extends Yn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:DH,sourceFtype:qa.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${ei(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({name:this.name,ftype:qa.simple_inductor,inductance:this.props.inductance,display_inductance:this._getSchematicSymbolDisplayValue(),supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function Nzt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new J9({name:n.name,inductance:n.inductance,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&ey(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}function Azt(n,e){let{injectionDb:t,subcircuit:i}=e;if(n.source_component_id!==null)return;let r=t.pcb_port.getWhere({source_port_id:n.source_port_id}),s=new qi({name:n.name,pinNumber:n.pin_number});i.add(s),s.source_port_id=n.source_port_id;let o=i.root;if(o&&r){let{db:a}=o,c=a.pcb_port.insert({pcb_component_id:void 0,layers:r.layers,subcircuit_id:i.subcircuit_id??void 0,pcb_group_id:i.getGroup()?.pcb_group_id??void 0,x:r.x,y:r.y,source_port_id:n.source_port_id,is_board_pinout:!1});s.pcb_port_id=c.pcb_port_id}}var Q9=class extends Yn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:gH,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${ei(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 Ds({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new Ds({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new Ds({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new Ds({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,resistance:t.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function Rzt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new Q9({name:n.name,resistance:n.resistance,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&ey(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var Ozt=(n,e)=>{let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=[],o=n.source_group_id;for(;o&&o!==i.source_group_id;){let a=t.source_group.get(o),c=r?.get(o);if(!a||!c)break;let l=c.props.name??c.fallbackUnassignedName;s.unshift(`.${l}`),o=a.parent_source_group_id}return s.push(`.${n.name}`),s.join(" > ")};function Lzt(n,e){let{injectionDb:t,subcircuit:i}=e,r=[];for(let o of n.connected_source_port_ids){let a=t.source_port.get(o);if(!a)continue;let c;if(a.source_component_id){let l=t.source_component.get(a.source_component_id);l&&(c=`${Ozt({name:l.name,source_group_id:l.source_group_id},e)} > .${a.name}`)}else c=`.${a.name}`;c&&r.push(c)}for(let o of n.connected_source_net_ids){let a=t.source_net.get(o);a&&r.push(`net.${a.name}`)}if(r.length<2)return;let s=new Ds({path:r});s.source_trace_id=n.source_trace_id,i.add(s)}var t6=class extends Yn{constructor(){super(...arguments);f(this,"emitter",this.portMap.pin1);f(this,"collector",this.portMap.pin2);f(this,"base",this.portMap.pin3)}get config(){let e=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??e,zodProps:zH,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let e={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:e})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:t.type});this.source_component_id=i.source_component_id}};function Fzt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new t6({name:n.name,type:n.transistor_type,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&ey(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var Tit=(n,e,t)=>{if(!e)return;let i=Je(e);if(e&&t?.length>0)throw new Error("Component cannot have both circuitJson and children");let s={injectionDb:i,subcircuit:n,groupsMap:new Map},o=i.source_group.list();for(let p of o)Izt(p,s);let a=i.pcb_board.list();for(let p of a)Pzt(p,s);let c=i.source_component.list();for(let p of c)switch(p.ftype){case"simple_resistor":Rzt(p,s);break;case"simple_capacitor":Tzt(p,s);break;case"simple_inductor":Nzt(p,s);break;case"simple_diode":Czt(p,s);break;case"simple_chip":Ezt(p,s);break;case"simple_transistor":Fzt(p,s);break;default:throw new Error(`No inflator implemented for source component ftype: "${p.ftype}"`)}let l=i.source_port.list();for(let p of l)Azt(p,s);let u=i.source_trace.list();for(let p of u)Lzt(p,s)},zzt=.01,Wnt=(n,e,t)=>{let i=n/2,r=e/2,s=Math.min(t,i,r);if(s<zzt)return[{x:-i,y:-r},{x:i,y:-r},{x:i,y:r},{x:-i,y:r}];let a=Math.max(1,Math.ceil(Math.PI/2*s/.1)),c=Math.PI/2/a,l=[];l.push({x:-i+s,y:-r}),l.push({x:i-s,y:-r});for(let u=1;u<=a;u++){let p=-Math.PI/2+u*c;l.push({x:i-s+s*Math.cos(p),y:-r+s+s*Math.sin(p)})}l.push({x:i,y:r-s});for(let u=1;u<=a;u++){let p=0+u*c;l.push({x:i-s+s*Math.cos(p),y:r-s+s*Math.sin(p)})}l.push({x:-i+s,y:r});for(let u=1;u<=a;u++){let p=Math.PI/2+u*c;l.push({x:-i+s+s*Math.cos(p),y:r-s+s*Math.sin(p)})}l.push({x:-i,y:-r+s});for(let u=1;u<=a;u++){let p=Math.PI+u*c;l.push({x:-i+s+s*Math.cos(p),y:-r+s+s*Math.sin(p)})}return l},TP=class extends Tl{constructor(){super(...arguments);f(this,"pcb_board_id",null);f(this,"source_board_id",null);f(this,"_drcChecksComplete",!1);f(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:R4}}get boardThickness(){return this._parsedProps.thickness??1.4}get allLayers(){return(this._parsedProps.layers??2)===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}_getBoardCalcVariables(){let{_parsedProps:e}=this;if((e.width==null||e.height==null)&&!e.outline)return{};let i=this.pcb_board_id?this.root?.db.pcb_board.get(this.pcb_board_id):null,r=i?.width??e.width,s=i?.height??e.height;if((r==null||s==null)&&e.outline?.length){let p=lo(e.outline);p&&(r??(r=p.maxX-p.minX),s??(s=p.maxY-p.minY))}let{pcbX:o,pcbY:a}=this.getResolvedPcbPositionProp(),c=i?.center??{x:o+(e.outlineOffsetX??0),y:a+(e.outlineOffsetY??0)},l=r??0,u=s??0;return{"board.minx":c.x-l/2,"board.maxx":c.x+l/2,"board.miny":c.y-u/2,"board.maxy":c.y+u/2}}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=e.pcb_board.get(this.pcb_board_id);if(r?.width&&r?.height||r?.outline&&r.outline.length>0)return;let s=1/0,o=1/0,a=-1/0,c=-1/0,l=git(e,this.subcircuit_id),u=new Set([this.subcircuit_id,...l]),p=e.pcb_component.list().filter(C=>C.subcircuit_id&&u.has(C.subcircuit_id)),d=e.pcb_group.list().filter(C=>C.subcircuit_id&&u.has(C.subcircuit_id)),_=!1,g=(C,E,R)=>{E===0||R===0||(_=!0,s=Math.min(s,C.x-E/2),o=Math.min(o,C.y-R/2),a=Math.max(a,C.x+E/2),c=Math.max(c,C.y+R/2))};for(let C of p)g(C.center,C.width,C.height);for(let C of d){let E=C.width??0,R=C.height??0;if(C.outline&&C.outline.length>0){let A=lo(C.outline);A&&(E=A.maxX-A.minX,R=A.maxY-A.minY)}g(C.center,E,R)}if(t.boardAnchorPosition){let{x:C,y:E}=t.boardAnchorPosition;s=Math.min(s,C),o=Math.min(o,E),a=Math.max(a,C),c=Math.max(c,E)}let x=2,b=_?a-s+x*2:0,S=_?c-o+x*2:0,P={x:_?(s+a)/2+(t.outlineOffsetX??0):(t.outlineOffsetX??0)+i.x,y:_?(o+c)/2+(t.outlineOffsetY??0):(t.outlineOffsetY??0)+i.y},T=t.width??b,k=t.height??S,N=t.outline;!N&&t.borderRadius!=null&&T>0&&k>0&&(N=Wnt(T,k,t.borderRadius));let M={width:T,height:k,center:P};N&&(M.outline=N.map(C=>({x:C.x+(t.outlineOffsetX??0),y:C.y+(t.outlineOffsetY??0)}))),e.pcb_board.update(this.pcb_board_id,M)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let e=this.root?.platform;if(!e?.printBoardInformationToSilkscreen)return;let t=this.root.db.pcb_board.get(this.pcb_board_id);if(!t)return;let i=[];if(e.projectName&&i.push(e.projectName),e.version&&i.push(`v${e.version}`),e.url&&i.push(e.url),i.length===0)return;let r=i.join(`
254
+ `),a={x:t.center.x+t.width/2-.25,y:t.center.y-t.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:r,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:e}=this.root,t=e.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=t.source_board_id}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:e,children:t}=this._parsedProps;Tit(this,e,t)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,r=t.circuitJson?.find(_=>_.type==="pcb_board"),s=t.width??r?.width??0,o=t.height??r?.height??0,a=this._getGlobalPcbPositionBeforeLayout(),c={x:a.x+(t.outlineOffsetX??0),y:a.y+(t.outlineOffsetY??0)},{boardAnchorPosition:l,boardAnchorAlignment:u}=t;if(l&&(c=EFt({boardAnchorPosition:l,boardAnchorAlignment:u??"center",width:s,height:o})),t.outline){let _=t.outline.map(N=>N.x),g=t.outline.map(N=>N.y),x=Math.min(..._),b=Math.max(..._),S=Math.min(...g),P=Math.max(...g),T=(x+b)/2,k=(S+P)/2;s=b-x,o=P-S,c={x:T+(t.outlineOffsetX??0),y:k+(t.outlineOffsetY??0)}}let p=t.outline;!p&&t.borderRadius!=null&&s>0&&o>0&&(p=Wnt(s,o,t.borderRadius));let d=e.pcb_board.insert({center:c,thickness:this.boardThickness,num_layers:this.allLayers.length,width:s,height:o,outline:p?.map(_=>({x:_.x+(t.outlineOffsetX??0),y:_.y+(t.outlineOffsetY??0)})),material:t.material});this.pcb_board_id=d.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let t=Gtt(e.toArray());for(let u of t)e.pcb_trace_error.insert(u);let i=Vtt(e.toArray());for(let u of i)e.pcb_port_not_connected_error.insert(u);let r=qtt(e.toArray());for(let u of r)e.pcb_component_outside_board_error.insert(u);let s=Jtt(e.toArray());for(let u of s)e.pcb_trace_error.insert(u);let o=Ktt(e.toArray());for(let u of o)e.pcb_via_clearance_error.insert(u);let a=Ztt(e.toArray());for(let u of a)e.pcb_via_clearance_error.insert(u);let c=Qtt(e.toArray());for(let u of c)e.pcb_footprint_overlap_error.insert(u);let l=tet(e.toArray());for(let u of l)e.source_pin_must_be_connected_error.insert(u)}_emitRenderLifecycleEvent(e,t){super._emitRenderLifecycleEvent(e,t),t==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e})}_repositionOnPcb(e){if(super._repositionOnPcb(e),this.pcb_board_id){let{db:t}=this.root,i=t.pcb_board.get(this.pcb_board_id);if(i?.center&&i.outline){let r=e.x-i.center.x,s=e.y-i.center.y,o=i.outline.map(a=>({x:a.x+r,y:a.y+s}));t.pcb_board.update(this.pcb_board_id,{outline:o})}}}},$zt=5,Hnt=2,Dzt=(n,e)=>{let{gapLength:t,cutoutWidth:i,mouseBites:r,mouseBiteHoleDiameter:s,mouseBiteHoleSpacing:o}=e,a=[],c=[];if(n.length<2)return{tabCutouts:a,mouseBiteHoles:c};let l=new Od(n.map(p=>Da(p.x,p.y))),u;if(n.length>2){let p=Da(n[0].x,n[0].y),d=Da(n[1].x,n[1].y),_=Rd(p,d).normalize(),g=_.rotate(Math.PI/2),b=p.translate(_.multiply(Yw(p,d).length/2)).translate(g.multiply(.01));u=l.contains(b)}else u=l.area()>0;for(let p=0;p<n.length;p++){let d=n[p],_=n[(p+1)%n.length];if(!d||!_)continue;let g=Da(d.x,d.y),x=Da(_.x,_.y),b=Yw(g,x),S=b.length;if(S<1e-6)continue;let P=Rd(g,x),T=P.normalize(),k=T.rotate(Math.PI/2),M=b.middle().translate(k.multiply(.01));l.contains(M)&&(k=k.multiply(-1));let C=2,E=C*s+(C-1)*o,R;r?R=E:R=t,R=Math.min(R,S*.9);let A=(S-R)/2,j=A+R;if(r){let dt=s+o;if(R>=E&&dt>0){let G=(R-E)/2+s/2,nt=A+G;for(let J=0;J<C;J++){let pt=nt+J*dt,ut=g.translate(T.multiply(pt));c.push({x:ut.x,y:ut.y})}}}let D=n[(p-1+n.length)%n.length],Y=n[(p+2)%n.length],X=0,W=0;if(D&&Y){let G=Rd(Da(D.x,D.y),g).cross(P),nt=u?G>1e-9:G<-1e-9,J=Rd(x,Da(Y.x,Y.y)),pt=P.cross(J),ut=u?pt>1e-9:pt<-1e-9;X=nt?i:0,W=ut?i:0}let et=[{start:0-X,end:A},{start:j,end:S+W}],H=k.multiply(i);for(let dt of et){let G=dt.end-dt.start;if(G<1e-6)continue;let J=g.translate(T.multiply(dt.start+G/2)).translate(H.multiply(.5)),pt=G,ut=i,wt=T.slope*180/Math.PI;a.push({type:"pcb_cutout",shape:"rect",center:{x:J.x,y:J.y},width:pt,height:ut,rotation:wt,corner_radius:i/2})}}return{tabCutouts:a,mouseBiteHoles:c}};function jzt(n,e){let t=[],i=[],{tabWidth:r,tabLength:s,mouseBites:o}=e,a=n.map(p=>{if((!p.outline||p.outline.length===0)&&p.width&&p.height){let d=p.width/2,_=p.height/2;return{...p,outline:[{x:p.center.x-d,y:p.center.y-_},{x:p.center.x+d,y:p.center.y-_},{x:p.center.x+d,y:p.center.y+_},{x:p.center.x-d,y:p.center.y+_}]}}return p});for(let p of a)if(p.outline&&p.outline.length>0){let d=r*.45,_=d*.1,g=Dzt(p.outline,{gapLength:s,cutoutWidth:r,mouseBites:o,mouseBiteHoleDiameter:d,mouseBiteHoleSpacing:_});t.push(...g.tabCutouts),i.push(...g.mouseBiteHoles)}let c=t.map((p,d)=>({...p,pcb_cutout_id:`panel_tab_${d}`})),l=r*.45,u=i.map((p,d)=>({type:"pcb_hole",pcb_hole_id:`panel_mouse_bite_${d}`,hole_shape:"circle",hole_diameter:l,x:p.x,y:p.y}));return{tabCutouts:c,mouseBiteHoles:u}}var Bzt=({boards:n,db:e,row:t,col:i,cellWidth:r,cellHeight:s,boardGap:o})=>{let a=n.map(C=>{let E=e.pcb_board.get(C.pcb_board_id);return!E||E.width===void 0||E.height===void 0?null:{board:C,width:E.width,height:E.height}}).filter(C=>C!==null);if(a.length===0)return{positions:[],gridWidth:0,gridHeight:0};let c=t,u=i??Math.ceil(c?a.length/c:Math.sqrt(a.length)),p=c??Math.ceil(a.length/u),d=Array(u).fill(0),_=Array(p).fill(0);a.forEach((C,E)=>{let R=E%u,A=Math.floor(E/u);A<_.length&&C.height>_[A]&&(_[A]=C.height),R<d.length&&C.width>d[R]&&(d[R]=C.width)});let g=r?V.parse(r):0,x=s?V.parse(s):0;for(let C=0;C<d.length;C++)d[C]=Math.max(d[C],g);for(let C=0;C<_.length;C++)_[C]=Math.max(_[C],x);let b=d.reduce((C,E)=>C+E,0)+(u>1?(u-1)*o:0),S=_.reduce((C,E)=>C+E,0)+(p>1?(p-1)*o:0),P=-b/2,k=[-S/2];for(let C=1;C<p;C++)k.push(k[C-1]+_[C-1]+o);let N=[P];for(let C=1;C<u;C++)N.push(N[C-1]+d[C-1]+o);let M=[];return a.forEach((C,E)=>{let R=E%u,A=Math.floor(E/u);if(A>=k.length||R>=N.length)return;let j=N[R],D=k[A],Y=d[R],X=_[A],W=j+Y/2,et=D+X/2;M.push({board:C.board,pos:{x:W,y:et}})}),{positions:M,gridWidth:b,gridHeight:S}},Mit=class extends Tl{constructor(){super(...arguments);f(this,"pcb_panel_id",null);f(this,"_tabsAndMouseBitesGenerated",!1)}get config(){return{componentName:"Panel",zodProps:hH}}get isGroup(){return!0}get isSubcircuit(){return!0}add(e){if(e.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(e)}doInitialPanelLayout(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.children.filter(a=>a instanceof TP),i=t.some(a=>a.props.pcbX!==void 0||a.props.pcbY!==void 0),r=t.filter(a=>a.props.pcbX===void 0&&a.props.pcbY===void 0);if(r.length>0&&!i){let a=this._parsedProps.tabWidth??Hnt,c=this._parsedProps.boardGap??a,{positions:l,gridWidth:u,gridHeight:p}=Bzt({boards:r,db:e,row:this._parsedProps.row,col:this._parsedProps.col,cellWidth:this._parsedProps.cellWidth,cellHeight:this._parsedProps.cellHeight,boardGap:c}),d=this._getGlobalPcbPositionBeforeLayout();for(let{board:x,pos:b}of l){let S=d.x+b.x,P=d.y+b.y;x._repositionOnPcb({x:S,y:P}),e.pcb_board.update(x.pcb_board_id,{center:{x:S,y:P}})}let _=this._parsedProps.width!==void 0,g=this._parsedProps.height!==void 0;if(_&&g)e.pcb_panel.update(this.pcb_panel_id,{width:V.parse(this._parsedProps.width),height:V.parse(this._parsedProps.height)});else if(u>0||p>0){let{edgePadding:x,edgePaddingLeft:b,edgePaddingRight:S,edgePaddingTop:P,edgePaddingBottom:T}=this._parsedProps,k=V.parse(x??5),N=V.parse(b??k),M=V.parse(S??k),C=V.parse(P??k),E=V.parse(T??k);e.pcb_panel.update(this.pcb_panel_id,{width:_?V.parse(this._parsedProps.width):u+N+M,height:g?V.parse(this._parsedProps.height):p+C+E})}}if(this._tabsAndMouseBitesGenerated)return;let s=this._parsedProps;if((s.panelizationMethod??"none")!=="none"){let a=t.map(_=>_.pcb_board_id).filter(_=>!!_),c=e.pcb_board.list().filter(_=>a.includes(_.pcb_board_id));if(c.length===0)return;let l=s.tabWidth??Hnt,u=s.boardGap??l,{tabCutouts:p,mouseBiteHoles:d}=jzt(c,{boardGap:u,tabWidth:l,tabLength:s.tabLength??$zt,mouseBites:s.mouseBites??!0});for(let _ of p)e.pcb_cutout.insert(_);for(let _ of d)e.pcb_hole.insert(_)}this._tabsAndMouseBitesGenerated=!0}runRenderCycle(){if(!this.children.some(e=>e.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}doInitialPcbComponentRender(){if(super.doInitialPcbComponentRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps,i=e.pcb_panel.insert({width:t.width!==void 0?V.parse(t.width):0,height:t.height!==void 0?V.parse(t.height):0,center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(t.noSolderMask??!1)});this.pcb_panel_id=i.pcb_panel_id}updatePcbComponentRender(){if(this.root?.pcbDisabled||!this.pcb_panel_id)return;let{db:e}=this.root,t=this._parsedProps,i=e.pcb_panel.get(this.pcb_panel_id);e.pcb_panel.update(this.pcb_panel_id,{width:t.width!==void 0?V.parse(t.width):i?.width,height:t.height!==void 0?V.parse(t.height):i?.height,center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(t.noSolderMask??!1)})}removePcbComponentRender(){this.pcb_panel_id&&(this.root?.db.pcb_panel.delete(this.pcb_panel_id),this.pcb_panel_id=null)}},Eit=class extends n0{constructor(n){super(n)}get config(){return{...super.config,componentName:"Pinout",zodProps:dH}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=t.source_component_id}},Cit=class extends Yn{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:_H,sourceFtype:qa.simple_fuse}}_getSchematicSymbolDisplayValue(){let n=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,t=typeof n=="string"?parseFloat(n):n,i=typeof e=="string"?parseFloat(e):e;return`${ei(t)}A / ${ei(i)}V`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=typeof e.currentRating=="string"?parseFloat(e.currentRating):e.currentRating,i=typeof e.voltageRating=="string"?parseFloat(e.voltageRating):e.voltageRating,r=n.source_component.insert({name:this.name,ftype:qa.simple_fuse,current_rating_amps:t,voltage_rating_volts:i,display_current_rating:`${ei(t)}A`,display_voltage_rating:`${ei(i)}V`});this.source_component_id=r.source_component_id}},Iit=class extends Yn{constructor(){super(...arguments);f(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:O4,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let t=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"?t:0,rightSize:i==="right"?t:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.pcb_component.insert({center:{x:i,y:r},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let o=0;o<t.length;o++){let a=t[o],c=e.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(p=>/^(pin)?\d+$/.test(p));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),s=o=>{if(o&&typeof o=="string"&&o.startsWith("{PIN")){let a=o.replace("{PIN","").replace("}","");return i[a]||o}return o};for(let o of r)if(o.route)for(let a of o.route)a.route_type==="wire"&&(a.start_pcb_port_id=s(a.start_pcb_port_id),a.end_pcb_port_id=s(a.end_pcb_port_id))}},qnt={"0402":"0402","0603":"0603","0805":"0805",1206:"1206"},Nit=class extends Yn{get config(){return{componentName:"Interconnect",zodProps:mH,shouldRenderAsSchematicBox:!0,sourceFtype:"interconnect"}}get defaultInternallyConnectedPinNames(){let{standard:n}=this._parsedProps;return n&&qnt[n]?[["pin1","pin2"]]:[]}_getImpliedFootprintString(){let{standard:n}=this._parsedProps;return n?qnt[n]??null:null}doInitialSourceRender(){let{db:n}=this.root,e=n.source_component.insert({ftype:"interconnect",name:this.name,are_pins_interchangeable:!0});this.source_component_id=e.source_component_id}doInitialSourceParentAttachment(){let{db:n}=this.root,e=this._getInternallyConnectedPins();for(let t of e){let i=t.map(r=>r.source_port_id).filter(r=>r!==null);i.length>=2&&n.source_component_internal_connection.insert({source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id,source_port_ids:i})}}},Ait=class extends Yn{constructor(){super(...arguments);f(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(e){return this.selectOne(`port.${e}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let e=this.children.filter(t=>t.componentName==="Port").map(t=>t.name);return e.length>0?[e]:[]}return this._parsedProps.bridgedPins??[]}get config(){let e=this._parsedProps??this.props,t=e.pinCount;if(e.pinCount==null&&!e.footprint&&(t=2),e.pinCount==null){let s=(e.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),o=s.length>0?Math.max(...s):0,a=e.pinLabels?Object.keys(e.pinLabels).length:0,c=Math.max(o,a);(c===2||c===3)&&(t=c),t==null&&e.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(t=this.getPortsFromFootprint().length)}let i="";t?i+=`solderjumper${t}`:i="solderjumper";let r=[];return Array.isArray(e.bridgedPins)&&e.bridgedPins.length>0?r=Array.from(new Set(e.bridgedPins.flat().map(s=>this._getPinNumberFromBridgedPinName(s)).filter(s=>s!==null))).sort((s,o)=>s-o):e.bridged&&t&&(r=Array.from({length:t},(s,o)=>o+1)),r.length>0&&(i+=`_bridged${r.join("")}`),{schematicSymbolName:e.symbolName??i,componentName:"SolderJumper",zodProps:fH,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let t=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);t==null&&!this._parsedProps.footprint&&(t=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?t:0,rightSize:i==="right"?t:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.pcb_component.insert({center:{x:i,y:r},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let o=0;o<t.length;o++){let a=t[o],c=e.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(p=>/^(pin)?\d+$/.test(p));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),s=o=>{if(o&&typeof o=="string"&&o.startsWith("{PIN")){let a=o.replace("{PIN","").replace("}","");return i[a]||o}return o};for(let o of r)if(o.route)for(let a of o.route)a.route_type==="wire"&&(a.start_pcb_port_id=s(a.start_pcb_port_id),a.end_pcb_port_id=s(a.end_pcb_port_id))}},Rit=class extends Yn{constructor(){super(...arguments);f(this,"pos",this.portMap.pin1);f(this,"anode",this.portMap.pin1);f(this,"neg",this.portMap.pin2);f(this,"cathode",this.portMap.pin2)}get config(){let e={laser:"laser_diode"},t=this.props.laser?"laser":null;return{schematicSymbolName:t?e[t]:this.props.symbolName??"led",componentName:"Led",zodProps:YH,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 e=super.getFootprinterString();return e&&this.props.color?`${e}_color(${this.props.color})`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_led",name:this.name,wave_length:t.wavelength,color:t.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},Oit=class extends Yn{constructor(){super(...arguments);f(this,"pos",this.portMap.pin1);f(this,"positive",this.portMap.pin1);f(this,"neg",this.portMap.pin2);f(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:nq,sourceFtype:"simple_power_source"}}initPorts(){this.add(new qi({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new qi({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:t.voltage,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},Lit=class extends Yn{constructor(){super(...arguments);f(this,"terminal1",this.portMap.terminal1);f(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:iq,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(e){if(!e.startsWith("Pcb"))for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}_getSchematicSymbolDisplayValue(){let{voltage:e,frequency:t}=this._parsedProps,i=[];return e!==void 0&&i.push(`${ei(e)}V`),t!==void 0&&i.push(`${ei(t)}Hz`),i.length>0?i.join(" "):void 0}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:t.voltage,frequency:t.frequency,peak_to_peak_voltage:t.peakToPeakVoltage,wave_shape:t.waveShape,phase:t.phase,duty_cycle:t.dutyCycle,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.portMap.terminal1,r=this.portMap.terminal2;e.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:r.source_port_id,voltage:t.voltage,frequency:t.frequency,peak_to_peak_voltage:t.peakToPeakVoltage,wave_shape:t.waveShape,phase:t.phase,duty_cycle:t.dutyCycle})}},Yzt=["leftedge","rightedge","topedge","bottomedge","center"],Fit=class extends Ce{get config(){return{componentName:"Constraint",zodProps:kH}}constructor(n){if(super(n),("xdist"in n||"ydist"in n)&&!("edgeToEdge"in n)&&!("centerToCenter"in n))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in n&&n.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let n=[],e=this.getPrimitiveContainer();function t(i){let r=i.split(" ").pop(),s=Yzt.includes(r)?r:void 0,o=s?i.replace(` ${s}`,""):i,a=e.selectOne(o,{pcbPrimitive:!0});a&&n.push({selector:i,component:a,componentSelector:o,edge:s})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&t(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)t(i);return{componentsWithSelectors:n}}},zit=class extends Ce{constructor(){super(...arguments);f(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:GH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),o=s(t.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for FabricationNoteRect. Must be "top" or "bottom".`);let a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=this.getSubcircuit(),l=t.hasStroke??(t.strokeWidth!==void 0&&t.strokeWidth!==null),u=e.pcb_fabrication_note_rect.insert({pcb_component_id:a,layer:o,color:t.color,center:{x:i,y:r},width:t.width,height:t.height,stroke_width:t.strokeWidth??1,is_filled:t.isFilled??!1,has_stroke:l,is_stroke_dashed:t.isStrokeDashed??!1,subcircuit_id:c?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,corner_radius:t.cornerRadius??void 0});this.fabrication_note_rect_id=u.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},$it=class extends Ce{constructor(){super(...arguments);f(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:WH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.getSubcircuit(),{_parsedProps:i}=this,r=i.layer??"top";if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let s=this._computePcbGlobalTransformBeforeLayout(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_fabrication_note_path.insert({pcb_component_id:o,layer:r,color:i.color,route:i.route.map(c=>{let l=je(s,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:t?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},Dit=class extends Ce{get config(){return{componentName:"FabricationNoteText",zodProps:VH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:n}=this.root,{_parsedProps:e}=this,{pcbX:t,pcbY:i}=this.getResolvedPcbPositionProp(),r=this.getPrimitiveContainer(),s=this.getSubcircuit();n.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:t,y:i},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:vP(e.text??""),pcb_component_id:r.pcb_component_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},jit=class extends Ce{constructor(){super(...arguments);f(this,"fabrication_note_dimension_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:HH}}_resolvePoint(e,t){if(typeof e=="string"){let s=this.getSubcircuit().selectOne(e);return s?s._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${e}"`),je(t,{x:0,y:0}))}let i=typeof e.x=="string"?parseFloat(e.x):e.x,r=typeof e.y=="string"?parseFloat(e.y):e.y;return je(t,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(t.from,i),s=this._resolvePoint(t.to,i),o=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(t.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,p=t.text??this._formatDistanceText({from:r,to:s,units:t.units??"mm"}),d=e.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:r,to:s,text:p,offset:t.offset,font:t.font??"tscircuit2024",font_size:t.fontSize??1,color:t.color,arrow_size:t.arrowSize??1});this.fabrication_note_dimension_id=d.pcb_fabrication_note_dimension_id}getPcbSize(){let e=this._computePcbGlobalTransformBeforeLayout(),t=this._resolvePoint(this._parsedProps.from,e),i=this._resolvePoint(this._parsedProps.to,e);return{width:Math.abs(i.x-t.x),height:Math.abs(i.y-t.y)}}_formatDistanceText({from:e,to:t,units:i}){let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s),a=i==="in"?o/25.4:o,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}`}},Bit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_note_line_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:wq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this.getGroup(),s=this._computePcbGlobalTransformBeforeLayout(),o=je(s,{x:t.x1,y:t.y1}),a=je(s,{x:t.x2,y:t.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=e.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,x1:o.x,y1:o.y,x2:a.x,y2:a.y,stroke_width:t.strokeWidth??.1,color:t.color,is_dashed:t.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:e}=this;return{width:Math.abs(e.x2-e.x1),height:Math.abs(e.y2-e.y1)}}},Yit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_note_rect_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:vq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=je(i,{x:0,y:0}),s=this.getSubcircuit(),o=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=e.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,center:r,width:t.width,height:t.height,stroke_width:t.strokeWidth??.1,is_filled:t.isFilled??!1,has_stroke:t.hasStroke??!0,is_stroke_dashed:t.isStrokeDashed??!1,color:t.color,corner_radius:t.cornerRadius??void 0});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:e}=this,t=typeof e.width=="string"?parseFloat(e.width):e.width,i=typeof e.height=="string"?parseFloat(e.height):e.height;return{width:t,height:i}}},Xit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_note_text_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:bq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=je(i,{x:0,y:0}),s=this.getSubcircuit(),o=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=e.pcb_note_text.insert({pcb_component_id:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,font:t.font??"tscircuit2024",font_size:t.fontSize??1,text:vP(t.text),anchor_position:r,anchor_alignment:t.anchorAlignment??"center",color:t.color});this.pcb_note_text_id=c.pcb_note_text_id}getPcbSize(){let{_parsedProps:e}=this,t=typeof e.fontSize=="string"?parseFloat(e.fontSize):e.fontSize??1,i=t*.6;return{width:e.text.length*i,height:t}}},Uit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_note_path_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:Sq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this.getSubcircuit(),s=this.getGroup(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=t.route.map(l=>{let{x:u,y:p,...d}=l,_=typeof u=="string"?parseFloat(u):u,g=typeof p=="string"?parseFloat(p):p,x=je(i,{x:_,y:g});return{...d,x:x.x,y:x.y}}),c=e.pcb_note_path.insert({pcb_component_id:o,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,route:a,stroke_width:t.strokeWidth??.1,color:t.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:e}=this;if(e.route.length===0)return{width:0,height:0};let t=e.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=e.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),r=Math.min(...t),s=Math.max(...t),o=Math.min(...i),a=Math.max(...i);return{width:s-r,height:a-o}}},Vit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_note_dimension_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:Pq}}_resolvePoint(e,t){if(typeof e=="string"){let s=this.getSubcircuit().selectOne(`.${e}`);return s?s._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${e}"`),je(t,{x:0,y:0}))}let i=typeof e.x=="string"?parseFloat(e.x):e.x,r=typeof e.y=="string"?parseFloat(e.y):e.y;return je(t,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(t.from,i),s=this._resolvePoint(t.to,i),o=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.text??this._formatDistanceText({from:r,to:s,units:t.units??"mm"}),u=e.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:r,to:s,text:l,font:t.font??"tscircuit2024",font_size:t.fontSize??1,color:t.color,arrow_size:t.arrowSize??1});this.pcb_note_dimension_id=u.pcb_note_dimension_id}getPcbSize(){let e=this._computePcbGlobalTransformBeforeLayout(),t=this._resolvePoint(this._parsedProps.from,e),i=this._resolvePoint(this._parsedProps.to,e);return{width:Math.abs(i.x-t.x),height:Math.abs(i.y-t.y)}}_formatDistanceText({from:e,to:t,units:i}){let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s),a=i==="in"?o/25.4:o,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}`}},Git=class extends Tl{constructor(n){super({...n,subcircuit:!0})}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:n,children:e}=this._parsedProps;Tit(this,n,e)}},Wit=class extends Tl{constructor(n){super({...n,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:n}=this.root,e=this._parsedProps;if(!this.pcb_group_id)return;let t=n.pcb_group.get(this.pcb_group_id),i=e.paddingLeft??e.padding??0,r=e.paddingRight??e.padding??0,s=e.paddingTop??e.padding??0,o=e.paddingBottom??e.padding??0;n.pcb_group.update(this.pcb_group_id,{width:(t.width??0)+i+r,height:(t.height??0)+s+o,center:{x:t.center.x+(r-i)/2,y:t.center.y+(s-o)/2}})}},Hit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_breakout_point_id",null);f(this,"matchedPort",null);f(this,"matchedNet",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:KH}}_matchConnection(){let{connection:e}=this._parsedProps,t=this.getSubcircuit();t&&(this.matchedPort=t.selectOne(e,{type:"port"}),this.matchedPort||(this.matchedNet=t.selectOne(e,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${e}"`))}_getSourceTraceIdForPort(e){let{db:t}=this.root;return t.source_trace.list().find(r=>r.connected_source_port_ids.includes(e.source_port_id))?.source_trace_id}_getSourceNetIdForPort(e){let{db:t}=this.root;return t.source_trace.list().find(r=>r.connected_source_port_ids.includes(e.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;this._matchConnection();let{pcbX:t,pcbY:i}=this.getResolvedPcbPositionProp(),r=this.parent?.getGroup(),s=this.getSubcircuit();if(!r||!r.pcb_group_id)return;let o=e.pcb_breakout_point.insert({pcb_group_id:r.pcb_group_id,subcircuit_id:s?.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:t,y:i});this.pcb_breakout_point_id=o.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:e,pcbY:t}=this.getResolvedPcbPositionProp();return{center:{x:e,y:t},bounds:{left:e,top:t,right:e,bottom:t},width:0,height:0}}_setPositionFromLayout(e){let{db:t}=this.root;this.pcb_breakout_point_id&&t.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:e.x,y:e.y})}getPcbSize(){return{width:0,height:0}}},qit=class extends Ce{constructor(){super(...arguments);f(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:OH}}_getAnchorSide(){let{_parsedProps:e}=this;if(e.anchorSide)return e.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";let s=r[0]._getGlobalSchematicPositionBeforeLayout(),o=s.x-i.x,a=s.y-i.y;if(Math.abs(o)>Math.abs(a)){if(o>0)return"right";if(o<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let e=this._resolveConnectsTo();if(!e)return[];let t=[];for(let i of e){let r=this.getSubcircuit().selectOne(i);r&&t.push(r)}return t}computeSchematicPropsTransform(){let{_parsedProps:e}=this;if(e.schX===void 0&&e.schY===void 0){let t=this._getConnectedPorts();if(t.length>0){let i=t[0]._getGlobalSchematicPositionBeforeLayout(),r=je(this.parent?.computeSchematicGlobalTransform?.()??Pr(),{x:0,y:0});return Tn(i.x-r.x,i.y-r.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),s=t.anchorSide??"right",o=kl({anchor_position:i,anchor_side:s,text:t.net}),a=e.schematic_net_label.insert({text:t.net,source_net_id:r.source_net_id,anchor_position:i,center:o,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:e}=this,t=e.connectsTo??e.connection;if(Array.isArray(t))return t;if(typeof t=="string")return[t]}_getNetName(){let{_parsedProps:e}=this;return e.net}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;e.net&&bP(this,[`net.${e.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let e=this._resolveConnectsTo();if(e)for(let t of e)this.add(new Ds({from:t,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:e}=this.root,t=this._resolveConnectsTo();if(!t||t.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),o={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of t){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let S=e.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id??""));if(S&&(u=e.schematic_trace.list().some(P=>P.source_trace_id===S.source_trace_id)),u)continue}let p=l._getGlobalSchematicPositionAfterLayout(),d=O9(l.facingDirection??"right")??"x+",_=tl({x:p.x,y:p.y,facingDirection:d},{x:i.x,y:i.y,facingDirection:o});if(!Array.isArray(_)||_.length<2)continue;let g=[];for(let S=0;S<_.length-1;S++)g.push({from:{x:_[S].x,y:_[S].y},to:{x:_[S+1].x,y:_[S+1].y}});let x,b;if(a?.source_net_id&&l.source_port_id){let S=e.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id));x=S?.source_trace_id,b=S?.subcircuit_connectivity_map_key||e.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}e.schematic_trace.insert({source_trace_id:x,edges:g,junctions:[],subcircuit_connectivity_map_key:b}),e.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},Zit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_silkscreen_circle_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:gq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),o=s(t.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenCircle. Must be "top" or "bottom".`);let a=this._computePcbGlobalTransformBeforeLayout(),c=this.getSubcircuit(),l=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,u=e.pcb_silkscreen_circle.insert({pcb_component_id:l,layer:o,center:{x:i,y:r},radius:t.radius,subcircuit_id:c?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_circle_id=u.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:e}=this,t=e.radius*2;return{width:t,height:t}}},Kit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_silkscreen_rect_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:yq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenRect. Must be "top" or "bottom".`);let s=this.getSubcircuit(),{pcbX:o,pcbY:a}=this.getResolvedPcbPositionProp(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,l=e.pcb_silkscreen_rect.insert({pcb_component_id:c,layer:r,center:{x:o,y:a},width:t.width,height:t.height,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:t.strokeWidth??.1,is_filled:t.filled??!1,corner_radius:t.cornerRadius??void 0});this.pcb_silkscreen_rect_id=l.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},Jit=class extends Ce{constructor(){super(...arguments);f(this,"pcb_silkscreen_line_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:_q}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenLine. Must be "top" or "bottom".`);let s=this.getSubcircuit(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_silkscreen_line.insert({pcb_component_id:o,layer:r,x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,stroke_width:t.strokeWidth??.1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:s?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:e}=this,t=Math.abs(e.x2-e.x1),i=Math.abs(e.y2-e.y1);return{width:t,height:i}}},Qit=class extends Ce{constructor(e){super(e);f(this,"pcb_via_id",null);f(this,"matchedPort",null);f(this,"isPcbPrimitive",!0);f(this,"source_manually_placed_via_id",null);f(this,"subcircuit_connectivity_map_key",null);let t=this._getLayers();this._parsedProps.layers=t,this.initPorts()}get config(){return{componentName:"Via",zodProps:qH}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}_getResolvedViaDiameters(e){return lFt({holeDiameter:this._parsedProps.holeDiameter,padDiameter:this._parsedProps.outerDiameter},e)}getPcbSize(){let e=this.getInheritedMergedProperty("pcbStyle"),{padDiameter:t}=this._getResolvedViaDiameters(e);return{width:t,height:t}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-i.width/2,top:t.y-i.height/2,right:t.x+i.width/2,bottom:t.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}_getLayers(){let{fromLayer:e="top",toLayer:t="bottom"}=this._parsedProps;return e===t?[e]:[e,t]}initPorts(){let e=this._parsedProps.layers;for(let i of e){let r=new qi({name:i,layer:i});r.registerMatch(this),this.add(r)}let t=new qi({name:"pin1"});t.registerMatch(this),this.add(t)}_getConnectedNetOrTrace(){let e=this._parsedProps.connectsTo;if(!e)return null;let t=this.getSubcircuit(),i=Array.isArray(e)?e:[e];for(let r of i)if(r.startsWith("net.")){let s=t.selectOne(r,{type:"net"});if(s)return s}return null}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.getInheritedMergedProperty("pcbStyle"),{padDiameter:i}=this._getResolvedViaDiameters(t),r=this._getGlobalPcbPositionBeforeLayout(),s=this.getSubcircuit(),o=e.pcb_component.insert({center:r,width:i,height:i,layer:this._parsedProps.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:s?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=o.pcb_component_id}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.getGroup(),r=this.getSubcircuit(),s=e.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:t.net??"",subcircuit_id:r?.subcircuit_id??void 0});this.source_component_id=s.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.getInheritedMergedProperty("pcbStyle"),{holeDiameter:i,padDiameter:r}=this._getResolvedViaDiameters(t),s=this._getGlobalPcbPositionBeforeLayout(),o=this.getSubcircuit(),a=e.pcb_via.insert({x:s.x,y:s.y,hole_diameter:i,outer_diameter:r,layers:["bottom","top"],from_layer:this._parsedProps.fromLayer||"bottom",to_layer:this._parsedProps.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:this._parsedProps.netIsAssignable??void 0});this.pcb_via_id=a.pcb_via_id}},trt=class extends Ce{constructor(){super(...arguments);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:QH}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;bP(this,[e.connectsTo])}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit().selectOne(t.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${t.connectsTo}" not found for copper pour`);return}let r=this.getSubcircuit(),s=e.toArray().filter(p=>p.type==="source_net"&&p.name===i.name)[0]||"",o=t.clearance??.2,a=iet(e.toArray(),{layer:t.layer,pour_connectivity_key:s.subcircuit_connectivity_map_key||"",pad_margin:t.padMargin??o,trace_margin:t.traceMargin??o,board_edge_margin:t.boardEdgeMargin??o,cutout_margin:t.cutoutMargin??o}),c=new net(a),{brep_shapes:l}=c.getOutput(),u=t.coveredWithSolderMask??!1;for(let p of l)e.pcb_copper_pour.insert({shape:"brep",layer:t.layer,brep_shape:p,source_net_id:i.source_net_id,subcircuit_id:r?.subcircuit_id??void 0,covered_with_solder_mask:u})})}},ert=class extends Yn{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:AH,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=t.source_component_id}},nrt=class extends Yn{_getPcbRotationBeforeLayout(){let n=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+n}get config(){return{componentName:"PinHeader",zodProps:RH,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),e=this._parsedProps.holeDiameter,t=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels,s=this._parsedProps.doubleRow?2:1;if(n>0){let o;if(i)!e&&!t?o=`pinrow${n}_p${i}`:o=`pinrow${n}_p${i}_id${e}_od${t}`;else if(!e&&!t)o=`pinrow${n}`;else return null;return r!==!0&&(o+="_nopinlabels"),s>1&&(o+=`_rows${s}`),o}return null}initPorts(){let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let e=1;e<=n;e++){let t=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[e-1]:this._parsedProps.pinLabels?.[`pin${e}`];if(t){let i=Array.isArray(t)?t[0]:t,r=Array.isArray(t)?t.slice(1):[];this.add(new qi({pinNumber:e,name:i,aliases:[`pin${e}`,...r]}))}else this.add(new qi({pinNumber:e,name:`pin${e}`}))}}_getSchematicPortArrangement(){let n=this._parsedProps.pinCount??1,e=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",t=this._parsedProps.schPinArrangement;return e==="left"?{leftSide:{direction:t?.leftSide?.direction??"top-to-bottom",pins:t?.leftSide?.pins??Array.from({length:n},(i,r)=>`pin${r+1}`)}}:{rightSide:{direction:t?.rightSide?.direction??"top-to-bottom",pins:t?.rightSide?.pins??Array.from({length:n},(i,r)=>`pin${r+1}`)}}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}};function Xzt(n){switch(n){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var irt=class extends Yn{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??Xzt(this.props.pinVariant),zodProps:SH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"no_ground",i=n.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:t,are_pins_interchangeable:t==="no_ground"||t==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let n=`${ei(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${ei(this._parsedProps.loadCapacitance)}F`:n}};function Uzt(n){switch(n){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var rrt=class extends Yn{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??Uzt(this.props.pinVariant),zodProps:bH,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${ei(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"two_pin",i=n.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:e.maxResistance,pin_variant:t,are_pins_interchangeable:t==="two_pin"});this.source_component_id=i.source_component_id}},srt=class extends Yn{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:LH,sourceFtype:qa.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let n=bi[this._getSchematicSymbolNameOrThrow()],e=n.ports.find(l=>l.labels.includes("1")),t=n.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),r=i.find(l=>l.props.pinNumber===1),s=i.find(l=>l.props.pinNumber===2),o=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;r.schematicSymbolPortDef=e,(!c||c.length===0)&&(s.schematicSymbolPortDef=t);for(let[l,u]of[[2,s],[3,o],[4,a]]){let p=c?.find(([_,g])=>_===`pin${l}`||g===`pin${l}`);if(!p){u.schematicSymbolPortDef=t;break}(p?.[0]===`pin${l}`?p[1]:p?.[0])!=="pin1"&&(u.schematicSymbolPortDef=t)}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:qa.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},ort=class extends Yn{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:vH,sourceFtype:"simple_crystal"}}initPorts(){let n=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:n})}_getSchematicSymbolDisplayValue(){let n=`${ei(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${ei(this._parsedProps.loadCapacitance)}F`:n}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin",are_pins_interchangeable:(e.pinVariant||"two_pin")==="two_pin"});this.source_component_id=t.source_component_id}},art=class extends Yn{get config(){let n=this.props.mosfetMode==="depletion"?"d":"e",t=`${this.props.channelType}_channel_${n}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??t,zodProps:$H,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=t.source_component_id}};function Vzt(n){return n.simSwitchFrequency!==void 0||n.simCloseAt!==void 0||n.simOpenAt!==void 0||n.simStartClosed!==void 0||n.simStartOpen!==void 0}var crt=class extends Yn{_getSwitchType(){let n=this._parsedProps;return n?n.dpdt?"dpdt":n.spst?"spst":n.spdt?"spdt":n.dpst?"dpst":n.type??"spst":"spst"}get config(){let n=this._getSwitchType(),e=this._parsedProps?.isNormallyClosed??!1,t={spst:e?"spst_normally_closed_switch":"spst_switch",spdt:e?"spdt_normally_closed_switch":"spdt_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??t[n],zodProps:UH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,e=this._parsedProps??{},t=n.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=t.source_component_id}doInitialSimulationRender(){let{_parsedProps:n}=this;if(!Vzt(n))return;let{db:e}=this.root,t={type:"simulation_switch",source_component_id:this.source_component_id||""};n.simSwitchFrequency!==void 0&&(t.switching_frequency=$r.parse(n.simSwitchFrequency)),n.simCloseAt!==void 0&&(t.closes_at=hr.parse(n.simCloseAt)),n.simOpenAt!==void 0&&(t.opens_at=hr.parse(n.simOpenAt)),n.simStartOpen!==void 0&&(t.starts_closed=!n.simStartOpen),n.simStartClosed!==void 0&&(t.starts_closed=n.simStartClosed),e.simulation_switch.insert(t)}},N9={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},lrt=class extends Yn{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:ZH,sourceFtype:qa.simple_test_point}}_getPropsWithDefaults(){let{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}=this._parsedProps;return!t&&e&&(t="through_hole"),t??(t="through_hole"),n??(n="circle"),t==="pad"?n==="circle"?i??(i=N9.SMT_CIRCLE_DIAMETER):n==="rect"&&(r??(r=N9.SMT_RECT_SIZE),s??(s=r)):t==="through_hole"&&(e??(e=N9.HOLE_DIAMETER)),{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}}_getImpliedFootprintString(){let{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}=this._getPropsWithDefaults();if(t==="through_hole")return`platedhole_d${e}`;if(t==="pad"){if(n==="circle")return`smtpad_circle_d${i}`;if(n==="rect")return`smtpad_rect_w${r}_h${s}`}throw new Error(`Footprint variant "${t}" with pad shape "${n}" not implemented`)}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,{padShape:t,holeDiameter:i,footprintVariant:r,padDiameter:s,width:o,height:a}=this._getPropsWithDefaults(),c=n.source_component.insert({ftype:qa.simple_test_point,name:this.name,supplier_part_numbers:e.supplierPartNumbers,footprint_variant:r,pad_shape:t,pad_diameter:s,hole_diameter:i,width:o,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},urt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:uq}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout();e.schematic_text.insert({anchor:t.anchor??"center",text:vP(t.text),font_size:t.fontSize,color:t.color||"#000000",position:{x:i.x,y:i.y},rotation:t.schRotation??0})}},prt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:lq}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_line.insert({schematic_component_id:r,x1:t.x1+i.x,y1:t.y1+i.y,x2:t.x2+i.x,y2:t.y2+i.y,stroke_width:t.strokeWidth??kP,color:t.color??PP,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=s.schematic_line_id}},hrt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:cq}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_rect.insert({center:{x:i.x,y:i.y},width:t.width,height:t.height,stroke_width:t.strokeWidth??kP,color:t.color??PP,is_filled:t.isFilled,schematic_component_id:r,is_dashed:t.isDashed,rotation:t.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=s.schematic_rect_id}},drt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:sq}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_arc.insert({schematic_component_id:r,center:{x:t.center.x+i.x,y:t.center.y+i.y},radius:t.radius,start_angle_degrees:t.startAngleDegrees,end_angle_degrees:t.endAngleDegrees,direction:t.direction,stroke_width:t.strokeWidth??kP,color:t.color??PP,is_dashed:t.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=s.schematic_arc_id}},frt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:aq}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_circle.insert({schematic_component_id:r,center:{x:t.center.x+i.x,y:t.center.y+i.y},radius:t.radius,stroke_width:t.strokeWidth??kP,color:t.color??PP,is_filled:t.isFilled,fill_color:t.fillColor,is_dashed:t.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=s.schematic_circle_id}};function Gzt({anchor:n,x:e,y:t,width:i,height:r,isInside:s}){switch(n){case"top_left":return{x:e,y:t+r,textAnchor:s?"top_left":"bottom_left"};case"top_center":return{x:e+i/2,y:t+r,textAnchor:s?"top_center":"bottom_center"};case"top_right":return{x:e+i,y:t+r,textAnchor:s?"top_right":"bottom_right"};case"center_left":return{x:e,y:t+r/2,textAnchor:s?"center_left":"center_right"};case"center":return{x:e+i/2,y:t+r/2,textAnchor:"center"};case"center_right":return{x:e+i,y:t+r/2,textAnchor:s?"center_right":"center_left"};case"bottom_left":return{x:e,y:t,textAnchor:s?"bottom_left":"top_left"};case"bottom_center":return{x:e+i/2,y:t,textAnchor:s?"bottom_center":"top_center"};case"bottom_right":return{x:e+i,y:t,textAnchor:s?"bottom_right":"top_right"};default:return{x:e+i/2,y:t+r,textAnchor:"center"}}}var mrt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:oq,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=.6,r=typeof t.padding=="number"?t.padding:0,s=typeof t.paddingTop=="number"?t.paddingTop:r,o=typeof t.paddingBottom=="number"?t.paddingBottom:r,a=typeof t.paddingLeft=="number"?t.paddingLeft:r,c=typeof t.paddingRight=="number"?t.paddingRight:r,l=t.overlay&&t.overlay.length>0,u=typeof t.width=="number"&&typeof t.height=="number",p,d,_,g,x,b;if(l){let P=t.overlay.map(J=>({selector:J,port:this.getSubcircuit().selectOne(J,{type:"port"})})).filter(({port:J})=>J!=null).map(({port:J})=>({position:J._getGlobalSchematicPositionAfterLayout()}));if(P.length===0)return;let T=P.map(J=>J.position.x),k=P.map(J=>J.position.y),N=Math.min(...T),M=Math.max(...T),C=Math.min(...k),E=Math.max(...k),R=M-N,A=E-C,j=R===0?i:0,D=A===0?i:0,Y=a+j/2,X=c+j/2,W=s+D/2,et=o+D/2,H=N-Y,dt=M+X,G=C-et,nt=E+W;p=dt-H,d=nt-G,_=H+(t.schX??0),g=G+(t.schY??0),x=_+p/2,b=g+d/2}else if(u){p=t.width,d=t.height;let S=this._getGlobalSchematicPositionBeforeLayout();x=S.x,b=S.y,_=x-p/2,g=b-d/2}else return;if(e.schematic_box.insert({height:d,width:p,x:_,y:g,is_dashed:t.strokeStyle==="dashed"}),t.title){let S=t.titleInside,P=.1,T=t.titleAlignment,k=Gzt({anchor:T,x:_,y:g,width:p,height:d,isInside:S}),N,M,C=k.textAnchor;S?(N=T.includes("top")?-P:T.includes("bottom")?P:0,M=T.includes("left")?P:T.includes("right")?-P:0):(N=T.includes("top")?P:T.includes("bottom")?-P:0,M=T.includes("center_left")?-P:T.includes("center_right")?P:0);let E=k.x+M,R=k.y+N;e.schematic_text.insert({anchor:C,text:t.title,font_size:t.titleFontSize??.18,color:t.titleColor??"#000000",position:{x:E,y:R},rotation:0})}}},_rt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:pq}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.children.filter(d=>d.componentName==="SchematicRow");if(i.length===0)return;let r=[],s=0;for(let d of i){let _=d.children.filter(g=>g.componentName==="SchematicCell");s=Math.max(s,_.length)}for(let d=0;d<i.length;d++)r[d]=[];for(let d=0;d<i.length;d++){let g=i[d].children.filter(b=>b.componentName==="SchematicCell"),x=0;for(let b=0;b<g.length;b++){for(;r[d][x];)x++;let S=g[b],P=S._parsedProps.colSpan??1,T=S._parsedProps.rowSpan??1;for(let k=0;k<T;k++)for(let N=0;N<P;N++)r[d+k]||(r[d+k]=[]),r[d+k][x+N]=S;x+=P}}s=Math.max(0,...r.map(d=>d.length));let o=i.map((d,_)=>d._parsedProps.height??1),a=Array.from({length:s},(d,_)=>{let g=0;for(let x=0;x<i.length;x++){let b=r[x]?.[_];if(b){let S=b._parsedProps.text??b._parsedProps.children,P=b._parsedProps.width??(S?.length??2)*.5;P>g&&(g=P)}}return g||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=e.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:o,cell_padding:t.cellPadding,border_width:t.borderWidth,anchor:t.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,p=0;for(let d=0;d<i.length;d++){let _=0;for(let g=0;g<s;g++){let x=r[d]?.[g];if(x&&!u.has(x)){u.add(x);let b=x._parsedProps,S=b.rowSpan??1,P=b.colSpan??1,T=0;for(let N=0;N<P;N++)T+=a[g+N];let k=0;for(let N=0;N<S;N++)k+=o[d+N];e.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:d,end_row_index:d+S-1,start_column_index:g,end_column_index:g+P-1,text:b.text??b.children,center:{x:c.x+_+T/2,y:c.y-p-k/2},width:T,height:k,horizontal_align:b.horizontalAlign,vertical_align:b.verticalAlign,font_size:b.fontSize??t.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[g]&&(_+=a[g])}p+=o[d]}}},yrt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:hq}}},grt=class extends Ce{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:dq}}},xrt=class extends Ce{constructor(){super(...arguments);f(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:NH}}},brt=class extends Ce{get config(){return{componentName:"AnalogSimulation",zodProps:FH}}doInitialSimulationRender(){let{db:n}=this.root,{duration:e,timePerStep:t}=this._parsedProps,i=e||10,r=t||.01;n.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:r})}},vrt=class extends Ce{constructor(){super(...arguments);f(this,"simulation_voltage_probe_id",null);f(this,"schematic_voltage_probe_id",null);f(this,"finalProbeName",null);f(this,"color",null)}get config(){return{componentName:"VoltageProbe",zodProps:rq}}doInitialSimulationRender(){let{db:e}=this.root,{connectsTo:t,name:i,referenceTo:r,color:s}=this._parsedProps,o=this.getSubcircuit();if(!o){this.renderError("VoltageProbe must be inside a subcircuit");return}let a=Array.isArray(t)?t:[t];if(a.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let c=a[0],l=o.selectOne(c,{type:"port"}),u=l?null:o.selectOne(c,{type:"net"});if(u&&u.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${c}" resolved to a non-net component "${u.componentName}".`);return}if(!l&&!u){this.renderError(`VoltageProbe could not find connection target "${c}"`);return}let p=l?.source_port_id??u?.source_net_id;if(!p){this.renderError("Could not identify connected source for VoltageProbe");return}let d=null,_=null;if(r){let b=Array.isArray(r)?r:[r];if(b.length!==1){this.renderError("VoltageProbe must reference exactly one port or net");return}let S=b[0];if(d=o.selectOne(S,{type:"port"}),_=d?null:o.selectOne(S,{type:"net"}),_&&_.componentName!=="Net"){this.renderError(`VoltageProbe reference target "${S}" resolved to a non-net component "${_.componentName}".`);return}if(!d&&!_){this.renderError(`VoltageProbe could not find reference target "${S}"`);return}}this.color=s??bzt(p);let g=i;g||(g=a[0].split(" > ").map(b=>b.replace(/^\./,"")).join(".")),this.finalProbeName=g??null;let{simulation_voltage_probe_id:x}=e.simulation_voltage_probe.insert({name:g,signal_input_source_port_id:l?.source_port_id??void 0,signal_input_source_net_id:u?.source_net_id??void 0,reference_input_source_port_id:d?.source_port_id??void 0,reference_input_source_net_id:_?.source_net_id??void 0,subcircuit_id:o.subcircuit_id||void 0,color:this.color});this.simulation_voltage_probe_id=x}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{connectsTo:t,name:i}=this._parsedProps,r=this.getSubcircuit();if(!r)return;let s=Array.isArray(t)?t:[t];if(s.length!==1)return;let o=s[0],a=r.selectOne(o,{type:"port"});if(!a||!a.schematic_port_id)return;let c=a._getGlobalSchematicPositionAfterLayout(),l=null;for(let d of e.schematic_trace.list()){for(let _ of d.edges)if(Math.abs(_.from.x-c.x)<1e-6&&Math.abs(_.from.y-c.y)<1e-6||Math.abs(_.to.x-c.x)<1e-6&&Math.abs(_.to.y-c.y)<1e-6){l=d.schematic_trace_id;break}if(l)break}if(!l)return;let u=this.finalProbeName,p=e.schematic_voltage_probe.insert({name:u,position:c,schematic_trace_id:l,subcircuit_id:r.subcircuit_id||void 0,color:this.color??void 0});this.schematic_voltage_probe_id=p.schematic_voltage_probe_id}},Wzt={name:"@tscircuit/core",type:"module",version:"0.0.916",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.178","@tscircuit/checks":"^0.0.87","@tscircuit/circuit-json-util":"^0.0.73","@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.8","@tscircuit/props":"^0.0.426","@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.328","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.23","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.30","circuit-to-svg":"^0.0.284",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.14","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.66","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"}},ny=class{constructor({platform:n,projectUrl:e}={}){f(this,"firstChild",null);f(this,"children");f(this,"db");f(this,"root",null);f(this,"isRoot",!0);f(this,"_schematicDisabledOverride");f(this,"pcbDisabled",!1);f(this,"pcbRoutingDisabled",!1);f(this,"_featureMspSchematicTraceRouting",!0);f(this,"name");f(this,"platform");f(this,"projectUrl");f(this,"_hasRenderedAtleastOnce",!1);f(this,"_eventListeners",{});this.children=[],this.db=Ie([]),this.root=this,this.platform=n,this.projectUrl=e,this.pcbDisabled=n?.pcbDisabled??!1}get schematicDisabled(){return this._schematicDisabledOverride!==void 0?this._schematicDisabledOverride:this._getBoard()?._parsedProps?.schematicDisabled??!1}set schematicDisabled(n){this._schematicDisabledOverride=n}add(n){let e;(0,Srt.isValidElement)(n)?e=nit(n):e=n,this.children.push(e)}setPlatform(n){this.platform={...this.platform,...n}}_getBoard(){let n=this.children.find(e=>e.componentName==="Board");if(n)return n}_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 n=this.children.filter(t=>t.lowercaseComponentName==="panel");if(n.length>1)throw new Error("Only one <panel> is allowed per circuit");if(n.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=n[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let e=new Tl({subcircuit:!0});e.parent=this,e.addAll(this.children),this.children=[e],this.firstChild=e}render(){this.firstChild||this._guessRootComponent();let{firstChild:n,db:e}=this;if(!n)throw new Error("RootCircuit has no root component");n.parent=this,n.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(e=>setTimeout(e,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(n=>n._hasIncompleteAsyncEffects())}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(n){let e=await Promise.resolve().then(()=>(ynt(),_nt)).catch(t=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
255
255
 
256
256
  "${t.message}"`)});if(n.view==="pcb")return e.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(n.view==="schematic")return e.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${n.view}`)}getCoreVersion(){let[n,e,t]=Wzt.version.split(".").map(Number);return`${n}.${e}.${t+1}`}async preview(n){let e=typeof n=="object"?n:{previewName:n};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return Pr()}_computePcbGlobalTransformBeforeLayout(){return Pr()}selectAll(n){return this._guessRootComponent(),this.firstChild?.selectAll(n)??[]}selectOne(n,e){return this._guessRootComponent(),this.firstChild?.selectOne(n,e)??null}emit(n,...e){if(this._eventListeners[n])for(let t of this._eventListeners[n])t(...e)}on(n,e){this._eventListeners[n]||(this._eventListeners[n]=[]),this._eventListeners[n].push(e)}removeListener(n,e){this._eventListeners[n]&&(this._eventListeners[n]=this._eventListeners[n].filter(t=>t!==e))}enableDebug(n){typeof n=="string"?j9.default.enable(n):(n===null||n===!1)&&j9.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},Hzt=ny,qzt=ny,Zzt=n=>{let[e,t]=Z_.default.useState(!0),[i,r]=Z_.default.useState(null),[s,o]=Z_.default.useState(),[a,c]=Z_.default.useState();return Z_.default.useEffect(()=>{t(!0),r(null),n&&setTimeout(()=>{try{let l=new ny;l.add(n),o(l),c(l.toJson())}catch(l){r(l)}t(!1)},1)},[n]),{isLoading:e,error:i,circuit:s,circuitJson:a}},iy=(n,e)=>(t,i)=>{let r=[];Array.isArray(e)?r.push(...e.flat()):typeof e=="object"&&r.push(...Object.values(e).flat(),...Object.keys(e));let s=o=>{if(o?.name&&o.name!==t)throw new Error(`Component name mismatch. Hook name: ${t}, Component prop name: ${o.name}`);let a={...i,...o,name:t},c=[];for(let l of r)if(a[l]){let u=`.${t} > .${l}`,p=a[l];c.push({from:u,to:p}),delete a[l]}return(0,Bd.jsxs)(Bd.Fragment,{children:[(0,Bd.jsx)(n,{...a}),c.map((l,u)=>(0,Bd.jsx)("trace",{...l},u))]})};for(let o of r)s[o]=`.${t} > .${o}`;return s},Kzt=iy(n=>(0,wrt.jsx)("capacitor",{...n}),PH),Jzt=n=>iy(e=>(0,Prt.jsx)("chip",{pinLabels:n,...e}),n),Qzt=iy(n=>(0,krt.jsx)("diode",{...n}),BH),t$t=iy(n=>(0,Trt.jsx)("led",{...n}),XH),e$t=iy(n=>(0,Mrt.jsx)("resistor",{...n}),xH),n$t=new Proxy(n=>new Proxy({},{get:(e,t)=>`.${n} > .${t}`}),{get:(n,e)=>{let t=(...i)=>{let r=i[0];return new Proxy({},{get:(s,o)=>`.${e} > .${o}`})};return new Proxy(t,{get:(i,r)=>e==="net"?`net.${r}`:e==="subcircuit"?new Proxy({},{get:(s,o)=>new Proxy({},{get:(a,c)=>`subcircuit.${r} > .${o} > .${c}`})}):`.${e} > .${r}`,apply:(i,r,s)=>e==="net"?new Proxy({},{get:(o,a)=>`net.${a}`}):new Proxy({},{get:(o,a)=>{let c=`.${e} > .${a}`;return["U","J","CN"].some(u=>e.startsWith(u))?c:new Proxy(new String(c),{get:(u,p)=>typeof p=="symbol"||p==="toString"?()=>c:`.${e} > .${a} > .${p}`})}})})}});eit(Znt);eit({Bug:n0});var vst=Vt(Qs(),1),R$t=Vt(xl(),1);var Crt=n=>{let e=n.match(/:[RC]_(\d{4})_/);if(e||(e=n.match(/:(SOIC-\d+|SOT-\d+|SOD-\d+|SSOP-\d+|TSSOP-\d+|QFP-\d+|QFN-\d+)/),e))return e[1]};var e6=n=>n.includes("cap")?n.replace(/cap/g,""):n;var Irt=n=>{if(n){if(n.startsWith("kicad:")){let e=Crt(n);return e?e6(e):n}return e6(n)}};var n6=new Map,Mr=async(n,e)=>{let t=new URLSearchParams({...e,json:"true"}).toString();if(n6.has(t))return n6.get(t);let r=await(await fetch(`https://jlcsearch.tscircuit.com/${n}/list?${t}`)).json();return n6.set(t,r),r},Er=n=>n?[...n].sort((e,t)=>Number(t.is_basic??!1)-Number(e.is_basic??!1)):[],Nrt={findPart:async({sourceComponent:n,footprinterString:e})=>{let t=Irt(e);if(n.type==="source_component"&&n.ftype==="simple_resistor"){let{resistors:i}=await Mr("resistors",{resistance:n.resistance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_capacitor"){let{capacitors:i}=await Mr("capacitors",{capacitance:n.capacitance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_pin_header"){let i;e?.includes("_p")&&(i=Number(e.split("_p")[1]));let{headers:r}=await Mr("headers",i?{pitch:i,num_pins:n.pin_count,gender:n.gender}:{num_pins:n.pin_count,gender:n.gender});return{jlcpcb:Er(r).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_potentiometer"){let{potentiometers:i}=await Mr("potentiometers",{resistance:n.max_resistance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_diode"){let{diodes:i}=await Mr("diodes",{package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_chip"){let{chips:i}=await Mr("chips",{package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_transistor"){let{transistors:i}=await Mr("transistors",{package:t,transistor_type:n.transistor_type});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_power_source"){let{power_sources:i}=await Mr("power_sources",{voltage:n.voltage,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_inductor"){let{inductors:i}=await Mr("inductors",{inductance:n.inductance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_crystal"){let{crystals:i}=await Mr("crystals",{frequency:n.frequency,load_capacitance:n.load_capacitance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_mosfet"){let{mosfets:i}=await Mr("mosfets",{package:t,mosfet_mode:n.mosfet_mode,channel_type:n.channel_type});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_resonator"){let{resonators:i}=await Mr("resonators",{frequency:n.frequency,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_switch"){let{switches:i}=await Mr("switches",{switch_type:n.type,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_led"){let{leds:i}=await Mr("leds",{package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_fuse"){let{fuses:i}=await Mr("fuses",{package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}return{}}};var Frt=Vt(Art(),1);tt();var Brt=Vt(Nn(),1),Yrt=Vt(Nn(),1),Si=h.tuple([h.coerce.number(),h.coerce.number()]),h$t=h.tuple([h.number(),h.number(),h.number()]),AP=h.union([Si,h$t]),d$t=h.object({kind:h.literal("arc"),start:Si,mid:Si,end:Si}),f$t=h.union([Si,d$t]),zrt=h.object({at:AP,size:Si,layer:h.string(),layers:h.array(h.string()),roundrect_rratio:h.number(),uuid:h.string()}).partial(),m$t=h.object({key:h.string(),val:h.string(),attributes:zrt}),CP=h.object({oval:h.boolean().default(!1),width:h.number().optional(),height:h.number().optional(),offset:Si.optional()}),$rt=h.object({name:h.string(),pad_type:h.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:h.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:AP,drill:h.union([h.number(),h.array(h.any()),CP]).transform(n=>typeof n=="number"?{oval:!1,width:n,height:n}:"oval"in n?n:n.length===2?{oval:!1,width:Number.parseFloat(n[0]),height:Number.parseFloat(n[0]),offset:Si.parse(n[1].slice(1))}:n.length===3||n.length===4?{oval:n[0]==="oval",width:Number.parseFloat(n[1]),height:Number.parseFloat(n[2]),offset:n[3]?Si.parse(n[3].slice(1)):void 0}:n).pipe(CP),size:h.union([h.array(h.number()).length(2).transform(([n,e])=>({width:n,height:e})),h.object({width:h.number(),height:h.number()})]),layers:h.array(h.string()).optional(),roundrect_rratio:h.number().optional(),uuid:h.string().optional()}),Drt=h.object({name:h.string(),pad_type:h.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:h.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:AP,size:Si,drill:h.union([h.number(),h.array(h.any()),CP]).transform(n=>typeof n=="number"?{oval:!1,width:n,height:n}:"oval"in n?n:n.length===2?{oval:!1,width:Number.parseFloat(n[0]),height:Number.parseFloat(n[0]),offset:Si.parse(n[1].slice(1))}:n.length===3||n.length===4?{oval:n[0]==="oval",width:Number.parseFloat(n[1]),height:Number.parseFloat(n[2]),offset:n[3]?Si.parse(n[3].slice(1)):void 0}:n).pipe(CP).optional(),layers:h.array(h.string()).optional(),roundrect_rratio:h.number().optional(),chamfer_ratio:h.number().optional(),solder_paste_margin:h.number().optional(),solder_paste_margin_ratio:h.number().optional(),clearance:h.number().optional(),zone_connection:h.union([h.literal(0).describe("Pad is not connect to zone"),h.literal(1).describe("Pad is connected to zone using thermal relief"),h.literal(2).describe("Pad is connected to zone using solid fill")]).optional(),thermal_width:h.number().optional(),thermal_gap:h.number().optional(),uuid:h.string().optional()}),jrt=h.object({font:h.object({size:Si,thickness:h.number().optional()})}).partial(),_$t=h.object({fp_text_type:h.literal("user"),text:h.string(),at:AP,layer:h.string(),uuid:h.string().optional(),effects:jrt.partial()}),y$t=h.object({start:Si,mid:Si,end:Si,stroke:h.object({width:h.number(),type:h.string()}),layer:h.string(),uuid:h.string().optional()}),g$t=h.object({center:Si,end:Si,stroke:h.object({width:h.number(),type:h.string()}),fill:h.string().optional(),layer:h.string(),uuid:h.string().optional()}),x$t=h.object({pts:h.array(f$t),stroke:h.object({width:h.number(),type:h.string()}).optional(),width:h.number().optional(),layer:h.string(),uuid:h.string().optional(),fill:h.string().optional()}).transform(n=>({...n,width:void 0,stroke:n.stroke??{width:n.width}})),b$t=h.object({start:Si,end:Si,stroke:h.object({width:h.number(),type:h.string()}).optional(),width:h.number().optional(),layer:h.string(),uuid:h.string().optional()}).transform(n=>({...n,width:void 0,stroke:n.stroke??{width:n.width}})),Rrt=h.object({footprint_name:h.string(),version:h.string().optional(),generator:h.string().optional(),generator_version:h.string().optional(),layer:h.string(),descr:h.string().default(""),tags:h.array(h.string()).optional(),properties:h.array(m$t),fp_lines:h.array(b$t),fp_texts:h.array(_$t),fp_arcs:h.array(y$t),fp_circles:h.array(g$t).optional(),fp_polys:h.array(x$t).optional(),pads:h.array(Drt),holes:h.array($rt).optional()}),IP=(n,e)=>{if(e==="effects"&&Array.isArray(n)){let t={};for(let i of n)if(i[0]==="font"){let r={};for(let s of i.slice(1))s.length===2?r[s[0].valueOf()]=Number.parseFloat(s[1].valueOf()):r[s[0].valueOf()]=s.slice(1).map(o=>Number.parseFloat(o.valueOf()));t.font=r}return jrt.parse(t)}if(e==="pts")return n.map(t=>{let i=t[0]?.valueOf?.()??t[0];if(i==="xy")return t.slice(1).map(r=>Number.parseFloat(r.valueOf()));if(i==="arc"){let r={kind:"arc"};for(let s of t.slice(1)){let o=s[0].valueOf();r[o]=s.slice(1).map(a=>Number.parseFloat(a.valueOf()))}return r}return t});if(e==="stroke"){let t={};for(let i of n){let r=i[0].valueOf();t[r]=IP(i.slice(1),r)}return t}return e==="at"||e==="size"||e==="start"||e==="mid"||e==="end"?(Array.isArray(n)?n:[n]).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)):e==="tags"?n.map(t=>t.valueOf()):e==="generator_version"||e==="version"?n[0].valueOf():n.length===2?n.valueOf():e==="uuid"?Array.isArray(n)?n[0].valueOf():n.valueOf():/^[\d\.]+$/.test(n)&&!Number.isNaN(Number.parseFloat(n))?Number.parseFloat(n):Array.isArray(n)&&n.length===1?n[0].valueOf():Array.isArray(n)?n.map(t=>t.valueOf()):n},Xe=(n,e)=>{for(let t of n)if(Array.isArray(t)&&t[0]===e)return IP(t.slice(1),e)},i6=(0,Brt.default)("kicad-mod-converter"),v$t=n=>{let e=(0,Frt.default)(n),t=e[1].valueOf(),i={},r=Object.entries(Rrt.shape).filter(([T,k])=>k._def.typeName==="ZodString"||T==="tags").map(([T])=>T);for(let T of e.slice(2)){if(!r.includes(T[0]))continue;let k=T[0].valueOf(),N=IP(T.slice(1),k);i[k]=N}let s=e.slice(2).filter(T=>T[0]==="property").map(T=>{let k=T[1].valueOf(),N=T[2].valueOf(),M=zrt.parse(T.slice(3).reduce((C,E)=>{let R=E[0].valueOf();return C[R]=IP(E.slice(1),R),C},{}));return{key:k,val:N,attributes:M}}),o=e.slice(2).filter(T=>T[0]==="pad"),a=[];for(let T of o){let k=Xe(T,"at"),N=Xe(T,"size"),M=Xe(T,"drill"),C=Xe(T,"layers");if(Array.isArray(C)?C=C.map(j=>j.valueOf()):typeof C=="string"?C=[C]:C||(C=[]),!C.includes("F.Cu")){i6(`Skipping pad without F.Cu layer: layers=${C.join(", ")}`);continue}let E=Xe(T,"roundrect_rratio"),R=Xe(T,"uuid"),A={name:T[1].valueOf(),pad_type:T[2].valueOf(),pad_shape:T[3].valueOf(),at:k,drill:M,size:N,layers:C,roundrect_rratio:E,uuid:R};i6(`attempting to parse pad: ${JSON.stringify(A,null," ")}`),a.push(Drt.parse(A))}let c=e.slice(2).filter(T=>T[0]==="fp_text"),l=[];for(let T of c){let k=T[2].valueOf(),N=Xe(T,"at"),M=Xe(T,"layer"),C=Xe(T,"uuid"),E=Xe(T,"effects");l.push({fp_text_type:"user",text:k,at:N,layer:M,uuid:C,effects:E})}let u=[],p=e.slice(2).filter(T=>T[0]==="fp_line");for(let T of p){let k=Xe(T,"start"),N=Xe(T,"end"),M=Xe(T,"stroke"),C=Xe(T,"layer"),E=Xe(T,"uuid");u.push({start:k,end:N,stroke:M,layer:C,uuid:E})}let d=[],_=e.slice(2).filter(T=>T[0]==="fp_arc");for(let T of _){let k=Xe(T,"start"),N=Xe(T,"mid"),M=Xe(T,"end"),C=Xe(T,"stroke"),E=Xe(T,"layer"),R=Xe(T,"uuid");!k||!M||!N||!C||!E||d.push({start:k,mid:N,end:M,stroke:C,layer:E,uuid:R})}let g=[],x=e.slice(2).filter(T=>T[0]==="fp_circle");for(let T of x){let k=Xe(T,"center"),N=Xe(T,"end"),M=Xe(T,"stroke"),C=Xe(T,"fill"),E=Xe(T,"layer"),R=Xe(T,"uuid");!k||!N||!M||!E||g.push({center:k,end:N,stroke:M,fill:C,layer:E,uuid:R})}let b=[],S=e.slice(2).filter(T=>T[0]==="fp_poly");for(let T of S){let k=Xe(T,"pts"),N=Xe(T,"stroke"),M=Xe(T,"width"),C=Xe(T,"layer"),E=Xe(T,"uuid"),R=Xe(T,"fill"),A=N;!A&&typeof M=="number"?A={width:M,type:"solid"}:A&&typeof A=="object"&&typeof M=="number"&&A.width===void 0&&(A={...A,width:M}),b.push({pts:k,stroke:A,layer:C,uuid:E,fill:R})}let P=[];for(let T of e.slice(2)){if(T[0]!=="pad"||T[2]?.valueOf?.()!=="thru_hole")continue;let k=T[1]?.valueOf?.(),N=T[2]?.valueOf?.(),M=T[3]?.valueOf?.(),C=Xe(T,"at"),E=Xe(T,"drill"),R=Xe(T,"size");Array.isArray(R)&&(R[0]==="size"&&(R=R.slice(1)),R={width:Number(R[0]),height:Number(R[1])});let A=Xe(T,"uuid"),j=Xe(T,"roundrect_rratio"),D=Xe(T,"layers");Array.isArray(D)?D=D.map(X=>X.valueOf()):typeof D=="string"?D=[D]:D||(D=[]);let Y={name:k,pad_type:N,pad_shape:M,at:C,drill:E,size:R,layers:D,roundrect_rratio:j,uuid:A};i6(`attempting to parse holes: ${JSON.stringify(Y,null,2)}`),P.push($rt.parse(Y))}return Rrt.parse({footprint_name:t,...i,properties:s,fp_lines:u,fp_texts:l,fp_arcs:d,fp_circles:g,pads:a,holes:P,fp_polys:b})},i0=Math.PI*2,Ort=n=>{let e=n%i0;return e<0&&(e+=i0),e},NP=(n,e)=>{let t=Ort(n),r=Ort(e)-t;return r<0&&(r+=i0),r};function Xrt(n,e,t){let i={x:(n.x+e.x)/2,y:(n.y+e.y)/2},r={x:(e.x+t.x)/2,y:(e.y+t.y)/2},s=-(n.x-e.x)/(n.y-e.y),o=-(e.x-t.x)/(e.y-t.y),a=(i.y-r.y+o*r.x-s*i.x)/(o-s),c=i.y+s*(a-i.x);return{x:a,y:c}}function Urt(n,e){return Math.sqrt((n.x-e.x)**2+(n.y-e.y)**2)}function sy(n,e){return Math.atan2(e.y-n.y,e.x-n.x)}var a6=(n,e,t)=>{let i=Xrt(n,e,t),r=Urt(i,n),s=sy(i,n),o=sy(i,e),a=sy(i,t),c=NP(s,o),l=NP(s,a),u=l;return c>l&&(u=l-i0),Math.abs(r*u)};function c6(n,e,t,i){let r=Xrt(n,e,t),s=Urt(r,n),o=sy(r,n),a=sy(r,e),c=sy(r,t),l=NP(o,a),u=NP(o,c),p=u;l>u&&(p=u-i0);let d=[];for(let _=0;_<=i;_++){let g=o+_/i*p,x=r.x+s*Math.cos(g),b=r.y+s*Math.sin(g);d.push({x,y:b})}return d}var Ml=n=>Array.isArray(n)?{x:n[0],y:n[1]}:n,r6=(n,e,t=1e-4)=>Math.abs(n.x-e.x)<t&&Math.abs(n.y-e.y)<t,S$t=n=>{let e=[],t=new Set;for(let i=0;i<n.length;i++){if(t.has(i))continue;let r=[n[i]];t.add(i);let s=n[i].end,o=!0;for(;o;){if(o=!1,r.length>1&&r6(s,r[0].start)){e.push(r);break}for(let a=0;a<n.length;a++)if(!t.has(a)){if(r6(s,n[a].start)){r.push(n[a]),t.add(a),s=n[a].end,o=!0;break}else if(r6(s,n[a].end)){n[a].type==="arc"?r.push({...n[a],reversed:!0}):r.push({...n[a],start:n[a].end,end:n[a].start}),t.add(a),s=n[a].start,o=!0;break}}if(!o){for(let a=r.length-1;a>=0;a--){let c=n.indexOf(r[a]);c!==-1&&t.delete(c)}break}}}return e},w$t=n=>{let e=[];for(let t of n)if(t.type==="line")e.push(t.start);else if(t.type==="arc"&&t.mid){let i=a6(t.start,t.mid,t.end),r=Math.max(3,Math.ceil(i)),s=c6(t.start,t.mid,t.end,r);t.reversed&&(s=s.reverse()),e.push(...s.slice(0,-1))}return e};function P$t(n){if(!Array.isArray(n))return null;let e=n.find(o=>o.layer?.toLowerCase()==="f.silks"&&(o.text?.includes("${REFERENCE}")||o.fp_text_type?.toLowerCase()==="reference"||o.text?.match(/^R\d+|C\d+|U\d+/))),t=e||n.find(o=>o.layer?.toLowerCase()==="f.fab"&&(o.text?.includes("${REFERENCE}")||o.fp_text_type?.toLowerCase()==="reference")),i=e||t;if(!i?.effects?.font?.size)return null;let[r,s]=i.effects.font.size;return s??r??1}var k$t=n=>n*Math.PI/180,s6=(n,e,t)=>{let i=k$t(t),r=Math.cos(i),s=Math.sin(i);return{x:n*r-e*s,y:n*s+e*r}},T$t=n=>{let e=[...new Map(n.map(u=>[`${u.x},${u.y}`,u])).values()];if(e.length!==4)return null;let t=e.map(u=>u.x),i=e.map(u=>u.y),r=[...new Set(t)],s=[...new Set(i)];if(r.length!==2||s.length!==2)return null;let[o,a]=r.sort((u,p)=>u-p),[c,l]=s.sort((u,p)=>u-p);return o===void 0||a===void 0||c===void 0||l===void 0?null:{x:(o+a)/2,y:(c+l)/2,width:a-o,height:l-c}},M$t=n=>{if(!n)return!1;let e=n.toLowerCase();return e!=="no"&&e!=="none"&&e!=="outline"},o6=n=>n&&Array.isArray(n)&&n.length>=3&&typeof n[2]=="number"?n[2]:0,Gr=n=>{let e=(n%360+360)%360;return e===90||e===270},Yd=n=>{if(n!=null)return`${n}`},Lrt=n=>{let e=Yd(n),t=e!==void 0?Number(e):NaN;return Number.isFinite(t)?t:void 0},ry=(0,Yrt.default)("kicad-mod-converter"),js=n=>{switch(n.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"}},E$t=async n=>{let{fp_lines:e,fp_texts:t,fp_arcs:i,fp_circles:r,pads:s,properties:o,holes:a,fp_polys:c}=n,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,p=new Map;for(let G of s){let nt=Yd(G.name);if(nt){u.add(nt);let J=Lrt(G.name);J!==void 0&&p.set(nt,J)}}if(a)for(let G of a){let nt=Yd(G.name);if(nt){u.add(nt);let J=Lrt(G.name);J!==void 0&&p.set(nt,J)}}let d=0,_=new Map;for(let G of u){let nt=`source_port_${d++}`;_.set(G,nt);let J=p.get(G);l.push({type:"source_port",source_port_id:nt,source_component_id:"source_component_0",name:G,port_hints:[G],pin_number:J,pin_label:J!==void 0?`pin${J}`:void 0}),l.push({type:"schematic_port",schematic_port_id:`schematic_port_${d++}`,source_port_id:nt,schematic_component_id:"schematic_component_0",center:{x:0,y:0}})}let g=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY,b=Number.POSITIVE_INFINITY,S=Number.NEGATIVE_INFINITY;for(let G of s){let nt=G.at[0],J=-G.at[1],pt=G.size[0],ut=G.size[1];g=Math.min(g,nt-pt/2),x=Math.max(x,nt+pt/2),b=Math.min(b,J-ut/2),S=Math.max(S,J+ut/2)}let P="pcb_component_0";l.push({type:"pcb_component",source_component_id:"source_component_0",pcb_component_id:P,layer:"top",center:{x:0,y:0},rotation:0,width:Number.isFinite(g)?x-g:0,height:Number.isFinite(b)?S-b:0});let T=0,k=new Map;for(let G of u){let nt=`pcb_port_${T++}`,J=_.get(G);k.set(G,nt);let pt=0,ut=0,wt=["top","bottom"],Et=s.find(ot=>Yd(ot.name)===G);if(Et)pt=Et.at[0],ut=-Et.at[1],wt=Et.layers?Et.layers.map(ot=>js(ot)).filter(Boolean):["top","bottom"];else if(a){let ot=a.find(U=>Yd(U.name)===G);ot&&(pt=ot.at[0],ut=-ot.at[1],wt=ot.layers?ot.layers.map(U=>js(U)).filter(Boolean):["top","bottom"])}l.push({type:"pcb_port",pcb_port_id:nt,source_port_id:J,pcb_component_id:P,x:pt,y:ut,layers:wt})}let N=0,M=0,C=0;for(let G of s){let nt=Yd(G.name),J=nt?p.get(nt):void 0;if(G.pad_type==="smd"){let pt=o6(G.at),ut=Gr(pt)?G.size[1]:G.size[0],wt=Gr(pt)?G.size[0]:G.size[1],Et=nt?k.get(nt):void 0,ot=J!==void 0?`pin${J}`:void 0;l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${N++}`,shape:"rect",x:G.at[0],y:-G.at[1],width:ut,height:wt,layer:js(G.layers?.[0]??"F.Cu"),pcb_component_id:P,port_hints:ot?[ot]:nt?[nt]:[],pcb_port_id:Et,pin_number:J,pin_label:ot})}else if(G.pad_type==="thru_hole"){if(G.pad_shape==="rect"){let pt=o6(G.at),ut=Gr(pt)?G.size[1]:G.size[0],wt=Gr(pt)?G.size[0]:G.size[1],Et=G.drill?.offset?.[0]??0,ot=G.drill?.offset?.[1]??0,U=s6(Et,ot,pt),q=nt?k.get(nt):void 0,it=J!==void 0?`pin${J}`:void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${M++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:G.at[0],y:-G.at[1],hole_offset_x:-U.x,hole_offset_y:-U.y,hole_diameter:G.drill?.width,rect_pad_width:ut,rect_pad_height:wt,layers:["top","bottom"],pcb_component_id:P,port_hints:it?[it]:nt?[nt]:[],pcb_port_id:q,pin_number:J,pin_label:it})}else if(G.pad_shape==="circle"){let pt=nt?k.get(nt):void 0,ut=J!==void 0?`pin${J}`:void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${M++}`,shape:"circle",x:G.at[0],y:-G.at[1],outer_diameter:G.size[0],hole_diameter:G.drill?.width,layers:["top","bottom"],pcb_component_id:P,port_hints:ut?[ut]:nt?[nt]:[],pcb_port_id:pt,pin_number:J,pin_label:ut})}else if(G.pad_shape==="oval"){let pt=nt?k.get(nt):void 0,ut=J!==void 0?`pin${J}`:void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${M++}`,shape:"pill",x:G.at[0],y:-G.at[1],outer_width:G.size[0],outer_height:G.size[1],hole_width:G.drill?.width,hole_height:G.drill?.height,layers:["top","bottom"],pcb_component_id:P,port_hints:ut?[ut]:nt?[nt]:[],pcb_port_id:pt,pin_number:J,pin_label:ut})}}else G.pad_type==="np_thru_hole"&&l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${C++}`,x:G.at[0],y:-G.at[1],hole_diameter:G.drill?.width,pcb_component_id:P})}if(a)for(let G of a){let nt=Yd(G.name),J=nt?p.get(nt):void 0,pt=G.layers?.some(at=>at.endsWith(".Cu")||at==="*.Cu"),ut=o6(G.at),wt=G.drill?.offset?.[0]??0,Et=G.drill?.offset?.[1]??0,ot=s6(wt,Et,ut),U=G.at[0]+ot.x,q=-(G.at[1]+ot.y),it=G.drill?.width??0,ht=G.size?.width??it,yt=G.roundrect_rratio??0,K=yt>0?Math.min(Gr(ut)?G.size?.height??ht:G.size?.width??ht,Gr(ut)?G.size?.width??ht:G.size?.height??ht)/2*yt:0;if(pt)if(G.pad_shape==="rect"){let at=nt?k.get(nt):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${M++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:G.at[0],y:-G.at[1],hole_offset_x:-ot.x,hole_offset_y:-ot.y,hole_diameter:it,rect_pad_width:Gr(ut)?G.size?.height??ht:G.size?.width??ht,rect_pad_height:Gr(ut)?G.size?.width??ht:G.size?.height??ht,rect_border_radius:K,port_hints:J!==void 0?[`pin${J}`]:nt?[nt]:[],layers:["top","bottom"],pcb_component_id:P,pcb_port_id:at,pin_number:J,pin_label:J!==void 0?`pin${J}`:void 0})}else if(G.pad_shape==="oval"){let at=nt?k.get(nt):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${M++}`,shape:"pill",x:U,y:q,outer_width:Gr(ut)?G.size?.height??ht:G.size?.width??ht,outer_height:Gr(ut)?G.size?.width??ht:G.size?.height??ht,hole_width:Gr(ut)?G.drill?.height??it:G.drill?.width??it,hole_height:Gr(ut)?G.drill?.width??it:G.drill?.height??it,port_hints:J!==void 0?[`pin${J}`]:nt?[nt]:[],layers:["top","bottom"],pcb_component_id:P,pcb_port_id:at,pin_number:J,pin_label:J!==void 0?`pin${J}`:void 0})}else if(G.pad_shape==="roundrect"){let at=nt?k.get(nt):void 0,Mt=G.drill?.offset?.[0]??0,Ft=G.drill?.offset?.[1]??0,Ot=s6(Mt,Ft,ut),Ne=Gr(ut)?G.size?.height??ht:G.size?.width??ht,Pe=Gr(ut)?G.size?.width??ht:G.size?.height??ht;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${M++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:U,y:q,hole_offset_x:-Ot.x,hole_offset_y:Ot.y,hole_diameter:it,rect_pad_width:Ne,rect_pad_height:Pe,rect_border_radius:K,port_hints:J!==void 0?[`pin${J}`]:nt?[nt]:[],layers:["top","bottom"],pcb_component_id:P,pcb_port_id:at,pin_number:J,pin_label:J!==void 0?`pin${J}`:void 0})}else{let at=nt?k.get(nt):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${M++}`,shape:"circle",x:U,y:q,outer_diameter:ht,hole_diameter:it,port_hints:J!==void 0?[`pin${J}`]:nt?[nt]:[],layers:["top","bottom"],pcb_component_id:P,pcb_port_id:at,pin_number:J,pin_label:J!==void 0?`pin${J}`:void 0})}else l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${C++}`,x:U,y:q,hole_diameter:ht,hole_shape:"circle",pcb_component_id:P})}let E=[];for(let G of e)G.layer.toLowerCase()==="edge.cuts"&&E.push({type:"line",start:{x:G.start[0],y:G.start[1]},end:{x:G.end[0],y:G.end[1]},strokeWidth:G.stroke.width});for(let G of i)G.layer.toLowerCase()==="edge.cuts"&&E.push({type:"arc",start:{x:G.start[0],y:G.start[1]},mid:{x:G.mid[0],y:G.mid[1]},end:{x:G.end[0],y:G.end[1]},strokeWidth:G.stroke.width});let R=S$t(E),A=0;for(let G of R){let nt=w$t(G);nt.length>=3&&l.push({type:"pcb_cutout",pcb_cutout_id:`pcb_cutout_${A++}`,shape:"polygon",points:nt.map(J=>({x:J.x,y:-J.y})),pcb_component_id:P})}let j=0,D=0,Y=0,X=0;for(let G of e){let nt=[{x:G.start[0],y:-G.start[1]},{x:G.end[0],y:-G.end[1]}],J=G.layer.toLowerCase();J==="f.cu"?l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${j++}`,pcb_component_id:P,layer:js(G.layer),route:nt,thickness:G.stroke.width}):J==="f.silks"?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${D++}`,pcb_component_id:P,layer:"top",route:nt,stroke_width:G.stroke.width}):J==="edge.cuts"?ry("Skipping Edge.Cuts fp_line (converted to pcb_cutout)",G.layer):J==="f.fab"?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${Y++}`,pcb_component_id:P,layer:"top",route:nt,stroke_width:G.stroke.width,port_hints:[]}):J.startsWith("user.")?l.push({type:"pcb_note_line",pcb_note_line_id:`pcb_note_line_${X++}`,pcb_component_id:P,x1:G.start[0],y1:-G.start[1],x2:G.end[0],y2:-G.end[1],stroke_width:G.stroke.width}):ry("Unhandled layer for fp_line",G.layer)}if(c)for(let G of c){let nt=[],J=ot=>{!Number.isFinite(ot.x)||!Number.isFinite(ot.y)||nt.push(ot)};for(let ot of G.pts){if(Array.isArray(ot)){J({x:ot[0],y:-ot[1]});continue}if(ot&&typeof ot=="object"&&"kind"in ot){if(ot.kind==="arc"){let U=Ml(ot.start),q=Ml(ot.mid),it=Ml(ot.end),ht=a6(U,q,it),yt=Math.max(8,Math.ceil(ht)),K=Math.max(2,Math.ceil(ht/.1)),at=c6(U,q,it,K).map(Mt=>({x:Mt.x,y:-Mt.y}));for(let Mt of at)J(Mt)}continue}}let pt=nt,wt=pt.length>2&&pt[0].x===pt[pt.length-1].x&&pt[0].y===pt[pt.length-1].y?pt.slice(0,-1):pt;if(pt.length===0)continue;let Et=G.stroke?.width??0;if(G.layer.endsWith(".Cu")){let ot=T$t(wt);ot?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${N++}`,shape:"rect",x:ot.x,y:ot.y,width:ot.width,height:ot.height,layer:js(G.layer),pcb_component_id:P}):M$t(G.fill)?wt.length>=3?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${N++}`,shape:"polygon",points:wt,layer:js(G.layer),pcb_component_id:P}):wt.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${j++}`,pcb_component_id:P,layer:js(G.layer),route:wt,thickness:Et}):wt.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${j++}`,pcb_component_id:P,layer:js(G.layer),route:wt,thickness:Et})}else G.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${D++}`,pcb_component_id:P,layer:js(G.layer),route:pt,stroke_width:Et}):G.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${Y++}`,pcb_component_id:P,layer:js(G.layer),route:wt,stroke_width:Et,port_hints:[]}):ry("Unhandled layer for fp_poly",G.layer)}let W=0;for(let G of i){let nt=G.layer.toLowerCase();if(nt==="edge.cuts"){ry("Skipping Edge.Cuts fp_arc (converted to pcb_cutout)",G.layer);continue}let J=Ml(G.start),pt=Ml(G.mid),ut=Ml(G.end),wt=a6(J,pt,ut),Et=c6(J,pt,ut,Math.ceil(wt));if(nt.startsWith("user.")){l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${W++}`,pcb_component_id:P,route:Et.map(U=>({x:U.x,y:-U.y})),stroke_width:G.stroke.width});continue}let ot=js(G.layer);if(!ot){ry("Unable to convert layer for fp_arc",G.layer);continue}l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${D++}`,layer:ot,pcb_component_id:P,route:Et.map(U=>({x:U.x,y:-U.y})),stroke_width:G.stroke.width})}if(r)for(let G of r){let nt=G.layer.toLowerCase(),J=Ml(G.center),pt=Ml(G.end),ut=Math.sqrt((pt.x-J.x)**2+(pt.y-J.y)**2),wt=Math.max(16,Math.ceil(2*Math.PI*ut)),Et=[];for(let ot=0;ot<=wt;ot++){let U=ot/wt*2*Math.PI;Et.push({x:J.x+ut*Math.cos(U),y:J.y+ut*Math.sin(U)})}nt.startsWith("user.")&&l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${W++}`,pcb_component_id:P,route:Et.map(ot=>({x:ot.x,y:-ot.y})),stroke_width:G.stroke.width})}for(let G of t){let nt=js(G.layer);G.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_text",layer:nt,font:"tscircuit2024",font_size:G.effects?.font?.size[0]??1,pcb_component_id:P,anchor_position:{x:G.at[0],y:-G.at[1]},anchor_alignment:"center",text:G.text}):G.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_text",layer:nt,font:"tscircuit2024",font_size:G.effects?.font?.size[0]??1,pcb_component_id:P,anchor_position:{x:G.at[0],y:-G.at[1]},anchor_alignment:"center",text:G.text}):ry("Unhandled layer for fp_text",G.layer)}let et=o.find(G=>G.key==="Reference"),H=o.find(G=>G.key==="Value"),dt=[et,H].filter(G=>G&&!!G.val);for(let G of dt){let nt=G.attributes.at;if(!nt)continue;let pt=G.attributes.layer?.toLowerCase()?.endsWith(".fab"),ut=P$t(t);l.push({type:pt?"pcb_fabrication_note_text":"pcb_silkscreen_text",layer:"top",font:"tscircuit2024",font_size:ut,pcb_component_id:P,anchor_position:{x:nt[0],y:-nt[1]},anchor_alignment:"center",text:G.val})}return l},Vrt=async n=>{let e=v$t(n);return await E$t(e)};var Grt=async n=>{try{return(await import(n)).default}catch{console.log(`Failed to load ${n} locally, trying CDN fallback...`);try{let t=await fetch(`https://cdn.jsdelivr.net/npm/${n}/+esm`);if(!t.ok)throw new Error(`Failed to fetch ${n} from CDN: ${t.statusText}`);let i=await t.text(),r=new Blob([i],{type:"application/javascript"}),s=URL.createObjectURL(r);try{let{default:o}=await import(s);return o}finally{URL.revokeObjectURL(s)}}catch(t){throw console.error(`CDN fallback for ${n} also failed:`,t),t}}};var C$t="https://kicad-mod-cache.tscircuit.com",RP=null,Wrt=()=>({partsEngine:Nrt,spiceEngineMap:{ngspice:{simulate:async n=>{if(!RP){let e=await Grt("@tscircuit/ngspice-spice-engine").catch(t=>{throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.",{cause:t})});e&&(RP=await e())}if(!RP)throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.");return RP.simulate(n)}}},footprintLibraryMap:{kicad:async n=>{let e=`${C$t}/${n}`,t=`${e}.circuit.json`,r=await(await fetch(t)).json(),s=Array.isArray(r)?r.filter(a=>a?.type==="pcb_silkscreen_text"?a?.text==="REF**":!0):r,o=`${e}.wrl`;return{footprintCircuitJson:s,cadModel:{wrlUrl:o,modelUnitToMmScale:2.54}}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async n=>{let e=await fetch(n).then(i=>i.text()),t=await Vrt(e);return{footprintCircuitJson:Array.isArray(t)?t:[t]}}}}});var h6={};$c(h6,{__addDisposableResource:()=>gst,__assign:()=>OP,__asyncDelegator:()=>ust,__asyncGenerator:()=>lst,__asyncValues:()=>pst,__await:()=>oy,__awaiter:()=>ist,__classPrivateFieldGet:()=>mst,__classPrivateFieldIn:()=>yst,__classPrivateFieldSet:()=>_st,__createBinding:()=>FP,__decorate:()=>Zrt,__disposeResources:()=>xst,__esDecorate:()=>Jrt,__exportStar:()=>sst,__extends:()=>Hrt,__generator:()=>rst,__importDefault:()=>fst,__importStar:()=>dst,__makeTemplateObject:()=>hst,__metadata:()=>nst,__param:()=>Krt,__propKey:()=>tst,__read:()=>p6,__rest:()=>qrt,__rewriteRelativeImportExtension:()=>bst,__runInitializers:()=>Qrt,__setFunctionName:()=>est,__spread:()=>ost,__spreadArray:()=>cst,__spreadArrays:()=>ast,__values:()=>LP,default:()=>A$t});var l6=function(n,e){return l6=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(t[r]=i[r])},l6(n,e)};function Hrt(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");l6(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var OP=function(){return OP=Object.assign||function(e){for(var t,i=1,r=arguments.length;i<r;i++){t=arguments[i];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s])}return e},OP.apply(this,arguments)};function qrt(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(n);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(n,i[r])&&(t[i[r]]=n[i[r]]);return t}function Zrt(n,e,t,i){var r=arguments.length,s=r<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,i);else for(var a=n.length-1;a>=0;a--)(o=n[a])&&(s=(r<3?o(s):r>3?o(e,t,s):o(e,t))||s);return r>3&&s&&Object.defineProperty(e,t,s),s}function Krt(n,e){return function(t,i){e(t,i,n)}}function Jrt(n,e,t,i,r,s){function o(S){if(S!==void 0&&typeof S!="function")throw new TypeError("Function expected");return S}for(var a=i.kind,c=a==="getter"?"get":a==="setter"?"set":"value",l=!e&&n?i.static?n:n.prototype:null,u=e||(l?Object.getOwnPropertyDescriptor(l,i.name):{}),p,d=!1,_=t.length-1;_>=0;_--){var g={};for(var x in i)g[x]=x==="access"?{}:i[x];for(var x in i.access)g.access[x]=i.access[x];g.addInitializer=function(S){if(d)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(S||null))};var b=(0,t[_])(a==="accessor"?{get:u.get,set:u.set}:u[c],g);if(a==="accessor"){if(b===void 0)continue;if(b===null||typeof b!="object")throw new TypeError("Object expected");(p=o(b.get))&&(u.get=p),(p=o(b.set))&&(u.set=p),(p=o(b.init))&&r.unshift(p)}else(p=o(b))&&(a==="field"?r.unshift(p):u[c]=p)}l&&Object.defineProperty(l,i.name,u),d=!0}function Qrt(n,e,t){for(var i=arguments.length>2,r=0;r<e.length;r++)t=i?e[r].call(n,t):e[r].call(n);return i?t:void 0}function tst(n){return typeof n=="symbol"?n:"".concat(n)}function est(n,e,t){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(n,"name",{configurable:!0,value:t?"".concat(t," ",e):e})}function nst(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}function ist(n,e,t,i){function r(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(i.next(u))}catch(p){o(p)}}function c(u){try{l(i.throw(u))}catch(p){o(p)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((i=i.apply(n,e||[])).next())})}function rst(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,r,s,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(t=0)),t;)try{if(i=1,r&&(s=l[0]&2?r.return:l[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,l[1])).done)return s;switch(r=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,r=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(n,t)}catch(u){l=[6,u],r=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}var FP=Object.create?(function(n,e,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,i,r)}):(function(n,e,t,i){i===void 0&&(i=t),n[i]=e[t]});function sst(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&FP(e,n,t)}function LP(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function p6(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var i=t.call(n),r,s=[],o;try{for(;(e===void 0||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(o)throw o.error}}return s}function ost(){for(var n=[],e=0;e<arguments.length;e++)n=n.concat(p6(arguments[e]));return n}function ast(){for(var n=0,e=0,t=arguments.length;e<t;e++)n+=arguments[e].length;for(var i=Array(n),r=0,e=0;e<t;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,r++)i[r]=s[o];return i}function cst(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;i<r;i++)(s||!(i in e))&&(s||(s=Array.prototype.slice.call(e,0,i)),s[i]=e[i]);return n.concat(s||Array.prototype.slice.call(e))}function oy(n){return this instanceof oy?(this.v=n,this):new oy(n)}function lst(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),r,s=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),r[Symbol.asyncIterator]=function(){return this},r;function o(_){return function(g){return Promise.resolve(g).then(_,p)}}function a(_,g){i[_]&&(r[_]=function(x){return new Promise(function(b,S){s.push([_,x,b,S])>1||c(_,x)})},g&&(r[_]=g(r[_])))}function c(_,g){try{l(i[_](g))}catch(x){d(s[0][3],x)}}function l(_){_.value instanceof oy?Promise.resolve(_.value.v).then(u,p):d(s[0][2],_)}function u(_){c("next",_)}function p(_){c("throw",_)}function d(_,g){_(g),s.shift(),s.length&&c(s[0][0],s[0][1])}}function ust(n){var e,t;return e={},i("next"),i("throw",function(r){throw r}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(r,s){e[r]=n[r]?function(o){return(t=!t)?{value:oy(n[r](o)),done:!1}:s?s(o):o}:s}}function pst(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof LP=="function"?LP(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=n[s]&&function(o){return new Promise(function(a,c){o=n[s](o),r(a,c,o.done,o.value)})}}function r(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function hst(n,e){return Object.defineProperty?Object.defineProperty(n,"raw",{value:e}):n.raw=e,n}var I$t=Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e},u6=function(n){return u6=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},u6(n)};function dst(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t=u6(n),i=0;i<t.length;i++)t[i]!=="default"&&FP(e,n,t[i]);return I$t(e,n),e}function fst(n){return n&&n.__esModule?n:{default:n}}function mst(n,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!i:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(n):i?i.value:e.get(n)}function _st(n,e,t,i,r){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?r.call(n,t):r?r.value=t:e.set(n,t),t}function yst(n,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof n=="function"?e===n:n.has(e)}function gst(n,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,r;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(r=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");r&&(i=function(){try{r.call(this)}catch(s){return Promise.reject(s)}}),n.stack.push({value:e,dispose:i,async:t})}else t&&n.stack.push({async:!0});return e}var N$t=typeof SuppressedError=="function"?SuppressedError:function(n,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=n,i.suppressed=e,i};function xst(n){function e(s){n.error=n.hasError?new N$t(s,n.error,"An error was suppressed during disposal."):s,n.hasError=!0}var t,i=0;function r(){for(;t=n.stack.pop();)try{if(!t.async&&i===1)return i=0,n.stack.push(t),Promise.resolve().then(r);if(t.dispose){var s=t.dispose.call(t.value);if(t.async)return i|=2,Promise.resolve(s).then(r,function(o){return e(o),r()})}else i|=1}catch(o){e(o)}if(i===1)return n.hasError?Promise.reject(n.error):Promise.resolve();if(n.hasError)throw n.error}return r()}function bst(n,e){return typeof n=="string"&&/^\.\.?\//.test(n)?n.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(t,i,r,s,o){return i?e?".jsx":".js":r&&(!s||!o)?t:r+s+"."+o.toLowerCase()+"js"}):n}var A$t={__extends:Hrt,__assign:OP,__rest:qrt,__decorate:Zrt,__param:Krt,__esDecorate:Jrt,__runInitializers:Qrt,__propKey:tst,__setFunctionName:est,__metadata:nst,__awaiter:ist,__generator:rst,__createBinding:FP,__exportStar:sst,__values:LP,__read:p6,__spread:ost,__spreadArrays:ast,__spreadArray:cst,__await:oy,__asyncGenerator:lst,__asyncDelegator:ust,__asyncValues:pst,__makeTemplateObject:hst,__importStar:dst,__importDefault:fst,__classPrivateFieldGet:mst,__classPrivateFieldSet:_st,__classPrivateFieldIn:yst,__addDisposableResource:gst,__disposeResources:xst,__rewriteRelativeImportExtension:bst};var d6=Vt(Nn(),1),E2e=(0,d6.default)("tsci:eval:execution-context");function r0(n,e={}){globalThis.React=vst;let t=e.platform||Wrt(),i=e.projectConfig?{...t,...e.projectConfig}:t;i.partsEngineDisabled&&(i.partsEngine=void 0);let r=new ny({platform:i});e.name&&(r.name=e.name),e.debugNamespace&&r.enableDebug(e.debugNamespace);let s=[];return{fsMap:{},entrypoint:"",logger:{info:o=>{s.push({msg:o})},getLogs:()=>s,stringifyLogs:()=>s.map(o=>o.msg).join(`
257
257
  `)},preSuppliedImports:{"@tscircuit/core":MP,tscircuit:MP,"@tscircuit/math-utils":j4,react:vst,"react/jsx-runtime":R$t,debug:d6.default,tslib:h6,"@tscircuit/props":{}},circuit:r,tsConfig:null,importStack:[],currentlyImporting:new Set,...n}}function El(n){let e=n;return e=e.replace(/\\/g,"/"),e=e.trim(),e.startsWith("./")&&(e=e.slice(2)),e.startsWith("/")&&(e=e.slice(1)),e}function Sst(n){let e={};for(let[t,i]of Object.entries(n))e[El(t)]=i;return e}function Bs(n){if(!n)return".";let t=n.replace(/\\/g,"/").replace(/\/+$/,"");return t.indexOf("/")===-1?".":t.substring(0,t.lastIndexOf("/"))||"/"}function zP(n,e){if(n.startsWith("../")){let t=Bs(e);return zP(n.slice(3),t)}return n.startsWith("./")?zP(n.slice(2),e):n.startsWith("/")?n.slice(1):`${e}/${n}`}function s0(n){if(Array.isArray(n))return null;let e=n["tsconfig.json"];if(!e)return null;try{let t=e.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,"");return JSON.parse(t)}catch(t){throw new Error(`Failed to parse tsconfig.json: ${t.message}`)}}function wst(n){let{importPath:e,normalizedFilePathMap:t,extensions:i,tsConfig:r,tsconfigDir:s}=n,o=r?.compilerOptions?.paths;if(!o)return null;let a=r?.compilerOptions?.baseUrl||".",c=u=>{let p=El(u);if(t.has(p))return t.get(p);for(let d of i){let _=`${p}.${d}`;if(t.has(_))return t.get(_)}return null};for(let[u,p]of Object.entries(o))if(u.includes("*")){let[_,g]=u.split("*");if(!e.startsWith(_)||!e.endsWith(g||""))continue;let x=e.slice(_.length,e.length-(g?g.length:0));for(let b of p){let S=b.replace("*",x),P=a&&!S.startsWith("./")&&!S.startsWith("/")?`${a}/${S}`:S,T=c(P);if(T)return T}}else{if(e!==u)continue;for(let _ of p){let g=a&&!_.startsWith("./")&&!_.startsWith("/")?`${a}/${_}`:_,x=c(g);if(x)return x}}let l=f6({importPath:e,normalizedFilePathMap:t,extensions:i,tsConfig:r,tsconfigDir:s});return l||null}function f6(n){let{importPath:e,normalizedFilePathMap:t,extensions:i,tsConfig:r,tsconfigDir:s}=n,o=r?.compilerOptions?.baseUrl;if(!o)return null;let c=`${s||"."}/${o}/${e}`;c=c.replace(/\/+/g,"/"),c=c.replace(/\/\.\//g,"/");let l=El(c);if(t.has(l))return t.get(l);for(let u of i){let p=`${l}.${u}`;if(t.has(p))return t.get(p)}return null}function Pst(n,e){let t=e?.compilerOptions?.paths;if(!t)return!1;for(let[i]of Object.entries(t))if(i.includes("*")){let[s,o]=i.split("*");if(n.startsWith(s)&&n.endsWith(o||""))return!0}else if(n===i)return!0;return!1}var $P=["tsx","ts","json","js","jsx","obj","gltf","glb","stl","step","stp"],o0=(n,e,t,i={})=>{let r=i.tsConfig??null,s=n.startsWith("./")||n.startsWith("../"),o=!!r?.compilerOptions?.baseUrl,a=t&&(s||!o)?zP(n,t):n,c=new Set(Array.isArray(e)?e:Object.keys(e));if(c.has(a))return a;let l=new Map;for(let p of c)l.set(El(p),p);let u=El(a);if(s||!o){if(l.has(u))return l.get(u);for(let p of $P){let d=`${u}.${p}`;if(l.has(d))return l.get(d)}}if(!s){let p=wst({importPath:n,normalizedFilePathMap:l,extensions:$P,tsConfig:r,tsconfigDir:i.tsconfigDir});if(p)return p;let d=f6({importPath:n,normalizedFilePathMap:l,extensions:$P,tsConfig:r,tsconfigDir:i.tsconfigDir});if(d)return d}if(!s&&!o){let p=El(n);if(l.has(p))return l.get(p);for(let d of $P){let _=`${p}.${d}`;if(l.has(_))return l.get(_)}}return null},DP=(n,e,t,i={})=>{let r=o0(n,e,t,i);if(!r)throw new Error(`File not found "${n}", available paths: