@tscircuit/eval 0.0.304 → 0.0.305
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.
- package/dist/blob-url.js +1 -1
- package/dist/eval/index.js +6 -2
- package/dist/lib/index.js +6 -2
- package/dist/webworker/entrypoint.js +4 -4
- package/lib/getPlatformConfig.ts +9 -1
- package/package.json +7 -7
- package/tests/examples/__snapshots__/example18-kicad-footprint-server.snap.svg +1 -0
- package/tests/examples/example18-kicad-footprint-server.test.tsx +5 -0
- package/tests/fixtures/preload.ts +1 -0
|
@@ -948,7 +948,7 @@ Using plugins:`),be.forEach(function(je){ebt(je,Z,ge)}),I||console.log("\nUsing
|
|
|
948
948
|
:is(button, input, select, textarea, optgroup, option)[disabled],
|
|
949
949
|
optgroup[disabled] > option,
|
|
950
950
|
fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *)
|
|
951
|
-
)`,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 Wu=qr(Kf(),1);var ZX={};function QX(n,e){return n===Wu.default.falseFunc?Wu.default.falseFunc:a=>e.isTag(a)&&n(a)}function eY(n,e){let a=e.getSiblings(n);if(a.length<=1)return[];let s=a.indexOf(n);return s<0||s===a.length-1?[]:a.slice(s+1).filter(e.isTag)}function JX(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 KX=(n,e,a,s,l)=>{let p=l(e,JX(a),s);return p===Wu.default.trueFunc?n:p===Wu.default.falseFunc?Wu.default.falseFunc:x=>p(x)&&n(x)},qR={is:KX,matches:KX,where:KX,not(n,e,a,s,l){let p=l(e,JX(a),s);return p===Wu.default.falseFunc?n:p===Wu.default.trueFunc?Wu.default.falseFunc:x=>!p(x)&&n(x)},has(n,e,a,s,l){let{adapter:p}=a,x=JX(a);x.relativeSelector=!0;let f=e.some(b=>b.some(Cb))?[ZX]:void 0,m=l(e,x,f);if(m===Wu.default.falseFunc)return Wu.default.falseFunc;let D=QX(m,p);if(f&&m!==Wu.default.trueFunc){let{shouldTestNextSiblings:b=!1}=m;return E=>{if(!n(E))return!1;f[0]=E;let A=p.getChildren(E),B=b?[...A,...eY(E,p)]:A;return p.existsOne(D,B)}}return b=>n(b)&&p.existsOne(D,p.getChildren(b))}};function L8e(n,e,a,s,l){var p;let{name:x,data:f}=e;if(Array.isArray(f)){if(!(x in qR))throw new Error(`Unknown pseudo-class :${x}(${f})`);return qR[x](n,f,a,s,l)}let m=(p=a.pseudos)===null||p===void 0?void 0:p[x],D=typeof m=="string"?m:WX[x];if(typeof D=="string"){if(f!=null)throw new Error(`Pseudo ${x} doesn't have any arguments`);let b=vb(D);return qR.is(n,b,a,s,l)}if(typeof m=="function")return HX(m,x,f,1),b=>m(b,f)&&n(b);if(x in Ab)return Ab[x](n,f,a,s);if(x in zR){let b=zR[x];return HX(b,x,f,2),E=>b(E,a,f)&&n(E)}throw new Error(`Unknown pseudo-class :${x}`)}function tY(n,e){let a=e.getParent(n);return a&&e.isTag(a)?a:null}function $8e(n,e,a,s,l){let{adapter:p,equals:x}=a;switch(e.type){case Kr.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case Kr.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case Kr.Attribute:{if(e.namespace!=null)throw new Error("Namespaced attributes are not yet supported by css-select");return(!a.xmlMode||a.lowerCaseAttributeNames)&&(e.name=e.name.toLowerCase()),k8e[e.action](n,e,a)}case Kr.Pseudo:return L8e(n,e,a,s,l);case Kr.Tag:{if(e.namespace!=null)throw new Error("Namespaced tag names are not yet supported by css-select");let{name:f}=e;return(!a.xmlMode||a.lowerCaseTags)&&(f=f.toLowerCase()),function(D){return p.getName(D)===f&&n(D)}}case Kr.Descendant:{if(a.cacheResults===!1||typeof WeakSet>"u")return function(D){let b=D;for(;b=tY(b,p);)if(n(b))return!0;return!1};let f=new WeakSet;return function(D){let b=D;for(;b=tY(b,p);)if(!f.has(b)){if(p.isTag(b)&&n(b))return!0;f.add(b)}return!1}}case"_flexibleDescendant":return function(m){let D=m;do if(n(D))return!0;while(D=tY(D,p));return!1};case Kr.Parent:return function(m){return p.getChildren(m).some(D=>p.isTag(D)&&n(D))};case Kr.Child:return function(m){let D=p.getParent(m);return D!=null&&p.isTag(D)&&n(D)};case Kr.Sibling:return function(m){let D=p.getSiblings(m);for(let b=0;b<D.length;b++){let E=D[b];if(x(m,E))break;if(p.isTag(E)&&n(E))return!0}return!1};case Kr.Adjacent:return p.prevElementSibling?function(m){let D=p.prevElementSibling(m);return D!=null&&n(D)}:function(m){let D=p.getSiblings(m),b;for(let E=0;E<D.length;E++){let A=D[E];if(x(m,A))break;p.isTag(A)&&(b=A)}return!!b&&n(b)};case Kr.Universal:{if(e.namespace!=null&&e.namespace!=="*")throw new Error("Namespaced universal selectors are not yet supported by css-select");return n}}}function z8e(n,e,a){let s=UR(n,e,a);return QX(s,e.adapter)}function UR(n,e,a){let s=typeof n=="string"?vb(n):n;return VR(s,e,a)}function q8e(n){return n.type===Kr.Pseudo&&(n.name==="scope"||Array.isArray(n.data)&&n.data.some(e=>e.some(q8e)))}var IIt={type:Kr.Descendant},jIt={type:"_flexibleDescendant"},kIt={type:Kr.Pseudo,name:"scope",data:null};function NIt(n,{adapter:e},a){let s=!!a?.every(l=>{let p=e.isTag(l)&&e.getParent(l);return l===ZX||p&&e.isTag(p)});for(let l of n){if(!(l.length>0&&Cb(l[0])&&l[0].type!==Kr.Descendant))if(s&&!l.some(q8e))l.unshift(IIt);else continue;l.unshift(kIt)}}function VR(n,e,a){var s;n.forEach(GX),a=(s=e.context)!==null&&s!==void 0?s:a;let l=Array.isArray(a),p=a&&(Array.isArray(a)?a:[a]);if(e.relativeSelector!==!1)NIt(n,e,p);else if(n.some(m=>m.length>0&&Cb(m[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let x=!1,f=n.map(m=>{if(m.length>=2){let[D,b]=m;D.type!==Kr.Pseudo||D.name!=="scope"||(l&&b.type===Kr.Descendant?m[1]=jIt:(b.type===Kr.Adjacent||b.type===Kr.Sibling)&&(x=!0))}return MIt(m,e,p)}).reduce(OIt,Jl.default.falseFunc);return f.shouldTestNextSiblings=x,f}function MIt(n,e,a){var s;return n.reduce((l,p)=>l===Jl.default.falseFunc?Jl.default.falseFunc:$8e(l,p,e,a,VR),(s=e.rootFunc)!==null&&s!==void 0?s:Jl.default.trueFunc)}function OIt(n,e){return e===Jl.default.falseFunc||n===Jl.default.trueFunc?n:n===Jl.default.falseFunc||e===Jl.default.trueFunc?e:function(s){return n(s)||e(s)}}var U8e=(n,e)=>n===e,LIt={adapter:LR,equals:U8e};function V8e(n){var e,a,s,l;let p=n??LIt;return(e=p.adapter)!==null&&e!==void 0||(p.adapter=LR),(a=p.equals)!==null&&a!==void 0||(p.equals=(l=(s=p.adapter)===null||s===void 0?void 0:s.equals)!==null&&l!==void 0?l:U8e),p}function nY(n){return function(a,s,l){let p=V8e(s);return n(a,p,l)}}var srr=nY(z8e),irr=nY(UR),orr=nY(VR);function G8e(n){return function(a,s,l){let p=V8e(l);typeof a!="function"&&(a=UR(a,p,s));let x=$It(s,p.adapter,a.shouldTestNextSiblings);return n(a,x,p)}}function $It(n,e,a=!1){return a&&(n=zIt(n,e)),Array.isArray(n)?e.removeSubsets(n):e.getChildren(n)}function zIt(n,e){let a=Array.isArray(n)?n.slice(0):[n],s=a.length;for(let l=0;l<s;l++){let p=eY(a[l],e);a.push(...p)}return a}var aY=G8e((n,e,a)=>n===rY.default.falseFunc||!e||e.length===0?[]:a.adapter.findAll(n,e)),GR=G8e((n,e,a)=>n===rY.default.falseFunc||!e||e.length===0?null:a.adapter.findOne(n,e));Xe();Yt();Xe();var E_e=qr(vs(),1);Yt();var __e=qr(vs(),1),R_e=qr(vs(),1);Yt();Zl();dY();var pY=(n,e={})=>{let a=n._internal_store;if(!a){a={counts:{}},n._internal_store=a;for(let l of n){let p=l.type,x=l[`${p}_id`];if(!x)continue;let f=Number.parseInt(x.split("_").pop());Number.isNaN(f)||(a.counts[p]=Math.max(a.counts[p]??0,f))}}return new Proxy({},{get:(l,p)=>p==="toArray"?()=>n:{get:x=>n.find(f=>f.type===p&&f[`${p}_id`]===x),getUsing:x=>{let f=Object.keys(x);if(f.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");let m=f[0],D=m.replace("_id",""),b=n.find(E=>E.type===D&&E[m]===x[m]);return b?n.find(E=>E.type===p&&E[`${p}_id`]===b[`${p}_id`]):null},getWhere:x=>{let f=Object.keys(x);return n.find(m=>m.type===p&&f.every(D=>m[D]===x[D]))},list:x=>{let f=x?Object.keys(x):[];return n.filter(m=>m.type===p&&f.every(D=>m[D]===x[D]))},insert:x=>{var D;(D=a.counts)[p]??(D[p]=-1),a.counts[p]++;let f=a.counts[p],m={type:p,[`${p}_id`]:`${p}_${f}`,...x};return e.validateInserts&&(qf[p]??zf).parse(m),n.push(m),m},delete:x=>{let f=n.find(m=>m[`${p}_id`]===x);f&&n.splice(n.indexOf(f),1)},update:(x,f)=>{let m=n.find(D=>D[`${p}_id`]===x);if(m)return Object.assign(m,f),m},select:x=>{if(p==="source_component")return n.find(f=>f.type==="source_component"&&f.name===x.replace(/\./g,""));if(p==="pcb_port"||p==="source_port"||p==="schematic_port"){let[f,m]=x.replace(/\./g,"").split(/[\s\>]+/),D=n.find(E=>E.type==="source_component"&&E.name===f);if(!D)return null;let b=n.find(E=>E.type==="source_port"&&E.source_component_id===D.source_component_id&&(E.name===m||(E.port_hints??[]).includes(m)));if(!b)return null;if(p==="source_port")return b;if(p==="pcb_port")return n.find(E=>E.type==="pcb_port"&&E.source_port_id===b.source_port_id);if(p==="schematic_port")return n.find(E=>E.type==="schematic_port"&&E.source_port_id===b.source_port_id)}}}})};pY.unparsed=pY;var a_e=pY;var har=qr(i_e(),1);Jo();function Ql(n){let e=n.width/2,a=n.height/2;return{minX:n.center.x-e,maxX:n.center.x+e,minY:n.center.y-a,maxY:n.center.y+a}}function eg(n,e){let a=Ql(n),s=Ql(e),l=Math.max(a.minX-s.maxX,s.minX-a.maxX,0),p=Math.max(a.minY-s.maxY,s.minY-a.maxY,0),x={x:0,y:0},f={x:0,y:0};return l===0&&p===0?{distance:0,pointA:n.center,pointB:e.center}:(x.x=xs(n.center.x,s.minX,s.maxX),x.y=xs(n.center.y,s.minY,s.maxY),f.x=xs(e.center.x,a.minX,a.maxX),f.y=xs(e.center.y,a.minY,a.maxY),{distance:Math.hypot(x.x-f.x,x.y-f.y),pointA:x,pointB:f})}function xs(n,e,a){return Math.max(e,Math.min(a,n))}function Ib(n,e){let a=Number.POSITIVE_INFINITY,s={x:0,y:0},l={x:0,y:0};for(let p of n)for(let x of e){let{distance:f,pointA:m,pointB:D}=eg(p,x);f<a&&(a=f,s=m,l=D)}return{pointA:s,pointB:l,distance:a}}Jo();Jo();var x_e="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var f_e=(n=21)=>{let e="",a=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=x_e[a[n]&63];return e};Jo();var r1=(n,e)=>Math.abs(n.x-e.x)+Math.abs(n.y-e.y),h_e=(n,e)=>{let a=e.x-n.x,s=e.y-n.y;return Math.abs(a)>Math.abs(s)?{dx:Math.sign(a),dy:0}:{dx:0,dy:Math.sign(s)}},b_e=(n,e,a)=>Math.abs(n.x-e.x)*Math.abs(a.dx)+Math.abs(n.y-e.y)*Math.abs(a.dy),F_e=(n,e=.1)=>`${Math.round(n.x/e)},${Math.round(n.y/e)}`,m_e=(n,e)=>Math.abs(n-e)<1e-4,v_e=(n,e,{viaDiameter:a=.5}={})=>{let s=[];for(let l=0;l<n.length-1;l++){let[p,x]=[n[l],n[l+1]],f=l-1>=0?n[l-1]:null,m=m_e(p.y,x.y),D=m_e(p.x,x.x);if(!m&&!D)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${p.x}, ${p.y}), end: (${x.x}, ${x.y})`);let b={type:"rect",layers:[p.layer],center:{x:(p.x+x.x)/2,y:(p.y+x.y)/2},width:m?Math.abs(p.x-x.x):.1,height:D?Math.abs(p.y-x.y):.1,connectedTo:[e]};if(s.push(b),f&&f.layer===p.layer&&p.layer!==x.layer){let E={type:"rect",layers:[p.layer,x.layer],center:{x:p.x,y:p.y},connectedTo:[e],width:a,height:a};s.push(E)}}return s},C_e=class{constructor(n){q(this,"obstacles");q(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,a){a??(a=this.GRID_STEP);for(let s of this.obstacles){let l=s.width/2+a,p=s.height/2+a;if(n>=s.center.x-l&&n<=s.center.x+l&&e>=s.center.y-p&&e<=s.center.y+p)return s}return null}isObstacleAt(n,e,a){return this.getObstacleAt(n,e,a)!==null}getDirectionDistancesToNearestObstacle(n,e){let{GRID_STEP:a}=this,s={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let l of this.obstacles)if(l.type==="rect"){let p=l.center.x-l.width/2-a,x=l.center.x+l.width/2+a,f=l.center.y+l.height/2+a,m=l.center.y-l.height/2-a;e>=m&&e<=f&&n>p&&(s.left=Math.min(s.left,n-x)),e>=m&&e<=f&&n<x&&(s.right=Math.min(s.right,p-n)),n>=p&&n<=x&&e<f&&(s.top=Math.min(s.top,m-e)),n>=p&&n<=x&&e>m&&(s.bottom=Math.min(s.bottom,e-f))}return s}getOrthoDirectionCollisionInfo(n,e,{margin:a=0}={}){let{x:s,y:l}=n,{dx:p,dy:x}=e,f=1/0,m=null;for(let D of this.obstacles){let b=D.left-a,E=D.right+a,A=D.top+a,B=D.bottom-a,w=null;p===1&&x===0?l>B&&l<A&&s<D.left&&(w=D.left-s):p===-1&&x===0?l>B&&l<A&&s>D.right&&(w=s-D.right):p===0&&x===1?s>b&&s<E&&l<D.bottom&&(w=D.bottom-l):p===0&&x===-1&&s>b&&s<E&&l>D.top&&(w=l-D.top),w!==null&&w<f&&(f=w,m=D)}return{dx:p,dy:x,wallDistance:f,obstacle:m}}getObstaclesOverlappingRegion(n){let e=[];for(let a of this.obstacles){let{left:s,right:l,top:p,bottom:x}=a;s<=n.maxX&&l>=n.minX&&p<=n.maxY&&x>=n.minY&&e.push(a)}return e}};function VIt(n){if(n.length<4)return n;let e=[{...n[0]}],a=n[0].layer;for(let s=1;s<n.length;s++){let l={start:n[s-1],end:n[s]},p=n[s].route_type==="via"||n[s-1].route_type==="via";if(n[s].layer!==a||p){e.push({...n[s]}),a=n[s].layer;continue}let x=!1,f=null,m=-1;for(let b=0;b<e.length-1;b++){let E={start:e[b],end:e[b+1]};if(E.start.layer===l.start.layer&&E.start.layer===l.start.layer){let A=GIt(E,l);if(A){x=!0,f={...A,layer:a},m=b;break}}}x&&f&&(e.splice(m+1),e.push(f));let D=e[e.length-1];(D.x!==n[s].x||D.y!==n[s].y)&&e.push(n[s])}return e}function GIt(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 a;if(n.start.x===n.end.x){let s=n.start.x,l=e.start.y;a={...n.start,x:s,y:l}}else{let s=e.start.x,l=n.start.y;a={...n.start,x:s,y:l}}return g_e(a,n)&&g_e(a,e)?a:null}function g_e(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 XIt(n){let e=[n[0]];for(let a=1;a<n.length-1;a++){let[s,l,p]=[n[a-1],n[a],n[a+1]];e.push(l),!(l.route_type!=="wire"||s.route_type!=="wire"||p.route_type!=="wire")&&s.layer===l.layer&&l.layer!==p.layer&&e.push({route_type:"via",from_layer:l.layer,to_layer:p.layer,x:l.x,y:l.y})}return e.push(n[n.length-1]),e}var xar=(0,__e.default)("autorouter:shortenPathWithShortcuts");function YIt(n,e){if(n.length<=2)return n;let a=[n[0]];for(let s=1;s<n.length;s++){let l={start:a[a.length-1],end:n[s]},p=-1,x=l.start.x===l.end.x,f=l.start.y===l.end.y;for(let m=s+1;m<n.length;m++){if(m<=p)continue;let D={start:n[m],end:n[m+1]};if(!D.end)continue;let b=D.start.x===D.end.x,E=D.start.y===D.end.y,A=x&&b,B=f&&E;if(B&&A||!(A||B))continue;let P=!1,N=Math.min(l.start.x,l.end.x),O=Math.max(l.start.x,l.end.x),$=Math.min(D.start.x,D.end.x),ee=Math.max(D.start.x,D.end.x),X=Math.min(l.start.y,l.end.y),te=Math.max(l.start.y,l.end.y),L=Math.min(D.start.y,D.end.y),K=Math.max(D.start.y,D.end.y);if(B?P=N<=ee&&O>=$:A&&(P=X<=K&&te>=L),!P)continue;let U=[],J=a[a.length-1],Q=n[m+2];if(!Q)continue;B&&$<O&&Q.x===$&&U.push({x:$,y:l.start.y,layer:l.start.layer}),B&&ee>N&&Q.x===ee&&U.push({x:ee,y:l.start.y,layer:l.start.layer}),A&&L<te&&Q.y===L&&U.push({x:l.start.x,y:L,layer:l.start.layer}),A&&K>X&&Q.y===K&&U.push({x:l.start.x,y:K,layer:l.start.layer});let de=null;for(let ce of U)if(!(e(J,ce)||e(Q,ce))){de=ce;break}if(de){a.push(de),s=m+1,p=m+1;break}}p===-1&&a.push(n[s])}return a[a.length-1]!==n[n.length-1]&&a.push(n[n.length-1]),a}var t1=(0,E_e.default)("autorouting-dataset:astar"),A_e=class{constructor(n){q(this,"openSet",[]);q(this,"closedSet",new Set);q(this,"debug",!1);q(this,"debugSolutions");q(this,"debugMessage",null);q(this,"debugTraceCount",0);q(this,"input");q(this,"obstacles");q(this,"allObstacles");q(this,"startNode");q(this,"goalPoint");q(this,"GRID_STEP");q(this,"OBSTACLE_MARGIN");q(this,"MAX_ITERATIONS");q(this,"isRemovePathLoopsEnabled");q(this,"isShortenPathWithShortcutsEnabled");q(this,"GREEDY_MULTIPLIER",1.1);q(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??t1.enabled,this.isRemovePathLoopsEnabled=n.isRemovePathLoopsEnabled??!1,this.isShortenPathWithShortcutsEnabled=n.isShortenPathWithShortcutsEnabled??!1,this.debug&&(t1.enabled=!0),t1.enabled&&(this.debugSolutions={},this.debugMessage="")}getNeighbors(n){return[]}isSameNode(n,e){return r1(n,e)<this.GRID_STEP}computeG(n,e){return n.g+r1(n,e)}computeH(n){return r1(n,this.goalPoint)}getNodeName(n){return F_e(n,this.GRID_STEP)}solveOneStep(){this.iterations+=1;let{openSet:n,closedSet:e,GRID_STEP:a,goalPoint:s}=this;n.sort((f,m)=>f.f-m.f);let l=n.shift();if(this.computeH(l)<=a*2)return{solved:!0,current:l,newNeighbors:[]};this.closedSet.add(this.getNodeName(l));let x=[];for(let f of this.getNeighbors(l)){if(e.has(this.getNodeName(f)))continue;let m=this.computeG(l,f),D=this.openSet.find(b=>this.isSameNode(b,f));if(!D||m<D.g){let b=this.computeH(f),E=m+b*this.GREEDY_MULTIPLIER,A={...f,g:m,h:b,f:E,obstacleHit:f.obstacleHit??void 0,manDistFromParent:r1(l,f),nodesInPath:l.nodesInPath+1,parent:l,enterMarginCost:f.enterMarginCost,travelMarginCostFactor:f.travelMarginCostFactor};n.push(A),x.push(A)}}return t1.enabled&&(n.sort((f,m)=>f.f-m.f),this.drawDebugSolution({current:l,newNeighbors:x})),{solved:!1,current:l,newNeighbors:x}}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:a,current:s}=this.solveOneStep();if(a){let l=[],p=s;for(;p;){let x=p.l;l.unshift({x:p.x,y:p.y,layer:x!==void 0?this.indexToLayer(x):e[0].layer}),p=p.parent}return t1.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations
|
|
951
|
+
)`,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 Wu=qr(Kf(),1);var ZX={};function QX(n,e){return n===Wu.default.falseFunc?Wu.default.falseFunc:a=>e.isTag(a)&&n(a)}function eY(n,e){let a=e.getSiblings(n);if(a.length<=1)return[];let s=a.indexOf(n);return s<0||s===a.length-1?[]:a.slice(s+1).filter(e.isTag)}function JX(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 KX=(n,e,a,s,l)=>{let p=l(e,JX(a),s);return p===Wu.default.trueFunc?n:p===Wu.default.falseFunc?Wu.default.falseFunc:x=>p(x)&&n(x)},qR={is:KX,matches:KX,where:KX,not(n,e,a,s,l){let p=l(e,JX(a),s);return p===Wu.default.falseFunc?n:p===Wu.default.trueFunc?Wu.default.falseFunc:x=>!p(x)&&n(x)},has(n,e,a,s,l){let{adapter:p}=a,x=JX(a);x.relativeSelector=!0;let f=e.some(b=>b.some(Cb))?[ZX]:void 0,m=l(e,x,f);if(m===Wu.default.falseFunc)return Wu.default.falseFunc;let D=QX(m,p);if(f&&m!==Wu.default.trueFunc){let{shouldTestNextSiblings:b=!1}=m;return E=>{if(!n(E))return!1;f[0]=E;let A=p.getChildren(E),B=b?[...A,...eY(E,p)]:A;return p.existsOne(D,B)}}return b=>n(b)&&p.existsOne(D,p.getChildren(b))}};function L8e(n,e,a,s,l){var p;let{name:x,data:f}=e;if(Array.isArray(f)){if(!(x in qR))throw new Error(`Unknown pseudo-class :${x}(${f})`);return qR[x](n,f,a,s,l)}let m=(p=a.pseudos)===null||p===void 0?void 0:p[x],D=typeof m=="string"?m:WX[x];if(typeof D=="string"){if(f!=null)throw new Error(`Pseudo ${x} doesn't have any arguments`);let b=vb(D);return qR.is(n,b,a,s,l)}if(typeof m=="function")return HX(m,x,f,1),b=>m(b,f)&&n(b);if(x in Ab)return Ab[x](n,f,a,s);if(x in zR){let b=zR[x];return HX(b,x,f,2),E=>b(E,a,f)&&n(E)}throw new Error(`Unknown pseudo-class :${x}`)}function tY(n,e){let a=e.getParent(n);return a&&e.isTag(a)?a:null}function $8e(n,e,a,s,l){let{adapter:p,equals:x}=a;switch(e.type){case Kr.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case Kr.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case Kr.Attribute:{if(e.namespace!=null)throw new Error("Namespaced attributes are not yet supported by css-select");return(!a.xmlMode||a.lowerCaseAttributeNames)&&(e.name=e.name.toLowerCase()),k8e[e.action](n,e,a)}case Kr.Pseudo:return L8e(n,e,a,s,l);case Kr.Tag:{if(e.namespace!=null)throw new Error("Namespaced tag names are not yet supported by css-select");let{name:f}=e;return(!a.xmlMode||a.lowerCaseTags)&&(f=f.toLowerCase()),function(D){return p.getName(D)===f&&n(D)}}case Kr.Descendant:{if(a.cacheResults===!1||typeof WeakSet>"u")return function(D){let b=D;for(;b=tY(b,p);)if(n(b))return!0;return!1};let f=new WeakSet;return function(D){let b=D;for(;b=tY(b,p);)if(!f.has(b)){if(p.isTag(b)&&n(b))return!0;f.add(b)}return!1}}case"_flexibleDescendant":return function(m){let D=m;do if(n(D))return!0;while(D=tY(D,p));return!1};case Kr.Parent:return function(m){return p.getChildren(m).some(D=>p.isTag(D)&&n(D))};case Kr.Child:return function(m){let D=p.getParent(m);return D!=null&&p.isTag(D)&&n(D)};case Kr.Sibling:return function(m){let D=p.getSiblings(m);for(let b=0;b<D.length;b++){let E=D[b];if(x(m,E))break;if(p.isTag(E)&&n(E))return!0}return!1};case Kr.Adjacent:return p.prevElementSibling?function(m){let D=p.prevElementSibling(m);return D!=null&&n(D)}:function(m){let D=p.getSiblings(m),b;for(let E=0;E<D.length;E++){let A=D[E];if(x(m,A))break;p.isTag(A)&&(b=A)}return!!b&&n(b)};case Kr.Universal:{if(e.namespace!=null&&e.namespace!=="*")throw new Error("Namespaced universal selectors are not yet supported by css-select");return n}}}function z8e(n,e,a){let s=UR(n,e,a);return QX(s,e.adapter)}function UR(n,e,a){let s=typeof n=="string"?vb(n):n;return VR(s,e,a)}function q8e(n){return n.type===Kr.Pseudo&&(n.name==="scope"||Array.isArray(n.data)&&n.data.some(e=>e.some(q8e)))}var IIt={type:Kr.Descendant},jIt={type:"_flexibleDescendant"},kIt={type:Kr.Pseudo,name:"scope",data:null};function NIt(n,{adapter:e},a){let s=!!a?.every(l=>{let p=e.isTag(l)&&e.getParent(l);return l===ZX||p&&e.isTag(p)});for(let l of n){if(!(l.length>0&&Cb(l[0])&&l[0].type!==Kr.Descendant))if(s&&!l.some(q8e))l.unshift(IIt);else continue;l.unshift(kIt)}}function VR(n,e,a){var s;n.forEach(GX),a=(s=e.context)!==null&&s!==void 0?s:a;let l=Array.isArray(a),p=a&&(Array.isArray(a)?a:[a]);if(e.relativeSelector!==!1)NIt(n,e,p);else if(n.some(m=>m.length>0&&Cb(m[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let x=!1,f=n.map(m=>{if(m.length>=2){let[D,b]=m;D.type!==Kr.Pseudo||D.name!=="scope"||(l&&b.type===Kr.Descendant?m[1]=jIt:(b.type===Kr.Adjacent||b.type===Kr.Sibling)&&(x=!0))}return MIt(m,e,p)}).reduce(OIt,Jl.default.falseFunc);return f.shouldTestNextSiblings=x,f}function MIt(n,e,a){var s;return n.reduce((l,p)=>l===Jl.default.falseFunc?Jl.default.falseFunc:$8e(l,p,e,a,VR),(s=e.rootFunc)!==null&&s!==void 0?s:Jl.default.trueFunc)}function OIt(n,e){return e===Jl.default.falseFunc||n===Jl.default.trueFunc?n:n===Jl.default.falseFunc||e===Jl.default.trueFunc?e:function(s){return n(s)||e(s)}}var U8e=(n,e)=>n===e,LIt={adapter:LR,equals:U8e};function V8e(n){var e,a,s,l;let p=n??LIt;return(e=p.adapter)!==null&&e!==void 0||(p.adapter=LR),(a=p.equals)!==null&&a!==void 0||(p.equals=(l=(s=p.adapter)===null||s===void 0?void 0:s.equals)!==null&&l!==void 0?l:U8e),p}function nY(n){return function(a,s,l){let p=V8e(s);return n(a,p,l)}}var srr=nY(z8e),irr=nY(UR),orr=nY(VR);function G8e(n){return function(a,s,l){let p=V8e(l);typeof a!="function"&&(a=UR(a,p,s));let x=$It(s,p.adapter,a.shouldTestNextSiblings);return n(a,x,p)}}function $It(n,e,a=!1){return a&&(n=zIt(n,e)),Array.isArray(n)?e.removeSubsets(n):e.getChildren(n)}function zIt(n,e){let a=Array.isArray(n)?n.slice(0):[n],s=a.length;for(let l=0;l<s;l++){let p=eY(a[l],e);a.push(...p)}return a}var aY=G8e((n,e,a)=>n===rY.default.falseFunc||!e||e.length===0?[]:a.adapter.findAll(n,e)),GR=G8e((n,e,a)=>n===rY.default.falseFunc||!e||e.length===0?null:a.adapter.findOne(n,e));Xe();Yt();Xe();var E_e=qr(vs(),1);Yt();var __e=qr(vs(),1),R_e=qr(vs(),1);Yt();Zl();dY();var pY=(n,e={})=>{let a=n._internal_store;if(!a){a={counts:{}},n._internal_store=a;for(let l of n){let p=l.type,x=l[`${p}_id`];if(!x)continue;let f=Number.parseInt(x.split("_").pop());Number.isNaN(f)||(a.counts[p]=Math.max(a.counts[p]??0,f))}}return new Proxy({},{get:(l,p)=>p==="toArray"?()=>n:{get:x=>n.find(f=>f.type===p&&f[`${p}_id`]===x),getUsing:x=>{let f=Object.keys(x);if(f.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");let m=f[0],D=m.replace("_id",""),b=n.find(E=>E.type===D&&E[m]===x[m]);return b?n.find(E=>E.type===p&&E[`${p}_id`]===b[`${p}_id`]):null},getWhere:x=>{let f=Object.keys(x);return n.find(m=>m.type===p&&f.every(D=>m[D]===x[D]))},list:x=>{let f=x?Object.keys(x):[];return n.filter(m=>m.type===p&&f.every(D=>m[D]===x[D]))},insert:x=>{var D;(D=a.counts)[p]??(D[p]=-1),a.counts[p]++;let f=a.counts[p],m={type:p,[`${p}_id`]:`${p}_${f}`,...x};return e.validateInserts&&(qf[p]??zf).parse(m),n.push(m),m},delete:x=>{let f=n.find(m=>m[`${p}_id`]===x);f&&n.splice(n.indexOf(f),1)},update:(x,f)=>{let m=n.find(D=>D.type===p&&D[`${p}_id`]===x);if(m)return Object.assign(m,f),m},select:x=>{if(p==="source_component")return n.find(f=>f.type==="source_component"&&f.name===x.replace(/\./g,""));if(p==="pcb_port"||p==="source_port"||p==="schematic_port"){let[f,m]=x.replace(/\./g,"").split(/[\s\>]+/),D=n.find(E=>E.type==="source_component"&&E.name===f);if(!D)return null;let b=n.find(E=>E.type==="source_port"&&E.source_component_id===D.source_component_id&&(E.name===m||(E.port_hints??[]).includes(m)));if(!b)return null;if(p==="source_port")return b;if(p==="pcb_port")return n.find(E=>E.type==="pcb_port"&&E.source_port_id===b.source_port_id);if(p==="schematic_port")return n.find(E=>E.type==="schematic_port"&&E.source_port_id===b.source_port_id)}}}})};pY.unparsed=pY;var a_e=pY;var har=qr(i_e(),1);Jo();function Ql(n){let e=n.width/2,a=n.height/2;return{minX:n.center.x-e,maxX:n.center.x+e,minY:n.center.y-a,maxY:n.center.y+a}}function eg(n,e){let a=Ql(n),s=Ql(e),l=Math.max(a.minX-s.maxX,s.minX-a.maxX,0),p=Math.max(a.minY-s.maxY,s.minY-a.maxY,0),x={x:0,y:0},f={x:0,y:0};return l===0&&p===0?{distance:0,pointA:n.center,pointB:e.center}:(x.x=xs(n.center.x,s.minX,s.maxX),x.y=xs(n.center.y,s.minY,s.maxY),f.x=xs(e.center.x,a.minX,a.maxX),f.y=xs(e.center.y,a.minY,a.maxY),{distance:Math.hypot(x.x-f.x,x.y-f.y),pointA:x,pointB:f})}function xs(n,e,a){return Math.max(e,Math.min(a,n))}function Ib(n,e){let a=Number.POSITIVE_INFINITY,s={x:0,y:0},l={x:0,y:0};for(let p of n)for(let x of e){let{distance:f,pointA:m,pointB:D}=eg(p,x);f<a&&(a=f,s=m,l=D)}return{pointA:s,pointB:l,distance:a}}Jo();Jo();var x_e="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var f_e=(n=21)=>{let e="",a=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=x_e[a[n]&63];return e};Jo();var r1=(n,e)=>Math.abs(n.x-e.x)+Math.abs(n.y-e.y),h_e=(n,e)=>{let a=e.x-n.x,s=e.y-n.y;return Math.abs(a)>Math.abs(s)?{dx:Math.sign(a),dy:0}:{dx:0,dy:Math.sign(s)}},b_e=(n,e,a)=>Math.abs(n.x-e.x)*Math.abs(a.dx)+Math.abs(n.y-e.y)*Math.abs(a.dy),F_e=(n,e=.1)=>`${Math.round(n.x/e)},${Math.round(n.y/e)}`,m_e=(n,e)=>Math.abs(n-e)<1e-4,v_e=(n,e,{viaDiameter:a=.5}={})=>{let s=[];for(let l=0;l<n.length-1;l++){let[p,x]=[n[l],n[l+1]],f=l-1>=0?n[l-1]:null,m=m_e(p.y,x.y),D=m_e(p.x,x.x);if(!m&&!D)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${p.x}, ${p.y}), end: (${x.x}, ${x.y})`);let b={type:"rect",layers:[p.layer],center:{x:(p.x+x.x)/2,y:(p.y+x.y)/2},width:m?Math.abs(p.x-x.x):.1,height:D?Math.abs(p.y-x.y):.1,connectedTo:[e]};if(s.push(b),f&&f.layer===p.layer&&p.layer!==x.layer){let E={type:"rect",layers:[p.layer,x.layer],center:{x:p.x,y:p.y},connectedTo:[e],width:a,height:a};s.push(E)}}return s},C_e=class{constructor(n){q(this,"obstacles");q(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,a){a??(a=this.GRID_STEP);for(let s of this.obstacles){let l=s.width/2+a,p=s.height/2+a;if(n>=s.center.x-l&&n<=s.center.x+l&&e>=s.center.y-p&&e<=s.center.y+p)return s}return null}isObstacleAt(n,e,a){return this.getObstacleAt(n,e,a)!==null}getDirectionDistancesToNearestObstacle(n,e){let{GRID_STEP:a}=this,s={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let l of this.obstacles)if(l.type==="rect"){let p=l.center.x-l.width/2-a,x=l.center.x+l.width/2+a,f=l.center.y+l.height/2+a,m=l.center.y-l.height/2-a;e>=m&&e<=f&&n>p&&(s.left=Math.min(s.left,n-x)),e>=m&&e<=f&&n<x&&(s.right=Math.min(s.right,p-n)),n>=p&&n<=x&&e<f&&(s.top=Math.min(s.top,m-e)),n>=p&&n<=x&&e>m&&(s.bottom=Math.min(s.bottom,e-f))}return s}getOrthoDirectionCollisionInfo(n,e,{margin:a=0}={}){let{x:s,y:l}=n,{dx:p,dy:x}=e,f=1/0,m=null;for(let D of this.obstacles){let b=D.left-a,E=D.right+a,A=D.top+a,B=D.bottom-a,w=null;p===1&&x===0?l>B&&l<A&&s<D.left&&(w=D.left-s):p===-1&&x===0?l>B&&l<A&&s>D.right&&(w=s-D.right):p===0&&x===1?s>b&&s<E&&l<D.bottom&&(w=D.bottom-l):p===0&&x===-1&&s>b&&s<E&&l>D.top&&(w=l-D.top),w!==null&&w<f&&(f=w,m=D)}return{dx:p,dy:x,wallDistance:f,obstacle:m}}getObstaclesOverlappingRegion(n){let e=[];for(let a of this.obstacles){let{left:s,right:l,top:p,bottom:x}=a;s<=n.maxX&&l>=n.minX&&p<=n.maxY&&x>=n.minY&&e.push(a)}return e}};function VIt(n){if(n.length<4)return n;let e=[{...n[0]}],a=n[0].layer;for(let s=1;s<n.length;s++){let l={start:n[s-1],end:n[s]},p=n[s].route_type==="via"||n[s-1].route_type==="via";if(n[s].layer!==a||p){e.push({...n[s]}),a=n[s].layer;continue}let x=!1,f=null,m=-1;for(let b=0;b<e.length-1;b++){let E={start:e[b],end:e[b+1]};if(E.start.layer===l.start.layer&&E.start.layer===l.start.layer){let A=GIt(E,l);if(A){x=!0,f={...A,layer:a},m=b;break}}}x&&f&&(e.splice(m+1),e.push(f));let D=e[e.length-1];(D.x!==n[s].x||D.y!==n[s].y)&&e.push(n[s])}return e}function GIt(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 a;if(n.start.x===n.end.x){let s=n.start.x,l=e.start.y;a={...n.start,x:s,y:l}}else{let s=e.start.x,l=n.start.y;a={...n.start,x:s,y:l}}return g_e(a,n)&&g_e(a,e)?a:null}function g_e(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 XIt(n){let e=[n[0]];for(let a=1;a<n.length-1;a++){let[s,l,p]=[n[a-1],n[a],n[a+1]];e.push(l),!(l.route_type!=="wire"||s.route_type!=="wire"||p.route_type!=="wire")&&s.layer===l.layer&&l.layer!==p.layer&&e.push({route_type:"via",from_layer:l.layer,to_layer:p.layer,x:l.x,y:l.y})}return e.push(n[n.length-1]),e}var xar=(0,__e.default)("autorouter:shortenPathWithShortcuts");function YIt(n,e){if(n.length<=2)return n;let a=[n[0]];for(let s=1;s<n.length;s++){let l={start:a[a.length-1],end:n[s]},p=-1,x=l.start.x===l.end.x,f=l.start.y===l.end.y;for(let m=s+1;m<n.length;m++){if(m<=p)continue;let D={start:n[m],end:n[m+1]};if(!D.end)continue;let b=D.start.x===D.end.x,E=D.start.y===D.end.y,A=x&&b,B=f&&E;if(B&&A||!(A||B))continue;let P=!1,N=Math.min(l.start.x,l.end.x),O=Math.max(l.start.x,l.end.x),$=Math.min(D.start.x,D.end.x),ee=Math.max(D.start.x,D.end.x),X=Math.min(l.start.y,l.end.y),te=Math.max(l.start.y,l.end.y),L=Math.min(D.start.y,D.end.y),K=Math.max(D.start.y,D.end.y);if(B?P=N<=ee&&O>=$:A&&(P=X<=K&&te>=L),!P)continue;let U=[],J=a[a.length-1],Q=n[m+2];if(!Q)continue;B&&$<O&&Q.x===$&&U.push({x:$,y:l.start.y,layer:l.start.layer}),B&&ee>N&&Q.x===ee&&U.push({x:ee,y:l.start.y,layer:l.start.layer}),A&&L<te&&Q.y===L&&U.push({x:l.start.x,y:L,layer:l.start.layer}),A&&K>X&&Q.y===K&&U.push({x:l.start.x,y:K,layer:l.start.layer});let de=null;for(let ce of U)if(!(e(J,ce)||e(Q,ce))){de=ce;break}if(de){a.push(de),s=m+1,p=m+1;break}}p===-1&&a.push(n[s])}return a[a.length-1]!==n[n.length-1]&&a.push(n[n.length-1]),a}var t1=(0,E_e.default)("autorouting-dataset:astar"),A_e=class{constructor(n){q(this,"openSet",[]);q(this,"closedSet",new Set);q(this,"debug",!1);q(this,"debugSolutions");q(this,"debugMessage",null);q(this,"debugTraceCount",0);q(this,"input");q(this,"obstacles");q(this,"allObstacles");q(this,"startNode");q(this,"goalPoint");q(this,"GRID_STEP");q(this,"OBSTACLE_MARGIN");q(this,"MAX_ITERATIONS");q(this,"isRemovePathLoopsEnabled");q(this,"isShortenPathWithShortcutsEnabled");q(this,"GREEDY_MULTIPLIER",1.1);q(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??t1.enabled,this.isRemovePathLoopsEnabled=n.isRemovePathLoopsEnabled??!1,this.isShortenPathWithShortcutsEnabled=n.isShortenPathWithShortcutsEnabled??!1,this.debug&&(t1.enabled=!0),t1.enabled&&(this.debugSolutions={},this.debugMessage="")}getNeighbors(n){return[]}isSameNode(n,e){return r1(n,e)<this.GRID_STEP}computeG(n,e){return n.g+r1(n,e)}computeH(n){return r1(n,this.goalPoint)}getNodeName(n){return F_e(n,this.GRID_STEP)}solveOneStep(){this.iterations+=1;let{openSet:n,closedSet:e,GRID_STEP:a,goalPoint:s}=this;n.sort((f,m)=>f.f-m.f);let l=n.shift();if(this.computeH(l)<=a*2)return{solved:!0,current:l,newNeighbors:[]};this.closedSet.add(this.getNodeName(l));let x=[];for(let f of this.getNeighbors(l)){if(e.has(this.getNodeName(f)))continue;let m=this.computeG(l,f),D=this.openSet.find(b=>this.isSameNode(b,f));if(!D||m<D.g){let b=this.computeH(f),E=m+b*this.GREEDY_MULTIPLIER,A={...f,g:m,h:b,f:E,obstacleHit:f.obstacleHit??void 0,manDistFromParent:r1(l,f),nodesInPath:l.nodesInPath+1,parent:l,enterMarginCost:f.enterMarginCost,travelMarginCostFactor:f.travelMarginCostFactor};n.push(A),x.push(A)}}return t1.enabled&&(n.sort((f,m)=>f.f-m.f),this.drawDebugSolution({current:l,newNeighbors:x})),{solved:!1,current:l,newNeighbors:x}}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:a,current:s}=this.solveOneStep();if(a){let l=[],p=s;for(;p;){let x=p.l;l.unshift({x:p.x,y:p.y,layer:x!==void 0?this.indexToLayer(x):e[0].layer}),p=p.parent}return t1.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations
|
|
952
952
|
`),this.isRemovePathLoopsEnabled&&(l=VIt(l)),this.isShortenPathWithShortcutsEnabled&&(l=YIt(l,(x,f)=>{if(x.x===f.x&&x.y===f.y)return!1;let m=this.obstacles.getOrthoDirectionCollisionInfo({x:x.x,y:x.y,l:this.layerToIndex(x.layer)??0},{dx:Math.sign(f.x-x.x),dy:Math.sign(f.y-x.y),dl:0},{margin:.05}),D=Math.sqrt((x.x-f.x)**2+(x.y-f.y)**2);return m.wallDistance<D})),{solved:!0,route:l,connectionName:n.name}}if(this.openSet.length===0)break}return t1.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations (failed)
|
|
953
953
|
`),{solved:!1,connectionName:n.name}}createObstacleList({dominantLayer:n,connection:e,obstaclesFromTraces:a}){return new C_e(this.allObstacles.filter(s=>!s.connectedTo.includes(e.name)).filter(s=>s.layers.includes(n)).concat(a??[]))}postprocessConnectionSolveResult(n,e){return e}solve(){let n=[],e=[];this.debugTraceCount=0;for(let a of this.input.connections){let s=a.pointsToConnect[0].layer??"top";this.debugTraceCount+=1,this.obstacles=this.createObstacleList({dominantLayer:s,connection:a,obstaclesFromTraces:e});let l=this.solveConnection(a);l=this.postprocessConnectionSolveResult(a,l),n.push(l),t1.enabled&&this.drawDebugTraceObstacles(e),l.solved&&e.push(...v_e(l.route.map(p=>({x:p.x,y:p.y,layer:p.layer??s})),a.name))}return n}solveAndMapToTraces(){return this.solve().flatMap(e=>e.solved?[{type:"pcb_trace",pcb_trace_id:`pcb_trace_for_${e.connectionName}`,route:XIt(e.route.map(a=>({route_type:"wire",x:a.x,y:a.y,width:this.input.minTraceWidth,layer:a.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:a}=this;for(let s in a)s.startsWith(`t${e}_`)&&a[s].push(...n.map((l,p)=>({type:"pcb_smtpad",pcb_component_id:"",layer:l.layers[0],width:l.width,shape:"rect",x:l.center.x,y:l.center.y,pcb_smtpad_id:`trace_obstacle_${p}`,height:l.height})))}drawDebugSolution({current:n,newNeighbors:e}){let a=this.getDebugGroup();if(!a)return;let{openSet:s,debugTraceCount:l,debugSolutions:p}=this;p[a]??(p[a]=[]);let x=p[a];x.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 f=0;f<s.length;f++){let m=s[f];x.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${m.x}_${m.y}`,layer:"top",route:[[0,.05],[.05,0],[0,-.05],[-.05,0],[0,.05]].map(([D,b])=>({x:m.x+D,y:m.y+b})),stroke_width:.01}),x.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${m.x}_${m.y}`,font:"tscircuit2024",font_size:.03,text:f.toString(),pcb_component_id:"",layer:"top",anchor_position:{x:m.x,y:m.y},anchor_alignment:"center"})}if(n.parent){let f=[],m=n;for(;m;)f.unshift(m),m=m.parent;x.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${n.x}_${n.y}`,layer:"top",route:f,stroke_width:.01})}}},HIt=(0,R_e.default)("autorouting-dataset:infinite-grid-ijump-astar:get-distance-to-overcome-obstacle");function mY({node:n,travelDir:e,wallDir:a,obstacle:s,obstacles:l,obstaclesInRow:p=0,OBSTACLE_MARGIN:x=.15,SHOULD_DETECT_CONJOINED_OBSTACLES:f=!1,MAX_CONJOINED_OBSTACLES:m=20}){let D;if(e.dx===0?e.dy>0?D=s.center.y+s.height/2-n.y:D=n.y-(s.center.y-s.height/2):e.dx>0?D=s.center.x+s.width/2-n.x:D=n.x-(s.center.x-s.width/2),D+=x,f&&p<m){let b=l.getObstacleAt(n.x+e.dx*D+a.dx*(a.wallDistance+.001),n.y+e.dy*D+a.dy*(a.wallDistance+.001));if(b===s)return D;if(b&&b.type==="rect"){let E=e.dy===0,A=E?s.height:s.width;if((E?b.height:b.width)>A)return HIt("next obstacle on path is bigger, not trying to overcome it"),D;let w=mY({node:{x:n.x+e.dx*D,y:n.y+e.dy*D},travelDir:e,wallDir:a,obstacle:b,obstacles:l,obstaclesInRow:p+1,SHOULD_DETECT_CONJOINED_OBSTACLES:f,MAX_CONJOINED_OBSTACLES:m,OBSTACLE_MARGIN:x});D+=w}}return D}var WIt=class extends A_e{constructor(){super(...arguments);q(this,"MAX_ITERATIONS",200)}getNeighbors(e){let a=this.obstacles,s=this.goalPoint,l;e.parent?l=h_e(e.parent,e):l=h_e(e,s);let p=[{dx:0,dy:1},{dx:1,dy:0},{dx:0,dy:-1},{dx:-1,dy:0}].filter(f=>f.dx===l.dx*-1&&f.dy===l.dy*-1?!1:!(f.dx===l.dx&&f.dy===l.dy&&e.parent?.obstacleHit)).map(f=>a.getOrthoDirectionCollisionInfo(e,f,{margin:this.OBSTACLE_MARGIN})).filter(f=>f.wallDistance>=this.OBSTACLE_MARGIN),x=[];for(let f of p){let m=null;e?.obstacleHit&&(m=mY({node:e,travelDir:f,wallDir:{...l,wallDistance:this.OBSTACLE_MARGIN},obstacle:e.obstacleHit,obstacles:a,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let D=b_e(e,s,f),b=(f.dx===0||Math.sign(s.x-e.x)===f.dx)&&(f.dy===0||Math.sign(s.y-e.y)===f.dy);D<f.wallDistance&&D>0&&b?x.push({...f,travelDistance:D}):m!==null&&m<f.wallDistance?x.push({...f,travelDistance:m}):f.wallDistance!==1/0&&x.push({...f,travelDistance:f.wallDistance-this.OBSTACLE_MARGIN})}return x.filter(f=>!a.isObstacleAt(e.x+f.dx*f.travelDistance,e.y+f.dy*f.travelDistance)).map(f=>({x:e.x+f.dx*f.travelDistance,y:e.y+f.dy*f.travelDistance,obstacleHit:f.obstacle}))}};function KIt(n,e=4){let{center:a,width:s,height:l,rotation:p}=n,x=[],f=p*Math.PI/180,m=Math.cos(f),D=Math.sin(f),b=(p%360+360)%360;if(l<=s?b>=45&&b<135||b>=225&&b<315:b>=135&&b<225||b>=315||b<45){let A=s/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*m,N=-w*D,O=A*1.1,$=Math.abs(l*m)+Math.abs(A*D);x.push({center:{x:a.x+P,y:a.y+N},width:O,height:$})}}else{let A=l/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*D,N=w*m,O=Math.abs(s*m)+Math.abs(A*D),$=A*1.1;x.push({center:{x:a.x+P,y:a.y+N},width:O,height:$})}}return x}var KR=["top","inner1","inner2","bottom"],S_e=(n,e)=>{let a=l=>e?l.concat(l.map(p=>e?.getNetConnectedToId(p)).filter(Boolean)):l,s=[];for(let l of n)if(l.type==="pcb_smtpad"){if(l.shape==="circle")s.push({type:"oval",layers:[l.layer],center:{x:l.x,y:l.y},width:l.radius*2,height:l.radius*2,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rect")s.push({type:"rect",layers:[l.layer],center:{x:l.x,y:l.y},width:l.width,height:l.height,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rotated_rect"){let p={center:{x:l.x,y:l.y},width:l.width,height:l.height,rotation:l.ccw_rotation},x=KIt(p);for(let f of x)s.push({type:"rect",layers:[l.layer],center:f.center,width:f.width,height:f.height,connectedTo:a([l.pcb_smtpad_id])})}}else if(l.type==="pcb_keepout")l.shape==="circle"?s.push({type:"oval",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.radius*2,height:l.radius*2,connectedTo:[]}):l.shape==="rect"&&s.push({type:"rect",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.type==="pcb_hole")l.hole_shape==="oval"?s.push({type:"oval",center:{x:l.x,y:l.y},width:l.hole_width,height:l.hole_height,connectedTo:[]}):l.hole_shape==="square"?s.push({type:"rect",layers:KR,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]}):(l.hole_shape==="round"||l.hole_shape==="circle")&&s.push({type:"rect",layers:KR,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]});else if(l.type==="pcb_plated_hole")l.shape==="circle"?s.push({type:"oval",layers:KR,center:{x:l.x,y:l.y},width:l.outer_diameter,height:l.outer_diameter,connectedTo:a([l.pcb_plated_hole_id])}):(l.shape==="oval"||l.shape==="pill")&&s.push({type:"oval",layers:KR,center:{x:l.x,y:l.y},width:l.outer_width,height:l.outer_height,connectedTo:a([l.pcb_plated_hole_id])});else if(l.type==="pcb_trace"){let p=v_e(l.route.map(x=>({x:x.x,y:x.y,layer:"layer"in x?x.layer:x.from_layer})),l.source_trace_id);s.push(...p)}else l.type==="pcb_via"&&s.push({type:"rect",layers:l.layers,center:{x:l.x,y:l.y},connectedTo:[],width:l.outer_diameter,height:l.outer_diameter});return s};function D_e(n){let{pcbConnMap:e,goalElementId:a}=n;if(!a.startsWith("pcb_port_"))throw new Error(`Currently alternative goal boxes must have a goal id with prefix "pcb_port_" (got ${a})`);let s=e.getAllTracesConnectedToPort(a);return S_e(s).map(l=>({...l,connectedTo:[a]}))}var B_e=n=>{let{connection:e,pcbConnMap:a}=n;if(e.pointsToConnect.length!==2)throw new Error(`Connection must have exactly 2 points for alternative goal boxes (got ${e.pointsToConnect.length})`);let[s,l]=e.pointsToConnect;if(!s.pcb_port_id||!l.pcb_port_id)throw new Error(`Connection points must have pcb_port_id for alternative goal box calculation (got ${s.pcb_port_id} and ${l.pcb_port_id})`);let p=D_e({goalElementId:s.pcb_port_id,pcbConnMap:a}).concat([{center:s,width:.01,height:.01,connectedTo:[s.pcb_port_id],layers:[s.layer],type:"rect"}]),x=D_e({goalElementId:l.pcb_port_id,pcbConnMap:a}).concat([{center:l,width:.01,height:.01,connectedTo:[l.pcb_port_id],layers:[l.layer],type:"rect"}]);if(p.length<=1&&x.length<=1)return{...e,startPoint:s,endPoint:l,goalBoxes:[]};let f=Ib(p,x),m,D,b;return p.length>=x.length?(m={...l,...f.pointB},D={...s,...f.pointA},b=p):(m={...s,...f.pointA},D={...l,...f.pointB},b=x),{startPoint:m,endPoint:D,goalBoxes:b,name:e.name,pointsToConnect:[m,D]}},JIt=(n,e={})=>{let a={minTraceWidth:.1};a.layerCount=e.layerCount??1,a.obstacles=S_e(n,e.connMap),a.connections=[];for(let l of n)if(l.type==="source_trace"){let p={name:l.source_trace_id,pointsToConnect:l.connected_source_port_ids.map(x=>{let f=a_e(n).pcb_port.getWhere({source_port_id:x});if(!f)throw new Error(`Could not find pcb_port for source_port_id "${x}"`);return{x:f.x,y:f.y,layer:f.layers?.[0]??"top",pcb_port_id:f.pcb_port_id}})};if(e.optimizeWithGoalBoxes){let x=new WR(n);p=B_e({connection:p,pcbConnMap:x})}a.connections.push(p),ZIt(a.obstacles,p.pointsToConnect,p.name)}let s={minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0};for(let l of a.obstacles)s.minX=Math.min(s.minX,l.center.x-l.width/2),s.maxX=Math.max(s.maxX,l.center.x+l.width/2),s.minY=Math.min(s.minY,l.center.y-l.height/2),s.maxY=Math.max(s.maxY,l.center.y+l.height/2);for(let l of a.connections)for(let p of l.pointsToConnect)s.minX=Math.min(s.minX,p.x),s.maxX=Math.max(s.maxX,p.x),s.minY=Math.min(s.minY,p.y),s.maxY=Math.max(s.maxY,p.y);return a.bounds=s,a},ZIt=(n,e,a)=>{for(let s of e)for(let l of n)QIt(s,l)&&l.connectedTo.push(a)};function QIt(n,e){let a=e.width/2,s=e.height/2;if(e.type==="rect")return n.x>=e.center.x-a&&n.x<=e.center.x+a&&n.y>=e.center.y-s&&n.y<=e.center.y+s;if(e.type==="oval"){let l=(n.x-e.center.x)/a,p=(n.y-e.center.y)/s;return l*l+p*p<=1}return!1}function y_e(n,e){let a=e.x>n.x?1:e.x<n.x?-1:0,s=e.y>n.y?1:e.y<n.y?-1:0,l=e.l>n.l?1:e.l<n.l?-1:0;return{dx:a,dy:s,dl:l}}var gY={1:["top"],2:["top","bottom"],4:["top","inner1","inner2","bottom"]},ejt=n=>gY[n];function w_e(n,e){let s=gY[n].indexOf(e);if(s===-1)throw new Error(`Invalid layer for getLayerIndex (for layerCount === ${n}): "${e}"`);return s}function tjt(n,e){let s=gY[n][e];if(!s)throw new Error(`Invalid index for indexToLayer (for layerCount === ${n}): "${e}"`);return s}var rjt=class extends C_e{constructor(e,a){super([]);q(this,"obstacles");q(this,"GRID_STEP",.1);q(this,"layerCount");this.layerCount=e;let s=ejt(e);this.obstacles=a.flatMap(l=>l.layers.filter(p=>s.includes(p)).map(p=>({...l,left:l.center.x-l.width/2,right:l.center.x+l.width/2,top:l.center.y+l.height/2,bottom:l.center.y-l.height/2,l:w_e(e,p)})))}getObstacleAt(e,a,s,l){l??(l=this.GRID_STEP);for(let p of this.obstacles){if(p.l!==s)continue;let x=p.width/2+l,f=p.height/2+l;if(e>=p.center.x-x&&e<=p.center.x+x&&a>=p.center.y-f&&a<=p.center.y+f)return p}return null}isObstacleAt(e,a,s,l){return this.getObstacleAt(e,a,s,l)!==null}getDirectionDistancesToNearestObstacle3d(e,a,s){let{GRID_STEP:l}=this,p={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let x of this.obstacles)if(x.l===s&&x.type==="rect"){let f=x.center.x-x.width/2-l,m=x.center.x+x.width/2+l,D=x.center.y+x.height/2+l,b=x.center.y-x.height/2-l;a>=b&&a<=D&&e>f&&(p.left=Math.min(p.left,e-m)),a>=b&&a<=D&&e<m&&(p.right=Math.min(p.right,f-e)),e>=f&&e<=m&&a<D&&(p.top=Math.min(p.top,b-a)),e>=f&&e<=m&&a>b&&(p.bottom=Math.min(p.bottom,a-D))}return p}getOrthoDirectionCollisionInfo(e,a,{margin:s=0}={}){let{x:l,y:p,l:x}=e,{dx:f,dy:m,dl:D}=a,b=1/0,E=null;if(D!==0){let A=x+D;return this.isObstacleAt(l,p,A,s)?(b=1,E=this.getObstacleAt(l,p,A,s)):b=1,{dx:f,dy:m,dl:D,wallDistance:b,obstacle:E}}else{for(let A of this.obstacles){if(A.l!==x)continue;let B=A.left-s,w=A.right+s,P=A.top+s,N=A.bottom-s,O=null;f===1&&m===0?p>N&&p<P&&l<A.left&&(O=A.left-l):f===-1&&m===0?p>N&&p<P&&l>A.right&&(O=l-A.right):f===0&&m===1?l>B&&l<w&&p<A.bottom&&(O=A.bottom-p):f===0&&m===-1&&l>B&&l<w&&p>A.top&&(O=p-A.top),O!==null&&O<b&&(b=O,E=A)}return{dx:f,dy:m,dl:0,wallDistance:b,obstacle:E}}}getObstaclesOverlappingRegion(e){let a=[];for(let s of this.obstacles){if(s.l!==e.l)continue;let{left:l,right:p,top:x,bottom:f}=s;l<=e.maxX&&p>=e.minX&&x>=e.minY&&f<=e.maxY&&a.push(s)}return a}},JR=class extends A_e{constructor(e){super(e);q(this,"MAX_ITERATIONS",500);q(this,"VIA_COST",4);q(this,"VIA_DIAMETER",.5);q(this,"allowLayerChange",!0);q(this,"layerCount");q(this,"obstacles");q(this,"optimizeWithGoalBoxes");q(this,"connMap");q(this,"pcbConnMap");q(this,"GOAL_RUSH_FACTOR",1.1);q(this,"defaultGoalViaMargin",.5);q(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 WR,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?B_e({connection:e,pcbConnMap:this.pcbConnMap}):e}postprocessConnectionSolveResult(e,a){if(!a.solved)return a;if(this.optimizeWithGoalBoxes){let s=a.route.map(l=>({x:l.x,y:l.y,route_type:"wire",layer:l.layer,width:this.input.minTraceWidth}));s[0].start_pcb_port_id=e.pointsToConnect[0].pcb_port_id,s[s.length-1].end_pcb_port_id=e.pointsToConnect[1].pcb_port_id,this.pcbConnMap.addTrace({type:"pcb_trace",pcb_trace_id:`postprocess_trace_${f_e(8)}`,route:s})}return a}createObstacleList({dominantLayer:e,connection:a,obstaclesFromTraces:s}){let l=this.connMap?this.connMap.getNetConnectedToId(a.name):a.name;if(!l)throw new Error(`The connection.name "${a.name}" wasn't present in the full connectivity map`);return new rjt(this.layerCount,this.allObstacles.filter(p=>!p.connectedTo.includes(l)).concat(s??[]))}computeG(e,a){let s=e.g+r1(e,a)*(e.travelMarginCostFactor??1)+(a.enterMarginCost??0);return(a.l??e.l!==-1??-1)&&(s+=this.VIA_COST),s}computeH(e){let a=Math.abs(e.x-this.goalPoint.x),s=Math.abs(e.y-this.goalPoint.y),l=Math.abs(e.l-this.goalPoint.l);return(a+s)**this.GOAL_RUSH_FACTOR+l*this.VIA_COST}getStartNode(e){return{...super.getStartNode(e),l:this.layerToIndex(e.pointsToConnect[0].layer)}}layerToIndex(e){return w_e(this.layerCount,e)}indexToLayer(e){return tjt(this.layerCount,e)}getNodeName(e){return`${F_e(e,this.GRID_STEP)}-${e.l??0}`}hasSpaceForVia(e,a){return e.every(s=>this.obstacles.getObstaclesOverlappingRegion({minX:a.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:a.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:a.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:a.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:s}).length===0)}getNeighborsSurroundingGoal(e){let a=this.obstacles,s=this.goalPoint,l=[],p=[{dx:1,dy:0,dl:0},{dx:-1,dy:0,dl:0},{dx:0,dy:1,dl:0},{dx:0,dy:-1,dl:0}],x=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin;for(let f of p){let m={x:e.x+f.dx*x,y:e.y+f.dy*x,l:e.l+f.dl,obstacleHit:null};this.hasSpaceForVia([e.l,s.l],m)&&l.push(m)}return l}getNeighbors(e){let a=this.obstacles,s=this.goalPoint,l=r1(e,s);if(l<=this.OBSTACLE_MARGIN)return this.getNeighborsSurroundingGoal(e);let p;e.parent?p=y_e(e.parent,e):p=y_e(e,s);let x=[{dx:0,dy:1,dl:0},{dx:1,dy:0,dl:0},{dx:0,dy:-1,dl:0},{dx:-1,dy:0,dl:0}],f=l>this.VIA_DIAMETER+this.OBSTACLE_MARGIN,m=r1(e,this.startNode)>this.VIA_DIAMETER+this.OBSTACLE_MARGIN;this.allowLayerChange&&f&&m&&(e.l<this.layerCount-1&&x.push({dx:0,dy:0,dl:1}),e.l>0&&x.push({dx:0,dy:0,dl:-1}));let D=x.filter(E=>E.dx===p.dx*-1&&E.dy===p.dy*-1&&E.dl===p.dl*-1?!1:!(E.dx===p.dx&&E.dy===p.dy&&E.dl===p.dl&&e.parent?.obstacleHit)).map(E=>a.getOrthoDirectionCollisionInfo(e,E,{margin:this.OBSTACLE_MARGIN})).filter(E=>!(E.wallDistance<this.OBSTACLE_MARGIN)),b=[];for(let E of D){let A=E.dx===0&&E.dy===0&&E.dl===1,B=E.dx===0&&E.dy===0&&E.dl===-1;if((A||B)&&![e.l,e.l+E.dl].every($=>a.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:$}).length===0))continue;if(A){e.l<this.layerCount-1&&b.push({...E,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}if(B){e.l>0&&b.push({...E,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}let w=null;e?.obstacleHit&&(w=mY({node:e,travelDir:E,wallDir:{...p,wallDistance:this.OBSTACLE_MARGIN},obstacle:e.obstacleHit,obstacles:a,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let P=b_e(e,s,E),N=(E.dx===0||Math.sign(s.x-e.x)===E.dx)&&(E.dy===0||Math.sign(s.y-e.y)===E.dy);if(P<E.wallDistance&&P>0&&N){let O=e.l===s.l,$=0;!O&&Math.abs(P-l)<this.GRID_STEP&&($=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin),b.push({...E,travelDistance:P-$,enterMarginCost:0,travelMarginCostFactor:1})}else if(w!==null&&w<E.wallDistance){for(let{margin:O,enterCost:$,travelCostFactor:ee}of this.marginsWithCosts)w-this.OBSTACLE_MARGIN+O*2<E.wallDistance&&b.push({...E,travelDistance:w-this.OBSTACLE_MARGIN+O,enterMarginCost:$,travelMarginCostFactor:ee});if(E.wallDistance===1/0)b.push({...E,travelDistance:P,enterMarginCost:0,travelMarginCostFactor:1});else if(E.wallDistance>this.largestMargin)for(let{margin:O,enterCost:$,travelCostFactor:ee}of this.marginsWithCosts)E.wallDistance>this.largestMargin+O&&b.push({...E,travelDistance:E.wallDistance-O,enterMarginCost:$,travelMarginCostFactor:ee})}else if(E.wallDistance!==1/0)for(let{margin:O,enterCost:$,travelCostFactor:ee}of this.marginsWithCosts)E.wallDistance>O&&b.push({...E,travelDistance:E.wallDistance-O,enterMarginCost:$,travelMarginCostFactor:ee})}return b.map(E=>({x:e.x+E.dx*E.travelDistance,y:e.y+E.dy*E.travelDistance,l:e.l+E.dl,obstacleHit:E.obstacle,travelMarginCostFactor:E.travelMarginCostFactor,enterMarginCost:E.enterMarginCost}))}};function T_e(n){let e=JIt(n),a=new WIt({input:e});return{solution:a.solveAndMapToTraces(),debugSolutions:a.debugSolutions,debugMessage:a.debugMessage}}Xe();Xe();Yt();Xe();Xe();Yt();Xe();Xe();Xe();Xe();Yt();Xe();Xe();Yt();Xe();Yt();Yt();Xe();Xe();Xe();Xe();Xe();Xe();Xe();Xe();Xe();Xe();Xe();Yt();Xe();Yt();Xe();Yt();Yt();Yt();Xe();Yt();Xe();Xe();Xe();Yt();Xe();Xe();Yt();Xe();Yt();Xe();Yt();Xe();Yt();Xe();Yt();Xe();Yt();Xe();Yt();Xe();Xe();Xe();Xe();Xe();Xe();Xe();Xe();Yt();Xe();Yt();Xe();Xe();Yt();Xe();Yt();Xe();Xe();Yt();Xe();Yt();Xe();Xe();Yt();Xe();Xe();Xe();Xe();Yt();Xe();Yt();Xe();Yt();Xe();Yt();Xe();Yt();Xe();Xe();Yt();Xe();Xe();Yt();Yt();Xe();Yt();Xe();Xe();Yt();Xe();Yt();Xe();Xe();Yt();Xe();Yt();Xe();Yt();Xe();Yt();Xe();Yt();Xe();Yt();Xe();Yt();Yt();Xe();Yt();Xe();Yt();Xe();Xe();Xe();var pr=n=>{};pr("extra props b");pr("missing props b");pr(!0);pr("property a has mismatched types");var njt=C.enum(["up","down","left","right"]),Par=C.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);pr(!0);pr(!0);var U0=C.array(C.string().or(C.number()));pr(!0);var P_e=C.object({x:ze,y:ze,z:ze}),ajt=C.object({x:C.union([C.number(),C.string()]),y:C.union([C.number(),C.string()]),z:C.union([C.number(),C.string()])}),e5=C.object({rotationOffset:C.number().or(ajt).optional(),positionOffset:P_e.optional(),size:P_e.optional()});pr(!0);var sjt=e5.extend({stlUrl:C.string()}),ijt=e5.extend({objUrl:C.string(),mtlUrl:C.string().optional()}),ojt=e5.extend({gltfUrl:C.string()}),ujt=e5.extend({jscad:C.record(C.any())}),cjt=C.union([C.null(),C.string(),sjt,ijt,ojt,ujt]);pr(!0);var ljt=C.custom(n=>!0),Ea=C.object({pcbX:ze.optional(),pcbY:ze.optional(),pcbRotation:Ba.optional(),layer:hn.optional(),pcbRelative:C.boolean().optional(),relative:C.boolean().optional()});pr(!0);var t5=C.object({pcbX:ze.optional(),pcbY:ze.optional(),pcbRotation:Ba.optional(),schX:ze.optional(),schY:ze.optional(),schRotation:Ba.optional(),layer:hn.optional(),footprint:ljt.optional(),relative:C.boolean().optional(),schRelative:C.boolean().optional(),pcbRelative:C.boolean().optional()});pr(!0);var djt=C.object({supplierPartNumbers:C.record(Im,C.array(C.string())).optional()});pr(!0);var pjt=C.object({providesPower:C.boolean().optional(),requiresPower:C.boolean().optional(),providesGround:C.boolean().optional(),requiresGround:C.boolean().optional(),providesVoltage:C.union([C.string(),C.number()]).optional(),requiresVoltage:C.union([C.string(),C.number()]).optional(),doNotConnect:C.boolean().optional()});pr(!0);var fs=t5.merge(djt).extend({key:C.any().optional(),name:C.string(),cadModel:cjt.optional(),children:C.any().optional(),symbolName:C.string().optional(),doNotPlace:C.boolean().optional(),pinAttributes:C.record(C.string(),pjt).optional()});pr(!0);var yY=["pin1","left","pin2","right"],r5=["pin1","left","anode","pos","pin2","right","cathode","neg"],$ar=ze.or(C.enum(["2x","3x","4x"])),Ip=C.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)");pr(!0);var ZR=C.object({pins:C.array(C.union([C.number(),C.string()])),direction:C.union([C.literal("top-to-bottom"),C.literal("left-to-right"),C.literal("bottom-to-top"),C.literal("right-to-left")])}),kb=C.object({leftSize:C.number().optional().describe("@deprecated, use leftPinCount"),topSize:C.number().optional().describe("@deprecated, use topPinCount"),rightSize:C.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:C.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:C.number().optional(),rightPinCount:C.number().optional(),topPinCount:C.number().optional(),bottomPinCount:C.number().optional(),leftSide:ZR.optional(),rightSide:ZR.optional(),topSide:ZR.optional(),bottomSide:ZR.optional()}),M_e=kb;pr(!0);var n5=C.record(C.object({marginLeft:ze.optional(),marginRight:ze.optional(),marginTop:ze.optional(),marginBottom:ze.optional(),leftMargin:ze.optional(),rightMargin:ze.optional(),topMargin:ze.optional(),bottomMargin:ze.optional()}));pr(!0);var Ju=C.string().regex(/^[A-Za-z0-9_]+$/),tg=C.object({x:ze,y:ze}),Nb=C.object({edit_event_id:C.string(),in_progress:C.boolean().optional(),created_at:C.number()});pr(!0);var xjt=Nb.extend({pcb_edit_event_type:C.literal("edit_component_location").describe("deprecated"),edit_event_type:C.literal("edit_pcb_component_location"),pcb_component_id:C.string(),original_center:C.object({x:C.number(),y:C.number()}),new_center:C.object({x:C.number(),y:C.number()})});pr(!0);var fjt=Nb.extend({pcb_edit_event_type:C.literal("edit_trace_hint").describe("deprecated"),edit_event_type:C.literal("edit_pcb_trace_hint").optional(),pcb_port_id:C.string(),pcb_trace_hint_id:C.string().optional(),route:C.array(C.object({x:C.number(),y:C.number(),via:C.boolean().optional()}))});pr(!0);var hjt=Nb.extend({edit_event_type:C.literal("edit_schematic_component_location"),schematic_component_id:C.string(),original_center:C.object({x:C.number(),y:C.number()}),new_center:C.object({x:C.number(),y:C.number()})});pr(!0);var asr=Nb.extend({edit_event_type:C.literal("edit_pcb_group_location"),pcb_group_id:C.string(),original_center:C.object({x:C.number(),y:C.number()}),new_center:C.object({x:C.number(),y:C.number()})});pr(!0);var isr=Nb.extend({edit_event_type:C.literal("edit_schematic_group_location"),schematic_group_id:C.string(),original_center:C.object({x:C.number(),y:C.number()}),new_center:C.object({x:C.number(),y:C.number()})});pr(!0);var usr=C.union([xjt,fjt,hjt]);pr(!0);var mjt=C.object({selector:C.string(),relative_to:C.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:mn});pr(!0);var gjt=C.object({pcb_port_selector:C.string(),offsets:C.array(Do)});pr(!0);var Djt=C.object({selector:C.string(),relative_to:C.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:mn});pr(!0);var yjt=C.object({pcb_placements:C.array(mjt).optional(),manual_trace_hints:C.array(gjt).optional(),schematic_placements:C.array(Djt).optional()});pr(!0);var jb=C.object({layoutMode:C.enum(["grid","flex","match-adapt","relative","none"]).optional(),position:C.enum(["absolute","relative"]).optional(),grid:C.boolean().optional(),gridCols:C.number().or(C.string()).optional(),gridRows:C.number().or(C.string()).optional(),gridTemplateRows:C.string().optional(),gridTemplateColumns:C.string().optional(),gridTemplate:C.string().optional(),gridGap:C.number().or(C.string()).optional(),gridRowGap:C.number().or(C.string()).optional(),gridColumnGap:C.number().or(C.string()).optional(),flex:C.boolean().or(C.string()).optional(),flexDirection:C.enum(["row","column"]).optional(),alignItems:C.enum(["start","center","end","stretch"]).optional(),justifyContent:C.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),flexRow:C.boolean().optional(),flexColumn:C.boolean().optional(),gap:C.number().or(C.string()).optional(),pack:C.boolean().optional().describe("Pack the contents of this group using a packing strategy"),packOrderStrategy:C.enum(["largest_to_smallest","first_to_last","highest_to_lowest_pin_count"]).optional(),packPlacementStrategy:C.enum(["shortest_connection_along_outline"]).optional(),padding:xe.optional(),paddingLeft:xe.optional(),paddingRight:xe.optional(),paddingTop:xe.optional(),paddingBottom:xe.optional(),paddingX:xe.optional(),paddingY:xe.optional(),width:xe.optional(),height:xe.optional(),matchAdapt:C.boolean().optional(),matchAdaptTemplate:C.any().optional()});pr(!0);var I_e=C.object({strokeWidth:xe.optional(),dashed:C.boolean().optional(),solid:C.boolean().optional()}),bjt=C.object({serverUrl:C.string().optional(),inputFormat:C.enum(["simplified","circuit-json"]).optional(),serverMode:C.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:C.boolean().optional(),cache:C.custom(n=>!0).optional(),traceClearance:xe.optional(),groupMode:C.enum(["sequential-trace","subcircuit"]).optional(),algorithmFn:C.custom(n=>typeof n=="function"||n===void 0).optional(),preset:C.enum(["sequential-trace","subcircuit","auto","auto-local","auto-cloud"]).optional(),local:C.boolean().optional()}),O_e=C.union([bjt,C.literal("sequential-trace"),C.literal("subcircuit"),C.literal("auto"),C.literal("auto-local"),C.literal("auto-cloud")]),L_e=t5.extend({name:C.string().optional(),children:C.any().optional(),schTitle:C.string().optional(),key:C.any().optional(),...jb.shape,grid:jb.shape.grid.describe("@deprecated use pcbGrid"),flex:jb.shape.flex.describe("@deprecated use pcbFlex"),pcbGrid:C.boolean().optional(),pcbGridCols:C.number().or(C.string()).optional(),pcbGridRows:C.number().or(C.string()).optional(),pcbGridTemplateRows:C.string().optional(),pcbGridTemplateColumns:C.string().optional(),pcbGridTemplate:C.string().optional(),pcbGridGap:C.number().or(C.string()).optional(),pcbGridRowGap:C.number().or(C.string()).optional(),pcbGridColumnGap:C.number().or(C.string()).optional(),pcbFlex:C.boolean().or(C.string()).optional(),pcbFlexGap:C.number().or(C.string()).optional(),pcbFlexDirection:C.enum(["row","column"]).optional(),pcbAlignItems:C.enum(["start","center","end","stretch"]).optional(),pcbJustifyContent:C.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),pcbFlexRow:C.boolean().optional(),pcbFlexColumn:C.boolean().optional(),pcbGap:C.number().or(C.string()).optional(),pcbPack:C.boolean().optional(),schGrid:C.boolean().optional(),schGridCols:C.number().or(C.string()).optional(),schGridRows:C.number().or(C.string()).optional(),schGridTemplateRows:C.string().optional(),schGridTemplateColumns:C.string().optional(),schGridTemplate:C.string().optional(),schGridGap:C.number().or(C.string()).optional(),schGridRowGap:C.number().or(C.string()).optional(),schGridColumnGap:C.number().or(C.string()).optional(),schFlex:C.boolean().or(C.string()).optional(),schFlexGap:C.number().or(C.string()).optional(),schFlexDirection:C.enum(["row","column"]).optional(),schAlignItems:C.enum(["start","center","end","stretch"]).optional(),schJustifyContent:C.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),schFlexRow:C.boolean().optional(),schFlexColumn:C.boolean().optional(),schGap:C.number().or(C.string()).optional(),schPack:C.boolean().optional(),schMatchAdapt:C.boolean().optional(),pcbWidth:xe.optional(),pcbHeight:xe.optional(),schWidth:xe.optional(),schHeight:xe.optional(),pcbLayout:jb.optional(),schLayout:jb.optional(),cellBorder:I_e.nullable().optional(),border:I_e.nullable().optional(),schPadding:xe.optional(),schPaddingLeft:xe.optional(),schPaddingRight:xe.optional(),schPaddingTop:xe.optional(),schPaddingBottom:xe.optional(),pcbPadding:xe.optional(),pcbPaddingLeft:xe.optional(),pcbPaddingRight:xe.optional(),pcbPaddingTop:xe.optional(),pcbPaddingBottom:xe.optional()}),$_e=C.custom(n=>"findPart"in n),bY=L_e.extend({manualEdits:yjt.optional(),schAutoLayoutEnabled:C.boolean().optional(),schTraceAutoLabelEnabled:C.boolean().optional(),schMaxTraceDistance:ze.optional(),routingDisabled:C.boolean().optional(),defaultTraceWidth:xe.optional(),minTraceWidth:xe.optional(),partsEngine:$_e.optional(),pcbRouteCache:C.custom(n=>!0).optional(),autorouter:O_e.optional(),square:C.boolean().optional(),emptyArea:C.string().optional(),filledArea:C.string().optional(),width:ze.optional(),height:ze.optional(),outline:C.array(tg).optional(),outlineOffsetX:ze.optional(),outlineOffsetY:ze.optional()}),Fjt=bY.extend({subcircuit:C.literal(!0)}),z_e=C.discriminatedUnion("subcircuit",[L_e.extend({subcircuit:C.literal(!1).optional()}),Fjt]);pr(!0);pr(!0);pr(!0);var FY=bY.extend({material:C.enum(["fr4","fr1"]).default("fr4"),layers:C.union([C.literal(2),C.literal(4)]).default(2),borderRadius:ze.optional()});pr(!0);var gsr=bY.extend({padding:ze.optional(),paddingLeft:ze.optional(),paddingRight:ze.optional(),paddingTop:ze.optional(),paddingBottom:ze.optional()});pr(!0);var Ejt=C.string().or(C.array(C.string()).readonly()).or(C.array(C.string())),vjt=C.custom().pipe(C.record(C.string(),Ejt)),Cjt=C.record(Ju,Ju.or(C.array(Ju).readonly()).or(C.array(Ju)));pr(!0);var _jt=C.object({manufacturerPartNumber:C.string().optional(),supplierPartNumber:C.record(Im,C.array(C.string())).optional()}),rg=fs.extend({manufacturerPartNumber:C.string().optional(),pinLabels:Cjt.optional(),showPinAliases:C.boolean().optional(),pcbPinLabels:C.record(C.string(),C.string()).optional(),internallyConnectedPins:C.array(C.array(C.union([C.string(),C.number()]))).optional(),externallyConnectedPins:C.array(C.array(C.string())).optional(),schPinArrangement:kb.optional(),schPortArrangement:kb.optional(),pinCompatibleVariants:C.array(_jt).optional(),schPinStyle:n5.optional(),schPinSpacing:ze.optional(),schWidth:ze.optional(),schHeight:ze.optional(),noSchematicRepresentation:C.boolean().optional(),connections:vjt.optional()});pr(!0);var q_e=rg;pr(!0);var EY=C.string().or(C.array(C.string()).readonly()).or(C.array(C.string())),n1=n=>C.record(C.enum(n),EY),vY=fs.extend({manufacturerPartNumber:C.string().optional(),pinLabels:C.record(C.number().or(Ju),Ju.or(C.array(Ju))).optional(),schPinStyle:n5.optional(),schPinSpacing:ze.optional(),schWidth:ze.optional(),schHeight:ze.optional(),schDirection:C.enum(["left","right"]).optional(),schPinArrangement:M_e.optional(),schPortArrangement:kb.optional(),pcbPinLabels:C.record(C.string(),C.string()).optional(),pinCount:C.union([C.literal(2),C.literal(3)]).optional(),internallyConnectedPins:C.array(C.array(C.union([C.string(),C.number()]))).optional(),connections:C.custom().pipe(C.record(C.string(),EY)).optional()});pr(!0);var U_e=vY.extend({bridgedPins:C.array(C.array(C.string())).optional(),bridged:C.boolean().optional()});pr(!0);var Asr=fs.extend({manufacturerPartNumber:C.string().optional(),pinLabels:C.record(C.number().or(Ju),Ju.or(C.array(Ju))).optional(),schPinStyle:n5.optional(),schPinSpacing:ze.optional(),schWidth:ze.optional(),schHeight:ze.optional(),schDirection:C.enum(["left","right"]).optional(),schPortArrangement:kb.optional(),internallyConnectedPins:C.array(C.array(C.union([C.string(),C.number()]))).optional(),standard:C.enum(["usb_c","m2"]).optional()});pr(!0);var V_e=fs.extend({currentRating:C.union([C.number(),C.string()]),voltageRating:C.union([C.number(),C.string()]).optional(),schShowRatings:C.boolean().optional(),schOrientation:Ip.optional(),connections:C.record(C.string(),C.union([C.string(),C.array(C.string()).readonly(),C.array(C.string())])).optional()}),QR=C.custom().transform(n=>{if(n!==void 0)return ze.parse(n)}),G_e=C.discriminatedUnion("shape",[Ea.omit({pcbRotation:!0,layer:!0}).extend({name:C.string().optional(),connectsTo:C.string().or(C.array(C.string())).optional(),shape:C.literal("circle"),holeDiameter:ze,outerDiameter:ze,portHints:U0.optional()}),Ea.omit({pcbRotation:!0,layer:!0}).extend({name:C.string().optional(),connectsTo:C.string().or(C.array(C.string())).optional(),shape:C.literal("oval"),outerWidth:ze,outerHeight:ze,holeWidth:QR,holeHeight:QR,innerWidth:ze.optional().describe("DEPRECATED use holeWidth"),innerHeight:ze.optional().describe("DEPRECATED use holeHeight"),portHints:U0.optional()}),Ea.omit({layer:!0}).extend({name:C.string().optional(),connectsTo:C.string().or(C.array(C.string())).optional(),shape:C.literal("pill"),rectPad:C.boolean().optional(),outerWidth:ze,outerHeight:ze,holeWidth:QR,holeHeight:QR,innerWidth:ze.optional().describe("DEPRECATED use holeWidth"),innerHeight:ze.optional().describe("DEPRECATED use holeHeight"),portHints:U0.optional()}),Ea.omit({pcbRotation:!0,layer:!0}).extend({name:C.string().optional(),connectsTo:C.string().or(C.array(C.string())).optional(),shape:C.literal("circular_hole_with_rect_pad"),holeDiameter:ze,rectPadWidth:ze,rectPadHeight:ze,holeShape:C.literal("circle").optional(),padShape:C.literal("rect").optional(),portHints:U0.optional()}),Ea.omit({pcbRotation:!0,layer:!0}).extend({name:C.string().optional(),connectsTo:C.string().or(C.array(C.string())).optional(),shape:C.literal("pill_hole_with_rect_pad"),holeShape:C.literal("pill"),padShape:C.literal("rect"),holeWidth:ze,holeHeight:ze,rectPadWidth:ze,rectPadHeight:ze,portHints:U0.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));pr(!0);var Ajt=["pin1","pin2","pos","neg"],X_e=fs.extend({resistance:Ap,pullupFor:C.string().optional(),pullupTo:C.string().optional(),pulldownFor:C.string().optional(),pulldownTo:C.string().optional(),schOrientation:Ip.optional(),connections:n1(Ajt).optional()}),Y_e=yY;pr(!0);var H_e=fs.extend({maxResistance:Ap,pinVariant:C.enum(["two_pin","three_pin"]).optional()});pr(!0);var Rjt=yY,W_e=fs.extend({frequency:Nc,loadCapacitance:Ul,manufacturerPartNumber:C.string().optional(),mpn:C.string().optional(),pinVariant:C.enum(["two_pin","four_pin"]).optional(),schOrientation:Ip.optional(),connections:n1(Rjt).optional()});pr(!0);var K_e=fs.extend({frequency:Nc,loadCapacitance:Ul,pinVariant:C.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});pr(!0);var $sr=FY.extend({leftPinCount:C.number().optional(),rightPinCount:C.number().optional(),topPinCount:C.number().optional(),bottomPinCount:C.number().optional(),leftPins:C.array(C.string()).optional(),rightPins:C.array(C.string()).optional(),topPins:C.array(C.string()).optional(),bottomPins:C.array(C.string()).optional(),pinPitch:ze.optional(),innerHoles:C.boolean().optional()});pr(!0);var Sjt=["pin1","pin2","pos","neg","anode","cathode"],J_e=fs.extend({capacitance:Ul,maxVoltageRating:zs.optional(),schShowRatings:C.boolean().optional().default(!1),polarized:C.boolean().optional().default(!1),decouplingFor:C.string().optional(),decouplingTo:C.string().optional(),bypassFor:C.string().optional(),bypassTo:C.string().optional(),maxDecouplingTraceLength:C.number().optional(),schOrientation:Ip.optional(),connections:n1(Sjt).optional()}),Z_e=r5;pr(!0);var Vsr=C.object({name:C.string(),connectsTo:C.string().or(C.array(C.string())).optional()});pr(!0);var Xsr=C.object({name:C.string().optional(),pcbOnly:C.boolean().optional(),schOnly:C.boolean().optional()});pr(!0);var Bjt=C.object({pcb:C.literal(!0).optional(),xDist:ze,left:C.string(),right:C.string(),edgeToEdge:C.literal(!0).optional(),centerToCenter:C.literal(!0).optional()});pr(!0);var wjt=C.object({pcb:C.literal(!0).optional(),yDist:ze,top:C.string(),bottom:C.string(),edgeToEdge:C.literal(!0).optional(),centerToCenter:C.literal(!0).optional()});pr(!0);var Tjt=C.object({pcb:C.literal(!0).optional(),sameY:C.literal(!0).optional(),for:C.array(C.string())});pr(!0);var Pjt=C.object({pcb:C.literal(!0).optional(),sameX:C.literal(!0).optional(),for:C.array(C.string())});pr(!0);var Q_e=C.union([Bjt,wjt,Tjt,Pjt]);pr(!0);var Ijt=Ea.omit({layer:!0,pcbRotation:!0}).extend({name:C.string().optional(),shape:C.literal("rect"),width:ze,height:ze});pr(!0);var jjt=Ea.omit({layer:!0,pcbRotation:!0}).extend({name:C.string().optional(),shape:C.literal("circle"),radius:ze});pr(!0);var kjt=Ea.omit({layer:!0,pcbRotation:!0}).extend({name:C.string().optional(),shape:C.literal("polygon"),points:C.array(tg)});pr(!0);var eAe=C.discriminatedUnion("shape",[Ijt,jjt,kjt]),Njt=Ea.omit({pcbRotation:!0}).extend({name:C.string().optional(),shape:C.literal("rect"),width:ze,height:ze,portHints:U0.optional()});pr(!0);var Mjt=Ea.omit({pcbRotation:!0}).extend({name:C.string().optional(),shape:C.literal("rotated_rect"),width:ze,height:ze,ccwRotation:C.number(),portHints:U0.optional()});pr(!0);var Ojt=Ea.omit({pcbRotation:!0}).extend({name:C.string().optional(),shape:C.literal("circle"),radius:ze,portHints:U0.optional()});pr(!0);var Ljt=Ea.omit({pcbRotation:!0}).extend({name:C.string().optional(),shape:C.literal("pill"),width:ze,height:ze,radius:ze,portHints:U0.optional()});pr(!0);var $jt=Ea.omit({pcbRotation:!0}).extend({name:C.string().optional(),shape:C.literal("polygon"),points:C.array(tg),portHints:U0.optional()});pr(!0);var tAe=C.discriminatedUnion("shape",[Ojt,Njt,Mjt,Ljt,$jt]);pr(!0);var zjt=Ea.omit({pcbRotation:!0}).extend({shape:C.literal("rect"),width:ze,height:ze});pr(!0);var qjt=Ea.omit({pcbRotation:!0}).extend({shape:C.literal("circle"),radius:ze});pr(!0);var Jsr=C.union([qjt,zjt]);pr(!0);var rAe=Ea.omit({pcbRotation:!0}).extend({name:C.string().optional(),diameter:ze.optional(),radius:ze.optional()}).transform(n=>({...n,diameter:n.diameter??2*n.radius,radius:n.radius??n.diameter/2}));pr(!0);var DY=C.union([C.string(),C.custom(n=>!!n.getPortSelector)]),j_e=C.object({key:C.string().optional(),thickness:ze.optional(),schematicRouteHints:C.array(tg).optional(),pcbRouteHints:C.array(Do).optional(),pcbPathRelativeTo:C.string().optional(),pcbPath:C.array(tg).optional(),schDisplayLabel:C.string().optional(),schStroke:C.string().optional(),maxLength:ze.optional()}),nAe=C.union([j_e.extend({path:C.array(DY)}),j_e.extend({from:DY,to:DY})]),aAe=C.object({originalLayer:hn.default("top").optional()});pr(!0);var air=C.object({originalFacingDirection:C.enum(["up","down","left","right"]).default("right").optional()});pr(!0);var Ujt=C.number().or(C.string().endsWith("mAh")).transform(n=>{if(typeof n=="string"){let e=n.replace("mAh",""),a=Number.parseFloat(e);if(Number.isNaN(a))throw new Error("Invalid capacity");return a}return n}).describe("Battery capacity in mAh"),sAe=fs.extend({capacity:Ujt.optional(),voltage:zs.optional(),standard:C.enum(["AA","AAA","9V","CR2032","18650","C"]).optional(),schOrientation:Ip.optional()});pr(!0);var iAe=fs.extend({pinCount:C.number(),pitch:ze.optional(),schFacingDirection:C.enum(["up","down","left","right"]).optional(),gender:C.enum(["male","female","unpopulated"]).optional().default("male"),showSilkscreenPinLabels:C.boolean().optional(),pcbPinLabels:C.record(C.string(),C.string()).optional(),doubleRow:C.boolean().optional(),rightAngle:C.boolean().optional(),holeDiameter:ze.optional(),platedDiameter:ze.optional(),pinLabels:C.record(C.string(),Ju).or(C.array(Ju)).optional(),connections:C.custom().pipe(C.record(C.string(),EY)).optional(),facingDirection:C.enum(["left","right"]).optional(),schPinArrangement:M_e.optional(),schPinStyle:n5.optional(),schPinSpacing:ze.optional(),schWidth:ze.optional(),schHeight:ze.optional()});pr(!0);var dir=C.object({net:C.string().optional(),connection:C.string().optional(),schX:ze.optional(),schY:ze.optional(),schRotation:Ba.optional(),anchorSide:C.enum(["left","top","right","bottom"]).optional()});pr(!0);var oAe=C.object({net:C.string().optional(),connection:C.string().optional(),connectsTo:C.string().or(C.array(C.string())).optional(),schX:ze.optional(),schY:ze.optional(),schRotation:Ba.optional(),anchorSide:C.enum(["left","top","right","bottom"]).optional()});pr(!0);var uAe=rg.extend({});pr(!0);pr(!0);var Vjt=["pin1","pin2","pin3","emitter","collector","base","gate","source","drain"],cAe=fs.extend({type:C.enum(["npn","pnp","bjt","jfet","mosfet","igbt"]),connections:n1(Vjt).optional()});pr(!0);var lAe=fs.extend({channelType:C.enum(["n","p"]),mosfetMode:C.enum(["enhancement","depletion"])});pr(!0);var Gjt=yY,dAe=fs.extend({inductance:PA,maxCurrentRating:C.union([C.string(),C.number()]).optional(),schOrientation:Ip.optional(),connections:n1(Gjt).optional()});pr(!0);var Xjt=C.enum(["anode","cathode","pin1","pin2","pos","neg"]),Yjt=C.string().or(C.array(C.string()).readonly()).or(C.array(C.string())),Hjt=C.record(Xjt,Yjt),Wjt=C.enum(["standard","schottky","zener","avalanche","photo","tvs"]),pAe=fs.extend({connections:Hjt.optional(),variant:Wjt.optional().default("standard"),standard:C.boolean().optional(),schottky:C.boolean().optional(),zener:C.boolean().optional(),avalanche:C.boolean().optional(),photo:C.boolean().optional(),tvs:C.boolean().optional(),schOrientation:Ip.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:C.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),C.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}),xAe=r5;pr(!0);var fAe=fs.extend({color:C.string().optional(),wavelength:C.string().optional(),schDisplayValue:C.string().optional(),schOrientation:Ip.optional(),connections:n1(r5).optional(),laser:C.boolean().optional()}),hAe=r5,mAe=fs.extend({type:C.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:C.boolean().optional().default(!1),spst:C.boolean().optional(),spdt:C.boolean().optional(),dpst:C.boolean().optional(),dpdt:C.boolean().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});pr(!0);var gAe=Ea.extend({text:C.string(),anchorAlignment:C.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:C.enum(["tscircuit2024"]).optional(),fontSize:xe.optional(),color:C.string().optional()}),DAe=Ea.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:C.array(Do),strokeWidth:xe.optional(),color:C.string().optional()}),Rir=C.object({layer:C.string().optional(),thickness:ze.optional(),route:C.array(Do)}),yAe=t5.extend({name:C.string().optional(),fromLayer:hn,toLayer:hn,holeDiameter:ze,outerDiameter:ze,connectsTo:C.string().or(C.array(C.string())).optional()});pr(!0);var bAe=fs.extend({footprintVariant:C.enum(["pad","through_hole"]).optional(),padShape:C.enum(["rect","circle"]).optional().default("circle"),padDiameter:ze.optional(),holeDiameter:ze.optional(),width:ze.optional(),height:ze.optional()}).refine(n=>n.footprintVariant!=="through_hole"||n.holeDiameter!==void 0,{message:"holeDiameter is required for through_hole testpoints"});pr(!0);var FAe=Ea.omit({pcbRotation:!0,layer:!0}).extend({connection:C.string()});pr(!0);var EAe=C.union([Ea.omit({pcbRotation:!0}).extend({shape:C.literal("circle"),radius:ze}),Ea.extend({shape:C.literal("rect"),width:ze,height:ze})]),Kjt=Ea.omit({pcbRotation:!0}).extend({shape:C.literal("rect"),width:ze,height:ze,connectsTo:C.string().or(C.array(C.string())).optional()});pr(!0);var Jjt=Ea.omit({pcbRotation:!0}).extend({shape:C.literal("circle"),radius:ze,connectsTo:C.string().or(C.array(C.string())).optional()});pr(!0);var Zjt=Ea.omit({pcbRotation:!0}).extend({shape:C.literal("polygon"),points:C.array(tg),connectsTo:C.string().or(C.array(C.string())).optional()});pr(!0);var Nir=C.discriminatedUnion("shape",[Kjt,Jjt,Zjt]),vAe=fs.extend({voltage:zs}),Qjt=["pin1","pin2","pos","neg"],ekt=C.union([C.string(),C.number()]).transform(n=>typeof n=="string"?n.endsWith("%")?parseFloat(n.slice(0,-1))/100:parseFloat(n):n).pipe(C.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),$ir=fs.extend({voltage:zs.optional(),frequency:Nc.optional(),peakToPeakVoltage:zs.optional(),waveShape:C.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Ba.optional(),dutyCycle:ekt.optional(),connections:n1(Qjt).optional()});pr(!0);var a5=C.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),CAe=C.object({schX:ze.optional(),schY:ze.optional(),width:ze.optional(),height:ze.optional(),overlay:C.array(C.string()).optional(),padding:ze.optional(),paddingLeft:ze.optional(),paddingRight:ze.optional(),paddingTop:ze.optional(),paddingBottom:ze.optional(),title:C.string().optional(),titleAlignment:a5.default("top_left"),titleColor:C.string().optional(),titleFontSize:ze.optional(),titleInside:C.boolean().default(!1),strokeStyle:C.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."}),Xir=C.object({x1:ze,y1:ze,x2:ze,y2:ze}),tkt=C.enum(["center","left","right","top","bottom"]),_Ae=C.object({schX:ze.optional(),schY:ze.optional(),text:C.string(),fontSize:C.number().default(1),anchor:C.union([tkt.describe("legacy"),a5]).default("center"),color:C.string().default("#000000"),schRotation:Ba.default(0)}),Zir=C.object({points:C.array(mn),isFilled:C.boolean().optional().default(!1),fillColor:C.enum(["red","blue"]).optional()}),AAe=C.object({schX:ze.optional(),schY:ze.optional(),children:C.any().optional(),cellPadding:ze.optional(),borderWidth:ze.optional(),anchor:a5.optional(),fontSize:ze.optional()});pr(!0);var RAe=C.object({children:C.any().optional(),height:ze.optional()});pr(!0);var SAe=C.object({children:C.string().optional(),horizontalAlign:C.enum(["left","center","right"]).optional(),verticalAlign:C.enum(["top","middle","bottom"]).optional(),fontSize:ze.optional(),rowSpan:C.number().optional(),colSpan:C.number().optional(),width:ze.optional(),text:C.string().optional()});pr(!0);var BAe=Ea.extend({text:C.string(),anchorAlignment:a5.default("center"),font:C.enum(["tscircuit2024"]).optional(),fontSize:xe.optional(),layers:C.array(hn).optional()}),wAe=Ea.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:C.array(Do),strokeWidth:xe.optional()}),TAe=Ea.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({strokeWidth:ze,x1:ze,y1:ze,x2:ze,y2:ze}),PAe=Ea.omit({pcbRotation:!0}).extend({filled:C.boolean().default(!0).optional(),stroke:C.enum(["dashed","solid","none"]).optional(),strokeWidth:ze.optional(),width:ze,height:ze}),IAe=Ea.omit({pcbRotation:!0}).extend({isFilled:C.boolean().optional(),isOutline:C.boolean().optional(),strokeWidth:ze.optional(),radius:ze}),k_e=C.object({x:ze,y:ze,via:C.boolean().optional(),toLayer:hn.optional()}),jAe=C.object({for:C.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:C.number().optional(),offset:Do.or(k_e).optional(),offsets:C.array(Do).or(C.array(k_e)).optional(),traceWidth:C.number().optional()}),Dor=t5.extend({name:C.string(),pinNumber:C.number().optional(),aliases:C.array(C.string()).optional(),direction:njt}),rkt=C.array(C.any()).describe("Circuit JSON"),N_e=C.function().args(C.string()).returns(C.promise(C.object({footprintCircuitJson:C.array(C.any())}))).describe("A function that takes a path and returns Circuit JSON"),bor=C.object({partsEngine:$_e.optional(),autorouter:O_e.optional(),registryApiUrl:C.string().optional(),cloudAutorouterUrl:C.string().optional(),projectName:C.string().optional(),version:C.string().optional(),url:C.string().optional(),printBoardInformationToSilkscreen:C.boolean().optional(),localCacheEngine:C.any().optional(),pcbDisabled:C.boolean().optional(),schematicDisabled:C.boolean().optional(),partsEngineDisabled:C.boolean().optional(),footprintLibraryMap:C.record(C.string(),C.union([N_e,C.record(C.string(),C.union([rkt,N_e]))])).optional()});pr(!0);Xe();Yt();Hl();Xe();var LF=qr(Ic(),1);Hl();Xe();function jp(){return new CY}var CY=class n{constructor(){q(this,"index",{});q(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 a=this.index[e.id()];return a===void 0?void 0:this.array[a]}setDefault(e,a){let s=this.index[e.id()];if(s===void 0){let l=new s5(e,a());return this.index[e.id()]=this.array.length,this.array.push(l),l}else return this.array[s]}insert(e,a){let s=new s5(e,a),l=this.index[e.id()];return l===void 0?(this.index[e.id()]=this.array.length,this.array.push(s)):this.array[l]=s,s}erase(e){let a=this.index[e.id()];if(a===void 0)return;this.index[e.id()]=void 0;let s=this.array[a],l=this.array.pop();return s!==l&&(this.array[a]=l,this.index[l.first.id()]=a),s}copy(){let e=new n;for(let a=0;a<this.array.length;a++){let s=this.array[a].copy();e.array[a]=s,e.index[s.first.id()]=a}return e}},s5=class n{constructor(e,a){q(this,"first");q(this,"second");this.first=e,this.second=a}copy(){return new n(this.first,this.second)}};var a1=class{constructor(e=""){q(this,"_name");q(this,"_value",0);q(this,"_context",null);q(this,"_id",nkt++);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 Is(this,e)}minus(e){return new Is(this,typeof e=="number"?-e:[-1,e])}multiply(e){return new Is([e,this])}divide(e){return new Is([1/e,this])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},nkt=0;var Is=class n{constructor(){q(this,"_terms");q(this,"_constant");let e=akt(arguments);this._terms=e.terms,this._constant=e.constant}terms(){return this._terms}constant(){return this._constant}value(){let e=this._constant;for(let a=0,s=this._terms.size();a<s;a++){let l=this._terms.itemAt(a);e+=l.first.value()*l.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(a){return a.second+"*"+a.first.toString()}).join(" + ");return!this.isConstant()&&this._constant!==0&&(e+=" + "),e+=this._constant,e}};function akt(n){let e=0,a=()=>0,s=jp();for(let l=0,p=n.length;l<p;++l){let x=n[l];if(typeof x=="number")e+=x;else if(x instanceof a1)s.setDefault(x,a).second+=1;else if(x instanceof Is){e+=x.constant();let f=x.terms();for(let m=0,D=f.size();m<D;m++){let b=f.itemAt(m);s.setDefault(b.first,a).second+=b.second}}else if(x instanceof Array){if(x.length!==2)throw new Error("array must have length 2");let f=x[0],m=x[1];if(typeof f!="number")throw new Error("array item 0 must be a number");if(m instanceof a1)s.setDefault(m,a).second+=f;else if(m instanceof Is){e+=m.constant()*f;let D=m.terms();for(let b=0,E=D.size();b<E;b++){let A=D.itemAt(b);s.setDefault(A.first,a).second+=A.second*f}}else throw new Error("array item 1 must be a variable or expression")}else throw new Error("invalid Expression argument: "+x)}return{terms:s,constant:e}}var Oc=class Oc{static create(e,a,s,l=1){let p=0;return p+=Math.max(0,Math.min(1e3,e*l))*1e6,p+=Math.max(0,Math.min(1e3,a*l))*1e3,p+=Math.max(0,Math.min(1e3,s*l)),p}static clip(e){return Math.max(0,Math.min(Oc.required,e))}};q(Oc,"required",Oc.create(1e3,1e3,1e3)),q(Oc,"strong",Oc.create(1,0,0)),q(Oc,"medium",Oc.create(0,1,0)),q(Oc,"weak",Oc.create(0,0,1));var qs=Oc;var yo;(function(n){n[n.Le=0]="Le",n[n.Ge=1]="Ge",n[n.Eq=2]="Eq"})(yo||(yo={}));var Zu=class{constructor(e,a,s,l=qs.required){q(this,"_expression");q(this,"_operator");q(this,"_strength");q(this,"_id",skt++);this._operator=a,this._strength=qs.clip(l),s===void 0&&e instanceof Is?this._expression=e:this._expression=e.minus(s)}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()+")"}},skt=0;var o5=class{constructor(){q(this,"maxIterations",1e3);q(this,"_cnMap",ikt());q(this,"_rowMap",okt());q(this,"_varMap",ukt());q(this,"_editMap",ckt());q(this,"_infeasibleRows",[]);q(this,"_objective",new c5);q(this,"_artificial",null);q(this,"_idTick",0)}createConstraint(e,a,s,l=qs.required){let p=new Zu(e,a,s,l);return this.addConstraint(p),p}addConstraint(e){if(this._cnMap.find(e)!==void 0)throw new Error("duplicate constraint");let s=this._createRow(e),l=s.row,p=s.tag,x=this._chooseSubject(l,p);if(x.type()===Qn.Invalid&&l.allDummies())if(i5(l.constant()))x=p.marker;else throw new Error("unsatisfiable constraint");if(x.type()===Qn.Invalid){if(!this._addWithArtificialVariable(l))throw new Error("unsatisfiable constraint")}else l.solveFor(x),this._substitute(x,l),this._rowMap.insert(x,l);this._cnMap.insert(e,p),this._optimize(this._objective)}removeConstraint(e){let a=this._cnMap.erase(e);if(a===void 0)throw new Error("unknown constraint");this._removeConstraintEffects(e,a.second);let s=a.second.marker,l=this._rowMap.erase(s);if(l===void 0){let p=this._getMarkerLeavingSymbol(s);if(p.type()===Qn.Invalid)throw new Error("failed to find leaving row");l=this._rowMap.erase(p),l.second.solveForEx(p,s),this._substitute(s,l.second)}this._optimize(this._objective)}hasConstraint(e){return this._cnMap.contains(e)}getConstraints(){return this._cnMap.array.map(({first:e})=>e)}addEditVariable(e,a){if(this._editMap.find(e)!==void 0)throw new Error("duplicate edit variable");if(a=qs.clip(a),a===qs.required)throw new Error("bad required strength");let l=new Is(e),p=new Zu(l,yo.Eq,void 0,a);this.addConstraint(p);let f={tag:this._cnMap.find(p).second,constraint:p,constant:0};this._editMap.insert(e,f)}removeEditVariable(e){let a=this._editMap.erase(e);if(a===void 0)throw new Error("unknown edit variable");this.removeConstraint(a.second.constraint)}hasEditVariable(e){return this._editMap.contains(e)}suggestValue(e,a){let s=this._editMap.find(e);if(s===void 0)throw new Error("unknown edit variable");let l=this._rowMap,p=s.second,x=a-p.constant;p.constant=a;let f=p.tag.marker,m=l.find(f);if(m!==void 0){m.second.add(-x)<0&&this._infeasibleRows.push(f),this._dualOptimize();return}let D=p.tag.other;if(m=l.find(D),m!==void 0){m.second.add(x)<0&&this._infeasibleRows.push(D),this._dualOptimize();return}for(let b=0,E=l.size();b<E;++b){let A=l.itemAt(b),B=A.second,w=B.coefficientFor(f);w!==0&&B.add(x*w)<0&&A.first.type()!==Qn.External&&this._infeasibleRows.push(A.first)}this._dualOptimize()}updateVariables(){let e=this._varMap,a=this._rowMap;for(let s=0,l=e.size();s<l;++s){let p=e.itemAt(s),x=a.find(p.second);x!==void 0?p.first.setValue(x.second.constant()):p.first.setValue(0)}}_getVarSymbol(e){let a=()=>this._makeSymbol(Qn.External);return this._varMap.setDefault(e,a).second}_createRow(e){let a=e.expression(),s=new c5(a.constant()),l=a.terms();for(let m=0,D=l.size();m<D;++m){let b=l.itemAt(m);if(!i5(b.second)){let E=this._getVarSymbol(b.first),A=this._rowMap.find(E);A!==void 0?s.insertRow(A.second,b.second):s.insertSymbol(E,b.second)}}let p=this._objective,x=e.strength(),f={marker:kp,other:kp};switch(e.op()){case yo.Le:case yo.Ge:{let m=e.op()===yo.Le?1:-1,D=this._makeSymbol(Qn.Slack);if(f.marker=D,s.insertSymbol(D,m),x<qs.required){let b=this._makeSymbol(Qn.Error);f.other=b,s.insertSymbol(b,-m),p.insertSymbol(b,x)}break}case yo.Eq:{if(x<qs.required){let m=this._makeSymbol(Qn.Error),D=this._makeSymbol(Qn.Error);f.marker=m,f.other=D,s.insertSymbol(m,-1),s.insertSymbol(D,1),p.insertSymbol(m,x),p.insertSymbol(D,x)}else{let m=this._makeSymbol(Qn.Dummy);f.marker=m,s.insertSymbol(m)}break}}return s.constant()<0&&s.reverseSign(),{row:s,tag:f}}_chooseSubject(e,a){let s=e.cells();for(let p=0,x=s.size();p<x;++p){let f=s.itemAt(p);if(f.first.type()===Qn.External)return f.first}let l=a.marker.type();return(l===Qn.Slack||l===Qn.Error)&&e.coefficientFor(a.marker)<0?a.marker:(l=a.other.type(),(l===Qn.Slack||l===Qn.Error)&&e.coefficientFor(a.other)<0?a.other:kp)}_addWithArtificialVariable(e){let a=this._makeSymbol(Qn.Slack);this._rowMap.insert(a,e.copy()),this._artificial=e.copy(),this._optimize(this._artificial);let s=i5(this._artificial.constant());this._artificial=null;let l=this._rowMap.erase(a);if(l!==void 0){let x=l.second;if(x.isConstant())return s;let f=this._anyPivotableSymbol(x);if(f.type()===Qn.Invalid)return!1;x.solveForEx(a,f),this._substitute(f,x),this._rowMap.insert(f,x)}let p=this._rowMap;for(let x=0,f=p.size();x<f;++x)p.itemAt(x).second.removeSymbol(a);return this._objective.removeSymbol(a),s}_substitute(e,a){let s=this._rowMap;for(let l=0,p=s.size();l<p;++l){let x=s.itemAt(l);x.second.substitute(e,a),x.second.constant()<0&&x.first.type()!==Qn.External&&this._infeasibleRows.push(x.first)}this._objective.substitute(e,a),this._artificial&&this._artificial.substitute(e,a)}_optimize(e){let a=0;for(;a<this.maxIterations;){let s=this._getEnteringSymbol(e);if(s.type()===Qn.Invalid)return;let l=this._getLeavingSymbol(s);if(l.type()===Qn.Invalid)throw new Error("the objective is unbounded");let p=this._rowMap.erase(l).second;p.solveForEx(l,s),this._substitute(s,p),this._rowMap.insert(s,p),a++}throw new Error("solver iterations exceeded")}_dualOptimize(){let e=this._rowMap,a=this._infeasibleRows;for(;a.length!==0;){let s=a.pop(),l=e.find(s);if(l!==void 0&&l.second.constant()<0){let p=this._getDualEnteringSymbol(l.second);if(p.type()===Qn.Invalid)throw new Error("dual optimize failed");let x=l.second;e.erase(s),x.solveForEx(s,p),this._substitute(p,x),e.insert(p,x)}}}_getEnteringSymbol(e){let a=e.cells();for(let s=0,l=a.size();s<l;++s){let p=a.itemAt(s),x=p.first;if(p.second<0&&x.type()!==Qn.Dummy)return x}return kp}_getDualEnteringSymbol(e){let a=Number.MAX_VALUE,s=kp,l=e.cells();for(let p=0,x=l.size();p<x;++p){let f=l.itemAt(p),m=f.first,D=f.second;if(D>0&&m.type()!==Qn.Dummy){let E=this._objective.coefficientFor(m)/D;E<a&&(a=E,s=m)}}return s}_getLeavingSymbol(e){let a=Number.MAX_VALUE,s=kp,l=this._rowMap;for(let p=0,x=l.size();p<x;++p){let f=l.itemAt(p),m=f.first;if(m.type()!==Qn.External){let D=f.second,b=D.coefficientFor(e);if(b<0){let E=-D.constant()/b;E<a&&(a=E,s=m)}}}return s}_getMarkerLeavingSymbol(e){let a=Number.MAX_VALUE,s=a,l=a,p=kp,x=p,f=p,m=p,D=this._rowMap;for(let b=0,E=D.size();b<E;++b){let A=D.itemAt(b),B=A.second,w=B.coefficientFor(e);if(w===0)continue;let P=A.first;if(P.type()===Qn.External)m=P;else if(w<0){let N=-B.constant()/w;N<s&&(s=N,x=P)}else{let N=B.constant()/w;N<l&&(l=N,f=P)}}return x!==p?x:f!==p?f:m}_removeConstraintEffects(e,a){a.marker.type()===Qn.Error&&this._removeMarkerEffects(a.marker,e.strength()),a.other.type()===Qn.Error&&this._removeMarkerEffects(a.other,e.strength())}_removeMarkerEffects(e,a){let s=this._rowMap.find(e);s!==void 0?this._objective.insertRow(s.second,-a):this._objective.insertSymbol(e,-a)}_anyPivotableSymbol(e){let a=e.cells();for(let s=0,l=a.size();s<l;++s){let p=a.itemAt(s),x=p.first.type();if(x===Qn.Slack||x===Qn.Error)return p.first}return kp}_makeSymbol(e){return new u5(e,this._idTick++)}};function i5(n){let e=1e-8;return n<0?-n<e:n<e}function ikt(){return jp()}function okt(){return jp()}function ukt(){return jp()}function ckt(){return jp()}var Qn;(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"})(Qn||(Qn={}));var u5=class{constructor(e,a){q(this,"_id");q(this,"_type");this._id=a,this._type=e}id(){return this._id}type(){return this._type}},kp=new u5(Qn.Invalid,-1),c5=class n{constructor(e=0){q(this,"_cellMap",jp());q(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 a=0,s=e.size();a<s;++a)if(e.itemAt(a).first.type()!==Qn.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,a=1){let s=this._cellMap.setDefault(e,()=>0);i5(s.second+=a)&&this._cellMap.erase(e)}insertRow(e,a=1){this._constant+=e._constant*a;let s=e._cellMap;for(let l=0,p=s.size();l<p;++l){let x=s.itemAt(l);this.insertSymbol(x.first,x.second*a)}}removeSymbol(e){this._cellMap.erase(e)}reverseSign(){this._constant=-this._constant;let e=this._cellMap;for(let a=0,s=e.size();a<s;++a){let l=e.itemAt(a);l.second=-l.second}}solveFor(e){let a=this._cellMap,l=-1/a.erase(e).second;this._constant*=l;for(let p=0,x=a.size();p<x;++p)a.itemAt(p).second*=l}solveForEx(e,a){this.insertSymbol(e,-1),this.solveFor(a)}coefficientFor(e){let a=this._cellMap.find(e);return a!==void 0?a.second:0}substitute(e,a){let s=this._cellMap.erase(e);s!==void 0&&this.insertRow(a,s.second)}};var ABe=qr(vs(),1);Yt();Jo();var _Y={};bm(_Y,{boundsAreaOverlap:()=>VAe,boundsDistance:()=>GAe,clamp:()=>xs,computeDistanceBetweenBoxes:()=>eg,distSq:()=>$Ae,distance:()=>Ri,doBoundsOverlap:()=>Ob,doSegmentsIntersect:()=>Zo,doesLineIntersectLine:()=>Np,doesSegmentIntersectRect:()=>NAe,findNearestPointsBetweenBoxSets:()=>Ib,getBoundingBox:()=>Ql,getSegmentIntersection:()=>kAe,getUnitVectorFromDirection:()=>x5,getUnitVectorFromPointAToB:()=>p5,grid:()=>XAe,midpoint:()=>LAe,onSegment:()=>ag,orientation:()=>ng,pointToBoundsDistance:()=>OAe,pointToBoxDistance:()=>MAe,pointToSegmentClosestPoint:()=>UAe,pointToSegmentDistance:()=>Us,range:()=>zAe,segmentToBoundsMinDistance:()=>Mb,segmentToBoxMinDistance:()=>qAe,segmentToCircleMinDistance:()=>d5,segmentToSegmentMinDistance:()=>l5});function Np([n,e],[a,s],{lineThickness:l=0}={}){return l===0?Zo(n,e,a,s):dkt(n,e,a,s)<=l}function Zo(n,e,a,s){let l=ng(n,e,a),p=ng(n,e,s),x=ng(a,s,n),f=ng(a,s,e);return!!(l!==p&&x!==f||l===0&&ag(n,a,e)||p===0&&ag(n,s,e)||x===0&&ag(a,n,s)||f===0&&ag(a,e,s))}function ng(n,e,a){let s=(e.y-n.y)*(a.x-e.x)-(e.x-n.x)*(a.y-e.y);return s===0?0:s>0?1:2}function ag(n,e,a){return e.x<=Math.max(n.x,a.x)&&e.x>=Math.min(n.x,a.x)&&e.y<=Math.max(n.y,a.y)&&e.y>=Math.min(n.y,a.y)}function dkt(n,e,a,s){if(n.x===e.x&&n.y===e.y)return Us(n,a,s);if(a.x===s.x&&a.y===s.y)return Us(a,n,e);if(Zo(n,e,a,s))return 0;let l=[Us(n,a,s),Us(e,a,s),Us(a,n,e),Us(s,n,e)];return Math.min(...l)}function Us(n,e,a){let s=(a.x-e.x)**2+(a.y-e.y)**2;if(s===0)return Ri(n,e);let l=((n.x-e.x)*(a.x-e.x)+(n.y-e.y)*(a.y-e.y))/s;l=Math.max(0,Math.min(1,l));let p={x:e.x+l*(a.x-e.x),y:e.y+l*(a.y-e.y)};return Ri(n,p)}function Ri(n,e){let a=n.x-e.x,s=n.y-e.y;return Math.sqrt(a*a+s*s)}function kAe(n,e,a,s){let l=e.x-n.x,p=e.y-n.y,x=s.x-a.x,f=s.y-a.y,m=n.x-a.x,D=n.y-a.y,b=l*f-p*x;if(Math.abs(b)<1e-10)return null;let E=(D*x-m*f)/b,A=(l*D-p*m)/b,B=1e-9;if(E>=-B&&E<=1+B&&A>=-B&&A<=1+B){let w=n.x+E*l,P=n.y+E*p;return{x:w,y:P}}return null}function NAe(n,e,a){let s=m=>m.x>=a.minX&&m.x<=a.maxX&&m.y>=a.minY&&m.y<=a.maxY;if(s(n)||s(e))return!0;let l={x:a.minX,y:a.minY},p={x:a.maxX,y:a.minY},x={x:a.minX,y:a.maxY},f={x:a.maxX,y:a.maxY};return Zo(n,e,l,p)||Zo(n,e,p,f)||Zo(n,e,f,x)||Zo(n,e,x,l)}function MAe(n,e){let a=e.width/2,s=e.height/2,l=e.center.x-a,p=e.center.x+a,x=e.center.y-s,f=e.center.y+s;if(n.x>=l&&n.x<=p&&n.y>=x&&n.y<=f)return 0;let m=xs(n.x,l,p),D=xs(n.y,x,f);return Ri(n,{x:m,y:D})}function OAe(n,e){if(n.x>=e.minX&&n.x<=e.maxX&&n.y>=e.minY&&n.y<=e.maxY)return 0;let a=xs(n.x,e.minX,e.maxX),s=xs(n.y,e.minY,e.maxY);return Ri(n,{x:a,y:s})}function LAe(n,e){return{x:(n.x+e.x)/2,y:(n.y+e.y)/2}}function $Ae(n,e){let a=n.x-e.x,s=n.y-e.y;return a*a+s*s}function zAe(n,e,a=1){if(a===0)throw new Error("step cannot be 0");let s,l;e===void 0?(s=0,l=n):(s=n,l=e);let p=[];if(a>0)for(let x=s;x<l;x+=a)p.push(x);else for(let x=s;x>l;x+=a)p.push(x);return p}function l5(n,e,a,s){if(n.x===e.x&&n.y===e.y)return Us(n,a,s);if(a.x===s.x&&a.y===s.y)return Us(a,n,e);if(Zo(n,e,a,s))return 0;let l=[Us(n,a,s),Us(e,a,s),Us(a,n,e),Us(s,n,e)];return Math.min(...l)}function Mb(n,e,a){let s={x:a.minX,y:a.minY},l={x:a.maxX,y:a.minY},p={x:a.minX,y:a.maxY},x={x:a.maxX,y:a.maxY};if(Zo(n,e,s,l)||Zo(n,e,l,x)||Zo(n,e,x,p)||Zo(n,e,p,s)||n.x>=a.minX&&n.x<=a.maxX&&n.y>=a.minY&&n.y<=a.maxY&&e.x>=a.minX&&e.x<=a.maxX&&e.y>=a.minY&&e.y<=a.maxY)return 0;let f=[Us(s,n,e),Us(l,n,e),Us(p,n,e),Us(x,n,e)];if(n.x>=a.minX&&n.x<=a.maxX&&n.y>=a.minY&&n.y<=a.maxY||e.x>=a.minX&&e.x<=a.maxX&&e.y>=a.minY&&e.y<=a.maxY)return 0;if(n.x<a.minX||n.x>a.maxX||n.y<a.minY||n.y>a.maxY){let m=xs(n.x,a.minX,a.maxX),D=xs(n.y,a.minY,a.maxY);f.push(Ri(n,{x:m,y:D}))}if(e.x<a.minX||e.x>a.maxX||e.y<a.minY||e.y>a.maxY){let m=xs(e.x,a.minX,a.maxX),D=xs(e.y,a.minY,a.maxY);f.push(Ri(e,{x:m,y:D}))}return Math.min(...f)}function qAe(n,e,a){let s=a.width/2,l=a.height/2,p={minX:a.center.x-s,maxX:a.center.x+s,minY:a.center.y-l,maxY:a.center.y+l};return Mb(n,e,p)}function d5(n,e,a){let s={x:a.x,y:a.y};if(n.x===e.x&&n.y===e.y)return Math.max(0,Ri(n,s)-a.radius);let l={x:e.x-n.x,y:e.y-n.y},p={x:s.x-n.x,y:s.y-n.y},x=l.x*l.x+l.y*l.y,f=Math.max(0,Math.min(1,(l.x*p.x+l.y*p.y)/x)),m={x:n.x+f*l.x,y:n.y+f*l.y},D=Ri(m,s);return Math.max(0,D-a.radius)}function UAe(n,e,a){let s=a.x-e.x,l=a.y-e.y,p=s*s+l*l;if(p===0)return{x:e.x,y:e.y};let x=((n.x-e.x)*s+(n.y-e.y)*l)/p;return x=Math.max(0,Math.min(1,x)),{x:e.x+x*s,y:e.y+x*l}}var VAe=(n,e)=>{let a=Math.max(0,Math.min(n.maxX,e.maxX)-Math.max(n.minX,e.minX)),s=Math.max(0,Math.min(n.maxY,e.maxY)-Math.max(n.minY,e.minY));return a*s};var GAe=(n,e)=>{let a=n.maxX<e.minX?e.minX-n.maxX:e.maxX<n.minX?n.minX-e.maxX:0,s=n.maxY<e.minY?e.minY-n.maxY:e.maxY<n.minY?n.minY-e.maxY:0;return Math.sqrt(a*a+s*s)};var Ob=(n,e)=>!(n.maxX<e.minX||e.maxX<n.minX||n.maxY<e.minY||e.maxY<n.minY);var p5=(n,e)=>{let a={x:e.x-n.x,y:e.y-n.y},s=Math.sqrt(a.x**2+a.y**2);return{x:a.x/s,y:a.y/s}},x5=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 XAe({rows:n,cols:e,xSpacing:a,ySpacing:s,width:l,height:p,offsetX:x=0,offsetY:f=0,yDirection:m="cartesian",centered:D=!0}){let b=a??1,E=s??1,A=l??e*b,B=p??n*E,w=D?-A/2:0,P=D?-B/2:0,N=l?l/e:b,O=p?p/n:E,$=[];for(let ee=0;ee<n;ee++)for(let X=0;X<e;X++){let te=ee*e+X,L=x+w+X*N+N/2,K=f+ee*O+O/2,U=m==="cartesian"?f+P+(n-1-ee)*O+O/2:f+P+ee*O+O/2;$.push({index:te,center:{x:L,y:U},topLeft:{x:L-N/2,y:U+O/2},bottomRight:{x:L+N/2,y:U-O/2},row:ee,col:X})}return $}Yt();var pkt=(n,e,a)=>{let s=[{x:n.x,y:n.y}],l=(n.x+e.x)/2,p=(n.y+e.y)/2,x={x:e.x,y:e.y};switch(e.facingDirection){case"x+":x.x+=a;break;case"x-":x.x-=a;break;case"y+":x.y+=a;break;case"y-":x.y-=a;break}let f=n.facingDirection??"none",m=e.facingDirection??"none",D=A=>{let B=s[s.length-1];(B.x!==A.x||B.y!==A.y)&&s.push(A)},b=Math.abs(n.y-e.y)<=Math.max(1e-6,a*.1),E=Math.abs(n.x-e.x)<=Math.max(1e-6,a*.1);if(f==="none"&&m==="none")D({x:l,y:n.y}),D({x:l,y:e.y});else if(f==="x+"&&m==="y+")n.x>e.x&&n.y<e.y?(D({x:n.x+a,y:n.y}),D({x:n.x+a,y:e.y+a}),D({x:e.x,y:e.y+a})):!E&&!b&&n.x<e.x&&n.y>e.y?D({x:e.x,y:n.y}):E?(D({x:n.x+a,y:n.y}),D({x:n.x+a,y:e.y+a}),D({x:e.x,y:e.y+a})):n.x<e.x?(D({x:l,y:n.y}),D({x:l,y:x.y}),D({x:e.x,y:x.y})):n.y<=e.y+a?(D({x:n.x+a,y:n.y}),D({x:n.x+a,y:n.y+a}),D({x:e.x,y:n.y+a}),D({x:e.x,y:e.y})):(D({x:n.x+a,y:n.y}),D({x:n.x+a,y:(n.y+e.y)/2}),D({x:e.x,y:(n.y+e.y)/2}));else if(f==="x+"&&m==="x+"&&!b){let A=Math.max(n.x+a,x.x);D({x:A,y:n.y}),D({x:A,y:e.y})}else if(f==="x+"&&m==="x+"&&b)D({x:n.x+a,y:n.y}),D({x:n.x+a,y:n.y+a}),D({x:e.x+a,y:n.y+a}),D({x:e.x+a,y:e.y});else if(f==="x+"&&m==="y-")if(E&&n.y<=e.y)D({x:n.x+a,y:n.y}),D({x:n.x+a,y:p}),D({x:e.x,y:p});else if(E&&n.y>e.y)D({x:n.x+a,y:n.y}),D({x:n.x+a,y:e.y-a}),D({x:e.x,y:e.y-a});else if(n.x<e.x&&n.y<e.y)D({x:e.x,y:n.y});else if(n.x>e.x&&n.y<e.y){let A=n.x+a;D({x:A,y:n.y}),D({x:A,y:p}),D({x:e.x,y:p})}else if(n.x>e.x&&n.y>e.y){let A=n.x+a;D({x:A,y:n.y}),D({x:A,y:x.y}),D({x:e.x,y:x.y})}else n.y===e.y?(D({x:n.x+a,y:n.y}),D({x:n.x+a,y:n.y-a}),D({x:e.x,y:n.y-a})):(D({x:l,y:n.y}),D({x:l,y:x.y}),D({x:e.x,y:x.y}));else if(f==="x+"&&m==="x-"&&n.x+a>=e.x-a&&!b){let A=n.x+a;D({x:A,y:n.y}),D({x:A,y:p}),D({x:x.x,y:p}),D({x:x.x,y:x.y})}else f==="x+"&&m==="x-"&&b&&e.x>n.x||(f==="x+"&&m==="x-"&&b?(D({x:n.x+a,y:n.y}),D({x:n.x+a,y:n.y+a}),D({x:e.x-a,y:n.y+a}),D({x:e.x-a,y:n.y})):(f==="x+"&&D({x:n.x+a,y:n.y}),D({x:l,y:s[s.length-1].y}),D({x:l,y:x.y}),D({x:x.x,y:x.y})));return D({x:e.x,y:e.y}),s},sg=(n,e,a={})=>{let s=n,l=e,p=!1;(s.x>l.x||s.x===l.x&&s.y>l.y)&&(p=!0,[s,l]=[l,s]);let x=s.facingDirection==="x-",f=s.facingDirection==="y-",m=$=>{let ee=x?s.x-($.x-s.x):$.x,X=f?s.y-($.y-s.y):$.y,te=$.facingDirection;return x&&(te==="x+"?te="x-":te==="x-"&&(te="x+")),f&&(te==="y+"?te="y-":te==="y-"&&(te="y+")),{x:ee,y:X,facingDirection:te}},D=($,ee)=>{let X=$.x-ee.x,te=$.y-ee.y,L=ee.x+te,K=ee.y-X,U=$.facingDirection;switch(U){case"x+":U="y-";break;case"y-":U="x-";break;case"x-":U="y+";break;case"y+":U="x+";break}return{x:L,y:K,facingDirection:U}},b=($,ee)=>{let X=$.x-ee.x,te=$.y-ee.y;return{x:ee.x-te,y:ee.y+X}},E=x||f?m(s):s,A=x||f?m(l):l,B=E,w=A,P=!1;E.facingDirection==="y+"&&(P=!0,B={...E,facingDirection:"x+"},w=D(A,E));let N=a?.overshoot??.1*Math.max(Math.abs(B.x-w.x),Math.abs(B.y-w.y)),O=pkt(B,w,N);return P&&(O=O.map($=>b($,B))),(x||f)&&(O=O.map(({x:$,y:ee})=>({x:x?s.x-($-s.x):$,y:f?s.y-(ee-s.y):ee}))),p?O.reverse():O};var YAe={name:"@tscircuit/capacity-autorouter",main:"./dist/index.js",version:"0.0.107",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"},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","@tscircuit/checks":"^0.0.36","@tscircuit/circuit-json-util":"^0.0.46","@tscircuit/core":"^0.0.337","@tscircuit/math-utils":"^0.0.18","@types/bun":"^1.2.16","@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","bun-match-svg":"^0.0.9","circuit-json-to-connectivity-map":"^0.0.19","circuit-to-svg":"^0.0.110",clsx:"^2.1.1",flatbush:"^4.4.0","graphics-debug":"^0.0.44",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","use-mouse-matrix-transform":"^1.3.0",vite:"^6.0.11","vite-tsconfig-paths":"^5.1.4"},peerDependencies:{typescript:"^5.7.3"},dependencies:{"fast-json-stable-stringify":"^2.1.0","object-hash":"^3.0.0"}};Yt();Jo();ea();var GW=qr(Ic(),1);var Z4e=qr(BY(),1),t6e=qr(BY(),1);var w5=(...n)=>{let e={points:[],lines:[],circles:[],rects:[]};return n.forEach((a,s)=>{a&&(a.lines&&(e.lines=[...e.lines||[],...a.lines.map(l=>({...l,step:s}))]),a.points&&(e.points=[...e.points||[],...a.points.map(l=>({...l,step:s}))]),a.circles&&(e.circles=[...e.circles||[],...a.circles.map(l=>({...l,step:s}))]),a.rects&&(e.rects=[...e.rects||[],...a.rects.map(l=>({...l,step:s}))]))}),e},Aa=class{constructor(){q(this,"MAX_ITERATIONS",1e3);q(this,"solved",!1);q(this,"failed",!1);q(this,"iterations",0);q(this,"progress",0);q(this,"error",null);q(this,"activeSubSolver");q(this,"failedSubSolvers");q(this,"timeToSolve");q(this,"stats",{});q(this,"cacheHit");q(this,"cacheKey");q(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`,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 eu(){return eu=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var a=arguments[e];for(var s in a)({}).hasOwnProperty.call(a,s)&&(n[s]=a[s])}return n},eu.apply(null,arguments)}function j5(n,e){return(j5=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(a,s){return a.__proto__=s,a})(n,e)}function M4e(n){return(M4e=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(n)}function O4e(){try{var n=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(O4e=function(){return!!n})()}function zY(n){var e=typeof Map=="function"?new Map:void 0;return zY=function(a){if(a===null||!(function(l){try{return Function.toString.call(l).indexOf("[native code]")!==-1}catch{return typeof l=="function"}})(a))return a;if(typeof a!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(a))return e.get(a);e.set(a,s)}function s(){return(function(l,p,x){if(O4e())return Reflect.construct.apply(null,arguments);var f=[null];f.push.apply(f,p);var m=new(l.bind.apply(l,f));return x&&j5(m,x.prototype),m})(a,arguments,M4e(this).constructor)}return s.prototype=Object.create(a.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),j5(s,a)},zY(n)}var Qo=(function(n){var e,a;function s(l){var p;if(1)p=n.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+l+" for more information.")||this;else for(var x,f,m;m<x;m++);return(function(D){if(D===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return D})(p)}return a=n,(e=s).prototype=Object.create(a.prototype),e.prototype.constructor=e,j5(e,a),s})(zY(Error));function u4e(n,e){return n.substr(-e.length)===e}var Ckt=/^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;function c4e(n){return typeof n!="string"?n:n.match(Ckt)?parseFloat(n):n}var l4e=function(n){return function(e,a){a===void 0&&(a="16px");var s=e,l=a;if(typeof e=="string"){if(!u4e(e,"px"))throw new Qo(69,n,e);s=c4e(e)}if(typeof a=="string"){if(!u4e(a,"px"))throw new Qo(70,n,a);l=c4e(a)}if(typeof s=="string")throw new Qo(71,e,n);if(typeof l=="string")throw new Qo(72,a,n);return""+s/l+n}};l4e("em"),l4e("rem");function wY(n){return Math.round(255*n)}function _kt(n,e,a){return wY(n)+","+wY(e)+","+wY(a)}function Wb(n,e,a,s){if(s===void 0&&(s=_kt),e===0)return s(a,a,a);var l=(n%360+360)%360/60,p=(1-Math.abs(2*a-1))*e,x=p*(1-Math.abs(l%2-1)),f=0,m=0,D=0;l>=0&&l<1?(f=p,m=x):l>=1&&l<2?(f=x,m=p):l>=2&&l<3?(m=p,D=x):l>=3&&l<4?(m=x,D=p):l>=4&&l<5?(f=x,D=p):l>=5&&l<6&&(f=p,D=x);var b=a-p/2;return s(f+b,m+b,D+b)}var d4e={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"},Akt=/^#[a-fA-F0-9]{6}$/,Rkt=/^#[a-fA-F0-9]{8}$/,Skt=/^#[a-fA-F0-9]{3}$/,Bkt=/^#[a-fA-F0-9]{4}$/,TY=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,wkt=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,Tkt=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,Pkt=/^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 dg(n){if(typeof n!="string")throw new Qo(3);var e=(function(A){if(typeof A!="string")return A;var B=A.toLowerCase();return d4e[B]?"#"+d4e[B]:A})(n);if(e.match(Akt))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(Rkt)){var a=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:a}}if(e.match(Skt))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(Bkt)){var s=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:s}}var l=TY.exec(e);if(l)return{red:parseInt(""+l[1],10),green:parseInt(""+l[2],10),blue:parseInt(""+l[3],10)};var p=wkt.exec(e.substring(0,50));if(p)return{red:parseInt(""+p[1],10),green:parseInt(""+p[2],10),blue:parseInt(""+p[3],10),alpha:parseFloat(""+p[4])>1?parseFloat(""+p[4])/100:parseFloat(""+p[4])};var x=Tkt.exec(e);if(x){var f="rgb("+Wb(parseInt(""+x[1],10),parseInt(""+x[2],10)/100,parseInt(""+x[3],10)/100)+")",m=TY.exec(f);if(!m)throw new Qo(4,e,f);return{red:parseInt(""+m[1],10),green:parseInt(""+m[2],10),blue:parseInt(""+m[3],10)}}var D=Pkt.exec(e.substring(0,50));if(D){var b="rgb("+Wb(parseInt(""+D[1],10),parseInt(""+D[2],10)/100,parseInt(""+D[3],10)/100)+")",E=TY.exec(b);if(!E)throw new Qo(4,e,b);return{red:parseInt(""+E[1],10),green:parseInt(""+E[2],10),blue:parseInt(""+E[3],10),alpha:parseFloat(""+D[4])>1?parseFloat(""+D[4])/100:parseFloat(""+D[4])}}throw new Qo(5)}function Op(n){return(function(e){var a,s=e.red/255,l=e.green/255,p=e.blue/255,x=Math.max(s,l,p),f=Math.min(s,l,p),m=(x+f)/2;if(x===f)return e.alpha!==void 0?{hue:0,saturation:0,lightness:m,alpha:e.alpha}:{hue:0,saturation:0,lightness:m};var D=x-f,b=m>.5?D/(2-x-f):D/(x+f);switch(x){case s:a=(l-p)/D+(l<p?6:0);break;case l:a=(p-s)/D+2;break;default:a=(s-l)/D+4}return a*=60,e.alpha!==void 0?{hue:a,saturation:b,lightness:m,alpha:e.alpha}:{hue:a,saturation:b,lightness:m}})(dg(n))}var qY=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 i1(n){var e=n.toString(16);return e.length===1?"0"+e:e}function PY(n){return i1(Math.round(255*n))}function Ikt(n,e,a){return qY("#"+PY(n)+PY(e)+PY(a))}function D5(n,e,a){return Wb(n,e,a,Ikt)}function UY(n,e,a){if(typeof n=="number"&&typeof e=="number"&&typeof a=="number")return qY("#"+i1(n)+i1(e)+i1(a));if(typeof n=="object"&&e===void 0&&a===void 0)return qY("#"+i1(n.red)+i1(n.green)+i1(n.blue));throw new Qo(6)}function L5(n,e,a,s){if(typeof n=="string"&&typeof e=="number"){var l=dg(n);return"rgba("+l.red+","+l.green+","+l.blue+","+e+")"}if(typeof n=="number"&&typeof e=="number"&&typeof a=="number"&&typeof s=="number")return s>=1?UY(n,e,a):"rgba("+n+","+e+","+a+","+s+")";if(typeof n=="object"&&e===void 0&&a===void 0&&s===void 0)return n.alpha>=1?UY(n.red,n.green,n.blue):"rgba("+n.red+","+n.green+","+n.blue+","+n.alpha+")";throw new Qo(7)}function Lp(n){if(typeof n!="object")throw new Qo(8);if((function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&typeof e.alpha=="number"})(n))return L5(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 UY(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,a,s,l){if(typeof e=="number"&&typeof a=="number"&&typeof s=="number"&&typeof l=="number")return l>=1?D5(e,a,s):"rgba("+Wb(e,a,s)+","+l+")";if(typeof e=="object"&&a===void 0&&s===void 0&&l===void 0)return e.alpha>=1?D5(e.hue,e.saturation,e.lightness):"rgba("+Wb(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new Qo(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,a,s){if(typeof e=="number"&&typeof a=="number"&&typeof s=="number")return D5(e,a,s);if(typeof e=="object"&&a===void 0&&s===void 0)return D5(e.hue,e.saturation,e.lightness);throw new Qo(1)})(n);throw new Qo(8)}function L4e(n,e,a){return function(){var s=a.concat(Array.prototype.slice.call(arguments));return s.length>=e?n.apply(this,s):L4e(n,e,s)}}function xu(n){return L4e(n,n.length,[])}xu(function(n,e){if(e==="transparent")return e;var a=Op(e);return Lp(eu({},a,{hue:a.hue+parseFloat(n)}))});function xg(n,e,a){return Math.max(n,Math.min(e,a))}xu(function(n,e){if(e==="transparent")return e;var a=Op(e);return Lp(eu({},a,{lightness:xg(0,1,a.lightness-parseFloat(n))}))});xu(function(n,e){if(e==="transparent")return e;var a=Op(e);return Lp(eu({},a,{saturation:xg(0,1,a.saturation-parseFloat(n))}))});xu(function(n,e){if(e==="transparent")return e;var a=Op(e);return Lp(eu({},a,{lightness:xg(0,1,a.lightness+parseFloat(n))}))});var $4e=xu(function(n,e,a){if(e==="transparent")return a;if(a==="transparent")return e;if(n===0)return a;var s=dg(e),l=eu({},s,{alpha:typeof s.alpha=="number"?s.alpha:1}),p=dg(a),x=eu({},p,{alpha:typeof p.alpha=="number"?p.alpha:1}),f=l.alpha-x.alpha,m=2*parseFloat(n)-1,D=((m*f===-1?m:m+f)/(1+m*f)+1)/2,b=1-D;return L5({red:Math.floor(l.red*D+x.red*b),green:Math.floor(l.green*D+x.green*b),blue:Math.floor(l.blue*D+x.blue*b),alpha:l.alpha*parseFloat(n)+x.alpha*(1-parseFloat(n))})});xu(function(n,e){if(e==="transparent")return e;var a=dg(e);return L5(eu({},a,{alpha:xg(0,1,(100*(typeof a.alpha=="number"?a.alpha:1)+100*parseFloat(n))/100)}))});xu(function(n,e){if(e==="transparent")return e;var a=Op(e);return Lp(eu({},a,{saturation:xg(0,1,a.saturation+parseFloat(n))}))});xu(function(n,e){return e==="transparent"?e:Lp(eu({},Op(e),{hue:parseFloat(n)}))});xu(function(n,e){return e==="transparent"?e:Lp(eu({},Op(e),{lightness:parseFloat(n)}))});xu(function(n,e){return e==="transparent"?e:Lp(eu({},Op(e),{saturation:parseFloat(n)}))});xu(function(n,e){return e==="transparent"?e:$4e(parseFloat(n),"rgb(0, 0, 0)",e)});xu(function(n,e){return e==="transparent"?e:$4e(parseFloat(n),"rgb(255, 255, 255)",e)});var jkt=xu(function(n,e){if(e==="transparent")return e;var a=dg(e);return L5(eu({},a,{alpha:xg(0,1,+(100*(typeof a.alpha=="number"?a.alpha:1)-100*parseFloat(n)).toFixed(2)/100)}))}),p4e=["blue","orange","purple","cyan","magenta","yellowgreen","darkgoldenrod","deeppink"],VY=(n,e)=>{let a={};for(let s=0;s<n.connections.length;s++){let l=n.connections[s],p=e?.getNetConnectedToId(l.name);p&&!a[p]&&(a[p]=`hsl(${300*s/n.connections.length}, 100%, 50%)`),a[l.name]=(p?a[p]:null)??`hsl(${340*s/n.connections.length}, 100%, 50%)`}return a},hs=(n,e)=>{try{return jkt(e,n)}catch(a){return console.error(a),n}},Kb=(n,e)=>n==="top"?0:n==="bottom"?e-1:parseInt(n.slice(5)),V0=(n,e=1)=>{let a=(("width"in n?n.width:n)/.5/2)**1.1*e;return n.availableZ?.length===1&&a>1?1:a},kkt=(n,e=.5,a=16)=>{let s=0,l=n;for(;s<a&&!(V0({width:l})<=e);)l/=2,s++;return Math.max(1,s)};function z4e(n,e,a=0,s=n.length-1,l=Nkt){for(;s>a;){if(s-a>600){let m=s-a+1,D=e-a+1,b=Math.log(m),E=.5*Math.exp(2*b/3),A=.5*Math.sqrt(b*E*(m-E)/m)*(D-m/2<0?-1:1);z4e(n,e,Math.max(a,Math.floor(e-D*E/m+A)),Math.min(s,Math.floor(e+(m-D)*E/m+A)),l)}let p=n[e],x=a,f=s;for(qb(n,a,e),l(n[s],p)>0&&qb(n,a,s);x<f;){for(qb(n,x,f),x++,f--;l(n[x],p)<0;)x++;for(;l(n[f],p)>0;)f--}l(n[a],p)===0?qb(n,a,f):(f++,qb(n,f,s)),f<=e&&(a=f+1),e<=f&&(s=f-1)}}function qb(n,e,a){let s=n[e];n[e]=n[a],n[a]=s}function Nkt(n,e){return n<e?-1:n>e?1:0}var Mkt=class{constructor(n=9){this._maxEntries=Math.max(4,n),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(n){let e=this.data,a=[];if(!b5(n,e))return a;let s=this.toBBox,l=[];for(;e;){for(let p=0;p<e.children.length;p++){let x=e.children[p],f=e.leaf?s(x):x;b5(n,f)&&(e.leaf?a.push(x):jY(n,f)?this._all(x,a):l.push(x))}e=l.pop()}return a}collides(n){let e=this.data;if(!b5(n,e))return!1;let a=[];for(;e;){for(let s=0;s<e.children.length;s++){let l=e.children[s],p=e.leaf?this.toBBox(l):l;if(b5(n,p)){if(e.leaf||jY(n,p))return!0;a.push(l)}}e=a.pop()}return!1}load(n){if(!n||!n.length)return this;if(n.length<this._minEntries){for(let a=0;a<n.length;a++)this.insert(n[a]);return this}let e=this._build(n.slice(),0,n.length-1,0);if(this.data.children.length)if(this.data.height===e.height)this._splitRoot(this.data,e);else{if(this.data.height<e.height){let a=this.data;this.data=e,e=a}this._insert(e,this.data.height-e.height-1,!0)}else this.data=e;return this}insert(n){return n&&this._insert(n,this.data.height-1),this}clear(){return this.data=ug([]),this}remove(n,e){if(!n)return this;let a=this.data,s=this.toBBox(n),l=[],p=[],x,f,m;for(;a||l.length;){if(a||(a=l.pop(),f=l[l.length-1],x=p.pop(),m=!0),a.leaf){let D=Okt(n,a.children,e);if(D!==-1)return a.children.splice(D,1),l.push(a),this._condense(l),this}m||a.leaf||!jY(a,s)?f?(x++,a=f.children[x],m=!1):a=null:(l.push(a),p.push(x),x=0,f=a,a=a.children[0])}return this}toBBox(n){return n}compareMinX(n,e){return n.minX-e.minX}compareMinY(n,e){return n.minY-e.minY}toJSON(){return this.data}fromJSON(n){return this.data=n,this}_all(n,e){let a=[];for(;n;)n.leaf?e.push(...n.children):a.push(...n.children),n=a.pop();return e}_build(n,e,a,s){let l=a-e+1,p,x=this._maxEntries;if(l<=x)return p=ug(n.slice(e,a+1)),og(p,this.toBBox),p;s||(s=Math.ceil(Math.log(l)/Math.log(x)),x=Math.ceil(l/Math.pow(x,s-1))),p=ug([]),p.leaf=!1,p.height=s;let f=Math.ceil(l/x),m=f*Math.ceil(Math.sqrt(x));x4e(n,e,a,m,this.compareMinX);for(let D=e;D<=a;D+=m){let b=Math.min(D+m-1,a);x4e(n,D,b,f,this.compareMinY);for(let E=D;E<=b;E+=f){let A=Math.min(E+f-1,b);p.children.push(this._build(n,E,A,s-1))}}return og(p,this.toBBox),p}_chooseSubtree(n,e,a,s){for(;s.push(e),!e.leaf&&s.length-1!==a;){let l,p=1/0,x=1/0;for(let f=0;f<e.children.length;f++){let m=e.children[f],D=IY(m),b=zkt(n,m)-D;b<x?(x=b,p=D<p?D:p,l=m):b===x&&D<p&&(p=D,l=m)}e=l||e.children[0]}return e}_insert(n,e,a){let s=a?n:this.toBBox(n),l=[],p=this._chooseSubtree(s,this.data,e,l);for(p.children.push(n),Vb(p,s);e>=0&&l[e].children.length>this._maxEntries;)this._split(l,e),e--;this._adjustParentBBoxes(s,l,e)}_split(n,e){let a=n[e],s=a.children.length,l=this._minEntries;this._chooseSplitAxis(a,l,s);let p=this._chooseSplitIndex(a,l,s),x=ug(a.children.splice(p,a.children.length-p));x.height=a.height,x.leaf=a.leaf,og(a,this.toBBox),og(x,this.toBBox),e?n[e-1].children.push(x):this._splitRoot(a,x)}_splitRoot(n,e){this.data=ug([n,e]),this.data.height=n.height+1,this.data.leaf=!1,og(this.data,this.toBBox)}_chooseSplitIndex(n,e,a){let s,l=1/0,p=1/0;for(let x=e;x<=a-e;x++){let f=Ub(n,0,x,this.toBBox),m=Ub(n,x,a,this.toBBox),D=qkt(f,m),b=IY(f)+IY(m);D<l?(l=D,s=x,p=b<p?b:p):D===l&&b<p&&(p=b,s=x)}return s||a-e}_chooseSplitAxis(n,e,a){let s=n.leaf?this.compareMinX:Lkt,l=n.leaf?this.compareMinY:$kt;this._allDistMargin(n,e,a,s)<this._allDistMargin(n,e,a,l)&&n.children.sort(s)}_allDistMargin(n,e,a,s){n.children.sort(s);let l=this.toBBox,p=Ub(n,0,e,l),x=Ub(n,a-e,a,l),f=y5(p)+y5(x);for(let m=e;m<a-e;m++){let D=n.children[m];Vb(p,n.leaf?l(D):D),f+=y5(p)}for(let m=a-e-1;m>=e;m--){let D=n.children[m];Vb(x,n.leaf?l(D):D),f+=y5(x)}return f}_adjustParentBBoxes(n,e,a){for(let s=a;s>=0;s--)Vb(e[s],n)}_condense(n){for(let e,a=n.length-1;a>=0;a--)n[a].children.length===0?a>0?(e=n[a-1].children,e.splice(e.indexOf(n[a]),1)):this.clear():og(n[a],this.toBBox)}};function Okt(n,e,a){if(!a)return e.indexOf(n);for(let s=0;s<e.length;s++)if(a(n,e[s]))return s;return-1}function og(n,e){Ub(n,0,n.children.length,e,n)}function Ub(n,e,a,s,l){l||(l=ug(null)),l.minX=1/0,l.minY=1/0,l.maxX=-1/0,l.maxY=-1/0;for(let p=e;p<a;p++){let x=n.children[p];Vb(l,n.leaf?s(x):x)}return l}function Vb(n,e){return n.minX=Math.min(n.minX,e.minX),n.minY=Math.min(n.minY,e.minY),n.maxX=Math.max(n.maxX,e.maxX),n.maxY=Math.max(n.maxY,e.maxY),n}function Lkt(n,e){return n.minX-e.minX}function $kt(n,e){return n.minY-e.minY}function IY(n){return(n.maxX-n.minX)*(n.maxY-n.minY)}function y5(n){return n.maxX-n.minX+(n.maxY-n.minY)}function zkt(n,e){return(Math.max(e.maxX,n.maxX)-Math.min(e.minX,n.minX))*(Math.max(e.maxY,n.maxY)-Math.min(e.minY,n.minY))}function qkt(n,e){let a=Math.max(n.minX,e.minX),s=Math.max(n.minY,e.minY),l=Math.min(n.maxX,e.maxX),p=Math.min(n.maxY,e.maxY);return Math.max(0,l-a)*Math.max(0,p-s)}function jY(n,e){return n.minX<=e.minX&&n.minY<=e.minY&&e.maxX<=n.maxX&&e.maxY<=n.maxY}function b5(n,e){return e.minX<=n.maxX&&e.minY<=n.maxY&&e.maxX>=n.minX&&e.maxY>=n.minY}function ug(n){return{children:n,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function x4e(n,e,a,s,l){let p=[e,a];for(;p.length;){if((a=p.pop())-(e=p.pop())<=s)continue;let x=e+Math.ceil((a-e)/s/2)*s;z4e(n,x,e,a,l),p.push(e,x,x,a)}}var f4e=class{constructor(n=9){q(this,"tree");this.tree=new Mkt(n)}insert(n,e,a,s,l){this.tree.insert({minX:e,minY:a,maxX:s,maxY:l,data:n})}bulkLoad(n){let e=n.map(({item:a,minX:s,minY:l,maxX:p,maxY:x})=>({minX:s,minY:l,maxX:p,maxY:x,data:a}));this.tree.load(e)}search(n,e,a,s){return this.tree.search({minX:n,minY:e,maxX:a,maxY:s}).map(l=>l.data)}clear(){this.tree.clear()}},Ukt=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(n,e){let a=this.length++;for(;a>0;){let s=a-1>>1,l=this.values[s];if(e>=l)break;this.ids[a]=this.ids[s],this.values[a]=l,a=s}this.ids[a]=n,this.values[a]=e}pop(){if(this.length===0)return;let n=this.ids[0];if(this.length--,this.length>0){let e=this.ids[0]=this.ids[this.length],a=this.values[0]=this.values[this.length],s=this.length>>1,l=0;for(;l<s;){let p=1+(l<<1),x=p+1,f=this.ids[p],m=this.values[p],D=this.values[x];if(x<this.length&&D<m&&(p=x,f=this.ids[x],m=D),m>=a)break;this.ids[l]=f,this.values[l]=m,l=p}this.ids[l]=e,this.values[l]=a}return n}peek(){if(this.length!==0)return this.ids[0]}peekValue(){if(this.length!==0)return this.values[0]}shrink(){this.ids.length=this.values.length=this.length}},h4e=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],m4e=class q4e{static from(e,a=0){if(a%8!=0)throw new Error("byteOffset must be 8-byte aligned.");if(!e||e.byteLength===void 0||e.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[s,l]=new Uint8Array(e,a+0,2);if(s!==251)throw new Error("Data does not appear to be in a Flatbush format.");let p=l>>4;if(p!==3)throw new Error(`Got v${p} data when expected v3.`);let x=h4e[15&l];if(!x)throw new Error("Unrecognized array type.");let[f]=new Uint16Array(e,a+2,1),[m]=new Uint32Array(e,a+4,1);return new q4e(m,f,x,void 0,e,a)}constructor(e,a=16,s=Float64Array,l=ArrayBuffer,p,x=0){if(e===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(e)||e<=0)throw new Error(`Unexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+a,2),65535),this.byteOffset=x;let f=e,m=f;this._levelBounds=[4*f];do f=Math.ceil(f/this.nodeSize),m+=f,this._levelBounds.push(4*m);while(f!==1);this.ArrayType=s,this.IndexArrayType=m<16384?Uint16Array:Uint32Array;let D=h4e.indexOf(this.ArrayType),b=4*m*this.ArrayType.BYTES_PER_ELEMENT;if(D<0)throw new Error(`Unexpected typed array class: ${s}.`);p&&p.byteLength!==void 0&&!p.buffer?(this.data=p,this._boxes=new this.ArrayType(this.data,x+8,4*m),this._indices=new this.IndexArrayType(this.data,x+8+b,m),this._pos=4*m,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1]):(this.data=new l(8+b+m*this.IndexArrayType.BYTES_PER_ELEMENT),this._boxes=new this.ArrayType(this.data,8,4*m),this._indices=new this.IndexArrayType(this.data,8+b,m),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(this.data,0,2).set([251,48+D]),new Uint16Array(this.data,2,1)[0]=a,new Uint32Array(this.data,4,1)[0]=e),this._queue=new Ukt}add(e,a,s=e,l=a){let p=this._pos>>2,x=this._boxes;return this._indices[p]=p,x[this._pos++]=e,x[this._pos++]=a,x[this._pos++]=s,x[this._pos++]=l,e<this.minX&&(this.minX=e),a<this.minY&&(this.minY=a),s>this.maxX&&(this.maxX=s),l>this.maxY&&(this.maxY=l),p}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let e=this._boxes;if(this.numItems<=this.nodeSize)return e[this._pos++]=this.minX,e[this._pos++]=this.minY,e[this._pos++]=this.maxX,void(e[this._pos++]=this.maxY);let a=this.maxX-this.minX||1,s=this.maxY-this.minY||1,l=new Uint32Array(this.numItems);for(let p=0,x=0;p<this.numItems;p++){let f=e[x++],m=e[x++],D=e[x++],b=e[x++],E=Math.floor(65535*((f+D)/2-this.minX)/a),A=Math.floor(65535*((m+b)/2-this.minY)/s);l[p]=Gkt(E,A)}GY(l,e,this._indices,0,this.numItems-1,this.nodeSize);for(let p=0,x=0;p<this._levelBounds.length-1;p++){let f=this._levelBounds[p];for(;x<f;){let m=x,D=e[x++],b=e[x++],E=e[x++],A=e[x++];for(let B=1;B<this.nodeSize&&x<f;B++)D=Math.min(D,e[x++]),b=Math.min(b,e[x++]),E=Math.max(E,e[x++]),A=Math.max(A,e[x++]);this._indices[this._pos>>2]=m,e[this._pos++]=D,e[this._pos++]=b,e[this._pos++]=E,e[this._pos++]=A}}}search(e,a,s,l,p){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let x=this._boxes.length-4,f=[],m=[];for(;x!==void 0;){let D=Math.min(x+4*this.nodeSize,D4e(x,this._levelBounds));for(let b=x;b<D;b+=4){if(s<this._boxes[b]||l<this._boxes[b+1]||e>this._boxes[b+2]||a>this._boxes[b+3])continue;let E=0|this._indices[b>>2];x>=4*this.numItems?f.push(E):(p===void 0||p(E))&&m.push(E)}x=f.pop()}return m}neighbors(e,a,s=1/0,l=1/0,p){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let x=this._boxes.length-4,f=this._queue,m=[],D=l*l;e:for(;x!==void 0;){let b=Math.min(x+4*this.nodeSize,D4e(x,this._levelBounds));for(let E=x;E<b;E+=4){let A=0|this._indices[E>>2],B=g4e(e,this._boxes[E],this._boxes[E+2]),w=g4e(a,this._boxes[E+1],this._boxes[E+3]),P=B*B+w*w;P>D||(x>=4*this.numItems?f.push(A<<1,P):(p===void 0||p(A))&&f.push(1+(A<<1),P))}for(;f.length&&1&f.peek();)if(f.peekValue()>D||(m.push(f.pop()>>1),m.length===s))break e;x=f.length?f.pop()>>1:void 0}return f.clear(),m}};function g4e(n,e,a){return n<e?e-n:n<=a?0:n-a}function D4e(n,e){let a=0,s=e.length-1;for(;a<s;){let l=a+s>>1;e[l]>n?s=l:a=l+1}return e[a]}function GY(n,e,a,s,l,p){if(Math.floor(s/p)>=Math.floor(l/p))return;let x=n[s+l>>1],f=s-1,m=l+1;for(;;){do f++;while(n[f]<x);do m--;while(n[m]>x);if(f>=m)break;Vkt(n,e,a,f,m)}GY(n,e,a,s,m,p),GY(n,e,a,m+1,l,p)}function Vkt(n,e,a,s,l){let p=n[s];n[s]=n[l],n[l]=p;let x=4*s,f=4*l,m=e[x],D=e[x+1],b=e[x+2],E=e[x+3];e[x]=e[f],e[x+1]=e[f+1],e[x+2]=e[f+2],e[x+3]=e[f+3],e[f]=m,e[f+1]=D,e[f+2]=b,e[f+3]=E;let A=a[s];a[s]=a[l],a[l]=A}function Gkt(n,e){let a=n^e,s=65535^a,l=65535^(n|e),p=n&(65535^e),x=a|s>>1,f=a>>1^a,m=l>>1^s&p>>1^l,D=a&l>>1^p>>1^p;a=x,s=f,l=m,p=D,x=a&a>>2^s&s>>2,f=a&s>>2^s&(a^s)>>2,m^=a&l>>2^s&p>>2,D^=s&l>>2^(a^s)&p>>2,a=x,s=f,l=m,p=D,x=a&a>>4^s&s>>4,f=a&s>>4^s&(a^s)>>4,m^=a&l>>4^s&p>>4,D^=s&l>>4^(a^s)&p>>4,a=x,s=f,l=m,p=D,m^=a&l>>8^s&p>>8,D^=s&l>>8^(a^s)&p>>8,a=m^m>>1,s=D^D>>1;let b=n^e,E=s|65535^(b|a);return b=16711935&(b|b<<8),b=252645135&(b|b<<4),b=858993459&(b|b<<2),b=1431655765&(b|b<<1),E=16711935&(E|E<<8),E=252645135&(E|E<<4),E=858993459&(E|E<<2),E=1431655765&(E|E<<1),(E<<1|b)>>>0}var Xkt=class{constructor(n){q(this,"index");q(this,"items",[]);q(this,"currentIndex",0);q(this,"capacity");this.capacity=Math.max(1,n),this.index=new m4e(this.capacity)}insert(n,e,a,s,l){if(this.currentIndex>=this.index.numItems)throw new Error("Exceeded initial capacity");this.items[this.currentIndex]=n,this.index.add(e,a,s,l),this.currentIndex++}finish(){this.index.finish()}search(n,e,a,s){return this.index.search(n,e,a,s).map(l=>this.items[l]||null).filter(Boolean)}clear(){this.items=[],this.currentIndex=0,this.index=new m4e(this.capacity)}},U4e=class{constructor(n="native",e=[]){q(this,"idx");q(this,"storage",[]);n==="flatbush"?e.length===0?(this.idx=new f4e,n="rbush"):this.idx=new Xkt(e.length):this.idx=n==="rbush"?new f4e:new class{constructor(){q(this,"shi",new Ykt(e))}insert(a){}search(a,s,l,p){let x=(a+l)/2,f=(s+p)/2,m=l-a,D=p-s;return this.shi.getNodesInArea(x,f,m,D)}clear(){}},e.forEach(a=>this.insert(a)),n==="flatbush"&&e.length>0&&this.idx.finish?.()}insert(n){this.storage.push(n),this.idx.insert(n,n.center.x-n.width/2,n.center.y-n.height/2,n.center.x+n.width/2,n.center.y+n.height/2)}search(n){return this.idx.search(n.minX,n.minY,n.maxX,n.maxY)}searchArea(n,e,a,s){return this.search({minX:n-a/2,minY:e-s/2,maxX:n+a/2,maxY:e+s/2})}},Ykt=class{constructor(n){q(this,"buckets");q(this,"CELL_SIZE",.4);this.obstacles=n,this.buckets=new Map;for(let e=0;e<n.length;e++){let a=n[e],s=a.center.x-a.width/2,l=a.center.y-a.height/2,p=a.center.x+a.width/2,x=a.center.y+a.height/2;for(let f=s;f<=p;f+=this.CELL_SIZE)for(let m=l;m<=x;m+=this.CELL_SIZE){let D=this.getBucketKey(f,m),b=this.buckets.get(D);b?b.push([a,e]):this.buckets.set(D,[[a,e]])}}}getBucketKey(n,e){return`${Math.floor(n/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getNodesInArea(n,e,a,s){let l=[],p=new Set,x=e-s/2,f=n+a/2,m=e+s/2;for(let D=n-a/2;D<=f;D+=this.CELL_SIZE)for(let b=x;b<=m;b+=this.CELL_SIZE){let E=this.getBucketKey(D,b),A=this.buckets.get(E)||[];for(let B of A)p.has(B[1])||(p.add(B[1]),l.push(B[0]))}return l}},Hkt=class{constructor(n){q(this,"buckets");q(this,"CELL_SIZE",5);this.targets=n,this.buckets=new Map;for(let e=0;e<n.length;e++){let a=n[e],s=Math.floor(a.bounds.minX/this.CELL_SIZE)*this.CELL_SIZE,l=Math.floor(a.bounds.minY/this.CELL_SIZE)*this.CELL_SIZE,p=a.bounds.maxX,x=a.bounds.maxY;for(let f=s;f<=p;f+=this.CELL_SIZE)for(let m=l;m<=x;m+=this.CELL_SIZE){let D=this.getBucketKey(f,m),b=this.buckets.get(D);b?b.push([a,e]):this.buckets.set(D,[[a,e]])}}}getBucketKey(n,e){return`${Math.floor(n/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getTargetsInArea(n,e,a,s){let l=[],p=new Set,x=Math.floor((n-a/2)/this.CELL_SIZE)*this.CELL_SIZE,f=Math.floor((e-s/2)/this.CELL_SIZE)*this.CELL_SIZE,m=n+a/2,D=e+s/2;for(let b=x;b<=m;b+=this.CELL_SIZE)for(let E=f;E<=D;E+=this.CELL_SIZE){let A=this.getBucketKey(b,E),B=this.buckets.get(A)||[];for(let w of B)p.has(w[1])||(p.add(w[1]),l.push(w[0]))}return l}},Wkt=class extends Aa{constructor(e,a={}){super();q(this,"unfinishedNodes");q(this,"finishedNodes");q(this,"nodeToXYOverlappingObstaclesMap");q(this,"layerCount");q(this,"MAX_DEPTH",4);q(this,"targets");q(this,"targetTree");q(this,"obstacleTree");q(this,"_nextNodeCounter",0);this.srj=e,this.opts=a,this.MAX_DEPTH=a?.capacityDepth??this.MAX_DEPTH,this.MAX_ITERATIONS=1e5,this.layerCount=e.layerCount??2;for(let x of e.obstacles)if(!x.zLayers){let f=[];for(let m of x.layers)f.push(Kb(m,e.layerCount));x.zLayers=f}let s={x:(e.bounds.minX+e.bounds.maxX)/2,y:(e.bounds.minY+e.bounds.maxY)/2},l={width:e.bounds.maxX-e.bounds.minX,height:e.bounds.maxY-e.bounds.minY},p=Math.max(l.width,l.height);this.unfinishedNodes=[{capacityMeshNodeId:this.getNextNodeId(),center:s,width:p,height:p,layer:"top",availableZ:[0,1],_depth:0,_containsTarget:!0,_containsObstacle:!0,_completelyInsideObstacle:!1}],this.finishedNodes=[],this.nodeToXYOverlappingObstaclesMap=new Map,this.obstacleTree=new U4e("flatbush",this.srj.obstacles),this.targets=this.computeTargets(),this.targetTree=new Hkt(this.targets)}computeTargets(){let e=[];for(let a of this.srj.connections)for(let s of a.pointsToConnect){let l=this.obstacleTree.searchArea(s.x,s.y,.01,.01).filter(f=>f.zLayers.some(m=>s.layer==="top"?m===0:m===1)),p={minX:s.x-.005,minY:s.y-.005,maxX:s.x+.005,maxY:s.y+.005};l.length>0&&(p={minX:Math.min(...l.map(f=>f.center.x-f.width/2)),minY:Math.min(...l.map(f=>f.center.y-f.height/2)),maxX:Math.max(...l.map(f=>f.center.x+f.width/2)),maxY:Math.max(...l.map(f=>f.center.y+f.height/2))});let x={...s,connectionName:a.name,availableZ:s.layer==="top"?[0]:[1],bounds:p};e.push(x)}return e}getNextNodeId(){return"cn"+this._nextNodeCounter++}getCapacityFromDepth(e){return(this.MAX_DEPTH-e+1)**2}getTargetIfNodeContainsTarget(e){let a=e.width>4*this.targetTree.CELL_SIZE?this.targets:this.targetTree.getTargetsInArea(e.center.x,e.center.y,e.width,e.height);for(let s of a)if(s.bounds.minX<=e.center.x+e.width/2&&s.bounds.maxX>=e.center.x-e.width/2&&s.bounds.minY<=e.center.y+e.height/2&&s.bounds.maxY>=e.center.y-e.height/2&&s.availableZ.some(l=>e.availableZ.includes(l)))return s;return null}getXYOverlappingObstacles(e){let a=this.nodeToXYOverlappingObstaclesMap.get(e.capacityMeshNodeId);if(a)return a;let s=[],l=e.center.x-e.width/2,p=e.center.x+e.width/2,x=e.center.y-e.height/2,f=e.center.y+e.height/2,m=e._parent?this.getXYOverlappingObstacles(e._parent):this.srj.obstacles;for(let D of m){let b=D.center.x-D.width/2,E=D.center.x+D.width/2,A=D.center.y-D.height/2,B=D.center.y+D.height/2;(p>=b&&l<=E&&f>=A&&x<=B||l>=b&&p<=E&&x>=A&&f<=B||b>=l&&E<=p&&A>=x&&B<=f)&&s.push(D)}return this.nodeToXYOverlappingObstaclesMap.set(e.capacityMeshNodeId,s),s}getXYZOverlappingObstacles(e){let a=this.getXYOverlappingObstacles(e),s=[];for(let l of a)e.availableZ.some(p=>l.zLayers.includes(p))&&s.push(l);return s}doesNodeOverlapObstacle(e){if(this.getXYZOverlappingObstacles(e).length>0)return!0;let a=e.center.x-e.width/2,s=e.center.x+e.width/2,l=e.center.y-e.height/2,p=e.center.y+e.height/2;return a<this.srj.bounds.minX||s>this.srj.bounds.maxX||l<this.srj.bounds.minY||p>this.srj.bounds.maxY}isNodeCompletelyInsideObstacle(e){let a=this.getXYZOverlappingObstacles(e),s=e.center.x-e.width/2,l=e.center.x+e.width/2,p=e.center.y-e.height/2,x=e.center.y+e.height/2;for(let f of a){let m=f.center.x-f.width/2,D=f.center.x+f.width/2,b=f.center.y-f.height/2,E=f.center.y+f.height/2;if(s>=m&&l<=D&&p>=b&&x<=E)return!0}return!1}getChildNodes(e){if(e._depth===this.MAX_DEPTH)return[];let a=[],s={width:e.width/2,height:e.height/2},l=[{x:e.center.x-s.width/2,y:e.center.y-s.height/2},{x:e.center.x+s.width/2,y:e.center.y-s.height/2},{x:e.center.x-s.width/2,y:e.center.y+s.height/2},{x:e.center.x+s.width/2,y:e.center.y+s.height/2}];for(let p of l){let x={capacityMeshNodeId:this.getNextNodeId(),center:p,width:s.width,height:s.height,layer:e.layer,availableZ:[0,1],_depth:(e._depth??0)+1,_parent:e};x._containsObstacle=this.doesNodeOverlapObstacle(x);let f=this.getTargetIfNodeContainsTarget(x);f&&(x._targetConnectionName=f.connectionName,x.availableZ=f.availableZ,x._containsTarget=!0),x._containsObstacle&&(x._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(x)),x._completelyInsideObstacle&&!x._containsTarget||a.push(x)}return a}shouldNodeBeXYSubdivided(e){return!(e._depth>=this.MAX_DEPTH)&&(!!e._containsTarget||!(!e._containsObstacle||e._completelyInsideObstacle))}_step(){let e=this.unfinishedNodes.pop();if(!e)return void(this.solved=!0);let a=this.getChildNodes(e),s=[],l=[];for(let p of a){let x=this.shouldNodeBeXYSubdivided(p);x?l.push(p):x||p._containsObstacle?!x&&p._containsTarget&&s.push(p):s.push(p)}this.unfinishedNodes.push(...l),this.finishedNodes.push(...s)}visualize(){let e={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Capacity Mesh Visualization"};for(let s of this.srj.obstacles)e.rects.push({center:s.center,width:s.width,height:s.height,fill:s.zLayers?.length===1&&s.zLayers?.includes(1)?"rgba(0,0,255,0.3)":"rgba(255,0,0,0.3)",stroke:"red",label:["obstacle",`z: ${s.zLayers.join(",")}`].join(`
|
|
954
954
|
`)});let a=[...this.finishedNodes,...this.unfinishedNodes];for(let s of a){let l=Math.min(...s.availableZ),p=this.unfinishedNodes.length>0&&s===this.unfinishedNodes[this.unfinishedNodes.length-1];e.rects.push({center:{x:s.center.x+l*s.width*.05,y:s.center.y-l*s.width*.05},width:Math.max(s.width-2,.8*s.width),height:Math.max(s.height-2,.8*s.height),fill:s._containsObstacle?"rgba(255,0,0,0.1)":{"0,1":"rgba(0,0,0,0.1)",0:"rgba(0,200,200, 0.1)",1:"rgba(0,0,200, 0.1)"}[s.availableZ.join(",")]??"rgba(0,200,200,0.1)",stroke:p?"rgba(255,165,0,0.5)":void 0,label:[s.capacityMeshNodeId,`availableZ: ${s.availableZ.join(",")}`,`target? ${s._containsTarget??!1}`,`obs? ${s._containsObstacle??!1}`,`${s.width.toFixed(2)}x${s.height.toFixed(2)}`,`capacity: ${V0(s).toFixed(2)}`].join(`
|
|
@@ -1035,10 +1035,10 @@ ${B.join(`
|
|
|
1035
1035
|
`)}
|
|
1036
1036
|
</div>`},uzt=n=>{let e=n.layout(),a={title:"CssGrid",coordinateSystem:"screen",lines:[],circles:[],points:[],rects:[],texts:[]},{cells:s}=e;for(let l of s){let{x:p,y:x,width:f,height:m,key:D}=l;a.rects.push({center:{x:p+f/2,y:x+m/2},width:f,height:m,fill:Y5e(D),label:D})}return a};function ES(n){return n.replace(/repeat\((\d+),\s*([^)]+)\)/g,(e,a,s)=>Array(Number(a)).fill(s.trim()).join(" "))}function vS(n){return n.trim().split(/\s+/).filter(Boolean)}function V5e(n){return n?vS(ES(n)).length:0}function G5e(n,e){if(n==="auto")return{fr:1};if(n.endsWith("%")){let s=parseFloat(n);return e!=null?e*s/100:0}if(n.endsWith("px"))return parseFloat(n);if(n.endsWith("em"))return parseFloat(n)*16;if(n.endsWith("fr"))return{fr:parseFloat(n)};let a=parseFloat(n);return Number.isNaN(a)?0:a}function X5e(n,e){return n>0?n:e+2+n}var czt=n=>{let e=n.opts,a=e.children,s,l;if("gridTemplate"in e&&typeof e.gridTemplate=="string"){let[L,K]=e.gridTemplate.split("/");s=L?.trim(),l=K?.trim()}else s=typeof e.gridTemplateRows=="string"?e.gridTemplateRows:void 0,l=typeof e.gridTemplateColumns=="string"?e.gridTemplateColumns:void 0;let p=V5e(l),x=V5e(s);function f(L,K,U,J){if(!L)return 0;let Q=ES(L),de=vS(Q),ce=de.length,Te=0,Ne=!1;for(let et=0;et<de.length;et++){let ct=de[et];if(ct.endsWith("px"))Te+=parseFloat(ct);else if(ct.endsWith("em"))Te+=parseFloat(ct)*16;else if(ct.endsWith("fr")||ct==="auto"){Ne=!0;let Mt=0;for(let Dt of K){let ot=U?Dt.columnStart||Dt.column:Dt.rowStart||Dt.row,it=U?Dt.columnSpan||1:Dt.rowSpan||1,qt=U?Dt.contentWidth:Dt.contentHeight,It=(typeof ot=="number"?ot:parseInt(ot||"1"))-1,tr=typeof it=="number"?it:parseInt(it.toString());if(It<=et&&et<It+tr&&qt){let Dr=typeof qt=="string"&&qt.endsWith("px")?parseFloat(qt):typeof qt=="number"?qt:0;Mt=Math.max(Mt,Dr/tr)}}Te+=Mt}}let Ve=J*(ce-1);return Te+Ve}function m(L,K,U,J=!0,Q=1){if(!L)return[];if(K==null){let it=ES(L),qt=vS(it),It=qt.length,tr=Fe=>Fe===void 0?0:typeof Fe=="number"?Fe:(Fe.endsWith("px"),parseFloat(Fe)),Dr=new Array(It).fill(0),Et=0;for(let Fe of a){let Pe=J?typeof Fe.columnSpan=="number"?Fe.columnSpan:Fe.columnSpan?parseInt(Fe.columnSpan.toString()):1:typeof Fe.rowSpan=="number"?Fe.rowSpan:Fe.rowSpan?parseInt(Fe.rowSpan.toString()):1,_e=J?Fe.contentWidth:Fe.contentHeight,Ze=tr(_e)/Pe,bt;J?(Fe.columnStart!==void 0||Fe.column!==void 0)&&(bt=parseInt(Fe.columnStart??Fe.column)-1):(Fe.rowStart!==void 0||Fe.row!==void 0)&&(bt=parseInt(Fe.rowStart??Fe.row)-1),(bt===void 0||Number.isNaN(bt))&&(J?bt=Et%It:bt=Math.floor(Et/Q),Et+=Pe);for(let Rt=0;Rt<Pe&&bt+Rt<It;Rt++)Dr[bt+Rt]=Math.max(Dr[bt+Rt],Ze)}return qt.forEach((Fe,Pe)=>{let _e=G5e(Fe,void 0);typeof _e=="number"&&(Dr[Pe]=_e)}),Dr}let de=ES(L),ce=vS(de),Te=ce.length,Ne=K;Ne==null&&(Ne=f(L,a,J,U));let Ve=Ne-U*(Te-1),et=0,ct=0,Mt=[],Dt=[];ce.forEach((it,qt)=>{let It=G5e(it,Ve);typeof It=="number"?(Dt.push(It),et+=It):It&&typeof It=="object"&&"fr"in It?(Dt.push(It),ct+=It.fr,Mt.push({idx:qt,fr:It.fr})):(Dt.push(0),et+=0)});let ot=Math.max(Ve-et,0);return Dt.map(it=>typeof it=="number"?it:ct>0?ot/ct*it.fr:0)}let D=typeof e.gap=="number"?e.gap:Array.isArray(e.gap)?e.gap[0]:0,b=typeof e.gap=="number"?e.gap:Array.isArray(e.gap)?e.gap[1]:0,E=m(s,e.containerHeight,D,!1,p||1),A=m(l,e.containerWidth,b,!0,x||1),B=E.length,w=A.length;w===0&&a.length>0&&(w=1);let P=[],N=0;for(let L of a){let K=L.rowStart!==void 0?L.rowStart:L.row,U=L.columnStart!==void 0?L.columnStart:L.column,J=L.rowSpan!==void 0?typeof L.rowSpan=="string"?parseInt(L.rowSpan):L.rowSpan:1,Q=L.columnSpan!==void 0?typeof L.columnSpan=="string"?parseInt(L.columnSpan):L.columnSpan:1;if(L.rowEnd!==void 0){let Te=typeof L.rowEnd=="string"?parseInt(L.rowEnd):L.rowEnd;K!==void 0?J=Te-(typeof K=="string"?parseInt(K):K):K=Te-J}if(L.columnEnd!==void 0){let Te=typeof L.columnEnd=="string"?parseInt(L.columnEnd):L.columnEnd;U!==void 0?Q=Te-(typeof U=="string"?parseInt(U):U):U=Te-Q}if(typeof K=="string"&&(K=parseInt(K)),typeof U=="string"&&(U=parseInt(U)),typeof K=="number"&&K<0&&(K=X5e(K,B)),typeof U=="number"&&U<0&&(U=X5e(U,w)),K===void 0&&U!==void 0)K=1;else if(U===void 0&&K!==void 0)U=1;else if(K===void 0&&U===void 0){let Te=N;K=Math.floor(Te/w)+1,U=Te%w+1}let de=K-1,ce=U-1;J=Math.max(1,J),Q=Math.max(1,Q),P.push({key:L.key,row:de,column:ce,rowSpan:J,columnSpan:Q,x:0,y:0,width:0,height:0}),N+=Q}let O=E.length,$=A.length;for(let L of P)L.row+L.rowSpan>O&&(O=L.row+L.rowSpan),L.column+L.columnSpan>$&&($=L.column+L.columnSpan);if(E.length===0&&O>0&&e.containerHeight){let L=O,U=(e.containerHeight-D*(L-1))/L;for(let J=0;J<L;J++)E.push(U)}else for(;E.length<O;)E.push(0);if(A.length===0&&$>0&&e.containerWidth){let L=$,U=(e.containerWidth-b*(L-1))/L;for(let J=0;J<L;J++)A.push(U)}else if(A.length===0&&a.length>0&&e.containerWidth)A.push(e.containerWidth);else for(;A.length<$;)A.push(0);let ee=(L,K,U)=>{let J=0;for(let Q=0;Q<L;Q++)J+=K[Q]||0,J+=U;return J},X=(L,K,U,J)=>{let Q=0;for(let de=L;de<L+K;de++)Q+=U[de]||0,de>L&&(Q+=J);return Q},te={};for(let L of P){let K=a.find(Dt=>Dt.key===L.key),U=ee(L.column,A,b),J=ee(L.row,E,D),Q=X(L.column,L.columnSpan,A,b),de=X(L.row,L.rowSpan,E,D),ce=Dt=>Dt===void 0?0:typeof Dt=="string"?Dt.endsWith("px")?parseFloat(Dt):Dt.endsWith("%")?0:parseFloat(Dt):Dt,Te=ce(K?.contentWidth),Ne=ce(K?.contentHeight),Ve=Q,et=de,ct=U,Mt=J;if(Te>0)switch(Ve=Te,e.justifyItems||"stretch"){case"start":ct=U;break;case"end":ct=U+Q-Ve;break;case"center":ct=U+(Q-Ve)/2;break;case"stretch":Ve=Q,ct=U;break}if(Ne>0)switch(et=Ne,e.alignItems||"stretch"){case"start":Mt=J;break;case"end":Mt=J+de-et;break;case"center":Mt=J+(de-et)/2;break;case"stretch":et=de,Mt=J;break}L.x=ct,L.y=Mt,L.width=Ve,L.height=et,te[L.key]={x:ct,y:Mt,width:Ve,height:et}}return{cells:P,rowSizes:E,columnSizes:A,rowGap:D,columnGap:b,itemCoordinates:te}},H5e=class{constructor(n){q(this,"opts");this.opts=n}layout(){return czt(this)}convertToHtml(){return ozt(this)}visualize(){return uzt(this)}};ea();Yt();ea();var kBe=qr(vs(),1);ea();Yt();var xW=class{constructor(n){q(this,"netMap");q(this,"idToNetMap");this.netMap=n,this.idToNetMap={};for(let[e,a]of Object.entries(n))for(let s of a)this.idToNetMap[s]=e}addConnections(n){for(let e of n){let a=new Set;for(let l of e){let p=this.idToNetMap[l];p&&a.add(p)}let s;if(a.size===0)s=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[s]=[];else if(a.size===1)s=a.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{s=a.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(let l of a)if(l!==s){let p=this.netMap[s],x=this.netMap[l];if(p&&x){p.push(...x),this.netMap[l]=p;for(let f of p)this.idToNetMap[f]=s}}}for(let l of e){let p=this.netMap[s];p&&!p.includes(l)&&p.push(l),this.idToNetMap[l]=s}}}getIdsConnectedToNet(n){return this.netMap[n]||[]}getNetConnectedToId(n){return this.idToNetMap[n]}areIdsConnected(n,e){if(n===e)return!0;let a=this.getNetConnectedToId(n);if(!a)return!1;let s=this.getNetConnectedToId(e);return s?a===s||s===n||s===n:!1}areAllIdsConnected(n){if(n.length===0)return!0;let e=this.getNetConnectedToId(n[0]);if(!e)return!1;for(let a of n){let s=this.getNetConnectedToId(a);if(s===void 0||s!==e)return!1}return!0}};var EF=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(e,a){let s=this.length++;for(;s>0;){let l=s-1>>1,p=this.values[l];if(a>=p)break;this.ids[s]=this.ids[l],this.values[s]=p,s=l}this.ids[s]=e,this.values[s]=a}pop(){if(this.length===0)return;let e=this.ids,a=this.values,s=e[0],l=--this.length;if(l>0){let p=e[l],x=a[l],f=0,m=l>>1;for(;f<m;){let D=(f<<1)+1,b=D+1,E=D+(+(b<l)&+(a[b]<a[D]));if(a[E]>=x)break;e[f]=e[E],a[f]=a[E],f=E}e[f]=p,a[f]=x}return s}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){this.ids.length=this.values.length=this.length}};var W5e=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],fW=3,vF=class n{static from(e,a=0){if(a%8!==0)throw new Error("byteOffset must be 8-byte aligned.");if(!e||e.byteLength===void 0||e.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[s,l]=new Uint8Array(e,a+0,2);if(s!==251)throw new Error("Data does not appear to be in a Flatbush format.");let p=l>>4;if(p!==fW)throw new Error(`Got v${p} data when expected v${fW}.`);let x=W5e[l&15];if(!x)throw new Error("Unrecognized array type.");let[f]=new Uint16Array(e,a+2,1),[m]=new Uint32Array(e,a+4,1);return new n(m,f,x,void 0,e,a)}constructor(e,a=16,s=Float64Array,l=ArrayBuffer,p,x=0){if(e===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(e)||e<=0)throw new Error(`Unexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+a,2),65535),this.byteOffset=x;let f=e,m=f;this._levelBounds=[f*4];do f=Math.ceil(f/this.nodeSize),m+=f,this._levelBounds.push(m*4);while(f!==1);this.ArrayType=s,this.IndexArrayType=m<16384?Uint16Array:Uint32Array;let D=W5e.indexOf(s),b=m*4*s.BYTES_PER_ELEMENT;if(D<0)throw new Error(`Unexpected typed array class: ${s}.`);if(p)this.data=p,this._boxes=new s(p,x+8,m*4),this._indices=new this.IndexArrayType(p,x+8+b,m),this._pos=m*4,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1];else{let E=this.data=new l(8+b+m*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new s(E,8,m*4),this._indices=new this.IndexArrayType(E,8+b,m),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(E,0,2).set([251,(fW<<4)+D]),new Uint16Array(E,2,1)[0]=a,new Uint32Array(E,4,1)[0]=e}this._queue=new EF}add(e,a,s=e,l=a){let p=this._pos>>2,x=this._boxes;return this._indices[p]=p,x[this._pos++]=e,x[this._pos++]=a,x[this._pos++]=s,x[this._pos++]=l,e<this.minX&&(this.minX=e),a<this.minY&&(this.minY=a),s>this.maxX&&(this.maxX=s),l>this.maxY&&(this.maxY=l),p}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let e=this._boxes;if(this.numItems<=this.nodeSize){e[this._pos++]=this.minX,e[this._pos++]=this.minY,e[this._pos++]=this.maxX,e[this._pos++]=this.maxY;return}let a=this.maxX-this.minX||1,s=this.maxY-this.minY||1,l=new Uint32Array(this.numItems),p=65535;for(let x=0,f=0;x<this.numItems;x++){let m=e[f++],D=e[f++],b=e[f++],E=e[f++],A=Math.floor(p*((m+b)/2-this.minX)/a),B=Math.floor(p*((D+E)/2-this.minY)/s);l[x]=dzt(A,B)}hW(l,e,this._indices,0,this.numItems-1,this.nodeSize);for(let x=0,f=0;x<this._levelBounds.length-1;x++){let m=this._levelBounds[x];for(;f<m;){let D=f,b=e[f++],E=e[f++],A=e[f++],B=e[f++];for(let w=1;w<this.nodeSize&&f<m;w++)b=Math.min(b,e[f++]),E=Math.min(E,e[f++]),A=Math.max(A,e[f++]),B=Math.max(B,e[f++]);this._indices[this._pos>>2]=D,e[this._pos++]=b,e[this._pos++]=E,e[this._pos++]=A,e[this._pos++]=B}}}search(e,a,s,l,p){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let x=this._boxes.length-4,f=[],m=[];for(;x!==void 0;){let D=Math.min(x+this.nodeSize*4,K5e(x,this._levelBounds));for(let b=x;b<D;b+=4){let E=this._boxes[b];if(s<E)continue;let A=this._boxes[b+1];if(l<A)continue;let B=this._boxes[b+2];if(e>B)continue;let w=this._boxes[b+3];if(a>w)continue;let P=this._indices[b>>2]|0;x>=this.numItems*4?f.push(P):(p===void 0||p(P,E,A,B,w))&&m.push(P)}x=f.pop()}return m}neighbors(e,a,s=1/0,l=1/0,p){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let x=this._boxes.length-4,f=this._queue,m=[],D=l*l;e:for(;x!==void 0;){let b=Math.min(x+this.nodeSize*4,K5e(x,this._levelBounds));for(let E=x;E<b;E+=4){let A=this._indices[E>>2]|0,B=this._boxes[E],w=this._boxes[E+1],P=this._boxes[E+2],N=this._boxes[E+3],O=e<B?B-e:e>P?e-P:0,$=a<w?w-a:a>N?a-N:0,ee=O*O+$*$;ee>D||(x>=this.numItems*4?f.push(A<<1,ee):(p===void 0||p(A))&&f.push((A<<1)+1,ee))}for(;f.length&&f.peek()&1;)if(f.peekValue()>D||(m.push(f.pop()>>1),m.length===s))break e;x=f.length?f.pop()>>1:void 0}return f.clear(),m}};function K5e(n,e){let a=0,s=e.length-1;for(;a<s;){let l=a+s>>1;e[l]>n?s=l:a=l+1}return e[a]}function hW(n,e,a,s,l,p){if(Math.floor(s/p)>=Math.floor(l/p))return;let x=n[s],f=n[s+l>>1],m=n[l],D=m,b=Math.max(x,f);m>b?D=b:b===x?D=Math.max(f,m):b===f&&(D=Math.max(x,m));let E=s-1,A=l+1;for(;;){do E++;while(n[E]<D);do A--;while(n[A]>D);if(E>=A)break;lzt(n,e,a,E,A)}hW(n,e,a,s,A,p),hW(n,e,a,A+1,l,p)}function lzt(n,e,a,s,l){let p=n[s];n[s]=n[l],n[l]=p;let x=4*s,f=4*l,m=e[x],D=e[x+1],b=e[x+2],E=e[x+3];e[x]=e[f],e[x+1]=e[f+1],e[x+2]=e[f+2],e[x+3]=e[f+3],e[f]=m,e[f+1]=D,e[f+2]=b,e[f+3]=E;let A=a[s];a[s]=a[l],a[l]=A}function dzt(n,e){let a=n^e,s=65535^a,l=65535^(n|e),p=n&(e^65535),x=a|s>>1,f=a>>1^a,m=l>>1^s&p>>1^l,D=a&l>>1^p>>1^p;a=x,s=f,l=m,p=D,x=a&a>>2^s&s>>2,f=a&s>>2^s&(a^s)>>2,m^=a&l>>2^s&p>>2,D^=s&l>>2^(a^s)&p>>2,a=x,s=f,l=m,p=D,x=a&a>>4^s&s>>4,f=a&s>>4^s&(a^s)>>4,m^=a&l>>4^s&p>>4,D^=s&l>>4^(a^s)&p>>4,a=x,s=f,l=m,p=D,m^=a&l>>8^s&p>>8,D^=s&l>>8^(a^s)&p>>8,a=m^m>>1,s=D^D>>1;let b=n^e,E=s|65535^(b|a);return b=(b|b<<8)&16711935,b=(b|b<<4)&252645135,b=(b|b<<2)&858993459,b=(b|b<<1)&1431655765,E=(E|E<<8)&16711935,E=(E|E<<4)&252645135,E=(E|E<<2)&858993459,E=(E|E<<1)&1431655765,(E<<1|b)>>>0}var Wp=class{constructor(){q(this,"MAX_ITERATIONS",1e5);q(this,"solved",!1);q(this,"failed",!1);q(this,"iterations",0);q(this,"progress",0);q(this,"error",null);q(this,"activeSubSolver");q(this,"failedSubSolvers");q(this,"timeToSolve");q(this,"stats",{})}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(n){throw this.error=`${this.constructor.name} error: ${n}`,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`,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:[]}}},nSe=n=>{let e=new xW({});for(let s of n.directConnections)e.addConnections([s.netId?[s.netId,...s.pinIds]:s.pinIds]);let a=new xW(e.netMap);for(let s of n.netConnections)a.addConnections([[s.netId,...s.pinIds]]);return{directConnMap:e,netConnMap:a}};function pzt(n,e={}){let a=n.length,s=e?.maxDistance??Number.POSITIVE_INFINITY;if(a<=1)return[];{let b=new Set;for(let E of n){if(b.has(E.pinId))throw new Error(`Duplicate pinId detected: "${E.pinId}"`);b.add(E.pinId)}}let l=(b,E)=>Math.abs(b.x-E.x)+Math.abs(b.y-E.y),p=new Array(a).fill(!1),x=new Array(a).fill(Number.POSITIVE_INFINITY),f=new Array(a).fill(-1),m=0;for(let b=1;b<a;b++)n[b].pinId<n[m].pinId&&(m=b);x[m]=0;let D=[];for(let b=0;b<a;b++){let E=-1,A=Number.POSITIVE_INFINITY,B="";for(let w=0;w<a;w++)if(!p[w]){let P=x[w];(P<A||P===A&&(B===""||n[w].pinId<B))&&(A=P,B=n[w].pinId,E=w)}p[E]=!0,f[E]!==-1&&D.push([n[E].pinId,n[f[E]].pinId]);for(let w=0;w<a;w++)if(!p[w]){let P=l(n[E],n[w]),N=e?.forbidEdge?.(n[E],n[w])??!1,O=P>s||N?Number.POSITIVE_INFINITY:P;(O<x[w]||O===x[w]&&n[E].pinId<n[f[w]]?.pinId)&&(x[w]=O,f[w]=E)}}return D}var CF=(n,e)=>{let{x:a,y:s}=n,{center:l,width:p,height:x}=e,f=l.y+x/2,m=l.y-x/2,D=l.x+p/2,b=l.x-p/2,E=f-s,A=s-m,B=D-a,w=a-b,P=Math.min(E,A,B,w);return P===E?"y+":P===A?"y-":P===B?"x+":"x-"},xzt=n=>{let{pins:e,inputProblem:a,pinIdMap:s,chipMap:l}=n,p=A=>{let B=new Set,w=[A];B.add(A);let P=a.directConnections||[];for(;w.length;){let N=w.shift();for(let O of P)if(O.pinIds.includes(N))for(let $ of O.pinIds)B.has($)||(B.add($),w.push($))}return B},x=e[0].pinId,f=e[1].pinId,m=new Set([...p(x),...p(f)]),D=new Map,b=new Map,E=new Set(e.map(A=>A.chipId));for(let A of m){let B=s.get(A);if(!B)continue;let w=l[B.chipId];if(!w)continue;let P=B._facingDirection??CF(B,w),N=b.get(w.chipId);if(!N){N={center:w.center};let O={xPos:0,xNeg:0,yPos:0,yNeg:0};for(let $ of w.pins){let ee=$._facingDirection??CF($,w);ee==="x+"&&O.xPos++,ee==="x-"&&O.xNeg++,ee==="y+"&&O.yPos++,ee==="y-"&&O.yNeg++}N.counts=O,b.set(w.chipId,N)}P==="x+"&&(N.hasXPos=!0),P==="x-"&&(N.hasXNeg=!0),P==="y+"&&(N.hasYPos=!0),P==="y-"&&(N.hasYNeg=!0)}for(let[A,B]of b){let w=new Set,P={axes:w},N=B.counts;!!!(N&&(N.xPos>1||N.xNeg>1||N.yPos>1||N.yNeg>1))&&E.has(A)||(B.hasXPos&&B.hasXNeg&&(P.x=B.center.x,w.add("x")),B.hasYPos&&B.hasYNeg&&(P.y=B.center.y,w.add("y"))),w.size>0&&D.set(A,P)}return D},mW=n=>{let{inputProblem:e,chipMap:a,pinIdMap:s,p1:l,p2:p}=n,x=xzt({pins:[l,p],inputProblem:e,pinIdMap:s,chipMap:a});if(x.size===0)return!1;let f=1e-9,m=(B,w)=>{for(let[,P]of x)if(P.axes.has("x")&&typeof P.x=="number"&&(B.x-P.x)*(w.x-P.x)<-f||P.axes.has("y")&&typeof P.y=="number"&&(B.y-P.y)*(w.y-P.y)<-f)return!0;return!1};if(Math.abs(l.x-p.x)<f||Math.abs(l.y-p.y)<f)return m({x:l.x,y:l.y},{x:p.x,y:p.y});let D={x:p.x,y:l.y},b={x:l.x,y:p.y},E=m({x:l.x,y:l.y},D)||m(D,{x:p.x,y:p.y}),A=m({x:l.x,y:l.y},b)||m(b,{x:p.x,y:p.y});return E&&A},Z0=(n,e=1)=>`hsl(${n.split("").reduce((s,l)=>s*31+l.charCodeAt(0),0)%360}, 100%, 50%, ${e})`,F1=(n,e={})=>{let{connectionAlpha:a=.8,chipAlpha:s=.8}=e,l={lines:[],points:[],rects:[]},p=new Map;for(let x of n.chips)for(let f of x.pins)p.set(f.pinId,f);for(let x of n.chips){l.rects.push({label:x.chipId,center:x.center,width:x.width,height:x.height,fill:Z0(x.chipId,s)});for(let f of x.pins)l.points.push({label:`${f.pinId}
|
|
1037
1037
|
${f._facingDirection??CF(f,x)}`,x:f.x,y:f.y,color:Z0(f.pinId,.8)})}for(let x of n.directConnections){let[f,m]=x.pinIds,D=p.get(f),b=p.get(m);l.lines.push({points:[{x:D.x,y:D.y},{x:b.x,y:b.y}],strokeColor:Z0(x.netId??`${f}-${m}`,a)})}for(let x of n.netConnections){let f=x.pinIds.map(m=>p.get(m));for(let m=0;m<f.length-1;m++)for(let D=m+1;D<f.length;D++){let b=f[m],E=f[D];l.lines.push({points:[{x:b.x,y:b.y},{x:E.x,y:E.y}],strokeColor:Z0(x.netId,a),strokeDash:"4 2"})}}return l},fzt=class extends Wp{constructor({inputProblem:e}){super();q(this,"inputProblem");q(this,"mspConnectionPairs",[]);q(this,"dcConnMap");q(this,"globalConnMap");q(this,"queuedDcNetIds");q(this,"chipMap");q(this,"maxMspPairDistance");q(this,"pinMap");q(this,"userNetIdByPinId");this.inputProblem=e,this.maxMspPairDistance=e.maxMspPairDistance??1;let{directConnMap:a,netConnMap:s}=nSe(e);this.dcConnMap=a,this.globalConnMap=s,this.pinMap={};for(let l of e.chips)for(let p of l.pins)this.pinMap[p.pinId]={...p,chipId:l.chipId};this.chipMap={};for(let l of e.chips)this.chipMap[l.chipId]=l;this.userNetIdByPinId={};for(let l of e.directConnections)if(l.netId){let[p,x]=l.pinIds;this.userNetIdByPinId[p]=l.netId,this.userNetIdByPinId[x]=l.netId}for(let l of e.netConnections)for(let p of l.pinIds)this.userNetIdByPinId[p]=l.netId;this.queuedDcNetIds=Object.keys(s.netMap)}getConstructorParams(){return{inputProblem:this.inputProblem}}_step(){if(this.queuedDcNetIds.length===0){this.solved=!0;return}let e=this.queuedDcNetIds.shift(),s=this.globalConnMap.getIdsConnectedToNet(e).filter(x=>!!this.pinMap[x]);if(s.length<=1)return;if(s.length===2){let[x,f]=s,m=this.pinMap[x],D=this.pinMap[f];if(Math.abs(m.x-D.x)+Math.abs(m.y-D.y)>this.maxMspPairDistance)return;let E=new Map(Object.entries(this.pinMap));if(mW({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:E,p1:m,p2:D}))return;let A=this.globalConnMap.getNetConnectedToId(x),B=this.userNetIdByPinId[x]??this.userNetIdByPinId[f];this.mspConnectionPairs.push({mspPairId:`${x}-${f}`,dcConnNetId:e,globalConnNetId:A,userNetId:B,pins:[m,D]});return}let l=new Map(Object.entries(this.pinMap)),p=pzt(s.map(x=>this.pinMap[x]).filter(Boolean),{maxDistance:this.maxMspPairDistance,forbidEdge:(x,f)=>mW({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:l,p1:x,p2:f})});for(let[x,f]of p){let m=this.pinMap[x],D=this.pinMap[f];if(mW({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:l,p1:m,p2:D}))continue;let b=this.globalConnMap.getNetConnectedToId(x),E=this.userNetIdByPinId[x]??this.userNetIdByPinId[f];this.mspConnectionPairs.push({mspPairId:`${x}-${f}`,dcConnNetId:e,globalConnNetId:b,userNetId:E,pins:[m,D]})}}visualize(){let e=F1(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let a of this.mspConnectionPairs)e.lines.push({points:[{x:a.pins[0].x,y:a.pins[0].y},{x:a.pins[1].x,y:a.pins[1].y}],strokeColor:Z0(a.mspPairId,.75)});return e}};function yW(n){let e=n.width/2,a=n.height/2;return{minX:n.center.x-e,maxX:n.center.x+e,minY:n.center.y-a,maxY:n.center.y+a}}var hzt=n=>{let e=yW(n);return{chipId:n.chipId,...e}},mzt=n=>n.chips.map(hzt),bW=1e-9,_S=(n,e,a=bW)=>Math.abs(n.x-e.x)<a,AS=(n,e,a=bW)=>Math.abs(n.y-e.y)<a,gzt=(n,e,a,s=bW)=>{let l=_S(n,e,s),p=AS(n,e,s);if(!l&&!p)return!1;if(l){let x=n.x;if(x<a.minX-s||x>a.maxX+s)return!1;let f=Math.min(n.y,e.y),m=Math.max(n.y,e.y);return Math.min(m,a.maxY)-Math.max(f,a.minY)>s}else{let x=n.y;if(x<a.minY-s||x>a.maxY+s)return!1;let f=Math.min(n.x,e.x),m=Math.max(n.x,e.x);return Math.min(m,a.maxX)-Math.max(f,a.minX)>s}},Dzt=(n,e,a={})=>{for(let s=0;s<n.length-1;s++){let l=n[s],p=n[s+1],x=a.excludeRectIdsForSegment?.(s)??new Set;for(let f of e)if(!x.has(f.chipId)&&gzt(l,p,f))return{segIndex:s,rect:f}}return null},aSe=1e-9,yzt=(n,e)=>({minX:Math.min(n.x,e.x),maxX:Math.max(n.x,e.x),minY:Math.min(n.y,e.y),maxY:Math.max(n.y,e.y)}),J5e=(n,e,a,s=aSe)=>n==="x"?e.x<a.minX-s?[(e.x+a.minX)/2]:e.x>a.maxX+s?[(e.x+a.maxX)/2]:[a.minX-.2,a.maxX+.2]:e.y<a.minY-s?[(e.y+a.minY)/2]:e.y>a.maxY+s?[(e.y+a.maxY)/2]:[a.minY-.2,a.maxY+.2],bzt=(n,e,a,s,l,p=aSe)=>{let x=[...s].map(f=>a.get(f)).filter(f=>!!f);if(n==="x"){let f=[l.minX,...x.map(A=>A.maxX)].filter(A=>A<e.minX-p),m=[l.maxX,...x.map(A=>A.minX)].filter(A=>A>e.maxX+p),D=f.length>0?Math.max(...f):void 0,b=m.length>0?Math.min(...m):void 0,E=[];return D!==void 0&&E.push((D+e.minX)/2),b!==void 0&&E.push((e.maxX+b)/2),E}else{let f=[l.minY,...x.map(A=>A.maxY)].filter(A=>A<e.minY-p),m=[l.maxY,...x.map(A=>A.minY)].filter(A=>A>e.maxY+p),D=f.length>0?Math.max(...f):void 0,b=m.length>0?Math.min(...m):void 0,E=[];return D!==void 0&&E.push((D+e.minY)/2),b!==void 0&&E.push((e.maxY+b)/2),E}},Fzt=1e-9,Ezt=(n,e,a,s,l=Fzt)=>{if(e<0||e>=n.length-1)return null;let p=n[e],x=n[e+1],f=_S(p,x,l),m=AS(p,x,l);if(!f&&!m||f&&a!=="x"||m&&a!=="y")return null;let D=n.map(b=>({...b}));if(a==="x"){if(Math.abs(p.x-s)<l&&Math.abs(x.x-s)<l)return null;D[e]={...D[e],x:s},D[e+1]={...D[e+1],x:s}}else{if(Math.abs(p.y-s)<l&&Math.abs(x.y-s)<l)return null;D[e]={...D[e],y:s},D[e+1]={...D[e+1],y:s}}if(e-1>=0){let b=D[e-1],E=D[e];if(Math.abs(b.x-E.x)+Math.abs(b.y-E.y)<l)return null}if(e+2<=D.length-1){let b=D[e+1],E=D[e+2];if(Math.abs(b.x-E.x)+Math.abs(b.y-E.y)<l)return null}for(let b=0;b<D.length-1;b++){let E=D[b],A=D[b+1];if(!AS(E,A,l)&&!_S(E,A,l))return null}return D},Z5e=(n,e=6)=>n.map(a=>`${a.x.toFixed(e)},${a.y.toFixed(e)}`).join("|"),vzt=class extends Wp{constructor(e){super();q(this,"pins");q(this,"inputProblem");q(this,"chipMap");q(this,"obstacles");q(this,"rectById");q(this,"aabb");q(this,"baseElbow");q(this,"solvedTracePath",null);q(this,"queue",[]);q(this,"visited",new Set);this.pins=e.pins,this.inputProblem=e.inputProblem,this.chipMap=e.chipMap;for(let l of this.pins)if(!l._facingDirection){let p=this.chipMap[l.chipId];l._facingDirection=CF(l,p)}this.obstacles=mzt(this.inputProblem),this.rectById=new Map(this.obstacles.map(l=>[l.chipId,l]));let[a,s]=this.pins;this.baseElbow=sg({x:a.x,y:a.y,facingDirection:a._facingDirection},{x:s.x,y:s.y,facingDirection:s._facingDirection},{overshoot:.2}),this.aabb=yzt({x:a.x,y:a.y},{x:s.x,y:s.y}),this.queue.push({path:this.baseElbow,collisionChipIds:new Set}),this.visited.add(Z5e(this.baseElbow))}getConstructorParams(){return{chipMap:this.chipMap,pins:this.pins,inputProblem:this.inputProblem}}axisOfSegment(e,a){return _S(e,a)?"x":AS(e,a)?"y":null}pathLength(e){let a=0;for(let s=0;s<e.length-1;s++)a+=Math.abs(e[s+1].x-e[s].x)+Math.abs(e[s+1].y-e[s].y);return a}_step(){if(this.solvedTracePath){this.solved=!0;return}let e=this.queue.shift();if(!e){this.failed=!0,this.error="No collision-free path found";return}let{path:a,collisionChipIds:s}=e,l=Dzt(a,this.obstacles);if(!l){this.solvedTracePath=a,this.solved=!0;return}let{segIndex:p,rect:x}=l,f=p===0,m=p===a.length-2;if(f){if(a.length<3)return;p=1}else if(m){if(a.length<3)return;p=a.length-3}let D=a[p],b=a[p+1],E=this.axisOfSegment(D,b);if(!E)return;let[A,B]=this.pins,w=[];if(s.size===0){let N=J5e(E,{x:A.x,y:A.y},x),O=J5e(E,{x:B.x,y:B.y},x),$=[...N,...O],ee=[...new Set($)];w.push(...ee)}else{let N=bzt(E,x,this.rectById,s,this.aabb);w.push(...N)}let P=[];for(let N of w){let O=Ezt(a,p,E,N);if(!O)continue;let $=Z5e(O);if(this.visited.has($))continue;this.visited.add($);let ee=new Set(s);ee.add(x.chipId);let X=this.pathLength(O);P.push({path:O,collisionRectIds:ee,len:X})}P.sort((N,O)=>N.len-O.len);for(let N of P)this.queue.push({path:N.path,collisionChipIds:N.collisionRectIds})}visualize(){let e=F1(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});e.lines.push({points:this.baseElbow,strokeColor:"red",strokeDash:"4 4"});let[a,s]=this.pins;e.lines.push({points:[{x:a.x,y:a.y},{x:s.x,y:s.y}],strokeColor:"blue",strokeDash:"5 5"});for(let{path:l,collisionChipIds:p}of this.queue)e.lines.push({points:l,strokeColor:"teal",strokeDash:"2 2"});return this.solvedTracePath?e.lines.push({points:this.solvedTracePath,strokeColor:"green"}):this.queue.length>0&&e.lines.push({points:this.queue[0].path,strokeColor:"orange"}),e}},Czt=class extends Wp{constructor(e){super();q(this,"inputProblem");q(this,"mspConnectionPairs");q(this,"dcConnMap");q(this,"globalConnMap");q(this,"queuedConnectionPairs");q(this,"chipMap");q(this,"currentConnectionPair",null);q(this,"solvedTracePaths",[]);q(this,"failedConnectionPairs",[]);this.inputProblem=e.inputProblem,this.mspConnectionPairs=e.mspConnectionPairs,this.dcConnMap=e.dcConnMap,this.globalConnMap=e.globalConnMap,this.chipMap=e.chipMap,this.queuedConnectionPairs=[...this.mspConnectionPairs]}getConstructorParams(){return{inputProblem:this.inputProblem,chipMap:this.chipMap,mspConnectionPairs:this.mspConnectionPairs,dcConnMap:this.dcConnMap,globalConnMap:this.globalConnMap}}_step(){if(this.activeSubSolver?.solved&&(this.solvedTracePaths.push({...this.currentConnectionPair,tracePath:this.activeSubSolver.solvedTracePath,mspConnectionPairIds:[this.currentConnectionPair.mspPairId],pinIds:[this.currentConnectionPair.pins[0].pinId,this.currentConnectionPair.pins[1].pinId]}),this.activeSubSolver=null,this.currentConnectionPair=null),this.activeSubSolver?.failed&&(this.currentConnectionPair&&this.failedConnectionPairs.push({...this.currentConnectionPair,error:this.activeSubSolver.error||void 0}),this.activeSubSolver=null,this.currentConnectionPair=null),this.activeSubSolver){this.activeSubSolver.step();return}let e=this.queuedConnectionPairs.shift();if(!e){this.solved=!0;return}this.currentConnectionPair=e;let{pins:a}=e;this.activeSubSolver=new vzt({inputProblem:this.inputProblem,pins:a,chipMap:this.chipMap})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=F1(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let{mspPairId:a,tracePath:s}of this.solvedTracePaths)e.lines.push({points:s,strokeColor:"green"});for(let a of this.failedConnectionPairs)e.lines.push({points:[{x:a.pins[0].x,y:a.pins[0].y},{x:a.pins[1].x,y:a.pins[1].y}],strokeColor:"red",strokeDash:"4 2"});return e}},_zt=({pts:n,segmentIndex:e,offset:a,JOG_SIZE:s,EPS:l=1e-6})=>{if(e!==0&&e!==n.length-2)return;let p=n[e],x=n[e+1],f=Math.abs(p.x-x.x)<l,m=Math.abs(p.y-x.y)<l;if(!f&&!m)return;let D=f?x.y>p.y?1:-1:x.x>p.x?1:-1;if(e===0)if(f){let b=p.y+D*s;n.splice(1,1,{x:p.x,y:b},{x:p.x+a,y:b},{x:x.x+a,y:x.y})}else{let b=p.x+D*s;n.splice(1,1,{x:b,y:p.y},{x:b,y:p.y+a},{x:x.x,y:x.y+a})}else if(f){let b=x.y-D*s;n.splice(e,1,{x:p.x+a,y:p.y},{x:x.x+a,y:b},{x:x.x,y:b})}else{let b=x.x-D*s;n.splice(e,1,{x:p.x,y:p.y+a},{x:b,y:x.y+a},{x:b,y:x.y})}},Azt=class extends Wp{constructor(e){super();q(this,"overlappingTraceSegments");q(this,"traceNetIslands");q(this,"SHIFT_DISTANCE",.1);q(this,"correctedTraceMap",{});this.overlappingTraceSegments=e.overlappingTraceSegments,this.traceNetIslands=e.traceNetIslands;for(let{connNetId:a,pathsWithOverlap:s}of this.overlappingTraceSegments)for(let{solvedTracePathIndex:l,traceSegmentIndex:p}of s){let x=this.traceNetIslands[a][l].mspPairId;this.correctedTraceMap[x]=this.traceNetIslands[a][l]}}_step(){let a=this.overlappingTraceSegments.map((p,x)=>{let f=Math.floor(x/2)+1;return(x%2===0?-f:f)*this.SHIFT_DISTANCE}),s=(p,x)=>Math.abs(p-x)<1e-6,l=(p,x)=>!!p&&!!x&&s(p.x,x.x)&&s(p.y,x.y);this.overlappingTraceSegments.forEach((p,x)=>{let f=a[x],m=new Map;for(let D of p.pathsWithOverlap)m.has(D.solvedTracePathIndex)||m.set(D.solvedTracePathIndex,new Set),m.get(D.solvedTracePathIndex).add(D.traceSegmentIndex);for(let[D,b]of m){let E=this.traceNetIslands[p.connNetId][D],A=this.correctedTraceMap[E.mspPairId]??E,B=A.tracePath.map($=>({...$})),w=Array.from(b).sort(($,ee)=>$-ee),P=Array.from(b).sort(($,ee)=>$-ee).reverse(),N=this.SHIFT_DISTANCE;for(let $ of P)if(!($<0||$>=B.length-1))if($===0||$===B.length-2)_zt({pts:B,segmentIndex:$,offset:f,JOG_SIZE:N,EPS:1e-6});else{let ee=B[$],X=B[$+1],te=Math.abs(ee.x-X.x)<1e-6,L=Math.abs(ee.y-X.y)<1e-6;if(!te&&!L)continue;te?(ee.x+=f,X.x+=f):(ee.y+=f,X.y+=f)}let O=[];for(let $ of B)(O.length===0||!l(O[O.length-1],$))&&O.push($);this.correctedTraceMap[E.mspPairId]={...A,tracePath:O}}}),this.solved=!0}visualize(){let e={lines:[],points:[],rects:[],circles:[]};for(let a of this.overlappingTraceSegments)for(let{solvedTracePathIndex:s,traceSegmentIndex:l}of a.pathsWithOverlap){let p=this.traceNetIslands[a.connNetId][s],x=p.tracePath[l],f=p.tracePath[l+1];e.lines.push({points:[x,f],strokeColor:"red"})}for(let a of Object.values(this.correctedTraceMap))e.lines.push({points:a.tracePath,strokeColor:"blue",strokeDash:"4 2"});return e}},Rzt=class extends Wp{constructor(e){super();q(this,"inputProblem");q(this,"inputTracePaths");q(this,"globalConnMap");q(this,"traceNetIslands",{});q(this,"correctedTraceMap",{});this.inputProblem=e.inputProblem,this.inputTracePaths=e.inputTracePaths,this.globalConnMap=e.globalConnMap;for(let a of this.inputTracePaths){let{mspPairId:s}=a;this.correctedTraceMap[s]=a}this.traceNetIslands=this.computeTraceNetIslands()}getConstructorParams(){return{inputProblem:this.inputProblem,inputTracePaths:this.inputTracePaths,globalConnMap:this.globalConnMap}}computeTraceNetIslands(){let e={};for(let a of this.inputTracePaths){let s=this.correctedTraceMap[a.mspPairId]??a,l=s.globalConnNetId;e[l]||(e[l]=[]),e[l].push(s)}return e}findNextOverlapIssue(){let a=Object.keys(this.traceNetIslands);for(let s=0;s<a.length;s++)for(let l=s+1;l<a.length;l++){let p=a[s],x=a[l],f=this.traceNetIslands[p]||[],m=this.traceNetIslands[x]||[],D=[],b=[],E=new Set,A=new Set,B=(w,P,N,O)=>{let $=Math.min(w,P),ee=Math.max(w,P),X=Math.min(N,O),te=Math.max(N,O);return Math.min(ee,te)-Math.max($,X)>.002};for(let w=0;w<f.length;w++){let N=f[w].tracePath;for(let O=0;O<N.length-1;O++){let $=N[O],ee=N[O+1],X=Math.abs($.x-ee.x)<.002,te=Math.abs($.y-ee.y)<.002;if(!(!X&&!te))for(let L=0;L<m.length;L++){let U=m[L].tracePath;for(let J=0;J<U.length-1;J++){let Q=U[J],de=U[J+1],ce=Math.abs(Q.x-de.x)<.002,Te=Math.abs(Q.y-de.y)<.002;if(!(!ce&&!Te)){if(X&&ce){if(Math.abs($.x-Q.x)<.002&&B($.y,ee.y,Q.y,de.y)){let Ne=`${w}:${O}`,Ve=`${L}:${J}`;E.has(Ne)||(D.push({solvedTracePathIndex:w,traceSegmentIndex:O}),E.add(Ne)),A.has(Ve)||(b.push({solvedTracePathIndex:L,traceSegmentIndex:J}),A.add(Ve))}}else if(te&&Te&&Math.abs($.y-Q.y)<.002&&B($.x,ee.x,Q.x,de.x)){let Ne=`${w}:${O}`,Ve=`${L}:${J}`;E.has(Ne)||(D.push({solvedTracePathIndex:w,traceSegmentIndex:O}),E.add(Ne)),A.has(Ve)||(b.push({solvedTracePathIndex:L,traceSegmentIndex:J}),A.add(Ve))}}}}}}if(D.length>0&&b.length>0)return{overlappingTraceSegments:[{connNetId:p,pathsWithOverlap:D},{connNetId:x,pathsWithOverlap:b}]}}return null}_step(){if(this.activeSubSolver?.solved){for(let[s,l]of Object.entries(this.activeSubSolver.correctedTraceMap))this.correctedTraceMap[s]=l;this.activeSubSolver=null,this.traceNetIslands=this.computeTraceNetIslands()}if(this.activeSubSolver){this.activeSubSolver.step();return}let e=this.findNextOverlapIssue();if(e===null){this.solved=!0;return}let{overlappingTraceSegments:a}=e;this.activeSubSolver=new Azt({overlappingTraceSegments:a,traceNetIslands:this.traceNetIslands})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=F1(this.inputProblem);for(let a of Object.values(this.correctedTraceMap))e.lines.push({points:a.tracePath,strokeColor:"purple"});return e}},Szt=class{constructor(n){q(this,"chips");q(this,"spatialIndex");q(this,"spatialIndexIdToChip");this.chips=n.map(e=>({...e,bounds:yW(e),spatialIndexId:null})),this.spatialIndexIdToChip=new Map,this.spatialIndex=new vF(n.length);for(let e of this.chips)e.spatialIndexId=this.spatialIndex.add(e.bounds.minX,e.bounds.minY,e.bounds.maxX,e.bounds.maxY),this.spatialIndexIdToChip.set(e.spatialIndexId,e);this.spatialIndex.finish()}getChipsInBounds(n){return this.spatialIndex.search(n.minX,n.minY,n.maxX,n.maxY).map(a=>this.spatialIndexIdToChip.get(a))}doesOrthogonalLineIntersectChip(n,e={}){let a=e.excludeChipIds??[],[s,l]=n,{x:p,y:x}=s,{x:f,y:m}=l;return this.getChipsInBounds({minX:Math.min(p,f),minY:Math.min(x,m),maxX:Math.max(p,f),maxY:Math.max(x,m)}).filter(b=>!a.includes(b.chipId)).length>0}},Q5e=.45,eSe=.2;function gW(n){return n==="y+"||n==="y-"?{width:eSe,height:Q5e}:{width:Q5e,height:eSe}}function DW(n,e,a,s){switch(e){case"x+":return{x:n.x+a/2,y:n.y};case"x-":return{x:n.x-a/2,y:n.y};case"y+":return{x:n.x,y:n.y+s/2};case"y-":return{x:n.x,y:n.y-s/2}}}function sSe(n,e,a){return{minX:n.x-e/2,minY:n.y-a/2,maxX:n.x+e/2,maxY:n.y+a/2}}function Bzt(n,e,a,s=1e-9){let l=Math.abs(n.x-e.x)<s,p=Math.abs(n.y-e.y)<s;if(!l&&!p)return!1;if(l){let x=n.x;if(x<a.minX-s||x>a.maxX+s)return!1;let f=Math.min(n.y,e.y),m=Math.max(n.y,e.y);return Math.min(m,a.maxY)-Math.max(f,a.minY)>s}else{let x=n.y;if(x<a.minY-s||x>a.maxY+s)return!1;let f=Math.min(n.x,e.x),m=Math.max(n.x,e.x);return Math.min(m,a.maxX)-Math.max(f,a.minX)>s}}function iSe(n,e,a,s){for(let[l,p]of Object.entries(e)){let x=p.tracePath;for(let f=0;f<x.length-1;f++)if(!(l===a&&f===s)&&Bzt(x[f],x[f+1],n))return{hasIntersection:!0,mspPairId:l,segIndex:f}}return{hasIntersection:!1}}function tSe(n){let e=0,a=n.tracePath;for(let s=0;s<a.length-1;s++)e+=Math.abs(a[s+1].x-a[s].x)+Math.abs(a[s+1].y-a[s].y);return e}function oSe(n){let{inputProblem:e,inputTraceMap:a,globalConnNetId:s,fallbackTrace:l,mspConnectionPairIds:p}=n,x=Object.fromEntries(e.chips.map(A=>[A.chipId,A])),f=Object.values(a).filter(A=>A.globalConnNetId===s);if(p&&p.length>0){let A=new Set(p);f=f.filter(B=>B.mspConnectionPairIds.some(w=>A.has(w)))}let m=new Set;for(let A of f)m.add(A.pins[0].chipId),m.add(A.pins[1].chipId);let D=null,b=-1;for(let A of m){let w=x[A]?.pins?.length??0;w>b&&(b=w,D=A)}let E=D==null?[]:f.filter(A=>A.pins[0].chipId===D||A.pins[1].chipId===D);return E.length>0?E.reduce((A,B)=>tSe(A)>=tSe(B)?A:B):l}function wzt(n,e){return[{x:n.x,y:n.y},{x:(n.x+e.x)/2,y:(n.y+e.y)/2},{x:e.x,y:e.y}]}function Tzt(n){let{inputProblem:e,inputTraceMap:a,chipObstacleSpatialIndex:s,overlappingSameNetTraceGroup:l,availableOrientations:p}=n,x=l.portOnlyPinId;if(!x)return{placement:null,testedCandidates:[],error:"No portOnlyPinId provided"};let f=null,m=null;for(let te of e.chips){let L=te.pins.find(K=>K.pinId===x);if(L){f={x:L.x,y:L.y},m=L._facingDirection||CF(L,te);break}}if(!f||!m)return{placement:null,testedCandidates:[],error:`Port-only pin not found: ${x}`};let D=p.length>0?p:["x+","x-","y+","y-"],b={x:f.x,y:f.y},E=te=>te==="x+"?{x:1,y:0}:te==="x-"?{x:-1,y:0}:te==="y+"?{x:0,y:1}:{x:0,y:-1},A=[];for(let te of D){let{width:L,height:K}=gW(te),U=DW(b,te,L,K),J=E(te),Q=.001,de={x:U.x+J.x*Q,y:U.y+J.y*Q},ce=sSe(de,L,K);if(s.getChipsInBounds(ce).length>0){A.push({center:de,width:L,height:K,bounds:ce,anchor:b,orientation:te,status:"chip-collision",hostSegIndex:-1});continue}if(iSe(ce,a,"",-1).hasIntersection){A.push({center:de,width:L,height:K,bounds:ce,anchor:b,orientation:te,status:"trace-collision",hostSegIndex:-1});continue}return A.push({center:de,width:L,height:K,bounds:ce,anchor:b,orientation:te,status:"ok",hostSegIndex:-1}),{placement:{globalConnNetId:l.globalConnNetId,dcConnNetId:void 0,netId:l.netId,mspConnectionPairIds:[],pinIds:[x],orientation:te,anchorPoint:b,width:L,height:K,center:de},testedCandidates:A}}let B=m,{width:w,height:P}=gW(B),N=DW(b,B,w,P),O=E(B),$=.001,ee={x:N.x+O.x*$,y:N.y+O.y*$};return{placement:{globalConnNetId:l.globalConnNetId,dcConnNetId:void 0,netId:l.netId,mspConnectionPairIds:[],pinIds:[x],orientation:B,anchorPoint:b,width:w,height:P,center:ee},testedCandidates:A}}function Pzt(n){let e=F1(n.inputProblem),a=n.overlappingSameNetTraceGroup.globalConnNetId,s=oSe({inputProblem:n.inputProblem,inputTraceMap:n.inputTraceMap,globalConnNetId:a,fallbackTrace:n.overlappingSameNetTraceGroup.overlappingTraces}),l=Z0(a,.9),p=Z0(a,.5);for(let x of Object.values(n.inputTraceMap)){let f=s?x.mspPairId===s.mspPairId:!1;e.lines.push({points:x.tracePath})}for(let x of n.testedCandidates){let f=x.status==="ok"?"rgba(0, 180, 0, 0.25)":x.status==="chip-collision"?"rgba(220, 0, 0, 0.25)":x.status==="trace-collision"?"rgba(220, 140, 0, 0.25)":"rgba(120, 120, 120, 0.15)",m=x.status==="ok"?"green":x.status==="chip-collision"?"red":x.status==="trace-collision"?"orange":"gray";e.rects.push({center:{x:(x.bounds.minX+x.bounds.maxX)/2,y:(x.bounds.minY+x.bounds.maxY)/2},width:x.width,height:x.height,fill:f,strokeColor:m}),e.points.push({x:x.anchor.x,y:x.anchor.y,color:m})}if(n.netLabelPlacement){let x=n.netLabelPlacement;e.rects.push({center:x.center,width:x.width,height:x.height,fill:"rgba(0, 128, 255, 0.35)",strokeColor:"blue"}),e.points.push({x:x.anchorPoint.x,y:x.anchorPoint.y,color:"blue"})}return e}var rSe=class extends Wp{constructor(e){super();q(this,"inputProblem");q(this,"inputTraceMap");q(this,"overlappingSameNetTraceGroup");q(this,"availableOrientations");q(this,"chipObstacleSpatialIndex");q(this,"netLabelPlacement",null);q(this,"testedCandidates",[]);this.inputProblem=e.inputProblem,this.inputTraceMap=e.inputTraceMap,this.overlappingSameNetTraceGroup=e.overlappingSameNetTraceGroup,this.availableOrientations=e.availableOrientations,this.chipObstacleSpatialIndex=e.inputProblem._chipObstacleSpatialIndex??new Szt(e.inputProblem.chips)}getConstructorParams(){return{inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations}}_step(){if(this.netLabelPlacement){this.solved=!0;return}if(this.overlappingSameNetTraceGroup.portOnlyPinId){let A=Tzt({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,chipObstacleSpatialIndex:this.chipObstacleSpatialIndex,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations});if(this.testedCandidates.push(...A.testedCandidates),A.placement){this.netLabelPlacement=A.placement,this.solved=!0;return}this.failed=!0,this.error=A.error??"Could not place net label at port without collisions";return}let e=this.overlappingSameNetTraceGroup.globalConnNetId,a=oSe({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,globalConnNetId:e,fallbackTrace:this.overlappingSameNetTraceGroup.overlappingTraces,mspConnectionPairIds:this.overlappingSameNetTraceGroup.mspConnectionPairIds});if(!a){this.failed=!0,this.error="No host trace found for net label placement";return}let s=new Set(this.overlappingSameNetTraceGroup.mspConnectionPairIds??[]),l=Object.values(this.inputTraceMap).filter(A=>A.globalConnNetId===e&&(s.size===0||A.mspConnectionPairIds.some(B=>s.has(B)))),p=this.availableOrientations.length===1?[a,...l.filter(A=>A.mspPairId!==a.mspPairId)]:[a],x=this.availableOrientations.length>0?this.availableOrientations:["x+","x-","y+","y-"],f=this.availableOrientations.length===1,m=(A,B)=>{switch(A){case"y+":return B.y;case"y-":return-B.y;case"x+":return B.x;case"x-":return-B.x}},D=null,b=-1/0,E=1e-6;for(let A of p){let B=A.tracePath.slice();for(let w=0;w<B.length-1;w++){let P=B[w],N=B[w+1],O=Math.abs(P.y-N.y)<E,$=Math.abs(P.x-N.x)<E;if(!O&&!$)continue;let ee=O?["y+","y-"]:["x+","x-"],X=x.filter(L=>ee.includes(L));if(X.length===0)continue;let te=wzt(P,N);for(let L of te)for(let K of X){let{width:U,height:J}=gW(K),Q=DW(L,K,U,J),de=K==="x+"?{x:1,y:0}:K==="x-"?{x:-1,y:0}:K==="y+"?{x:0,y:1}:{x:0,y:-1},ce=1e-4,Te={x:Q.x+de.x*ce,y:Q.y+de.y*ce},Ne=sSe(Te,U,J);if(this.chipObstacleSpatialIndex.getChipsInBounds(Ne).length>0){this.testedCandidates.push({center:Te,width:U,height:J,bounds:Ne,anchor:L,orientation:K,status:"chip-collision",hostSegIndex:w});continue}if(iSe(Ne,this.inputTraceMap,A.mspPairId,w).hasIntersection){this.testedCandidates.push({center:Te,width:U,height:J,bounds:Ne,anchor:L,orientation:K,status:"trace-collision",hostSegIndex:w});continue}if(this.testedCandidates.push({center:Te,width:U,height:J,bounds:Ne,anchor:L,orientation:K,status:"ok",hostSegIndex:w}),f){let ct=m(K,L);ct>b+1e-9&&(b=ct,D={anchor:L,orientation:K,width:U,height:J,center:Q,hostSegIndex:w,dcConnNetId:A.dcConnNetId,mspPairId:A.mspPairId,pinIds:[A.pins[0].pinId,A.pins[1].pinId]});continue}this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:A.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[A.mspPairId],pinIds:[A.pins[0].pinId,A.pins[1].pinId],orientation:K,anchorPoint:L,width:U,height:J,center:Q},this.solved=!0;return}}}if(f&&D){this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:D.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[D.mspPairId],pinIds:D.pinIds,orientation:D.orientation,anchorPoint:D.anchor,width:D.width,height:D.height,center:D.center},this.solved=!0;return}this.failed=!0,this.error="Could not place net label without collisions"}visualize(){return Pzt(this)}},Izt=class extends Wp{constructor(e){super();q(this,"inputProblem");q(this,"inputTraceMap");q(this,"overlappingSameNetTraceGroups");q(this,"queuedOverlappingSameNetTraceGroups");q(this,"netLabelPlacements",[]);q(this,"currentGroup",null);q(this,"triedAnyOrientationFallbackForCurrentGroup",!1);this.inputProblem=e.inputProblem,this.inputTraceMap=e.inputTraceMap,this.overlappingSameNetTraceGroups=this.computeOverlappingSameNetTraceGroups(),this.queuedOverlappingSameNetTraceGroups=[...this.overlappingSameNetTraceGroups]}computeOverlappingSameNetTraceGroups(){let e={};for(let m of Object.values(this.inputTraceMap)){let D=m.globalConnNetId;e[D]||(e[D]=[]),e[D].push(m)}let{netConnMap:a}=nSe(this.inputProblem),s=new Map;for(let m of this.inputProblem.chips)for(let D of m.pins)s.set(D.pinId,D);let l={};for(let m of this.inputProblem.directConnections)if(m.netId){let[D,b]=m.pinIds;l[D]=m.netId,l[b]=m.netId}for(let m of this.inputProblem.netConnections)for(let D of m.pinIds)l[D]=m.netId;let p=[],x=this.inputProblem.chips.flatMap(m=>m.pins.map(D=>D.pinId)),f=new Set;for(let m of x){let D=a.getNetConnectedToId(m);D&&f.add(D)}for(let m of f){let b=a.getIdsConnectedToNet(m).filter(B=>s.has(B)),E={};for(let B of b)E[B]=new Set;for(let B of e[m]??[]){let w=B.pins[0].pinId,P=B.pins[1].pinId;E[w]&&E[P]&&(E[w].add(P),E[P].add(w))}let A=new Set;for(let B of b){if(A.has(B))continue;let w=[B],P=new Set;for(A.add(B);w.length>0;){let O=w.pop();P.add(O);for(let $ of E[O]??[])A.has($)||(A.add($),w.push($))}let N=(e[m]??[]).filter(O=>P.has(O.pins[0].pinId)&&P.has(O.pins[1].pinId));if(N.length>0){let O=K=>{let U=0,J=K.tracePath;for(let Q=0;Q<J.length-1;Q++)U+=Math.abs(J[Q+1].x-J[Q].x)+Math.abs(J[Q+1].y-J[Q].y);return U},$=N[0],ee=O($);for(let K=1;K<N.length;K++){let U=O(N[K]);U>ee&&($=N[K],ee=U)}let X=N.find(K=>K.userNetId!=null)?.userNetId;if(!X){for(let K of P)if(l[K]){X=l[K];break}}let te=Array.from(new Set(N.flatMap(K=>K.mspConnectionPairIds??[K.mspPairId]))),L={globalConnNetId:m,netId:X,overlappingTraces:$,mspConnectionPairIds:te};p.push(L)}else for(let O of P){let $=l[O];$&&p.push({globalConnNetId:m,netId:$,portOnlyPinId:O})}}}return p}_step(){if(this.activeSubSolver?.solved){this.netLabelPlacements.push(this.activeSubSolver.netLabelPlacement),this.activeSubSolver=null,this.currentGroup=null,this.triedAnyOrientationFallbackForCurrentGroup=!1;return}if(this.activeSubSolver?.failed){let s=["x+","x-","y+","y-"],l=this.activeSubSolver.availableOrientations,p=l.length===4&&s.every(x=>l.includes(x));if(!this.triedAnyOrientationFallbackForCurrentGroup&&!p&&this.currentGroup){this.triedAnyOrientationFallbackForCurrentGroup=!0,this.activeSubSolver=new rSe({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.currentGroup,availableOrientations:s});return}this.failed=!0,this.error=this.activeSubSolver.error;return}if(this.activeSubSolver){this.activeSubSolver.step();return}let e=this.queuedOverlappingSameNetTraceGroups.shift();if(!e){this.solved=!0;return}let a=e.netId??e.globalConnNetId;this.currentGroup=e,this.triedAnyOrientationFallbackForCurrentGroup=!1,this.activeSubSolver=new rSe({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:e,availableOrientations:this.inputProblem.availableNetLabelOrientations[a]??["x+","x-","y+","y-"]})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=F1(this.inputProblem);for(let a of Object.values(this.inputTraceMap))e.lines.push({points:a.tracePath,strokeColor:"purple"});for(let a of this.netLabelPlacements)e.rects.push({center:a.center,width:a.width,height:a.height,fill:Z0(a.globalConnNetId,.35),strokeColor:Z0(a.globalConnNetId,.9)}),e.points.push({x:a.anchorPoint.x,y:a.anchorPoint.y,color:Z0(a.globalConnNetId,.9)});return e}},jzt=n=>{for(let e of n.chips){let a=yW(e);for(let s of e.pins){if(!(s.x>a.minX&&s.x<a.maxX&&s.y>a.minY&&s.y<a.maxY))continue;let p=s.x-a.minX,x=a.maxX-s.x,f=s.y-a.minY,m=a.maxY-s.y,D=Math.min(p,x,f,m);D===p?s.x=a.minX:D===x?s.x=a.maxX:D===f?s.y=a.minY:s.y=a.maxY,s._facingDirection=void 0}}},kzt=n=>{for(let e of n.chips){let a=e.width/2,s=e.height/2,l=0,p=0;for(let m of e.pins){let D=Math.abs(m.x-e.center.x),b=Math.abs(m.y-e.center.y);D>l&&(l=D),b>p&&(p=b)}let x=Math.max(a,l),f=Math.max(s,p);if(x>a||f>s){e.width=x*2,e.height=f*2;for(let m of e.pins)m._facingDirection=void 0}}};function CS(n,e,a,s={}){return{solverName:n,solverClass:e,getConstructorParams:a,onSolved:s.onSolved}}var uSe=class extends Wp{constructor(e){super();q(this,"mspConnectionPairSolver");q(this,"schematicTraceLinesSolver");q(this,"traceOverlapShiftSolver");q(this,"netLabelPlacementSolver");q(this,"startTimeOfPhase");q(this,"endTimeOfPhase");q(this,"timeSpentOnPhase");q(this,"firstIterationOfPhase");q(this,"inputProblem");q(this,"pipelineDef",[CS("mspConnectionPairSolver",fzt,()=>[{inputProblem:this.inputProblem}],{onSolved:e=>{}}),CS("schematicTraceLinesSolver",Czt,()=>[{mspConnectionPairs:this.mspConnectionPairSolver.mspConnectionPairs,dcConnMap:this.mspConnectionPairSolver.dcConnMap,globalConnMap:this.mspConnectionPairSolver.globalConnMap,inputProblem:this.inputProblem,chipMap:this.mspConnectionPairSolver.chipMap}],{onSolved:e=>{}}),CS("traceOverlapShiftSolver",Rzt,()=>[{inputProblem:this.inputProblem,inputTracePaths:this.schematicTraceLinesSolver.solvedTracePaths,globalConnMap:this.mspConnectionPairSolver.globalConnMap}],{onSolved:e=>{}}),CS("netLabelPlacementSolver",Izt,()=>[{inputProblem:this.inputProblem,inputTraceMap:this.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(this.schematicTraceLinesSolver.solvedTracePaths.map(e=>[e.mspPairId,e]))}],{onSolved:e=>{}})]);q(this,"currentPipelineStepIndex",0);this.inputProblem=this.cloneAndCorrectInputProblem(e),this.MAX_ITERATIONS=1e6,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={},this.firstIterationOfPhase={}}getConstructorParams(){return this.inputProblem}cloneAndCorrectInputProblem(e){let a=structuredClone({...e,_chipObstacleSpatialIndex:void 0});return kzt(a),jzt(a),a}_step(){let e=this.pipelineDef[this.currentPipelineStepIndex];if(!e){this.solved=!0;return}if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.endTimeOfPhase[e.solverName]=performance.now(),this.timeSpentOnPhase[e.solverName]=this.endTimeOfPhase[e.solverName]-this.startTimeOfPhase[e.solverName],e.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let a=e.getConstructorParams(this);this.activeSubSolver=new e.solverClass(...a),this[e.solverName]=this.activeSubSolver,this.timeSpentOnPhase[e.solverName]=0,this.startTimeOfPhase[e.solverName]=performance.now(),this.firstIterationOfPhase[e.solverName]=this.iterations}solveUntilPhase(e){for(;this.getCurrentPhase().toLowerCase()!==e.toLowerCase();)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let e=[F1(this.inputProblem),...this.pipelineDef.map(a=>this[a.solverName]?.visualize()).filter(Boolean).map((a,s)=>{for(let l of a.rects??[])l.step=s;for(let l of a.points??[])l.step=s;for(let l of a.circles??[])l.step=s;for(let l of a.texts??[])l.step=s;for(let l of a.lines??[])l.step=s;return a})];return e.length===1?e[0]:{points:e.flatMap(a=>a.points||[]),rects:e.flatMap(a=>a.rects||[]),lines:e.flatMap(a=>a.lines||[]),circles:e.flatMap(a=>a.circles||[]),texts:e.flatMap(a=>a.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}};var NBe=qr(vs(),1);var MBe=qr(vs(),1);var OBe=qr(vs(),1);Jo();ea();Jo();ea();ea();Yt();ea();ea();Jo();ea();function cSe(n,e,a,s){return Math.sqrt((a-n)**2+(s-e)**2)}var Nzt=n=>{let e=n.filter(p=>p.type==="pcb_port"),a=n.filter(p=>p.type==="pcb_smtpad"),s=n.filter(p=>p.type==="pcb_trace");function l(p,x={}){let f=x.traceWidth||0,m=e.find(D=>cSe(D.x,D.y,p.x,p.y)<.01);if(m)return m.pcb_port_id;if(x.isFirstOrLastPoint){let D=a.find(b=>{if(b.shape==="rect")return Math.abs(p.x-b.x)<b.width/2+f/2&&Math.abs(p.y-b.y)<b.height/2+f/2;if(b.shape==="circle")return cSe(p.x,p.y,b.x,b.y)<b.radius});if(D)return D.pcb_port_id??null}return null}for(let p of s)for(let x=0;x<p.route.length;x++){let f=p.route[x],m=x===0||x===p.route.length-1;if(f.route_type==="wire"){if(!f.start_pcb_port_id&&x===0){let D=l(f,{isFirstOrLastPoint:m,traceWidth:f.width});D&&(f.start_pcb_port_id=D)}if(!f.end_pcb_port_id&&x===p.route.length-1){let D=l(f,{isFirstOrLastPoint:m,traceWidth:f.width});D&&(f.end_pcb_port_id=D)}}}};function dSe(n){Nzt(n);let e=n.filter(x=>x.type==="source_trace"),a=n.filter(x=>x.type==="pcb_port"),s=[],l=Ku(n),p=new Map;for(let x of a)p.set(x.source_port_id,x);for(let x of e){let f=x.connected_source_port_ids;if(f.length<2)continue;let m=[],D=[];for(let w of f){let P=p.get(w);P?m.push(P):D.push(w)}if(m.length<2)continue;let b=m[0],E=l.getNetConnectedToId(b.pcb_port_id);l.getIdsConnectedToNet(E).filter(w=>n.some(P=>P.type==="pcb_trace"&&("pcb_trace_id"in P&&P.pcb_trace_id===w||"route_id"in P&&P.route_id===w))).length===0&&new Set(m.map(P=>P.pcb_component_id)).size>1&&s.push({type:"pcb_port_not_connected_error",message:`pcb_port_not_connected_error: Pcb ports [${m.map(P=>P.pcb_port_id).join(", ")}] are not connected together through the same net.`,error_type:"pcb_port_not_connected_error",pcb_port_ids:m.map(P=>P.pcb_port_id),pcb_component_ids:m.map(P=>P.pcb_component_id),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${x.source_trace_id}`})}return s}var Mzt=class{constructor({objects:n,getBounds:e,getId:a,CELL_SIZE:s}){q(this,"buckets");q(this,"objectsById");q(this,"getBounds");q(this,"getId");q(this,"CELL_SIZE",.4);q(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=e,this.getId=a??(()=>this._getNextId()),this.CELL_SIZE=s??this.CELL_SIZE;for(let l of n)this.addObject(l)}_getNextId(){return`${this._idCounter++}`}addObject(n){let e=this.getBounds(n),a=this.getId(n),s={...n,spatialIndexId:a};this.objectsById.set(a,s);let l=Math.floor(e.minX/this.CELL_SIZE),p=Math.floor(e.minY/this.CELL_SIZE),x=Math.floor(e.maxX/this.CELL_SIZE),f=Math.floor(e.maxY/this.CELL_SIZE);for(let m=l;m<=x;m++)for(let D=p;D<=f;D++){let b=`${m}x${D}`,E=this.buckets.get(b);E?E.push(s):this.buckets.set(b,[s])}}removeObject(n){let e=this.objectsById.get(n);if(!e)return!1;this.objectsById.delete(n);let a=this.getBounds(e),s=Math.floor(a.minX/this.CELL_SIZE),l=Math.floor(a.minY/this.CELL_SIZE),p=Math.floor(a.maxX/this.CELL_SIZE),x=Math.floor(a.maxY/this.CELL_SIZE);for(let f=s;f<=p;f++)for(let m=l;m<=x;m++){let D=`${f}x${m}`,b=this.buckets.get(D);if(b){let E=b.findIndex(A=>A.spatialIndexId===n);E!==-1&&(b.splice(E,1),b.length===0&&this.buckets.delete(D))}}return!0}getBucketKey(n,e){return`${Math.floor(n/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getObjectsInBounds(n,e=0){let a=[],s=new Set,l=Math.floor((n.minX-e)/this.CELL_SIZE),p=Math.floor((n.minY-e)/this.CELL_SIZE),x=Math.floor((n.maxX+e)/this.CELL_SIZE),f=Math.floor((n.maxY+e)/this.CELL_SIZE);for(let m=l;m<=x;m++)for(let D=p;D<=f;D++){let b=`${m}x${D}`,E=this.buckets.get(b)||[];for(let A of E){let B=A.spatialIndexId;s.has(B)||(s.add(B),a.push(A))}}return a}},_F=n=>n.type==="pcb_trace_segment"?{minX:Math.min(n.x1,n.x2),minY:Math.min(n.y1,n.y2),maxX:Math.max(n.x1,n.x2),maxY:Math.max(n.y1,n.y2)}:e4e([n]),FW=.1,Ozt=.15;var EW=.005;function Lzt(n){let e=new Set;for(let a of n.route)a.route_type==="wire"&&(a.start_pcb_port_id&&e.add(a.start_pcb_port_id),a.end_pcb_port_id&&e.add(a.end_pcb_port_id));return Array.from(e)}function vW(n){let e=new Set;for(let a of n)for(let s of Lzt(a))e.add(s);return Array.from(e)}var $zt=(n,e)=>{let a={x:n.x1,y:n.y1},s={x:n.x2,y:n.y2},l={x:e.x1,y:e.y1},p={x:e.x2,y:e.y2},x={x:s.x-a.x,y:s.y-a.y},f={x:p.x-l.x,y:p.y-l.y},m=x.x*x.x+x.y*x.y,D=f.x*f.x+f.y*f.y;if(m===0||D===0){if(m===0&&D===0)return{x:(a.x+l.x)/2,y:(a.y+l.y)/2};if(m===0){let de=Q0(((a.x-l.x)*f.x+(a.y-l.y)*f.y)/D,0,1),ce={x:l.x+de*f.x,y:l.y+de*f.y};return{x:(a.x+ce.x)/2,y:(a.y+ce.y)/2}}let J=Q0(((l.x-a.x)*x.x+(l.y-a.y)*x.y)/m,0,1),Q={x:a.x+J*x.x,y:a.y+J*x.y};return{x:(Q.x+l.x)/2,y:(Q.y+l.y)/2}}let b={x:a.x-l.x,y:a.y-l.y},E=x.x*x.x+x.y*x.y,A=x.x*f.x+x.y*f.y,B=x.x*b.x+x.y*b.y,w=f.x*f.x+f.y*f.y,P=f.x*b.x+f.y*b.y,N=E*w-A*A;if(N<1e-10)return zzt(a,s,l,p,x,f,m,D);let O=(A*P-w*B)/N,$=(E*P-A*B)/N;O=Q0(O,0,1),$=Q0($,0,1),$=(O*A+P)/w,$=Q0($,0,1),O=($*A-B)/E,O=Q0(O,0,1);let ee={x:a.x+O*x.x,y:a.y+O*x.y},X={x:l.x+$*f.x,y:l.y+$*f.y},te=ee.x-X.x,L=ee.y-X.y,K=Math.sqrt(te*te+L*L);return{x:(ee.x+X.x)/2,y:(ee.y+X.y)/2}},zzt=(n,e,a,s,l,p,x,f)=>{let m=((a.x-n.x)*l.x+(a.y-n.y)*l.y)/x;m=Q0(m,0,1);let D={x:n.x+m*l.x,y:n.y+m*l.y},b=((s.x-n.x)*l.x+(s.y-n.y)*l.y)/x;b=Q0(b,0,1);let E={x:n.x+b*l.x,y:n.y+b*l.y},A=((n.x-a.x)*p.x+(n.y-a.y)*p.y)/f;A=Q0(A,0,1);let B={x:a.x+A*p.x,y:a.y+A*p.y},w=((e.x-a.x)*p.x+(e.y-a.y)*p.y)/f;w=Q0(w,0,1);let P={x:a.x+w*p.x,y:a.y+w*p.y},O=[{pointA:D,pointB:a,distance:Math.sqrt((D.x-a.x)**2+(D.y-a.y)**2)},{pointA:E,pointB:s,distance:Math.sqrt((E.x-s.x)**2+(E.y-s.y)**2)},{pointA:n,pointB:B,distance:Math.sqrt((n.x-B.x)**2+(n.y-B.y)**2)},{pointA:e,pointB:P,distance:Math.sqrt((e.x-P.x)**2+(e.y-P.y)**2)}].reduce(($,ee)=>ee.distance<$.distance?ee:$);return{x:(O.pointA.x+O.pointB.x)/2,y:(O.pointA.y+O.pointB.y)/2}},Q0=(n,e,a)=>Math.max(e,Math.min(a,n)),qzt=n=>{if(n.type==="pcb_via"||n.type==="pcb_plated_hole"&&n.shape==="circle")return n.outer_diameter/2;if(n.type==="pcb_hole"&&n.hole_shape==="circle")return n.hole_diameter/2;if(n.type==="pcb_smtpad"&&n.shape==="circle")return n.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(n)}`)},lSe=(n,e)=>{let a={x:n.x1,y:n.y1},s={x:n.x2,y:n.y2},l=e.minX,p=e.minY,x=e.maxX,f=e.maxY;if(a.x===s.x&&a.y===s.y){let U=Math.max(l,Math.min(x,a.x)),J=Math.max(p,Math.min(f,a.y));return U===a.x&&J===a.y?{x:a.x,y:a.y}:{x:U,y:J}}let m=s.x-a.x,D=s.y-a.y,b=m!==0?(l-a.x)/m:Number.NEGATIVE_INFINITY,E=m!==0?(x-a.x)/m:Number.POSITIVE_INFINITY,A=D!==0?(p-a.y)/D:Number.NEGATIVE_INFINITY,B=D!==0?(f-a.y)/D:Number.POSITIVE_INFINITY,w=Math.max(Math.min(b,E),Math.min(A,B)),P=Math.min(Math.max(b,E),Math.max(A,B));if(w<=P&&P>=0&&w<=1){let U=Math.max(0,Math.min(1,w));return{x:a.x+U*m,y:a.y+U*D}}let N={x:Math.max(l,Math.min(x,a.x)),y:Math.max(p,Math.min(f,a.y))},O={x:Math.max(l,Math.min(x,s.x)),y:Math.max(p,Math.min(f,s.y))},$=(N.x-a.x)**2+(N.y-a.y)**2,ee=(O.x-s.x)**2+(O.y-s.y)**2,X=[{start:{x:l,y:p},end:{x,y:p}},{start:{x,y:p},end:{x,y:f}},{start:{x,y:f},end:{x:l,y:f}},{start:{x:l,y:f},end:{x:l,y:p}}],te=Math.min($,ee),L=$<=ee?N:O,K=(U,J,Q)=>Math.max(J,Math.min(Q,U));for(let U of X){let J={x:s.x-a.x,y:s.y-a.y},Q={x:U.end.x-U.start.x,y:U.end.y-U.start.y},de={x:a.x-U.start.x,y:a.y-U.start.y},ce=J.x*J.x+J.y*J.y,Te=J.x*Q.x+J.y*Q.y,Ne=J.x*de.x+J.y*de.y,Ve=Q.x*Q.x+Q.y*Q.y,et=Q.x*de.x+Q.y*de.y,ct=ce*Ve-Te*Te;if(Math.abs(ct)<1e-10)continue;let Mt=(Te*et-Ve*Ne)/ct,Dt=(ce*et-Te*Ne)/ct;Mt=K(Mt,0,1),Dt=K(Dt,0,1);let ot={x:a.x+Mt*J.x,y:a.y+Mt*J.y},it={x:U.start.x+Dt*Q.x,y:U.start.y+Dt*Q.y},qt=ot.x-it.x,It=ot.y-it.y,tr=qt*qt+It*It;tr<te&&(te=tr,L={x:(ot.x+it.x)/2,y:(ot.y+it.y)/2})}return L};function Uzt(n){return n.type==="pcb_trace_segment"?[n.layer]:n.type==="pcb_smtpad"?[n.layer]:n.type==="pcb_plated_hole"?Array.isArray(n.layers)?n.layers:[...jm]:n.type==="pcb_hole"?[...jm]:n.type==="pcb_via"?Array.isArray(n.layers)?n.layers:[...jm]:n.type==="pcb_keepout"?Array.isArray(n.layers)?n.layers:[]:[]}function pSe(n,{connMap:e}={}){let a=[];e??(e=Ku(n));let l=Na(n).pcb_trace.list().flatMap(w=>{let P=[];for(let N=0;N<w.route.length-1;N++){let O=w.route[N],$=w.route[N+1];O.route_type==="wire"&&$.route_type==="wire"&&O.layer===$.layer&&P.push({type:"pcb_trace_segment",pcb_trace_id:w.pcb_trace_id,_pcbTrace:w,thickness:"width"in O?O.width:"width"in $?$.width:Ozt,layer:O.layer,x1:O.x,y1:O.y,x2:$.x,y2:$.y})}return P}),p=Na(n).pcb_smtpad.list(),x=Na(n).pcb_plated_hole.list(),f=Na(n).pcb_hole.list(),m=Na(n).pcb_via.list(),D=Na(n).pcb_keepout.list(),b=[...l,...p,...x,...f,...m,...D],E=new Mzt({objects:b,getBounds:_F}),A=w=>zb(n,w),B=new Set;for(let w of l){let P=FW,N=_F(w),O=E.getObjectsInBounds(N,P+w.thickness/2);if(!(w.x1===w.x2&&w.y1===w.y2))for(let $ of O){if(!Uzt($).includes(w.layer))continue;if($.type==="pcb_trace_segment"){let L=$;if(w.layer!==L.layer||e.areIdsConnected(w.pcb_trace_id,L.pcb_trace_id))continue;let K=l5({x:w.x1,y:w.y1},{x:w.x2,y:w.y2},{x:L.x1,y:L.y1},{x:L.x2,y:L.y2})-w.thickness/2-L.thickness/2;if(K>FW-EW)continue;let U=`overlap_${w.pcb_trace_id}_${L.pcb_trace_id}`,J=`overlap_${L.pcb_trace_id}_${w.pcb_trace_id}`;if(B.has(U)||B.has(J))continue;B.add(U),a.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${A(w.pcb_trace_id)} overlaps with ${A(L.pcb_trace_id)} ${K<0?"(accidental contact)":`(gap: ${K.toFixed(3)}mm)`}`,pcb_trace_id:w.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:U,pcb_component_ids:[],center:$zt(w,L),pcb_port_ids:vW([w._pcbTrace,L._pcbTrace])});continue}let ee=f5($);if(e.areIdsConnected(w.pcb_trace_id,"pcb_trace_id"in $?$.pcb_trace_id:ee))continue;if($.type==="pcb_via"||$.type==="pcb_plated_hole"&&$.shape==="circle"||$.type==="pcb_hole"||$.type==="pcb_smtpad"&&$.shape==="circle"){let L=qzt($),U=d5({x:w.x1,y:w.y1},{x:w.x2,y:w.y2},{x:$.x,y:$.y,radius:L})-w.thickness/2;if(U>FW-EW)continue;let J=`overlap_${w.pcb_trace_id}_${ee}`;if(B.has(J))continue;B.add(J),a.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${A(w.pcb_trace_id)} overlaps with ${$.type} "${A(f5($))}" ${U<0?"(accidental contact)":`(gap: ${U.toFixed(3)}mm)`}`,pcb_trace_id:w.pcb_trace_id,center:lSe(w,_F($)),source_trace_id:"",pcb_trace_error_id:J,pcb_component_ids:["pcb_component_id"in $?$.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...vW([w._pcbTrace]),"pcb_port_id"in $?$.pcb_port_id:void 0].filter(Boolean)})}let te=Mb({x:w.x1,y:w.y1},{x:w.x2,y:w.y2},_F($))-w.thickness/2;if(te+EW<P){let L=`overlap_${w.pcb_trace_id}_${ee}`;if(B.has(L))continue;B.add(L),a.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${A(w.pcb_trace_id)} overlaps with ${$.type} "${A(f5($))}" ${te<0?"(accidental contact)":`(gap: ${te.toFixed(3)}mm)`}`,pcb_trace_id:w.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:L,pcb_component_ids:["pcb_component_id"in $?$.pcb_component_id:void 0].filter(Boolean),center:lSe(w,_F($)),pcb_port_ids:[...vW([w._pcbTrace]),"pcb_port_id"in $?$.pcb_port_id:void 0].filter(Boolean)})}}}return a}var CW=[{value:1e12,symbol:"T"},{value:1e9,symbol:"G"},{value:1e6,symbol:"M"},{value:1e3,symbol:"k"},{value:1,symbol:""},{value:.001,symbol:"m"},{value:1e-6,symbol:"\xB5"},{value:1e-9,symbol:"n"},{value:1e-12,symbol:"p"}];function js(n){if(n==null)return"";if(n===0)return"0";let e=Math.abs(n),a=CW.find(p=>{let x=e/p.value;return x>=1&&x<1e3})||CW[CW.length-1],l=(n/a.value).toPrecision(3);return l.includes(".")&&!/\.0+$/.test(l)&&(l=l.replace(/0+$/,"")),l=l.replace(/\.0+$/,""),`${l}${a.symbol}`}Yt();Xe();Hl();ea();var v9e=qr(Ic(),1);var HW=qr(vs(),1),Lg=qr(Ic(),1),omr=qr(Ic(),1);var A1=qr(E1(),1);var C9e=qr(E1(),1),_9e=qr(E1(),1);var A9e=qr(E1(),1);var R9e=qr(E1(),1);var S9e=qr(E1(),1),B9e=qr(Ic(),1);var pUt=Object.defineProperty,xUt=(n,e)=>{for(var a in e)pUt(n,a,{get:e[a],enumerable:!0})},gBe={};xUt(gBe,{Battery:()=>o9e,Board:()=>LBe,Breakout:()=>e9e,BreakoutPoint:()=>t9e,Capacitor:()=>$Be,Chip:()=>HS,Constraint:()=>KBe,Crystal:()=>x9e,Cutout:()=>MF,Diode:()=>qBe,FabricationNotePath:()=>JBe,FabricationNoteText:()=>ZBe,Footprint:()=>RBe,Fuse:()=>UBe,Group:()=>zg,Hole:()=>tK,Inductor:()=>l9e,Jumper:()=>VBe,Keepout:()=>qS,Led:()=>XBe,Mosfet:()=>h9e,Net:()=>JW,NetLabel:()=>r9e,NormalComponent:()=>Za,PcbTrace:()=>eK,PinHeader:()=>u9e,Pinout:()=>zBe,PlatedHole:()=>zS,Port:()=>Ii,Potentiometer:()=>d9e,PowerSource:()=>YBe,PrimitiveComponent:()=>ma,PushButton:()=>p9e,Renderable:()=>WW,Resistor:()=>WBe,Resonator:()=>c9e,SchematicBox:()=>y9e,SchematicCell:()=>E9e,SchematicRow:()=>F9e,SchematicTable:()=>b9e,SchematicText:()=>D9e,SilkscreenCircle:()=>n9e,SilkscreenLine:()=>s9e,SilkscreenPath:()=>QW,SilkscreenRect:()=>a9e,SilkscreenText:()=>YS,SmtPad:()=>$S,SolderJumper:()=>GBe,Subcircuit:()=>QBe,Switch:()=>m9e,TestPoint:()=>g9e,Trace:()=>zc,TraceHint:()=>aK,Transistor:()=>f9e,Via:()=>i9e,VoltageSource:()=>HBe});var fUt=(0,bBe.default)("tscircuit:renderable"),id=["ReactSubtreesRender","SourceNameDuplicateComponentRemoval","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","AssignFallbackProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SourceDesignRuleChecks","SimulationRender","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbLayout","PcbBoardAutoSize","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender"],hUt={PcbTraceRender:["PcbFootprintStringRender"]},mUt=0,WW=class{constructor(n){q(this,"renderPhaseStates");q(this,"shouldBeRemoved",!1);q(this,"children");q(this,"isPcbPrimitive",!1);q(this,"isSchematicPrimitive",!1);q(this,"_renderId");q(this,"_currentRenderPhase",null);q(this,"_asyncEffects",[]);q(this,"parent",null);this._renderId=`${mUt++}`,this.children=[],this.renderPhaseStates={};for(let e of id)this.renderPhaseStates[e]={initialized:!1,dirty:!1}}_markDirty(n){this.renderPhaseStates[n].dirty=!0;let e=id.indexOf(n);for(let a=e+1;a<id.length;a++)this.renderPhaseStates[id[a]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(n)}_queueAsyncEffect(n,e){let a={promise:e(),phase:this._currentRenderPhase,effectName:n,complete:!1};this._asyncEffects.push(a),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:n,componentDisplayName:this.getString(),phase:a.phase}),a.promise.then(()=>{a.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:n,componentDisplayName:this.getString(),phase:a.phase})}).catch(s=>{console.error(`Async effect error in ${a.phase} "${n}":
|
|
1038
|
-
${s.stack}`),a.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:n,componentDisplayName:this.getString(),phase:a.phase,error:s.toString()})})}_emitRenderLifecycleEvent(n,e){fUt(`${n}:${e} ${this.getString()}`);let a=`renderable:renderLifecycle:${n}:${e}`,s={renderId:this._renderId,componentDisplayName:this.getString(),type:a};"root"in this&&this.root&&(this.root.emit(a,s),this.root.emit("renderable:renderLifecycle:anyEvent",{...s,type:a}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(n=>!n.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(n){for(let e of this._asyncEffects)if(!e.complete&&e.phase===n)return!0;for(let e of this.children)if(e._hasIncompleteAsyncEffectsInSubtreeForPhase(n))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(n=>n.getRenderGraph())}}runRenderCycle(){for(let n of id)this.runRenderPhaseForChildren(n),this.runRenderPhase(n)}runRenderPhase(n){this._currentRenderPhase=n;let e=this.renderPhaseStates[n],a=e.initialized,s=e.dirty;if(!a&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&a){this._emitRenderLifecycleEvent(n,"start"),this?.[`remove${n}`]?.(),e.initialized=!1,e.dirty=!1,this._emitRenderLifecycleEvent(n,"end");return}let l=id.indexOf(n)-1;if(l>=0){let x=id[l];if(this._asyncEffects.filter(m=>m.phase===x).some(m=>!m.complete))return}let p=hUt[n]||[];for(let x of p)if(this._hasIncompleteAsyncEffectsInSubtreeForPhase(x))return;if(this._emitRenderLifecycleEvent(n,"start"),a){s&&(this?.[`update${n}`]?.(),e.dirty=!1),this._emitRenderLifecycleEvent(n,"end");return}e.dirty=!1,this?.[`doInitial${n}`]?.(),e.initialized=!0,this._emitRenderLifecycleEvent(n,"end")}runRenderPhaseForChildren(n){for(let e of this.children)e.runRenderPhaseForChildren(n),e.runRenderPhase(n)}renderError(n){throw typeof n=="string"?new Error(n):new Error(JSON.stringify(n,null,2))}},LS={},FBe=n=>{let e=Object.fromEntries(Object.entries(n).map(([a,s])=>[a.toLowerCase(),s]));Object.assign(LS,n),Object.assign(LS,e)},gUt=class extends Error{constructor(n,e,a){let s,l=Object.keys(a).filter(m=>m!=="_errors"),p=[],x=e.pinLabels;if(x)for(let[m,D]of Object.entries(x)){let b=Array.isArray(D)?D:[D];for(let E of b)typeof E=="string"&&(E.startsWith(" ")||E.endsWith(" "))&&p.push(`pinLabels.${m} ("${E}" has leading or trailing spaces)`)}let f=l.map(m=>m==="pinLabels"&&p.length>0?p.join(", "):a[m]._errors[0]?`${m} (${a[m]._errors[0]})`:`${m} (${JSON.stringify(a[m])})`).join(", ");"name"in e?s=`Invalid props for ${n} "${e.name}": ${f}`:"footprint"in e&&typeof e.footprint=="string"?s=`Invalid props for ${n} (unnamed ${e.footprint} component): ${f}`:s=`Invalid props for ${n} (unnamed): ${f}`,super(s),this.componentName=n,this.originalProps=e,this.formattedError=a}};function jW(n,e){let a=e.match(/^#(\w+)/);if(a)return n.props.id===a[1];let s=e.match(/^\.(\w+)/);if(s)return n.isMatchingNameOrAlias(s[1]);let[l,...p]=e.split(/(?=[#.[])/);return l==="pin"&&(l="port"),l&&l!=="*"&&n.lowercaseComponentName!==l.toLowerCase()?!1:p.every(x=>{if(x.startsWith("#"))return n.props.id===x.slice(1);if(x.startsWith("."))return n.isMatchingNameOrAlias(x.slice(1));let f=x.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!f)return!0;let[,m,D]=f;return n.props[m].toString()===D})}var KW={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 s=n._parsedProps[e];return typeof s=="string"?s:s!=null?String(s):null}if(e in n){let s=n[e];return typeof s=="string"?s:s!=null?String(s):null}let a=n._attributeLowerToCamelNameMap;if(a){let s=a[e];if(s&&s in n){let l=n[s];return typeof l=="string"?l:l!=null?String(l):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 a=n._attributeLowerToCamelNameMap;if(a){let s=a[e];if(s&&s 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,a=e.indexOf(n);return a>0?e[a-1]:null},getText:()=>"",removeSubsets:n=>n.filter((e,a)=>!n.some((s,l)=>a!==l&&s!==e&&s.getDescendants().includes(e))),existsOne:(n,e)=>e.some(n),findAll:(n,e)=>{let a=[],s=l=>{n(l)&&a.push(l);for(let p of l.children)s(p)};for(let l of e)s(l);return a},findOne:(n,e)=>{for(let a of e){if(n(a))return a;let s=a.children;if(s.length>0){let l=KW.findOne(n,s);if(l)return l}}return null},equals:(n,e)=>n._renderId===e._renderId,isHovered:n=>!1,isVisited:n=>!1,isActive:n=>!1},DUt={...KW,getChildren:n=>n.children.filter(e=>!e.isSubcircuit)},KSe={...KW,getChildren:n=>n.children.filter(e=>e.isSubcircuit)},JSe=n=>{if(/net\.[^\s>]*\./.test(n))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(n))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(n)){let e=n.match(/net\.([^ >]+)/),a=e?e[1]:"";throw new Error(`Net name "${a}" cannot start with a number, try using a prefix like "VBUS1"`)}return n.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(e,a,s,l)=>{let p=/^\d+$/.test(l)?`pin${l}`:l;return`${a}.${s} > .${p}`}).trim()},kW={adapter:DUt,cacheResults:!0},ma=class extends WW{constructor(e){super(e);q(this,"parent",null);q(this,"children");q(this,"childrenPendingRemoval");q(this,"props");q(this,"_parsedProps");q(this,"externallyAddedAliases");q(this,"isPrimitiveContainer",!1);q(this,"canHaveTextChildren",!1);q(this,"source_group_id",null);q(this,"source_component_id",null);q(this,"schematic_component_id",null);q(this,"pcb_component_id",null);q(this,"cad_component_id",null);q(this,"fallbackUnassignedName");q(this,"_cachedSelectAllQueries",new Map);q(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=e??{},this.externallyAddedAliases=[];let s=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(e??{});if(s.success)this._parsedProps=s.data;else throw new gUt(this.lowercaseComponentName,this.props,s.error.format())}get config(){return{componentName:"",zodProps:C.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(e){let a=this;for(;a;){if(a._parsedProps&&e in a._parsedProps)return a._parsedProps[e];a=a.parent}if(this.root?.platform&&e in this.root.platform)return this.root.platform[e]}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 a=this.config.zodProps.parse({...this.props,...e}),s=this.props;this.props=a,this._parsedProps=this.config.zodProps.parse(e),this.onPropsChange({oldProps:s,newProps:a,changedProps:Object.keys(e)}),this.parent?.onChildChanged?.(this)}computePcbPropsTransform(){let{_parsedProps:e}=this;return Ts(ka(e.pcbX??0,e.pcbY??0),Xf((e.pcbRotation??0)*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let{_parsedProps:e}=this,a=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(a&&this.props.pcbX===void 0&&this.props.pcbY===void 0)return Ts(this.parent?._computePcbGlobalTransformBeforeLayout()??_i(),Ts(ka(a.x,a.y),Xf((e.pcbRotation??0)*Math.PI/180)));if(this.isPcbPrimitive){let s=this.getPrimitiveContainer();if(s){let l=s._parsedProps.layer==="bottom",p=s._getGlobalPcbPositionBeforeLayout();if(l){let x=Ts(ka(p.x,p.y),Yq(),ka(-p.x,-p.y));return Ts(this.parent?._computePcbGlobalTransformBeforeLayout()??_i(),Yq(),this.computePcbPropsTransform())}}}return Ts(this.parent?._computePcbGlobalTransformBeforeLayout()??_i(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let e=this.getPrimitiveContainer(),a=e?e._parsedProps.layer==="bottom":!1;return{isFlipped:a,maybeFlipLayer:l=>a?l==="top"?"bottom":"top":l}}_setPositionFromLayout(e){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:e}=this;return Ts(ka(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){let e=this._getSchematicGlobalManualPlacementTransform(this);return e||Ts(this.parent?.computeSchematicGlobalTransform?.()??_i(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:e}=this,a=this.config.schematicSymbolName,s={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},l=e.schOrientation!==void 0?s[e.schOrientation]:e.schRotation;if(l===void 0&&(l=0),l=l%360,l<0&&(l+=360),e.schRotation!==void 0&&l%90!==0)throw new Error(`Schematic rotation ${e.schRotation} is not supported for ${this.componentName}`);let p=`${a}_horz`,x=`${a}_vert`,f=`${a}_up`,m=`${a}_down`,D=`${a}_left`,b=`${a}_right`;if(b in Ps&&l===0)return b;if(f in Ps&&l===90)return f;if(D in Ps&&l===180)return D;if(m in Ps&&l===270)return m;if(p in Ps&&(l===0||l===180))return p;if(x in Ps&&(l===90||l===270))return x;if(a in Ps)return a}_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?Ps[e]??null:null}_getPcbManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let a=this.props.manualEdits;if(!a)return null;let s=a?.pcb_placements;if(!s)return null;for(let l of s)if(jW(e,l.selector)||e.props.name===l.selector)return rs(this._computePcbGlobalTransformBeforeLayout(),l.center);return null}_getSchematicManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let a=this.props.manualEdits;if(!a)return null;let s=a.schematic_placements;if(!s)return null;for(let l of s)if(jW(e,l.selector)||e.props.name===l.selector)return rs(this.computeSchematicGlobalTransform(),l.center);return null}_getSchematicGlobalManualPlacementTransform(e){let a=this.getSubcircuit()?._parsedProps.manualEdits;if(!a)return null;for(let s of a.schematic_placements??[])if((jW(e,s.selector)||e.props.name===s.selector)&&s.relative_to==="group_center")return Ts(this.parent?._computePcbGlobalTransformBeforeLayout()??_i(),ka(s.center.x,s.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return rs(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return rs(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(e){this.parent=e}onPropsChange(e){}onChildChanged(e){this.parent?.onChildChanged?.(e)}add(e){let a=e.__text;if(typeof a=="string"){if(this.canHaveTextChildren||a.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${a}"`)}if(Object.keys(e).length!==0){if(this.lowercaseComponentName==="board"&&e.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");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 a of e)this.add(a)}remove(e){this.children=this.children.filter(a=>a!==e),this.childrenPendingRemoval.push(e),e.shouldBeRemoved=!0}getSubcircuitSelector(){let e=this.name,a=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?a:`${this.parent.getSubcircuitSelector()} > ${a}`}getFullPathSelector(){let e=this.name,a=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName,s=this.parent?.getFullPathSelector?.();return s?`${s} > ${a}`:a}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(e){return this.getNameAndAliases().includes(e)}isMatchingAnyOf(e){return this.getNameAndAliases().some(a=>e.map(s=>s.toString()).includes(a))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(e){let a=[this.componentName,this.lowercaseComponentName],s=[this.name].filter(Boolean),l=e.trim().split(/\> /)[0],p=l[0];return l.length>1?!1:!!(e==="*"||e[0]==="#"&&e.slice(1)===this.props.id||e[0]==="."&&s.includes(e.slice(1))||/^[a-zA-Z0-9_]/.test(p)&&a.includes(p))}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 a of e){let s=a.parent?.getNameAndAliases(),l=a.getNameAndAliases();if(s)for(let p of s)for(let x of l){let f=[`.${p} > .${x}`,`.${p} .${x}`];for(let m of f){let D=this._cachedSelectAllQueries.get(m);D?D.push(a):this._cachedSelectAllQueries.set(m,[a])}}}for(let[a,s]of this._cachedSelectAllQueries.entries())s.length===1&&this._cachedSelectOneQueries.set(a,s[0])}selectAll(e){if(this._cachedSelectAllQueries.has(e))return this._cachedSelectAllQueries.get(e);let a=JSe(e),s=aY(a,this,kW);if(s.length>0)return this._cachedSelectAllQueries.set(e,s),s;let[l,...p]=a.split(" "),x=GR(l,this,{adapter:KSe});if(!x)return[];let f=x.selectAll(p.join(" "));return this._cachedSelectAllQueries.set(e,f),f}selectOne(e,a){if(this._cachedSelectOneQueries.has(e))return this._cachedSelectOneQueries.get(e);let s=JSe(e);a?.port&&(a.type="port");let l=null;if(a?.type&&(l=aY(s,this,kW).find(D=>D.lowercaseComponentName===a.type)),l??(l=GR(s,this,kW)),l)return this._cachedSelectOneQueries.set(e,l),l;let[p,...x]=s.split(" "),f=GR(p,this,{adapter:KSe});return f?(l=f.selectOne(x.join(" "),a),this._cachedSelectOneQueries.set(e,l),l):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 a of this.children)e.push(a),e.push(...a.getDescendants());return e}getSelectableDescendants(){let e=[];for(let a of this.children)a.isSubcircuit?e.push(a):(e.push(a),e.push(...a.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);this.root?.db.pcb_placement_error.insert(e)}getString(){let{lowercaseComponentName:e,_parsedProps:a,parent:s}=this;return a?.pinNumber!==void 0&&s?.props?.name&&a?.name?`<${e}#${this._renderId}(pin:${a.pinNumber} .${s?.props.name}>.${a.name}) />`:s?.props?.name&&a?.name?`<${e}#${this._renderId}(.${s?.props.name}>.${a?.name}) />`:a?.from&&a?.to?`<${e}#${this._renderId}(from:${a.from} to:${a?.to}) />`:a?.name?`<${e}#${this._renderId} name=".${a?.name}" />`:a?.portHints?`<${e}#${this._renderId}(${a.portHints.map(l=>`.${l}`).join(", ")}) />`:`<${e}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},yUt=class extends ma{constructor(n,e){super(n),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:n.pcbX,pcbY:n.pcbY,schX:n.schX,schY:n.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:C.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 bUt(n,e){return new yUt(n,e)}function FUt(n,e){let a=n;return a.__tsci={...e},n}var EUt={supportsMutation:!0,createInstance(n,e){let a=LS[n];if(!a)throw Object.keys(LS).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 FUt(new a(e),{})}catch(s){return bUt({...e,componentType:n},s)}},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:()=>MS.DefaultEventPriority,getCurrentUpdatePriority:()=>MS.DefaultEventPriority,resolveUpdatePriority:()=>MS.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},jS=(0,yBe.default)(EUt),EBe=n=>{let e={children:[],props:{name:"$root"},add(p){p.parent=this,this.children.push(p)},computePcbGlobalTransform(){return _i()}},a=[],s=jS.createContainer(e,0,null,!1,null,"tsci",p=>{console.log("Error in createContainer"),console.error(p),a.push(p)},null);if(jS.updateContainerSync(n,s,null,()=>{}),jS.flushSyncWork(),a.length>0)throw a[0];let l=jS.getPublicRootInstance(s);return l||e.children[0]},OF=(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 a in e)if((Array.isArray(e[a])?e[a]:[e[a]]).includes(n))return Number(a.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${n}"`)},vUt=(n,e)=>{if(!n)return;let a={},s={};for(let[l,p]of Object.entries(n)){let x=OF(l,e);s[x]={...s[x],...p}}for(let[l,p]of Object.entries(s)){let x=`pin${l}`;a[x]={bottom_margin:p.bottomMargin,left_margin:p.leftMargin,right_margin:p.rightMargin,top_margin:p.topMargin}}return a},CUt=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 vBe(n){let e=[];for(let a=0;a<n.length-1;a++)e.push([n[a],n[a+1]]);return e}var _Ut=C.object({name:C.string().refine(n=>!/[+-]/.test(n),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),JW=class extends ma{constructor(){super(...arguments);q(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:_Ut}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=a.name.startsWith("GND"),l=a.name.startsWith("V"),p=e.source_net.insert({name:a.name,member_source_group_ids:[],is_ground:s,is_power:l,is_positive_voltage_source:l});this.source_net_id=p.source_net_id}doInitialSourceParentAttachment(){let e=this.getSubcircuit();if(!e)return;let{db:a}=this.root;a.source_net.update(this.source_net_id,{subcircuit_id:e.subcircuit_id})}getAllConnectedPorts(){let e=this.getSubcircuit().selectAll("port"),a=[];for(let s of e){let l=s._getDirectlyConnectedTraces();for(let p of l)if(p._isExplicitlyConnectedToNet(this)){a.push(s);break}}return a}_getAllDirectlyConnectedTraces(){let e=this.getSubcircuit().selectAll("trace"),a=[];for(let s of e)s._isExplicitlyConnectedToNet(this)&&a.push(s);return a}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getAllDirectlyConnectedTraces().filter(x=>(x._portsRoutedOnPcb?.length??0)>0),l=[];for(let x of s){let f=x._portsRoutedOnPcb,m=l.find(D=>f.some(b=>D.ports.includes(b)));if(!m){l.push({ports:[...f],traces:[x]});continue}m.traces.push(x),m.ports.push(...f)}if(l.length===0)return;let p=vBe(l);for(let[x,f]of p){let m=x.ports.map(O=>O._getGlobalPcbPositionBeforeLayout()),D=f.ports.map(O=>O._getGlobalPcbPositionBeforeLayout()),b=1/0,E=[-1,-1];for(let O=0;O<m.length;O++){let $=m[O];for(let ee=0;ee<D.length;ee++){let X=D[ee],te=Math.sqrt(($.x-X.x)**2+($.y-X.y)**2);te<b&&(b=te,E=[O,ee])}}let A=x.ports[E[0]],B=f.ports[E[1]],w=e.toArray().filter(O=>O.type==="pcb_smtpad"||O.type==="pcb_trace"||O.type==="pcb_plated_hole"||O.type==="pcb_hole"||O.type==="source_port"||O.type==="pcb_port"),{solution:P}=T_e(w.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[A.source_port_id,B.source_port_id]}])),N=P[0];if(!N){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[A.pcb_component_id,B.pcb_component_id].filter(Boolean),pcb_port_ids:[A.pcb_port_id,B.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(N)}}renderError(e){if(typeof e=="string")return super.renderError(e);this.root?.db.pcb_trace_error.insert(e)}},ZW=(n,e)=>{for(let a of e)if(typeof a=="string"&&a.startsWith("net.")){if(/net\.[^\s>]*\./.test(a))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(a))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(a)){let l=a.split("net.")[1];throw new Error(`Net name "${l}" cannot start with a number, try using a prefix like "VBUS1"`)}let s=n.getSubcircuit();if(!s.selectOne(a)){let l=new JW({name:a.split("net.")[1]});s.add(l)}}},$S=class extends ma{constructor(){super(...arguments);q(this,"pcb_smtpad_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:tAe}}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==="polygon"){let a=e.points,s=a.map(D=>D.x),l=a.map(D=>D.y),p=Math.min(...s),x=Math.max(...s),f=Math.min(...l),m=Math.max(...l);return{width:x-p,height:m-f}}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 a of e)if(a.isMatchingAnyOf(this.props.portHints)){this.matchedPort=a,a.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this;if(!a.portHints)return;let s=this.getPrimitiveContainer(),l=this.getSubcircuit(),p=this._getGlobalPcbPositionBeforeLayout(),x=s?._getGlobalPcbPositionBeforeLayout(),f=QA(this._computePcbGlobalTransformBeforeLayout()),m=Math.abs(f.rotation.angle*(180/Math.PI)-90)%180<.01,{maybeFlipLayer:D}=this._getPcbPrimitiveFlippedHelpers(),b=s?._parsedProps.pcbRotation??0,E=null,A=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;a.shape==="circle"?(E=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"circle",radius:a.radius,port_hints:a.portHints.map(B=>B.toString()),x:p.x,y:p.y,subcircuit_id:l?.subcircuit_id??void 0}),e.pcb_solder_paste.insert({layer:E.layer,shape:"circle",radius:E.radius*.7,x:E.x,y:E.y,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):a.shape==="rect"?(E=b===0||m?e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"rect",width:m?a.height:a.width,height:m?a.width:a.height,port_hints:a.portHints.map(B=>B.toString()),x:p.x,y:p.y,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):e.pcb_smtpad.insert({pcb_component_id:A,layer:D(a.layer??"top"),shape:"rotated_rect",width:a.width,height:a.height,x:p.x,y:p.y,ccw_rotation:b,port_hints:a.portHints.map(B=>B.toString()),subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),E.shape==="rect"&&e.pcb_solder_paste.insert({layer:D(a.layer??"top"),shape:"rect",width:E.width*.7,height:E.height*.7,x:E.x,y:E.y,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),E.shape==="rotated_rect"&&e.pcb_solder_paste.insert({layer:D(a.layer??"top"),shape:"rotated_rect",width:E.width*.7,height:E.height*.7,x:E.x,y:E.y,ccw_rotation:b,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):a.shape==="polygon"&&(E=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"polygon",points:a.points.map(B=>({x:B.x+p.x,y:B.y+p.y})),port_hints:a.portHints.map(B=>B.toString()),subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})),E&&(this.pcb_smtpad_id=E.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,a=e.pcb_smtpad.get(this.pcb_smtpad_id);if(a.shape==="rect")return{center:{x:a.x,y:a.y},bounds:{left:a.x-a.width/2,top:a.y+a.height/2,right:a.x+a.width/2,bottom:a.y-a.height/2},width:a.width,height:a.height};if(a.shape==="rotated_rect"){let s=a.ccw_rotation*Math.PI/180,l=Math.cos(s),p=Math.sin(s),x=a.width/2,f=a.height/2,m=Math.abs(x*l)+Math.abs(f*p),D=Math.abs(x*p)+Math.abs(f*l);return{center:{x:a.x,y:a.y},bounds:{left:a.x-m,right:a.x+m,top:a.y-D,bottom:a.y+D},width:m*2,height:D*2}}if(a.shape==="circle")return{center:{x:a.x,y:a.y},bounds:{left:a.x-a.radius,top:a.y-a.radius,right:a.x+a.radius,bottom:a.y+a.radius},width:a.radius*2,height:a.radius*2};if(a.shape==="polygon"){let s=a.points,l=s.map(b=>b.x),p=s.map(b=>b.y),x=Math.min(...l),f=Math.max(...l),m=Math.min(...p),D=Math.max(...p);return{center:{x:(x+f)/2,y:(m+D)/2},bounds:{left:x,top:D,right:f,bottom:m},width:f-x,height:D-m}}throw new Error(`circuitJson bounds calculation not implemented for shape "${a.shape}"`)}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_smtpad.update(this.pcb_smtpad_id,{x:e.x,y:e.y});let s=a.pcb_solder_paste.list().find(l=>l.pcb_smtpad_id===this.pcb_smtpad_id);a.pcb_solder_paste.update(s?.pcb_solder_paste_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}},QW=class extends ma{constructor(){super(...arguments);q(this,"pcb_silkscreen_path_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:wAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenPath. Must be "top" or "bottom".`);let p=this._computePcbGlobalTransformBeforeLayout(),x=this.getSubcircuit(),f=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=e.pcb_silkscreen_path.insert({pcb_component_id:f,layer:l,route:a.route.map(D=>{let b=rs(p,{x:D.x,y:D.y});return{...D,x:b.x,y:b.y}}),stroke_width:a.strokeWidth??.1,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=m.pcb_silkscreen_path_id}_setPositionFromLayout(e){let{db:a}=this.root,{_parsedProps:s}=this,l=a.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!l)return;let p=0,x=0;for(let b of l.route)p+=b.x,x+=b.y;p/=l.route.length,x/=l.route.length;let f=e.x-p,m=e.y-x,D=l.route.map(b=>({...b,x:b.x+f,y:b.y+m}));a.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:D})}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let a=1/0,s=-1/0,l=1/0,p=-1/0;for(let x of e.route)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),p=Math.max(p,x.y);return{width:s-a,height:p-l}}},AUt=C.object({route:C.array(MA),source_trace_id:C.string().optional()}),eK=class extends ma{constructor(){super(...arguments);q(this,"pcb_trace_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:AUt}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer(),l=this.getSubcircuit(),{maybeFlipLayer:p}=this._getPcbPrimitiveFlippedHelpers(),x=this._computePcbGlobalTransformBeforeLayout(),f=a.route.map(D=>{let{x:b,y:E,...A}=D,B=rs(x,{x:b,y:E});return D.route_type==="wire"&&D.layer?{...B,...A,layer:p(D.layer)}:{...B,...A}}),m=e.pcb_trace.insert({pcb_component_id:s.pcb_component_id,source_trace_id:a.source_trace_id,route:f,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=m.pcb_trace_id}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let a=1/0,s=-1/0,l=1/0,p=-1/0;for(let x of e.route)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),p=Math.max(p,x.y),x.route_type==="wire"&&(a=Math.min(a,x.x-x.width/2),s=Math.max(s,x.x+x.width/2),l=Math.min(l,x.y-x.width/2),p=Math.max(p,x.y+x.width/2));return a===1/0||s===-1/0||l===1/0||p===-1/0?{width:0,height:0}:{width:s-a,height:p-l}}},zS=class extends ma{constructor(){super(...arguments);q(this,"pcb_plated_hole_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:G_e}}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};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_plated_hole.get(this.pcb_plated_hole_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y+s.height/2,right:a.x+s.width/2,bottom:a.y-s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.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 a of e)if(a.isMatchingAnyOf(this.props.portHints)){this.matchedPort=a,a.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,p=this.getSubcircuit();if(a.shape==="circle"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:a.outerDiameter,hole_diameter:a.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:a.outerDiameter/2,x:s.x,y:s.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:a.outerDiameter/2,x:s.x,y:s.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(a.shape==="pill"&&a.rectPad){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:a.outerWidth,outer_height:a.outerHeight,hole_width:a.holeWidth,hole_height:a.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:a.pcbRotation??0,rect_ccw_rotation:a.pcbRotation??0,rect_pad_width:a.outerWidth,rect_pad_height:a.outerHeight});this.pcb_plated_hole_id=x.pcb_plated_hole_id}else if(a.shape==="pill"||a.shape==="oval"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:a.outerWidth,outer_height:a.outerHeight,hole_width:a.holeWidth,hole_height:a.holeHeight,shape:a.shape,port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:a.shape,width:a.outerWidth,height:a.outerHeight,x:s.x,y:s.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:a.shape,width:a.outerWidth,height:a.outerHeight,x:s.x,y:s.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(a.shape==="circular_hole_with_rect_pad"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:a.holeDiameter,rect_pad_width:a.rectPadWidth,rect_pad_height:a.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id}else if(a.shape==="pill_hole_with_rect_pad"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:a.holeWidth,hole_height:a.holeHeight,rect_pad_width:a.rectPadWidth,rect_pad_height:a.rectPadHeight,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},qS=class extends ma{constructor(){super(...arguments);q(this,"pcb_keepout_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:EAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let e=this.getSubcircuit(),{db:a}=this.root,{_parsedProps:s}=this,l=this._getGlobalPcbPositionBeforeLayout(),p=QA(this._computePcbGlobalTransformBeforeLayout()),x=Math.abs(p.rotation.angle*(180/Math.PI)-90)%180<.01,f=null;s.shape==="circle"?f=a.pcb_keepout.insert({layers:["top"],shape:"circle",radius:s.radius,center:{x:l.x,y:l.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0}):s.shape==="rect"&&(f=a.pcb_keepout.insert({layers:["top"],shape:"rect",...x?{width:s.height,height:s.width}:{width:s.width,height:s.height},center:{x:l.x,y:l.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0})),f&&(this.pcb_keepout_id=f.pcb_keepout_id)}},tK=class extends ma{constructor(){super(...arguments);q(this,"pcb_hole_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:rAe}}getPcbSize(){let{_parsedProps:e}=this;return{width:e.diameter,height:e.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=this._getGlobalPcbPositionBeforeLayout(),p=e.pcb_hole.insert({hole_shape:"circle",hole_diameter:a.diameter,x:l.x,y:l.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:s?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=p.pcb_hole_id}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_hole.get(this.pcb_hole_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y-s.height/2,right:a.x+s.width/2,bottom:a.y+s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_hole.update(this.pcb_hole_id,{x:e.x,y:e.y})}},YS=class extends ma{constructor(){super(...arguments);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:BAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer(),l=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:p}=this._getPcbPrimitiveFlippedHelpers(),x=this.getSubcircuit(),f=new Set(a.layers);a.layer&&f.add(a.layer);let m=f.size>0?Array.from(f):["top"];for(let D of m)e.pcb_silkscreen_text.insert({anchor_alignment:a.anchorAlignment,anchor_position:{x:l.x,y:l.y},font:a.font??"tscircuit2024",font_size:a.fontSize??1,layer:p(D),text:a.text??"",ccw_rotation:a.pcbRotation,pcb_component_id:s.pcb_component_id,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:e}=this,a=e.fontSize??1,l=(e.text??"").length*a,p=a;return{width:l*a,height:p*a}}},MF=class extends ma{constructor(){super(...arguments);q(this,"pcb_cutout_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:eAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=this.getGroup()?.pcb_group_id??void 0,p=this._getGlobalPcbPositionBeforeLayout(),f=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,m;if(a.shape==="rect"){let D=typeof f=="string"?parseInt(f.replace("deg",""),10):f,b=Math.abs(D%180)===90,E={shape:"rect",center:p,width:b?a.height:a.width,height:b?a.width:a.height,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(E)}else if(a.shape==="circle"){let D={shape:"circle",center:p,radius:a.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(D)}else if(a.shape==="polygon"){let D=this._computePcbGlobalTransformBeforeLayout(),E={shape:"polygon",points:a.points.map(A=>rs(D,A)),subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(E)}m&&(this.pcb_cutout_id=m.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 a=1/0,s=-1/0,l=1/0,p=-1/0;for(let x of e.points)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),p=Math.max(p,x.y);return{width:s-a,height:p-l}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,a=e.pcb_cutout.get(this.pcb_cutout_id);if(!a)return super._getPcbCircuitJsonBounds();if(a.shape==="rect")return{center:a.center,bounds:{left:a.center.x-a.width/2,top:a.center.y+a.height/2,right:a.center.x+a.width/2,bottom:a.center.y-a.height/2},width:a.width,height:a.height};if(a.shape==="circle")return{center:a.center,bounds:{left:a.center.x-a.radius,top:a.center.y+a.radius,right:a.center.x+a.radius,bottom:a.center.y-a.radius},width:a.radius*2,height:a.radius*2};if(a.shape==="polygon"){if(a.points.length===0)return super._getPcbCircuitJsonBounds();let s=1/0,l=-1/0,p=1/0,x=-1/0;for(let f of a.points)s=Math.min(s,f.x),l=Math.max(l,f.x),p=Math.min(p,f.y),x=Math.max(x,f.y);return{center:{x:(s+l)/2,y:(p+x)/2},bounds:{left:s,top:x,right:l,bottom:p},width:l-s,height:x-p}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(e){if(!this.pcb_cutout_id)return;let{db:a}=this.root,s=a.pcb_cutout.get(this.pcb_cutout_id);if(s){if(s.shape==="rect"||s.shape==="circle")a.pcb_cutout.update(this.pcb_cutout_id,{...s,center:e});else if(s.shape==="polygon"){let l=this._getPcbCircuitJsonBounds().center,p=e.x-l.x,x=e.y-l.y,f=s.points.map(m=>({x:m.x+p,y:m.y+x}));a.pcb_cutout.update(this.pcb_cutout_id,{...s,points:f})}}}},RUt=({elm:n,pinLabels:e,layer:a,readableRotation:s,anchorAlignment:l})=>{let p=n.text.replace(/[{}]/g,"").toLowerCase(),x=p;if(Array.isArray(e)){let f=parseInt(p.replace(/[^\d]/g,""),10)-1;x=String(e[f]??p)}else typeof e=="object"&&(x=String(e[p]??p));return new YS({anchorAlignment:l||"center",text:x??p,layer:a||"top",fontSize:n.font_size+.2,pcbX:isNaN(n.anchor_position.x)?0:n.anchor_position.x,pcbY:n.anchor_position.y,pcbRotation:s??0})},SUt=(n,e)=>((-parseInt(n||"0",10)+(e??0))%360+360)%360,zW=({componentName:n,componentRotation:e,footprint:a,pinLabels:s,pcbPinLabels:l},p)=>{let x=[];for(let f of p)if(f.type==="pcb_smtpad"&&f.shape==="rect")x.push(new $S({pcbX:f.x,pcbY:f.y,layer:f.layer,shape:"rect",height:f.height,width:f.width,portHints:f.port_hints}));else if(f.type==="pcb_smtpad"&&f.shape==="circle")x.push(new $S({pcbX:f.x,pcbY:f.y,layer:f.layer,shape:"circle",radius:f.radius,portHints:f.port_hints}));else if(f.type==="pcb_silkscreen_path")x.push(new QW({layer:f.layer,route:f.route,strokeWidth:f.stroke_width}));else if(f.type==="pcb_plated_hole")f.shape==="circle"?x.push(new zS({pcbX:f.x,pcbY:f.y,shape:"circle",holeDiameter:f.hole_diameter,outerDiameter:f.outer_diameter,portHints:f.port_hints})):f.shape==="circular_hole_with_rect_pad"&&x.push(new zS({pcbX:f.x,pcbY:f.y,shape:"circular_hole_with_rect_pad",holeDiameter:f.hole_diameter,rectPadHeight:f.rect_pad_height,rectPadWidth:f.rect_pad_width,portHints:f.port_hints}));else if(f.type==="pcb_keepout"&&f.shape==="circle")x.push(new qS({pcbX:f.center.x,pcbY:f.center.y,shape:"circle",radius:f.radius}));else if(f.type==="pcb_keepout"&&f.shape==="rect")x.push(new qS({pcbX:f.center.x,pcbY:f.center.y,shape:"rect",width:f.width,height:f.height}));else if(f.type==="pcb_hole"&&f.hole_shape==="circle")x.push(new tK({pcbX:f.x,pcbY:f.y,diameter:f.hole_diameter}));else if(f.type==="pcb_cutout")f.shape==="rect"?x.push(new MF({pcbX:f.center.x,pcbY:f.center.y,shape:"rect",width:f.width,height:f.height})):f.shape==="circle"?x.push(new MF({pcbX:f.center.x,pcbY:f.center.y,shape:"circle",radius:f.radius})):f.shape==="polygon"&&x.push(new MF({shape:"polygon",points:f.points}));else if(f.type==="pcb_silkscreen_text"){let m=SUt(e,f.ccw_rotation);a.includes("pinrow")&&f.text.includes("PIN")?x.push(RUt({elm:f,pinLabels:l??s,layer:f.layer,readableRotation:m,anchorAlignment:f.anchor_alignment})):x.push(new YS({anchorAlignment:f.anchor_alignment||"center",text:n,fontSize:f.font_size+.2,pcbX:Number.isNaN(f.anchor_position.x)?0:f.anchor_position.x,pcbY:f.anchor_position.y,pcbRotation:m??0}))}else f.type==="pcb_trace"&&x.push(new eK({route:f.route}));return x};function rK(n){let e=1/0,a=1/0,s=-1/0,l=-1/0,p=!1;for(let m of n)if(m.isPcbPrimitive&&!m.componentName.startsWith("Silkscreen")){let{x:D,y:b}=m._getGlobalPcbPositionBeforeLayout(),{width:E,height:A}=m.getPcbSize();e=Math.min(e,D-E/2),a=Math.min(a,b-A/2),s=Math.max(s,D+E/2),l=Math.max(l,b+A/2),p=!0}else if(m.children.length>0){let D=rK(m.children);(D.width>0||D.height>0)&&(e=Math.min(e,D.minX),a=Math.min(a,D.minY),s=Math.max(s,D.maxX),l=Math.max(l,D.maxY),p=!0)}if(!p)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let x=s-e,f=l-a;return x<0&&(x=0),f<0&&(f=0),{minX:e,minY:a,maxX:s,maxY:l,width:x,height:f}}function BUt(n,e){let a=e.x-n.x,s=e.y-n.y;return Math.abs(a)>Math.abs(s)?a>=0?"right":"left":s>=0?"up":"down"}var ZSe=n=>{if(n.length<=1)return!0;let e=n.map(p=>{let x=p._getPcbCircuitJsonBounds();return{left:x.bounds.left,right:x.bounds.right,top:x.bounds.top,bottom:x.bounds.bottom}}),a=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let p=0;p<e.length;p++)for(let x=p+1;x<e.length;x++){let f=e[p],m=e[x];a[p][x]=a[x][p]=!(f.right<m.left||f.left>m.right||f.bottom>m.top||f.top<m.bottom)}let s=new Set,l=p=>{s.add(p);for(let x=0;x<e.length;x++)a[p][x]&&!s.has(x)&&l(x)};return l(0),s.size===e.length},QSe=n=>{if(n.length===0)throw new Error("Cannot get center of empty PCB primitives array");let e=n.map(l=>l._getPcbCircuitJsonBounds().center).filter(Boolean),a=e.reduce((l,p)=>l+p.x,0),s=e.reduce((l,p)=>l+p.y,0);return{x:a/e.length,y:s/e.length}},wUt=C.object({name:C.string().optional(),pinNumber:C.number().optional(),aliases:C.array(C.string()).optional(),layer:C.string().optional(),layers:C.array(C.string()).optional()}),Ii=class extends ma{constructor(e,a={}){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);q(this,"source_port_id",null);q(this,"pcb_port_id",null);q(this,"schematic_port_id",null);q(this,"schematicSymbolPortDef",null);q(this,"matchedComponents");q(this,"facingDirection",null);q(this,"originDescription",null);a.originDescription&&(this.originDescription=a.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:wUt}}_getGlobalPcbPositionBeforeLayout(){let e=this.matchedComponents.find(s=>s.isPcbPrimitive),a=this.parent;if(a&&!a.props.footprint)throw new Error(`${a.componentName} "${a.props.name}" does not have a footprint. Add a footprint prop, e.g. <${a.componentName.toLowerCase()} footprint="..." />`);if(!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,a=e.pcb_port.get(this.pcb_port_id);return{center:{x:a.x,y:a.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let e=this.parent;if(!e||!e._getInternallyConnectedPins)return[];let a=e._getInternallyConnectedPins();for(let s of a)if(s.some(l=>l===this))return s;return[]}_hasSchematicPort(){if(this.parent?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(l=>l.schematicSymbolPortDef));let a=this?.parent?._getSchematicBoxDimensions();return!!(a&&this.props.pinNumber!==void 0&&a.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let e=this.parent?.getSchematicSymbol();if(e){let s=this.schematicSymbolPortDef;if(!s&&(s=this._getPortsInternallyConnectedToThisPort().find(p=>p.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!s))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let l=Ts(this.parent.computeSchematicGlobalTransform(),ka(-e.center.x,-e.center.y));return rs(l,s)}let a=this?.parent?._getSchematicBoxDimensions();if(a&&this.props.pinNumber!==void 0){let s=a.getPortPositionByPinNumber(this.props.pinNumber);if(!s)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return rs(this.parent.computeSchematicGlobalTransform(),s)}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 a=e.schematic_port.get(this.schematic_port_id);if(!a)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return a.center}registerMatch(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??[]]))}isMatchingPort(e){return this.isMatchingAnyOf(e.getNameAndAliases())}getPortSelector(){return`.${this.parent?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:e,layers:a}=this._parsedProps;return a||(e?[e]:Array.from(new Set(this.matchedComponents.flatMap(s=>s.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(s=>!s._couldNotFindPort).filter(s=>s._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getNameAndAliases(),l=e.source_port.insert({name:a.name,pin_number:a.pinNumber,port_hints:s,source_component_id:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=l.source_port_id}doInitialSourceParentAttachment(){let{db:e}=this.root;if(!this.parent?.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:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=this.parent?.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{matchedComponents:a}=this;if(!this.parent?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()})`);let s=a.filter(p=>p.isPcbPrimitive);if(s.length===0)return;let l=null;if(s.length===1&&(l=s[0]._getPcbCircuitJsonBounds().center),s.length>1){if(!ZSe(s))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${s.map(p=>p.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);l=QSe(s)}if(l){let p=this.getSubcircuit(),x=e.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...l,source_port_id:this.source_port_id});this.pcb_port_id=x.pcb_port_id}else{let p=s[0];throw new Error(`${p.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;let a=this.matchedComponents.filter(x=>x.isPcbPrimitive);if(a.length===0)return;let s=null;if(a.length===1&&(s=a[0]._getPcbCircuitJsonBounds().center),a.length>1)try{ZSe(a)&&(s=QSe(a))}catch{}if(!s)return;let l=this.getSubcircuit(),p=e.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...s,source_port_id:this.source_port_id});this.pcb_port_id=p.pcb_port_id}doInitialSchematicPortRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer();if(!s||!this._hasSchematicPort())return;let l=s._getGlobalSchematicPositionBeforeLayout(),p=this._getGlobalSchematicPositionBeforeLayout(),x=null,f=s._getSchematicBoxDimensions();f&&a.pinNumber!==void 0&&(x=f.getPortPositionByPinNumber(a.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&e.schematic_debug_object.insert({shape:"rect",center:p,size:{width:.1,height:.1},label:"obstacle"}),x?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[x.side]:this.facingDirection=BUt(l,p);let m=e.source_port.get(this.source_port_id),D=[];for(let P of m?.port_hints??[])P.match(/^(pin)?\d+$/)||P.match(/^(left|right)/)&&!m?.name.match(/^(left|right)/)||D.push(P);let b;this.parent?.props?.showPinAliases&&D.length>0?b=D.join("/"):D.length>0&&(b=D[0]);let A=this.parent?._parsedProps?.pinAttributes,B={type:"schematic_port",schematic_component_id:this.parent?.schematic_component_id,center:p,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:x?.side,pin_number:a.pinNumber,true_ccw_index:x?.trueIndex,display_pin_label:b,is_connected:!1};if(A){for(let P of this.getNameAndAliases())if(A[P]){let N=A[P];N.requiresPower&&(B.has_input_arrow=!0),N.providesPower&&(B.has_output_arrow=!0)}}let w=e.schematic_port.insert(B);this.schematic_port_id=w.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(e){let{db:a}=this.root;this.pcb_port_id&&a.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}`}},CBe=n=>{let e=n.find(a=>/^(pin)?\d+$/.test(a));return e?Number.parseInt(e.replace(/^pin/,"")):null};function IF(n,e){let a=CBe(n);if(!a)return null;let l=[...n.filter(p=>p.toString()!==a.toString()&&p!==`pin${a}`),...e?.additionalAliases?.[`pin${a}`]??[]];return new Ii({pinNumber:a,aliases:l})}var TUt=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},PUt=n=>{if(TUt(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:a=0,topSize:s=0,bottomSize:l=0}=n;return{leftSize:e,rightSize:a,topSize:s,bottomSize:l}};function _Be(n){let e=n;return e.leftSide!==void 0||e.rightSide!==void 0||e.topSide!==void 0||e.bottomSide!==void 0}var IUt=n=>{let e=n.portDistanceFromEdge??.4,a=n.schPortArrangement?PUt(n.schPortArrangement):null,s={left:0,right:0,top:0,bottom:0},l=n.pinCount??null;if(l===null)if(a)l=a.leftSize+a.rightSize+a.topSize;else throw new Error("Could not determine pin count for the schematic box");if(l&&!a){let w=Math.floor(l/2);a={leftSize:l-w,rightSize:w,topSize:0,bottomSize:0}}a||(a={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let p=({side:w,sideIndex:P,truePinIndex:N})=>{if(!n.schPortArrangement||!_Be(n.schPortArrangement))return N+1;let O={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[w],$=n.schPortArrangement?.[`${w}Side`]?.direction??O,ee=n.schPortArrangement?.[`${w}Side`]?.pins,X=P;return $!==O&&(X=ee.length-P-1),OF(ee[X],n.pinLabels)},x=[],f=0,m=0;for(let w=0;w<a.leftSize;w++){let P=p({side:"left",sideIndex:w,truePinIndex:m}),N=n.numericSchPinStyle?.[`pin${P}`]??n.numericSchPinStyle?.[P];N?.topMargin&&(f+=N.topMargin),x.push({trueIndex:m,pinNumber:P,side:"left",distanceFromOrthogonalEdge:f}),N?.bottomMargin&&(f+=N.bottomMargin),w===a.leftSize-1?s.left=f:f+=n.schPinSpacing,m++}f=0;for(let w=0;w<a.bottomSize;w++){let P=p({side:"bottom",sideIndex:w,truePinIndex:m}),N=n.numericSchPinStyle?.[`pin${P}`]??n.numericSchPinStyle?.[P];N?.leftMargin&&(f+=N.leftMargin),x.push({trueIndex:m,pinNumber:P,side:"bottom",distanceFromOrthogonalEdge:f}),N?.rightMargin&&(f+=N.rightMargin),w===a.bottomSize-1?s.bottom=f:f+=n.schPinSpacing,m++}f=0;for(let w=0;w<a.rightSize;w++){let P=p({side:"right",sideIndex:w,truePinIndex:m}),N=n.numericSchPinStyle?.[`pin${P}`]??n.numericSchPinStyle?.[P];N?.bottomMargin&&(f+=N.bottomMargin),x.push({trueIndex:m,pinNumber:P,side:"right",distanceFromOrthogonalEdge:f}),N?.topMargin&&(f+=N.topMargin),w===a.rightSize-1?s.right=f:f+=n.schPinSpacing,m++}f=0;for(let w=0;w<a.topSize;w++){let P=p({side:"top",sideIndex:w,truePinIndex:m}),N=n.numericSchPinStyle?.[`pin${P}`]??n.numericSchPinStyle?.[P];N?.rightMargin&&(f+=N.rightMargin),x.push({trueIndex:m,pinNumber:P,side:"top",distanceFromOrthogonalEdge:f}),N?.leftMargin&&(f+=N.leftMargin),w===a.topSize-1?s.top=f:f+=n.schPinSpacing,m++}let D=n.schWidth;if(D===void 0){D=Math.max(s.top+n.schPinSpacing*2,s.bottom+n.schPinSpacing*2);let w=n.pinLabels?Math.max(...Object.values(n.pinLabels).map(N=>N.length*.1)):0,P=w>0?1.1:0;D=Math.max(D,w+P)}let b=n.schHeight;b||(b=Math.max(s.left+n.schPinSpacing*2,s.right+n.schPinSpacing*2));let E={left:{x:-D/2-e,y:s.left/2},bottom:{x:-s.bottom/2,y:-b/2-e},right:{x:D/2+e,y:-s.right/2},top:{x:s.top/2,y:b/2+e}},A={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},B=x.map(w=>{let{distanceFromOrthogonalEdge:P,side:N}=w,O=E[N],$=A[N];return{x:O.x+P*$.x,y:O.y+P*$.y,...w}});return{getPortPositionByPinNumber(w){let P=B.find(N=>N.pinNumber.toString()===w.toString());return P||null},getSize(){return{width:D,height:b}},getSizeIncludingPins(){return{width:D+(a.leftSize||a.rightSize?.4:0),height:b+(a.topSize||a.bottomSize?.4:0)}},pinCount:l}},jUt=(0,ABe.default)("tscircuit:core:footprint"),RBe=class extends ma{get config(){return{componentName:"Footprint",zodProps:aAe}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let n=this.children.filter(E=>E.componentName==="Constraint");if(n.length===0)return;let{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),a=E=>e&&"left"in E&&"right"in E?{...E,left:E.right,right:E.left}:E,s=n.flatMap(E=>E._getAllReferencedComponents().componentsWithSelectors).map(({component:E,selector:A,componentSelector:B,edge:w})=>({component:E,selector:A,componentSelector:B,edge:w,bounds:E._getPcbCircuitJsonBounds()}));if(s.some(E=>E.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function l(E){return s.find(({selector:A})=>A===E)}let p=new o5,x={};function f(E){return E in x||(x[E]=new a1(E),p.addEditVariable(x[E],qs.weak)),x[E]}for(let{selector:E,bounds:A}of s){let B=f(`${E}_x`),w=f(`${E}_y`);p.suggestValue(B,A.center.x),p.suggestValue(w,A.center.y)}for(let E of n){let A=E._parsedProps;if("xDist"in A){let{xDist:B,left:w,right:P,edgeToEdge:N,centerToCenter:O}=a(A),$=f(`${w}_x`),ee=f(`${P}_x`),X=l(w)?.bounds,te=l(P)?.bounds;if(O){let L=new Is(ee,[-1,$]);p.addConstraint(new Zu(L,yo.Eq,A.xDist,qs.required))}else if(N){let L=new Is(ee,-te.width/2,[-1,$],-X.width/2);p.addConstraint(new Zu(L,yo.Eq,A.xDist,qs.required))}}else if("yDist"in A){let{yDist:B,top:w,bottom:P,edgeToEdge:N,centerToCenter:O}=A,$=f(`${w}_y`),ee=f(`${P}_y`),X=l(w)?.bounds,te=l(P)?.bounds;if(O){let L=new Is($,[-1,ee]);p.addConstraint(new Zu(L,yo.Eq,A.yDist,qs.required))}else if(N){let L=new Is($,X.height/2,[-1,ee],-te.height/2);p.addConstraint(new Zu(L,yo.Eq,A.yDist,qs.required))}}else if("sameY"in A){let{for:B}=A;if(B.length<2)continue;let w=B.map(N=>f(`${N}_y`)),P=new Is(...w.slice(1));p.addConstraint(new Zu(P,yo.Eq,w[0],qs.required))}else if("sameX"in A){let{for:B}=A;if(B.length<2)continue;let w=B.map(N=>f(`${N}_x`)),P=new Is(...w.slice(1));p.addConstraint(new Zu(P,yo.Eq,w[0],qs.required))}}p.updateVariables(),jUt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(x).map(([E,A])=>({var:E,val:A.value()}))));let m={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:E,bounds:{width:A,height:B}}of s){let w=f(`${E}_x`),P=f(`${E}_y`),N=w.value()-A/2,O=w.value()+A/2,$=P.value()+B/2,ee=P.value()-B/2;m.left=Math.min(m.left,N),m.right=Math.max(m.right,O),m.top=Math.max(m.top,$),m.bottom=Math.min(m.bottom,ee)}let D={x:-(m.right+m.left)/2,y:-(m.top+m.bottom)/2},b=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();D.x+=b.x,D.y+=b.y;for(let{component:E,selector:A}of s){let B=f(`${A}_x`),w=f(`${A}_y`);E._setPositionFromLayout({x:B.value()+D.x,y:w.value()+D.y})}}},kUt=(n,e)=>{if(!n)return;let a={};for(let[s,l]of Object.entries(n)){let p=OF(s,e),x={leftMargin:l.marginLeft??l.leftMargin,rightMargin:l.marginRight??l.rightMargin,topMargin:l.marginTop??l.topMargin,bottomMargin:l.marginBottom??l.bottomMargin};a[`pin${p}`]={...a[`pin${p}`],...x}}return a},eBe=class{constructor({input:n}){q(this,"input");this.input=n}solveAndMapToTraces(){let n=[];for(let e of this.input.connections){if(e.pointsToConnect.length!==2)continue;let[a,s]=e.pointsToConnect,l={type:"pcb_trace",pcb_trace_id:"",connection_name:e.name,route:[{route_type:"wire",x:a.x,y:a.y,layer:"top",width:.1},{route_type:"wire",x:s.x,y:s.y,layer:"top",width:.1}]};n.push(l)}return n}},NUt=n=>{let e=Math.min(...n.map(p=>p.center.x)),a=Math.max(...n.map(p=>p.center.x)),s=Math.min(...n.map(p=>p.center.y)),l=Math.max(...n.map(p=>p.center.y));return{minX:e,maxX:a,minY:s,maxY:l}},tBe=["top","bottom","inner1","inner2"],OS=(n,e=[])=>{let a=[];if(e.length===0){let f=n[0].layers;for(let m of f)a.push(...OS(n.slice(1),[m]));return a}if(n.length===0)return[];let s=n[0],l=s.via||s.optional_via,p=e[e.length-1];if(n.length===1){let f=s;return f.layers&&l?f.layers.map(m=>({layer_path:[...e,m]})):f.layers?.includes(p)?[{layer_path:[...e,p]}]:[]}if(!l)return s.layers&&!s.layers.includes(p)?[]:OS(n.slice(1),e.concat([p]));let x=(s.optional_via?tBe:tBe.filter(f=>f!==p)).filter(f=>!s.layers||s.layers?.includes(f));for(let f of x)a.push(...OS(n.slice(1),e.concat(f)));return a};function rBe(n){let e={x:n.to.x-n.from.x,y:n.to.y-n.from.y},a=Math.abs(e.x),s=Math.abs(e.y);return a>s?e.x>0?"right":"left":e.y>0?"down":"up"}function kg(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}var MUt=n=>{if(n.length===1)return n[0];if(n.some(m=>m.length===0))throw new Error("Cannot merge routes with zero length");let e=[],a=n[0][0],s=n[0][n[0].length-1],l=n[1][0],p=n[1][n[1].length-1],x=Math.min(kg(a,l),kg(a,p)),f=Math.min(kg(s,l),kg(s,p));x<f?e.push(...n[0].reverse()):e.push(...n[0]);for(let m=1;m<n.length;m++){let D=e[e.length-1],b=n[m],E=b[0],A=b[b.length-1],B=kg(D,E),w=kg(D,A);B<w?e.push(...b):e.push(...b.reverse())}for(let m=1;m<e.length-1;m++){let D=e[m-1],b=e[m];D.route_type==="wire"&&b.route_type==="wire"&&D.layer!==b.layer&&e.splice(m,0,{x:D.x,y:D.y,from_layer:D.layer,to_layer:b.layer,route_type:"via"})}return e},OUt=(n,e)=>{let a="_getGlobalPcbPositionBeforeLayout"in n?n._getGlobalPcbPositionBeforeLayout():n,s="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((a.x-s.x)**2+(a.y-s.y)**2)};function LUt(n,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let a=e[0],s=1/0;for(let l of e){let p=OUt(n,l);p<s&&(a=l,s=p)}return a}var $Ut=(n,e)=>{let a=0;a+=n.length??0,a+=e.filter(s=>s.is_crossing).length;for(let s=1;s<e.length;s++){let l=e[s-1],p=e[s],x=Math.abs(l.from.x-l.to.x)<.01,f=Math.abs(p.from.x-p.to.x)<.01;x!==f&&a++}return a},$F=n=>({up:"bottom",down:"top",left:"right",right:"left"})[n]??null,qW=({firstEdge:n,firstEdgePort:e,firstDominantDirection:a,lastEdge:s,lastEdgePort:l,lastDominantDirection:p})=>{if(n&&e)return qW({lastEdge:{from:n.to,to:n.from},lastEdgePort:e,lastDominantDirection:a}).reverse().map(f=>({from:f.to,to:f.from}));let x=[];if(s&&l){let f={x:s.to.x,y:s.to.y};p==="left"||p==="right"?(f.x=l.position.x,x.push({from:s.to,to:{...f}}),x.push({from:f,to:{...l.position}})):(f.y=l.position.y,x.push({from:s.to,to:{...f}}),x.push({from:f,to:{...l.position}}))}return x=x.filter(f=>Ri(f.from,f.to)>.01),x};function zUt(n){try{return[n(),null]}catch(e){return[null,e]}}var qUt=(n,{db:e})=>{let a=n.map(s=>{let l=e.source_port.get(s.source_port_id);if(!l?.source_component_id)return null;let p=e.source_component.get(l.source_component_id);return p?.ftype==="simple_capacitor"?p.max_decoupling_trace_length:null}).filter(s=>s!==null);if(a.length!==0)return Math.min(...a)};function UUt({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 VUt=(n,{db:e})=>{let a=e.pcb_board.list()[0];if(a.outline){let m=a.outline,D=(b,E)=>{let A=!1;for(let B=0,w=E.length-1;B<E.length;w=B++){let P=E[B].x,N=E[B].y,O=E[w].x,$=E[w].y;N>b.y!=$>b.y&&b.x<(O-P)*(b.y-N)/($-N)+P&&(A=!A)}return A};return n.some(b=>!D(b,m))}let s=a.width,l=a.height,p=a.center.x,x=a.center.y;return n.some(m=>m.x<p-s/2||m.y<x-l/2||m.x>p+s/2||m.y>x+l/2)},nBe=(n,e)=>Math.abs(n-e)<1e-4,GUt=(n,e,{viaDiameter:a=.5}={})=>{let s=[];for(let l=0;l<n.length-1;l++){let[p,x]=[n[l],n[l+1]],f=l-1>=0?n[l-1]:null,m=nBe(p.y,x.y),D=nBe(p.x,x.x);if(!m&&!D)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${p.x}, ${p.y}), end: (${x.x}, ${x.y})`);let b={type:"rect",layers:[p.layer],center:{x:(p.x+x.x)/2,y:(p.y+x.y)/2},width:m?Math.abs(p.x-x.x):.1,height:D?Math.abs(p.y-x.y):.1,connectedTo:[e]};if(s.push(b),f&&f.layer===p.layer&&p.layer!==x.layer){let E={type:"rect",layers:[p.layer,x.layer],center:{x:p.x,y:p.y},connectedTo:[e],width:a,height:a};s.push(E)}}return s};function XUt(n,e=4){let{center:a,width:s,height:l,rotation:p}=n,x=[],f=p*Math.PI/180,m=Math.cos(f),D=Math.sin(f),b=(p%360+360)%360;if(l<=s?b>=45&&b<135||b>=225&&b<315:b>=135&&b<225||b>=315||b<45){let A=s/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*m,N=-w*D,O=A*1.1,$=Math.abs(l*m)+Math.abs(A*D);x.push({center:{x:a.x+P,y:a.y+N},width:O,height:$})}}else{let A=l/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*D,N=w*m,O=Math.abs(s*m)+Math.abs(A*D),$=A*1.1;x.push({center:{x:a.x+P,y:a.y+N},width:O,height:$})}}return x}function YUt(n,e={}){if(n.length<3)return[];let{rectHeight:a=.1}=e,s=[],l=n.map(f=>f.y),p=Math.min(...l),x=Math.max(...l);for(let f=p;f<x;f+=a){let m=f+a/2,D=[];for(let b=0;b<n.length;b++){let E=n[b],A=n[(b+1)%n.length];if(E.y<=m&&A.y>m||A.y<=m&&E.y>m){let B=(m-E.y)*(A.x-E.x)/(A.y-E.y)+E.x;D.push(B)}}D.sort((b,E)=>b-E);for(let b=0;b<D.length;b+=2)if(b+1<D.length){let E=D[b],B=D[b+1]-E;B>1e-6&&s.push({center:{x:E+B/2,y:m},width:B,height:a})}}return s}function HUt(n,e={}){let{center:a,radius:s}=n,{rectHeight:l=.1}=e,p=[],x=Math.ceil(s*2/l);for(let f=0;f<x;f++){let m=a.y-s+(f+.5)*l,D=m-a.y,b=Math.sqrt(s*s-D*D);b>0&&p.push({center:{x:a.x,y:m},width:b*2,height:l})}return p}var Zp=["top","inner1","inner2","bottom"],SBe=(n,e)=>{let a=l=>e?l.concat(l.map(p=>e?.getNetConnectedToId(p)).filter(Boolean)):l,s=[];for(let l of n)if(l.type==="pcb_smtpad"){if(l.shape==="circle")s.push({type:"oval",layers:[l.layer],center:{x:l.x,y:l.y},width:l.radius*2,height:l.radius*2,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rect")s.push({type:"rect",layers:[l.layer],center:{x:l.x,y:l.y},width:l.width,height:l.height,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rotated_rect"){let p={center:{x:l.x,y:l.y},width:l.width,height:l.height,rotation:l.ccw_rotation},x=XUt(p);for(let f of x)s.push({type:"rect",layers:[l.layer],center:f.center,width:f.width,height:f.height,connectedTo:a([l.pcb_smtpad_id])})}}else if(l.type==="pcb_keepout")l.shape==="circle"?s.push({type:"oval",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.radius*2,height:l.radius*2,connectedTo:[]}):l.shape==="rect"&&s.push({type:"rect",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.type==="pcb_cutout"){if(l.shape==="rect")s.push({type:"rect",layers:Zp,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.shape==="circle"){let p=HUt({center:l.center,radius:l.radius},{rectHeight:.6});for(let x of p)s.push({type:"rect",layers:Zp,center:x.center,width:x.width,height:x.height,connectedTo:[]})}else if(l.shape==="polygon"){let p=YUt(l.points,{rectHeight:.6});for(let x of p)s.push({type:"rect",layers:Zp,center:x.center,width:x.width,height:x.height,connectedTo:[]})}}else if(l.type==="pcb_hole")l.hole_shape==="oval"?s.push({type:"oval",center:{x:l.x,y:l.y},width:l.hole_width,height:l.hole_height,connectedTo:[]}):l.hole_shape==="square"?s.push({type:"rect",layers:Zp,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]}):(l.hole_shape==="round"||l.hole_shape==="circle")&&s.push({type:"rect",layers:Zp,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]});else if(l.type==="pcb_plated_hole")l.shape==="circle"?s.push({type:"oval",layers:Zp,center:{x:l.x,y:l.y},width:l.outer_diameter,height:l.outer_diameter,connectedTo:a([l.pcb_plated_hole_id])}):l.shape==="circular_hole_with_rect_pad"?s.push({type:"rect",layers:Zp,center:{x:l.x,y:l.y},width:l.rect_pad_width,height:l.rect_pad_height,connectedTo:a([l.pcb_plated_hole_id])}):(l.shape==="oval"||l.shape==="pill")&&s.push({type:"oval",layers:Zp,center:{x:l.x,y:l.y},width:l.outer_width,height:l.outer_height,connectedTo:a([l.pcb_plated_hole_id])});else if(l.type==="pcb_trace"){let p=GUt(l.route.map(x=>({x:x.x,y:x.y,layer:"layer"in x?x.layer:x.from_layer})),l.source_trace_id);s.push(...p)}else l.type==="pcb_via"&&s.push({type:"rect",layers:l.layers,center:{x:l.x,y:l.y},connectedTo:[],width:l.outer_diameter,height:l.outer_diameter});return s},Qp=({anchor_position:n,anchor_side:e,text:a,font_size:s=.18})=>{let l=.1*(s/.18),p=a.length*l,x=s,f={...n};switch(e){case"right":f.x-=p/2;break;case"left":f.x+=p/2;break;case"top":f.y-=x/2;break;case"bottom":f.y+=x/2;break}return f},nK=({db:n,source_trace_id:e,sameNetOnly:a,differentNetOnly:s})=>{!a&&!s&&(s=!0);let l=n.source_trace.get(e),p=[];for(let x of n.schematic_trace.list()){if(x.source_trace_id===e)continue;let m=n.source_trace.get(x.source_trace_id)?.subcircuit_connectivity_map_key===l.subcircuit_connectivity_map_key;s&&m||a&&!m||p.push(x)}return p},WUt=({edges:n,otherEdges:e})=>{let a=[...n];for(let s=0;s<a.length;s++){if(s>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let l=a[s],p=Math.abs(l.from.x-l.to.x)<.01?"vertical":l.from.y===l.to.y?"horizontal":"not-orthogonal";if(p==="not-orthogonal")continue;let x=[];for(let P of e){let N=P.from.x===P.to.x?"vertical":P.from.y===P.to.y?"horizontal":"not-orthogonal";if(N==="not-orthogonal"||p===N)continue;if(Np([l.from,l.to],[P.from,P.to],{lineThickness:.01})){let $=p==="vertical"?l.from.x:P.from.x,ee=p==="vertical"?P.from.y:l.from.y,X={x:$,y:ee};x.push({otherEdge:P,crossingPoint:X,distanceFromEdgeFrom:Ri(l.from,X)})}}if(x.length===0)continue;let f=x[0];for(let P of x)P.distanceFromEdgeFrom<f.distanceFromEdgeFrom&&(f=P);let m=f.crossingPoint,D=.075;if(m.x===l.from.x&&m.y===l.from.y)continue;let b=p5(l.from,m),E={x:m.x-b.x*D/2,y:m.y-b.y*D/2},A={x:m.x+b.x*D/2,y:m.y+b.y*D/2},B=Ri(A,l.to)<D,w=[{from:l.from,to:E},{from:E,to:A,is_crossing:!0},{from:A,to:l.to}];a.splice(s,1,...w),s+=w.length-2,B&&s++}return a},UW=.001,Ng=(n,e)=>{let a=Math.min(e.from.x,e.to.x),s=Math.max(e.from.x,e.to.x),l=Math.min(e.from.y,e.to.y),p=Math.max(e.from.y,e.to.y);return n.x>=a&&n.x<=s&&n.y>=l&&n.y<=p},aBe=n=>{let e=Math.abs(n.from.x-n.to.x)<UW,a=Math.abs(n.from.y-n.to.y)<UW;return e?"vertical":a?"horizontal":"diagonal"},KUt=(n,e)=>{let a=aBe(n),s=aBe(e);if(a===s)return null;if(a==="vertical"&&s==="horizontal"||a==="horizontal"&&s==="vertical"){let E=a==="vertical"?n:e,A=a==="horizontal"?n:e,B=E.from.x,w=A.from.y,P={x:B,y:w};return Ng(P,n)&&Ng(P,e)?P:null}if(a==="vertical"||s==="vertical"){let E=a==="vertical"?n:e,A=a==="vertical"?e:n,B=E.from.x,w=(A.to.y-A.from.y)/(A.to.x-A.from.x),P=A.from.y-w*A.from.x,N=w*B+P,O={x:B,y:N};return Ng(O,n)&&Ng(O,e)?O:null}let l=(n.to.y-n.from.y)/(n.to.x-n.from.x),p=n.from.y-l*n.from.x,x=(e.to.y-e.from.y)/(e.to.x-e.from.x),f=e.from.y-x*e.from.x;if(Math.abs(l-x)<UW)return null;let m=(f-p)/(l-x),D=l*m+p,b={x:m,y:D};return Ng(b,n)&&Ng(b,e)?b:null},JUt=({edges:n,db:e,source_trace_id:a})=>{let s=nK({db:e,source_trace_id:a,sameNetOnly:!0}).flatMap(p=>p.edges),l=new Map;for(let p of n)for(let x of s){let f=KUt(p,x);if(f){let m=`${f.x.toFixed(6)},${f.y.toFixed(6)}`;l.has(m)||l.set(m,f)}}return Array.from(l.values())};function ZUt(n){let e=1/0,a=1/0,s=-1/0,l=-1/0;for(let p of n){let x,f,m,D;p.type==="schematic_component"?(x=p.center?.x,f=p.center?.y,m=p.size?.width,D=p.size?.height):p.type==="schematic_box"?(x=p.x,f=p.y,m=p.width,D=p.height):p.type==="schematic_port"?(x=p.center?.x,f=p.center?.y,m=.2,D=.2):p.type==="schematic_text"&&(x=p.position?.x,f=p.position?.y,m=(p.text?.length??0)*.1,D=.2),typeof x=="number"&&typeof f=="number"&&typeof m=="number"&&typeof D=="number"&&(e=Math.min(e,x-m/2),s=Math.max(s,x+m/2),a=Math.min(a,f-D/2),l=Math.max(l,f+D/2))}return{minX:e,maxX:s,minY:a,maxY:l}}function QUt(n,e={}){let{minX:a,maxX:s,minY:l,maxY:p}=n,x=e.padding??1;if(!isFinite(a)||!isFinite(s)||!isFinite(l)||!isFinite(p))return[];let f=a-x,m=s+x,D=p+x,b=l-x,E=.01;return[{type:"rect",layers:["top"],center:{x:(f+m)/2,y:D},width:m-f,height:E,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(f+m)/2,y:b},width:m-f,height:E,connectedTo:[]},{type:"rect",layers:["top"],center:{x:f,y:(D+b)/2},width:E,height:D-b,connectedTo:[]},{type:"rect",layers:["top"],center:{x:m,y:(D+b)/2},width:E,height:D-b,connectedTo:[]}]}var eVt=n=>{let e=n.root.db,a=n._findConnectedPorts().ports??[],s=new Set(a.map(x=>x.schematic_port_id)),l=[];for(let x of e.toArray()){if(x.type==="schematic_component"){let f=!!x.symbol_name,m=x.size.width>x.size.height?"horz":"vert";l.push({type:"rect",layers:["top"],center:x.center,width:x.size.width+(f&&m==="horz"?-.5:0),height:x.size.height+(f&&m==="vert"?-.5:0),connectedTo:[]})}if(x.type==="schematic_port"){if(s.has(x.schematic_port_id))continue;let f=x.facing_direction?x5(x.facing_direction):{x:0,y:0};l.push({type:"rect",layers:["top"],center:{x:x.center.x-f.x*.1,y:x.center.y-f.y*.1},width:.1+Math.abs(f.x)*.3,height:.1+Math.abs(f.y)*.3,connectedTo:[]})}x.type==="schematic_text"&&l.push({type:"rect",layers:["top"],center:x.position,width:(x.text?.length??0)*.1,height:.2,connectedTo:[]}),x.type==="schematic_box"&&l.push({type:"rect",layers:["top"],center:{x:x.x,y:x.y},width:x.width,height:x.height,connectedTo:[]})}let p=ZUt(e.toArray());return l.push(...QUt(p,{padding:1})),l},tVt=({edges:n,db:e,source_trace_id:a})=>{let s=e.source_trace.get(a),l=nK({db:e,source_trace_id:a,differentNetOnly:!0}).flatMap(x=>x.edges),p=x=>{let{from:f,to:m}=x;return f.x===m.x?"vertical":"horizontal"};for(let x of n){let f=p(x),m=()=>l.find(b=>p(b)===f&&Np([x.from,x.to],[b.from,b.to],{lineThickness:.05})),D=m();for(;D;)f==="horizontal"?(x.from.y+=.1,x.to.y+=.1):(x.from.x+=.1,x.to.x+=.1),D=m()}},VW=n=>{switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},rVt=YAe.version??"unknown",jF=class extends Error{constructor(n){super(`${n} (capacity-autorouter@${rVt})`),this.name="AutorouterError"}},US=class extends Error{constructor(n){super(n.message),this.errorData=n,this.name="TraceConnectionError"}},nVt=n=>{if(n.root?._featureMspSchematicTraceRouting||n._couldNotFindPort||n.root?.schematicDisabled)return;let{db:e}=n.root,{_parsedProps:a,parent:s}=n;if(!s)throw new Error("Trace has no parent");let l,p;try{let Ne=n._findConnectedPorts();l=Ne.allPortsFound,p=Ne.portsWithSelectors??[]}catch(Ne){if(Ne instanceof US){e.source_trace_not_connected_error.insert({...Ne.errorData,error_type:"source_trace_not_connected_error"});return}throw Ne}let{netsWithSelectors:x}=n._findConnectedNets();if(!l)return;let m=p.map(Ne=>Ne.port.schematic_port_id).sort().join(","),D=n.root?._getBoard();if(D?._connectedSchematicPortPairs&&D._connectedSchematicPortPairs.has(m))return;let b={name:n.source_trace_id,pointsToConnect:[]},E=eVt(n),A=p.filter(({port:Ne})=>Ne.schematic_port_id!==null).map(({port:Ne})=>({port:Ne,position:Ne._getGlobalSchematicPositionAfterLayout(),schematic_port_id:Ne.schematic_port_id??void 0,facingDirection:Ne.facingDirection}));if(A.length===1&&x.length===1){let Ne=x[0].net,{port:Ve,position:et}=A[0],ct=n.getSubcircuit().selectAll("netlabel").find(ot=>{let it=ot._parsedProps.connection??ot._parsedProps.connectsTo;return it?Array.isArray(it)?it.some(It=>n.getSubcircuit().selectOne(It,{port:!0})===Ve):n.getSubcircuit().selectOne(it,{port:!0})===Ve:!1});if(!ct){let ot=e.schematic_net_label.getWhere({source_trace_id:n.source_trace_id});ot&&(ct=ot)}if(ct){let ot="_getGlobalSchematicPositionBeforeLayout"in ct?ct._getGlobalSchematicPositionBeforeLayout():ct.anchor_position,it=[];et.x===ot.x||et.y===ot.y?it.push({from:et,to:ot}):(it.push({from:et,to:{x:ot.x,y:et.y}}),it.push({from:{x:ot.x,y:et.y},to:ot}));let qt=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:it,junctions:[],subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=qt.schematic_trace_id;return}if(n.props.schDisplayLabel){let ot=$F(Ve.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel,source_net_id:Ne.source_net_id,anchor_position:et,center:Qp({anchor_position:et,anchor_side:ot,text:n.props.schDisplayLabel}),anchor_side:ot});return}let Mt=$F(Ve.facingDirection)??"bottom",Dt=e.schematic_net_label.insert({text:Ne._parsedProps.name,source_net_id:Ne.source_net_id,anchor_position:et,center:Qp({anchor_position:et,anchor_side:Mt,text:Ne._parsedProps.name}),anchor_side:Mt});return}if(n.props.schDisplayLabel&&("from"in n.props&&"to"in n.props||"path"in n.props)){n._doInitialSchematicTraceRenderWithDisplayLabel();return}if(A.length<2)return;let P=(()=>{let Ne=[];for(let et=0;et<A.length-1;et++){let ct=A[et],Mt=A[et+1],Dt=sg({x:ct.position.x,y:ct.position.y,facingDirection:VW(ct.facingDirection)},{x:Mt.position.x,y:Mt.position.y,facingDirection:VW(Mt.facingDirection)});for(let ot=0;ot<Dt.length-1;ot++)Ne.push({from:Dt[ot],to:Dt[ot+1]})}let Ve=(et,ct)=>{let Mt=ct.width/2,Dt=ct.height/2,ot=ct.center.x-Mt,it=ct.center.x+Mt,qt=ct.center.y-Dt,It=ct.center.y+Dt,tr=Et=>Et.x>=ot&&Et.x<=it&&Et.y>=qt&&Et.y<=It;return tr(et.from)||tr(et.to)?!0:[[{x:ot,y:qt},{x:it,y:qt}],[{x:it,y:qt},{x:it,y:It}],[{x:it,y:It},{x:ot,y:It}],[{x:ot,y:It},{x:ot,y:qt}]].some(Et=>Np([et.from,et.to],Et,{lineThickness:0}))};for(let et of Ne)for(let ct of E)if(Ve(et,ct))return null;return Ne})();P&&P.length===0&&(P=null),b.pointsToConnect=A.map(({position:Ne})=>({...Ne,layer:"top"}));let N=NUt(E),O=2,$={minTraceWidth:.1,obstacles:E,connections:[b],bounds:{minX:N.minX-O,maxX:N.maxX+O,minY:N.minY-O,maxY:N.maxY+O},layerCount:1},ee=JR,X=!1;if(n.getSubcircuit().props._schDirectLineRoutingEnabled&&(ee=eBe,X=!0),!P){let Ve=new ee({input:$,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(Ve.length===0){if(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection()){n._doInitialSchematicTraceRenderWithDisplayLabel();return}Ve=new eBe({input:$}).solveAndMapToTraces(),X=!0}let[{route:et}]=Ve;P=[];for(let ct=0;ct<et.length-1;ct++)P.push({from:et[ct],to:et[ct+1]})}let te=n.source_trace_id,L=[];if(!X){tVt({edges:P,db:e,source_trace_id:te});let Ne=nK({db:e,source_trace_id:te,differentNetOnly:!0}).flatMap(Ve=>Ve.edges);P=WUt({edges:P,otherEdges:Ne}),L=JUt({edges:P,db:e,source_trace_id:n.source_trace_id})}if(!P||P.length===0)return;let K=P[P.length-1],U=A[A.length-1],J=rBe(K);P.push(...qW({lastEdge:K,lastEdgePort:U,lastDominantDirection:J}));let Q=P[0],de=A[0],ce=rBe(Q);if(P.unshift(...qW({firstEdge:Q,firstEdgePort:de,firstDominantDirection:ce})),!n.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(n.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&$Ut(L,P)>=5&&(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection())){n._doInitialSchematicTraceRenderWithDisplayLabel();return}let Te=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:P,junctions:L,subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=Te.schematic_trace_id;for(let{port:Ne}of p)Ne.schematic_port_id&&e.schematic_port.update(Ne.schematic_port_id,{is_connected:!0});D?._connectedSchematicPortPairs&&D._connectedSchematicPortPairs.add(m)};function BBe(n){let e=0;for(let a=0;a<n.length;a++){let s=n[a];if(s.route_type==="wire"){let l=n[a+1];if(l){let p=l.x-s.x,x=l.y-s.y;e+=Math.sqrt(p*p+x*x)}}else s.route_type==="via"&&(e+=1.6)}return e}var kS=n=>({...n._getGlobalPcbPositionAfterLayout(),layers:n.getAvailablePcbLayers()}),aVt=!1;function sVt(n){if(n.root?.pcbDisabled)return;let{db:e}=n.root,{_parsedProps:a,parent:s}=n,l=n.getSubcircuit();if(!s)throw new Error("Trace has no parent");if(l._parsedProps.routingDisabled)return;let p=l._parsedProps.pcbRouteCache?.pcbTraces;if(p){let J=e.pcb_trace.insert({route:p.flatMap(Q=>Q.route),source_trace_id:n.source_trace_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0});n.pcb_trace_id=J.pcb_trace_id;return}if(a.pcbPath&&a.pcbPath.length>0||!l._shouldUseTraceByTraceRouting())return;let{allPortsFound:x,ports:f}=n._findConnectedPorts(),m=[];if(!x)return;let D=[];for(let J of f)J._hasMatchedPcbPrimitive()||D.push(J);if(D.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: ${D.map(J=>J.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:D.map(J=>J.pcb_port_id).filter(Boolean)});return}let b=n._findConnectedNets().netsWithSelectors;if(f.length===0&&b.length===2){n.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(f.length===1&&b.length===1){let J=f[0],de=b[0].net.getAllConnectedPorts().filter(Te=>Te!==J);if(de.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let ce=LUt(J,de);m.push(ce),f.push(ce)}else if(f.length>1&&b.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 E=f.flatMap(J=>J.matchedComponents.filter(Q=>Q.componentName==="TraceHint")),A=(n._parsedProps.pcbRouteHints??[]).concat(E.flatMap(J=>J.getPcbRouteHints()));if(f.length>2){n.renderError(`Trace has more than two ports (${f.map(J=>J.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(n.getSubcircuit().selectAll("trace").filter(J=>J.renderPhaseStates.PcbTraceRender.initialized).some(J=>J._portsRoutedOnPcb.length===f.length&&J._portsRoutedOnPcb.every(Q=>f.includes(Q))))return;let P=[];A.length===0?P=[kS(f[0]),kS(f[1])]:P=[kS(f[0]),...A,kS(f[1])];let N=OS(P);if(aVt&&N.length===0){n.renderError(`Could not find a common layer (using hints) for trace ${n.getString()}`);return}let O=Ku(n.root.db.toArray()),[$,ee]=zUt(()=>SBe(n.root.db.toArray()));if(ee){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: ${ee.message}`,source_trace_id:n.source_trace_id,center:{x:0,y:0},pcb_port_ids:f.map(J=>J.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[]});return}for(let J of $)if(J.connectedTo.length>0){let de=O.getNetConnectedToId(J.connectedTo[0]);de&&J.connectedTo.push(de)}let X=[];if(N.length===0)X=P;else{let J=N[0].layer_path;X=P.map((Q,de)=>Q.via?{...Q,via_to_layer:J[de]}:{...Q,layers:[J[de]]})}X[0].pcb_port_id=f[0].pcb_port_id,X[X.length-1].pcb_port_id=f[1].pcb_port_id;let te=[];for(let[J,Q]of vBe(X)){let de="via_to_layer"in J?J.via_to_layer:null,ce=2,Te="layers"in J&&J.layers.length===1?J.layers[0]:de??"top",Ne="layers"in Q&&Q.layers.length===1?Q.layers[0]:de??"top",Ve="pcb_port_id"in J?J.pcb_port_id:null,et="pcb_port_id"in Q?Q.pcb_port_id:null,ct=n.getSubcircuit()._parsedProps.minTraceWidth??.16,Mt=new JR({OBSTACLE_MARGIN:ct*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Ve&&et),connMap:O,input:{obstacles:$,minTraceWidth:ct,connections:[{name:n.source_trace_id,pointsToConnect:[{...J,layer:Te,pcb_port_id:Ve},{...Q,layer:Ne,pcb_port_id:et}]}],layerCount:n.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(J.x,Q.x)-ce,maxX:Math.max(J.x,Q.x)+ce,minY:Math.min(J.y,Q.y)-ce,maxY:Math.max(J.y,Q.y)+ce}}}),Dt=null;try{Dt=Mt.solveAndMapToTraces()}catch(qt){n.renderError({type:"pcb_trace_error",pcb_trace_error_id:n.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${qt.message}`,source_trace_id:n.pcb_trace_id,center:{x:(J.x+Q.x)/2,y:(J.y+Q.y)/2},pcb_port_ids:f.map(It=>It.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:f.map(It=>It.pcb_component_id)})}if(!Dt)return;if(Dt.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:(J.x+Q.x)/2,y:(J.y+Q.y)/2},pcb_port_ids:f.map(qt=>qt.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:f.map(qt=>qt.pcb_component_id)});return}let[ot]=Dt;de&&(ot.route=ot.route.map(qt=>(qt.route_type==="wire"&&!qt.layer&&(qt.layer=de),qt))),Ve&&ot.route[0].route_type==="wire"&&(ot.route[0].start_pcb_port_id=Ve);let it=ot.route[ot.route.length-1];et&&it.route_type==="wire"&&(it.end_pcb_port_id=et),te.push(ot.route)}let L=MUt(te),K=BBe(L),U=e.pcb_trace.insert({route:L,source_trace_id:n.source_trace_id,subcircuit_id:n.getSubcircuit()?.subcircuit_id,trace_length:K});n._portsRoutedOnPcb=f,n.pcb_trace_id=U.pcb_trace_id;for(let J of L)J.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:U.pcb_trace_id,x:J.x,y:J.y,hole_diameter:.3,outer_diameter:.6,layers:[J.from_layer,J.to_layer],from_layer:J.from_layer,to_layer:J.to_layer});n._insertErrorIfTraceIsOutsideBoard(L,f)}function iVt(n){if(n.root?.pcbDisabled)return;let{db:e}=n.root,{_parsedProps:a}=n,s=n.getSubcircuit();if(!a.pcbPath||a.pcbPath.length===0)return;let{allPortsFound:l,ports:p,portsWithSelectors:x}=n._findConnectedPorts();if(!l)return;let f=[];for(let $ of p)$._hasMatchedPcbPrimitive()||f.push($);if(f.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: ${f.map($=>$.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:f.map($=>$.pcb_port_id).filter(Boolean)});return}let m;a.pcbPathRelativeTo&&(m=x.find($=>$.selector===a.pcbPathRelativeTo)?.port,m||(m=n.getSubcircuit().selectOne(a.pcbPathRelativeTo))),m||(m=p[0]);let D=p.find($=>$!==m)??p[1],b=m.getAvailablePcbLayers()[0]||"top",E=a.thickness??n.getSubcircuit()._parsedProps.minTraceWidth??.16,A=m._getGlobalPcbPositionAfterLayout(),B=D._getGlobalPcbPositionAfterLayout(),w=[];w.push({route_type:"wire",x:A.x,y:A.y,width:E,layer:b,start_pcb_port_id:m.pcb_port_id});let P=m?._computePcbGlobalTransformBeforeLayout?.()||_i();for(let $ of a.pcbPath){let ee=rs(P,{x:$.x,y:$.y});w.push({route_type:"wire",x:ee.x,y:ee.y,width:E,layer:b})}w.push({route_type:"wire",x:B.x,y:B.y,width:E,layer:b,end_pcb_port_id:D.pcb_port_id});let N=BBe(w),O=e.pcb_trace.insert({route:w,source_trace_id:n.source_trace_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,trace_length:N});n._portsRoutedOnPcb=p,n.pcb_trace_id=O.pcb_trace_id,n._insertErrorIfTraceIsOutsideBoard(w,p)}function oVt(n){if(n.root?.schematicDisabled)return;let{db:e}=n.root,{_parsedProps:a,parent:s}=n;if(!s)throw new Error("Trace has no parent");let{allPortsFound:l,portsWithSelectors:p}=n._findConnectedPorts();if(!l)return;let x=p.map(({port:X})=>({port:X,position:X._getGlobalSchematicPositionAfterLayout(),schematic_port_id:X.schematic_port_id,facingDirection:X.facingDirection}));if(x.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let f,m,D=x[0].position,b=x[0].port;if("path"in n.props){if(n.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[f,m]=n.props.path}else{if(!("from"in n.props&&"to"in n.props))throw new Error("Missing 'from' or 'to' properties in props.");f=n.props.from,m=n.props.to}if(!b.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${f}).`);let E=x[1].position,A=x[1].port;if(!A.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${m}).`);let B=e.schematic_net_label.list().find(X=>X.source_net_id===b.source_port_id),w=e.schematic_net_label.list().find(X=>X.source_net_id===A.source_port_id),[P,N]=p.map(({port:X})=>X),$=P.parent?.config.shouldRenderAsSchematicBox?`${P?.parent?.props.name}_${P?.props.name}`:`${N?.parent?.props.name}_${N?.props.name}`,ee=n.props.schDisplayLabel??$;if(B&&B.text!==ee&&(B.text=`${ee} / ${B.text}`),w&&w?.text!==ee&&(w.text=`${ee} / ${w.text}`),!w){let X=$F(A.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??$,source_net_id:A.source_port_id,anchor_position:E,center:Qp({anchor_position:E,anchor_side:X,text:n.props.schDisplayLabel??$}),anchor_side:X})}if(!B){let X=$F(b.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??$,source_net_id:b.source_port_id,anchor_position:D,center:Qp({anchor_position:D,anchor_side:X,text:n.props.schDisplayLabel??$}),anchor_side:X})}}function uVt(n){let{_parsedProps:e,parent:a}=n;if(!a)throw new Error("Trace has no parent");let l=n.getTracePortPathSelectors().map(p=>({selector:p,port:n.getSubcircuit().selectOne(p,{type:"port"})??null}));for(let{selector:p,port:x}of l)if(!x){let f,m,D=p.lastIndexOf(".");if(D!==-1&&D>p.lastIndexOf(" "))f=p.slice(0,D),m=p.slice(D+1);else{let X=p.match(/^(.*[ >])?([^ >]+)$/);f=X?.[1]?.trim()??"",m=X?.[2]??p}let b=f?n.getSubcircuit().selectOne(f):null;if(!b&&f&&!/[.#\[]/.test(f)&&(b=n.getSubcircuit().selectOne(`.${f}`)),!b){let X=f?`Could not find port for selector "${p}". Component "${f}" not found`:`Could not find port for selector "${p}"`,te=n.getSubcircuit(),L=te.getGroup();throw new US({error_type:"source_trace_not_connected_error",message:X,subcircuit_id:te.subcircuit_id??void 0,source_group_id:L?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[p]})}let E=b.children.filter(X=>X.componentName==="Port"),A=m.includes(".")?m.split(".").pop()??"":m,B=E.flatMap(X=>X.getNameAndAliases()),w=B.some(X=>!/^(pin\d+|\d+)$/.test(X)),P=Array.from(new Set(B)).join(", "),N;E.length===0?N="It has no ports":w?N=`It has [${P}]`:N=`It has ${E.length} pins and no pinLabels (consider adding pinLabels)`;let O=`Could not find port for selector "${p}". Component "${b.props.name??f}" found, but does not have pin "${A}". ${N}`,$=n.getSubcircuit(),ee=$.getGroup();throw new US({error_type:"source_trace_not_connected_error",message:O,subcircuit_id:$.subcircuit_id??void 0,source_group_id:ee?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[p]})}return l.some(p=>!p.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:l,ports:l.map(({port:p})=>p)}}var zc=class extends ma{constructor(e){super(e);q(this,"source_trace_id",null);q(this,"pcb_trace_id",null);q(this,"schematic_trace_id",null);q(this,"_portsRoutedOnPcb");q(this,"subcircuit_connectivity_map_key",null);q(this,"_traceConnectionHash",null);q(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}get config(){return{zodProps:nAe,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 uVt(this)}_resolveNet(e){let a=this.getSubcircuit().selectOne(e,{type:"net"});if(a)return a;let s=e.match(/^net\.(.+)$/),l=s?s[1]:null;return l&&this.root._getBoard().getDescendants().find(x=>x.componentName==="Net"&&x._parsedProps.name===l)||null}_findConnectedNets(){let e=this.getTracePathNetSelectors().map(s=>({selector:s,net:this._resolveNet(s)})),a=e.filter(s=>!s.net);return a.length>0&&this.renderError(`Could not find net for selector "${a[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(s=>s.net)}}_getAllTracesConnectedToSameNet(){let e=this.getSubcircuit().selectAll("trace"),a=this._findConnectedNets().nets,s=this._findConnectedPorts().ports??[];return e.filter(l=>{if(l===this)return!1;let p=l._findConnectedNets().nets,x=l._findConnectedPorts().ports??[];return p.some(f=>a.includes(f))||x.some(f=>s.includes(f))})}_isExplicitlyConnectedToPort(e){let{allPortsFound:a,portsWithSelectors:s}=this._findConnectedPorts();return a?s.map(p=>p.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){ZW(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();return!e||!a?null:[...a].sort((p,x)=>(p.pcb_port_id||"").localeCompare(x.pcb_port_id||"")).map(p=>p.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:e}=this.root,{_parsedProps:a,parent:s}=this;if(!s){this.renderError("Trace has no parent");return}let l,p;try{let E=this._findConnectedPorts();l=E.allPortsFound,p=E.portsWithSelectors??[]}catch(E){if(E instanceof US){e.source_trace_not_connected_error.insert({...E.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw E}if(!l)return;this._traceConnectionHash=this._computeTraceConnectionHash();let f=e.source_trace.list().find(E=>E.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&E.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(f){this.source_trace_id=f.source_trace_id;return}let m=this._findConnectedNets().nets,D=UUt({ports:p,nets:m}),b=e.source_trace.insert({connected_source_port_ids:p.map(E=>E.port.source_port_id),connected_source_net_ids:m.map(E=>E.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:qUt(p.map(E=>E.port),{db:e})??a.maxLength,display_name:D,min_trace_thickness:a.thickness});this.source_trace_id=b.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,a){let{db:s}=this.root;VUt(e,{db:s})&&s.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:a.map(p=>p.pcb_port_id)})}doInitialPcbManualTraceRender(){iVt(this)}doInitialPcbTraceRender(){sVt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){oVt(this)}_isSymbolToChipConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let p=s.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return p&&!x||!p&&x}_isSymbolToSymbolConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let p=!s.parent.config.shouldRenderAsSchematicBox,x=!l.parent.config.shouldRenderAsSchematicBox;return p&&x}_isChipToChipConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let p=s.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return p&&x}doInitialSchematicTraceRender(){nVt(this)}},cVt=n=>{let{db:e}=n.root;if(n.pcb_component_id){let a=e.pcb_component.get(n.pcb_component_id);return a?{width:a.width,height:a.height}:null}if(n.pcb_group_id){let a=e.pcb_group.get(n.pcb_group_id);return a?{width:a.width,height:a.height}:null}return null},lVt=(n,e)=>{let{db:a}=n.root,s=a.toArray();if(n.pcb_component_id){h5(s,n.pcb_component_id,e);return}if(n.source_group_id){m5(s,n.source_group_id,e);return}throw new Error(`Cannot reposition component ${n.getString()}: no pcb_component_id or source_group_id`)},dVt=n=>{let{db:e}=n.root;if(!n.source_component_id)return;let a=n.selectAll("port"),s=e.source_trace.list(),l=new Set;for(let x of s)for(let f of x.connected_source_port_ids)l.add(f);let p=n._getInternallyConnectedPins();for(let x of p)if(x.some(f=>f.source_port_id&&l.has(f.source_port_id)))for(let f of x)f.source_port_id&&l.add(f.source_port_id);for(let x of a)x.source_port_id&&pVt(n,x)&&(l.has(x.source_port_id)||e.source_pin_missing_trace_warning.insert({message:`Port ${x.getNameAndAliases()[0]} on ${n.props.name} is missing a trace`,source_component_id:n.source_component_id,source_port_id:x.source_port_id,subcircuit_id:n.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},pVt=(n,e)=>{if(n.config.componentName==="Chip"){let a=n.props.pinAttributes;if(!a)return!1;for(let s of e.getNameAndAliases()){let l=a[s];if(l?.requiresPower||l?.requiresGround||l?.requiresVoltage!==void 0)return!0}return!1}return!0};function xVt(n){let e=n.font_size,a=n.text.length*e*.6,s=e,l=n.anchor_alignment||"center",p=n.anchor_position.x,x=n.anchor_position.y;switch(l){case"top_left":p=n.anchor_position.x+a/2,x=n.anchor_position.y+s/2;break;case"top_center":p=n.anchor_position.x,x=n.anchor_position.y+s/2;break;case"top_right":p=n.anchor_position.x-a/2,x=n.anchor_position.y+s/2;break;case"center_left":p=n.anchor_position.x+a/2,x=n.anchor_position.y;break;case"center":p=n.anchor_position.x,x=n.anchor_position.y;break;case"center_right":p=n.anchor_position.x-a/2,x=n.anchor_position.y;break;case"bottom_left":p=n.anchor_position.x+a/2,x=n.anchor_position.y-s/2;break;case"bottom_center":p=n.anchor_position.x,x=n.anchor_position.y-s/2;break;case"bottom_right":p=n.anchor_position.x-a/2,x=n.anchor_position.y-s/2;break;default:p=n.anchor_position.x,x=n.anchor_position.y;break}return{x:p-a/2,y:x-s/2,width:a,height:s}}function fVt(n){if(!n._adjustSilkscreenTextAutomatically||n.root?.pcbDisabled||!n.pcb_component_id)return;let{db:e}=n.root,s=n._getPcbCircuitJsonBounds().center,l=e.pcb_silkscreen_text.list({pcb_component_id:n.pcb_component_id}).filter(m=>m.text===n.name);if(l.length===0)return;let f=n.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(m=>m!==n&&m.pcb_component_id).map(m=>{let D=m._getPcbCircuitJsonBounds(),b={center:D.center,width:D.width,height:D.height};return Ql(b)});for(let m of l){let D=m.anchor_position,b=xVt(m),E={center:{x:b.x+b.width/2,y:b.y+b.height/2},width:b.width,height:b.height},A=Ql(E);if(!f.some(ee=>Ob(A,ee)))continue;let w=2*s.x-D.x,P=2*s.y-D.y,N={center:{x:w,y:P},width:b.width,height:b.height},O=Ql(N);f.some(ee=>Ob(O,ee))||e.pcb_silkscreen_text.update(m.pcb_silkscreen_text_id,{anchor_position:{x:w,y:P}})}}function hVt(n){if(!n)return{validPinLabels:n,invalidPinLabelsMessages:[]};let e={},a=[];for(let[s,l]of Object.entries(n)){let p=Array.isArray(l)?l.slice():[l],x=[];for(let f of p)mVt(s,f)?x.push(f):a.push(`Invalid pin label: ${s} = '${f}' - excluding from component. Please use a valid pin label.`);x.length>0&&(e[s]=Array.isArray(l)?x:x[0])}return{validPinLabels:Object.keys(e).length>0?e:void 0,invalidPinLabelsMessages:a}}function mVt(n,e){try{let a={name:"test",footprint:"test",pinLabels:{[n]:e}};return rg.safeParse(a).success}catch{return!1}}var VS=n=>n.startsWith("http://")||n.startsWith("https://"),XW=n=>{if(VS(n))return null;let e=n.indexOf(":");if(e<=0)return null;let a=n.slice(0,e),s=n.slice(e+1);return!a||!s?null:{footprintLib:a,footprintName:s}};function gVt(n,e){let{footprint:a}=n.props;if(a??(a=n._getImpliedFootprintString?.()),!a)return;let{pcbRotation:s,pinLabels:l,pcbPinLabels:p}=n.props;if(typeof a=="string"&&VS(a)){if(n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let x=a;e("load-footprint-url",async()=>{let m=await(await fetch(x)).json(),D=zW({componentName:n.name,componentRotation:s,footprint:x,pinLabels:l,pcbPinLabels:p},m);n.addAll(D),n._markDirty("InitializePortsFromChildren")});return}if(typeof a=="string"){let x=XW(a);if(!x||n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let m=n.root?.platform?.footprintLibraryMap?.[x.footprintLib],D;if(typeof m=="function"&&(D=m),!D)return;e("load-lib-footprint",async()=>{let b=await D(x.footprintName),E=Array.isArray(b)?b:Array.isArray(b?.footprintCircuitJson)?b.footprintCircuitJson:null;if(!E)return;let A=zW({componentName:n.name,componentRotation:s,footprint:a,pinLabels:l,pcbPinLabels:p},E);n.addAll(A);for(let B of n.children)B.componentName==="Port"&&B._markDirty?.("PcbPortRender");n._markDirty("InitializePortsFromChildren")});return}if((0,GW.isValidElement)(a)){if(n.reactSubtrees.some(f=>f.element===a))return;let x=n._renderReactSubtree(a);n.reactSubtrees.push(x),n.add(x.component);return}!(0,GW.isValidElement)(a)&&a.componentName==="Footprint"&&n.add(a)}var DVt=(0,DBe.default)("tscircuit:core"),yVt=C.object({x:Ba,y:Ba,z:Ba}),Za=class extends ma{constructor(e){let a={...e},s=[];if(a.pinLabels&&!Array.isArray(a.pinLabels)){let{validPinLabels:l,invalidPinLabelsMessages:p}=hVt(a.pinLabels);a.pinLabels=l,s=p}super(a);q(this,"reactSubtrees",[]);q(this,"_impliedFootprint");q(this,"isPrimitiveContainer",!0);q(this,"_isNormalComponent",!0);q(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});q(this,"_asyncSupplierPartNumbers");q(this,"pcb_missing_footprint_error_id");q(this,"_hasStartedFootprintUrlLoad",!1);q(this,"_invalidPinLabelMessages",[]);q(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=s,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(a=>a.map(s=>typeof s=="number"?`pin${s}`:s))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let e=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(l=>l!==this&&l._isNormalComponent&&l.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let l=this._getGlobalPcbPositionBeforeLayout(),p=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:l,schematic_center:p}),this.shouldBeRemoved=!0;let x=[...this.children];for(let f of x)this.remove(f)}}initPorts(e={}){if(this.root?.schematicDisabled)return;let{config:a}=this,s=[],l=this._getSchematicPortArrangement();if(l&&!this._parsedProps.pinLabels){for(let D in l){let b=l[D].pins;if(Array.isArray(b))for(let E of b){let A=OF(E,this._parsedProps.pinLabels);s.push(new Ii({pinNumber:A,aliases:e.additionalAliases?.[`pin${A}`]??[]},{originDescription:`schPortArrangement:${D}`}))}}let f=["left","right","top","bottom"],m=1;for(let D of f){let b=l[`${D}Size`];for(let E=0;E<b;E++)s.push(new Ii({pinNumber:m++,aliases:e.additionalAliases?.[`pin${m}`]??[]},{originDescription:`schPortArrangement:${D}`}))}}let p=this._parsedProps.pinLabels;if(p)for(let[f,m]of Object.entries(p)){f=f.replace("pin","");let D=s.find(A=>A._parsedProps.pinNumber===Number(f)),b=Array.isArray(m)?m[0]:m,E=Array.isArray(m)?m.slice(1):[];D?(D.externallyAddedAliases.push(b,...E),D.props.name=b):(D=new Ii({pinNumber:parseInt(f),name:b,aliases:[...E,...e.additionalAliases?.[`pin${parseInt(f)}`]??[]]},{originDescription:`pinLabels:pin${f}`}),s.push(D))}if(a.schematicSymbolName&&!e.ignoreSymbolPorts){let f=Ps[this._getSchematicSymbolNameOrThrow()];if(!f)return;for(let m of f.ports){let D=CBe(m.labels);if(!D)continue;let b=s.find(E=>E._parsedProps.pinNumber===Number(D));if(b)b.schematicSymbolPortDef=m;else{let E=IF(m.labels.concat(e.additionalAliases?.[`pin${D}`]??[]));E&&(E.originDescription=`schematicSymbol:labels[0]:${m.labels[0]}`,E.schematicSymbolPortDef=m,s.push(E))}}this.addAll(s)}if(!this._getSchematicPortArrangement()){let f=this.getPortsFromFootprint(e);for(let m of f)s.some(D=>D.isMatchingAnyOf(m.getNameAndAliases()))||s.push(m)}let x=e.pinCount??this._getPinCount()??0;for(let f=1;f<=x;f++){if(s.find(D=>D._parsedProps.pinNumber===f))continue;if(!l){s.push(new Ii({pinNumber:f,aliases:e.additionalAliases?.[`pin${f}`]??[]}));continue}let m=[...l.leftSide?.pins??[],...l.rightSide?.pins??[],...l.topSide?.pins??[],...l.bottomSide?.pins??[]].map(D=>OF(D,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(D=>D in l)&&(m=Array.from({length:this._getPinCount()},(D,b)=>b+1)),m.includes(f)&&s.push(new Ii({pinNumber:f,aliases:e.additionalAliases?.[`pin${f}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${f}`}))}s.length>0&&this.addAll(s)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:e,pinLabels:a,pcbPinLabels:s}=this.props,{footprint:l}=this.props;if(l??(l=this._getImpliedFootprintString?.()),!!l&&typeof l=="string"){if(VS(l)||XW(l))return;let p=Mq.string(l).soup(),x=zW({componentName:this.name??this.componentName,componentRotation:e,footprint:l,pinLabels:a,pcbPinLabels:s},p);this.addAll(x)}}get portMap(){return new Proxy({},{get:(e,a)=>{let s=this.children.find(l=>l.componentName==="Port"&&l.isMatchingNameOrAlias(a));if(!s)throw new Error(`There was an issue finding the port "${a.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return s}})}getInstanceForReactElement(e){for(let a of this.reactSubtrees)if(a.element===e)return a.component;return null}doInitialSourceRender(){let e=this.config.sourceFtype;if(!e)return;let{db:a}=this.root,{_parsedProps:s}=this,l=a.source_component.insert({ftype:e,name:this.name,manufacturer_part_number:s.manufacturerPartNumber??s.mfn,supplier_part_numbers:s.supplierPartNumbers});this.source_component_id=l.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let l of this._invalidPinLabelMessages){let p="pinLabels",x=l.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);x&&(p=`pinLabels['${x[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:p,message:l,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:a}=this.config;a?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let s=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&s){if(!this.schematic_component_id)return;let l=NA.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(l)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let e=[];for(let a of this.internallyConnectedPinNames){let s=[];for(let l of a)s.push(this.portMap[l]);e.push(s)}return e}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getSchematicSymbolNameOrThrow(),l=Ps[s],p=this._getGlobalSchematicPositionBeforeLayout();if(l){let x=e.schematic_component.insert({center:p,size:l.size,source_component_id:this.source_component_id,symbol_name:s,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=x.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getSchematicBoxDimensions(),l={};if(Array.isArray(a.pinLabels))a.pinLabels.forEach((B,w)=>{l[String(w+1)]=B});else for(let[B,w]of Object.entries(a.pinLabels??{}))l[B]=Array.isArray(w)?w[0]:w;let p=this._getGlobalSchematicPositionBeforeLayout(),x=this._getSchematicPortArrangement(),f=e.schematic_component.insert({center:p,rotation:a.schRotation??0,size:s.getSize(),port_arrangement:CUt(x),pin_spacing:a.schPinSpacing??.2,pin_styles:vUt(a.schPinStyle,a.pinLabels),port_labels:l,source_component_id:this.source_component_id}),m=x?.topSide!==void 0||x?.bottomSide!==void 0,D=s?.getSize().width,b=s?.getSize().height,E=e.schematic_text.insert({text:a.manufacturerPartNumber??"",schematic_component_id:f.schematic_component_id,anchor:"left",rotation:0,position:{x:m?p.x+(D??0)/2+.1:p.x-(D??0)/2,y:m?p.y+(b??0)/2+.35:p.y-(b??0)/2-.13},color:"#006464",font_size:.18}),A=e.schematic_text.insert({text:a.name??"",schematic_component_id:f.schematic_component_id,anchor:"left",rotation:0,position:{x:m?p.x+(D??0)/2+.1:p.x-(D??0)/2,y:m?p.y+(b??0)/2+.55:p.y+(b??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=f.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:s.subcircuit_id??void 0});if(!(a.footprint??this._getImpliedFootprintString())&&!this.isGroup){let f=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=f.pcb_missing_footprint_error_id}this.pcb_component_id=l.pcb_component_id;let x=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&x){let f=OA.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:s.subcircuit_id??void 0});e.pcb_manual_edit_conflict_warning.insert(f)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:e}=this.root,{_parsedProps:a}=this,s=rK(this.children);if(s.width===0||s.height===0)return;let l={x:(s.minX+s.maxX)/2,y:(s.minY+s.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:l,width:s.width,height:s.height})}_renderReactSubtree(e){return{element:e,component:EBe(e)}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){}doInitialPcbFootprintStringRender(){gVt(this,(e,a)=>this._queueAsyncEffect(e,a))}_hasExistingPortExactly(e){return this.children.filter(s=>s.componentName==="Port").some(s=>{let l=e.getNameAndAliases(),p=s.getNameAndAliases();return l.length===p.length&&l.every(x=>p.includes(x))})}add(e){let a;if((0,LF.isValidElement)(e)){let s=this._renderReactSubtree(e);this.reactSubtrees.push(s),a=s.component}else a=e;if(a.componentName==="Port"){if(this._hasExistingPortExactly(a))return;let l=this.children.filter(p=>p.componentName==="Port").find(p=>p.isMatchingAnyOf(a.getNameAndAliases()));l&&DVt(`Similar ports added. Port 1: ${l}, Port 2: ${a}`)}super.add(a)}getPortsFromFootprint(e){let{footprint:a}=this.props;if((!a||(0,LF.isValidElement)(a))&&(a=this.children.find(l=>l.componentName==="Footprint")),typeof a=="string"){if(VS(a))return[];if(XW(a))return[];let l=Mq.string(a).soup(),p=[];for(let x of l)if("port_hints"in x&&x.port_hints){let f=IF(x.port_hints,e);if(!f)continue;f.originDescription=`footprint:string:${a}:port_hints[0]:${x.port_hints[0]}`,p.push(f)}return p}if(!(0,LF.isValidElement)(a)&&a&&a.componentName==="Footprint"){let l=a,p=1,x=[];for(let f of l.children){if(!f.props.portHints)continue;let m=f.props.portHints;m.some(E=>E.startsWith("pin"))||(m=[...m,`pin${p}`]),p++;let b=IF(m);b&&(b.originDescription=`footprint:${a}`,x.push(b))}return x}let s=[];if(!a){for(let l of this.children)if(l.props.portHints&&l.isPcbPrimitive){let p=IF(l.props.portHints);p&&s.push(p)}}return s}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:e}=this;if(!e.schematicSymbolName)return[];let a=Ps[e.schematicSymbolName];if(!a)return[];let s=[];for(let l of a.ports){let p=IF(l.labels);p&&(p.schematicSymbolPortDef=l,s.push(p))}return s}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:e}=this,a=[];if(e.connections)for(let[s,l]of Object.entries(e.connections)){let p=Array.isArray(l)?l:[l];for(let x of p)a.push(x)}return a}_createNetsFromProps(e){ZW(this,e)}_getPcbCircuitJsonBounds(){let{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let a=e.pcb_component.get(this.pcb_component_id);return{center:{x:a.center.x,y:a.center.y},bounds:{left:a.center.x-a.width/2,top:a.center.y-a.height/2,right:a.center.x+a.width/2,bottom:a.center.y+a.height/2},width:a.width,height:a.height}}_getPinCountFromSchematicPortArrangement(){let e=this._getSchematicPortArrangement();if(!e)return 0;if(!_Be(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);let{leftSide:s,rightSide:l,topSide:p,bottomSide:x}=e;return Math.max(...s?.pins??[],...l?.pins??[],...p?.pins??[],...x?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let a=this.getPortsFromFootprint();if(a.length>0)return a.length;let{pinLabels:s}=this._parsedProps;if(s){if(Array.isArray(s))return s.length;let l=Object.keys(s).map(p=>p.startsWith("pin")?parseInt(p.slice(3)):parseInt(p)).filter(p=>!Number.isNaN(p));return l.length>0?Math.max(...l):Object.keys(s).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this,a=this._getPinCount(),s=e.schPinSpacing??.2;return IUt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:s,numericSchPinStyle:kUt(e.schPinStyle,e.pinLabels),pinCount:a,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:e.pinLabels})}doInitialCadModelRender(){let{db:e}=this.root,{boardThickness:a=0}=this.root?._getBoard()??{},s=this._parsedProps.cadModel,l=this.props.footprint??this._getImpliedFootprintString();if(!this.pcb_component_id||!s&&!l||s===null)return;let p=this._getPcbCircuitJsonBounds(),x=e.pcb_component.get(this.pcb_component_id);if(typeof s=="string")throw new Error("String cadModel not yet implemented");let f=yVt.parse({x:0,y:0,z:typeof s?.rotationOffset=="number"?s.rotationOffset:0,...typeof s?.rotationOffset=="object"?s.rotationOffset??{}:{}}),m=Lf.parse({x:0,y:0,z:0,...typeof s?.positionOffset=="object"?s.positionOffset:{}}),D=this.props.layer==="bottom"?"bottom":"top",b=e.cad_component.insert({position:{x:p.center.x+m.x,y:p.center.y+m.y,z:(D==="bottom"?-a/2:a/2)+m.z},rotation:{x:f.x,y:(D==="top"?0:180)+f.y,z:D==="bottom"?-((x?.rotation??0)+f.z)+180:(x?.rotation??0)+f.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(s??{})?this._addCachebustToModelUrl(s.stlUrl):void 0,model_obj_url:"objUrl"in(s??{})?this._addCachebustToModelUrl(s.objUrl):void 0,model_gltf_url:"gltfUrl"in(s??{})?this._addCachebustToModelUrl(s.gltfUrl):void 0,model_jscad:"jscad"in(s??{})?s.jscad:void 0,footprinter_string:typeof l=="string"&&!s?l:void 0})}_addCachebustToModelUrl(e){if(!e||!e.includes("modelcdn.tscircuit.com"))return e;let a=this.root?.getClientOrigin()??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(a)}`}_getPartsEngineCacheKey(e,a){return JSON.stringify({ftype:e.ftype,name:e.name,manufacturer_part_number:e.manufacturer_part_number,footprinterString:a})}async _getSupplierPartNumbers(e,a,s){if(this.props.doNotPlace)return{};let l=this.root?.platform?.localCacheEngine,p=this._getPartsEngineCacheKey(a,s);if(l){let m=await l.getItem(p);if(m)try{return JSON.parse(m)}catch{}}let x=await Promise.resolve(e.findPart({sourceComponent:a,footprinterString:s})),f=x==="Not found"?{}:x;if(l)try{await l.setItem(p,JSON.stringify(f))}catch{}return f}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let e=this.getInheritedProperty("partsEngine");if(!e)return;let{db:a}=this.root,s=a.source_component.get(this.source_component_id);if(!s||s.supplier_part_numbers)return;let l;this.props.footprint&&typeof this.props.footprint=="string"&&(l=this.props.footprint);let p=this._getSupplierPartNumbers(e,s,l);if(!(p instanceof Promise)){a.source_component.update(this.source_component_id,{supplier_part_numbers:p});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await p,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:e}=this.root,a=e.source_component.get(this.source_component_id);if(a&&!a.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[a,s]of Object.entries(e.connections)){let l=Array.isArray(s)?s:[s];for(let p of l)this.add(new zc({from:`${this.getSubcircuitSelector()} > port.${a}`,to:p}))}}doInitialSourceDesignRuleChecks(){dVt(this)}_getMinimumFlexContainerSize(){return cVt(this)}_repositionOnPcb(e){return lVt(this,e)}doInitialSilkscreenOverlapAdjustment(){return fVt(this)}},bVt=class{constructor(n,e={}){q(this,"input");q(this,"isRouting",!1);q(this,"solver");q(this,"eventHandlers",{complete:[],error:[],progress:[]});q(this,"cycleCount",0);q(this,"stepDelay");q(this,"timeoutId");this.input=n;let{capacityDepth:a,targetMinCapacity:s,stepDelay:l=0}=e;this.solver=new r6e(n,{capacityDepth:a,targetMinCapacity:s,cacheProvider:null}),this.stepDelay=l}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new jF(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 a=(this.solver.iterations-e)/(Date.now()-n)*1e3;this.cycleCount++;let s=this.solver?.preview()||void 0,l=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:a,progress:l,phase:this.solver.getCurrentPhase(),debugGraphics:s}),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 jF(n.message):new jF(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 jF(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},aK=class extends ma{constructor(){super(...arguments);q(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:jAe}}doInitialPortMatching(){let{db:e}=this.root,{_parsedProps:a,parent:s}=this;if(!s)return;if(s.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!s)throw new Error("TraceHint has no parent");if(!a.for){this.renderError(`TraceHint has no for property (${this})`);return}let l=s.selectOne(a.for,{type:"port"});l||this.renderError(`${this} could not find port for selector "${a.for}"`),this.matchedPort=l,l.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:e}=this,a=e.offset?[e.offset]:e.offsets;if(!a)return[];let s=this._computePcbGlobalTransformBeforeLayout();return a.map(l=>({...rs(s,l),via:l.via,to_layer:l.to_layer,trace_width:l.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=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()})}},wBe=({circuitJson:n,editEvents:e,manualEditsFile:a})=>{let s={...a,pcb_placements:[...a.pcb_placements??[]]};for(let l of e)if(l.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:p,new_center:x}=l,f=ia(n).pcb_component.get(p);if(!f)continue;let m=ia(n).source_component.get(f.source_component_id);if(!m)continue;let D=s.pcb_placements?.findIndex(E=>E.selector===m.name),b={selector:m.name,center:x,relative_to:"group_center"};D>=0?s.pcb_placements[D]=b:s.pcb_placements.push(b)}return s},TBe=({circuitJson:n,editEvents:e,manualEditsFile:a})=>{let s={...a,schematic_placements:[...a.schematic_placements??[]]};for(let l of e)if(l.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:p,new_center:x}=l,f=ia(n).schematic_component.get(p);if(!f)continue;let m=ia(n).source_component.get(f.source_component_id);if(!m)continue;let D=s.schematic_placements?.findIndex(E=>E.selector===m.name),b={selector:m.name,center:x,relative_to:"group_center"};D>=0?s.schematic_placements[D]=b:s.schematic_placements.push(b)}return s},FVt=({circuitJson:n,editEvents:e,manualEditsFile:a})=>{let s=e.filter(x=>x.edit_event_type==="edit_schematic_component_location"),l=e.filter(x=>x.edit_event_type==="edit_pcb_component_location"),p=a;return s.length>0&&(p=TBe({circuitJson:n,editEvents:s,manualEditsFile:p})),l.length>0&&(p=wBe({circuitJson:n,editEvents:l,manualEditsFile:p})),p},EVt=(n,e)=>{if(ia(n).pcb_trace_hint.get(e.pcb_trace_hint_id))n=n.map(s=>s.pcb_trace_hint_id===e.pcb_trace_hint_id?{...s,route:e.route}:s);else{let s=ia(n).pcb_port.get(e.pcb_port_id);n=n.filter(l=>!(l.type==="pcb_trace_hint"&&l.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:s?.pcb_component_id}])}return n},vVt=({circuitJson:n,editEvents:e})=>{n=JSON.parse(JSON.stringify(n));for(let a of e)if(a.edit_event_type==="edit_pcb_component_location"){let s=n.find(p=>p.type==="pcb_component"&&p.pcb_component_id===a.pcb_component_id);if((!s||s.center.x!==a.new_center.x||s.center.y!==a.new_center.y)&&a.original_center){let p=ka(a.new_center.x-a.original_center.x,a.new_center.y-a.original_center.y);n=n.map(x=>x.pcb_component_id!==a.pcb_component_id?x:RY(x,p))}}else a.edit_event_type==="edit_schematic_component_location"?n=n.map(s=>s.type==="schematic_component"&&s.schematic_component_id===a.schematic_component_id?{...s,center:a.new_center}:s):a.edit_event_type==="edit_pcb_trace_hint"&&(n=EVt(n,a));return n},PBe=(n,e)=>{let a=n.source_group.list(),s=[],l=p=>{let x=a.filter(f=>f.parent_subcircuit_id===p);for(let f of x)f.subcircuit_id&&(s.push(f.subcircuit_id),l(f.subcircuit_id))};return l(e),s},YW=({db:n,circuitJson:e,subcircuit_id:a,minTraceWidth:s=.1})=>{if(!n&&e&&(n=ia(e)),!n)throw new Error("db or circuitJson is required");let l=n.pcb_trace_hint.list(),p=a?new Set([a]):null;if(a){let K=PBe(n,a);for(let U of K)p.add(U)}let x=(e??n.toArray()).filter(K=>!a||"subcircuit_id"in K&&p.has(K.subcircuit_id)),f=n.pcb_board.list()[0];n=ia(x);let m=Ku(x),D=SBe([...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(K=>!a||p?.has(K.subcircuit_id)),m);for(let K of D){let U=K.connectedTo.flatMap(J=>m.getIdsConnectedToNet(J));K.connectedTo.push(...U)}let b=D.flatMap(K=>[{x:K.center.x-K.width/2,y:K.center.y-K.height/2},{x:K.center.x+K.width/2,y:K.center.y+K.height/2}]),E;if(f?E={minX:f.center.x-f.width/2,maxX:f.center.x+f.width/2,minY:f.center.y-f.height/2,maxY:f.center.y+f.height/2}:E={minX:Math.min(...b.map(K=>K.x))-1,maxX:Math.max(...b.map(K=>K.x))+1,minY:Math.min(...b.map(K=>K.y))-1,maxY:Math.max(...b.map(K=>K.y))+1},a){let K=n.pcb_group.getWhere({subcircuit_id:a});if(K){let U={minX:K.center.x-K.width/2,maxX:K.center.x+K.width/2,minY:K.center.y-K.height/2,maxY:K.center.y+K.height/2};E={minX:Math.min(E.minX,U.minX),maxX:Math.max(E.maxX,U.maxX),minY:Math.min(E.minY,U.minY),maxY:Math.max(E.maxY,U.maxY)}}}let A=new Set(n.pcb_trace.list().map(K=>K.source_trace_id).filter(K=>!!K)),B=n.source_trace.list().filter(K=>!A.has(K.source_trace_id)).map(K=>{let U=K.connected_source_port_ids.map(Ve=>{let et=n.source_port.get(Ve),ct=n.pcb_port.getWhere({source_port_id:Ve});return{...et,...ct}});if(U.length<2)return null;let[J,Q]=U,de=J.layers?.[0]??"top",ce=Q.layers?.[0]??"top",Te=l.filter(Ve=>Ve.pcb_port_id===J.pcb_port_id||Ve.pcb_port_id===Q.pcb_port_id),Ne=[];for(let Ve of Te){let ct=n.pcb_port.get(Ve.pcb_port_id)?.layers?.[0]??"top";for(let Mt of Ve.route)Ne.push({x:Mt.x,y:Mt.y,layer:ct})}return{name:K.source_trace_id??m.getNetConnectedToId(K.source_trace_id)??"",source_trace_id:K.source_trace_id,pointsToConnect:[{x:J.x,y:J.y,layer:de,pointId:J.pcb_port_id,pcb_port_id:J.pcb_port_id},...Ne,{x:Q.x,y:Q.y,layer:ce,pointId:Q.pcb_port_id,pcb_port_id:Q.pcb_port_id}]}}).filter(K=>K!==null),w=new Map(B.map(K=>[K.source_trace_id,K])),P=n.source_net.list().filter(K=>!a||p?.has(K.subcircuit_id)),N=[];for(let K of P){let U=n.source_trace.list().filter(J=>J.connected_source_net_ids?.includes(K.source_net_id));N.push({name:K.source_net_id??m.getNetConnectedToId(K.source_net_id),pointsToConnect:U.flatMap(J=>n.pcb_port.list().filter(de=>J.connected_source_port_ids.includes(de.source_port_id)).map(de=>({x:de.x,y:de.y,layer:de.layers?.[0]??"top",pointId:de.pcb_port_id,pcb_port_id:de.pcb_port_id})))})}let O=n.pcb_breakout_point.list().filter(K=>!a||p?.has(K.subcircuit_id)),$=[],ee=new Map;for(let K of O){let U={x:K.x,y:K.y,layer:"top"};if(K.source_trace_id){let J=w.get(K.source_trace_id)??ee.get(K.source_trace_id);if(J)J.pointsToConnect.push(U);else{let Q={name:K.source_trace_id,source_trace_id:K.source_trace_id,pointsToConnect:[U]};$.push(Q),ee.set(K.source_trace_id,Q)}}else if(K.source_net_id){let J=N.find(Q=>Q.name===K.source_net_id);J?J.pointsToConnect.push(U):$.push({name:K.source_net_id,pointsToConnect:[U]})}else if(K.source_port_id){let J=n.pcb_port.getWhere({source_port_id:K.source_port_id});J&&$.push({name:K.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:J.x,y:J.y,layer:J.layers?.[0]??"top",pointId:J.pcb_port_id,pcb_port_id:J.pcb_port_id},U]})}}let X=[...B,...N,...$],te=new Map;for(let K of X)for(let U of K.pointsToConnect)U.pointId&&te.set(U.pointId,K);let L=n.pcb_trace.list().filter(K=>!a||p?.has(K.subcircuit_id));for(let K of L){let U=new Set;for(let de of K.route)de.start_pcb_port_id&&U.add(de.start_pcb_port_id),de.end_pcb_port_id&&U.add(de.end_pcb_port_id);if(U.size<2)continue;let J=U.values().next().value;if(!J)continue;let Q=te.get(J);Q&&[...U].every(de=>te.get(de)===Q)&&(Q.externallyConnectedPointIds??(Q.externallyConnectedPointIds=[]),Q.externallyConnectedPointIds.push([...U]))}return{simpleRouteJson:{bounds:E,obstacles:D,connections:X,layerCount:f?.num_layers??2,minTraceWidth:s},connMap:m}},CVt=n=>{let e={};if(!n)return e;for(let s of id)e[s]=0;let a=new Map;for(let s of n){let[,,l,p]=s.type.split(":");if(p==="start"){a.set(`${l}:${s.renderId}`,s);continue}if(p==="end"){let x=a.get(`${l}:${s.renderId}`);if(x){let f=s.createdAt-x.createdAt;e[l]=(e[l]||0)+f}}}return e},_Vt=n=>{let e=n.map(m=>[...new Set(m)]),a=e.map(()=>[]),s=e.map(()=>null);for(let m=0;m<e.length;m++)for(let D of e[m])if(/^\d+$/.test(D)){s[m]=Number.parseInt(D);break}let l=0,p=new Set;for(let m=0;m<s.length;m++){let D=s[m];if(D===null||D<1)continue;if(!p.has(D)){p.add(D),a[m].push(`pin${D}`),l=Math.max(l,D);continue}let b=0;for(let E of a[m])E.startsWith(`pin${D}_alt`)&&b++;a[m].push(`pin${D}_alt${b+1}`)}for(let m=0;m<a.length;m++)a[m][0]?.includes("_alt")&&(l++,a[m].unshift(`pin${l}`));for(let m=0;m<a.length;m++)a[m].length===0&&(l++,a[m].push(`pin${l}`));let x={};for(let m of e)for(let D of m)/^\d+$/.test(D)||(x[D]=(x[D]??0)+1);let f={};for(let m=0;m<e.length;m++){let D=e[m];for(let b of D)/^\d+$/.test(b)||(x[b]===1?a[m].push(b):(f[b]=(f[b]??0)+1,a[m].push(`${b}${f[b]}`)))}return a},sBe=(0,IBe.default)("Group_doInitialSchematicLayoutMatchAdapt");function AVt(n){let{db:e}=n.root,a=Lb(e.toArray(),{source_group_id:n.source_group_id}),s=rH(a);sBe.enabled&&global.debugGraphics?.push(Vp(s,{title:`floatingBpcGraph-${n.name}`}));let l=rH(a),p={boxes:l.boxes,pins:l.pins.map(m=>({...m,color:m.color.replace("not_connected","normal")}))},{result:x}=TRe([{variantName:"default",floatingGraph:l},{variantName:"noNotConnected",floatingGraph:p}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(l.boxes.filter(m=>l.pins.filter(E=>E.boxId===m.boxId).filter(E=>!E.color.includes("center")).length<=2).map(m=>m.boxId)),corpus:{}});sBe.enabled&&global.debugGraphics?.push(Vp(x,{title:`laidOutBpcGraph-${n.name}`}));let f=n._getGlobalSchematicPositionBeforeLayout();for(let m of x.boxes){if(!m.center)continue;let D=e.schematic_component.get(m.boxId);if(D){let E={x:m.center.x+f.x,y:m.center.y+f.y},A=e.schematic_port.list({schematic_component_id:D.schematic_component_id}),B=e.schematic_text.list({schematic_component_id:D.schematic_component_id}),w={x:E.x-D.center.x,y:E.y-D.center.y};for(let P of A)P.center.x+=w.x,P.center.y+=w.y;for(let P of B)P.position.x+=w.x,P.position.y+=w.y;D.center=E;continue}let b=e.schematic_net_label.get(m.boxId);if(b){let E=x.pins.find(B=>B.boxId===m.boxId&&B.color==="netlabel_center");if(!E)throw new Error(`No pin found for net label: ${m.boxId}`);let A={x:m.center.x+f.x,y:m.center.y+f.y};b.center=A,b.anchor_position={x:A.x+E.offset.x,y:A.y+E.offset.y};continue}console.error(`No schematic element found for box: ${m.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var nn=(0,jBe.default)("Group_doInitialSchematicLayoutMatchpack");function iBe(n){switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function oBe(n,e){let a=["right","up","left","down"],s=a.indexOf(n);if(s===-1)return n;let l=Math.round(e/90),p=(s+l)%4;return a[p<0?p+4:p]}function RVt(n,e,a){let s={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};nn(`[${a.name}] Processing ${n.childNodes.length} child nodes for input problem`),n.childNodes.forEach((p,x)=>{if(nn(`[${a.name}] Processing child ${x}: nodeType=${p.nodeType}`),p.nodeType==="component"?nn(`[${a.name}] - Component: ${p.sourceComponent?.name}`):p.nodeType==="group"&&nn(`[${a.name}] - Group: ${p.sourceGroup?.name}`),p.nodeType==="component"&&p.sourceComponent){let f=p.sourceComponent.name||`chip_${x}`,m=e.schematic_component.getWhere({source_component_id:p.sourceComponent.source_component_id});if(!m)return;let D=a.children.find(A=>A.source_component_id===p.sourceComponent?.source_component_id),b=[0,90,180,270];D?._parsedProps?.schOrientation&&(b=[0]),D?._parsedProps?.schRotation!==void 0&&(b=[0]),s.chipMap[f]={chipId:f,pins:[],size:{x:m.size?.width||1,y:m.size?.height||1},availableRotations:b};let E=e.schematic_port.list({schematic_component_id:m.schematic_component_id});for(let A of E){let B=e.source_port.get(A.source_port_id);if(!B)continue;let w=`${f}.${B.pin_number||B.name||A.schematic_port_id}`;s.chipMap[f].pins.push(w);let P=iBe(A.facing_direction);s.chipPinMap[w]={pinId:w,offset:{x:(A.center?.x||0)-(m.center.x||0),y:(A.center?.y||0)-(m.center.y||0)},side:P}}}else if(p.nodeType==="group"&&p.sourceGroup){let f=p.sourceGroup.name||`group_${x}`;nn(`[${a.name}] Processing nested group: ${f}`);let m=e.schematic_group?.getWhere?.({source_group_id:p.sourceGroup.source_group_id});if(nn(`[${a.name}] Found schematic_group for ${f}:`,m),m){nn(`[${a.name}] Treating group ${f} as composite chip`);let D=e.schematic_component.list({schematic_group_id:m.schematic_group_id});nn(`[${a.name}] Group ${f} has ${D.length} components:`,D.map($=>$.source_component_id));let b=1/0,E=-1/0,A=1/0,B=-1/0,w=!1;for(let $ of D)if($.center&&$.size){w=!0;let ee=$.size.width/2,X=$.size.height/2;b=Math.min(b,$.center.x-ee),E=Math.max(E,$.center.x+ee),A=Math.min(A,$.center.y-X),B=Math.max(B,$.center.y+X)}let P=w?E-b:2,N=w?B-A:2;nn(`[${a.name}] Group ${f} computed size: ${P} x ${N}`);let O=[];for(let $ of D){let ee=e.schematic_port.list({schematic_component_id:$.schematic_component_id});for(let X of ee){let te=e.source_port.get(X.source_port_id);if(!te)continue;let L=`${f}.${te.pin_number||te.name||X.schematic_port_id}`;O.push(L);let K=m.center||{x:0,y:0},U=iBe(X.facing_direction);s.chipPinMap[L]={pinId:L,offset:{x:(X.center?.x||0)-K.x,y:(X.center?.y||0)-K.y},side:U}}}nn(`[${a.name}] Group ${f} has ${O.length} pins:`,O),s.chipMap[f]={chipId:f,pins:O,size:{x:P,y:N}},nn(`[${a.name}] Added group ${f} to chipMap`)}else nn(`[${a.name}] Warning: No schematic_group found for group ${f}`)}}),nn(`[${a.name}] Creating connections using connectivity keys`);let l=new Map;for(let[p,x]of Object.entries(s.chipMap))for(let f of x.pins){let m=f.split(".").pop(),D=n.childNodes.find(b=>b.nodeType==="component"&&b.sourceComponent?b.sourceComponent.name===p:b.nodeType==="group"&&b.sourceGroup?`group_${n.childNodes.indexOf(b)}`===p:!1);if(D?.nodeType==="group"&&D.sourceGroup){let b=e.schematic_group?.getWhere?.({source_group_id:D.sourceGroup.source_group_id});if(b){let E=e.schematic_component.list({schematic_group_id:b.schematic_group_id});for(let A of E){let B=e.source_port.list({source_component_id:A.source_component_id});for(let w of B){let P=w.pin_number||w.name;if(String(P)===String(m))if(w.subcircuit_connectivity_map_key){let N=w.subcircuit_connectivity_map_key;l.has(N)||l.set(N,[]),l.get(N).push(f),nn(`[${a.name}] \u2713 Pin ${f} has connectivity key: ${N}`)}else nn(`[${a.name}] Pin ${f} has no connectivity key`)}}}}else if(D?.nodeType==="component"&&D.sourceComponent){let b=e.source_port.list({source_component_id:D.sourceComponent.source_component_id});for(let E of b){let A=E.pin_number||E.name;if(String(A)===String(m)&&E.subcircuit_connectivity_map_key){let B=E.subcircuit_connectivity_map_key;l.has(B)||l.set(B,[]),l.get(B).push(f),nn(`[${a.name}] Pin ${f} has connectivity key: ${B}`)}}}}nn(`[${a.name}] Found ${l.size} connectivity groups:`,Array.from(l.entries()).map(([p,x])=>({key:p,pins:x})));for(let[p,x]of l)if(x.length>=2){let f=e.source_trace.list().filter(b=>b.subcircuit_connectivity_map_key===p),m=f.some(b=>b.connected_source_net_ids&&b.connected_source_net_ids.length>0),D=f.some(b=>b.connected_source_port_ids&&b.connected_source_port_ids.length>=2);if(nn(`[${a.name}] Connectivity ${p}: hasNetConnections=${m}, hasDirectConnections=${D}`),D){for(let b of f)if(b.connected_source_port_ids&&b.connected_source_port_ids.length>=2){let E=[];for(let A of b.connected_source_port_ids)for(let B of x){let w=B.split(".").pop(),P=e.source_port.get(A);if(P&&String(P.pin_number||P.name)===String(w)){let N=B.split(".")[0],O=n.childNodes.find($=>$.nodeType==="component"&&$.sourceComponent?$.sourceComponent.name===N:$.nodeType==="group"&&$.sourceGroup?`group_${n.childNodes.indexOf($)}`===N:!1);O?.nodeType==="component"&&O.sourceComponent&&e.source_port.list({source_component_id:O.sourceComponent.source_component_id}).some(ee=>ee.source_port_id===A)&&E.push(B)}}for(let A=0;A<E.length;A++)for(let B=A+1;B<E.length;B++){let w=E[A],P=E[B];s.pinStrongConnMap[`${w}-${P}`]=!0,s.pinStrongConnMap[`${P}-${w}`]=!0,nn(`[${a.name}] Created strong connection: ${w} <-> ${P}`)}}}if(m){let b=e.source_net.getWhere({subcircuit_connectivity_map_key:p}),E=b?.is_ground??!1,A=b?.is_power??!1;s.netMap[p]={netId:p,isGround:E,isPositiveVoltageSource:A};for(let B of x)s.netConnMap[`${B}-${p}`]=!0;nn(`[${a.name}] Created net ${p} with ${x.length} pins:`,x)}}return s}function SVt(n){let{db:e}=n.root,a=ig(e.toArray(),{source_group_id:n.source_group_id});if(nn(`[${n.name}] Starting matchpack layout with ${a.childNodes.length} children`),nn(`[${n.name}] Tree structure:`,JSON.stringify(a,null,2)),a.childNodes.length<=1){nn(`[${n.name}] Only ${a.childNodes.length} children, skipping layout`);return}nn("Converting circuit tree to InputProblem...");let s=RVt(a,e,n);nn.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${n.name}`,content:JSON.stringify(s,null,2)});let l=new L5e(s);if(nn("Starting LayoutPipelineSolver..."),nn.enabled&&global.debugGraphics){let m=l.visualize();global.debugGraphics.push({...m,title:`matchpack-initial-${n.name}`})}if(l.solve(),nn(`Solver completed in ${l.iterations} iterations`),nn(`Solved: ${l.solved}, Failed: ${l.failed}`),l.failed)throw nn(`Solver failed with error: ${l.error}`),new Error(`Matchpack layout solver failed: ${l.error}`);let p=l.getOutputLayout();if(nn("OutputLayout:",JSON.stringify(p,null,2)),nn("Solver completed successfully:",!l.failed),nn.enabled&&global.debugGraphics){let m=l.visualize();global.debugGraphics.push({...m,title:`matchpack-final-${n.name}`})}let x=l.checkForOverlaps(p);if(x.length>0){nn(`Warning: Found ${x.length} overlapping components:`);for(let m of x)nn(` ${m.chip1} overlaps ${m.chip2} (area: ${m.overlapArea})`)}let f=n._getGlobalSchematicPositionBeforeLayout();nn(`Group offset: x=${f.x}, y=${f.y}`),nn(`Applying layout results for ${Object.keys(p.chipPlacements).length} chip placements`);for(let[m,D]of Object.entries(p.chipPlacements)){nn(`Processing placement for chip: ${m} at (${D.x}, ${D.y})`);let b=a.childNodes.find(A=>{if(A.nodeType==="component"&&A.sourceComponent){let B=A.sourceComponent.name===m;return nn(` Checking component ${A.sourceComponent.name}: matches=${B}`),B}if(A.nodeType==="group"&&A.sourceGroup){let B=A.sourceGroup.name,w=`group_${a.childNodes.indexOf(A)}`,P=w===m;return nn(` Checking group ${B} (expected chipId: ${w}): matches=${P}`),P}return!1});if(!b){nn(`Warning: No tree node found for chip: ${m}`),nn("Available tree nodes:",a.childNodes.map((A,B)=>({type:A.nodeType,name:A.nodeType==="component"?A.sourceComponent?.name:A.sourceGroup?.name,expectedChipId:A.nodeType==="group"?`group_${B}`:A.sourceComponent?.name})));continue}let E={x:D.x+f.x,y:D.y+f.y};if(b.nodeType==="component"&&b.sourceComponent){let A=e.schematic_component.getWhere({source_component_id:b.sourceComponent.source_component_id});if(A){nn(`Moving component ${m} to (${E.x}, ${E.y})`);let B=e.schematic_port.list({schematic_component_id:A.schematic_component_id}),w=e.schematic_text.list({schematic_component_id:A.schematic_component_id}),P={x:E.x-A.center.x,y:E.y-A.center.y};for(let N of B)N.center.x+=P.x,N.center.y+=P.y;for(let N of w)N.position.x+=P.x,N.position.y+=P.y;if(A.center=E,D.ccwRotationDegrees!==0){nn(`Component ${m} has rotation: ${D.ccwRotationDegrees}\xB0`);let N=D.ccwRotationDegrees*Math.PI/180,O=Math.cos(N),$=Math.sin(N);for(let ee of B){let X=ee.center.x-E.x,te=ee.center.y-E.y,L=X*O-te*$,K=X*$+te*O;ee.center.x=E.x+L,ee.center.y=E.y+K;let U=ee.facing_direction||"right";ee.facing_direction=oBe(U,D.ccwRotationDegrees)}for(let ee of w){let X=ee.position.x-E.x,te=ee.position.y-E.y,L=X*O-te*$,K=X*$+te*O;ee.position.x=E.x+L,ee.position.y=E.y+K}if(A.symbol_name){let ee=A.symbol_name.match(/_(right|left|up|down)$/);ee&&(A.symbol_name=A.symbol_name.replace(ee[0],`_${oBe(ee[1],D.ccwRotationDegrees)}`))}}}}else if(b.nodeType==="group"&&b.sourceGroup){let A=e.schematic_group?.getWhere?.({source_group_id:b.sourceGroup.source_group_id});if(A){nn(`Moving group ${m} to (${E.x}, ${E.y}) from (${A.center?.x}, ${A.center?.y})`);let B=e.schematic_component.list({schematic_group_id:A.schematic_group_id});nn(`Group ${m} has ${B.length} components to move`);let w=A.center||{x:0,y:0},P={x:E.x-w.x,y:E.y-w.y};nn(`Position delta for group ${m}: (${P.x}, ${P.y})`);for(let N of B)if(N.center){let O={...N.center};N.center.x+=P.x,N.center.y+=P.y,nn(`Moved component ${N.source_component_id} from (${O.x}, ${O.y}) to (${N.center.x}, ${N.center.y})`);let $=e.schematic_port.list({schematic_component_id:N.schematic_component_id}),ee=e.schematic_text.list({schematic_component_id:N.schematic_component_id});for(let X of $)X.center&&(X.center.x+=P.x,X.center.y+=P.y);for(let X of ee)X.position&&(X.position.x+=P.x,X.position.y+=P.y)}A.center=E,nn(`Updated group ${m} center to (${E.x}, ${E.y})`)}}}nn("Matchpack layout completed successfully")}function BVt(n){if(!n.isSubcircuit)return;let{db:e}=n.root,a=n.selectAll("trace"),s=new Pb({});s.addConnections(a.map(f=>{let m=e.source_trace.get(f.source_trace_id);return m?[m.source_trace_id,...m.connected_source_port_ids,...m.connected_source_net_ids]:null}).filter(f=>f!==null));let{name:l}=n._parsedProps;for(let f of a){if(!f.source_trace_id)continue;let m=s.getNetConnectedToId(f.source_trace_id);m&&(f.subcircuit_connectivity_map_key=`${l??`unnamedsubcircuit${n._renderId}`}_${m}`,e.source_trace.update(f.source_trace_id,{subcircuit_connectivity_map_key:f.subcircuit_connectivity_map_key}))}let p=new Set;for(let f of a){if(!f.source_trace_id)continue;let m=e.source_trace.get(f.source_trace_id);if(m)for(let D of m.connected_source_port_ids)p.add(D)}for(let f of p){let m=s.getNetConnectedToId(f);if(!m)continue;let D=`${l??`unnamedsubcircuit${n._renderId}`}_${m}`;e.source_port.update(f,{subcircuit_connectivity_map_key:D})}let x=new Set;for(let f of a){if(!f.source_trace_id)continue;let m=e.source_trace.get(f.source_trace_id);if(m)for(let D of m.connected_source_net_ids)x.add(D)}for(let f of x){let m=s.getNetConnectedToId(f);if(!m)continue;let D=`${l??`unnamedsubcircuit${n._renderId}`}_${m}`;e.source_net.update(f,{subcircuit_connectivity_map_key:D})}}function wVt(n){let{db:e}=n.root,a=n._parsedProps,s=n.children.filter(te=>{let L=te._parsedProps?.schX!==void 0||te._parsedProps?.schY!==void 0;return te.schematic_component_id&&!L});if(s.length===0)return;let l=0,p=0;for(let te of s){let L=e.schematic_component.get(te.schematic_component_id);L?.size&&(l=Math.max(l,L.size.width),p=Math.max(p,L.size.height))}l===0&&s.length>0&&(l=1),p===0&&s.length>0&&(p=1);let x=a.gridCols,f,m=a.gridGap,D=a.gridRowGap,b=a.gridColumnGap;a.schLayout?.grid&&(x=a.schLayout.grid.cols??x,f=a.schLayout.grid.rows,m=a.schLayout.gridGap??m,D=a.schLayout.gridRowGap??D,b=a.schLayout.gridColumnGap??b);let E,A;x!==void 0&&f!==void 0?(E=x,A=f):x!==void 0?(E=x,A=Math.ceil(s.length/E)):f!==void 0?(A=f,E=Math.ceil(s.length/A)):(E=Math.ceil(Math.sqrt(s.length)),A=Math.ceil(s.length/E)),E===0&&s.length>0&&(E=1),A===0&&s.length>0&&(A=s.length);let B,w,P=te=>{if(te!==void 0)return typeof te=="number"?te:xe.parse(te)};if(D!==void 0||b!==void 0){let te=typeof m=="object"&&m!==null?m.x:m,L=typeof m=="object"&&m!==null?m.y:m;B=P(b??te)??1,w=P(D??L)??1}else if(typeof m=="number")B=m,w=m;else if(typeof m=="string"){let te=xe.parse(m);B=te,w=te}else if(typeof m=="object"&&m!==null){let te=m.x,L=m.y;B=typeof te=="number"?te:xe.parse(te??"0mm"),w=typeof L=="number"?L:xe.parse(L??"0mm")}else B=1,w=1;let N=E*l+Math.max(0,E-1)*B,O=A*p+Math.max(0,A-1)*w,$=n._getGlobalSchematicPositionBeforeLayout(),ee=$.x-N/2+l/2,X=$.y+O/2-p/2;for(let te=0;te<s.length;te++){let L=s[te];if(!L.schematic_component_id)continue;let K=Math.floor(te/E),U=te%E;if(K>=A||U>=E){console.warn(`Schematic grid layout: Child ${L.getString()} at index ${te} (row ${K}, col ${U}) exceeds specified grid dimensions (${A}x${E}). Skipping placement.`);continue}let J=ee+U*(l+B),Q=X-K*(p+w),de=e.schematic_component.get(L.schematic_component_id);if(de){let ce=de.center,Te={x:J,y:Q};e.schematic_component.update(L.schematic_component_id,{center:Te});let Ne=Te.x-ce.x,Ve=Te.y-ce.y,et=e.schematic_port.list({schematic_component_id:L.schematic_component_id});for(let Mt of et)e.schematic_port.update(Mt.schematic_port_id,{center:{x:Mt.center.x+Ne,y:Mt.center.y+Ve}});let ct=e.schematic_text.list({schematic_component_id:L.schematic_component_id});for(let Mt of ct)e.schematic_text.update(Mt.schematic_text_id,{position:{x:Mt.position.x+Ne,y:Mt.position.y+Ve}})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:N,height:O,center:$})}var uBe=(n,e)=>{let{sourceComponent:a,sourceGroup:s}=e;if(e.nodeType==="component"){let l=n.schematic_component.getWhere({source_component_id:a?.source_component_id});return l?.size?{width:l.size.width,height:l.size.height}:null}if(e.nodeType==="group"){let l=n.schematic_group.getWhere({source_group_id:s?.source_group_id});if(l?.width&&l?.height)return{width:l.width,height:l.height};let p=n.schematic_component.list({schematic_group_id:l?.schematic_group_id}),x=1/0,f=-1/0,m=1/0,D=-1/0;for(let A of p)if(A.center&&A.size){let B=A.size.width/2,w=A.size.height/2;x=Math.min(x,A.center.x-B),f=Math.max(f,A.center.x+B),m=Math.min(m,A.center.y-w),D=Math.max(D,A.center.y+w)}let b=f-x,E=D-m;return{width:b,height:E}}return null},TVt=n=>{let{db:e}=n.root,a=n._parsedProps,s=ig(e.toArray(),{source_group_id:n.source_group_id}),l=a.schJustifyContent??a.justifyContent,p=a.schAlignItems??a.alignItems,x=a.schFlexGap??a.schGap??a.gap,f=a.schFlexDirection??"row",m={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[l??"space-between"],D={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[p??"center"];if(!m)throw new Error(`Invalid justifyContent value: "${l}"`);if(!D)throw new Error(`Invalid alignItems value: "${p}"`);let b=0,E=0;typeof x=="object"?(b=x.y??0,E=x.x??0):typeof x=="number"?(b=x,E=x):typeof x=="string"&&(b=xe.parse(x),E=xe.parse(x));let A,B=a.width??a.schWidth??void 0,w=a.height??a.schHeight??void 0;(B===void 0||w===void 0)&&(A=g5(s.childNodes.map(X=>uBe(e,X)).filter(X=>X!==null),{alignItems:D,justifyContent:m,direction:f,rowGap:b,columnGap:E}),B=A.width,w=A.height);let N=new FS(B,w,{alignItems:D,justifyContent:m,direction:f,rowGap:b,columnGap:E});for(let X of s.childNodes){let te=uBe(e,X);N.addChild({metadata:X,width:te?.width??0,height:te?.height??0,flexBasis:te?f==="row"?te.width:te.height:void 0})}N.build();let O={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let X of N.children)O.minX=Math.min(O.minX,X.position.x),O.minY=Math.min(O.minY,X.position.y),O.maxX=Math.max(O.maxX,X.position.x+X.size.width),O.maxY=Math.max(O.maxY,X.position.y+X.size.height);O.width=O.maxX-O.minX,O.height=O.maxY-O.minY;let $={x:-(O.maxX+O.minX)/2,y:-(O.maxY+O.minY)/2},ee=e.toArray();for(let X of N.children){let{sourceComponent:te,sourceGroup:L}=X.metadata;if(te){let K=e.schematic_component.getWhere({source_component_id:te.source_component_id});if(!K)continue;n4e(ee,K.schematic_component_id,{x:X.position.x+X.size.width/2+$.x,y:X.position.y+X.size.height/2+$.y})}if(L){if(!e.schematic_group.getWhere({source_group_id:L.source_group_id}))continue;s4e(ee,L.source_group_id,{x:X.position.x+X.size.width/2+$.x,y:X.position.y+X.size.height/2+$.y})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:O.width,height:O.height})},NW=1;function PVt(n){let{db:e}=n.root,a=n._parsedProps,s=IVt(n);if(s.length===0)return;let l=jVt({db:e,pcbChildren:s}),p=kVt(a),x=NVt({props:a,pcbChildren:s,childDimensions:l,gridConfig:p}),f=LVt({pcbChildren:s,childDimensions:l,gridLayout:x,gridConfig:p}),{itemCoordinates:m}=f.layout();$Vt({db:e,group:n,pcbChildren:s,itemCoordinates:m,gridLayout:x}),zVt({db:e,group:n,props:a,gridLayout:x})}function IVt(n){return n.children.filter(e=>e.pcb_component_id||e.pcb_group_id)}function jVt(n){let{db:e,pcbChildren:a}=n,s=0,l=0;for(let p of a){let x=0,f=0;if(p.pcb_group_id){let m=e.pcb_group.get(p.pcb_group_id);x=m?.width??0,f=m?.height??0}else if(p.pcb_component_id){let m=e.pcb_component.get(p.pcb_component_id);x=m?.width??0,f=m?.height??0}s=Math.max(s,x),l=Math.max(l,f)}return{width:s,height:l}}function kVt(n){let e=n.pcbGridCols??n.gridCols??n.pcbLayout?.grid?.cols,a=n.pcbGridRows??n.pcbLayout?.grid?.rows,s=n.pcbGridTemplateColumns,l=n.pcbGridTemplateRows,p=E=>E===void 0?NW:typeof E=="number"?E:xe.parse(E),x=n.pcbGridGap??n.gridGap??n.pcbLayout?.gridGap,f=n.pcbGridRowGap??n.gridRowGap??n.pcbLayout?.gridRowGap,m=n.pcbGridColumnGap??n.gridColumnGap??n.pcbLayout?.gridColumnGap,D=NW,b=NW;if(f!==void 0||m!==void 0){let E=typeof x=="object"?x?.x:x,A=typeof x=="object"?x?.y:x;D=p(m??E),b=p(f??A)}else if(typeof x=="object"&&x!==null)D=p(x.x),b=p(x.y);else{let E=p(x);D=E,b=E}return{cols:e,rows:a,gapX:D,gapY:b,templateColumns:s,templateRows:l}}function NVt(n){let{props:e,pcbChildren:a,childDimensions:s,gridConfig:l}=n;return e.pcbGridTemplateColumns||e.pcbGridTemplateRows?MVt({props:e,gridConfig:l,pcbChildren:a,childDimensions:s}):OVt({gridConfig:l,pcbChildren:a,childDimensions:s})}function MVt(n){let{props:e,gridConfig:a,pcbChildren:s,childDimensions:l}=n,p=e.pcbGridTemplateColumns??"",x=e.pcbGridTemplateRows??"",f=A=>{let B=A.match(/repeat\((\d+),/);return B?parseInt(B[1]):Math.ceil(Math.sqrt(s.length))},m=e.pcbGridTemplateColumns?f(p):Math.ceil(Math.sqrt(s.length)),D=e.pcbGridTemplateRows?f(x):Math.ceil(s.length/m),b=m*l.width+Math.max(0,m-1)*a.gapX,E=D*l.height+Math.max(0,D-1)*a.gapY;return{gridTemplateColumns:p,gridTemplateRows:x,containerWidth:b,containerHeight:E}}function OVt(n){let{gridConfig:e,pcbChildren:a,childDimensions:s}=n,l,p;e.cols!==void 0&&e.rows!==void 0?(l=e.cols,p=e.rows):e.cols!==void 0?(l=e.cols,p=Math.ceil(a.length/l)):e.rows!==void 0?(p=e.rows,l=Math.ceil(a.length/p)):(l=Math.ceil(Math.sqrt(a.length)),p=Math.ceil(a.length/l)),l=Math.max(1,l),p=Math.max(1,p);let x=l*s.width+Math.max(0,l-1)*e.gapX,f=p*s.height+Math.max(0,p-1)*e.gapY,m=`repeat(${l}, ${s.width}px)`,D=`repeat(${p}, ${s.height}px)`;return{gridTemplateColumns:m,gridTemplateRows:D,containerWidth:x,containerHeight:f}}function LVt(n){let{pcbChildren:e,childDimensions:a,gridLayout:s,gridConfig:l}=n,p=e.map((x,f)=>({key:x.getString()||`child-${f}`,contentWidth:a.width,contentHeight:a.height}));return new H5e({containerWidth:s.containerWidth,containerHeight:s.containerHeight,gridTemplateColumns:s.gridTemplateColumns,gridTemplateRows:s.gridTemplateRows,gap:[l.gapY,l.gapX],children:p})}function $Vt(n){let{db:e,group:a,pcbChildren:s,itemCoordinates:l,gridLayout:p}=n,x=a._getGlobalPcbPositionBeforeLayout(),f=e.toArray();for(let m=0;m<s.length;m++){let D=s[m],b=D.getString()||`child-${m}`,E=l[b];if(!E){console.warn(`PCB grid layout: No coordinates found for child ${b}`);continue}let A=x.x-p.containerWidth/2+E.x+E.width/2,B=x.y+p.containerHeight/2-E.y-E.height/2;if(D.pcb_component_id)h5(f,D.pcb_component_id,{x:A,y:B});else{let w=D;w.pcb_group_id&&w.source_group_id&&m5(f,w.source_group_id,{x:A,y:B})}}}function zVt(n){let{db:e,group:a,props:s,gridLayout:l}=n;if(a.pcb_group_id){let p=a._getGlobalPcbPositionBeforeLayout();e.pcb_group.update(a.pcb_group_id,{width:s.width??l.containerWidth,height:s.height??l.containerHeight,center:p})}}function qVt(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 a=typeof n=="object"?n.preset:n,s=typeof n=="object"?n:{};switch(a){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:l,local:p,groupMode:x,...f}=s;return{local:!1,groupMode:"subcircuit",...e,...f}}default:return{local:!0,groupMode:"subcircuit"}}}var UVt="1mm",cBe=(0,kBe.default)("Group_doInitialPcbLayoutPack"),kF=(n,e,a)=>{if(e===a)return!0;let s=n.source_group.get(e);return!s||!s.parent_source_group_id?!1:kF(n,s.parent_source_group_id,a)},VVt=n=>{let{db:e}=n.root,{_parsedProps:a}=n,{packOrderStrategy:s,packPlacementStrategy:l,gap:p,pcbGap:x,pcbPackGap:f}=a,m=f??x??p,D=xe.parse(m??UVt),b={...M5e(N5e(e.toArray(),{source_group_id:n.source_group_id,shouldAddInnerObstacles:!0})),orderStrategy:s??"largest_to_smallest",placementStrategy:l??"minimum_sum_squared_distance_to_network",minGap:D};cBe.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:b}));let E=gS(b);if(cBe.enabled){let A=mS(E);A.title=`packOutput-${n.name}`,global.debugGraphics?.push(A)}for(let A of E.components){let{center:B,componentId:w,ccwRotationOffset:P,ccwRotationDegrees:N}=A,O=e.pcb_component.get(w);if(O){let K=n.source_group_id,J=e.source_component.get(O.source_component_id)?.source_group_id;if(J!==void 0&&!kF(e,J,K))continue;let Q=O.center,de=N??P??0,ce=Ts(n._computePcbGlobalTransformBeforeLayout(),ka(B.x,B.y),Xf(de*Math.PI/180),ka(-Q.x,-Q.y)),Te=e.toArray().filter(Ne=>"pcb_component_id"in Ne&&Ne.pcb_component_id===w);$b(Te,ce);continue}let $=e.pcb_group.list().find(K=>K.source_group_id===w);if(!$)continue;let ee=$.center,X=N??P??0,te=Ts(n._computePcbGlobalTransformBeforeLayout(),ka(B.x,B.y),Xf(X*Math.PI/180),ka(-ee.x,-ee.y)),L=e.toArray().filter(K=>{if("source_group_id"in K&&K.source_group_id&&(K.source_group_id===w||kF(e,K.source_group_id,w)))return!0;if("source_component_id"in K&&K.source_component_id){let U=e.source_component.get(K.source_component_id);if(U?.source_group_id&&(U.source_group_id===w||kF(e,U.source_group_id,w)))return!0}if("pcb_component_id"in K&&K.pcb_component_id){let U=e.pcb_component.get(K.pcb_component_id);if(U?.source_component_id){let J=e.source_component.get(U.source_component_id);if(J?.source_group_id&&(J.source_group_id===w||kF(e,J.source_group_id,w)))return!0}}return!1});$b(L,te),e.pcb_group.update($.pcb_group_id,{center:B})}},GVt=n=>{let{db:e}=n.root,{_parsedProps:a}=n,s=n.children.filter(te=>te.pcb_component_id||te.pcb_group_id);if(s.some(te=>{let L=te._parsedProps;return L?.pcbX!==void 0||L?.pcbY!==void 0}))return;let p=a.pcbJustifyContent??a.justifyContent,x=a.pcbAlignItems??a.alignItems,f=a.pcbFlexGap??a.pcbGap??a.gap,m=a.pcbFlexDirection??"row",D={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"}[p??"space-between"],b={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[x??"center"];if(!D)throw new Error(`Invalid justifyContent value: "${p}"`);if(!b)throw new Error(`Invalid alignItems value: "${x}"`);let E=0,A=0;typeof f=="object"?(E=f.y??0,A=f.x??0):typeof f=="number"?(E=f,A=f):typeof f=="string"&&(E=xe.parse(f),A=xe.parse(f));let B,w=a.width??a.pcbWidth??void 0,P=a.height??a.pcbHeight??void 0;(w===void 0||P===void 0)&&(B=g5(s.map(te=>te._getMinimumFlexContainerSize()).filter(te=>te!==null),{alignItems:b,justifyContent:D,direction:m,rowGap:E,columnGap:A}),w=B.width,P=B.height);let O=new FS(w,P,{alignItems:b,justifyContent:D,direction:m,rowGap:E,columnGap:A});for(let te of s){let L=te._getMinimumFlexContainerSize();O.addChild({metadata:te,width:L?.width??0,height:L?.height??0,flexBasis:L?m==="row"?L.width:L.height:void 0})}O.build();let $={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let te of O.children)$.minX=Math.min($.minX,te.position.x),$.minY=Math.min($.minY,te.position.y),$.maxX=Math.max($.maxX,te.position.x+te.size.width),$.maxY=Math.max($.maxY,te.position.y+te.size.height);$.width=$.maxX-$.minX,$.height=$.maxY-$.minY;let ee=n._getGlobalPcbPositionBeforeLayout(),X={x:ee.x-($.maxX+$.minX)/2,y:ee.y-($.maxY+$.minY)/2};for(let te of O.children)te.metadata._repositionOnPcb({x:te.position.x+te.size.width/2+X.x,y:te.position.y+te.size.height/2+X.y});e.pcb_group.update(n.pcb_group_id,{width:$.width,height:$.height,center:ee})};function XVt(n){let{db:e}=n.root,a=new Map,s=new Map,l=new Set,x=n.selectAll("trace").filter(Q=>Q._parsedProps?.schDisplayLabel),f=n.selectAll("group"),m=[n.schematic_group_id,...f.map(Q=>Q.schematic_group_id)],D=e.schematic_component.list().filter(Q=>m.includes(Q.schematic_group_id)),b=[],E=new Map,A=new Map;for(let Q of D){let de=Q.schematic_component_id,ce=[],Te=e.source_component.getWhere({source_component_id:Q.source_component_id}),Ne=e.schematic_port.list({schematic_component_id:Q.schematic_component_id});for(let Ve of Ne){let et=`${Te?.name??Q.schematic_component_id}.${Ve.pin_number}`;E.set(et,Ve.schematic_port_id),A.set(Ve.schematic_port_id,et)}for(let Ve of Ne){let et=A.get(Ve.schematic_port_id);ce.push({pinId:et,x:Ve.center.x,y:Ve.center.y})}b.push({chipId:de,center:Q.center,width:Q.size.width,height:Q.size.height,pins:ce})}let B=new Set,w=new Map,P=new Map,N=new Map;for(let Q of D){let de=e.schematic_port.list({schematic_component_id:Q.schematic_component_id});for(let ce of de)B.add(ce.schematic_port_id),ce.source_port_id&&(w.set(ce.schematic_port_id,ce.source_port_id),P.set(ce.source_port_id,ce.schematic_port_id))}let O=new Set;n.subcircuit_id&&O.add(n.subcircuit_id);for(let Q of f)Q.subcircuit_id&&O.add(Q.subcircuit_id);let ee=e.source_trace.list().filter(Q=>{if(Q.subcircuit_id===n.subcircuit_id)return!0;for(let de of Q.connected_source_port_ids)if(P.has(de))return!0;return!1}).flatMap(Q=>Q.connected_source_net_ids);for(let Q of ee){let de=e.source_net.get(Q);de?.subcircuit_id&&O.add(de.subcircuit_id)}let X=[],te=new Map;for(let Q of e.source_trace.list()){if(Q.subcircuit_id&&!O.has(Q.subcircuit_id))continue;let de=(Q.connected_source_port_ids??[]).map(ce=>P.get(ce)).filter(ce=>!!ce&&B.has(ce));if(de.length>=2){let[ce,Te]=de.slice(0,2),Ne=[ce,Te].sort().join("::");if(!te.has(Ne)){te.set(Ne,Q.source_trace_id);let Ve=Q.display_name??Q.source_trace_id;Q.subcircuit_connectivity_map_key&&(l.add(Q.subcircuit_connectivity_map_key),N.set(Ve,Q.subcircuit_connectivity_map_key),s.set(Q.subcircuit_connectivity_map_key,Ve)),X.push({pinIds:[ce,Te].map(et=>A.get(et)),netId:Ve})}}}let L=[];for(let Q of e.source_net.list().filter(de=>!de.subcircuit_id||O.has(de.subcircuit_id)))Q.subcircuit_connectivity_map_key&&(l.add(Q.subcircuit_connectivity_map_key),a.set(Q.subcircuit_connectivity_map_key,Q));let K=new Map;for(let[Q,de]of w){let ce=e.source_port.get(de);if(!ce?.subcircuit_connectivity_map_key)continue;let Te=ce.subcircuit_connectivity_map_key;l.add(Te),K.has(Te)||K.set(Te,[]),K.get(Te).push(Q)}for(let[Q,de]of K){let ce=a.get(Q);if(ce&&de.length>=2){let Te=String(ce.name||ce.source_net_id||Q);N.set(Te,Q),s.set(Q,Te),L.push({netId:Te,pinIds:de.map(Ne=>A.get(Ne))})}}let U=(()=>{let Q={},de=new Set(L.map(ce=>ce.netId));for(let ce of e.source_net.list().filter(Te=>!Te.subcircuit_id||O.has(Te.subcircuit_id)))ce.name&&de.has(ce.name)&&(ce.is_ground||ce.name.toLowerCase().startsWith("gnd")?Q[ce.name]=["y-"]:ce.is_power||ce.name.toLowerCase().startsWith("v")?Q[ce.name]=["y+"]:Q[ce.name]=["x-","x+"]);return Q})();return{inputProblem:{chips:b,directConnections:X,netConnections:L,availableNetLabelOrientations:U,maxMspPairDistance:n._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:E,pairKeyToSourceTraceId:te,sckToSourceNet:a,sckToUserNetId:s,userNetIdToSck:N,allSourceAndSchematicPortIdsInScope:B,schPortIdToSourcePortId:w,displayLabelTraces:x,allScks:l}}var Ji=1e-6;function lBe(n){let e=Math.abs(n.to.x-n.from.x),a=Math.abs(n.to.y-n.from.y);return e>=a}function GS(n,e){return Math.hypot(e.x-n.x,e.y-n.y)}function dBe(n,e,a){return{x:n.x+(e.x-n.x)*a,y:n.y+(e.y-n.y)*a}}function pBe(n,e,a){let s=GS(n,e);if(s<Ji)return 0;let l=((a.x-n.x)*(e.x-n.x)+(a.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,l))*s}function NS(n,e,a,s){return n*s-e*a}function YVt(n,e,a,s){let l={x:e.x-n.x,y:e.y-n.y},p={x:s.x-a.x,y:s.y-a.y},x=NS(l.x,l.y,p.x,p.y),f={x:a.x-n.x,y:a.y-n.y},m=NS(f.x,f.y,l.x,l.y);if(Math.abs(x)<Ji&&Math.abs(m)<Ji||Math.abs(x)<Ji&&Math.abs(m)>=Ji)return null;let D=NS(f.x,f.y,p.x,p.y)/x,b=NS(f.x,f.y,l.x,l.y)/x;return D<-Ji||D>1+Ji||b<-Ji||b>1+Ji?null:{x:n.x+D*l.x,y:n.y+D*l.y}}function HVt(n,e=Ji){if(n.length===0)return n;n.sort((l,p)=>l.start-p.start);let a=[],s={...n[0]};for(let l=1;l<n.length;l++){let p=n[l];p.start<=s.end+e?s.end=Math.max(s.end,p.end):(a.push(s),s={...p})}return a.push(s),a}function WVt(n,e,a){let s=GS(n.from,n.to);if(s<Ji||e.length===0)return[n];let l=a/2,p=e.map(E=>({start:Math.max(0,E-l),end:Math.min(s,E+l)})).filter(E=>E.end-E.start>Ji),x=HVt(p),f=[],m=0,D={x:n.to.x-n.from.x,y:n.to.y-n.from.y},b=(E,A,B)=>{if(A-E<=Ji)return;let w=E/s,P=A/s;f.push({from:dBe(n.from,n.to,w),to:dBe(n.from,n.to,P),...B?{is_crossing:!0}:{}})};for(let E of x)E.start-m>Ji&&b(m,E.start,!1),b(E.start,E.end,!0),m=E.end;return s-m>Ji&&b(m,s,!1),f.length>0?f:[n]}function KVt(n,e={}){let a=e.crossSegmentLength??.075,s=e.tolerance??Ji,l=new Map,p=m=>`${m.traceIdx}:${m.edgeIdx}`,x=m=>n[m.traceIdx].edges[m.edgeIdx];for(let m=0;m<n.length;m++){let D=n[m];for(let b=0;b<D.edges.length;b++){let E=D.edges[b];for(let A=m;A<n.length;A++){let B=n[A];for(let w=A===m?b+1:0;w<B.edges.length;w++){let P=B.edges[w],N=YVt(E.from,E.to,P.from,P.to);if(!N)continue;let O=GS(E.from,E.to),$=GS(P.from,P.to);if(O<s||$<s)continue;let ee=pBe(E.from,E.to,N),X=pBe(P.from,P.to,N),te=ee<=s||Math.abs(O-ee)<=s||Number.isNaN(ee),L=X<=s||Math.abs($-X)<=s||Number.isNaN(X);if(!te&&!L){let K=lBe(E),U=lBe(P),J;if(K!==U)J=K;else{let ce=Math.abs(E.to.x-E.from.x),Te=Math.abs(E.to.y-E.from.y),Ne=Math.abs(P.to.x-P.from.x),Ve=Math.abs(P.to.y-P.from.y),et=ce-Te,ct=Ne-Ve;J=et===ct?!0:et>ct}let Q=p({traceIdx:J?m:A,edgeIdx:J?b:w}),de=l.get(Q)??[];de.push(J?ee:X),l.set(Q,de)}}}}}let f=n.map(m=>({source_trace_id:m.source_trace_id,edges:[]}));for(let m=0;m<n.length;m++){let D=n[m];for(let b=0;b<D.edges.length;b++){let E=p({traceIdx:m,edgeIdx:b}),A=l.get(E)??[];if(A.length===0){f[m].edges.push(D.edges[b]);continue}let B=Array.from(new Set(A.map(P=>Number(P.toFixed(6))))).sort((P,N)=>P-N),w=WVt(D.edges[b],B,a);f[m].edges.push(...w)}}return f}var tl=1e-6;function XS(n,e,a=tl){return Math.abs(n-e)<=a}function $g(n,e,a=tl){return XS(n.x,e.x,a)&&XS(n.y,e.y,a)}function xBe(n,e,a,s=tl){let l=Math.min(e.x,a.x)-s,p=Math.max(e.x,a.x)+s,x=Math.min(e.y,a.y)-s,f=Math.max(e.y,a.y)+s;return n.x<l||n.x>p||n.y<x||n.y>f?!1:Math.abs((a.x-e.x)*(n.y-e.y)-(a.y-e.y)*(n.x-e.x))<=s}function fBe(n,e=tl){let a=new Map;for(let s of n){let l=`${s.x.toFixed(6)},${s.y.toFixed(6)}`;a.has(l)||a.set(l,s)}return Array.from(a.values())}function hBe(n){return{x:n.to.x-n.from.x,y:n.to.y-n.from.y}}function MW(n,e,a=tl){let s=hBe(n),l=hBe(e),p=Math.hypot(s.x,s.y),x=Math.hypot(l.x,l.y);if(p<a||x<a)return!0;let f=s.x*l.y-s.y*l.x;return Math.abs(f)<=a*p*x}function NF(n,e,a=tl){return n.edges.filter(s=>$g(s.from,e,a)||$g(s.to,e,a))}function mBe(n,e,a=tl){for(let s of n.edges){if($g(s.from,e,a))return s.from;if($g(s.to,e,a))return s.to}return null}function JVt(n,e,a=tl){let s=$g(n.from,e,a)||XS(n.from.x,e.x,a)&&XS(n.from.y,e.y,a)?n.to:n.from,l=s.x-e.x,p=s.y-e.y;return Math.abs(l)<a&&Math.abs(p)<a?null:Math.abs(l)>=Math.abs(p)?l>=0?"right":"left":p>=0?"up":"down"}function Mg(n,e,a=tl){let s=NF(n,e,a);if(s.length<2)return null;let l=s.map(E=>JVt(E,e,a)),p=l.includes("up"),x=l.includes("down"),f=l.includes("left"),m=l.includes("right"),D=p?"up":x?"down":null,b=m?"right":f?"left":null;return D&&b?`${D}-${b}`:null}function ZVt(n,e={}){let a=e.tolerance??tl,s={};for(let p of n)s[p.source_trace_id]=[];let l=n.map(p=>{let x=[];for(let f of p.edges)x.push(f.from,f.to);return fBe(x,a)});for(let p=0;p<n.length;p++){let x=n[p],f=l[p];for(let m=p+1;m<n.length;m++){let D=n[m],b=l[m];for(let E of f)for(let A of b)if($g(E,A,a)){let B=NF(x,E,a),w=NF(D,A,a),P=B.some(ee=>w.some(X=>!MW(ee,X,a))),N=Mg(x,E,a),O=Mg(D,A,a);P&&!(N!==null&&O!==null&&N===O)&&(s[x.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[D.source_trace_id].push(A))}for(let E of f)for(let A of D.edges)if(xBe(E,A.from,A.to,a)){let w=NF(x,E,a).some(ee=>!MW(ee,A,a)),P=Mg(x,E,a),N=mBe(D,E,a*1e3),O=N?Mg(D,N,a):null;w&&!(P!==null&&O!==null&&P===O)&&(s[x.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[D.source_trace_id].push(E))}for(let E of b)for(let A of x.edges)if(xBe(E,A.from,A.to,a)){let w=NF(D,E,a).some(ee=>!MW(A,ee,a)),P=Mg(D,E,a),N=mBe(x,E,a*1e3),O=N?Mg(x,N,a):null;w&&!(O!==null&&P!==null&&O===P)&&(s[D.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[x.source_trace_id].push(E))}}}for(let p of Object.keys(s))s[p]=fBe(s[p],a);return s}var OW=(0,MBe.default)("Group_doInitialSchematicTraceRender");function QVt(n){let{group:e,solver:a,pinIdToSchematicPortId:s,userNetIdToSck:l}=n,{db:p}=e.root,x=a.traceOverlapShiftSolver?.correctedTraceMap,f=[];OW(`Traces inside SchematicTraceSolver output: ${Object.values(x??{}).length}`);for(let b of Object.values(x??{})){let E=b?.tracePath;if(!Array.isArray(E)||E.length<2){OW(`Skipping trace ${b?.pinIds.join(",")} because it has less than 2 points`);continue}let A=[];for(let P=0;P<E.length-1;P++)A.push({from:{x:E[P].x,y:E[P].y},to:{x:E[P+1].x,y:E[P+1].y}});let B=null,w;if(Array.isArray(b?.pins)&&b.pins.length===2){let P=s.get(b.pins[0]?.pinId),N=s.get(b.pins[1]?.pinId);if(P&&N){for(let O of[P,N])p.schematic_port.get(O)&&p.schematic_port.update(O,{is_connected:!0});w=l.get(String(b.userNetId))}}B||(B=`solver_${b?.mspPairId}`,w=l.get(String(b.userNetId))),f.push({source_trace_id:B,edges:A,subcircuit_connectivity_map_key:w})}OW(`Applying ${f.length} traces from SchematicTraceSolver output`);let m=KVt(f.map(b=>({source_trace_id:b.source_trace_id,edges:b.edges}))),D=ZVt(m);for(let b of m)p.schematic_trace.insert({source_trace_id:b.source_trace_id,edges:b.edges,junctions:D[b.source_trace_id]??[],subcircuit_connectivity_map_key:f.find(E=>E.source_trace_id===b.source_trace_id)?.subcircuit_connectivity_map_key})}var eGt=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"}},tGt=n=>{for(let a of n){let s=a._getDirectlyConnectedTraces();for(let l of s){let p=l._parsedProps.schDisplayLabel;if(p)return{name:p,wasAssignedDisplayLabel:!0}}}return{name:n.map(a=>a._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},LW=(0,OBe.default)("Group_doInitialSchematicTraceRender");function rGt(n){let{group:e,solver:a,sckToSourceNet:s,allScks:l,allSourceAndSchematicPortIdsInScope:p,schPortIdToSourcePortId:x,userNetIdToSck:f,pinIdToSchematicPortId:m,schematicPortIdsWithPreExistingNetLabels:D,schematicPortIdsWithRoutedTraces:b}=n,{db:E}=e.root,A=a.netLabelPlacementSolver?.netLabelPlacements??[],B=a.mspConnectionPairSolver.globalConnMap;for(let w of A){LW(`processing placement: ${w.netId}`);let P=B.getIdsConnectedToNet(w.globalConnNetId).find(Q=>f.get(Q)),N=f.get(P),O=w.anchorPoint,$=w.orientation,ee=eGt($),X=N?s.get(N):void 0,te=w.pinIds.map(Q=>m.get(Q));if(te.some(Q=>D.has(Q))){LW(`skipping net label placement for "${w.netId}" REASON:schematic port has pre-existing net label`);continue}if(X){let Q=X.name,de=Qp({anchor_position:O,anchor_side:ee,text:Q});E.schematic_net_label.insert({text:Q,anchor_position:O,center:de,anchor_side:ee,...X?.source_net_id?{source_net_id:X.source_net_id}:{}});continue}let L=e.selectAll("port").filter(Q=>Q._getSubcircuitConnectivityKey()===N),{name:K,wasAssignedDisplayLabel:U}=tGt(L);if(!U&&te.some(Q=>b.has(Q))){LW(`skipping net label placement for "${w.netId}" REASON:schematic port has routed traces and no display label`);continue}let J=Qp({anchor_position:O,anchor_side:ee,text:K});E.schematic_net_label.insert({text:K,anchor_position:O,center:J,anchor_side:ee})}}var nGt=({allSourceAndSchematicPortIdsInScope:n,group:e,schPortIdToSourcePortId:a,sckToSourceNet:s,pinIdToSchematicPortId:l,schematicPortIdsWithPreExistingNetLabels:p})=>{let{db:x}=e.root;for(let f of Array.from(n)){let m=x.schematic_port.get(f);if(!m||m.is_connected)continue;let D=a.get(f);if(!D)continue;let E=x.source_port.get(D)?.subcircuit_connectivity_map_key;if(!E)continue;let A=s.get(E);if(!A||x.schematic_net_label.list().some(O=>Math.abs(O.anchor_position.x-m.center.x)<.1&&Math.abs(O.anchor_position.y-m.center.y)<.1?A.source_net_id&&O.source_net_id?O.source_net_id===A.source_net_id:O.text===(A.name||E):!1))continue;let w=A.name||A.source_net_id||E,P=$F(m.facing_direction||"right")||"right",N=Qp({anchor_position:m.center,anchor_side:P,text:w});x.schematic_net_label.insert({text:w,anchor_position:m.center,center:N,anchor_side:P,...A.source_net_id?{source_net_id:A.source_net_id}:{}})}},aGt=n=>{let e=new Set,a=n.selectAll("netlabel");for(let s of a){let l=s._getConnectedPorts();for(let p of l)p.schematic_port_id&&e.add(p.schematic_port_id)}return e},sGt=({solver:n,pinIdToSchematicPortId:e})=>{let a=n.schematicTraceLinesSolver.solvedTracePaths,s=new Set;for(let l of a)for(let p of l.pinIds){let x=e.get(p);x&&s.add(x)}return s},iGt=(0,NBe.default)("Group_doInitialSchematicTraceRender"),oGt=n=>{if(!n.root?._featureMspSchematicTraceRouting||!n.isSubcircuit||n.root?.schematicDisabled)return;let{inputProblem:e,pinIdToSchematicPortId:a,pairKeyToSourceTraceId:s,sckToSourceNet:l,allSourceAndSchematicPortIdsInScope:p,schPortIdToSourcePortId:x,displayLabelTraces:f,allScks:m,userNetIdToSck:D}=XVt(n),b=aGt(n);iGt.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(e,null,2)});let E=new uSe(e);E.solve();let A=sGt({solver:E,pinIdToSchematicPortId:a});QVt({group:n,solver:E,pinIdToSchematicPortId:a,userNetIdToSck:D}),rGt({group:n,solver:E,sckToSourceNet:l,allSourceAndSchematicPortIdsInScope:p,schPortIdToSourcePortId:x,pinIdToSchematicPortId:a,allScks:m,userNetIdToSck:D,schematicPortIdsWithPreExistingNetLabels:b,schematicPortIdsWithRoutedTraces:A}),nGt({group:n,allSourceAndSchematicPortIdsInScope:p,schPortIdToSourcePortId:x,sckToSourceNet:l,pinIdToSchematicPortId:a,schematicPortIdsWithPreExistingNetLabels:b})},zg=class extends Za{constructor(){super(...arguments);q(this,"pcb_group_id",null);q(this,"schematic_group_id",null);q(this,"subcircuit_id",null);q(this,"_hasStartedAsyncAutorouting",!1);q(this,"_asyncAutoroutingResult",null);q(this,"unnamedElementCounter",{})}get config(){return{zodProps:z_e,componentName:"Group"}}doInitialSourceGroupRender(){let{db:e}=this.root,a=e.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit});this.source_group_id=a.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${a.source_group_id}`,e.source_group.update(a.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:e}=this.root;for(let a of this.children)e.source_component.update(a.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:e}=this.root,a=this.parent?.getGroup?.();if(a?.source_group_id&&e.source_group.update(this.source_group_id,{parent_source_group_id:a.source_group_id}),!this.isSubcircuit)return;let s=this.parent?.getSubcircuit?.()?.subcircuit_id;s&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:s})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:a.autorouter?{trace_clearance:a.autorouter.traceClearance}:void 0});this.pcb_group_id=s.pcb_group_id;for(let l of this.children)e.pcb_component.update(l.pcb_component_id,{pcb_group_id:s.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,a=this._parsedProps,s=rK(this.children);if(this.pcb_group_id){let l=s.width,p=s.height,x=(s.minX+s.maxX)/2,f=(s.minY+s.maxY)/2;if(this.isSubcircuit){let{padLeft:b,padRight:E,padTop:A,padBottom:B}=this._resolvePcbPadding();l+=b+E,p+=A+B,x+=(E-b)/2,f+=(A-B)/2}let D=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0?e.pcb_group.get(this.pcb_group_id)?.center??{x,y:f}:{x,y:f};e.pcb_group.update(this.pcb_group_id,{width:Number(a.width??l),height:Number(a.height??p),center:D})}}getNextAvailableName(e){var a,s;return(a=this.unnamedElementCounter)[s=e.lowercaseComponentName]??(a[s]=1),`unnamed_${e.lowercaseComponentName}${this.unnamedElementCounter[e.lowercaseComponentName]++}`}_resolvePcbPadding(){let e=this._parsedProps,a=e.pcbLayout,s=E=>{let A=a?.[E],B=e[E];if(typeof A=="number")return A;if(typeof B=="number")return B},l=s("padding")??0,p=s("paddingX"),x=s("paddingY"),f=s("paddingLeft")??p??l,m=s("paddingRight")??p??l,D=s("paddingTop")??x??l,b=s("paddingBottom")??x??l;return{padLeft:f,padRight:m,padTop:D,padBottom:b}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:e}=this,{db:a}=this.root,s=e;if(!this.isSubcircuit)return;let l=s.manualEdits?.manual_trace_hints;if(l)for(let p of l)this.add(new aK({for:p.pcb_port_selector,offsets:p.offsets}))}doInitialSourceAddConnectivityMapKey(){BVt(this)}_areChildSubcircuitsRouted(){let e=this.selectAll("group").filter(a=>a.isSubcircuit);for(let a of e)if(a._shouldRouteAsync()&&!a._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,Og.default)("tscircuit:core:_hasTracesToRoute"),a=this.selectAll("trace");return e(`[${this.getString()}] has ${a.length} traces to route`),a.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:e}=this.root,a=(0,Og.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),s=this._parsedProps,l=this._getAutorouterConfig(),p=l.serverUrl,x=l.serverMode,f=(b,E)=>(a("fetching",b),E.headers&&(E.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(b,E)),m=this.root.db.toArray().filter(b=>b.type.startsWith("source_")||b.type.startsWith("pcb_"));if(x==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:E}=await f(`${p}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:YW({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(A=>A.json());this._asyncAutoroutingResult=E,this._markDirty("PcbTraceRender");return}let{autorouting_result:b}=await f(`${p}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:m,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(E=>E.json());this._asyncAutoroutingResult=b,this._markDirty("PcbTraceRender");return}let{autorouting_job:D}=await f(`${p}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:m,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:l.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(b=>b.json());for(;;){let{autorouting_job:b}=await f(`${p}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:D.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(E=>E.json());if(b.is_finished){let{autorouting_job_output:E}=await f(`${p}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:D.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(A=>A.json());this._asyncAutoroutingResult={output_pcb_traces:E.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(b.has_error){let E=new jF(`Autorouting job failed: ${JSON.stringify(b.error)}`);throw e.pcb_autorouting_error.insert({pcb_error_id:D.autorouting_job_id,error_type:"pcb_autorouting_error",message:E.message}),E}await new Promise(E=>setTimeout(E,100))}}async _runLocalAutorouting(){let{db:e}=this.root,a=this._parsedProps,s=(0,Og.default)("tscircuit:core:_runLocalAutorouting");s(`[${this.getString()}] starting local autorouting`);let l=this._getAutorouterConfig(),{simpleRouteJson:p}=YW({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(s.enabled){let m=ZY(p);m.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(m)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:p});let x;l.algorithmFn?x=await l.algorithmFn(p):x=new bVt(p,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity});let f=new Promise((m,D)=>{x.on("complete",b=>{s(`[${this.getString()}] local autorouting complete`),m(b.traces)}),x.on("error",b=>{s(`[${this.getString()}] local autorouting error: ${b.error.message}`),D(b.error)})});x.on("progress",m=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...m})}),x.start();try{let m=await f;this._asyncAutoroutingResult={output_pcb_traces:m},this._markDirty("PcbTraceRender")}catch(m){let{db:D}=this.root;throw D.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:m instanceof Error?m.message:String(m)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:m instanceof Error?m.message:String(m)},simpleRouteJson:p}),m}finally{x.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let e=(0,Og.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(){oGt(this)}updatePcbTraceRender(){let e=(0,Og.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:a}=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:a}=this._asyncAutoroutingResult.output_simple_route_json;if(a)for(let s of a){let l=e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:s.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;let{db:a}=this.root;for(let s of e)if(s.type==="pcb_trace"){if(s.subcircuit_id=this.subcircuit_id,s.connection_name){let l=s.connection_name;s.source_trace_id=l}a.pcb_trace.insert(s)}for(let s of e)if(s.type!=="pcb_via"&&s.type==="pcb_trace")for(let l of s.route)l.route_type==="via"&&a.pcb_via.insert({pcb_trace_id:s.pcb_trace_id,x:l.x,y:l.y,hole_diameter:.3,outer_diameter:.6,layers:[l.from_layer,l.to_layer],from_layer:l.from_layer,to_layer:l.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=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=s.schematic_group_id;for(let l of this.children)l.schematic_component_id&&e.schematic_component.update(l.schematic_component_id,{schematic_group_id:s.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 a=this.children.some(l=>{let p=l._parsedProps;return p?.schX!==void 0||p?.schY!==void 0}),s=(e.manualEdits?.schematic_placements?.length??0)>0;return!a&&!s?"match-adapt":"relative"}doInitialSchematicLayout(){let e=this._getSchematicLayoutMode();e==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),e==="grid"&&this._doInitialSchematicLayoutGrid(),e==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){AVt(this)}_doInitialSchematicLayoutMatchpack(){SVt(this)}_doInitialSchematicLayoutGrid(){wVt(this)}_doInitialSchematicLayoutFlex(){TVt(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 a=e.pcbX!==void 0||e.pcbY!==void 0,s=(e.manualEdits?.pcb_placements?.length??0)>0;if(this.children.some(x=>{let f=x._parsedProps;return f?.pcbX!==void 0||f?.pcbY!==void 0}))return"none";let p=this.children.reduce((x,f)=>{let m=f._parsedProps,D=m?.pcbX!==void 0||m?.pcbY!==void 0;return x+(D?0:1)},0);return!a&&!s&&p>1?"pack":"none"}doInitialPcbLayout(){let e=this._getPcbLayoutMode();e==="grid"?this._doInitialPcbLayoutGrid():e==="pack"?this._doInitialPcbLayoutPack():e==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){PVt(this)}_doInitialPcbLayoutPack(){VVt(this)}_doInitialPcbLayoutFlex(){GVt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,a=this._parsedProps;if(!a.border)return;let s=typeof a.schWidth=="number"?a.schWidth:void 0,l=typeof a.schHeight=="number"?a.schHeight:void 0,p=typeof a.schPadding=="number"?a.schPadding:0,x=typeof a.schPaddingLeft=="number"?a.schPaddingLeft:p,f=typeof a.schPaddingRight=="number"?a.schPaddingRight:p,m=typeof a.schPaddingTop=="number"?a.schPaddingTop:p,D=typeof a.schPaddingBottom=="number"?a.schPaddingBottom:p,b=this.schematic_group_id?e.schematic_group.get(this.schematic_group_id):null;if(b&&(s===void 0&&typeof b.width=="number"&&(s=b.width),l===void 0&&typeof b.height=="number"&&(l=b.height)),s===void 0||l===void 0)return;let E=b?.center??this._getGlobalSchematicPositionBeforeLayout(),A=E.x-s/2-x,B=E.y-l/2-D,w=s+x+f,P=l+m+D;e.schematic_box.insert({width:w,height:P,x:A,y:B,is_dashed:a.border?.dashed??!1})}_determineSideFromPosition(e,a){if(!e.center||!a.center)return"left";let s=e.center.x-a.center.x,l=e.center.y-a.center.y;return Math.abs(s)>Math.abs(l)?s>0?"right":"left":l>0?"bottom":"top"}_calculateSchematicBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let a=1/0,s=-1/0,l=1/0,p=-1/0;for(let f of e)a=Math.min(a,f.centerX),s=Math.max(s,f.centerX),l=Math.min(l,f.centerY),p=Math.max(p,f.centerY);let x=2;return{minX:a-x,maxX:s+x,minY:l-x,maxY:p+x}}_getAutorouterConfig(){let e=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return qVt(e)}_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 a=new Map;for(let s of this.children)if(!s.isSubcircuit&&s._parsedProps.name){let l=a.get(s._parsedProps.name)||[];l.push(s),a.set(s._parsedProps.name,l)}for(let[s,l]of a.entries())l.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${s}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:l.map(p=>p.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:e}=this.root,a=e;for(let s of a.schematic_net_label.list()){let l=a.source_net.get(s.source_net_id),p=s.text||l?.name||"";if(s.anchor_side==="top"&&/^gnd/i.test(p)){a.schematic_net_label.update(s.schematic_net_label_id,{symbol_name:"ground_down"});continue}s.anchor_side==="bottom"&&/^v/i.test(p)&&a.schematic_net_label.update(s.schematic_net_label_id,{symbol_name:"vcc_up"})}}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(e){return super._repositionOnPcb(e)}},LBe=class extends zg{constructor(){super(...arguments);q(this,"pcb_board_id",null);q(this,"_drcChecksComplete",!1);q(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:FY}}get boardThickness(){let{_parsedProps:e}=this;return 1.4}get allLayers(){return(this._parsedProps.layers??2)===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db:e}=this.root,{_parsedProps:a}=this;if(a.width&&a.height)return;let s=1/0,l=1/0,p=-1/0,x=-1/0,f=PBe(e,this.subcircuit_id),m=new Set([this.subcircuit_id,...f]),D=e.pcb_component.list().filter(ee=>ee.subcircuit_id&&m.has(ee.subcircuit_id)),b=e.pcb_group.list().filter(ee=>ee.subcircuit_id&&m.has(ee.subcircuit_id)),E=!1,A=(ee,X,te)=>{X===0||te===0||(E=!0,s=Math.min(s,ee.x-X/2),l=Math.min(l,ee.y-te/2),p=Math.max(p,ee.x+X/2),x=Math.max(x,ee.y+te/2))};for(let ee of D)A(ee.center,ee.width,ee.height);for(let ee of b)A(ee.center,ee.width,ee.height);let B=2,w=E?p-s+B*2:0,P=E?x-l+B*2:0,N={x:E?(s+p)/2+(a.outlineOffsetX??0):a.outlineOffsetX??0,y:E?(l+x)/2+(a.outlineOffsetY??0):a.outlineOffsetY??0},O=a.width??w,$=a.height??P;e.pcb_board.update(this.pcb_board_id,{width:O,height:$,center:N})}_addBoardInformationToSilkscreen(){let e=this.root?.platform;if(!e?.printBoardInformationToSilkscreen)return;let a=this.root.db.pcb_board.get(this.pcb_board_id);if(!a)return;let s=[];if(e.projectName&&s.push(e.projectName),e.version&&s.push(`v${e.version}`),e.url&&s.push(e.url),s.length===0)return;let l=s.join(`
|
|
1039
|
-
`),f={x:a.center.x+a.width/2-.25,y:a.center.y-a.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:l,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:f})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=a.width??0,l=a.height??0,p={x:(a.pcbX??0)+(a.outlineOffsetX??0),y:(a.pcbY??0)+(a.outlineOffsetY??0)};if(a.outline){let f=a.outline.map(B=>B.x),m=a.outline.map(B=>B.y),D=Math.min(...f),b=Math.max(...f),E=Math.min(...m),A=Math.max(...m);s=b-D,l=A-E,p={x:(D+b)/2+(a.outlineOffsetX??0),y:(E+A)/2+(a.outlineOffsetY??0)}}let x=e.pcb_board.insert({center:p,thickness:this.boardThickness,num_layers:this.allLayers.length,width:s,height:l,outline:a.outline?.map(f=>({x:f.x+(a.outlineOffsetX??0),y:f.y+(a.outlineOffsetY??0)})),material:a.material});this.pcb_board_id=x.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)}_computePcbGlobalTransformBeforeLayout(){return _i()}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 a=pSe(e.toArray());for(let l of a)e.pcb_trace_error.insert(l);let s=dSe(e.toArray());for(let l of s)e.pcb_port_not_connected_error.insert(l)}_emitRenderLifecycleEvent(e,a){super._emitRenderLifecycleEvent(e,a),a==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e})}},uGt=new Proxy({},{get:(n,e)=>e}),od=uGt,$Be=class extends Za{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:J_e,sourceFtype:od.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,a=typeof e=="string"?e:`${js(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${a}/${js(this._parsedProps.maxVoltageRating)}V`:a}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new zc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new zc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,capacitance:a.capacitance,max_voltage_rating:a.maxVoltageRating,max_decoupling_trace_length:a.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!a.polarized});this.source_component_id=s.source_component_id}},HS=class extends Za{constructor(e){super(e);q(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:rg,shouldRenderAsSchematicBox:!0}}initPorts(e={}){super.initPorts(e);let{_parsedProps:a}=this;if(a.externallyConnectedPins){let s=new Set;for(let[l,p]of a.externallyConnectedPins)s.add(l),s.add(p);for(let l of s)if(!this.children.find(x=>x instanceof Ii&&x.isMatchingAnyOf([l]))){let x=l.match(/^pin(\d+)$/);if(x){let f=parseInt(x[1]);this.add(new Ii({pinNumber:f,aliases:[l]}))}else this.add(new Ii({name:l,aliases:[l]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:e}=this;e?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:e}=this;if(e.externallyConnectedPins)for(let[a,s]of e.externallyConnectedPins)this.add(new zc({from:`${this.getSubcircuitSelector()} > port.${a}`,to:`${this.getSubcircuitSelector()} > port.${s}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:e}=this.root,{pinAttributes:a}=this.props;if(!a)return;let s=null,l=null,p,x=this.selectAll("port");for(let E of x)for(let A of E.getNameAndAliases())if(a[A]){let B=a[A];B.providesPower&&(s=E,p=B.providesVoltage),B.providesGround&&(l=E)}if(!s||!l||p===void 0)return;let f=e.source_port.get(s.source_port_id);if(!f?.subcircuit_connectivity_map_key)return;let m=e.source_port.get(l.source_port_id);if(!m?.subcircuit_connectivity_map_key)return;let D=e.source_net.getWhere({subcircuit_connectivity_map_key:f.subcircuit_connectivity_map_key}),b=e.source_net.getWhere({subcircuit_connectivity_map_key:m.subcircuit_connectivity_map_key});!D||!b||e.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:s.source_port_id,positive_source_net_id:D.source_net_id,negative_source_port_id:l.source_port_id,negative_source_net_id:b.source_net_id,voltage:p})}},zBe=class extends HS{constructor(n){super(n)}get config(){return{...super.config,componentName:"Pinout",zodProps:q_e}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=a.source_component_id}},qBe=class extends Za{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"anode",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"cathode",this.portMap.pin2)}get config(){let e={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},a=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:a?e[a]:this.props.symbolName??"diode",componentName:"Diode",zodProps:pAe,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},UBe=class extends Za{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:V_e,sourceFtype:od.simple_fuse}}_getSchematicSymbolDisplayValue(){let n=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,a=typeof n=="string"?parseFloat(n):n,s=typeof e=="string"?parseFloat(e):e;return`${js(a)}A / ${js(s)}V`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=typeof e.currentRating=="string"?parseFloat(e.currentRating):e.currentRating,s=typeof e.voltageRating=="string"?parseFloat(e.voltageRating):e.voltageRating,l=n.source_component.insert({name:this.name,ftype:od.simple_fuse,current_rating_amps:a,voltage_rating_volts:s,display_current_rating:`${js(a)}A`,display_voltage_rating:`${js(s)}V`});this.source_component_id=l.source_component_id}},VBe=class extends Za{constructor(){super(...arguments);q(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:vY,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let a=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),s=this._parsedProps.schDirection??"right";return{leftSize:s==="left"?a:0,rightSize:s==="right"?a:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,a=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),s={};for(let x=0;x<a.length;x++){let f=a[x],m=e.source_port.get(f.source_port_id),D="";if(typeof m?.pin_number=="number")D=m.pin_number.toString();else if(Array.isArray(m?.port_hints)){let b=m.port_hints.find(E=>/^(pin)?\d+$/.test(E));b&&(/^pin\d+$/.test(b)?D=b.replace(/^pin/,""):D=b)}s[D]=f.pcb_port_id}let l=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),p=x=>{if(x&&typeof x=="string"&&x.startsWith("{PIN")){let f=x.replace("{PIN","").replace("}","");return s[f]||x}return x};for(let x of l)if(x.route)for(let f of x.route)f.route_type==="wire"&&(f.start_pcb_port_id=p(f.start_pcb_port_id),f.end_pcb_port_id=p(f.end_pcb_port_id))}},GBe=class extends Za{constructor(){super(...arguments);q(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(a=>a.componentName==="Port").map(a=>a.name);return e.length>0?[e]:[]}return this._parsedProps.bridgedPins??[]}get config(){let e=this._parsedProps??this.props,a=e.pinCount;if(e.pinCount==null&&!e.footprint&&(a=2),e.pinCount==null){let p=(e.bridgedPins??[]).flat().map(D=>this._getPinNumberFromBridgedPinName(D)).filter(D=>D!==null),x=p.length>0?Math.max(...p):0,f=e.pinLabels?Object.keys(e.pinLabels).length:0,m=Math.max(x,f);(m===2||m===3)&&(a=m),a==null&&e.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(a=this.getPortsFromFootprint().length)}let s="";a?s+=`solderjumper${a}`:s="solderjumper";let l=[];return Array.isArray(e.bridgedPins)&&e.bridgedPins.length>0?l=Array.from(new Set(e.bridgedPins.flat().map(p=>this._getPinNumberFromBridgedPinName(p)).filter(p=>p!==null))).sort((p,x)=>p-x):e.bridged&&a&&(l=Array.from({length:a},(p,x)=>x+1)),l.length>0&&(s+=`_bridged${l.join("")}`),{schematicSymbolName:e.symbolName??s,componentName:"SolderJumper",zodProps:U_e,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let a=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);a==null&&!this._parsedProps.footprint&&(a=2);let s=this._parsedProps.schDirection??"right";return{leftSize:s==="left"?a:0,rightSize:s==="right"?a:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,a=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),s={};for(let x=0;x<a.length;x++){let f=a[x],m=e.source_port.get(f.source_port_id),D="";if(typeof m?.pin_number=="number")D=m.pin_number.toString();else if(Array.isArray(m?.port_hints)){let b=m.port_hints.find(E=>/^(pin)?\d+$/.test(E));b&&(/^pin\d+$/.test(b)?D=b.replace(/^pin/,""):D=b)}s[D]=f.pcb_port_id}let l=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),p=x=>{if(x&&typeof x=="string"&&x.startsWith("{PIN")){let f=x.replace("{PIN","").replace("}","");return s[f]||x}return x};for(let x of l)if(x.route)for(let f of x.route)f.route_type==="wire"&&(f.start_pcb_port_id=p(f.start_pcb_port_id),f.end_pcb_port_id=p(f.end_pcb_port_id))}},XBe=class extends Za{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"anode",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"cathode",this.portMap.pin2)}get config(){let e={laser:"laser_diode"},a=this.props.laser?"laser":null;return{schematicSymbolName:a?e[a]:this.props.symbolName??"led",componentName:"Led",zodProps:fAe,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_led",name:this.name,wave_length:a.wavelength,color:a.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},YBe=class extends Za{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"positive",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:vAe,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Ii({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Ii({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:a.voltage,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},cGt=fs.extend({voltage:zs.optional(),frequency:Nc.optional(),peakToPeakVoltage:zs.optional(),waveShape:C.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Ba.optional(),dutyCycle:C.number().optional()}),HBe=class extends Za{constructor(){super(...arguments);q(this,"terminal1",this.portMap.terminal1);q(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:cGt,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(e){if(!e.startsWith("Pcb"))for(let a of this.children)a.runRenderPhaseForChildren(e),a.runRenderPhase(e)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:a.voltage,frequency:a.frequency,peak_to_peak_voltage:a.peakToPeakVoltage,wave_shape:a.waveShape,phase:a.phase,duty_cycle:a.dutyCycle,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialSimulationRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.portMap.terminal1,l=this.portMap.terminal2;e.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:s.source_port_id,terminal2_source_port_id:l.source_port_id,voltage:a.voltage,frequency:a.frequency,peak_to_peak_voltage:a.peakToPeakVoltage,wave_shape:a.waveShape,phase:a.phase,duty_cycle:a.dutyCycle})}},WBe=class extends Za{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:X_e,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${js(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 zc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new zc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new zc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new zc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,resistance:a.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}},lGt=["leftedge","rightedge","topedge","bottomedge","center"],KBe=class extends ma{get config(){return{componentName:"Constraint",zodProps:Q_e}}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 a(s){let l=s.split(" ").pop(),p=lGt.includes(l)?l:void 0,x=p?s.replace(` ${p}`,""):s,f=e.selectOne(x,{pcbPrimitive:!0});f&&n.push({selector:s,component:f,componentSelector:x,edge:p})}for(let s of["left","right","top","bottom"])s in this._parsedProps&&a(this._parsedProps[s]);if("for"in this._parsedProps)for(let s of this._parsedProps.for)a(s);return{componentsWithSelectors:n}}},JBe=class extends ma{constructor(){super(...arguments);q(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:DAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,a=this.getSubcircuit(),{_parsedProps:s}=this,l=s.layer??"top";if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenPath. Must be "top" or "bottom".`);let p=this._computePcbGlobalTransformBeforeLayout(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_fabrication_note_path.insert({pcb_component_id:x,layer:l,color:s.color,route:s.route.map(m=>{let D=rs(p,{x:m.x,y:m.y});return{...m,x:D.x,y:D.y}}),stroke_width:s.strokeWidth??.1,subcircuit_id:a?.subcircuit_id??void 0});this.fabrication_note_path_id=f.pcb_fabrication_note_path_id}},ZBe=class extends ma{get config(){return{componentName:"FabricationNoteText",zodProps:gAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:n}=this.root,{_parsedProps:e}=this,a=this.getPrimitiveContainer(),s=this.getSubcircuit();n.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:e.pcbX??0,y:e.pcbY??0},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:e.text??"",pcb_component_id:a.pcb_component_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},QBe=class extends zg{constructor(n){super({...n,subcircuit:!0})}},e9e=class extends zg{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 a=n.pcb_group.get(this.pcb_group_id),s=e.paddingLeft??e.padding??0,l=e.paddingRight??e.padding??0,p=e.paddingTop??e.padding??0,x=e.paddingBottom??e.padding??0;n.pcb_group.update(this.pcb_group_id,{width:a.width+s+l,height:a.height+p+x,center:{x:a.center.x+(l-s)/2,y:a.center.y+(p-x)/2}})}},t9e=class extends ma{constructor(){super(...arguments);q(this,"pcb_breakout_point_id",null);q(this,"matchedPort",null);q(this,"matchedNet",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:FAe}}_matchConnection(){let{connection:e}=this._parsedProps,a=this.getSubcircuit();a&&(this.matchedPort=a.selectOne(e,{type:"port"}),this.matchedPort||(this.matchedNet=a.selectOne(e,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${e}"`))}_getSourceTraceIdForPort(e){let{db:a}=this.root;return a.source_trace.list().find(l=>l.connected_source_port_ids.includes(e.source_port_id))?.source_trace_id}_getSourceNetIdForPort(e){let{db:a}=this.root;return a.source_trace.list().find(l=>l.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:a=0,pcbY:s=0}=this._parsedProps,l=this.parent?.getGroup(),p=this.getSubcircuit();if(!l||!l.pcb_group_id)return;let x=e.pcb_breakout_point.insert({pcb_group_id:l.pcb_group_id,subcircuit_id:p?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:a,y:s});this.pcb_breakout_point_id=x.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:e=0,pcbY:a=0}=this._parsedProps;return{center:{x:e,y:a},bounds:{left:e,top:a,right:e,bottom:a},width:0,height:0}}_setPositionFromLayout(e){let{db:a}=this.root;this.pcb_breakout_point_id&&a.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:e.x,y:e.y})}getPcbSize(){return{width:0,height:0}}},r9e=class extends ma{constructor(){super(...arguments);q(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:oAe}}_getAnchorSide(){let{_parsedProps:e}=this;if(e.anchorSide)return e.anchorSide;if(!this._resolveConnectsTo())return"right";let s=this._getGlobalSchematicPositionBeforeLayout(),l=this._getConnectedPorts();if(l.length===0)return"right";let p=l[0]._getGlobalSchematicPositionBeforeLayout(),x=p.x-s.x,f=p.y-s.y;if(Math.abs(x)>Math.abs(f)){if(x>0)return"right";if(x<0)return"left"}else{if(f>0)return"top";if(f<0)return"bottom"}return"right"}_getConnectedPorts(){let e=this._resolveConnectsTo();if(!e)return[];let a=[];for(let s of e){let l=this.getSubcircuit().selectOne(s);l&&a.push(l)}return a}computeSchematicPropsTransform(){let{_parsedProps:e}=this;if(e.schX===void 0&&e.schY===void 0){let a=this._getConnectedPorts();if(a.length>0){let s=a[0]._getGlobalSchematicPositionBeforeLayout(),l=rs(this.parent?.computeSchematicGlobalTransform?.()??_i(),{x:0,y:0});return ka(s.x-l.x,s.y-l.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalSchematicPositionBeforeLayout(),l=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),p=a.anchorSide??"right",x=Qp({anchor_position:s,anchor_side:p,text:a.net}),f=e.schematic_net_label.insert({text:a.net,source_net_id:l.source_net_id,anchor_position:s,center:x,anchor_side:this._getAnchorSide()});this.source_net_label_id=f.source_net_id}_resolveConnectsTo(){let{_parsedProps:e}=this,a=e.connectsTo??e.connection;if(Array.isArray(a))return a;if(typeof a=="string")return[a]}_getNetName(){let{_parsedProps:e}=this;return e.net}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;e.net&&ZW(this,[`net.${e.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let e=this._resolveConnectsTo();if(e)for(let a of e)this.add(new zc({from:a,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:e}=this.root,a=this._resolveConnectsTo();if(!a||a.length===0)return;let s=this._getGlobalSchematicPositionBeforeLayout(),l=this._getAnchorSide(),x={left:"x-",right:"x+",top:"y+",bottom:"y-"}[l],f=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let m of a){let D=this.getSubcircuit().selectOne(m,{type:"port"});if(!D||!D.schematic_port_id)continue;let b=!1;if(f?.source_net_id){let O=e.source_trace.list().find($=>$.connected_source_net_ids?.includes(f.source_net_id)&&$.connected_source_port_ids?.includes(D.source_port_id??""));if(O&&(b=e.schematic_trace.list().some($=>$.source_trace_id===O.source_trace_id)),b)continue}let E=D._getGlobalSchematicPositionAfterLayout(),A=VW(D.facingDirection??"right")??"x+",B=sg({x:E.x,y:E.y,facingDirection:A},{x:s.x,y:s.y,facingDirection:x});if(!Array.isArray(B)||B.length<2)continue;let w=[];for(let O=0;O<B.length-1;O++)w.push({from:{x:B[O].x,y:B[O].y},to:{x:B[O+1].x,y:B[O+1].y}});let P,N;if(f?.source_net_id&&D.source_port_id){let O=e.source_trace.list().find($=>$.connected_source_net_ids?.includes(f.source_net_id)&&$.connected_source_port_ids?.includes(D.source_port_id));P=O?.source_trace_id,N=O?.subcircuit_connectivity_map_key||e.source_net.get(f.source_net_id)?.subcircuit_connectivity_map_key}e.schematic_trace.insert({source_trace_id:P,edges:w,junctions:[],subcircuit_connectivity_map_key:N}),e.schematic_port.update(D.schematic_port_id,{is_connected:!0})}}},n9e=class extends ma{constructor(){super(...arguments);q(this,"pcb_silkscreen_circle_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:IAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenCircle. Must be "top" or "bottom".`);let p=this._computePcbGlobalTransformBeforeLayout(),x=this.getSubcircuit(),f=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=e.pcb_silkscreen_circle.insert({pcb_component_id:f,layer:l,center:{x:a.pcbX??0,y:a.pcbY??0},radius:a.radius,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:a.strokeWidth??.1});this.pcb_silkscreen_circle_id=m.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:e}=this,a=e.radius*2;return{width:a,height:a}}},a9e=class extends ma{constructor(){super(...arguments);q(this,"pcb_silkscreen_rect_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:PAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenRect. Must be "top" or "bottom".`);let p=this.getSubcircuit(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_silkscreen_rect.insert({pcb_component_id:x,layer:l,center:{x:a.pcbX??0,y:a.pcbY??0},width:a.width,height:a.height,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:a.strokeWidth??.1});this.pcb_silkscreen_rect_id=f.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},s9e=class extends ma{constructor(){super(...arguments);q(this,"pcb_silkscreen_line_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:TAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenLine. Must be "top" or "bottom".`);let p=this.getSubcircuit(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_silkscreen_line.insert({pcb_component_id:x,layer:l,x1:a.x1,y1:a.y1,x2:a.x2,y2:a.y2,stroke_width:a.strokeWidth??.1,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:p?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=f.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:e}=this,a=Math.abs(e.x2-e.x1),s=Math.abs(e.y2-e.y1);return{width:a,height:s}}},i9e=class extends ma{constructor(e){super(e);q(this,"pcb_via_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0);q(this,"source_manually_placed_via_id",null);let a=this._getLayers();this._parsedProps.layers=a,this.initPorts()}get config(){return{componentName:"Via",zodProps:yAe}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:e}=this;return{width:e.outerDiameter,height:e.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_via.get(this.pcb_via_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y-s.height/2,right:a.x+s.width/2,bottom:a.y+s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}_getLayers(){let{fromLayer:e="top",toLayer:a="bottom"}=this._parsedProps;return e===a?[e]:[e,a]}initPorts(){let e=this._parsedProps.layers;for(let s of e){let l=new Ii({name:s,layer:s});l.registerMatch(this),this.add(l)}let a=new Ii({name:"pin1"});a.registerMatch(this),this.add(a)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.getSubcircuit(),p=e.pcb_component.insert({center:s,width:a.outerDiameter,height:a.outerDiameter,layer:a.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:l?.subcircuit_id??void 0});this.pcb_component_id=p.pcb_component_id}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getGroup(),l=this.getSubcircuit(),p=e.source_manually_placed_via.insert({source_group_id:s?.source_group_id,source_net_id:a.net??"",subcircuit_id:l?.subcircuit_id??void 0});this.source_component_id=p.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.getSubcircuit(),p=e.pcb_via.insert({x:s.x,y:s.y,hole_diameter:a.holeDiameter,outer_diameter:a.outerDiameter,layers:["bottom","top"],from_layer:a.fromLayer||"bottom",to_layer:a.toLayer||"top",subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=p.pcb_via_id}},o9e=class extends Za{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:sAe,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,a=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=a.source_component_id}},u9e=class extends Za{get config(){return{componentName:"PinHeader",zodProps:iAe,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,a=this._parsedProps.platedDiameter,s=this._parsedProps.pitch,l=this._parsedProps.showSilkscreenPinLabels;if(n>0){let p;if(s)!e&&!a?p=`pinrow${n}_p${s}`:p=`pinrow${n}_p${s}_id${e}_od${a}`;else if(!e&&!a)p=`pinrow${n}`;else return null;return l!==!0&&(p+="_nopinlabels"),p}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 a=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[e-1]:this._parsedProps.pinLabels?.[`pin${e}`];if(a){let s=Array.isArray(a)?a[0]:a,l=Array.isArray(a)?a.slice(1):[];this.add(new Ii({pinNumber:e,name:s,aliases:[`pin${e}`,...l]}))}else this.add(new Ii({pinNumber:e,name:`pin${e}`}))}}_getSchematicPortArrangement(){let n=this._parsedProps.pinCount??1,e=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",a=this._parsedProps.schPinArrangement;return e==="left"?{leftSide:{direction:a?.leftSide?.direction??"top-to-bottom",pins:a?.leftSide?.pins??Array.from({length:n},(s,l)=>`pin${l+1}`)}}:{rightSide:{direction:a?.rightSide?.direction??"top-to-bottom",pins:a?.rightSide?.pins??Array.from({length:n},(s,l)=>`pin${l+1}`)}}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=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=a.source_component_id}};function dGt(n){switch(n){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var c9e=class extends Za{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??dGt(this.props.pinVariant),zodProps:K_e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=e.pinVariant||"no_ground",s=n.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:a,are_pins_interchangeable:a==="no_ground"||a==="ground_pin"});this.source_component_id=s.source_component_id}_getSchematicSymbolDisplayValue(){let n=`${js(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${js(this._parsedProps.loadCapacitance)}F`:n}},l9e=class extends Za{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:dAe,sourceFtype:od.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${js(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({name:this.name,ftype:od.simple_inductor,inductance:a.inductance,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}};function pGt(n){switch(n){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var d9e=class extends Za{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??pGt(this.props.pinVariant),zodProps:H_e,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${js(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=e.pinVariant||"two_pin",s=n.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:e.maxResistance,pin_variant:a,are_pins_interchangeable:a==="two_pin"});this.source_component_id=s.source_component_id}},p9e=class extends Za{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:uAe,sourceFtype:od.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let n=Ps[this._getSchematicSymbolNameOrThrow()],e=n.ports.find(D=>D.labels.includes("1")),a=n.ports.find(D=>D.labels.includes("2")),s=this.selectAll("port"),l=s.find(D=>D.props.pinNumber===1),p=s.find(D=>D.props.pinNumber===2),x=s.find(D=>D.props.pinNumber===3),f=s.find(D=>D.props.pinNumber===4),{internallyConnectedPins:m}=this._parsedProps;l.schematicSymbolPortDef=e,(!m||m.length===0)&&(p.schematicSymbolPortDef=a);for(let[D,b]of[[2,p],[3,x],[4,f]]){let E=m?.find(([B,w])=>B===`pin${D}`||w===`pin${D}`);if(!E){b.schematicSymbolPortDef=a;break}(E?.[0]===`pin${D}`?E[1]:E?.[0])!=="pin1"&&(b.schematicSymbolPortDef=a)}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({name:this.name,ftype:od.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}},x9e=class extends Za{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:W_e,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=`${js(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${js(this._parsedProps.loadCapacitance)}F`:n}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=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=a.source_component_id}},f9e=class extends Za{constructor(){super(...arguments);q(this,"emitter",this.portMap.pin1);q(this,"collector",this.portMap.pin2);q(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:cAe,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:a}=this,s=e.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:a.type});this.source_component_id=s.source_component_id}},h9e=class extends Za{get config(){let n=this.props.mosfetMode==="depletion"?"d":"e",a=`${this.props.channelType}_channel_${n}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??a,zodProps:lAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=a.source_component_id}},m9e=class extends Za{_getSwitchType(){let{spst:n,spdt:e,dpst:a,dpdt:s,type:l}=this._parsedProps??{};return s?"dpdt":n?"spst":e?"spdt":a?"dpst":l??"spst"}get config(){let n=this._getSwitchType(),{isNormallyClosed:e}=this._parsedProps??{},s={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"}[n]??"spst_switch";return{componentName:"Switch",schematicSymbolName:this.props.symbolName??s,zodProps:mAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({ftype:"simple_switch",name:this.name,switch_type:e.type,is_normally_closed:e.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=a.source_component_id}},$W={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},g9e=class extends Za{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:bAe,sourceFtype:od.simple_test_point}}_getPropsWithDefaults(){let{padShape:n,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:p}=this._parsedProps;return!a&&e&&(a="through_hole"),a??(a="through_hole"),n??(n="circle"),a==="pad"?n==="circle"?s??(s=$W.SMT_CIRCLE_DIAMETER):n==="rect"&&(l??(l=$W.SMT_RECT_SIZE),p??(p=l)):a==="through_hole"&&(e??(e=$W.HOLE_DIAMETER)),{padShape:n,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:p}}_getImpliedFootprintString(){let{padShape:n,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:p}=this._getPropsWithDefaults();if(a==="through_hole")return`platedhole_d${e}`;if(a==="pad"){if(n==="circle")return`smtpad_circle_d${s}`;if(n==="rect")return`smtpad_rect_w${l}_h${p}`}throw new Error(`Footprint variant "${a}" with pad shape "${n}" not implemented`)}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,{padShape:a,holeDiameter:s,footprintVariant:l,padDiameter:p,width:x,height:f}=this._getPropsWithDefaults(),m=n.source_component.insert({ftype:od.simple_test_point,name:this.name,supplier_part_numbers:e.supplierPartNumbers,footprint_variant:l,pad_shape:a,pad_diameter:p,hole_diameter:s,width:x,height:f,are_pins_interchangeable:!0});this.source_component_id=m.source_component_id}},D9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:_Ae}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalSchematicPositionBeforeLayout();e.schematic_text.insert({anchor:a.anchor??"center",text:a.text,font_size:a.fontSize,color:a.color||"#000000",position:{x:s.x,y:s.y},rotation:a.schRotation??0})}};function xGt({anchor:n,x:e,y:a,width:s,height:l,isInside:p}){switch(n){case"top_left":return{x:e,y:a+l,textAnchor:p?"top_left":"bottom_left"};case"top_center":return{x:e+s/2,y:a+l,textAnchor:p?"top_center":"bottom_center"};case"top_right":return{x:e+s,y:a+l,textAnchor:p?"top_right":"bottom_right"};case"center_left":return{x:e,y:a+l/2,textAnchor:p?"center_left":"center_right"};case"center":return{x:e+s/2,y:a+l/2,textAnchor:"center"};case"center_right":return{x:e+s,y:a+l/2,textAnchor:p?"center_right":"center_left"};case"bottom_left":return{x:e,y:a,textAnchor:p?"bottom_left":"top_left"};case"bottom_center":return{x:e+s/2,y:a,textAnchor:p?"bottom_center":"top_center"};case"bottom_right":return{x:e+s,y:a,textAnchor:p?"bottom_right":"top_right"};default:return{x:e+s/2,y:a+l,textAnchor:"center"}}}var y9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:CAe,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=.6,l=typeof a.padding=="number"?a.padding:0,p=typeof a.paddingTop=="number"?a.paddingTop:l,x=typeof a.paddingBottom=="number"?a.paddingBottom:l,f=typeof a.paddingLeft=="number"?a.paddingLeft:l,m=typeof a.paddingRight=="number"?a.paddingRight:l,D=a.overlay&&a.overlay.length>0,b=typeof a.width=="number"&&typeof a.height=="number",E,A,B,w,P,N;if(D){let $=a.overlay.map(it=>({selector:it,port:this.getSubcircuit().selectOne(it,{type:"port"})})).filter(({port:it})=>it!=null).map(({port:it})=>({position:it._getGlobalSchematicPositionAfterLayout()}));if($.length===0)return;let ee=$.map(it=>it.position.x),X=$.map(it=>it.position.y),te=Math.min(...ee),L=Math.max(...ee),K=Math.min(...X),U=Math.max(...X),J=L-te,Q=U-K,de=J===0?s:0,ce=Q===0?s:0,Te=f+de/2,Ne=m+de/2,Ve=p+ce/2,et=x+ce/2,ct=te-Te,Mt=L+Ne,Dt=K-et,ot=U+Ve;E=Mt-ct,A=ot-Dt,B=ct+(a.schX??0),w=Dt+(a.schY??0),P=B+E/2,N=w+A/2}else if(b){E=a.width,A=a.height;let O=this._getGlobalSchematicPositionBeforeLayout();P=O.x,N=O.y,B=P-E/2,w=N-A/2}else return;if(e.schematic_box.insert({height:A,width:E,x:B,y:w,is_dashed:a.strokeStyle==="dashed"}),a.title){let O=a.titleInside,$=.1,ee=a.titleAlignment,X=xGt({anchor:ee,x:B,y:w,width:E,height:A,isInside:O}),te,L,K=X.textAnchor;O?(te=ee.includes("top")?-$:ee.includes("bottom")?$:0,L=ee.includes("left")?$:ee.includes("right")?-$:0):(te=ee.includes("top")?$:ee.includes("bottom")?-$:0,L=ee.includes("center_left")?-$:ee.includes("center_right")?$:0);let U=X.x+L,J=X.y+te;e.schematic_text.insert({anchor:K,text:a.title,font_size:a.titleFontSize??.18,color:a.titleColor??"#000000",position:{x:U,y:J},rotation:0})}}},b9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0);q(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:AAe}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.children.filter(A=>A.componentName==="SchematicRow");if(s.length===0)return;let l=[],p=0;for(let A of s){let B=A.children.filter(w=>w.componentName==="SchematicCell");p=Math.max(p,B.length)}for(let A=0;A<s.length;A++)l[A]=[];for(let A=0;A<s.length;A++){let w=s[A].children.filter(N=>N.componentName==="SchematicCell"),P=0;for(let N=0;N<w.length;N++){for(;l[A][P];)P++;let O=w[N],$=O._parsedProps.colSpan??1,ee=O._parsedProps.rowSpan??1;for(let X=0;X<ee;X++)for(let te=0;te<$;te++)l[A+X]||(l[A+X]=[]),l[A+X][P+te]=O;P+=$}}p=Math.max(0,...l.map(A=>A.length));let x=s.map((A,B)=>A._parsedProps.height??1),f=Array.from({length:p},(A,B)=>{let w=0;for(let P=0;P<s.length;P++){let N=l[P]?.[B];if(N){let O=N._parsedProps.text??N._parsedProps.children,$=N._parsedProps.width??(O?.length??2)*.5;$>w&&(w=$)}}return w||10}),m=this._getGlobalSchematicPositionBeforeLayout(),D=e.schematic_table.insert({anchor_position:m,column_widths:f,row_heights:x,cell_padding:a.cellPadding,border_width:a.borderWidth,anchor:a.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=D.schematic_table_id;let b=new Set,E=0;for(let A=0;A<s.length;A++){let B=0;for(let w=0;w<p;w++){let P=l[A]?.[w];if(P&&!b.has(P)){b.add(P);let N=P._parsedProps,O=N.rowSpan??1,$=N.colSpan??1,ee=0;for(let te=0;te<$;te++)ee+=f[w+te];let X=0;for(let te=0;te<O;te++)X+=x[A+te];e.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:A,end_row_index:A+O-1,start_column_index:w,end_column_index:w+$-1,text:N.text??N.children,center:{x:m.x+B+ee/2,y:m.y-E-X/2},width:ee,height:X,horizontal_align:N.horizontalAlign,vertical_align:N.verticalAlign,font_size:N.fontSize??a.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}f[w]&&(B+=f[w])}E+=x[A]}}},F9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:RAe}}},E9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0);q(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:SAe}}},fGt={name:"@tscircuit/core",type:"module",version:"0.0.703",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"'},devDependencies:{"@biomejs/biome":"^1.8.3","@tscircuit/capacity-autorouter":"^0.0.107","@tscircuit/checks":"^0.0.71","@tscircuit/circuit-json-util":"^0.0.67","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.21","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.298","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.35","@tscircuit/simple-3d-svg":"^0.0.38","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.245","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-simple-3d":"^0.0.6","circuit-to-svg":"^0.0.185",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.195","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.33","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"}},qg=class{constructor({platform:n,projectUrl:e}={}){q(this,"firstChild",null);q(this,"children");q(this,"db");q(this,"root",null);q(this,"isRoot",!0);q(this,"schematicDisabled",!1);q(this,"pcbDisabled",!1);q(this,"pcbRoutingDisabled",!1);q(this,"_featureMspSchematicTraceRouting",!0);q(this,"name");q(this,"platform");q(this,"projectUrl");q(this,"_hasRenderedAtleastOnce",!1);q(this,"_eventListeners",{});this.children=[],this.db=ia([]),this.root=this,this.platform=n,this.projectUrl=e,this.pcbDisabled=n?.pcbDisabled??!1}add(n){let e;(0,v9e.isValidElement)(n)?e=EBe(n):e=n,this.children.push(e)}_getBoard(){return this.children.find(n=>n.componentName==="Board")}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let n=new zg({subcircuit:!0});n.parent=this,n.addAll(this.children),this.children=[n],this.firstChild=n}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()?!0:n.children.some(e=>e._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(n){let e=await Promise.resolve().then(()=>(WSe(),HSe)).catch(a=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
|
|
1038
|
+
${s.stack}`),a.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:n,componentDisplayName:this.getString(),phase:a.phase,error:s.toString()})})}_emitRenderLifecycleEvent(n,e){fUt(`${n}:${e} ${this.getString()}`);let a=`renderable:renderLifecycle:${n}:${e}`,s={renderId:this._renderId,componentDisplayName:this.getString(),type:a};"root"in this&&this.root&&(this.root.emit(a,s),this.root.emit("renderable:renderLifecycle:anyEvent",{...s,type:a}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(n=>!n.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(n){for(let e of this._asyncEffects)if(!e.complete&&e.phase===n)return!0;for(let e of this.children)if(e._hasIncompleteAsyncEffectsInSubtreeForPhase(n))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(n=>n.getRenderGraph())}}runRenderCycle(){for(let n of id)this.runRenderPhaseForChildren(n),this.runRenderPhase(n)}runRenderPhase(n){this._currentRenderPhase=n;let e=this.renderPhaseStates[n],a=e.initialized,s=e.dirty;if(!a&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&a){this._emitRenderLifecycleEvent(n,"start"),this?.[`remove${n}`]?.(),e.initialized=!1,e.dirty=!1,this._emitRenderLifecycleEvent(n,"end");return}let l=id.indexOf(n)-1;if(l>=0){let x=id[l];if(this._asyncEffects.filter(m=>m.phase===x).some(m=>!m.complete))return}let p=hUt[n]||[];for(let x of p)if(this._hasIncompleteAsyncEffectsInSubtreeForPhase(x))return;if(this._emitRenderLifecycleEvent(n,"start"),a){s&&(this?.[`update${n}`]?.(),e.dirty=!1),this._emitRenderLifecycleEvent(n,"end");return}e.dirty=!1,this?.[`doInitial${n}`]?.(),e.initialized=!0,this._emitRenderLifecycleEvent(n,"end")}runRenderPhaseForChildren(n){for(let e of this.children)e.runRenderPhaseForChildren(n),e.runRenderPhase(n)}renderError(n){throw typeof n=="string"?new Error(n):new Error(JSON.stringify(n,null,2))}},LS={},FBe=n=>{let e=Object.fromEntries(Object.entries(n).map(([a,s])=>[a.toLowerCase(),s]));Object.assign(LS,n),Object.assign(LS,e)},gUt=class extends Error{constructor(n,e,a){let s,l=Object.keys(a).filter(m=>m!=="_errors"),p=[],x=e.pinLabels;if(x)for(let[m,D]of Object.entries(x)){let b=Array.isArray(D)?D:[D];for(let E of b)typeof E=="string"&&(E.startsWith(" ")||E.endsWith(" "))&&p.push(`pinLabels.${m} ("${E}" has leading or trailing spaces)`)}let f=l.map(m=>m==="pinLabels"&&p.length>0?p.join(", "):a[m]._errors[0]?`${m} (${a[m]._errors[0]})`:`${m} (${JSON.stringify(a[m])})`).join(", ");"name"in e?s=`Invalid props for ${n} "${e.name}": ${f}`:"footprint"in e&&typeof e.footprint=="string"?s=`Invalid props for ${n} (unnamed ${e.footprint} component): ${f}`:s=`Invalid props for ${n} (unnamed): ${f}`,super(s),this.componentName=n,this.originalProps=e,this.formattedError=a}};function jW(n,e){let a=e.match(/^#(\w+)/);if(a)return n.props.id===a[1];let s=e.match(/^\.(\w+)/);if(s)return n.isMatchingNameOrAlias(s[1]);let[l,...p]=e.split(/(?=[#.[])/);return l==="pin"&&(l="port"),l&&l!=="*"&&n.lowercaseComponentName!==l.toLowerCase()?!1:p.every(x=>{if(x.startsWith("#"))return n.props.id===x.slice(1);if(x.startsWith("."))return n.isMatchingNameOrAlias(x.slice(1));let f=x.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!f)return!0;let[,m,D]=f;return n.props[m].toString()===D})}var KW={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 s=n._parsedProps[e];return typeof s=="string"?s:s!=null?String(s):null}if(e in n){let s=n[e];return typeof s=="string"?s:s!=null?String(s):null}let a=n._attributeLowerToCamelNameMap;if(a){let s=a[e];if(s&&s in n){let l=n[s];return typeof l=="string"?l:l!=null?String(l):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 a=n._attributeLowerToCamelNameMap;if(a){let s=a[e];if(s&&s 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,a=e.indexOf(n);return a>0?e[a-1]:null},getText:()=>"",removeSubsets:n=>n.filter((e,a)=>!n.some((s,l)=>a!==l&&s!==e&&s.getDescendants().includes(e))),existsOne:(n,e)=>e.some(n),findAll:(n,e)=>{let a=[],s=l=>{n(l)&&a.push(l);for(let p of l.children)s(p)};for(let l of e)s(l);return a},findOne:(n,e)=>{for(let a of e){if(n(a))return a;let s=a.children;if(s.length>0){let l=KW.findOne(n,s);if(l)return l}}return null},equals:(n,e)=>n._renderId===e._renderId,isHovered:n=>!1,isVisited:n=>!1,isActive:n=>!1},DUt={...KW,getChildren:n=>n.children.filter(e=>!e.isSubcircuit)},KSe={...KW,getChildren:n=>n.children.filter(e=>e.isSubcircuit)},JSe=n=>{if(/net\.[^\s>]*\./.test(n))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(n))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(n)){let e=n.match(/net\.([^ >]+)/),a=e?e[1]:"";throw new Error(`Net name "${a}" cannot start with a number, try using a prefix like "VBUS1"`)}return n.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(e,a,s,l)=>{let p=/^\d+$/.test(l)?`pin${l}`:l;return`${a}.${s} > .${p}`}).trim()},kW={adapter:DUt,cacheResults:!0},ma=class extends WW{constructor(e){super(e);q(this,"parent",null);q(this,"children");q(this,"childrenPendingRemoval");q(this,"props");q(this,"_parsedProps");q(this,"externallyAddedAliases");q(this,"isPrimitiveContainer",!1);q(this,"canHaveTextChildren",!1);q(this,"source_group_id",null);q(this,"source_component_id",null);q(this,"schematic_component_id",null);q(this,"pcb_component_id",null);q(this,"cad_component_id",null);q(this,"fallbackUnassignedName");q(this,"_cachedSelectAllQueries",new Map);q(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=e??{},this.externallyAddedAliases=[];let s=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(e??{});if(s.success)this._parsedProps=s.data;else throw new gUt(this.lowercaseComponentName,this.props,s.error.format())}get config(){return{componentName:"",zodProps:C.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(e){let a=this;for(;a;){if(a._parsedProps&&e in a._parsedProps)return a._parsedProps[e];a=a.parent}if(this.root?.platform&&e in this.root.platform)return this.root.platform[e]}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 a=this.config.zodProps.parse({...this.props,...e}),s=this.props;this.props=a,this._parsedProps=this.config.zodProps.parse(e),this.onPropsChange({oldProps:s,newProps:a,changedProps:Object.keys(e)}),this.parent?.onChildChanged?.(this)}computePcbPropsTransform(){let{_parsedProps:e}=this;return Ts(ka(e.pcbX??0,e.pcbY??0),Xf((e.pcbRotation??0)*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let{_parsedProps:e}=this,a=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(a&&this.props.pcbX===void 0&&this.props.pcbY===void 0)return Ts(this.parent?._computePcbGlobalTransformBeforeLayout()??_i(),Ts(ka(a.x,a.y),Xf((e.pcbRotation??0)*Math.PI/180)));if(this.isPcbPrimitive){let s=this.getPrimitiveContainer();if(s){let l=s._parsedProps.layer==="bottom",p=s._getGlobalPcbPositionBeforeLayout();if(l){let x=Ts(ka(p.x,p.y),Yq(),ka(-p.x,-p.y));return Ts(this.parent?._computePcbGlobalTransformBeforeLayout()??_i(),Yq(),this.computePcbPropsTransform())}}}return Ts(this.parent?._computePcbGlobalTransformBeforeLayout()??_i(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let e=this.getPrimitiveContainer(),a=e?e._parsedProps.layer==="bottom":!1;return{isFlipped:a,maybeFlipLayer:l=>a?l==="top"?"bottom":"top":l}}_setPositionFromLayout(e){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:e}=this;return Ts(ka(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){let e=this._getSchematicGlobalManualPlacementTransform(this);return e||Ts(this.parent?.computeSchematicGlobalTransform?.()??_i(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:e}=this,a=this.config.schematicSymbolName,s={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},l=e.schOrientation!==void 0?s[e.schOrientation]:e.schRotation;if(l===void 0&&(l=0),l=l%360,l<0&&(l+=360),e.schRotation!==void 0&&l%90!==0)throw new Error(`Schematic rotation ${e.schRotation} is not supported for ${this.componentName}`);let p=`${a}_horz`,x=`${a}_vert`,f=`${a}_up`,m=`${a}_down`,D=`${a}_left`,b=`${a}_right`;if(b in Ps&&l===0)return b;if(f in Ps&&l===90)return f;if(D in Ps&&l===180)return D;if(m in Ps&&l===270)return m;if(p in Ps&&(l===0||l===180))return p;if(x in Ps&&(l===90||l===270))return x;if(a in Ps)return a}_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?Ps[e]??null:null}_getPcbManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let a=this.props.manualEdits;if(!a)return null;let s=a?.pcb_placements;if(!s)return null;for(let l of s)if(jW(e,l.selector)||e.props.name===l.selector)return rs(this._computePcbGlobalTransformBeforeLayout(),l.center);return null}_getSchematicManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let a=this.props.manualEdits;if(!a)return null;let s=a.schematic_placements;if(!s)return null;for(let l of s)if(jW(e,l.selector)||e.props.name===l.selector)return rs(this.computeSchematicGlobalTransform(),l.center);return null}_getSchematicGlobalManualPlacementTransform(e){let a=this.getSubcircuit()?._parsedProps.manualEdits;if(!a)return null;for(let s of a.schematic_placements??[])if((jW(e,s.selector)||e.props.name===s.selector)&&s.relative_to==="group_center")return Ts(this.parent?._computePcbGlobalTransformBeforeLayout()??_i(),ka(s.center.x,s.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return rs(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return rs(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(e){this.parent=e}onPropsChange(e){}onChildChanged(e){this.parent?.onChildChanged?.(e)}add(e){let a=e.__text;if(typeof a=="string"){if(this.canHaveTextChildren||a.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${a}"`)}if(Object.keys(e).length!==0){if(this.lowercaseComponentName==="board"&&e.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");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 a of e)this.add(a)}remove(e){this.children=this.children.filter(a=>a!==e),this.childrenPendingRemoval.push(e),e.shouldBeRemoved=!0}getSubcircuitSelector(){let e=this.name,a=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?a:`${this.parent.getSubcircuitSelector()} > ${a}`}getFullPathSelector(){let e=this.name,a=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName,s=this.parent?.getFullPathSelector?.();return s?`${s} > ${a}`:a}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(e){return this.getNameAndAliases().includes(e)}isMatchingAnyOf(e){return this.getNameAndAliases().some(a=>e.map(s=>s.toString()).includes(a))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(e){let a=[this.componentName,this.lowercaseComponentName],s=[this.name].filter(Boolean),l=e.trim().split(/\> /)[0],p=l[0];return l.length>1?!1:!!(e==="*"||e[0]==="#"&&e.slice(1)===this.props.id||e[0]==="."&&s.includes(e.slice(1))||/^[a-zA-Z0-9_]/.test(p)&&a.includes(p))}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 a of e){let s=a.parent?.getNameAndAliases(),l=a.getNameAndAliases();if(s)for(let p of s)for(let x of l){let f=[`.${p} > .${x}`,`.${p} .${x}`];for(let m of f){let D=this._cachedSelectAllQueries.get(m);D?D.push(a):this._cachedSelectAllQueries.set(m,[a])}}}for(let[a,s]of this._cachedSelectAllQueries.entries())s.length===1&&this._cachedSelectOneQueries.set(a,s[0])}selectAll(e){if(this._cachedSelectAllQueries.has(e))return this._cachedSelectAllQueries.get(e);let a=JSe(e),s=aY(a,this,kW);if(s.length>0)return this._cachedSelectAllQueries.set(e,s),s;let[l,...p]=a.split(" "),x=GR(l,this,{adapter:KSe});if(!x)return[];let f=x.selectAll(p.join(" "));return this._cachedSelectAllQueries.set(e,f),f}selectOne(e,a){if(this._cachedSelectOneQueries.has(e))return this._cachedSelectOneQueries.get(e);let s=JSe(e);a?.port&&(a.type="port");let l=null;if(a?.type&&(l=aY(s,this,kW).find(D=>D.lowercaseComponentName===a.type)),l??(l=GR(s,this,kW)),l)return this._cachedSelectOneQueries.set(e,l),l;let[p,...x]=s.split(" "),f=GR(p,this,{adapter:KSe});return f?(l=f.selectOne(x.join(" "),a),this._cachedSelectOneQueries.set(e,l),l):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 a of this.children)e.push(a),e.push(...a.getDescendants());return e}getSelectableDescendants(){let e=[];for(let a of this.children)a.isSubcircuit?e.push(a):(e.push(a),e.push(...a.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);this.root?.db.pcb_placement_error.insert(e)}getString(){let{lowercaseComponentName:e,_parsedProps:a,parent:s}=this;return a?.pinNumber!==void 0&&s?.props?.name&&a?.name?`<${e}#${this._renderId}(pin:${a.pinNumber} .${s?.props.name}>.${a.name}) />`:s?.props?.name&&a?.name?`<${e}#${this._renderId}(.${s?.props.name}>.${a?.name}) />`:a?.from&&a?.to?`<${e}#${this._renderId}(from:${a.from} to:${a?.to}) />`:a?.name?`<${e}#${this._renderId} name=".${a?.name}" />`:a?.portHints?`<${e}#${this._renderId}(${a.portHints.map(l=>`.${l}`).join(", ")}) />`:`<${e}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},yUt=class extends ma{constructor(n,e){super(n),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:n.pcbX,pcbY:n.pcbY,schX:n.schX,schY:n.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:C.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 bUt(n,e){return new yUt(n,e)}function FUt(n,e){let a=n;return a.__tsci={...e},n}var EUt={supportsMutation:!0,createInstance(n,e){let a=LS[n];if(!a)throw Object.keys(LS).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 FUt(new a(e),{})}catch(s){return bUt({...e,componentType:n},s)}},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:()=>MS.DefaultEventPriority,getCurrentUpdatePriority:()=>MS.DefaultEventPriority,resolveUpdatePriority:()=>MS.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},jS=(0,yBe.default)(EUt),EBe=n=>{let e={children:[],props:{name:"$root"},add(p){p.parent=this,this.children.push(p)},computePcbGlobalTransform(){return _i()}},a=[],s=jS.createContainer(e,0,null,!1,null,"tsci",p=>{console.log("Error in createContainer"),console.error(p),a.push(p)},null);if(jS.updateContainerSync(n,s,null,()=>{}),jS.flushSyncWork(),a.length>0)throw a[0];let l=jS.getPublicRootInstance(s);return l||e.children[0]},OF=(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 a in e)if((Array.isArray(e[a])?e[a]:[e[a]]).includes(n))return Number(a.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${n}"`)},vUt=(n,e)=>{if(!n)return;let a={},s={};for(let[l,p]of Object.entries(n)){let x=OF(l,e);s[x]={...s[x],...p}}for(let[l,p]of Object.entries(s)){let x=`pin${l}`;a[x]={bottom_margin:p.bottomMargin,left_margin:p.leftMargin,right_margin:p.rightMargin,top_margin:p.topMargin}}return a},CUt=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 vBe(n){let e=[];for(let a=0;a<n.length-1;a++)e.push([n[a],n[a+1]]);return e}var _Ut=C.object({name:C.string().refine(n=>!/[+-]/.test(n),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),JW=class extends ma{constructor(){super(...arguments);q(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:_Ut}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=a.name.startsWith("GND"),l=a.name.startsWith("V"),p=e.source_net.insert({name:a.name,member_source_group_ids:[],is_ground:s,is_power:l,is_positive_voltage_source:l});this.source_net_id=p.source_net_id}doInitialSourceParentAttachment(){let e=this.getSubcircuit();if(!e)return;let{db:a}=this.root;a.source_net.update(this.source_net_id,{subcircuit_id:e.subcircuit_id})}getAllConnectedPorts(){let e=this.getSubcircuit().selectAll("port"),a=[];for(let s of e){let l=s._getDirectlyConnectedTraces();for(let p of l)if(p._isExplicitlyConnectedToNet(this)){a.push(s);break}}return a}_getAllDirectlyConnectedTraces(){let e=this.getSubcircuit().selectAll("trace"),a=[];for(let s of e)s._isExplicitlyConnectedToNet(this)&&a.push(s);return a}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getAllDirectlyConnectedTraces().filter(x=>(x._portsRoutedOnPcb?.length??0)>0),l=[];for(let x of s){let f=x._portsRoutedOnPcb,m=l.find(D=>f.some(b=>D.ports.includes(b)));if(!m){l.push({ports:[...f],traces:[x]});continue}m.traces.push(x),m.ports.push(...f)}if(l.length===0)return;let p=vBe(l);for(let[x,f]of p){let m=x.ports.map(O=>O._getGlobalPcbPositionBeforeLayout()),D=f.ports.map(O=>O._getGlobalPcbPositionBeforeLayout()),b=1/0,E=[-1,-1];for(let O=0;O<m.length;O++){let $=m[O];for(let ee=0;ee<D.length;ee++){let X=D[ee],te=Math.sqrt(($.x-X.x)**2+($.y-X.y)**2);te<b&&(b=te,E=[O,ee])}}let A=x.ports[E[0]],B=f.ports[E[1]],w=e.toArray().filter(O=>O.type==="pcb_smtpad"||O.type==="pcb_trace"||O.type==="pcb_plated_hole"||O.type==="pcb_hole"||O.type==="source_port"||O.type==="pcb_port"),{solution:P}=T_e(w.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[A.source_port_id,B.source_port_id]}])),N=P[0];if(!N){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[A.pcb_component_id,B.pcb_component_id].filter(Boolean),pcb_port_ids:[A.pcb_port_id,B.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(N)}}renderError(e){if(typeof e=="string")return super.renderError(e);this.root?.db.pcb_trace_error.insert(e)}},ZW=(n,e)=>{for(let a of e)if(typeof a=="string"&&a.startsWith("net.")){if(/net\.[^\s>]*\./.test(a))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(a))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(a)){let l=a.split("net.")[1];throw new Error(`Net name "${l}" cannot start with a number, try using a prefix like "VBUS1"`)}let s=n.getSubcircuit();if(!s.selectOne(a)){let l=new JW({name:a.split("net.")[1]});s.add(l)}}},$S=class extends ma{constructor(){super(...arguments);q(this,"pcb_smtpad_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:tAe}}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==="polygon"){let a=e.points,s=a.map(D=>D.x),l=a.map(D=>D.y),p=Math.min(...s),x=Math.max(...s),f=Math.min(...l),m=Math.max(...l);return{width:x-p,height:m-f}}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 a of e)if(a.isMatchingAnyOf(this.props.portHints)){this.matchedPort=a,a.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this;if(!a.portHints)return;let s=this.getPrimitiveContainer(),l=this.getSubcircuit(),p=this._getGlobalPcbPositionBeforeLayout(),x=s?._getGlobalPcbPositionBeforeLayout(),f=QA(this._computePcbGlobalTransformBeforeLayout()),m=Math.abs(f.rotation.angle*(180/Math.PI)-90)%180<.01,{maybeFlipLayer:D}=this._getPcbPrimitiveFlippedHelpers(),b=s?._parsedProps.pcbRotation??0,E=null,A=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;a.shape==="circle"?(E=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"circle",radius:a.radius,port_hints:a.portHints.map(B=>B.toString()),x:p.x,y:p.y,subcircuit_id:l?.subcircuit_id??void 0}),e.pcb_solder_paste.insert({layer:E.layer,shape:"circle",radius:E.radius*.7,x:E.x,y:E.y,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):a.shape==="rect"?(E=b===0||m?e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"rect",width:m?a.height:a.width,height:m?a.width:a.height,port_hints:a.portHints.map(B=>B.toString()),x:p.x,y:p.y,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):e.pcb_smtpad.insert({pcb_component_id:A,layer:D(a.layer??"top"),shape:"rotated_rect",width:a.width,height:a.height,x:p.x,y:p.y,ccw_rotation:b,port_hints:a.portHints.map(B=>B.toString()),subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),E.shape==="rect"&&e.pcb_solder_paste.insert({layer:D(a.layer??"top"),shape:"rect",width:E.width*.7,height:E.height*.7,x:E.x,y:E.y,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),E.shape==="rotated_rect"&&e.pcb_solder_paste.insert({layer:D(a.layer??"top"),shape:"rotated_rect",width:E.width*.7,height:E.height*.7,x:E.x,y:E.y,ccw_rotation:b,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):a.shape==="polygon"&&(E=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"polygon",points:a.points.map(B=>({x:B.x+p.x,y:B.y+p.y})),port_hints:a.portHints.map(B=>B.toString()),subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})),E&&(this.pcb_smtpad_id=E.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,a=e.pcb_smtpad.get(this.pcb_smtpad_id);if(a.shape==="rect")return{center:{x:a.x,y:a.y},bounds:{left:a.x-a.width/2,top:a.y+a.height/2,right:a.x+a.width/2,bottom:a.y-a.height/2},width:a.width,height:a.height};if(a.shape==="rotated_rect"){let s=a.ccw_rotation*Math.PI/180,l=Math.cos(s),p=Math.sin(s),x=a.width/2,f=a.height/2,m=Math.abs(x*l)+Math.abs(f*p),D=Math.abs(x*p)+Math.abs(f*l);return{center:{x:a.x,y:a.y},bounds:{left:a.x-m,right:a.x+m,top:a.y-D,bottom:a.y+D},width:m*2,height:D*2}}if(a.shape==="circle")return{center:{x:a.x,y:a.y},bounds:{left:a.x-a.radius,top:a.y-a.radius,right:a.x+a.radius,bottom:a.y+a.radius},width:a.radius*2,height:a.radius*2};if(a.shape==="polygon"){let s=a.points,l=s.map(b=>b.x),p=s.map(b=>b.y),x=Math.min(...l),f=Math.max(...l),m=Math.min(...p),D=Math.max(...p);return{center:{x:(x+f)/2,y:(m+D)/2},bounds:{left:x,top:D,right:f,bottom:m},width:f-x,height:D-m}}throw new Error(`circuitJson bounds calculation not implemented for shape "${a.shape}"`)}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_smtpad.update(this.pcb_smtpad_id,{x:e.x,y:e.y});let s=a.pcb_solder_paste.list().find(l=>l.pcb_smtpad_id===this.pcb_smtpad_id);a.pcb_solder_paste.update(s?.pcb_solder_paste_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}},QW=class extends ma{constructor(){super(...arguments);q(this,"pcb_silkscreen_path_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:wAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenPath. Must be "top" or "bottom".`);let p=this._computePcbGlobalTransformBeforeLayout(),x=this.getSubcircuit(),f=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=e.pcb_silkscreen_path.insert({pcb_component_id:f,layer:l,route:a.route.map(D=>{let b=rs(p,{x:D.x,y:D.y});return{...D,x:b.x,y:b.y}}),stroke_width:a.strokeWidth??.1,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=m.pcb_silkscreen_path_id}_setPositionFromLayout(e){let{db:a}=this.root,{_parsedProps:s}=this,l=a.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!l)return;let p=0,x=0;for(let b of l.route)p+=b.x,x+=b.y;p/=l.route.length,x/=l.route.length;let f=e.x-p,m=e.y-x,D=l.route.map(b=>({...b,x:b.x+f,y:b.y+m}));a.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:D})}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let a=1/0,s=-1/0,l=1/0,p=-1/0;for(let x of e.route)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),p=Math.max(p,x.y);return{width:s-a,height:p-l}}},AUt=C.object({route:C.array(MA),source_trace_id:C.string().optional()}),eK=class extends ma{constructor(){super(...arguments);q(this,"pcb_trace_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:AUt}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer(),l=this.getSubcircuit(),{maybeFlipLayer:p}=this._getPcbPrimitiveFlippedHelpers(),x=this._computePcbGlobalTransformBeforeLayout(),f=a.route.map(D=>{let{x:b,y:E,...A}=D,B=rs(x,{x:b,y:E});return D.route_type==="wire"&&D.layer?{...B,...A,layer:p(D.layer)}:{...B,...A}}),m=e.pcb_trace.insert({pcb_component_id:s.pcb_component_id,source_trace_id:a.source_trace_id,route:f,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=m.pcb_trace_id}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let a=1/0,s=-1/0,l=1/0,p=-1/0;for(let x of e.route)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),p=Math.max(p,x.y),x.route_type==="wire"&&(a=Math.min(a,x.x-x.width/2),s=Math.max(s,x.x+x.width/2),l=Math.min(l,x.y-x.width/2),p=Math.max(p,x.y+x.width/2));return a===1/0||s===-1/0||l===1/0||p===-1/0?{width:0,height:0}:{width:s-a,height:p-l}}},zS=class extends ma{constructor(){super(...arguments);q(this,"pcb_plated_hole_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:G_e}}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};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_plated_hole.get(this.pcb_plated_hole_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y+s.height/2,right:a.x+s.width/2,bottom:a.y-s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.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 a of e)if(a.isMatchingAnyOf(this.props.portHints)){this.matchedPort=a,a.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,p=this.getSubcircuit();if(a.shape==="circle"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:a.outerDiameter,hole_diameter:a.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:a.outerDiameter/2,x:s.x,y:s.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:a.outerDiameter/2,x:s.x,y:s.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(a.shape==="pill"&&a.rectPad){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:a.outerWidth,outer_height:a.outerHeight,hole_width:a.holeWidth,hole_height:a.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:a.pcbRotation??0,rect_ccw_rotation:a.pcbRotation??0,rect_pad_width:a.outerWidth,rect_pad_height:a.outerHeight});this.pcb_plated_hole_id=x.pcb_plated_hole_id}else if(a.shape==="pill"||a.shape==="oval"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:a.outerWidth,outer_height:a.outerHeight,hole_width:a.holeWidth,hole_height:a.holeHeight,shape:a.shape,port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:a.shape,width:a.outerWidth,height:a.outerHeight,x:s.x,y:s.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:a.shape,width:a.outerWidth,height:a.outerHeight,x:s.x,y:s.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(a.shape==="circular_hole_with_rect_pad"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:a.holeDiameter,rect_pad_width:a.rectPadWidth,rect_pad_height:a.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id}else if(a.shape==="pill_hole_with_rect_pad"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:a.holeWidth,hole_height:a.holeHeight,rect_pad_width:a.rectPadWidth,rect_pad_height:a.rectPadHeight,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},qS=class extends ma{constructor(){super(...arguments);q(this,"pcb_keepout_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:EAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let e=this.getSubcircuit(),{db:a}=this.root,{_parsedProps:s}=this,l=this._getGlobalPcbPositionBeforeLayout(),p=QA(this._computePcbGlobalTransformBeforeLayout()),x=Math.abs(p.rotation.angle*(180/Math.PI)-90)%180<.01,f=null;s.shape==="circle"?f=a.pcb_keepout.insert({layers:["top"],shape:"circle",radius:s.radius,center:{x:l.x,y:l.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0}):s.shape==="rect"&&(f=a.pcb_keepout.insert({layers:["top"],shape:"rect",...x?{width:s.height,height:s.width}:{width:s.width,height:s.height},center:{x:l.x,y:l.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0})),f&&(this.pcb_keepout_id=f.pcb_keepout_id)}},tK=class extends ma{constructor(){super(...arguments);q(this,"pcb_hole_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:rAe}}getPcbSize(){let{_parsedProps:e}=this;return{width:e.diameter,height:e.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=this._getGlobalPcbPositionBeforeLayout(),p=e.pcb_hole.insert({hole_shape:"circle",hole_diameter:a.diameter,x:l.x,y:l.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:s?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=p.pcb_hole_id}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_hole.get(this.pcb_hole_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y-s.height/2,right:a.x+s.width/2,bottom:a.y+s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_hole.update(this.pcb_hole_id,{x:e.x,y:e.y})}},YS=class extends ma{constructor(){super(...arguments);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:BAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer(),l=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:p}=this._getPcbPrimitiveFlippedHelpers(),x=this.getSubcircuit(),f=new Set(a.layers);a.layer&&f.add(a.layer);let m=f.size>0?Array.from(f):["top"];for(let D of m)e.pcb_silkscreen_text.insert({anchor_alignment:a.anchorAlignment,anchor_position:{x:l.x,y:l.y},font:a.font??"tscircuit2024",font_size:a.fontSize??1,layer:p(D),text:a.text??"",ccw_rotation:a.pcbRotation,pcb_component_id:s.pcb_component_id,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:e}=this,a=e.fontSize??1,l=(e.text??"").length*a,p=a;return{width:l*a,height:p*a}}},MF=class extends ma{constructor(){super(...arguments);q(this,"pcb_cutout_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:eAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=this.getGroup()?.pcb_group_id??void 0,p=this._getGlobalPcbPositionBeforeLayout(),f=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,m;if(a.shape==="rect"){let D=typeof f=="string"?parseInt(f.replace("deg",""),10):f,b=Math.abs(D%180)===90,E={shape:"rect",center:p,width:b?a.height:a.width,height:b?a.width:a.height,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(E)}else if(a.shape==="circle"){let D={shape:"circle",center:p,radius:a.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(D)}else if(a.shape==="polygon"){let D=this._computePcbGlobalTransformBeforeLayout(),E={shape:"polygon",points:a.points.map(A=>rs(D,A)),subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(E)}m&&(this.pcb_cutout_id=m.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 a=1/0,s=-1/0,l=1/0,p=-1/0;for(let x of e.points)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),p=Math.max(p,x.y);return{width:s-a,height:p-l}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,a=e.pcb_cutout.get(this.pcb_cutout_id);if(!a)return super._getPcbCircuitJsonBounds();if(a.shape==="rect")return{center:a.center,bounds:{left:a.center.x-a.width/2,top:a.center.y+a.height/2,right:a.center.x+a.width/2,bottom:a.center.y-a.height/2},width:a.width,height:a.height};if(a.shape==="circle")return{center:a.center,bounds:{left:a.center.x-a.radius,top:a.center.y+a.radius,right:a.center.x+a.radius,bottom:a.center.y-a.radius},width:a.radius*2,height:a.radius*2};if(a.shape==="polygon"){if(a.points.length===0)return super._getPcbCircuitJsonBounds();let s=1/0,l=-1/0,p=1/0,x=-1/0;for(let f of a.points)s=Math.min(s,f.x),l=Math.max(l,f.x),p=Math.min(p,f.y),x=Math.max(x,f.y);return{center:{x:(s+l)/2,y:(p+x)/2},bounds:{left:s,top:x,right:l,bottom:p},width:l-s,height:x-p}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(e){if(!this.pcb_cutout_id)return;let{db:a}=this.root,s=a.pcb_cutout.get(this.pcb_cutout_id);if(s){if(s.shape==="rect"||s.shape==="circle")a.pcb_cutout.update(this.pcb_cutout_id,{...s,center:e});else if(s.shape==="polygon"){let l=this._getPcbCircuitJsonBounds().center,p=e.x-l.x,x=e.y-l.y,f=s.points.map(m=>({x:m.x+p,y:m.y+x}));a.pcb_cutout.update(this.pcb_cutout_id,{...s,points:f})}}}},RUt=({elm:n,pinLabels:e,layer:a,readableRotation:s,anchorAlignment:l})=>{let p=n.text.replace(/[{}]/g,"").toLowerCase(),x=p;if(Array.isArray(e)){let f=parseInt(p.replace(/[^\d]/g,""),10)-1;x=String(e[f]??p)}else typeof e=="object"&&(x=String(e[p]??p));return new YS({anchorAlignment:l||"center",text:x??p,layer:a||"top",fontSize:n.font_size+.2,pcbX:isNaN(n.anchor_position.x)?0:n.anchor_position.x,pcbY:n.anchor_position.y,pcbRotation:s??0})},SUt=(n,e)=>((-parseInt(n||"0",10)+(e??0))%360+360)%360,zW=({componentName:n,componentRotation:e,footprint:a,pinLabels:s,pcbPinLabels:l},p)=>{let x=[];for(let f of p)if(f.type==="pcb_smtpad"&&f.shape==="rect")x.push(new $S({pcbX:f.x,pcbY:f.y,layer:f.layer,shape:"rect",height:f.height,width:f.width,portHints:f.port_hints}));else if(f.type==="pcb_smtpad"&&f.shape==="circle")x.push(new $S({pcbX:f.x,pcbY:f.y,layer:f.layer,shape:"circle",radius:f.radius,portHints:f.port_hints}));else if(f.type==="pcb_silkscreen_path")x.push(new QW({layer:f.layer,route:f.route,strokeWidth:f.stroke_width}));else if(f.type==="pcb_plated_hole")f.shape==="circle"?x.push(new zS({pcbX:f.x,pcbY:f.y,shape:"circle",holeDiameter:f.hole_diameter,outerDiameter:f.outer_diameter,portHints:f.port_hints})):f.shape==="circular_hole_with_rect_pad"&&x.push(new zS({pcbX:f.x,pcbY:f.y,shape:"circular_hole_with_rect_pad",holeDiameter:f.hole_diameter,rectPadHeight:f.rect_pad_height,rectPadWidth:f.rect_pad_width,portHints:f.port_hints}));else if(f.type==="pcb_keepout"&&f.shape==="circle")x.push(new qS({pcbX:f.center.x,pcbY:f.center.y,shape:"circle",radius:f.radius}));else if(f.type==="pcb_keepout"&&f.shape==="rect")x.push(new qS({pcbX:f.center.x,pcbY:f.center.y,shape:"rect",width:f.width,height:f.height}));else if(f.type==="pcb_hole"&&f.hole_shape==="circle")x.push(new tK({pcbX:f.x,pcbY:f.y,diameter:f.hole_diameter}));else if(f.type==="pcb_cutout")f.shape==="rect"?x.push(new MF({pcbX:f.center.x,pcbY:f.center.y,shape:"rect",width:f.width,height:f.height})):f.shape==="circle"?x.push(new MF({pcbX:f.center.x,pcbY:f.center.y,shape:"circle",radius:f.radius})):f.shape==="polygon"&&x.push(new MF({shape:"polygon",points:f.points}));else if(f.type==="pcb_silkscreen_text"){let m=SUt(e,f.ccw_rotation);a.includes("pinrow")&&f.text.includes("PIN")?x.push(RUt({elm:f,pinLabels:l??s,layer:f.layer,readableRotation:m,anchorAlignment:f.anchor_alignment})):x.push(new YS({anchorAlignment:f.anchor_alignment||"center",text:n,fontSize:f.font_size+.2,pcbX:Number.isNaN(f.anchor_position.x)?0:f.anchor_position.x,pcbY:f.anchor_position.y,pcbRotation:m??0}))}else f.type==="pcb_trace"&&x.push(new eK({route:f.route}));return x};function rK(n){let e=1/0,a=1/0,s=-1/0,l=-1/0,p=!1;for(let m of n)if(m.isPcbPrimitive&&!m.componentName.startsWith("Silkscreen")){let{x:D,y:b}=m._getGlobalPcbPositionBeforeLayout(),{width:E,height:A}=m.getPcbSize();e=Math.min(e,D-E/2),a=Math.min(a,b-A/2),s=Math.max(s,D+E/2),l=Math.max(l,b+A/2),p=!0}else if(m.children.length>0){let D=rK(m.children);(D.width>0||D.height>0)&&(e=Math.min(e,D.minX),a=Math.min(a,D.minY),s=Math.max(s,D.maxX),l=Math.max(l,D.maxY),p=!0)}if(!p)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let x=s-e,f=l-a;return x<0&&(x=0),f<0&&(f=0),{minX:e,minY:a,maxX:s,maxY:l,width:x,height:f}}function BUt(n,e){let a=e.x-n.x,s=e.y-n.y;return Math.abs(a)>Math.abs(s)?a>=0?"right":"left":s>=0?"up":"down"}var ZSe=n=>{if(n.length<=1)return!0;let e=n.map(p=>{let x=p._getPcbCircuitJsonBounds();return{left:x.bounds.left,right:x.bounds.right,top:x.bounds.top,bottom:x.bounds.bottom}}),a=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let p=0;p<e.length;p++)for(let x=p+1;x<e.length;x++){let f=e[p],m=e[x];a[p][x]=a[x][p]=!(f.right<m.left||f.left>m.right||f.bottom>m.top||f.top<m.bottom)}let s=new Set,l=p=>{s.add(p);for(let x=0;x<e.length;x++)a[p][x]&&!s.has(x)&&l(x)};return l(0),s.size===e.length},QSe=n=>{if(n.length===0)throw new Error("Cannot get center of empty PCB primitives array");let e=n.map(l=>l._getPcbCircuitJsonBounds().center).filter(Boolean),a=e.reduce((l,p)=>l+p.x,0),s=e.reduce((l,p)=>l+p.y,0);return{x:a/e.length,y:s/e.length}},wUt=C.object({name:C.string().optional(),pinNumber:C.number().optional(),aliases:C.array(C.string()).optional(),layer:C.string().optional(),layers:C.array(C.string()).optional()}),Ii=class extends ma{constructor(e,a={}){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);q(this,"source_port_id",null);q(this,"pcb_port_id",null);q(this,"schematic_port_id",null);q(this,"schematicSymbolPortDef",null);q(this,"matchedComponents");q(this,"facingDirection",null);q(this,"originDescription",null);a.originDescription&&(this.originDescription=a.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:wUt}}_getGlobalPcbPositionBeforeLayout(){let e=this.matchedComponents.find(s=>s.isPcbPrimitive),a=this.parent;if(a&&!a.props.footprint)throw new Error(`${a.componentName} "${a.props.name}" does not have a footprint. Add a footprint prop, e.g. <${a.componentName.toLowerCase()} footprint="..." />`);if(!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,a=e.pcb_port.get(this.pcb_port_id);return{center:{x:a.x,y:a.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let e=this.parent;if(!e||!e._getInternallyConnectedPins)return[];let a=e._getInternallyConnectedPins();for(let s of a)if(s.some(l=>l===this))return s;return[]}_hasSchematicPort(){if(this.parent?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(l=>l.schematicSymbolPortDef));let a=this?.parent?._getSchematicBoxDimensions();return!!(a&&this.props.pinNumber!==void 0&&a.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let e=this.parent?.getSchematicSymbol();if(e){let s=this.schematicSymbolPortDef;if(!s&&(s=this._getPortsInternallyConnectedToThisPort().find(p=>p.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!s))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let l=Ts(this.parent.computeSchematicGlobalTransform(),ka(-e.center.x,-e.center.y));return rs(l,s)}let a=this?.parent?._getSchematicBoxDimensions();if(a&&this.props.pinNumber!==void 0){let s=a.getPortPositionByPinNumber(this.props.pinNumber);if(!s)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return rs(this.parent.computeSchematicGlobalTransform(),s)}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 a=e.schematic_port.get(this.schematic_port_id);if(!a)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return a.center}registerMatch(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??[]]))}isMatchingPort(e){return this.isMatchingAnyOf(e.getNameAndAliases())}getPortSelector(){return`.${this.parent?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:e,layers:a}=this._parsedProps;return a||(e?[e]:Array.from(new Set(this.matchedComponents.flatMap(s=>s.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(s=>!s._couldNotFindPort).filter(s=>s._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getNameAndAliases(),l=e.source_port.insert({name:a.name,pin_number:a.pinNumber,port_hints:s,source_component_id:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=l.source_port_id}doInitialSourceParentAttachment(){let{db:e}=this.root;if(!this.parent?.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:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=this.parent?.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{matchedComponents:a}=this;if(!this.parent?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()})`);let s=a.filter(p=>p.isPcbPrimitive);if(s.length===0)return;let l=null;if(s.length===1&&(l=s[0]._getPcbCircuitJsonBounds().center),s.length>1){if(!ZSe(s))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${s.map(p=>p.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);l=QSe(s)}if(l){let p=this.getSubcircuit(),x=e.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...l,source_port_id:this.source_port_id});this.pcb_port_id=x.pcb_port_id}else{let p=s[0];throw new Error(`${p.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;let a=this.matchedComponents.filter(x=>x.isPcbPrimitive);if(a.length===0)return;let s=null;if(a.length===1&&(s=a[0]._getPcbCircuitJsonBounds().center),a.length>1)try{ZSe(a)&&(s=QSe(a))}catch{}if(!s)return;let l=this.getSubcircuit(),p=e.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...s,source_port_id:this.source_port_id});this.pcb_port_id=p.pcb_port_id}doInitialSchematicPortRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer();if(!s||!this._hasSchematicPort())return;let l=s._getGlobalSchematicPositionBeforeLayout(),p=this._getGlobalSchematicPositionBeforeLayout(),x=null,f=s._getSchematicBoxDimensions();f&&a.pinNumber!==void 0&&(x=f.getPortPositionByPinNumber(a.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&e.schematic_debug_object.insert({shape:"rect",center:p,size:{width:.1,height:.1},label:"obstacle"}),x?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[x.side]:this.facingDirection=BUt(l,p);let m=e.source_port.get(this.source_port_id),D=[];for(let P of m?.port_hints??[])P.match(/^(pin)?\d+$/)||P.match(/^(left|right)/)&&!m?.name.match(/^(left|right)/)||D.push(P);let b;this.parent?.props?.showPinAliases&&D.length>0?b=D.join("/"):D.length>0&&(b=D[0]);let A=this.parent?._parsedProps?.pinAttributes,B={type:"schematic_port",schematic_component_id:this.parent?.schematic_component_id,center:p,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:x?.side,pin_number:a.pinNumber,true_ccw_index:x?.trueIndex,display_pin_label:b,is_connected:!1};if(A){for(let P of this.getNameAndAliases())if(A[P]){let N=A[P];N.requiresPower&&(B.has_input_arrow=!0),N.providesPower&&(B.has_output_arrow=!0)}}let w=e.schematic_port.insert(B);this.schematic_port_id=w.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(e){let{db:a}=this.root;this.pcb_port_id&&a.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}`}},CBe=n=>{let e=n.find(a=>/^(pin)?\d+$/.test(a));return e?Number.parseInt(e.replace(/^pin/,"")):null};function IF(n,e){let a=CBe(n);if(!a)return null;let l=[...n.filter(p=>p.toString()!==a.toString()&&p!==`pin${a}`),...e?.additionalAliases?.[`pin${a}`]??[]];return new Ii({pinNumber:a,aliases:l})}var TUt=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},PUt=n=>{if(TUt(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:a=0,topSize:s=0,bottomSize:l=0}=n;return{leftSize:e,rightSize:a,topSize:s,bottomSize:l}};function _Be(n){let e=n;return e.leftSide!==void 0||e.rightSide!==void 0||e.topSide!==void 0||e.bottomSide!==void 0}var IUt=n=>{let e=n.portDistanceFromEdge??.4,a=n.schPortArrangement?PUt(n.schPortArrangement):null,s={left:0,right:0,top:0,bottom:0},l=n.pinCount??null;if(l===null)if(a)l=a.leftSize+a.rightSize+a.topSize;else throw new Error("Could not determine pin count for the schematic box");if(l&&!a){let w=Math.floor(l/2);a={leftSize:l-w,rightSize:w,topSize:0,bottomSize:0}}a||(a={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let p=({side:w,sideIndex:P,truePinIndex:N})=>{if(!n.schPortArrangement||!_Be(n.schPortArrangement))return N+1;let O={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[w],$=n.schPortArrangement?.[`${w}Side`]?.direction??O,ee=n.schPortArrangement?.[`${w}Side`]?.pins,X=P;return $!==O&&(X=ee.length-P-1),OF(ee[X],n.pinLabels)},x=[],f=0,m=0;for(let w=0;w<a.leftSize;w++){let P=p({side:"left",sideIndex:w,truePinIndex:m}),N=n.numericSchPinStyle?.[`pin${P}`]??n.numericSchPinStyle?.[P];N?.topMargin&&(f+=N.topMargin),x.push({trueIndex:m,pinNumber:P,side:"left",distanceFromOrthogonalEdge:f}),N?.bottomMargin&&(f+=N.bottomMargin),w===a.leftSize-1?s.left=f:f+=n.schPinSpacing,m++}f=0;for(let w=0;w<a.bottomSize;w++){let P=p({side:"bottom",sideIndex:w,truePinIndex:m}),N=n.numericSchPinStyle?.[`pin${P}`]??n.numericSchPinStyle?.[P];N?.leftMargin&&(f+=N.leftMargin),x.push({trueIndex:m,pinNumber:P,side:"bottom",distanceFromOrthogonalEdge:f}),N?.rightMargin&&(f+=N.rightMargin),w===a.bottomSize-1?s.bottom=f:f+=n.schPinSpacing,m++}f=0;for(let w=0;w<a.rightSize;w++){let P=p({side:"right",sideIndex:w,truePinIndex:m}),N=n.numericSchPinStyle?.[`pin${P}`]??n.numericSchPinStyle?.[P];N?.bottomMargin&&(f+=N.bottomMargin),x.push({trueIndex:m,pinNumber:P,side:"right",distanceFromOrthogonalEdge:f}),N?.topMargin&&(f+=N.topMargin),w===a.rightSize-1?s.right=f:f+=n.schPinSpacing,m++}f=0;for(let w=0;w<a.topSize;w++){let P=p({side:"top",sideIndex:w,truePinIndex:m}),N=n.numericSchPinStyle?.[`pin${P}`]??n.numericSchPinStyle?.[P];N?.rightMargin&&(f+=N.rightMargin),x.push({trueIndex:m,pinNumber:P,side:"top",distanceFromOrthogonalEdge:f}),N?.leftMargin&&(f+=N.leftMargin),w===a.topSize-1?s.top=f:f+=n.schPinSpacing,m++}let D=n.schWidth;if(D===void 0){D=Math.max(s.top+n.schPinSpacing*2,s.bottom+n.schPinSpacing*2);let w=n.pinLabels?Math.max(...Object.values(n.pinLabels).map(N=>N.length*.1)):0,P=w>0?1.1:0;D=Math.max(D,w+P)}let b=n.schHeight;b||(b=Math.max(s.left+n.schPinSpacing*2,s.right+n.schPinSpacing*2));let E={left:{x:-D/2-e,y:s.left/2},bottom:{x:-s.bottom/2,y:-b/2-e},right:{x:D/2+e,y:-s.right/2},top:{x:s.top/2,y:b/2+e}},A={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},B=x.map(w=>{let{distanceFromOrthogonalEdge:P,side:N}=w,O=E[N],$=A[N];return{x:O.x+P*$.x,y:O.y+P*$.y,...w}});return{getPortPositionByPinNumber(w){let P=B.find(N=>N.pinNumber.toString()===w.toString());return P||null},getSize(){return{width:D,height:b}},getSizeIncludingPins(){return{width:D+(a.leftSize||a.rightSize?.4:0),height:b+(a.topSize||a.bottomSize?.4:0)}},pinCount:l}},jUt=(0,ABe.default)("tscircuit:core:footprint"),RBe=class extends ma{get config(){return{componentName:"Footprint",zodProps:aAe}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let n=this.children.filter(E=>E.componentName==="Constraint");if(n.length===0)return;let{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),a=E=>e&&"left"in E&&"right"in E?{...E,left:E.right,right:E.left}:E,s=n.flatMap(E=>E._getAllReferencedComponents().componentsWithSelectors).map(({component:E,selector:A,componentSelector:B,edge:w})=>({component:E,selector:A,componentSelector:B,edge:w,bounds:E._getPcbCircuitJsonBounds()}));if(s.some(E=>E.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function l(E){return s.find(({selector:A})=>A===E)}let p=new o5,x={};function f(E){return E in x||(x[E]=new a1(E),p.addEditVariable(x[E],qs.weak)),x[E]}for(let{selector:E,bounds:A}of s){let B=f(`${E}_x`),w=f(`${E}_y`);p.suggestValue(B,A.center.x),p.suggestValue(w,A.center.y)}for(let E of n){let A=E._parsedProps;if("xDist"in A){let{xDist:B,left:w,right:P,edgeToEdge:N,centerToCenter:O}=a(A),$=f(`${w}_x`),ee=f(`${P}_x`),X=l(w)?.bounds,te=l(P)?.bounds;if(O){let L=new Is(ee,[-1,$]);p.addConstraint(new Zu(L,yo.Eq,A.xDist,qs.required))}else if(N){let L=new Is(ee,-te.width/2,[-1,$],-X.width/2);p.addConstraint(new Zu(L,yo.Eq,A.xDist,qs.required))}}else if("yDist"in A){let{yDist:B,top:w,bottom:P,edgeToEdge:N,centerToCenter:O}=A,$=f(`${w}_y`),ee=f(`${P}_y`),X=l(w)?.bounds,te=l(P)?.bounds;if(O){let L=new Is($,[-1,ee]);p.addConstraint(new Zu(L,yo.Eq,A.yDist,qs.required))}else if(N){let L=new Is($,X.height/2,[-1,ee],-te.height/2);p.addConstraint(new Zu(L,yo.Eq,A.yDist,qs.required))}}else if("sameY"in A){let{for:B}=A;if(B.length<2)continue;let w=B.map(N=>f(`${N}_y`)),P=new Is(...w.slice(1));p.addConstraint(new Zu(P,yo.Eq,w[0],qs.required))}else if("sameX"in A){let{for:B}=A;if(B.length<2)continue;let w=B.map(N=>f(`${N}_x`)),P=new Is(...w.slice(1));p.addConstraint(new Zu(P,yo.Eq,w[0],qs.required))}}p.updateVariables(),jUt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(x).map(([E,A])=>({var:E,val:A.value()}))));let m={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:E,bounds:{width:A,height:B}}of s){let w=f(`${E}_x`),P=f(`${E}_y`),N=w.value()-A/2,O=w.value()+A/2,$=P.value()+B/2,ee=P.value()-B/2;m.left=Math.min(m.left,N),m.right=Math.max(m.right,O),m.top=Math.max(m.top,$),m.bottom=Math.min(m.bottom,ee)}let D={x:-(m.right+m.left)/2,y:-(m.top+m.bottom)/2},b=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();D.x+=b.x,D.y+=b.y;for(let{component:E,selector:A}of s){let B=f(`${A}_x`),w=f(`${A}_y`);E._setPositionFromLayout({x:B.value()+D.x,y:w.value()+D.y})}}},kUt=(n,e)=>{if(!n)return;let a={};for(let[s,l]of Object.entries(n)){let p=OF(s,e),x={leftMargin:l.marginLeft??l.leftMargin,rightMargin:l.marginRight??l.rightMargin,topMargin:l.marginTop??l.topMargin,bottomMargin:l.marginBottom??l.bottomMargin};a[`pin${p}`]={...a[`pin${p}`],...x}}return a},eBe=class{constructor({input:n}){q(this,"input");this.input=n}solveAndMapToTraces(){let n=[];for(let e of this.input.connections){if(e.pointsToConnect.length!==2)continue;let[a,s]=e.pointsToConnect,l={type:"pcb_trace",pcb_trace_id:"",connection_name:e.name,route:[{route_type:"wire",x:a.x,y:a.y,layer:"top",width:.1},{route_type:"wire",x:s.x,y:s.y,layer:"top",width:.1}]};n.push(l)}return n}},NUt=n=>{let e=Math.min(...n.map(p=>p.center.x)),a=Math.max(...n.map(p=>p.center.x)),s=Math.min(...n.map(p=>p.center.y)),l=Math.max(...n.map(p=>p.center.y));return{minX:e,maxX:a,minY:s,maxY:l}},tBe=["top","bottom","inner1","inner2"],OS=(n,e=[])=>{let a=[];if(e.length===0){let f=n[0].layers;for(let m of f)a.push(...OS(n.slice(1),[m]));return a}if(n.length===0)return[];let s=n[0],l=s.via||s.optional_via,p=e[e.length-1];if(n.length===1){let f=s;return f.layers&&l?f.layers.map(m=>({layer_path:[...e,m]})):f.layers?.includes(p)?[{layer_path:[...e,p]}]:[]}if(!l)return s.layers&&!s.layers.includes(p)?[]:OS(n.slice(1),e.concat([p]));let x=(s.optional_via?tBe:tBe.filter(f=>f!==p)).filter(f=>!s.layers||s.layers?.includes(f));for(let f of x)a.push(...OS(n.slice(1),e.concat(f)));return a};function rBe(n){let e={x:n.to.x-n.from.x,y:n.to.y-n.from.y},a=Math.abs(e.x),s=Math.abs(e.y);return a>s?e.x>0?"right":"left":e.y>0?"down":"up"}function kg(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}var MUt=n=>{if(n.length===1)return n[0];if(n.some(m=>m.length===0))throw new Error("Cannot merge routes with zero length");let e=[],a=n[0][0],s=n[0][n[0].length-1],l=n[1][0],p=n[1][n[1].length-1],x=Math.min(kg(a,l),kg(a,p)),f=Math.min(kg(s,l),kg(s,p));x<f?e.push(...n[0].reverse()):e.push(...n[0]);for(let m=1;m<n.length;m++){let D=e[e.length-1],b=n[m],E=b[0],A=b[b.length-1],B=kg(D,E),w=kg(D,A);B<w?e.push(...b):e.push(...b.reverse())}for(let m=1;m<e.length-1;m++){let D=e[m-1],b=e[m];D.route_type==="wire"&&b.route_type==="wire"&&D.layer!==b.layer&&e.splice(m,0,{x:D.x,y:D.y,from_layer:D.layer,to_layer:b.layer,route_type:"via"})}return e},OUt=(n,e)=>{let a="_getGlobalPcbPositionBeforeLayout"in n?n._getGlobalPcbPositionBeforeLayout():n,s="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((a.x-s.x)**2+(a.y-s.y)**2)};function LUt(n,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let a=e[0],s=1/0;for(let l of e){let p=OUt(n,l);p<s&&(a=l,s=p)}return a}var $Ut=(n,e)=>{let a=0;a+=n.length??0,a+=e.filter(s=>s.is_crossing).length;for(let s=1;s<e.length;s++){let l=e[s-1],p=e[s],x=Math.abs(l.from.x-l.to.x)<.01,f=Math.abs(p.from.x-p.to.x)<.01;x!==f&&a++}return a},$F=n=>({up:"bottom",down:"top",left:"right",right:"left"})[n]??null,qW=({firstEdge:n,firstEdgePort:e,firstDominantDirection:a,lastEdge:s,lastEdgePort:l,lastDominantDirection:p})=>{if(n&&e)return qW({lastEdge:{from:n.to,to:n.from},lastEdgePort:e,lastDominantDirection:a}).reverse().map(f=>({from:f.to,to:f.from}));let x=[];if(s&&l){let f={x:s.to.x,y:s.to.y};p==="left"||p==="right"?(f.x=l.position.x,x.push({from:s.to,to:{...f}}),x.push({from:f,to:{...l.position}})):(f.y=l.position.y,x.push({from:s.to,to:{...f}}),x.push({from:f,to:{...l.position}}))}return x=x.filter(f=>Ri(f.from,f.to)>.01),x};function zUt(n){try{return[n(),null]}catch(e){return[null,e]}}var qUt=(n,{db:e})=>{let a=n.map(s=>{let l=e.source_port.get(s.source_port_id);if(!l?.source_component_id)return null;let p=e.source_component.get(l.source_component_id);return p?.ftype==="simple_capacitor"?p.max_decoupling_trace_length:null}).filter(s=>s!==null);if(a.length!==0)return Math.min(...a)};function UUt({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 VUt=(n,{db:e})=>{let a=e.pcb_board.list()[0];if(a.outline){let m=a.outline,D=(b,E)=>{let A=!1;for(let B=0,w=E.length-1;B<E.length;w=B++){let P=E[B].x,N=E[B].y,O=E[w].x,$=E[w].y;N>b.y!=$>b.y&&b.x<(O-P)*(b.y-N)/($-N)+P&&(A=!A)}return A};return n.some(b=>!D(b,m))}let s=a.width,l=a.height,p=a.center.x,x=a.center.y;return n.some(m=>m.x<p-s/2||m.y<x-l/2||m.x>p+s/2||m.y>x+l/2)},nBe=(n,e)=>Math.abs(n-e)<1e-4,GUt=(n,e,{viaDiameter:a=.5}={})=>{let s=[];for(let l=0;l<n.length-1;l++){let[p,x]=[n[l],n[l+1]],f=l-1>=0?n[l-1]:null,m=nBe(p.y,x.y),D=nBe(p.x,x.x);if(!m&&!D)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${p.x}, ${p.y}), end: (${x.x}, ${x.y})`);let b={type:"rect",layers:[p.layer],center:{x:(p.x+x.x)/2,y:(p.y+x.y)/2},width:m?Math.abs(p.x-x.x):.1,height:D?Math.abs(p.y-x.y):.1,connectedTo:[e]};if(s.push(b),f&&f.layer===p.layer&&p.layer!==x.layer){let E={type:"rect",layers:[p.layer,x.layer],center:{x:p.x,y:p.y},connectedTo:[e],width:a,height:a};s.push(E)}}return s};function XUt(n,e=4){let{center:a,width:s,height:l,rotation:p}=n,x=[],f=p*Math.PI/180,m=Math.cos(f),D=Math.sin(f),b=(p%360+360)%360;if(l<=s?b>=45&&b<135||b>=225&&b<315:b>=135&&b<225||b>=315||b<45){let A=s/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*m,N=-w*D,O=A*1.1,$=Math.abs(l*m)+Math.abs(A*D);x.push({center:{x:a.x+P,y:a.y+N},width:O,height:$})}}else{let A=l/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*D,N=w*m,O=Math.abs(s*m)+Math.abs(A*D),$=A*1.1;x.push({center:{x:a.x+P,y:a.y+N},width:O,height:$})}}return x}function YUt(n,e={}){if(n.length<3)return[];let{rectHeight:a=.1}=e,s=[],l=n.map(f=>f.y),p=Math.min(...l),x=Math.max(...l);for(let f=p;f<x;f+=a){let m=f+a/2,D=[];for(let b=0;b<n.length;b++){let E=n[b],A=n[(b+1)%n.length];if(E.y<=m&&A.y>m||A.y<=m&&E.y>m){let B=(m-E.y)*(A.x-E.x)/(A.y-E.y)+E.x;D.push(B)}}D.sort((b,E)=>b-E);for(let b=0;b<D.length;b+=2)if(b+1<D.length){let E=D[b],B=D[b+1]-E;B>1e-6&&s.push({center:{x:E+B/2,y:m},width:B,height:a})}}return s}function HUt(n,e={}){let{center:a,radius:s}=n,{rectHeight:l=.1}=e,p=[],x=Math.ceil(s*2/l);for(let f=0;f<x;f++){let m=a.y-s+(f+.5)*l,D=m-a.y,b=Math.sqrt(s*s-D*D);b>0&&p.push({center:{x:a.x,y:m},width:b*2,height:l})}return p}var Zp=["top","inner1","inner2","bottom"],SBe=(n,e)=>{let a=l=>e?l.concat(l.map(p=>e?.getNetConnectedToId(p)).filter(Boolean)):l,s=[];for(let l of n)if(l.type==="pcb_smtpad"){if(l.shape==="circle")s.push({type:"oval",layers:[l.layer],center:{x:l.x,y:l.y},width:l.radius*2,height:l.radius*2,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rect")s.push({type:"rect",layers:[l.layer],center:{x:l.x,y:l.y},width:l.width,height:l.height,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rotated_rect"){let p={center:{x:l.x,y:l.y},width:l.width,height:l.height,rotation:l.ccw_rotation},x=XUt(p);for(let f of x)s.push({type:"rect",layers:[l.layer],center:f.center,width:f.width,height:f.height,connectedTo:a([l.pcb_smtpad_id])})}}else if(l.type==="pcb_keepout")l.shape==="circle"?s.push({type:"oval",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.radius*2,height:l.radius*2,connectedTo:[]}):l.shape==="rect"&&s.push({type:"rect",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.type==="pcb_cutout"){if(l.shape==="rect")s.push({type:"rect",layers:Zp,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.shape==="circle"){let p=HUt({center:l.center,radius:l.radius},{rectHeight:.6});for(let x of p)s.push({type:"rect",layers:Zp,center:x.center,width:x.width,height:x.height,connectedTo:[]})}else if(l.shape==="polygon"){let p=YUt(l.points,{rectHeight:.6});for(let x of p)s.push({type:"rect",layers:Zp,center:x.center,width:x.width,height:x.height,connectedTo:[]})}}else if(l.type==="pcb_hole")l.hole_shape==="oval"?s.push({type:"oval",center:{x:l.x,y:l.y},width:l.hole_width,height:l.hole_height,connectedTo:[]}):l.hole_shape==="square"?s.push({type:"rect",layers:Zp,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]}):(l.hole_shape==="round"||l.hole_shape==="circle")&&s.push({type:"rect",layers:Zp,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]});else if(l.type==="pcb_plated_hole")l.shape==="circle"?s.push({type:"oval",layers:Zp,center:{x:l.x,y:l.y},width:l.outer_diameter,height:l.outer_diameter,connectedTo:a([l.pcb_plated_hole_id])}):l.shape==="circular_hole_with_rect_pad"?s.push({type:"rect",layers:Zp,center:{x:l.x,y:l.y},width:l.rect_pad_width,height:l.rect_pad_height,connectedTo:a([l.pcb_plated_hole_id])}):(l.shape==="oval"||l.shape==="pill")&&s.push({type:"oval",layers:Zp,center:{x:l.x,y:l.y},width:l.outer_width,height:l.outer_height,connectedTo:a([l.pcb_plated_hole_id])});else if(l.type==="pcb_trace"){let p=GUt(l.route.map(x=>({x:x.x,y:x.y,layer:"layer"in x?x.layer:x.from_layer})),l.source_trace_id);s.push(...p)}else l.type==="pcb_via"&&s.push({type:"rect",layers:l.layers,center:{x:l.x,y:l.y},connectedTo:[],width:l.outer_diameter,height:l.outer_diameter});return s},Qp=({anchor_position:n,anchor_side:e,text:a,font_size:s=.18})=>{let l=.1*(s/.18),p=a.length*l,x=s,f={...n};switch(e){case"right":f.x-=p/2;break;case"left":f.x+=p/2;break;case"top":f.y-=x/2;break;case"bottom":f.y+=x/2;break}return f},nK=({db:n,source_trace_id:e,sameNetOnly:a,differentNetOnly:s})=>{!a&&!s&&(s=!0);let l=n.source_trace.get(e),p=[];for(let x of n.schematic_trace.list()){if(x.source_trace_id===e)continue;let m=n.source_trace.get(x.source_trace_id)?.subcircuit_connectivity_map_key===l.subcircuit_connectivity_map_key;s&&m||a&&!m||p.push(x)}return p},WUt=({edges:n,otherEdges:e})=>{let a=[...n];for(let s=0;s<a.length;s++){if(s>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let l=a[s],p=Math.abs(l.from.x-l.to.x)<.01?"vertical":l.from.y===l.to.y?"horizontal":"not-orthogonal";if(p==="not-orthogonal")continue;let x=[];for(let P of e){let N=P.from.x===P.to.x?"vertical":P.from.y===P.to.y?"horizontal":"not-orthogonal";if(N==="not-orthogonal"||p===N)continue;if(Np([l.from,l.to],[P.from,P.to],{lineThickness:.01})){let $=p==="vertical"?l.from.x:P.from.x,ee=p==="vertical"?P.from.y:l.from.y,X={x:$,y:ee};x.push({otherEdge:P,crossingPoint:X,distanceFromEdgeFrom:Ri(l.from,X)})}}if(x.length===0)continue;let f=x[0];for(let P of x)P.distanceFromEdgeFrom<f.distanceFromEdgeFrom&&(f=P);let m=f.crossingPoint,D=.075;if(m.x===l.from.x&&m.y===l.from.y)continue;let b=p5(l.from,m),E={x:m.x-b.x*D/2,y:m.y-b.y*D/2},A={x:m.x+b.x*D/2,y:m.y+b.y*D/2},B=Ri(A,l.to)<D,w=[{from:l.from,to:E},{from:E,to:A,is_crossing:!0},{from:A,to:l.to}];a.splice(s,1,...w),s+=w.length-2,B&&s++}return a},UW=.001,Ng=(n,e)=>{let a=Math.min(e.from.x,e.to.x),s=Math.max(e.from.x,e.to.x),l=Math.min(e.from.y,e.to.y),p=Math.max(e.from.y,e.to.y);return n.x>=a&&n.x<=s&&n.y>=l&&n.y<=p},aBe=n=>{let e=Math.abs(n.from.x-n.to.x)<UW,a=Math.abs(n.from.y-n.to.y)<UW;return e?"vertical":a?"horizontal":"diagonal"},KUt=(n,e)=>{let a=aBe(n),s=aBe(e);if(a===s)return null;if(a==="vertical"&&s==="horizontal"||a==="horizontal"&&s==="vertical"){let E=a==="vertical"?n:e,A=a==="horizontal"?n:e,B=E.from.x,w=A.from.y,P={x:B,y:w};return Ng(P,n)&&Ng(P,e)?P:null}if(a==="vertical"||s==="vertical"){let E=a==="vertical"?n:e,A=a==="vertical"?e:n,B=E.from.x,w=(A.to.y-A.from.y)/(A.to.x-A.from.x),P=A.from.y-w*A.from.x,N=w*B+P,O={x:B,y:N};return Ng(O,n)&&Ng(O,e)?O:null}let l=(n.to.y-n.from.y)/(n.to.x-n.from.x),p=n.from.y-l*n.from.x,x=(e.to.y-e.from.y)/(e.to.x-e.from.x),f=e.from.y-x*e.from.x;if(Math.abs(l-x)<UW)return null;let m=(f-p)/(l-x),D=l*m+p,b={x:m,y:D};return Ng(b,n)&&Ng(b,e)?b:null},JUt=({edges:n,db:e,source_trace_id:a})=>{let s=nK({db:e,source_trace_id:a,sameNetOnly:!0}).flatMap(p=>p.edges),l=new Map;for(let p of n)for(let x of s){let f=KUt(p,x);if(f){let m=`${f.x.toFixed(6)},${f.y.toFixed(6)}`;l.has(m)||l.set(m,f)}}return Array.from(l.values())};function ZUt(n){let e=1/0,a=1/0,s=-1/0,l=-1/0;for(let p of n){let x,f,m,D;p.type==="schematic_component"?(x=p.center?.x,f=p.center?.y,m=p.size?.width,D=p.size?.height):p.type==="schematic_box"?(x=p.x,f=p.y,m=p.width,D=p.height):p.type==="schematic_port"?(x=p.center?.x,f=p.center?.y,m=.2,D=.2):p.type==="schematic_text"&&(x=p.position?.x,f=p.position?.y,m=(p.text?.length??0)*.1,D=.2),typeof x=="number"&&typeof f=="number"&&typeof m=="number"&&typeof D=="number"&&(e=Math.min(e,x-m/2),s=Math.max(s,x+m/2),a=Math.min(a,f-D/2),l=Math.max(l,f+D/2))}return{minX:e,maxX:s,minY:a,maxY:l}}function QUt(n,e={}){let{minX:a,maxX:s,minY:l,maxY:p}=n,x=e.padding??1;if(!isFinite(a)||!isFinite(s)||!isFinite(l)||!isFinite(p))return[];let f=a-x,m=s+x,D=p+x,b=l-x,E=.01;return[{type:"rect",layers:["top"],center:{x:(f+m)/2,y:D},width:m-f,height:E,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(f+m)/2,y:b},width:m-f,height:E,connectedTo:[]},{type:"rect",layers:["top"],center:{x:f,y:(D+b)/2},width:E,height:D-b,connectedTo:[]},{type:"rect",layers:["top"],center:{x:m,y:(D+b)/2},width:E,height:D-b,connectedTo:[]}]}var eVt=n=>{let e=n.root.db,a=n._findConnectedPorts().ports??[],s=new Set(a.map(x=>x.schematic_port_id)),l=[];for(let x of e.toArray()){if(x.type==="schematic_component"){let f=!!x.symbol_name,m=x.size.width>x.size.height?"horz":"vert";l.push({type:"rect",layers:["top"],center:x.center,width:x.size.width+(f&&m==="horz"?-.5:0),height:x.size.height+(f&&m==="vert"?-.5:0),connectedTo:[]})}if(x.type==="schematic_port"){if(s.has(x.schematic_port_id))continue;let f=x.facing_direction?x5(x.facing_direction):{x:0,y:0};l.push({type:"rect",layers:["top"],center:{x:x.center.x-f.x*.1,y:x.center.y-f.y*.1},width:.1+Math.abs(f.x)*.3,height:.1+Math.abs(f.y)*.3,connectedTo:[]})}x.type==="schematic_text"&&l.push({type:"rect",layers:["top"],center:x.position,width:(x.text?.length??0)*.1,height:.2,connectedTo:[]}),x.type==="schematic_box"&&l.push({type:"rect",layers:["top"],center:{x:x.x,y:x.y},width:x.width,height:x.height,connectedTo:[]})}let p=ZUt(e.toArray());return l.push(...QUt(p,{padding:1})),l},tVt=({edges:n,db:e,source_trace_id:a})=>{let s=e.source_trace.get(a),l=nK({db:e,source_trace_id:a,differentNetOnly:!0}).flatMap(x=>x.edges),p=x=>{let{from:f,to:m}=x;return f.x===m.x?"vertical":"horizontal"};for(let x of n){let f=p(x),m=()=>l.find(b=>p(b)===f&&Np([x.from,x.to],[b.from,b.to],{lineThickness:.05})),D=m();for(;D;)f==="horizontal"?(x.from.y+=.1,x.to.y+=.1):(x.from.x+=.1,x.to.x+=.1),D=m()}},VW=n=>{switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},rVt=YAe.version??"unknown",jF=class extends Error{constructor(n){super(`${n} (capacity-autorouter@${rVt})`),this.name="AutorouterError"}},US=class extends Error{constructor(n){super(n.message),this.errorData=n,this.name="TraceConnectionError"}},nVt=n=>{if(n.root?._featureMspSchematicTraceRouting||n._couldNotFindPort||n.root?.schematicDisabled)return;let{db:e}=n.root,{_parsedProps:a,parent:s}=n;if(!s)throw new Error("Trace has no parent");let l,p;try{let Ne=n._findConnectedPorts();l=Ne.allPortsFound,p=Ne.portsWithSelectors??[]}catch(Ne){if(Ne instanceof US){e.source_trace_not_connected_error.insert({...Ne.errorData,error_type:"source_trace_not_connected_error"});return}throw Ne}let{netsWithSelectors:x}=n._findConnectedNets();if(!l)return;let m=p.map(Ne=>Ne.port.schematic_port_id).sort().join(","),D=n.root?._getBoard();if(D?._connectedSchematicPortPairs&&D._connectedSchematicPortPairs.has(m))return;let b={name:n.source_trace_id,pointsToConnect:[]},E=eVt(n),A=p.filter(({port:Ne})=>Ne.schematic_port_id!==null).map(({port:Ne})=>({port:Ne,position:Ne._getGlobalSchematicPositionAfterLayout(),schematic_port_id:Ne.schematic_port_id??void 0,facingDirection:Ne.facingDirection}));if(A.length===1&&x.length===1){let Ne=x[0].net,{port:Ve,position:et}=A[0],ct=n.getSubcircuit().selectAll("netlabel").find(ot=>{let it=ot._parsedProps.connection??ot._parsedProps.connectsTo;return it?Array.isArray(it)?it.some(It=>n.getSubcircuit().selectOne(It,{port:!0})===Ve):n.getSubcircuit().selectOne(it,{port:!0})===Ve:!1});if(!ct){let ot=e.schematic_net_label.getWhere({source_trace_id:n.source_trace_id});ot&&(ct=ot)}if(ct){let ot="_getGlobalSchematicPositionBeforeLayout"in ct?ct._getGlobalSchematicPositionBeforeLayout():ct.anchor_position,it=[];et.x===ot.x||et.y===ot.y?it.push({from:et,to:ot}):(it.push({from:et,to:{x:ot.x,y:et.y}}),it.push({from:{x:ot.x,y:et.y},to:ot}));let qt=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:it,junctions:[],subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=qt.schematic_trace_id;return}if(n.props.schDisplayLabel){let ot=$F(Ve.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel,source_net_id:Ne.source_net_id,anchor_position:et,center:Qp({anchor_position:et,anchor_side:ot,text:n.props.schDisplayLabel}),anchor_side:ot});return}let Mt=$F(Ve.facingDirection)??"bottom",Dt=e.schematic_net_label.insert({text:Ne._parsedProps.name,source_net_id:Ne.source_net_id,anchor_position:et,center:Qp({anchor_position:et,anchor_side:Mt,text:Ne._parsedProps.name}),anchor_side:Mt});return}if(n.props.schDisplayLabel&&("from"in n.props&&"to"in n.props||"path"in n.props)){n._doInitialSchematicTraceRenderWithDisplayLabel();return}if(A.length<2)return;let P=(()=>{let Ne=[];for(let et=0;et<A.length-1;et++){let ct=A[et],Mt=A[et+1],Dt=sg({x:ct.position.x,y:ct.position.y,facingDirection:VW(ct.facingDirection)},{x:Mt.position.x,y:Mt.position.y,facingDirection:VW(Mt.facingDirection)});for(let ot=0;ot<Dt.length-1;ot++)Ne.push({from:Dt[ot],to:Dt[ot+1]})}let Ve=(et,ct)=>{let Mt=ct.width/2,Dt=ct.height/2,ot=ct.center.x-Mt,it=ct.center.x+Mt,qt=ct.center.y-Dt,It=ct.center.y+Dt,tr=Et=>Et.x>=ot&&Et.x<=it&&Et.y>=qt&&Et.y<=It;return tr(et.from)||tr(et.to)?!0:[[{x:ot,y:qt},{x:it,y:qt}],[{x:it,y:qt},{x:it,y:It}],[{x:it,y:It},{x:ot,y:It}],[{x:ot,y:It},{x:ot,y:qt}]].some(Et=>Np([et.from,et.to],Et,{lineThickness:0}))};for(let et of Ne)for(let ct of E)if(Ve(et,ct))return null;return Ne})();P&&P.length===0&&(P=null),b.pointsToConnect=A.map(({position:Ne})=>({...Ne,layer:"top"}));let N=NUt(E),O=2,$={minTraceWidth:.1,obstacles:E,connections:[b],bounds:{minX:N.minX-O,maxX:N.maxX+O,minY:N.minY-O,maxY:N.maxY+O},layerCount:1},ee=JR,X=!1;if(n.getSubcircuit().props._schDirectLineRoutingEnabled&&(ee=eBe,X=!0),!P){let Ve=new ee({input:$,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(Ve.length===0){if(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection()){n._doInitialSchematicTraceRenderWithDisplayLabel();return}Ve=new eBe({input:$}).solveAndMapToTraces(),X=!0}let[{route:et}]=Ve;P=[];for(let ct=0;ct<et.length-1;ct++)P.push({from:et[ct],to:et[ct+1]})}let te=n.source_trace_id,L=[];if(!X){tVt({edges:P,db:e,source_trace_id:te});let Ne=nK({db:e,source_trace_id:te,differentNetOnly:!0}).flatMap(Ve=>Ve.edges);P=WUt({edges:P,otherEdges:Ne}),L=JUt({edges:P,db:e,source_trace_id:n.source_trace_id})}if(!P||P.length===0)return;let K=P[P.length-1],U=A[A.length-1],J=rBe(K);P.push(...qW({lastEdge:K,lastEdgePort:U,lastDominantDirection:J}));let Q=P[0],de=A[0],ce=rBe(Q);if(P.unshift(...qW({firstEdge:Q,firstEdgePort:de,firstDominantDirection:ce})),!n.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(n.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&$Ut(L,P)>=5&&(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection())){n._doInitialSchematicTraceRenderWithDisplayLabel();return}let Te=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:P,junctions:L,subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=Te.schematic_trace_id;for(let{port:Ne}of p)Ne.schematic_port_id&&e.schematic_port.update(Ne.schematic_port_id,{is_connected:!0});D?._connectedSchematicPortPairs&&D._connectedSchematicPortPairs.add(m)};function BBe(n){let e=0;for(let a=0;a<n.length;a++){let s=n[a];if(s.route_type==="wire"){let l=n[a+1];if(l){let p=l.x-s.x,x=l.y-s.y;e+=Math.sqrt(p*p+x*x)}}else s.route_type==="via"&&(e+=1.6)}return e}var kS=n=>({...n._getGlobalPcbPositionAfterLayout(),layers:n.getAvailablePcbLayers()}),aVt=!1;function sVt(n){if(n.root?.pcbDisabled)return;let{db:e}=n.root,{_parsedProps:a,parent:s}=n,l=n.getSubcircuit();if(!s)throw new Error("Trace has no parent");if(l._parsedProps.routingDisabled)return;let p=l._parsedProps.pcbRouteCache?.pcbTraces;if(p){let J=e.pcb_trace.insert({route:p.flatMap(Q=>Q.route),source_trace_id:n.source_trace_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0});n.pcb_trace_id=J.pcb_trace_id;return}if(a.pcbPath&&a.pcbPath.length>0||!l._shouldUseTraceByTraceRouting())return;let{allPortsFound:x,ports:f}=n._findConnectedPorts(),m=[];if(!x)return;let D=[];for(let J of f)J._hasMatchedPcbPrimitive()||D.push(J);if(D.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: ${D.map(J=>J.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:D.map(J=>J.pcb_port_id).filter(Boolean)});return}let b=n._findConnectedNets().netsWithSelectors;if(f.length===0&&b.length===2){n.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(f.length===1&&b.length===1){let J=f[0],de=b[0].net.getAllConnectedPorts().filter(Te=>Te!==J);if(de.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let ce=LUt(J,de);m.push(ce),f.push(ce)}else if(f.length>1&&b.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 E=f.flatMap(J=>J.matchedComponents.filter(Q=>Q.componentName==="TraceHint")),A=(n._parsedProps.pcbRouteHints??[]).concat(E.flatMap(J=>J.getPcbRouteHints()));if(f.length>2){n.renderError(`Trace has more than two ports (${f.map(J=>J.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(n.getSubcircuit().selectAll("trace").filter(J=>J.renderPhaseStates.PcbTraceRender.initialized).some(J=>J._portsRoutedOnPcb.length===f.length&&J._portsRoutedOnPcb.every(Q=>f.includes(Q))))return;let P=[];A.length===0?P=[kS(f[0]),kS(f[1])]:P=[kS(f[0]),...A,kS(f[1])];let N=OS(P);if(aVt&&N.length===0){n.renderError(`Could not find a common layer (using hints) for trace ${n.getString()}`);return}let O=Ku(n.root.db.toArray()),[$,ee]=zUt(()=>SBe(n.root.db.toArray()));if(ee){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: ${ee.message}`,source_trace_id:n.source_trace_id,center:{x:0,y:0},pcb_port_ids:f.map(J=>J.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[]});return}for(let J of $)if(J.connectedTo.length>0){let de=O.getNetConnectedToId(J.connectedTo[0]);de&&J.connectedTo.push(de)}let X=[];if(N.length===0)X=P;else{let J=N[0].layer_path;X=P.map((Q,de)=>Q.via?{...Q,via_to_layer:J[de]}:{...Q,layers:[J[de]]})}X[0].pcb_port_id=f[0].pcb_port_id,X[X.length-1].pcb_port_id=f[1].pcb_port_id;let te=[];for(let[J,Q]of vBe(X)){let de="via_to_layer"in J?J.via_to_layer:null,ce=2,Te="layers"in J&&J.layers.length===1?J.layers[0]:de??"top",Ne="layers"in Q&&Q.layers.length===1?Q.layers[0]:de??"top",Ve="pcb_port_id"in J?J.pcb_port_id:null,et="pcb_port_id"in Q?Q.pcb_port_id:null,ct=n.getSubcircuit()._parsedProps.minTraceWidth??.16,Mt=new JR({OBSTACLE_MARGIN:ct*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Ve&&et),connMap:O,input:{obstacles:$,minTraceWidth:ct,connections:[{name:n.source_trace_id,pointsToConnect:[{...J,layer:Te,pcb_port_id:Ve},{...Q,layer:Ne,pcb_port_id:et}]}],layerCount:n.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(J.x,Q.x)-ce,maxX:Math.max(J.x,Q.x)+ce,minY:Math.min(J.y,Q.y)-ce,maxY:Math.max(J.y,Q.y)+ce}}}),Dt=null;try{Dt=Mt.solveAndMapToTraces()}catch(qt){n.renderError({type:"pcb_trace_error",pcb_trace_error_id:n.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${qt.message}`,source_trace_id:n.pcb_trace_id,center:{x:(J.x+Q.x)/2,y:(J.y+Q.y)/2},pcb_port_ids:f.map(It=>It.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:f.map(It=>It.pcb_component_id)})}if(!Dt)return;if(Dt.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:(J.x+Q.x)/2,y:(J.y+Q.y)/2},pcb_port_ids:f.map(qt=>qt.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:f.map(qt=>qt.pcb_component_id)});return}let[ot]=Dt;de&&(ot.route=ot.route.map(qt=>(qt.route_type==="wire"&&!qt.layer&&(qt.layer=de),qt))),Ve&&ot.route[0].route_type==="wire"&&(ot.route[0].start_pcb_port_id=Ve);let it=ot.route[ot.route.length-1];et&&it.route_type==="wire"&&(it.end_pcb_port_id=et),te.push(ot.route)}let L=MUt(te),K=BBe(L),U=e.pcb_trace.insert({route:L,source_trace_id:n.source_trace_id,subcircuit_id:n.getSubcircuit()?.subcircuit_id,trace_length:K});n._portsRoutedOnPcb=f,n.pcb_trace_id=U.pcb_trace_id;for(let J of L)J.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:U.pcb_trace_id,x:J.x,y:J.y,hole_diameter:.3,outer_diameter:.6,layers:[J.from_layer,J.to_layer],from_layer:J.from_layer,to_layer:J.to_layer});n._insertErrorIfTraceIsOutsideBoard(L,f)}function iVt(n){if(n.root?.pcbDisabled)return;let{db:e}=n.root,{_parsedProps:a}=n,s=n.getSubcircuit();if(!a.pcbPath||a.pcbPath.length===0)return;let{allPortsFound:l,ports:p,portsWithSelectors:x}=n._findConnectedPorts();if(!l)return;let f=[];for(let $ of p)$._hasMatchedPcbPrimitive()||f.push($);if(f.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: ${f.map($=>$.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:f.map($=>$.pcb_port_id).filter(Boolean)});return}let m;a.pcbPathRelativeTo&&(m=x.find($=>$.selector===a.pcbPathRelativeTo)?.port,m||(m=n.getSubcircuit().selectOne(a.pcbPathRelativeTo))),m||(m=p[0]);let D=p.find($=>$!==m)??p[1],b=m.getAvailablePcbLayers()[0]||"top",E=a.thickness??n.getSubcircuit()._parsedProps.minTraceWidth??.16,A=m._getGlobalPcbPositionAfterLayout(),B=D._getGlobalPcbPositionAfterLayout(),w=[];w.push({route_type:"wire",x:A.x,y:A.y,width:E,layer:b,start_pcb_port_id:m.pcb_port_id});let P=m?._computePcbGlobalTransformBeforeLayout?.()||_i();for(let $ of a.pcbPath){let ee=rs(P,{x:$.x,y:$.y});w.push({route_type:"wire",x:ee.x,y:ee.y,width:E,layer:b})}w.push({route_type:"wire",x:B.x,y:B.y,width:E,layer:b,end_pcb_port_id:D.pcb_port_id});let N=BBe(w),O=e.pcb_trace.insert({route:w,source_trace_id:n.source_trace_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,trace_length:N});n._portsRoutedOnPcb=p,n.pcb_trace_id=O.pcb_trace_id,n._insertErrorIfTraceIsOutsideBoard(w,p)}function oVt(n){if(n.root?.schematicDisabled)return;let{db:e}=n.root,{_parsedProps:a,parent:s}=n;if(!s)throw new Error("Trace has no parent");let{allPortsFound:l,portsWithSelectors:p}=n._findConnectedPorts();if(!l)return;let x=p.map(({port:X})=>({port:X,position:X._getGlobalSchematicPositionAfterLayout(),schematic_port_id:X.schematic_port_id,facingDirection:X.facingDirection}));if(x.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let f,m,D=x[0].position,b=x[0].port;if("path"in n.props){if(n.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[f,m]=n.props.path}else{if(!("from"in n.props&&"to"in n.props))throw new Error("Missing 'from' or 'to' properties in props.");f=n.props.from,m=n.props.to}if(!b.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${f}).`);let E=x[1].position,A=x[1].port;if(!A.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${m}).`);let B=e.schematic_net_label.list().find(X=>X.source_net_id===b.source_port_id),w=e.schematic_net_label.list().find(X=>X.source_net_id===A.source_port_id),[P,N]=p.map(({port:X})=>X),$=P.parent?.config.shouldRenderAsSchematicBox?`${P?.parent?.props.name}_${P?.props.name}`:`${N?.parent?.props.name}_${N?.props.name}`,ee=n.props.schDisplayLabel??$;if(B&&B.text!==ee&&(B.text=`${ee} / ${B.text}`),w&&w?.text!==ee&&(w.text=`${ee} / ${w.text}`),!w){let X=$F(A.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??$,source_net_id:A.source_port_id,anchor_position:E,center:Qp({anchor_position:E,anchor_side:X,text:n.props.schDisplayLabel??$}),anchor_side:X})}if(!B){let X=$F(b.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??$,source_net_id:b.source_port_id,anchor_position:D,center:Qp({anchor_position:D,anchor_side:X,text:n.props.schDisplayLabel??$}),anchor_side:X})}}function uVt(n){let{_parsedProps:e,parent:a}=n;if(!a)throw new Error("Trace has no parent");let l=n.getTracePortPathSelectors().map(p=>({selector:p,port:n.getSubcircuit().selectOne(p,{type:"port"})??null}));for(let{selector:p,port:x}of l)if(!x){let f,m,D=p.lastIndexOf(".");if(D!==-1&&D>p.lastIndexOf(" "))f=p.slice(0,D),m=p.slice(D+1);else{let X=p.match(/^(.*[ >])?([^ >]+)$/);f=X?.[1]?.trim()??"",m=X?.[2]??p}let b=f?n.getSubcircuit().selectOne(f):null;if(!b&&f&&!/[.#\[]/.test(f)&&(b=n.getSubcircuit().selectOne(`.${f}`)),!b){let X=f?`Could not find port for selector "${p}". Component "${f}" not found`:`Could not find port for selector "${p}"`,te=n.getSubcircuit(),L=te.getGroup();throw new US({error_type:"source_trace_not_connected_error",message:X,subcircuit_id:te.subcircuit_id??void 0,source_group_id:L?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[p]})}let E=b.children.filter(X=>X.componentName==="Port"),A=m.includes(".")?m.split(".").pop()??"":m,B=E.flatMap(X=>X.getNameAndAliases()),w=B.some(X=>!/^(pin\d+|\d+)$/.test(X)),P=Array.from(new Set(B)).join(", "),N;E.length===0?N="It has no ports":w?N=`It has [${P}]`:N=`It has ${E.length} pins and no pinLabels (consider adding pinLabels)`;let O=`Could not find port for selector "${p}". Component "${b.props.name??f}" found, but does not have pin "${A}". ${N}`,$=n.getSubcircuit(),ee=$.getGroup();throw new US({error_type:"source_trace_not_connected_error",message:O,subcircuit_id:$.subcircuit_id??void 0,source_group_id:ee?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[p]})}return l.some(p=>!p.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:l,ports:l.map(({port:p})=>p)}}var zc=class extends ma{constructor(e){super(e);q(this,"source_trace_id",null);q(this,"pcb_trace_id",null);q(this,"schematic_trace_id",null);q(this,"_portsRoutedOnPcb");q(this,"subcircuit_connectivity_map_key",null);q(this,"_traceConnectionHash",null);q(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}get config(){return{zodProps:nAe,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 uVt(this)}_resolveNet(e){let a=this.getSubcircuit().selectOne(e,{type:"net"});if(a)return a;let s=e.match(/^net\.(.+)$/),l=s?s[1]:null;return l&&this.root._getBoard().getDescendants().find(x=>x.componentName==="Net"&&x._parsedProps.name===l)||null}_findConnectedNets(){let e=this.getTracePathNetSelectors().map(s=>({selector:s,net:this._resolveNet(s)})),a=e.filter(s=>!s.net);return a.length>0&&this.renderError(`Could not find net for selector "${a[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(s=>s.net)}}_getAllTracesConnectedToSameNet(){let e=this.getSubcircuit().selectAll("trace"),a=this._findConnectedNets().nets,s=this._findConnectedPorts().ports??[];return e.filter(l=>{if(l===this)return!1;let p=l._findConnectedNets().nets,x=l._findConnectedPorts().ports??[];return p.some(f=>a.includes(f))||x.some(f=>s.includes(f))})}_isExplicitlyConnectedToPort(e){let{allPortsFound:a,portsWithSelectors:s}=this._findConnectedPorts();return a?s.map(p=>p.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){ZW(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();return!e||!a?null:[...a].sort((p,x)=>(p.pcb_port_id||"").localeCompare(x.pcb_port_id||"")).map(p=>p.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:e}=this.root,{_parsedProps:a,parent:s}=this;if(!s){this.renderError("Trace has no parent");return}let l,p;try{let E=this._findConnectedPorts();l=E.allPortsFound,p=E.portsWithSelectors??[]}catch(E){if(E instanceof US){e.source_trace_not_connected_error.insert({...E.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw E}if(!l)return;this._traceConnectionHash=this._computeTraceConnectionHash();let f=e.source_trace.list().find(E=>E.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&E.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(f){this.source_trace_id=f.source_trace_id;return}let m=this._findConnectedNets().nets,D=UUt({ports:p,nets:m}),b=e.source_trace.insert({connected_source_port_ids:p.map(E=>E.port.source_port_id),connected_source_net_ids:m.map(E=>E.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:qUt(p.map(E=>E.port),{db:e})??a.maxLength,display_name:D,min_trace_thickness:a.thickness});this.source_trace_id=b.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,a){let{db:s}=this.root;VUt(e,{db:s})&&s.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:a.map(p=>p.pcb_port_id)})}doInitialPcbManualTraceRender(){iVt(this)}doInitialPcbTraceRender(){sVt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){oVt(this)}_isSymbolToChipConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let p=s.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return p&&!x||!p&&x}_isSymbolToSymbolConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let p=!s.parent.config.shouldRenderAsSchematicBox,x=!l.parent.config.shouldRenderAsSchematicBox;return p&&x}_isChipToChipConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let p=s.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return p&&x}doInitialSchematicTraceRender(){nVt(this)}},cVt=n=>{let{db:e}=n.root;if(n.pcb_component_id){let a=e.pcb_component.get(n.pcb_component_id);return a?{width:a.width,height:a.height}:null}if(n.pcb_group_id){let a=e.pcb_group.get(n.pcb_group_id);return a?{width:a.width,height:a.height}:null}return null},lVt=(n,e)=>{let{db:a}=n.root,s=a.toArray();if(n.pcb_component_id){h5(s,n.pcb_component_id,e);return}if(n.source_group_id){m5(s,n.source_group_id,e);return}throw new Error(`Cannot reposition component ${n.getString()}: no pcb_component_id or source_group_id`)},dVt=n=>{let{db:e}=n.root;if(!n.source_component_id)return;let a=n.selectAll("port"),s=e.source_trace.list(),l=new Set;for(let x of s)for(let f of x.connected_source_port_ids)l.add(f);let p=n._getInternallyConnectedPins();for(let x of p)if(x.some(f=>f.source_port_id&&l.has(f.source_port_id)))for(let f of x)f.source_port_id&&l.add(f.source_port_id);for(let x of a)x.source_port_id&&pVt(n,x)&&(l.has(x.source_port_id)||e.source_pin_missing_trace_warning.insert({message:`Port ${x.getNameAndAliases()[0]} on ${n.props.name} is missing a trace`,source_component_id:n.source_component_id,source_port_id:x.source_port_id,subcircuit_id:n.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},pVt=(n,e)=>{if(n.config.componentName==="Chip"){let a=n.props.pinAttributes;if(!a)return!1;for(let s of e.getNameAndAliases()){let l=a[s];if(l?.requiresPower||l?.requiresGround||l?.requiresVoltage!==void 0)return!0}return!1}return!0};function xVt(n){let e=n.font_size,a=n.text.length*e*.6,s=e,l=n.anchor_alignment||"center",p=n.anchor_position.x,x=n.anchor_position.y;switch(l){case"top_left":p=n.anchor_position.x+a/2,x=n.anchor_position.y+s/2;break;case"top_center":p=n.anchor_position.x,x=n.anchor_position.y+s/2;break;case"top_right":p=n.anchor_position.x-a/2,x=n.anchor_position.y+s/2;break;case"center_left":p=n.anchor_position.x+a/2,x=n.anchor_position.y;break;case"center":p=n.anchor_position.x,x=n.anchor_position.y;break;case"center_right":p=n.anchor_position.x-a/2,x=n.anchor_position.y;break;case"bottom_left":p=n.anchor_position.x+a/2,x=n.anchor_position.y-s/2;break;case"bottom_center":p=n.anchor_position.x,x=n.anchor_position.y-s/2;break;case"bottom_right":p=n.anchor_position.x-a/2,x=n.anchor_position.y-s/2;break;default:p=n.anchor_position.x,x=n.anchor_position.y;break}return{x:p-a/2,y:x-s/2,width:a,height:s}}function fVt(n){if(!n._adjustSilkscreenTextAutomatically||n.root?.pcbDisabled||!n.pcb_component_id)return;let{db:e}=n.root,s=n._getPcbCircuitJsonBounds().center,l=e.pcb_silkscreen_text.list({pcb_component_id:n.pcb_component_id}).filter(m=>m.text===n.name);if(l.length===0)return;let f=n.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(m=>m!==n&&m.pcb_component_id).map(m=>{let D=m._getPcbCircuitJsonBounds(),b={center:D.center,width:D.width,height:D.height};return Ql(b)});for(let m of l){let D=m.anchor_position,b=xVt(m),E={center:{x:b.x+b.width/2,y:b.y+b.height/2},width:b.width,height:b.height},A=Ql(E);if(!f.some(ee=>Ob(A,ee)))continue;let w=2*s.x-D.x,P=2*s.y-D.y,N={center:{x:w,y:P},width:b.width,height:b.height},O=Ql(N);f.some(ee=>Ob(O,ee))||e.pcb_silkscreen_text.update(m.pcb_silkscreen_text_id,{anchor_position:{x:w,y:P}})}}function hVt(n){if(!n)return{validPinLabels:n,invalidPinLabelsMessages:[]};let e={},a=[];for(let[s,l]of Object.entries(n)){let p=Array.isArray(l)?l.slice():[l],x=[];for(let f of p)mVt(s,f)?x.push(f):a.push(`Invalid pin label: ${s} = '${f}' - excluding from component. Please use a valid pin label.`);x.length>0&&(e[s]=Array.isArray(l)?x:x[0])}return{validPinLabels:Object.keys(e).length>0?e:void 0,invalidPinLabelsMessages:a}}function mVt(n,e){try{let a={name:"test",footprint:"test",pinLabels:{[n]:e}};return rg.safeParse(a).success}catch{return!1}}var VS=n=>n.startsWith("http://")||n.startsWith("https://"),XW=n=>{if(VS(n))return null;let e=n.indexOf(":");if(e<=0)return null;let a=n.slice(0,e),s=n.slice(e+1);return!a||!s?null:{footprintLib:a,footprintName:s}};function gVt(n,e){let{footprint:a}=n.props;if(a??(a=n._getImpliedFootprintString?.()),!a)return;let{pcbRotation:s,pinLabels:l,pcbPinLabels:p}=n.props;if(typeof a=="string"&&VS(a)){if(n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let x=a;e("load-footprint-url",async()=>{let m=await(await fetch(x)).json(),D=zW({componentName:n.name,componentRotation:s,footprint:x,pinLabels:l,pcbPinLabels:p},m);n.addAll(D),n._markDirty("InitializePortsFromChildren")});return}if(typeof a=="string"){let x=XW(a);if(!x||n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let m=n.root?.platform?.footprintLibraryMap?.[x.footprintLib],D;if(typeof m=="function"&&(D=m),!D)return;e("load-lib-footprint",async()=>{let b=await D(x.footprintName),E=Array.isArray(b)?b:Array.isArray(b?.footprintCircuitJson)?b.footprintCircuitJson:null;if(!E)return;let A=zW({componentName:n.name,componentRotation:s,footprint:a,pinLabels:l,pcbPinLabels:p},E);n.addAll(A);for(let B of n.children)B.componentName==="Port"&&B._markDirty?.("PcbPortRender");n._markDirty("InitializePortsFromChildren")});return}if((0,GW.isValidElement)(a)){if(n.reactSubtrees.some(f=>f.element===a))return;let x=n._renderReactSubtree(a);n.reactSubtrees.push(x),n.add(x.component);return}!(0,GW.isValidElement)(a)&&a.componentName==="Footprint"&&n.add(a)}var DVt=(0,DBe.default)("tscircuit:core"),yVt=C.object({x:Ba,y:Ba,z:Ba}),Za=class extends ma{constructor(e){let a={...e},s=[];if(a.pinLabels&&!Array.isArray(a.pinLabels)){let{validPinLabels:l,invalidPinLabelsMessages:p}=hVt(a.pinLabels);a.pinLabels=l,s=p}super(a);q(this,"reactSubtrees",[]);q(this,"_impliedFootprint");q(this,"isPrimitiveContainer",!0);q(this,"_isNormalComponent",!0);q(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});q(this,"_asyncSupplierPartNumbers");q(this,"pcb_missing_footprint_error_id");q(this,"_hasStartedFootprintUrlLoad",!1);q(this,"_invalidPinLabelMessages",[]);q(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=s,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(a=>a.map(s=>typeof s=="number"?`pin${s}`:s))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let e=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(l=>l!==this&&l._isNormalComponent&&l.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let l=this._getGlobalPcbPositionBeforeLayout(),p=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:l,schematic_center:p}),this.shouldBeRemoved=!0;let x=[...this.children];for(let f of x)this.remove(f)}}initPorts(e={}){if(this.root?.schematicDisabled)return;let{config:a}=this,s=[],l=this._getSchematicPortArrangement();if(l&&!this._parsedProps.pinLabels){for(let D in l){let b=l[D].pins;if(Array.isArray(b))for(let E of b){let A=OF(E,this._parsedProps.pinLabels);s.push(new Ii({pinNumber:A,aliases:e.additionalAliases?.[`pin${A}`]??[]},{originDescription:`schPortArrangement:${D}`}))}}let f=["left","right","top","bottom"],m=1;for(let D of f){let b=l[`${D}Size`];for(let E=0;E<b;E++)s.push(new Ii({pinNumber:m++,aliases:e.additionalAliases?.[`pin${m}`]??[]},{originDescription:`schPortArrangement:${D}`}))}}let p=this._parsedProps.pinLabels;if(p)for(let[f,m]of Object.entries(p)){f=f.replace("pin","");let D=s.find(A=>A._parsedProps.pinNumber===Number(f)),b=Array.isArray(m)?m[0]:m,E=Array.isArray(m)?m.slice(1):[];D?(D.externallyAddedAliases.push(b,...E),D.props.name=b):(D=new Ii({pinNumber:parseInt(f),name:b,aliases:[...E,...e.additionalAliases?.[`pin${parseInt(f)}`]??[]]},{originDescription:`pinLabels:pin${f}`}),s.push(D))}if(a.schematicSymbolName&&!e.ignoreSymbolPorts){let f=Ps[this._getSchematicSymbolNameOrThrow()];if(!f)return;for(let m of f.ports){let D=CBe(m.labels);if(!D)continue;let b=s.find(E=>E._parsedProps.pinNumber===Number(D));if(b)b.schematicSymbolPortDef=m;else{let E=IF(m.labels.concat(e.additionalAliases?.[`pin${D}`]??[]));E&&(E.originDescription=`schematicSymbol:labels[0]:${m.labels[0]}`,E.schematicSymbolPortDef=m,s.push(E))}}this.addAll(s)}if(!this._getSchematicPortArrangement()){let f=this.getPortsFromFootprint(e);for(let m of f)s.some(D=>D.isMatchingAnyOf(m.getNameAndAliases()))||s.push(m)}let x=e.pinCount??this._getPinCount()??0;for(let f=1;f<=x;f++){if(s.find(D=>D._parsedProps.pinNumber===f))continue;if(!l){s.push(new Ii({pinNumber:f,aliases:e.additionalAliases?.[`pin${f}`]??[]}));continue}let m=[...l.leftSide?.pins??[],...l.rightSide?.pins??[],...l.topSide?.pins??[],...l.bottomSide?.pins??[]].map(D=>OF(D,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(D=>D in l)&&(m=Array.from({length:this._getPinCount()},(D,b)=>b+1)),m.includes(f)&&s.push(new Ii({pinNumber:f,aliases:e.additionalAliases?.[`pin${f}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${f}`}))}s.length>0&&this.addAll(s)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:e,pinLabels:a,pcbPinLabels:s}=this.props,{footprint:l}=this.props;if(l??(l=this._getImpliedFootprintString?.()),!!l&&typeof l=="string"){if(VS(l)||XW(l))return;let p=Mq.string(l).soup(),x=zW({componentName:this.name??this.componentName,componentRotation:e,footprint:l,pinLabels:a,pcbPinLabels:s},p);this.addAll(x)}}get portMap(){return new Proxy({},{get:(e,a)=>{let s=this.children.find(l=>l.componentName==="Port"&&l.isMatchingNameOrAlias(a));if(!s)throw new Error(`There was an issue finding the port "${a.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return s}})}getInstanceForReactElement(e){for(let a of this.reactSubtrees)if(a.element===e)return a.component;return null}doInitialSourceRender(){let e=this.config.sourceFtype;if(!e)return;let{db:a}=this.root,{_parsedProps:s}=this,l=a.source_component.insert({ftype:e,name:this.name,manufacturer_part_number:s.manufacturerPartNumber??s.mfn,supplier_part_numbers:s.supplierPartNumbers});this.source_component_id=l.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let l of this._invalidPinLabelMessages){let p="pinLabels",x=l.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);x&&(p=`pinLabels['${x[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:p,message:l,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:a}=this.config;a?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let s=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&s){if(!this.schematic_component_id)return;let l=NA.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(l)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let e=[];for(let a of this.internallyConnectedPinNames){let s=[];for(let l of a)s.push(this.portMap[l]);e.push(s)}return e}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getSchematicSymbolNameOrThrow(),l=Ps[s],p=this._getGlobalSchematicPositionBeforeLayout();if(l){let x=e.schematic_component.insert({center:p,size:l.size,source_component_id:this.source_component_id,symbol_name:s,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=x.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getSchematicBoxDimensions(),l={};if(Array.isArray(a.pinLabels))a.pinLabels.forEach((B,w)=>{l[String(w+1)]=B});else for(let[B,w]of Object.entries(a.pinLabels??{}))l[B]=Array.isArray(w)?w[0]:w;let p=this._getGlobalSchematicPositionBeforeLayout(),x=this._getSchematicPortArrangement(),f=e.schematic_component.insert({center:p,rotation:a.schRotation??0,size:s.getSize(),port_arrangement:CUt(x),pin_spacing:a.schPinSpacing??.2,pin_styles:vUt(a.schPinStyle,a.pinLabels),port_labels:l,source_component_id:this.source_component_id}),m=x?.topSide!==void 0||x?.bottomSide!==void 0,D=s?.getSize().width,b=s?.getSize().height,E=e.schematic_text.insert({text:a.manufacturerPartNumber??"",schematic_component_id:f.schematic_component_id,anchor:"left",rotation:0,position:{x:m?p.x+(D??0)/2+.1:p.x-(D??0)/2,y:m?p.y+(b??0)/2+.35:p.y-(b??0)/2-.13},color:"#006464",font_size:.18}),A=e.schematic_text.insert({text:a.name??"",schematic_component_id:f.schematic_component_id,anchor:"left",rotation:0,position:{x:m?p.x+(D??0)/2+.1:p.x-(D??0)/2,y:m?p.y+(b??0)/2+.55:p.y+(b??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=f.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:s.subcircuit_id??void 0});if(!(a.footprint??this._getImpliedFootprintString())&&!this.isGroup){let f=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=f.pcb_missing_footprint_error_id}this.pcb_component_id=l.pcb_component_id;let x=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&x){let f=OA.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:s.subcircuit_id??void 0});e.pcb_manual_edit_conflict_warning.insert(f)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:e}=this.root,{_parsedProps:a}=this,s=rK(this.children);if(s.width===0||s.height===0)return;let l={x:(s.minX+s.maxX)/2,y:(s.minY+s.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:l,width:s.width,height:s.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}_renderReactSubtree(e){return{element:e,component:EBe(e)}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){}doInitialPcbFootprintStringRender(){gVt(this,(e,a)=>this._queueAsyncEffect(e,a))}_hasExistingPortExactly(e){return this.children.filter(s=>s.componentName==="Port").some(s=>{let l=e.getNameAndAliases(),p=s.getNameAndAliases();return l.length===p.length&&l.every(x=>p.includes(x))})}add(e){let a;if((0,LF.isValidElement)(e)){let s=this._renderReactSubtree(e);this.reactSubtrees.push(s),a=s.component}else a=e;if(a.componentName==="Port"){if(this._hasExistingPortExactly(a))return;let l=this.children.filter(p=>p.componentName==="Port").find(p=>p.isMatchingAnyOf(a.getNameAndAliases()));l&&DVt(`Similar ports added. Port 1: ${l}, Port 2: ${a}`)}super.add(a)}getPortsFromFootprint(e){let{footprint:a}=this.props;if((!a||(0,LF.isValidElement)(a))&&(a=this.children.find(l=>l.componentName==="Footprint")),typeof a=="string"){if(VS(a))return[];if(XW(a))return[];let l=Mq.string(a).soup(),p=[];for(let x of l)if("port_hints"in x&&x.port_hints){let f=IF(x.port_hints,e);if(!f)continue;f.originDescription=`footprint:string:${a}:port_hints[0]:${x.port_hints[0]}`,p.push(f)}return p}if(!(0,LF.isValidElement)(a)&&a&&a.componentName==="Footprint"){let l=a,p=1,x=[];for(let f of l.children){if(!f.props.portHints)continue;let m=f.props.portHints;m.some(E=>E.startsWith("pin"))||(m=[...m,`pin${p}`]),p++;let b=IF(m);b&&(b.originDescription=`footprint:${a}`,x.push(b))}return x}let s=[];if(!a){for(let l of this.children)if(l.props.portHints&&l.isPcbPrimitive){let p=IF(l.props.portHints);p&&s.push(p)}}return s}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:e}=this;if(!e.schematicSymbolName)return[];let a=Ps[e.schematicSymbolName];if(!a)return[];let s=[];for(let l of a.ports){let p=IF(l.labels);p&&(p.schematicSymbolPortDef=l,s.push(p))}return s}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:e}=this,a=[];if(e.connections)for(let[s,l]of Object.entries(e.connections)){let p=Array.isArray(l)?l:[l];for(let x of p)a.push(x)}return a}_createNetsFromProps(e){ZW(this,e)}_getPcbCircuitJsonBounds(){let{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let a=e.pcb_component.get(this.pcb_component_id);return{center:{x:a.center.x,y:a.center.y},bounds:{left:a.center.x-a.width/2,top:a.center.y-a.height/2,right:a.center.x+a.width/2,bottom:a.center.y+a.height/2},width:a.width,height:a.height}}_getPinCountFromSchematicPortArrangement(){let e=this._getSchematicPortArrangement();if(!e)return 0;if(!_Be(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);let{leftSide:s,rightSide:l,topSide:p,bottomSide:x}=e;return Math.max(...s?.pins??[],...l?.pins??[],...p?.pins??[],...x?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let a=this.getPortsFromFootprint();if(a.length>0)return a.length;let{pinLabels:s}=this._parsedProps;if(s){if(Array.isArray(s))return s.length;let l=Object.keys(s).map(p=>p.startsWith("pin")?parseInt(p.slice(3)):parseInt(p)).filter(p=>!Number.isNaN(p));return l.length>0?Math.max(...l):Object.keys(s).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this,a=this._getPinCount(),s=e.schPinSpacing??.2;return IUt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:s,numericSchPinStyle:kUt(e.schPinStyle,e.pinLabels),pinCount:a,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:e.pinLabels})}doInitialCadModelRender(){let{db:e}=this.root,{boardThickness:a=0}=this.root?._getBoard()??{},s=this._parsedProps.cadModel,l=this.props.footprint??this._getImpliedFootprintString();if(!this.pcb_component_id||!s&&!l||s===null)return;let p=this._getPcbCircuitJsonBounds(),x=e.pcb_component.get(this.pcb_component_id);if(typeof s=="string")throw new Error("String cadModel not yet implemented");let f=yVt.parse({x:0,y:0,z:typeof s?.rotationOffset=="number"?s.rotationOffset:0,...typeof s?.rotationOffset=="object"?s.rotationOffset??{}:{}}),m=Lf.parse({x:0,y:0,z:0,...typeof s?.positionOffset=="object"?s.positionOffset:{}}),D=this.props.layer==="bottom"?"bottom":"top",b=e.cad_component.insert({position:{x:p.center.x+m.x,y:p.center.y+m.y,z:(D==="bottom"?-a/2:a/2)+m.z},rotation:{x:f.x,y:(D==="top"?0:180)+f.y,z:D==="bottom"?-((x?.rotation??0)+f.z)+180:(x?.rotation??0)+f.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(s??{})?this._addCachebustToModelUrl(s.stlUrl):void 0,model_obj_url:"objUrl"in(s??{})?this._addCachebustToModelUrl(s.objUrl):void 0,model_gltf_url:"gltfUrl"in(s??{})?this._addCachebustToModelUrl(s.gltfUrl):void 0,model_jscad:"jscad"in(s??{})?s.jscad:void 0,footprinter_string:typeof l=="string"&&!s?l:void 0})}_addCachebustToModelUrl(e){if(!e||!e.includes("modelcdn.tscircuit.com"))return e;let a=this.root?.getClientOrigin()??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(a)}`}_getPartsEngineCacheKey(e,a){return JSON.stringify({ftype:e.ftype,name:e.name,manufacturer_part_number:e.manufacturer_part_number,footprinterString:a})}async _getSupplierPartNumbers(e,a,s){if(this.props.doNotPlace)return{};let l=this.root?.platform?.localCacheEngine,p=this._getPartsEngineCacheKey(a,s);if(l){let m=await l.getItem(p);if(m)try{return JSON.parse(m)}catch{}}let x=await Promise.resolve(e.findPart({sourceComponent:a,footprinterString:s})),f=x==="Not found"?{}:x;if(l)try{await l.setItem(p,JSON.stringify(f))}catch{}return f}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let e=this.getInheritedProperty("partsEngine");if(!e)return;let{db:a}=this.root,s=a.source_component.get(this.source_component_id);if(!s||s.supplier_part_numbers)return;let l;this.props.footprint&&typeof this.props.footprint=="string"&&(l=this.props.footprint);let p=this._getSupplierPartNumbers(e,s,l);if(!(p instanceof Promise)){a.source_component.update(this.source_component_id,{supplier_part_numbers:p});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await p,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:e}=this.root,a=e.source_component.get(this.source_component_id);if(a&&!a.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[a,s]of Object.entries(e.connections)){let l=Array.isArray(s)?s:[s];for(let p of l)this.add(new zc({from:`${this.getSubcircuitSelector()} > port.${a}`,to:p}))}}doInitialSourceDesignRuleChecks(){dVt(this)}_getMinimumFlexContainerSize(){return cVt(this)}_repositionOnPcb(e){return lVt(this,e)}doInitialSilkscreenOverlapAdjustment(){return fVt(this)}},bVt=class{constructor(n,e={}){q(this,"input");q(this,"isRouting",!1);q(this,"solver");q(this,"eventHandlers",{complete:[],error:[],progress:[]});q(this,"cycleCount",0);q(this,"stepDelay");q(this,"timeoutId");this.input=n;let{capacityDepth:a,targetMinCapacity:s,stepDelay:l=0}=e;this.solver=new r6e(n,{capacityDepth:a,targetMinCapacity:s,cacheProvider:null}),this.stepDelay=l}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new jF(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 a=(this.solver.iterations-e)/(Date.now()-n)*1e3;this.cycleCount++;let s=this.solver?.preview()||void 0,l=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:a,progress:l,phase:this.solver.getCurrentPhase(),debugGraphics:s}),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 jF(n.message):new jF(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 jF(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},aK=class extends ma{constructor(){super(...arguments);q(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:jAe}}doInitialPortMatching(){let{db:e}=this.root,{_parsedProps:a,parent:s}=this;if(!s)return;if(s.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!s)throw new Error("TraceHint has no parent");if(!a.for){this.renderError(`TraceHint has no for property (${this})`);return}let l=s.selectOne(a.for,{type:"port"});l||this.renderError(`${this} could not find port for selector "${a.for}"`),this.matchedPort=l,l.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:e}=this,a=e.offset?[e.offset]:e.offsets;if(!a)return[];let s=this._computePcbGlobalTransformBeforeLayout();return a.map(l=>({...rs(s,l),via:l.via,to_layer:l.to_layer,trace_width:l.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=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()})}},wBe=({circuitJson:n,editEvents:e,manualEditsFile:a})=>{let s={...a,pcb_placements:[...a.pcb_placements??[]]};for(let l of e)if(l.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:p,new_center:x}=l,f=ia(n).pcb_component.get(p);if(!f)continue;let m=ia(n).source_component.get(f.source_component_id);if(!m)continue;let D=s.pcb_placements?.findIndex(E=>E.selector===m.name),b={selector:m.name,center:x,relative_to:"group_center"};D>=0?s.pcb_placements[D]=b:s.pcb_placements.push(b)}return s},TBe=({circuitJson:n,editEvents:e,manualEditsFile:a})=>{let s={...a,schematic_placements:[...a.schematic_placements??[]]};for(let l of e)if(l.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:p,new_center:x}=l,f=ia(n).schematic_component.get(p);if(!f)continue;let m=ia(n).source_component.get(f.source_component_id);if(!m)continue;let D=s.schematic_placements?.findIndex(E=>E.selector===m.name),b={selector:m.name,center:x,relative_to:"group_center"};D>=0?s.schematic_placements[D]=b:s.schematic_placements.push(b)}return s},FVt=({circuitJson:n,editEvents:e,manualEditsFile:a})=>{let s=e.filter(x=>x.edit_event_type==="edit_schematic_component_location"),l=e.filter(x=>x.edit_event_type==="edit_pcb_component_location"),p=a;return s.length>0&&(p=TBe({circuitJson:n,editEvents:s,manualEditsFile:p})),l.length>0&&(p=wBe({circuitJson:n,editEvents:l,manualEditsFile:p})),p},EVt=(n,e)=>{if(ia(n).pcb_trace_hint.get(e.pcb_trace_hint_id))n=n.map(s=>s.pcb_trace_hint_id===e.pcb_trace_hint_id?{...s,route:e.route}:s);else{let s=ia(n).pcb_port.get(e.pcb_port_id);n=n.filter(l=>!(l.type==="pcb_trace_hint"&&l.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:s?.pcb_component_id}])}return n},vVt=({circuitJson:n,editEvents:e})=>{n=JSON.parse(JSON.stringify(n));for(let a of e)if(a.edit_event_type==="edit_pcb_component_location"){let s=n.find(p=>p.type==="pcb_component"&&p.pcb_component_id===a.pcb_component_id);if((!s||s.center.x!==a.new_center.x||s.center.y!==a.new_center.y)&&a.original_center){let p=ka(a.new_center.x-a.original_center.x,a.new_center.y-a.original_center.y);n=n.map(x=>x.pcb_component_id!==a.pcb_component_id?x:RY(x,p))}}else a.edit_event_type==="edit_schematic_component_location"?n=n.map(s=>s.type==="schematic_component"&&s.schematic_component_id===a.schematic_component_id?{...s,center:a.new_center}:s):a.edit_event_type==="edit_pcb_trace_hint"&&(n=EVt(n,a));return n},PBe=(n,e)=>{let a=n.source_group.list(),s=[],l=p=>{let x=a.filter(f=>f.parent_subcircuit_id===p);for(let f of x)f.subcircuit_id&&(s.push(f.subcircuit_id),l(f.subcircuit_id))};return l(e),s},YW=({db:n,circuitJson:e,subcircuit_id:a,minTraceWidth:s=.1})=>{if(!n&&e&&(n=ia(e)),!n)throw new Error("db or circuitJson is required");let l=n.pcb_trace_hint.list(),p=a?new Set([a]):null;if(a){let K=PBe(n,a);for(let U of K)p.add(U)}let x=(e??n.toArray()).filter(K=>!a||"subcircuit_id"in K&&p.has(K.subcircuit_id)),f=n.pcb_board.list()[0];n=ia(x);let m=Ku(x),D=SBe([...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(K=>!a||p?.has(K.subcircuit_id)),m);for(let K of D){let U=K.connectedTo.flatMap(J=>m.getIdsConnectedToNet(J));K.connectedTo.push(...U)}let b=D.flatMap(K=>[{x:K.center.x-K.width/2,y:K.center.y-K.height/2},{x:K.center.x+K.width/2,y:K.center.y+K.height/2}]),E;if(f?E={minX:f.center.x-f.width/2,maxX:f.center.x+f.width/2,minY:f.center.y-f.height/2,maxY:f.center.y+f.height/2}:E={minX:Math.min(...b.map(K=>K.x))-1,maxX:Math.max(...b.map(K=>K.x))+1,minY:Math.min(...b.map(K=>K.y))-1,maxY:Math.max(...b.map(K=>K.y))+1},a){let K=n.pcb_group.getWhere({subcircuit_id:a});if(K){let U={minX:K.center.x-K.width/2,maxX:K.center.x+K.width/2,minY:K.center.y-K.height/2,maxY:K.center.y+K.height/2};E={minX:Math.min(E.minX,U.minX),maxX:Math.max(E.maxX,U.maxX),minY:Math.min(E.minY,U.minY),maxY:Math.max(E.maxY,U.maxY)}}}let A=new Set(n.pcb_trace.list().map(K=>K.source_trace_id).filter(K=>!!K)),B=n.source_trace.list().filter(K=>!A.has(K.source_trace_id)).map(K=>{let U=K.connected_source_port_ids.map(Ve=>{let et=n.source_port.get(Ve),ct=n.pcb_port.getWhere({source_port_id:Ve});return{...et,...ct}});if(U.length<2)return null;let[J,Q]=U,de=J.layers?.[0]??"top",ce=Q.layers?.[0]??"top",Te=l.filter(Ve=>Ve.pcb_port_id===J.pcb_port_id||Ve.pcb_port_id===Q.pcb_port_id),Ne=[];for(let Ve of Te){let ct=n.pcb_port.get(Ve.pcb_port_id)?.layers?.[0]??"top";for(let Mt of Ve.route)Ne.push({x:Mt.x,y:Mt.y,layer:ct})}return{name:K.source_trace_id??m.getNetConnectedToId(K.source_trace_id)??"",source_trace_id:K.source_trace_id,pointsToConnect:[{x:J.x,y:J.y,layer:de,pointId:J.pcb_port_id,pcb_port_id:J.pcb_port_id},...Ne,{x:Q.x,y:Q.y,layer:ce,pointId:Q.pcb_port_id,pcb_port_id:Q.pcb_port_id}]}}).filter(K=>K!==null),w=new Map(B.map(K=>[K.source_trace_id,K])),P=n.source_net.list().filter(K=>!a||p?.has(K.subcircuit_id)),N=[];for(let K of P){let U=n.source_trace.list().filter(J=>J.connected_source_net_ids?.includes(K.source_net_id));N.push({name:K.source_net_id??m.getNetConnectedToId(K.source_net_id),pointsToConnect:U.flatMap(J=>n.pcb_port.list().filter(de=>J.connected_source_port_ids.includes(de.source_port_id)).map(de=>({x:de.x,y:de.y,layer:de.layers?.[0]??"top",pointId:de.pcb_port_id,pcb_port_id:de.pcb_port_id})))})}let O=n.pcb_breakout_point.list().filter(K=>!a||p?.has(K.subcircuit_id)),$=[],ee=new Map;for(let K of O){let U={x:K.x,y:K.y,layer:"top"};if(K.source_trace_id){let J=w.get(K.source_trace_id)??ee.get(K.source_trace_id);if(J)J.pointsToConnect.push(U);else{let Q={name:K.source_trace_id,source_trace_id:K.source_trace_id,pointsToConnect:[U]};$.push(Q),ee.set(K.source_trace_id,Q)}}else if(K.source_net_id){let J=N.find(Q=>Q.name===K.source_net_id);J?J.pointsToConnect.push(U):$.push({name:K.source_net_id,pointsToConnect:[U]})}else if(K.source_port_id){let J=n.pcb_port.getWhere({source_port_id:K.source_port_id});J&&$.push({name:K.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:J.x,y:J.y,layer:J.layers?.[0]??"top",pointId:J.pcb_port_id,pcb_port_id:J.pcb_port_id},U]})}}let X=[...B,...N,...$],te=new Map;for(let K of X)for(let U of K.pointsToConnect)U.pointId&&te.set(U.pointId,K);let L=n.pcb_trace.list().filter(K=>!a||p?.has(K.subcircuit_id));for(let K of L){let U=new Set;for(let de of K.route)de.start_pcb_port_id&&U.add(de.start_pcb_port_id),de.end_pcb_port_id&&U.add(de.end_pcb_port_id);if(U.size<2)continue;let J=U.values().next().value;if(!J)continue;let Q=te.get(J);Q&&[...U].every(de=>te.get(de)===Q)&&(Q.externallyConnectedPointIds??(Q.externallyConnectedPointIds=[]),Q.externallyConnectedPointIds.push([...U]))}return{simpleRouteJson:{bounds:E,obstacles:D,connections:X,layerCount:f?.num_layers??2,minTraceWidth:s},connMap:m}},CVt=n=>{let e={};if(!n)return e;for(let s of id)e[s]=0;let a=new Map;for(let s of n){let[,,l,p]=s.type.split(":");if(p==="start"){a.set(`${l}:${s.renderId}`,s);continue}if(p==="end"){let x=a.get(`${l}:${s.renderId}`);if(x){let f=s.createdAt-x.createdAt;e[l]=(e[l]||0)+f}}}return e},_Vt=n=>{let e=n.map(m=>[...new Set(m)]),a=e.map(()=>[]),s=e.map(()=>null);for(let m=0;m<e.length;m++)for(let D of e[m])if(/^\d+$/.test(D)){s[m]=Number.parseInt(D);break}let l=0,p=new Set;for(let m=0;m<s.length;m++){let D=s[m];if(D===null||D<1)continue;if(!p.has(D)){p.add(D),a[m].push(`pin${D}`),l=Math.max(l,D);continue}let b=0;for(let E of a[m])E.startsWith(`pin${D}_alt`)&&b++;a[m].push(`pin${D}_alt${b+1}`)}for(let m=0;m<a.length;m++)a[m][0]?.includes("_alt")&&(l++,a[m].unshift(`pin${l}`));for(let m=0;m<a.length;m++)a[m].length===0&&(l++,a[m].push(`pin${l}`));let x={};for(let m of e)for(let D of m)/^\d+$/.test(D)||(x[D]=(x[D]??0)+1);let f={};for(let m=0;m<e.length;m++){let D=e[m];for(let b of D)/^\d+$/.test(b)||(x[b]===1?a[m].push(b):(f[b]=(f[b]??0)+1,a[m].push(`${b}${f[b]}`)))}return a},sBe=(0,IBe.default)("Group_doInitialSchematicLayoutMatchAdapt");function AVt(n){let{db:e}=n.root,a=Lb(e.toArray(),{source_group_id:n.source_group_id}),s=rH(a);sBe.enabled&&global.debugGraphics?.push(Vp(s,{title:`floatingBpcGraph-${n.name}`}));let l=rH(a),p={boxes:l.boxes,pins:l.pins.map(m=>({...m,color:m.color.replace("not_connected","normal")}))},{result:x}=TRe([{variantName:"default",floatingGraph:l},{variantName:"noNotConnected",floatingGraph:p}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(l.boxes.filter(m=>l.pins.filter(E=>E.boxId===m.boxId).filter(E=>!E.color.includes("center")).length<=2).map(m=>m.boxId)),corpus:{}});sBe.enabled&&global.debugGraphics?.push(Vp(x,{title:`laidOutBpcGraph-${n.name}`}));let f=n._getGlobalSchematicPositionBeforeLayout();for(let m of x.boxes){if(!m.center)continue;let D=e.schematic_component.get(m.boxId);if(D){let E={x:m.center.x+f.x,y:m.center.y+f.y},A=e.schematic_port.list({schematic_component_id:D.schematic_component_id}),B=e.schematic_text.list({schematic_component_id:D.schematic_component_id}),w={x:E.x-D.center.x,y:E.y-D.center.y};for(let P of A)P.center.x+=w.x,P.center.y+=w.y;for(let P of B)P.position.x+=w.x,P.position.y+=w.y;D.center=E;continue}let b=e.schematic_net_label.get(m.boxId);if(b){let E=x.pins.find(B=>B.boxId===m.boxId&&B.color==="netlabel_center");if(!E)throw new Error(`No pin found for net label: ${m.boxId}`);let A={x:m.center.x+f.x,y:m.center.y+f.y};b.center=A,b.anchor_position={x:A.x+E.offset.x,y:A.y+E.offset.y};continue}console.error(`No schematic element found for box: ${m.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var nn=(0,jBe.default)("Group_doInitialSchematicLayoutMatchpack");function iBe(n){switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function oBe(n,e){let a=["right","up","left","down"],s=a.indexOf(n);if(s===-1)return n;let l=Math.round(e/90),p=(s+l)%4;return a[p<0?p+4:p]}function RVt(n,e,a){let s={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};nn(`[${a.name}] Processing ${n.childNodes.length} child nodes for input problem`),n.childNodes.forEach((p,x)=>{if(nn(`[${a.name}] Processing child ${x}: nodeType=${p.nodeType}`),p.nodeType==="component"?nn(`[${a.name}] - Component: ${p.sourceComponent?.name}`):p.nodeType==="group"&&nn(`[${a.name}] - Group: ${p.sourceGroup?.name}`),p.nodeType==="component"&&p.sourceComponent){let f=p.sourceComponent.name||`chip_${x}`,m=e.schematic_component.getWhere({source_component_id:p.sourceComponent.source_component_id});if(!m)return;let D=a.children.find(A=>A.source_component_id===p.sourceComponent?.source_component_id),b=[0,90,180,270];D?._parsedProps?.schOrientation&&(b=[0]),D?._parsedProps?.schRotation!==void 0&&(b=[0]),s.chipMap[f]={chipId:f,pins:[],size:{x:m.size?.width||1,y:m.size?.height||1},availableRotations:b};let E=e.schematic_port.list({schematic_component_id:m.schematic_component_id});for(let A of E){let B=e.source_port.get(A.source_port_id);if(!B)continue;let w=`${f}.${B.pin_number||B.name||A.schematic_port_id}`;s.chipMap[f].pins.push(w);let P=iBe(A.facing_direction);s.chipPinMap[w]={pinId:w,offset:{x:(A.center?.x||0)-(m.center.x||0),y:(A.center?.y||0)-(m.center.y||0)},side:P}}}else if(p.nodeType==="group"&&p.sourceGroup){let f=p.sourceGroup.name||`group_${x}`;nn(`[${a.name}] Processing nested group: ${f}`);let m=e.schematic_group?.getWhere?.({source_group_id:p.sourceGroup.source_group_id});if(nn(`[${a.name}] Found schematic_group for ${f}:`,m),m){nn(`[${a.name}] Treating group ${f} as composite chip`);let D=e.schematic_component.list({schematic_group_id:m.schematic_group_id});nn(`[${a.name}] Group ${f} has ${D.length} components:`,D.map($=>$.source_component_id));let b=1/0,E=-1/0,A=1/0,B=-1/0,w=!1;for(let $ of D)if($.center&&$.size){w=!0;let ee=$.size.width/2,X=$.size.height/2;b=Math.min(b,$.center.x-ee),E=Math.max(E,$.center.x+ee),A=Math.min(A,$.center.y-X),B=Math.max(B,$.center.y+X)}let P=w?E-b:2,N=w?B-A:2;nn(`[${a.name}] Group ${f} computed size: ${P} x ${N}`);let O=[];for(let $ of D){let ee=e.schematic_port.list({schematic_component_id:$.schematic_component_id});for(let X of ee){let te=e.source_port.get(X.source_port_id);if(!te)continue;let L=`${f}.${te.pin_number||te.name||X.schematic_port_id}`;O.push(L);let K=m.center||{x:0,y:0},U=iBe(X.facing_direction);s.chipPinMap[L]={pinId:L,offset:{x:(X.center?.x||0)-K.x,y:(X.center?.y||0)-K.y},side:U}}}nn(`[${a.name}] Group ${f} has ${O.length} pins:`,O),s.chipMap[f]={chipId:f,pins:O,size:{x:P,y:N}},nn(`[${a.name}] Added group ${f} to chipMap`)}else nn(`[${a.name}] Warning: No schematic_group found for group ${f}`)}}),nn(`[${a.name}] Creating connections using connectivity keys`);let l=new Map;for(let[p,x]of Object.entries(s.chipMap))for(let f of x.pins){let m=f.split(".").pop(),D=n.childNodes.find(b=>b.nodeType==="component"&&b.sourceComponent?b.sourceComponent.name===p:b.nodeType==="group"&&b.sourceGroup?`group_${n.childNodes.indexOf(b)}`===p:!1);if(D?.nodeType==="group"&&D.sourceGroup){let b=e.schematic_group?.getWhere?.({source_group_id:D.sourceGroup.source_group_id});if(b){let E=e.schematic_component.list({schematic_group_id:b.schematic_group_id});for(let A of E){let B=e.source_port.list({source_component_id:A.source_component_id});for(let w of B){let P=w.pin_number||w.name;if(String(P)===String(m))if(w.subcircuit_connectivity_map_key){let N=w.subcircuit_connectivity_map_key;l.has(N)||l.set(N,[]),l.get(N).push(f),nn(`[${a.name}] \u2713 Pin ${f} has connectivity key: ${N}`)}else nn(`[${a.name}] Pin ${f} has no connectivity key`)}}}}else if(D?.nodeType==="component"&&D.sourceComponent){let b=e.source_port.list({source_component_id:D.sourceComponent.source_component_id});for(let E of b){let A=E.pin_number||E.name;if(String(A)===String(m)&&E.subcircuit_connectivity_map_key){let B=E.subcircuit_connectivity_map_key;l.has(B)||l.set(B,[]),l.get(B).push(f),nn(`[${a.name}] Pin ${f} has connectivity key: ${B}`)}}}}nn(`[${a.name}] Found ${l.size} connectivity groups:`,Array.from(l.entries()).map(([p,x])=>({key:p,pins:x})));for(let[p,x]of l)if(x.length>=2){let f=e.source_trace.list().filter(b=>b.subcircuit_connectivity_map_key===p),m=f.some(b=>b.connected_source_net_ids&&b.connected_source_net_ids.length>0),D=f.some(b=>b.connected_source_port_ids&&b.connected_source_port_ids.length>=2);if(nn(`[${a.name}] Connectivity ${p}: hasNetConnections=${m}, hasDirectConnections=${D}`),D){for(let b of f)if(b.connected_source_port_ids&&b.connected_source_port_ids.length>=2){let E=[];for(let A of b.connected_source_port_ids)for(let B of x){let w=B.split(".").pop(),P=e.source_port.get(A);if(P&&String(P.pin_number||P.name)===String(w)){let N=B.split(".")[0],O=n.childNodes.find($=>$.nodeType==="component"&&$.sourceComponent?$.sourceComponent.name===N:$.nodeType==="group"&&$.sourceGroup?`group_${n.childNodes.indexOf($)}`===N:!1);O?.nodeType==="component"&&O.sourceComponent&&e.source_port.list({source_component_id:O.sourceComponent.source_component_id}).some(ee=>ee.source_port_id===A)&&E.push(B)}}for(let A=0;A<E.length;A++)for(let B=A+1;B<E.length;B++){let w=E[A],P=E[B];s.pinStrongConnMap[`${w}-${P}`]=!0,s.pinStrongConnMap[`${P}-${w}`]=!0,nn(`[${a.name}] Created strong connection: ${w} <-> ${P}`)}}}if(m){let b=e.source_net.getWhere({subcircuit_connectivity_map_key:p}),E=b?.is_ground??!1,A=b?.is_power??!1;s.netMap[p]={netId:p,isGround:E,isPositiveVoltageSource:A};for(let B of x)s.netConnMap[`${B}-${p}`]=!0;nn(`[${a.name}] Created net ${p} with ${x.length} pins:`,x)}}return s}function SVt(n){let{db:e}=n.root,a=ig(e.toArray(),{source_group_id:n.source_group_id});if(nn(`[${n.name}] Starting matchpack layout with ${a.childNodes.length} children`),nn(`[${n.name}] Tree structure:`,JSON.stringify(a,null,2)),a.childNodes.length<=1){nn(`[${n.name}] Only ${a.childNodes.length} children, skipping layout`);return}nn("Converting circuit tree to InputProblem...");let s=RVt(a,e,n);nn.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${n.name}`,content:JSON.stringify(s,null,2)});let l=new L5e(s);if(nn("Starting LayoutPipelineSolver..."),nn.enabled&&global.debugGraphics){let m=l.visualize();global.debugGraphics.push({...m,title:`matchpack-initial-${n.name}`})}if(l.solve(),nn(`Solver completed in ${l.iterations} iterations`),nn(`Solved: ${l.solved}, Failed: ${l.failed}`),l.failed)throw nn(`Solver failed with error: ${l.error}`),new Error(`Matchpack layout solver failed: ${l.error}`);let p=l.getOutputLayout();if(nn("OutputLayout:",JSON.stringify(p,null,2)),nn("Solver completed successfully:",!l.failed),nn.enabled&&global.debugGraphics){let m=l.visualize();global.debugGraphics.push({...m,title:`matchpack-final-${n.name}`})}let x=l.checkForOverlaps(p);if(x.length>0){nn(`Warning: Found ${x.length} overlapping components:`);for(let m of x)nn(` ${m.chip1} overlaps ${m.chip2} (area: ${m.overlapArea})`)}let f=n._getGlobalSchematicPositionBeforeLayout();nn(`Group offset: x=${f.x}, y=${f.y}`),nn(`Applying layout results for ${Object.keys(p.chipPlacements).length} chip placements`);for(let[m,D]of Object.entries(p.chipPlacements)){nn(`Processing placement for chip: ${m} at (${D.x}, ${D.y})`);let b=a.childNodes.find(A=>{if(A.nodeType==="component"&&A.sourceComponent){let B=A.sourceComponent.name===m;return nn(` Checking component ${A.sourceComponent.name}: matches=${B}`),B}if(A.nodeType==="group"&&A.sourceGroup){let B=A.sourceGroup.name,w=`group_${a.childNodes.indexOf(A)}`,P=w===m;return nn(` Checking group ${B} (expected chipId: ${w}): matches=${P}`),P}return!1});if(!b){nn(`Warning: No tree node found for chip: ${m}`),nn("Available tree nodes:",a.childNodes.map((A,B)=>({type:A.nodeType,name:A.nodeType==="component"?A.sourceComponent?.name:A.sourceGroup?.name,expectedChipId:A.nodeType==="group"?`group_${B}`:A.sourceComponent?.name})));continue}let E={x:D.x+f.x,y:D.y+f.y};if(b.nodeType==="component"&&b.sourceComponent){let A=e.schematic_component.getWhere({source_component_id:b.sourceComponent.source_component_id});if(A){nn(`Moving component ${m} to (${E.x}, ${E.y})`);let B=e.schematic_port.list({schematic_component_id:A.schematic_component_id}),w=e.schematic_text.list({schematic_component_id:A.schematic_component_id}),P={x:E.x-A.center.x,y:E.y-A.center.y};for(let N of B)N.center.x+=P.x,N.center.y+=P.y;for(let N of w)N.position.x+=P.x,N.position.y+=P.y;if(A.center=E,D.ccwRotationDegrees!==0){nn(`Component ${m} has rotation: ${D.ccwRotationDegrees}\xB0`);let N=D.ccwRotationDegrees*Math.PI/180,O=Math.cos(N),$=Math.sin(N);for(let ee of B){let X=ee.center.x-E.x,te=ee.center.y-E.y,L=X*O-te*$,K=X*$+te*O;ee.center.x=E.x+L,ee.center.y=E.y+K;let U=ee.facing_direction||"right";ee.facing_direction=oBe(U,D.ccwRotationDegrees)}for(let ee of w){let X=ee.position.x-E.x,te=ee.position.y-E.y,L=X*O-te*$,K=X*$+te*O;ee.position.x=E.x+L,ee.position.y=E.y+K}if(A.symbol_name){let ee=A.symbol_name.match(/_(right|left|up|down)$/);ee&&(A.symbol_name=A.symbol_name.replace(ee[0],`_${oBe(ee[1],D.ccwRotationDegrees)}`))}}}}else if(b.nodeType==="group"&&b.sourceGroup){let A=e.schematic_group?.getWhere?.({source_group_id:b.sourceGroup.source_group_id});if(A){nn(`Moving group ${m} to (${E.x}, ${E.y}) from (${A.center?.x}, ${A.center?.y})`);let B=e.schematic_component.list({schematic_group_id:A.schematic_group_id});nn(`Group ${m} has ${B.length} components to move`);let w=A.center||{x:0,y:0},P={x:E.x-w.x,y:E.y-w.y};nn(`Position delta for group ${m}: (${P.x}, ${P.y})`);for(let N of B)if(N.center){let O={...N.center};N.center.x+=P.x,N.center.y+=P.y,nn(`Moved component ${N.source_component_id} from (${O.x}, ${O.y}) to (${N.center.x}, ${N.center.y})`);let $=e.schematic_port.list({schematic_component_id:N.schematic_component_id}),ee=e.schematic_text.list({schematic_component_id:N.schematic_component_id});for(let X of $)X.center&&(X.center.x+=P.x,X.center.y+=P.y);for(let X of ee)X.position&&(X.position.x+=P.x,X.position.y+=P.y)}A.center=E,nn(`Updated group ${m} center to (${E.x}, ${E.y})`)}}}nn("Matchpack layout completed successfully")}function BVt(n){if(!n.isSubcircuit)return;let{db:e}=n.root,a=n.selectAll("trace"),s=new Pb({});s.addConnections(a.map(f=>{let m=e.source_trace.get(f.source_trace_id);return m?[m.source_trace_id,...m.connected_source_port_ids,...m.connected_source_net_ids]:null}).filter(f=>f!==null));let{name:l}=n._parsedProps;for(let f of a){if(!f.source_trace_id)continue;let m=s.getNetConnectedToId(f.source_trace_id);m&&(f.subcircuit_connectivity_map_key=`${l??`unnamedsubcircuit${n._renderId}`}_${m}`,e.source_trace.update(f.source_trace_id,{subcircuit_connectivity_map_key:f.subcircuit_connectivity_map_key}))}let p=new Set;for(let f of a){if(!f.source_trace_id)continue;let m=e.source_trace.get(f.source_trace_id);if(m)for(let D of m.connected_source_port_ids)p.add(D)}for(let f of p){let m=s.getNetConnectedToId(f);if(!m)continue;let D=`${l??`unnamedsubcircuit${n._renderId}`}_${m}`;e.source_port.update(f,{subcircuit_connectivity_map_key:D})}let x=new Set;for(let f of a){if(!f.source_trace_id)continue;let m=e.source_trace.get(f.source_trace_id);if(m)for(let D of m.connected_source_net_ids)x.add(D)}for(let f of x){let m=s.getNetConnectedToId(f);if(!m)continue;let D=`${l??`unnamedsubcircuit${n._renderId}`}_${m}`;e.source_net.update(f,{subcircuit_connectivity_map_key:D})}}function wVt(n){let{db:e}=n.root,a=n._parsedProps,s=n.children.filter(te=>{let L=te._parsedProps?.schX!==void 0||te._parsedProps?.schY!==void 0;return te.schematic_component_id&&!L});if(s.length===0)return;let l=0,p=0;for(let te of s){let L=e.schematic_component.get(te.schematic_component_id);L?.size&&(l=Math.max(l,L.size.width),p=Math.max(p,L.size.height))}l===0&&s.length>0&&(l=1),p===0&&s.length>0&&(p=1);let x=a.gridCols,f,m=a.gridGap,D=a.gridRowGap,b=a.gridColumnGap;a.schLayout?.grid&&(x=a.schLayout.grid.cols??x,f=a.schLayout.grid.rows,m=a.schLayout.gridGap??m,D=a.schLayout.gridRowGap??D,b=a.schLayout.gridColumnGap??b);let E,A;x!==void 0&&f!==void 0?(E=x,A=f):x!==void 0?(E=x,A=Math.ceil(s.length/E)):f!==void 0?(A=f,E=Math.ceil(s.length/A)):(E=Math.ceil(Math.sqrt(s.length)),A=Math.ceil(s.length/E)),E===0&&s.length>0&&(E=1),A===0&&s.length>0&&(A=s.length);let B,w,P=te=>{if(te!==void 0)return typeof te=="number"?te:xe.parse(te)};if(D!==void 0||b!==void 0){let te=typeof m=="object"&&m!==null?m.x:m,L=typeof m=="object"&&m!==null?m.y:m;B=P(b??te)??1,w=P(D??L)??1}else if(typeof m=="number")B=m,w=m;else if(typeof m=="string"){let te=xe.parse(m);B=te,w=te}else if(typeof m=="object"&&m!==null){let te=m.x,L=m.y;B=typeof te=="number"?te:xe.parse(te??"0mm"),w=typeof L=="number"?L:xe.parse(L??"0mm")}else B=1,w=1;let N=E*l+Math.max(0,E-1)*B,O=A*p+Math.max(0,A-1)*w,$=n._getGlobalSchematicPositionBeforeLayout(),ee=$.x-N/2+l/2,X=$.y+O/2-p/2;for(let te=0;te<s.length;te++){let L=s[te];if(!L.schematic_component_id)continue;let K=Math.floor(te/E),U=te%E;if(K>=A||U>=E){console.warn(`Schematic grid layout: Child ${L.getString()} at index ${te} (row ${K}, col ${U}) exceeds specified grid dimensions (${A}x${E}). Skipping placement.`);continue}let J=ee+U*(l+B),Q=X-K*(p+w),de=e.schematic_component.get(L.schematic_component_id);if(de){let ce=de.center,Te={x:J,y:Q};e.schematic_component.update(L.schematic_component_id,{center:Te});let Ne=Te.x-ce.x,Ve=Te.y-ce.y,et=e.schematic_port.list({schematic_component_id:L.schematic_component_id});for(let Mt of et)e.schematic_port.update(Mt.schematic_port_id,{center:{x:Mt.center.x+Ne,y:Mt.center.y+Ve}});let ct=e.schematic_text.list({schematic_component_id:L.schematic_component_id});for(let Mt of ct)e.schematic_text.update(Mt.schematic_text_id,{position:{x:Mt.position.x+Ne,y:Mt.position.y+Ve}})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:N,height:O,center:$})}var uBe=(n,e)=>{let{sourceComponent:a,sourceGroup:s}=e;if(e.nodeType==="component"){let l=n.schematic_component.getWhere({source_component_id:a?.source_component_id});return l?.size?{width:l.size.width,height:l.size.height}:null}if(e.nodeType==="group"){let l=n.schematic_group.getWhere({source_group_id:s?.source_group_id});if(l?.width&&l?.height)return{width:l.width,height:l.height};let p=n.schematic_component.list({schematic_group_id:l?.schematic_group_id}),x=1/0,f=-1/0,m=1/0,D=-1/0;for(let A of p)if(A.center&&A.size){let B=A.size.width/2,w=A.size.height/2;x=Math.min(x,A.center.x-B),f=Math.max(f,A.center.x+B),m=Math.min(m,A.center.y-w),D=Math.max(D,A.center.y+w)}let b=f-x,E=D-m;return{width:b,height:E}}return null},TVt=n=>{let{db:e}=n.root,a=n._parsedProps,s=ig(e.toArray(),{source_group_id:n.source_group_id}),l=a.schJustifyContent??a.justifyContent,p=a.schAlignItems??a.alignItems,x=a.schFlexGap??a.schGap??a.gap,f=a.schFlexDirection??"row",m={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[l??"space-between"],D={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[p??"center"];if(!m)throw new Error(`Invalid justifyContent value: "${l}"`);if(!D)throw new Error(`Invalid alignItems value: "${p}"`);let b=0,E=0;typeof x=="object"?(b=x.y??0,E=x.x??0):typeof x=="number"?(b=x,E=x):typeof x=="string"&&(b=xe.parse(x),E=xe.parse(x));let A,B=a.width??a.schWidth??void 0,w=a.height??a.schHeight??void 0;(B===void 0||w===void 0)&&(A=g5(s.childNodes.map(X=>uBe(e,X)).filter(X=>X!==null),{alignItems:D,justifyContent:m,direction:f,rowGap:b,columnGap:E}),B=A.width,w=A.height);let N=new FS(B,w,{alignItems:D,justifyContent:m,direction:f,rowGap:b,columnGap:E});for(let X of s.childNodes){let te=uBe(e,X);N.addChild({metadata:X,width:te?.width??0,height:te?.height??0,flexBasis:te?f==="row"?te.width:te.height:void 0})}N.build();let O={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let X of N.children)O.minX=Math.min(O.minX,X.position.x),O.minY=Math.min(O.minY,X.position.y),O.maxX=Math.max(O.maxX,X.position.x+X.size.width),O.maxY=Math.max(O.maxY,X.position.y+X.size.height);O.width=O.maxX-O.minX,O.height=O.maxY-O.minY;let $={x:-(O.maxX+O.minX)/2,y:-(O.maxY+O.minY)/2},ee=e.toArray();for(let X of N.children){let{sourceComponent:te,sourceGroup:L}=X.metadata;if(te){let K=e.schematic_component.getWhere({source_component_id:te.source_component_id});if(!K)continue;n4e(ee,K.schematic_component_id,{x:X.position.x+X.size.width/2+$.x,y:X.position.y+X.size.height/2+$.y})}if(L){if(!e.schematic_group.getWhere({source_group_id:L.source_group_id}))continue;s4e(ee,L.source_group_id,{x:X.position.x+X.size.width/2+$.x,y:X.position.y+X.size.height/2+$.y})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:O.width,height:O.height})},NW=1;function PVt(n){let{db:e}=n.root,a=n._parsedProps,s=IVt(n);if(s.length===0)return;let l=jVt({db:e,pcbChildren:s}),p=kVt(a),x=NVt({props:a,pcbChildren:s,childDimensions:l,gridConfig:p}),f=LVt({pcbChildren:s,childDimensions:l,gridLayout:x,gridConfig:p}),{itemCoordinates:m}=f.layout();$Vt({db:e,group:n,pcbChildren:s,itemCoordinates:m,gridLayout:x}),zVt({db:e,group:n,props:a,gridLayout:x})}function IVt(n){return n.children.filter(e=>e.pcb_component_id||e.pcb_group_id)}function jVt(n){let{db:e,pcbChildren:a}=n,s=0,l=0;for(let p of a){let x=0,f=0;if(p.pcb_group_id){let m=e.pcb_group.get(p.pcb_group_id);x=m?.width??0,f=m?.height??0}else if(p.pcb_component_id){let m=e.pcb_component.get(p.pcb_component_id);x=m?.width??0,f=m?.height??0}s=Math.max(s,x),l=Math.max(l,f)}return{width:s,height:l}}function kVt(n){let e=n.pcbGridCols??n.gridCols??n.pcbLayout?.grid?.cols,a=n.pcbGridRows??n.pcbLayout?.grid?.rows,s=n.pcbGridTemplateColumns,l=n.pcbGridTemplateRows,p=E=>E===void 0?NW:typeof E=="number"?E:xe.parse(E),x=n.pcbGridGap??n.gridGap??n.pcbLayout?.gridGap,f=n.pcbGridRowGap??n.gridRowGap??n.pcbLayout?.gridRowGap,m=n.pcbGridColumnGap??n.gridColumnGap??n.pcbLayout?.gridColumnGap,D=NW,b=NW;if(f!==void 0||m!==void 0){let E=typeof x=="object"?x?.x:x,A=typeof x=="object"?x?.y:x;D=p(m??E),b=p(f??A)}else if(typeof x=="object"&&x!==null)D=p(x.x),b=p(x.y);else{let E=p(x);D=E,b=E}return{cols:e,rows:a,gapX:D,gapY:b,templateColumns:s,templateRows:l}}function NVt(n){let{props:e,pcbChildren:a,childDimensions:s,gridConfig:l}=n;return e.pcbGridTemplateColumns||e.pcbGridTemplateRows?MVt({props:e,gridConfig:l,pcbChildren:a,childDimensions:s}):OVt({gridConfig:l,pcbChildren:a,childDimensions:s})}function MVt(n){let{props:e,gridConfig:a,pcbChildren:s,childDimensions:l}=n,p=e.pcbGridTemplateColumns??"",x=e.pcbGridTemplateRows??"",f=A=>{let B=A.match(/repeat\((\d+),/);return B?parseInt(B[1]):Math.ceil(Math.sqrt(s.length))},m=e.pcbGridTemplateColumns?f(p):Math.ceil(Math.sqrt(s.length)),D=e.pcbGridTemplateRows?f(x):Math.ceil(s.length/m),b=m*l.width+Math.max(0,m-1)*a.gapX,E=D*l.height+Math.max(0,D-1)*a.gapY;return{gridTemplateColumns:p,gridTemplateRows:x,containerWidth:b,containerHeight:E}}function OVt(n){let{gridConfig:e,pcbChildren:a,childDimensions:s}=n,l,p;e.cols!==void 0&&e.rows!==void 0?(l=e.cols,p=e.rows):e.cols!==void 0?(l=e.cols,p=Math.ceil(a.length/l)):e.rows!==void 0?(p=e.rows,l=Math.ceil(a.length/p)):(l=Math.ceil(Math.sqrt(a.length)),p=Math.ceil(a.length/l)),l=Math.max(1,l),p=Math.max(1,p);let x=l*s.width+Math.max(0,l-1)*e.gapX,f=p*s.height+Math.max(0,p-1)*e.gapY,m=`repeat(${l}, ${s.width}px)`,D=`repeat(${p}, ${s.height}px)`;return{gridTemplateColumns:m,gridTemplateRows:D,containerWidth:x,containerHeight:f}}function LVt(n){let{pcbChildren:e,childDimensions:a,gridLayout:s,gridConfig:l}=n,p=e.map((x,f)=>({key:x.getString()||`child-${f}`,contentWidth:a.width,contentHeight:a.height}));return new H5e({containerWidth:s.containerWidth,containerHeight:s.containerHeight,gridTemplateColumns:s.gridTemplateColumns,gridTemplateRows:s.gridTemplateRows,gap:[l.gapY,l.gapX],children:p})}function $Vt(n){let{db:e,group:a,pcbChildren:s,itemCoordinates:l,gridLayout:p}=n,x=a._getGlobalPcbPositionBeforeLayout(),f=e.toArray();for(let m=0;m<s.length;m++){let D=s[m],b=D.getString()||`child-${m}`,E=l[b];if(!E){console.warn(`PCB grid layout: No coordinates found for child ${b}`);continue}let A=x.x-p.containerWidth/2+E.x+E.width/2,B=x.y+p.containerHeight/2-E.y-E.height/2;if(D.pcb_component_id)h5(f,D.pcb_component_id,{x:A,y:B});else{let w=D;w.pcb_group_id&&w.source_group_id&&m5(f,w.source_group_id,{x:A,y:B})}}}function zVt(n){let{db:e,group:a,props:s,gridLayout:l}=n;if(a.pcb_group_id){let p=a._getGlobalPcbPositionBeforeLayout();e.pcb_group.update(a.pcb_group_id,{width:s.width??l.containerWidth,height:s.height??l.containerHeight,center:p})}}function qVt(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 a=typeof n=="object"?n.preset:n,s=typeof n=="object"?n:{};switch(a){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:l,local:p,groupMode:x,...f}=s;return{local:!1,groupMode:"subcircuit",...e,...f}}default:return{local:!0,groupMode:"subcircuit"}}}var UVt="1mm",cBe=(0,kBe.default)("Group_doInitialPcbLayoutPack"),kF=(n,e,a)=>{if(e===a)return!0;let s=n.source_group.get(e);return!s||!s.parent_source_group_id?!1:kF(n,s.parent_source_group_id,a)},VVt=n=>{let{db:e}=n.root,{_parsedProps:a}=n,{packOrderStrategy:s,packPlacementStrategy:l,gap:p,pcbGap:x,pcbPackGap:f}=a,m=f??x??p,D=xe.parse(m??UVt),b={...M5e(N5e(e.toArray(),{source_group_id:n.source_group_id,shouldAddInnerObstacles:!0})),orderStrategy:s??"largest_to_smallest",placementStrategy:l??"minimum_sum_squared_distance_to_network",minGap:D};cBe.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:b}));let E=gS(b);if(cBe.enabled){let A=mS(E);A.title=`packOutput-${n.name}`,global.debugGraphics?.push(A)}for(let A of E.components){let{center:B,componentId:w,ccwRotationOffset:P,ccwRotationDegrees:N}=A,O=e.pcb_component.get(w);if(O){let K=n.source_group_id,J=e.source_component.get(O.source_component_id)?.source_group_id;if(J!==void 0&&!kF(e,J,K))continue;let Q=O.center,de=N??P??0,ce=Ts(n._computePcbGlobalTransformBeforeLayout(),ka(B.x,B.y),Xf(de*Math.PI/180),ka(-Q.x,-Q.y)),Te=e.toArray().filter(Ne=>"pcb_component_id"in Ne&&Ne.pcb_component_id===w);$b(Te,ce);continue}let $=e.pcb_group.list().find(K=>K.source_group_id===w);if(!$)continue;let ee=$.center,X=N??P??0,te=Ts(n._computePcbGlobalTransformBeforeLayout(),ka(B.x,B.y),Xf(X*Math.PI/180),ka(-ee.x,-ee.y)),L=e.toArray().filter(K=>{if("source_group_id"in K&&K.source_group_id&&(K.source_group_id===w||kF(e,K.source_group_id,w)))return!0;if("source_component_id"in K&&K.source_component_id){let U=e.source_component.get(K.source_component_id);if(U?.source_group_id&&(U.source_group_id===w||kF(e,U.source_group_id,w)))return!0}if("pcb_component_id"in K&&K.pcb_component_id){let U=e.pcb_component.get(K.pcb_component_id);if(U?.source_component_id){let J=e.source_component.get(U.source_component_id);if(J?.source_group_id&&(J.source_group_id===w||kF(e,J.source_group_id,w)))return!0}}return!1});$b(L,te),e.pcb_group.update($.pcb_group_id,{center:B})}},GVt=n=>{let{db:e}=n.root,{_parsedProps:a}=n,s=n.children.filter(te=>te.pcb_component_id||te.pcb_group_id);if(s.some(te=>{let L=te._parsedProps;return L?.pcbX!==void 0||L?.pcbY!==void 0}))return;let p=a.pcbJustifyContent??a.justifyContent,x=a.pcbAlignItems??a.alignItems,f=a.pcbFlexGap??a.pcbGap??a.gap,m=a.pcbFlexDirection??"row",D={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"}[p??"space-between"],b={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[x??"center"];if(!D)throw new Error(`Invalid justifyContent value: "${p}"`);if(!b)throw new Error(`Invalid alignItems value: "${x}"`);let E=0,A=0;typeof f=="object"?(E=f.y??0,A=f.x??0):typeof f=="number"?(E=f,A=f):typeof f=="string"&&(E=xe.parse(f),A=xe.parse(f));let B,w=a.width??a.pcbWidth??void 0,P=a.height??a.pcbHeight??void 0;(w===void 0||P===void 0)&&(B=g5(s.map(te=>te._getMinimumFlexContainerSize()).filter(te=>te!==null),{alignItems:b,justifyContent:D,direction:m,rowGap:E,columnGap:A}),w=B.width,P=B.height);let O=new FS(w,P,{alignItems:b,justifyContent:D,direction:m,rowGap:E,columnGap:A});for(let te of s){let L=te._getMinimumFlexContainerSize();O.addChild({metadata:te,width:L?.width??0,height:L?.height??0,flexBasis:L?m==="row"?L.width:L.height:void 0})}O.build();let $={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let te of O.children)$.minX=Math.min($.minX,te.position.x),$.minY=Math.min($.minY,te.position.y),$.maxX=Math.max($.maxX,te.position.x+te.size.width),$.maxY=Math.max($.maxY,te.position.y+te.size.height);$.width=$.maxX-$.minX,$.height=$.maxY-$.minY;let ee=n._getGlobalPcbPositionBeforeLayout(),X={x:ee.x-($.maxX+$.minX)/2,y:ee.y-($.maxY+$.minY)/2};for(let te of O.children)te.metadata._repositionOnPcb({x:te.position.x+te.size.width/2+X.x,y:te.position.y+te.size.height/2+X.y});e.pcb_group.update(n.pcb_group_id,{width:$.width,height:$.height,center:ee})};function XVt(n){let{db:e}=n.root,a=new Map,s=new Map,l=new Set,x=n.selectAll("trace").filter(Q=>Q._parsedProps?.schDisplayLabel),f=n.selectAll("group"),m=[n.schematic_group_id,...f.map(Q=>Q.schematic_group_id)],D=e.schematic_component.list().filter(Q=>m.includes(Q.schematic_group_id)),b=[],E=new Map,A=new Map;for(let Q of D){let de=Q.schematic_component_id,ce=[],Te=e.source_component.getWhere({source_component_id:Q.source_component_id}),Ne=e.schematic_port.list({schematic_component_id:Q.schematic_component_id});for(let Ve of Ne){let et=`${Te?.name??Q.schematic_component_id}.${Ve.pin_number}`;E.set(et,Ve.schematic_port_id),A.set(Ve.schematic_port_id,et)}for(let Ve of Ne){let et=A.get(Ve.schematic_port_id);ce.push({pinId:et,x:Ve.center.x,y:Ve.center.y})}b.push({chipId:de,center:Q.center,width:Q.size.width,height:Q.size.height,pins:ce})}let B=new Set,w=new Map,P=new Map,N=new Map;for(let Q of D){let de=e.schematic_port.list({schematic_component_id:Q.schematic_component_id});for(let ce of de)B.add(ce.schematic_port_id),ce.source_port_id&&(w.set(ce.schematic_port_id,ce.source_port_id),P.set(ce.source_port_id,ce.schematic_port_id))}let O=new Set;n.subcircuit_id&&O.add(n.subcircuit_id);for(let Q of f)Q.subcircuit_id&&O.add(Q.subcircuit_id);let ee=e.source_trace.list().filter(Q=>{if(Q.subcircuit_id===n.subcircuit_id)return!0;for(let de of Q.connected_source_port_ids)if(P.has(de))return!0;return!1}).flatMap(Q=>Q.connected_source_net_ids);for(let Q of ee){let de=e.source_net.get(Q);de?.subcircuit_id&&O.add(de.subcircuit_id)}let X=[],te=new Map;for(let Q of e.source_trace.list()){if(Q.subcircuit_id&&!O.has(Q.subcircuit_id))continue;let de=(Q.connected_source_port_ids??[]).map(ce=>P.get(ce)).filter(ce=>!!ce&&B.has(ce));if(de.length>=2){let[ce,Te]=de.slice(0,2),Ne=[ce,Te].sort().join("::");if(!te.has(Ne)){te.set(Ne,Q.source_trace_id);let Ve=Q.display_name??Q.source_trace_id;Q.subcircuit_connectivity_map_key&&(l.add(Q.subcircuit_connectivity_map_key),N.set(Ve,Q.subcircuit_connectivity_map_key),s.set(Q.subcircuit_connectivity_map_key,Ve)),X.push({pinIds:[ce,Te].map(et=>A.get(et)),netId:Ve})}}}let L=[];for(let Q of e.source_net.list().filter(de=>!de.subcircuit_id||O.has(de.subcircuit_id)))Q.subcircuit_connectivity_map_key&&(l.add(Q.subcircuit_connectivity_map_key),a.set(Q.subcircuit_connectivity_map_key,Q));let K=new Map;for(let[Q,de]of w){let ce=e.source_port.get(de);if(!ce?.subcircuit_connectivity_map_key)continue;let Te=ce.subcircuit_connectivity_map_key;l.add(Te),K.has(Te)||K.set(Te,[]),K.get(Te).push(Q)}for(let[Q,de]of K){let ce=a.get(Q);if(ce&&de.length>=2){let Te=String(ce.name||ce.source_net_id||Q);N.set(Te,Q),s.set(Q,Te),L.push({netId:Te,pinIds:de.map(Ne=>A.get(Ne))})}}let U=(()=>{let Q={},de=new Set(L.map(ce=>ce.netId));for(let ce of e.source_net.list().filter(Te=>!Te.subcircuit_id||O.has(Te.subcircuit_id)))ce.name&&de.has(ce.name)&&(ce.is_ground||ce.name.toLowerCase().startsWith("gnd")?Q[ce.name]=["y-"]:ce.is_power||ce.name.toLowerCase().startsWith("v")?Q[ce.name]=["y+"]:Q[ce.name]=["x-","x+"]);return Q})();return{inputProblem:{chips:b,directConnections:X,netConnections:L,availableNetLabelOrientations:U,maxMspPairDistance:n._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:E,pairKeyToSourceTraceId:te,sckToSourceNet:a,sckToUserNetId:s,userNetIdToSck:N,allSourceAndSchematicPortIdsInScope:B,schPortIdToSourcePortId:w,displayLabelTraces:x,allScks:l}}var Ji=1e-6;function lBe(n){let e=Math.abs(n.to.x-n.from.x),a=Math.abs(n.to.y-n.from.y);return e>=a}function GS(n,e){return Math.hypot(e.x-n.x,e.y-n.y)}function dBe(n,e,a){return{x:n.x+(e.x-n.x)*a,y:n.y+(e.y-n.y)*a}}function pBe(n,e,a){let s=GS(n,e);if(s<Ji)return 0;let l=((a.x-n.x)*(e.x-n.x)+(a.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,l))*s}function NS(n,e,a,s){return n*s-e*a}function YVt(n,e,a,s){let l={x:e.x-n.x,y:e.y-n.y},p={x:s.x-a.x,y:s.y-a.y},x=NS(l.x,l.y,p.x,p.y),f={x:a.x-n.x,y:a.y-n.y},m=NS(f.x,f.y,l.x,l.y);if(Math.abs(x)<Ji&&Math.abs(m)<Ji||Math.abs(x)<Ji&&Math.abs(m)>=Ji)return null;let D=NS(f.x,f.y,p.x,p.y)/x,b=NS(f.x,f.y,l.x,l.y)/x;return D<-Ji||D>1+Ji||b<-Ji||b>1+Ji?null:{x:n.x+D*l.x,y:n.y+D*l.y}}function HVt(n,e=Ji){if(n.length===0)return n;n.sort((l,p)=>l.start-p.start);let a=[],s={...n[0]};for(let l=1;l<n.length;l++){let p=n[l];p.start<=s.end+e?s.end=Math.max(s.end,p.end):(a.push(s),s={...p})}return a.push(s),a}function WVt(n,e,a){let s=GS(n.from,n.to);if(s<Ji||e.length===0)return[n];let l=a/2,p=e.map(E=>({start:Math.max(0,E-l),end:Math.min(s,E+l)})).filter(E=>E.end-E.start>Ji),x=HVt(p),f=[],m=0,D={x:n.to.x-n.from.x,y:n.to.y-n.from.y},b=(E,A,B)=>{if(A-E<=Ji)return;let w=E/s,P=A/s;f.push({from:dBe(n.from,n.to,w),to:dBe(n.from,n.to,P),...B?{is_crossing:!0}:{}})};for(let E of x)E.start-m>Ji&&b(m,E.start,!1),b(E.start,E.end,!0),m=E.end;return s-m>Ji&&b(m,s,!1),f.length>0?f:[n]}function KVt(n,e={}){let a=e.crossSegmentLength??.075,s=e.tolerance??Ji,l=new Map,p=m=>`${m.traceIdx}:${m.edgeIdx}`,x=m=>n[m.traceIdx].edges[m.edgeIdx];for(let m=0;m<n.length;m++){let D=n[m];for(let b=0;b<D.edges.length;b++){let E=D.edges[b];for(let A=m;A<n.length;A++){let B=n[A];for(let w=A===m?b+1:0;w<B.edges.length;w++){let P=B.edges[w],N=YVt(E.from,E.to,P.from,P.to);if(!N)continue;let O=GS(E.from,E.to),$=GS(P.from,P.to);if(O<s||$<s)continue;let ee=pBe(E.from,E.to,N),X=pBe(P.from,P.to,N),te=ee<=s||Math.abs(O-ee)<=s||Number.isNaN(ee),L=X<=s||Math.abs($-X)<=s||Number.isNaN(X);if(!te&&!L){let K=lBe(E),U=lBe(P),J;if(K!==U)J=K;else{let ce=Math.abs(E.to.x-E.from.x),Te=Math.abs(E.to.y-E.from.y),Ne=Math.abs(P.to.x-P.from.x),Ve=Math.abs(P.to.y-P.from.y),et=ce-Te,ct=Ne-Ve;J=et===ct?!0:et>ct}let Q=p({traceIdx:J?m:A,edgeIdx:J?b:w}),de=l.get(Q)??[];de.push(J?ee:X),l.set(Q,de)}}}}}let f=n.map(m=>({source_trace_id:m.source_trace_id,edges:[]}));for(let m=0;m<n.length;m++){let D=n[m];for(let b=0;b<D.edges.length;b++){let E=p({traceIdx:m,edgeIdx:b}),A=l.get(E)??[];if(A.length===0){f[m].edges.push(D.edges[b]);continue}let B=Array.from(new Set(A.map(P=>Number(P.toFixed(6))))).sort((P,N)=>P-N),w=WVt(D.edges[b],B,a);f[m].edges.push(...w)}}return f}var tl=1e-6;function XS(n,e,a=tl){return Math.abs(n-e)<=a}function $g(n,e,a=tl){return XS(n.x,e.x,a)&&XS(n.y,e.y,a)}function xBe(n,e,a,s=tl){let l=Math.min(e.x,a.x)-s,p=Math.max(e.x,a.x)+s,x=Math.min(e.y,a.y)-s,f=Math.max(e.y,a.y)+s;return n.x<l||n.x>p||n.y<x||n.y>f?!1:Math.abs((a.x-e.x)*(n.y-e.y)-(a.y-e.y)*(n.x-e.x))<=s}function fBe(n,e=tl){let a=new Map;for(let s of n){let l=`${s.x.toFixed(6)},${s.y.toFixed(6)}`;a.has(l)||a.set(l,s)}return Array.from(a.values())}function hBe(n){return{x:n.to.x-n.from.x,y:n.to.y-n.from.y}}function MW(n,e,a=tl){let s=hBe(n),l=hBe(e),p=Math.hypot(s.x,s.y),x=Math.hypot(l.x,l.y);if(p<a||x<a)return!0;let f=s.x*l.y-s.y*l.x;return Math.abs(f)<=a*p*x}function NF(n,e,a=tl){return n.edges.filter(s=>$g(s.from,e,a)||$g(s.to,e,a))}function mBe(n,e,a=tl){for(let s of n.edges){if($g(s.from,e,a))return s.from;if($g(s.to,e,a))return s.to}return null}function JVt(n,e,a=tl){let s=$g(n.from,e,a)||XS(n.from.x,e.x,a)&&XS(n.from.y,e.y,a)?n.to:n.from,l=s.x-e.x,p=s.y-e.y;return Math.abs(l)<a&&Math.abs(p)<a?null:Math.abs(l)>=Math.abs(p)?l>=0?"right":"left":p>=0?"up":"down"}function Mg(n,e,a=tl){let s=NF(n,e,a);if(s.length<2)return null;let l=s.map(E=>JVt(E,e,a)),p=l.includes("up"),x=l.includes("down"),f=l.includes("left"),m=l.includes("right"),D=p?"up":x?"down":null,b=m?"right":f?"left":null;return D&&b?`${D}-${b}`:null}function ZVt(n,e={}){let a=e.tolerance??tl,s={};for(let p of n)s[p.source_trace_id]=[];let l=n.map(p=>{let x=[];for(let f of p.edges)x.push(f.from,f.to);return fBe(x,a)});for(let p=0;p<n.length;p++){let x=n[p],f=l[p];for(let m=p+1;m<n.length;m++){let D=n[m],b=l[m];for(let E of f)for(let A of b)if($g(E,A,a)){let B=NF(x,E,a),w=NF(D,A,a),P=B.some(ee=>w.some(X=>!MW(ee,X,a))),N=Mg(x,E,a),O=Mg(D,A,a);P&&!(N!==null&&O!==null&&N===O)&&(s[x.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[D.source_trace_id].push(A))}for(let E of f)for(let A of D.edges)if(xBe(E,A.from,A.to,a)){let w=NF(x,E,a).some(ee=>!MW(ee,A,a)),P=Mg(x,E,a),N=mBe(D,E,a*1e3),O=N?Mg(D,N,a):null;w&&!(P!==null&&O!==null&&P===O)&&(s[x.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[D.source_trace_id].push(E))}for(let E of b)for(let A of x.edges)if(xBe(E,A.from,A.to,a)){let w=NF(D,E,a).some(ee=>!MW(A,ee,a)),P=Mg(D,E,a),N=mBe(x,E,a*1e3),O=N?Mg(x,N,a):null;w&&!(O!==null&&P!==null&&O===P)&&(s[D.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[x.source_trace_id].push(E))}}}for(let p of Object.keys(s))s[p]=fBe(s[p],a);return s}var OW=(0,MBe.default)("Group_doInitialSchematicTraceRender");function QVt(n){let{group:e,solver:a,pinIdToSchematicPortId:s,userNetIdToSck:l}=n,{db:p}=e.root,x=a.traceOverlapShiftSolver?.correctedTraceMap,f=[];OW(`Traces inside SchematicTraceSolver output: ${Object.values(x??{}).length}`);for(let b of Object.values(x??{})){let E=b?.tracePath;if(!Array.isArray(E)||E.length<2){OW(`Skipping trace ${b?.pinIds.join(",")} because it has less than 2 points`);continue}let A=[];for(let P=0;P<E.length-1;P++)A.push({from:{x:E[P].x,y:E[P].y},to:{x:E[P+1].x,y:E[P+1].y}});let B=null,w;if(Array.isArray(b?.pins)&&b.pins.length===2){let P=s.get(b.pins[0]?.pinId),N=s.get(b.pins[1]?.pinId);if(P&&N){for(let O of[P,N])p.schematic_port.get(O)&&p.schematic_port.update(O,{is_connected:!0});w=l.get(String(b.userNetId))}}B||(B=`solver_${b?.mspPairId}`,w=l.get(String(b.userNetId))),f.push({source_trace_id:B,edges:A,subcircuit_connectivity_map_key:w})}OW(`Applying ${f.length} traces from SchematicTraceSolver output`);let m=KVt(f.map(b=>({source_trace_id:b.source_trace_id,edges:b.edges}))),D=ZVt(m);for(let b of m)p.schematic_trace.insert({source_trace_id:b.source_trace_id,edges:b.edges,junctions:D[b.source_trace_id]??[],subcircuit_connectivity_map_key:f.find(E=>E.source_trace_id===b.source_trace_id)?.subcircuit_connectivity_map_key})}var eGt=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"}},tGt=n=>{for(let a of n){let s=a._getDirectlyConnectedTraces();for(let l of s){let p=l._parsedProps.schDisplayLabel;if(p)return{name:p,wasAssignedDisplayLabel:!0}}}return{name:n.map(a=>a._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},LW=(0,OBe.default)("Group_doInitialSchematicTraceRender");function rGt(n){let{group:e,solver:a,sckToSourceNet:s,allScks:l,allSourceAndSchematicPortIdsInScope:p,schPortIdToSourcePortId:x,userNetIdToSck:f,pinIdToSchematicPortId:m,schematicPortIdsWithPreExistingNetLabels:D,schematicPortIdsWithRoutedTraces:b}=n,{db:E}=e.root,A=a.netLabelPlacementSolver?.netLabelPlacements??[],B=a.mspConnectionPairSolver.globalConnMap;for(let w of A){LW(`processing placement: ${w.netId}`);let P=B.getIdsConnectedToNet(w.globalConnNetId).find(Q=>f.get(Q)),N=f.get(P),O=w.anchorPoint,$=w.orientation,ee=eGt($),X=N?s.get(N):void 0,te=w.pinIds.map(Q=>m.get(Q));if(te.some(Q=>D.has(Q))){LW(`skipping net label placement for "${w.netId}" REASON:schematic port has pre-existing net label`);continue}if(X){let Q=X.name,de=Qp({anchor_position:O,anchor_side:ee,text:Q});E.schematic_net_label.insert({text:Q,anchor_position:O,center:de,anchor_side:ee,...X?.source_net_id?{source_net_id:X.source_net_id}:{}});continue}let L=e.selectAll("port").filter(Q=>Q._getSubcircuitConnectivityKey()===N),{name:K,wasAssignedDisplayLabel:U}=tGt(L);if(!U&&te.some(Q=>b.has(Q))){LW(`skipping net label placement for "${w.netId}" REASON:schematic port has routed traces and no display label`);continue}let J=Qp({anchor_position:O,anchor_side:ee,text:K});E.schematic_net_label.insert({text:K,anchor_position:O,center:J,anchor_side:ee})}}var nGt=({allSourceAndSchematicPortIdsInScope:n,group:e,schPortIdToSourcePortId:a,sckToSourceNet:s,pinIdToSchematicPortId:l,schematicPortIdsWithPreExistingNetLabels:p})=>{let{db:x}=e.root;for(let f of Array.from(n)){let m=x.schematic_port.get(f);if(!m||m.is_connected)continue;let D=a.get(f);if(!D)continue;let E=x.source_port.get(D)?.subcircuit_connectivity_map_key;if(!E)continue;let A=s.get(E);if(!A||x.schematic_net_label.list().some(O=>Math.abs(O.anchor_position.x-m.center.x)<.1&&Math.abs(O.anchor_position.y-m.center.y)<.1?A.source_net_id&&O.source_net_id?O.source_net_id===A.source_net_id:O.text===(A.name||E):!1))continue;let w=A.name||A.source_net_id||E,P=$F(m.facing_direction||"right")||"right",N=Qp({anchor_position:m.center,anchor_side:P,text:w});x.schematic_net_label.insert({text:w,anchor_position:m.center,center:N,anchor_side:P,...A.source_net_id?{source_net_id:A.source_net_id}:{}})}},aGt=n=>{let e=new Set,a=n.selectAll("netlabel");for(let s of a){let l=s._getConnectedPorts();for(let p of l)p.schematic_port_id&&e.add(p.schematic_port_id)}return e},sGt=({solver:n,pinIdToSchematicPortId:e})=>{let a=n.schematicTraceLinesSolver.solvedTracePaths,s=new Set;for(let l of a)for(let p of l.pinIds){let x=e.get(p);x&&s.add(x)}return s},iGt=(0,NBe.default)("Group_doInitialSchematicTraceRender"),oGt=n=>{if(!n.root?._featureMspSchematicTraceRouting||!n.isSubcircuit||n.root?.schematicDisabled)return;let{inputProblem:e,pinIdToSchematicPortId:a,pairKeyToSourceTraceId:s,sckToSourceNet:l,allSourceAndSchematicPortIdsInScope:p,schPortIdToSourcePortId:x,displayLabelTraces:f,allScks:m,userNetIdToSck:D}=XVt(n),b=aGt(n);iGt.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(e,null,2)});let E=new uSe(e);E.solve();let A=sGt({solver:E,pinIdToSchematicPortId:a});QVt({group:n,solver:E,pinIdToSchematicPortId:a,userNetIdToSck:D}),rGt({group:n,solver:E,sckToSourceNet:l,allSourceAndSchematicPortIdsInScope:p,schPortIdToSourcePortId:x,pinIdToSchematicPortId:a,allScks:m,userNetIdToSck:D,schematicPortIdsWithPreExistingNetLabels:b,schematicPortIdsWithRoutedTraces:A}),nGt({group:n,allSourceAndSchematicPortIdsInScope:p,schPortIdToSourcePortId:x,sckToSourceNet:l,pinIdToSchematicPortId:a,schematicPortIdsWithPreExistingNetLabels:b})},zg=class extends Za{constructor(){super(...arguments);q(this,"pcb_group_id",null);q(this,"schematic_group_id",null);q(this,"subcircuit_id",null);q(this,"_hasStartedAsyncAutorouting",!1);q(this,"_asyncAutoroutingResult",null);q(this,"unnamedElementCounter",{})}get config(){return{zodProps:z_e,componentName:"Group"}}doInitialSourceGroupRender(){let{db:e}=this.root,a=e.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit});this.source_group_id=a.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${a.source_group_id}`,e.source_group.update(a.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:e}=this.root;for(let a of this.children)e.source_component.update(a.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:e}=this.root,a=this.parent?.getGroup?.();if(a?.source_group_id&&e.source_group.update(this.source_group_id,{parent_source_group_id:a.source_group_id}),!this.isSubcircuit)return;let s=this.parent?.getSubcircuit?.()?.subcircuit_id;s&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:s})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:a.autorouter?{trace_clearance:a.autorouter.traceClearance}:void 0});this.pcb_group_id=s.pcb_group_id;for(let l of this.children)e.pcb_component.update(l.pcb_component_id,{pcb_group_id:s.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,a=this._parsedProps,s=rK(this.children);if(this.pcb_group_id){let l=s.width,p=s.height,x=(s.minX+s.maxX)/2,f=(s.minY+s.maxY)/2;if(this.isSubcircuit){let{padLeft:b,padRight:E,padTop:A,padBottom:B}=this._resolvePcbPadding();l+=b+E,p+=A+B,x+=(E-b)/2,f+=(A-B)/2}let D=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0?e.pcb_group.get(this.pcb_group_id)?.center??{x,y:f}:{x,y:f};e.pcb_group.update(this.pcb_group_id,{width:Number(a.width??l),height:Number(a.height??p),center:D})}}getNextAvailableName(e){var a,s;return(a=this.unnamedElementCounter)[s=e.lowercaseComponentName]??(a[s]=1),`unnamed_${e.lowercaseComponentName}${this.unnamedElementCounter[e.lowercaseComponentName]++}`}_resolvePcbPadding(){let e=this._parsedProps,a=e.pcbLayout,s=E=>{let A=a?.[E],B=e[E];if(typeof A=="number")return A;if(typeof B=="number")return B},l=s("padding")??0,p=s("paddingX"),x=s("paddingY"),f=s("paddingLeft")??p??l,m=s("paddingRight")??p??l,D=s("paddingTop")??x??l,b=s("paddingBottom")??x??l;return{padLeft:f,padRight:m,padTop:D,padBottom:b}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:e}=this,{db:a}=this.root,s=e;if(!this.isSubcircuit)return;let l=s.manualEdits?.manual_trace_hints;if(l)for(let p of l)this.add(new aK({for:p.pcb_port_selector,offsets:p.offsets}))}doInitialSourceAddConnectivityMapKey(){BVt(this)}_areChildSubcircuitsRouted(){let e=this.selectAll("group").filter(a=>a.isSubcircuit);for(let a of e)if(a._shouldRouteAsync()&&!a._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,Og.default)("tscircuit:core:_hasTracesToRoute"),a=this.selectAll("trace");return e(`[${this.getString()}] has ${a.length} traces to route`),a.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:e}=this.root,a=(0,Og.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),s=this._parsedProps,l=this._getAutorouterConfig(),p=l.serverUrl,x=l.serverMode,f=(b,E)=>(a("fetching",b),E.headers&&(E.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(b,E)),m=this.root.db.toArray().filter(b=>b.type.startsWith("source_")||b.type.startsWith("pcb_"));if(x==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:E}=await f(`${p}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:YW({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(A=>A.json());this._asyncAutoroutingResult=E,this._markDirty("PcbTraceRender");return}let{autorouting_result:b}=await f(`${p}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:m,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(E=>E.json());this._asyncAutoroutingResult=b,this._markDirty("PcbTraceRender");return}let{autorouting_job:D}=await f(`${p}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:m,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:l.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(b=>b.json());for(;;){let{autorouting_job:b}=await f(`${p}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:D.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(E=>E.json());if(b.is_finished){let{autorouting_job_output:E}=await f(`${p}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:D.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(A=>A.json());this._asyncAutoroutingResult={output_pcb_traces:E.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(b.has_error){let E=new jF(`Autorouting job failed: ${JSON.stringify(b.error)}`);throw e.pcb_autorouting_error.insert({pcb_error_id:D.autorouting_job_id,error_type:"pcb_autorouting_error",message:E.message}),E}await new Promise(E=>setTimeout(E,100))}}async _runLocalAutorouting(){let{db:e}=this.root,a=this._parsedProps,s=(0,Og.default)("tscircuit:core:_runLocalAutorouting");s(`[${this.getString()}] starting local autorouting`);let l=this._getAutorouterConfig(),{simpleRouteJson:p}=YW({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(s.enabled){let m=ZY(p);m.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(m)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:p});let x;l.algorithmFn?x=await l.algorithmFn(p):x=new bVt(p,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity});let f=new Promise((m,D)=>{x.on("complete",b=>{s(`[${this.getString()}] local autorouting complete`),m(b.traces)}),x.on("error",b=>{s(`[${this.getString()}] local autorouting error: ${b.error.message}`),D(b.error)})});x.on("progress",m=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...m})}),x.start();try{let m=await f;this._asyncAutoroutingResult={output_pcb_traces:m},this._markDirty("PcbTraceRender")}catch(m){let{db:D}=this.root;throw D.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:m instanceof Error?m.message:String(m)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:m instanceof Error?m.message:String(m)},simpleRouteJson:p}),m}finally{x.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let e=(0,Og.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(){oGt(this)}updatePcbTraceRender(){let e=(0,Og.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:a}=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:a}=this._asyncAutoroutingResult.output_simple_route_json;if(a)for(let s of a){let l=e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:s.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;let{db:a}=this.root;for(let s of e)if(s.type==="pcb_trace"){if(s.subcircuit_id=this.subcircuit_id,s.connection_name){let l=s.connection_name;s.source_trace_id=l}a.pcb_trace.insert(s)}for(let s of e)if(s.type!=="pcb_via"&&s.type==="pcb_trace")for(let l of s.route)l.route_type==="via"&&a.pcb_via.insert({pcb_trace_id:s.pcb_trace_id,x:l.x,y:l.y,hole_diameter:.3,outer_diameter:.6,layers:[l.from_layer,l.to_layer],from_layer:l.from_layer,to_layer:l.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=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=s.schematic_group_id;for(let l of this.children)l.schematic_component_id&&e.schematic_component.update(l.schematic_component_id,{schematic_group_id:s.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 a=this.children.some(l=>{let p=l._parsedProps;return p?.schX!==void 0||p?.schY!==void 0}),s=(e.manualEdits?.schematic_placements?.length??0)>0;return!a&&!s?"match-adapt":"relative"}doInitialSchematicLayout(){let e=this._getSchematicLayoutMode();e==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),e==="grid"&&this._doInitialSchematicLayoutGrid(),e==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){AVt(this)}_doInitialSchematicLayoutMatchpack(){SVt(this)}_doInitialSchematicLayoutGrid(){wVt(this)}_doInitialSchematicLayoutFlex(){TVt(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 a=e.pcbX!==void 0||e.pcbY!==void 0,s=(e.manualEdits?.pcb_placements?.length??0)>0;if(this.children.some(x=>{let f=x._parsedProps;return f?.pcbX!==void 0||f?.pcbY!==void 0}))return"none";let p=this.children.reduce((x,f)=>{let m=f._parsedProps,D=m?.pcbX!==void 0||m?.pcbY!==void 0;return x+(D?0:1)},0);return!a&&!s&&p>1?"pack":"none"}doInitialPcbLayout(){let e=this._getPcbLayoutMode();e==="grid"?this._doInitialPcbLayoutGrid():e==="pack"?this._doInitialPcbLayoutPack():e==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){PVt(this)}_doInitialPcbLayoutPack(){VVt(this)}_doInitialPcbLayoutFlex(){GVt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,a=this._parsedProps;if(!a.border)return;let s=typeof a.schWidth=="number"?a.schWidth:void 0,l=typeof a.schHeight=="number"?a.schHeight:void 0,p=typeof a.schPadding=="number"?a.schPadding:0,x=typeof a.schPaddingLeft=="number"?a.schPaddingLeft:p,f=typeof a.schPaddingRight=="number"?a.schPaddingRight:p,m=typeof a.schPaddingTop=="number"?a.schPaddingTop:p,D=typeof a.schPaddingBottom=="number"?a.schPaddingBottom:p,b=this.schematic_group_id?e.schematic_group.get(this.schematic_group_id):null;if(b&&(s===void 0&&typeof b.width=="number"&&(s=b.width),l===void 0&&typeof b.height=="number"&&(l=b.height)),s===void 0||l===void 0)return;let E=b?.center??this._getGlobalSchematicPositionBeforeLayout(),A=E.x-s/2-x,B=E.y-l/2-D,w=s+x+f,P=l+m+D;e.schematic_box.insert({width:w,height:P,x:A,y:B,is_dashed:a.border?.dashed??!1})}_determineSideFromPosition(e,a){if(!e.center||!a.center)return"left";let s=e.center.x-a.center.x,l=e.center.y-a.center.y;return Math.abs(s)>Math.abs(l)?s>0?"right":"left":l>0?"bottom":"top"}_calculateSchematicBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let a=1/0,s=-1/0,l=1/0,p=-1/0;for(let f of e)a=Math.min(a,f.centerX),s=Math.max(s,f.centerX),l=Math.min(l,f.centerY),p=Math.max(p,f.centerY);let x=2;return{minX:a-x,maxX:s+x,minY:l-x,maxY:p+x}}_getAutorouterConfig(){let e=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return qVt(e)}_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 a=new Map;for(let s of this.children)if(!s.isSubcircuit&&s._parsedProps.name){let l=a.get(s._parsedProps.name)||[];l.push(s),a.set(s._parsedProps.name,l)}for(let[s,l]of a.entries())l.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${s}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:l.map(p=>p.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:e}=this.root,a=e;for(let s of a.schematic_net_label.list()){let l=a.source_net.get(s.source_net_id),p=s.text||l?.name||"";if(s.anchor_side==="top"&&/^gnd/i.test(p)){a.schematic_net_label.update(s.schematic_net_label_id,{symbol_name:"ground_down"});continue}s.anchor_side==="bottom"&&/^v/i.test(p)&&a.schematic_net_label.update(s.schematic_net_label_id,{symbol_name:"vcc_up"})}}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(e){return super._repositionOnPcb(e)}},LBe=class extends zg{constructor(){super(...arguments);q(this,"pcb_board_id",null);q(this,"_drcChecksComplete",!1);q(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:FY}}get boardThickness(){let{_parsedProps:e}=this;return 1.4}get allLayers(){return(this._parsedProps.layers??2)===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db:e}=this.root,{_parsedProps:a}=this;if(a.width&&a.height)return;let s=1/0,l=1/0,p=-1/0,x=-1/0,f=PBe(e,this.subcircuit_id),m=new Set([this.subcircuit_id,...f]),D=e.pcb_component.list().filter(ee=>ee.subcircuit_id&&m.has(ee.subcircuit_id)),b=e.pcb_group.list().filter(ee=>ee.subcircuit_id&&m.has(ee.subcircuit_id)),E=!1,A=(ee,X,te)=>{X===0||te===0||(E=!0,s=Math.min(s,ee.x-X/2),l=Math.min(l,ee.y-te/2),p=Math.max(p,ee.x+X/2),x=Math.max(x,ee.y+te/2))};for(let ee of D)A(ee.center,ee.width,ee.height);for(let ee of b)A(ee.center,ee.width,ee.height);let B=2,w=E?p-s+B*2:0,P=E?x-l+B*2:0,N={x:E?(s+p)/2+(a.outlineOffsetX??0):a.outlineOffsetX??0,y:E?(l+x)/2+(a.outlineOffsetY??0):a.outlineOffsetY??0},O=a.width??w,$=a.height??P;e.pcb_board.update(this.pcb_board_id,{width:O,height:$,center:N})}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let e=this.root?.platform;if(!e?.printBoardInformationToSilkscreen)return;let a=this.root.db.pcb_board.get(this.pcb_board_id);if(!a)return;let s=[];if(e.projectName&&s.push(e.projectName),e.version&&s.push(`v${e.version}`),e.url&&s.push(e.url),s.length===0)return;let l=s.join(`
|
|
1039
|
+
`),f={x:a.center.x+a.width/2-.25,y:a.center.y-a.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:l,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:f})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=a.width??0,l=a.height??0,p={x:(a.pcbX??0)+(a.outlineOffsetX??0),y:(a.pcbY??0)+(a.outlineOffsetY??0)};if(a.outline){let f=a.outline.map(B=>B.x),m=a.outline.map(B=>B.y),D=Math.min(...f),b=Math.max(...f),E=Math.min(...m),A=Math.max(...m);s=b-D,l=A-E,p={x:(D+b)/2+(a.outlineOffsetX??0),y:(E+A)/2+(a.outlineOffsetY??0)}}let x=e.pcb_board.insert({center:p,thickness:this.boardThickness,num_layers:this.allLayers.length,width:s,height:l,outline:a.outline?.map(f=>({x:f.x+(a.outlineOffsetX??0),y:f.y+(a.outlineOffsetY??0)})),material:a.material});this.pcb_board_id=x.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)}_computePcbGlobalTransformBeforeLayout(){return _i()}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 a=pSe(e.toArray());for(let l of a)e.pcb_trace_error.insert(l);let s=dSe(e.toArray());for(let l of s)e.pcb_port_not_connected_error.insert(l)}_emitRenderLifecycleEvent(e,a){super._emitRenderLifecycleEvent(e,a),a==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e})}},uGt=new Proxy({},{get:(n,e)=>e}),od=uGt,$Be=class extends Za{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:J_e,sourceFtype:od.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,a=typeof e=="string"?e:`${js(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${a}/${js(this._parsedProps.maxVoltageRating)}V`:a}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new zc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new zc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,capacitance:a.capacitance,max_voltage_rating:a.maxVoltageRating,max_decoupling_trace_length:a.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!a.polarized});this.source_component_id=s.source_component_id}},HS=class extends Za{constructor(e){super(e);q(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:rg,shouldRenderAsSchematicBox:!0}}initPorts(e={}){super.initPorts(e);let{_parsedProps:a}=this;if(a.externallyConnectedPins){let s=new Set;for(let[l,p]of a.externallyConnectedPins)s.add(l),s.add(p);for(let l of s)if(!this.children.find(x=>x instanceof Ii&&x.isMatchingAnyOf([l]))){let x=l.match(/^pin(\d+)$/);if(x){let f=parseInt(x[1]);this.add(new Ii({pinNumber:f,aliases:[l]}))}else this.add(new Ii({name:l,aliases:[l]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:e}=this;e?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:e}=this;if(e.externallyConnectedPins)for(let[a,s]of e.externallyConnectedPins)this.add(new zc({from:`${this.getSubcircuitSelector()} > port.${a}`,to:`${this.getSubcircuitSelector()} > port.${s}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:e}=this.root,{pinAttributes:a}=this.props;if(!a)return;let s=null,l=null,p,x=this.selectAll("port");for(let E of x)for(let A of E.getNameAndAliases())if(a[A]){let B=a[A];B.providesPower&&(s=E,p=B.providesVoltage),B.providesGround&&(l=E)}if(!s||!l||p===void 0)return;let f=e.source_port.get(s.source_port_id);if(!f?.subcircuit_connectivity_map_key)return;let m=e.source_port.get(l.source_port_id);if(!m?.subcircuit_connectivity_map_key)return;let D=e.source_net.getWhere({subcircuit_connectivity_map_key:f.subcircuit_connectivity_map_key}),b=e.source_net.getWhere({subcircuit_connectivity_map_key:m.subcircuit_connectivity_map_key});!D||!b||e.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:s.source_port_id,positive_source_net_id:D.source_net_id,negative_source_port_id:l.source_port_id,negative_source_net_id:b.source_net_id,voltage:p})}},zBe=class extends HS{constructor(n){super(n)}get config(){return{...super.config,componentName:"Pinout",zodProps:q_e}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=a.source_component_id}},qBe=class extends Za{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"anode",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"cathode",this.portMap.pin2)}get config(){let e={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},a=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:a?e[a]:this.props.symbolName??"diode",componentName:"Diode",zodProps:pAe,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},UBe=class extends Za{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:V_e,sourceFtype:od.simple_fuse}}_getSchematicSymbolDisplayValue(){let n=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,a=typeof n=="string"?parseFloat(n):n,s=typeof e=="string"?parseFloat(e):e;return`${js(a)}A / ${js(s)}V`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=typeof e.currentRating=="string"?parseFloat(e.currentRating):e.currentRating,s=typeof e.voltageRating=="string"?parseFloat(e.voltageRating):e.voltageRating,l=n.source_component.insert({name:this.name,ftype:od.simple_fuse,current_rating_amps:a,voltage_rating_volts:s,display_current_rating:`${js(a)}A`,display_voltage_rating:`${js(s)}V`});this.source_component_id=l.source_component_id}},VBe=class extends Za{constructor(){super(...arguments);q(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:vY,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let a=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),s=this._parsedProps.schDirection??"right";return{leftSize:s==="left"?a:0,rightSize:s==="right"?a:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,a=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),s={};for(let x=0;x<a.length;x++){let f=a[x],m=e.source_port.get(f.source_port_id),D="";if(typeof m?.pin_number=="number")D=m.pin_number.toString();else if(Array.isArray(m?.port_hints)){let b=m.port_hints.find(E=>/^(pin)?\d+$/.test(E));b&&(/^pin\d+$/.test(b)?D=b.replace(/^pin/,""):D=b)}s[D]=f.pcb_port_id}let l=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),p=x=>{if(x&&typeof x=="string"&&x.startsWith("{PIN")){let f=x.replace("{PIN","").replace("}","");return s[f]||x}return x};for(let x of l)if(x.route)for(let f of x.route)f.route_type==="wire"&&(f.start_pcb_port_id=p(f.start_pcb_port_id),f.end_pcb_port_id=p(f.end_pcb_port_id))}},GBe=class extends Za{constructor(){super(...arguments);q(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(a=>a.componentName==="Port").map(a=>a.name);return e.length>0?[e]:[]}return this._parsedProps.bridgedPins??[]}get config(){let e=this._parsedProps??this.props,a=e.pinCount;if(e.pinCount==null&&!e.footprint&&(a=2),e.pinCount==null){let p=(e.bridgedPins??[]).flat().map(D=>this._getPinNumberFromBridgedPinName(D)).filter(D=>D!==null),x=p.length>0?Math.max(...p):0,f=e.pinLabels?Object.keys(e.pinLabels).length:0,m=Math.max(x,f);(m===2||m===3)&&(a=m),a==null&&e.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(a=this.getPortsFromFootprint().length)}let s="";a?s+=`solderjumper${a}`:s="solderjumper";let l=[];return Array.isArray(e.bridgedPins)&&e.bridgedPins.length>0?l=Array.from(new Set(e.bridgedPins.flat().map(p=>this._getPinNumberFromBridgedPinName(p)).filter(p=>p!==null))).sort((p,x)=>p-x):e.bridged&&a&&(l=Array.from({length:a},(p,x)=>x+1)),l.length>0&&(s+=`_bridged${l.join("")}`),{schematicSymbolName:e.symbolName??s,componentName:"SolderJumper",zodProps:U_e,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let a=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);a==null&&!this._parsedProps.footprint&&(a=2);let s=this._parsedProps.schDirection??"right";return{leftSize:s==="left"?a:0,rightSize:s==="right"?a:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,a=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),s={};for(let x=0;x<a.length;x++){let f=a[x],m=e.source_port.get(f.source_port_id),D="";if(typeof m?.pin_number=="number")D=m.pin_number.toString();else if(Array.isArray(m?.port_hints)){let b=m.port_hints.find(E=>/^(pin)?\d+$/.test(E));b&&(/^pin\d+$/.test(b)?D=b.replace(/^pin/,""):D=b)}s[D]=f.pcb_port_id}let l=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),p=x=>{if(x&&typeof x=="string"&&x.startsWith("{PIN")){let f=x.replace("{PIN","").replace("}","");return s[f]||x}return x};for(let x of l)if(x.route)for(let f of x.route)f.route_type==="wire"&&(f.start_pcb_port_id=p(f.start_pcb_port_id),f.end_pcb_port_id=p(f.end_pcb_port_id))}},XBe=class extends Za{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"anode",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"cathode",this.portMap.pin2)}get config(){let e={laser:"laser_diode"},a=this.props.laser?"laser":null;return{schematicSymbolName:a?e[a]:this.props.symbolName??"led",componentName:"Led",zodProps:fAe,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_led",name:this.name,wave_length:a.wavelength,color:a.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},YBe=class extends Za{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"positive",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:vAe,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Ii({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Ii({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:a.voltage,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},cGt=fs.extend({voltage:zs.optional(),frequency:Nc.optional(),peakToPeakVoltage:zs.optional(),waveShape:C.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Ba.optional(),dutyCycle:C.number().optional()}),HBe=class extends Za{constructor(){super(...arguments);q(this,"terminal1",this.portMap.terminal1);q(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:cGt,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(e){if(!e.startsWith("Pcb"))for(let a of this.children)a.runRenderPhaseForChildren(e),a.runRenderPhase(e)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:a.voltage,frequency:a.frequency,peak_to_peak_voltage:a.peakToPeakVoltage,wave_shape:a.waveShape,phase:a.phase,duty_cycle:a.dutyCycle,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialSimulationRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.portMap.terminal1,l=this.portMap.terminal2;e.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:s.source_port_id,terminal2_source_port_id:l.source_port_id,voltage:a.voltage,frequency:a.frequency,peak_to_peak_voltage:a.peakToPeakVoltage,wave_shape:a.waveShape,phase:a.phase,duty_cycle:a.dutyCycle})}},WBe=class extends Za{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:X_e,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${js(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 zc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new zc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new zc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new zc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,resistance:a.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}},lGt=["leftedge","rightedge","topedge","bottomedge","center"],KBe=class extends ma{get config(){return{componentName:"Constraint",zodProps:Q_e}}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 a(s){let l=s.split(" ").pop(),p=lGt.includes(l)?l:void 0,x=p?s.replace(` ${p}`,""):s,f=e.selectOne(x,{pcbPrimitive:!0});f&&n.push({selector:s,component:f,componentSelector:x,edge:p})}for(let s of["left","right","top","bottom"])s in this._parsedProps&&a(this._parsedProps[s]);if("for"in this._parsedProps)for(let s of this._parsedProps.for)a(s);return{componentsWithSelectors:n}}},JBe=class extends ma{constructor(){super(...arguments);q(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:DAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,a=this.getSubcircuit(),{_parsedProps:s}=this,l=s.layer??"top";if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenPath. Must be "top" or "bottom".`);let p=this._computePcbGlobalTransformBeforeLayout(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_fabrication_note_path.insert({pcb_component_id:x,layer:l,color:s.color,route:s.route.map(m=>{let D=rs(p,{x:m.x,y:m.y});return{...m,x:D.x,y:D.y}}),stroke_width:s.strokeWidth??.1,subcircuit_id:a?.subcircuit_id??void 0});this.fabrication_note_path_id=f.pcb_fabrication_note_path_id}},ZBe=class extends ma{get config(){return{componentName:"FabricationNoteText",zodProps:gAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:n}=this.root,{_parsedProps:e}=this,a=this.getPrimitiveContainer(),s=this.getSubcircuit();n.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:e.pcbX??0,y:e.pcbY??0},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:e.text??"",pcb_component_id:a.pcb_component_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},QBe=class extends zg{constructor(n){super({...n,subcircuit:!0})}},e9e=class extends zg{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 a=n.pcb_group.get(this.pcb_group_id),s=e.paddingLeft??e.padding??0,l=e.paddingRight??e.padding??0,p=e.paddingTop??e.padding??0,x=e.paddingBottom??e.padding??0;n.pcb_group.update(this.pcb_group_id,{width:a.width+s+l,height:a.height+p+x,center:{x:a.center.x+(l-s)/2,y:a.center.y+(p-x)/2}})}},t9e=class extends ma{constructor(){super(...arguments);q(this,"pcb_breakout_point_id",null);q(this,"matchedPort",null);q(this,"matchedNet",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:FAe}}_matchConnection(){let{connection:e}=this._parsedProps,a=this.getSubcircuit();a&&(this.matchedPort=a.selectOne(e,{type:"port"}),this.matchedPort||(this.matchedNet=a.selectOne(e,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${e}"`))}_getSourceTraceIdForPort(e){let{db:a}=this.root;return a.source_trace.list().find(l=>l.connected_source_port_ids.includes(e.source_port_id))?.source_trace_id}_getSourceNetIdForPort(e){let{db:a}=this.root;return a.source_trace.list().find(l=>l.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:a=0,pcbY:s=0}=this._parsedProps,l=this.parent?.getGroup(),p=this.getSubcircuit();if(!l||!l.pcb_group_id)return;let x=e.pcb_breakout_point.insert({pcb_group_id:l.pcb_group_id,subcircuit_id:p?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:a,y:s});this.pcb_breakout_point_id=x.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:e=0,pcbY:a=0}=this._parsedProps;return{center:{x:e,y:a},bounds:{left:e,top:a,right:e,bottom:a},width:0,height:0}}_setPositionFromLayout(e){let{db:a}=this.root;this.pcb_breakout_point_id&&a.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:e.x,y:e.y})}getPcbSize(){return{width:0,height:0}}},r9e=class extends ma{constructor(){super(...arguments);q(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:oAe}}_getAnchorSide(){let{_parsedProps:e}=this;if(e.anchorSide)return e.anchorSide;if(!this._resolveConnectsTo())return"right";let s=this._getGlobalSchematicPositionBeforeLayout(),l=this._getConnectedPorts();if(l.length===0)return"right";let p=l[0]._getGlobalSchematicPositionBeforeLayout(),x=p.x-s.x,f=p.y-s.y;if(Math.abs(x)>Math.abs(f)){if(x>0)return"right";if(x<0)return"left"}else{if(f>0)return"top";if(f<0)return"bottom"}return"right"}_getConnectedPorts(){let e=this._resolveConnectsTo();if(!e)return[];let a=[];for(let s of e){let l=this.getSubcircuit().selectOne(s);l&&a.push(l)}return a}computeSchematicPropsTransform(){let{_parsedProps:e}=this;if(e.schX===void 0&&e.schY===void 0){let a=this._getConnectedPorts();if(a.length>0){let s=a[0]._getGlobalSchematicPositionBeforeLayout(),l=rs(this.parent?.computeSchematicGlobalTransform?.()??_i(),{x:0,y:0});return ka(s.x-l.x,s.y-l.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalSchematicPositionBeforeLayout(),l=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),p=a.anchorSide??"right",x=Qp({anchor_position:s,anchor_side:p,text:a.net}),f=e.schematic_net_label.insert({text:a.net,source_net_id:l.source_net_id,anchor_position:s,center:x,anchor_side:this._getAnchorSide()});this.source_net_label_id=f.source_net_id}_resolveConnectsTo(){let{_parsedProps:e}=this,a=e.connectsTo??e.connection;if(Array.isArray(a))return a;if(typeof a=="string")return[a]}_getNetName(){let{_parsedProps:e}=this;return e.net}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;e.net&&ZW(this,[`net.${e.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let e=this._resolveConnectsTo();if(e)for(let a of e)this.add(new zc({from:a,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:e}=this.root,a=this._resolveConnectsTo();if(!a||a.length===0)return;let s=this._getGlobalSchematicPositionBeforeLayout(),l=this._getAnchorSide(),x={left:"x-",right:"x+",top:"y+",bottom:"y-"}[l],f=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let m of a){let D=this.getSubcircuit().selectOne(m,{type:"port"});if(!D||!D.schematic_port_id)continue;let b=!1;if(f?.source_net_id){let O=e.source_trace.list().find($=>$.connected_source_net_ids?.includes(f.source_net_id)&&$.connected_source_port_ids?.includes(D.source_port_id??""));if(O&&(b=e.schematic_trace.list().some($=>$.source_trace_id===O.source_trace_id)),b)continue}let E=D._getGlobalSchematicPositionAfterLayout(),A=VW(D.facingDirection??"right")??"x+",B=sg({x:E.x,y:E.y,facingDirection:A},{x:s.x,y:s.y,facingDirection:x});if(!Array.isArray(B)||B.length<2)continue;let w=[];for(let O=0;O<B.length-1;O++)w.push({from:{x:B[O].x,y:B[O].y},to:{x:B[O+1].x,y:B[O+1].y}});let P,N;if(f?.source_net_id&&D.source_port_id){let O=e.source_trace.list().find($=>$.connected_source_net_ids?.includes(f.source_net_id)&&$.connected_source_port_ids?.includes(D.source_port_id));P=O?.source_trace_id,N=O?.subcircuit_connectivity_map_key||e.source_net.get(f.source_net_id)?.subcircuit_connectivity_map_key}e.schematic_trace.insert({source_trace_id:P,edges:w,junctions:[],subcircuit_connectivity_map_key:N}),e.schematic_port.update(D.schematic_port_id,{is_connected:!0})}}},n9e=class extends ma{constructor(){super(...arguments);q(this,"pcb_silkscreen_circle_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:IAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenCircle. Must be "top" or "bottom".`);let p=this._computePcbGlobalTransformBeforeLayout(),x=this.getSubcircuit(),f=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=e.pcb_silkscreen_circle.insert({pcb_component_id:f,layer:l,center:{x:a.pcbX??0,y:a.pcbY??0},radius:a.radius,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:a.strokeWidth??.1});this.pcb_silkscreen_circle_id=m.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:e}=this,a=e.radius*2;return{width:a,height:a}}},a9e=class extends ma{constructor(){super(...arguments);q(this,"pcb_silkscreen_rect_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:PAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenRect. Must be "top" or "bottom".`);let p=this.getSubcircuit(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_silkscreen_rect.insert({pcb_component_id:x,layer:l,center:{x:a.pcbX??0,y:a.pcbY??0},width:a.width,height:a.height,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:a.strokeWidth??.1});this.pcb_silkscreen_rect_id=f.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},s9e=class extends ma{constructor(){super(...arguments);q(this,"pcb_silkscreen_line_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:TAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenLine. Must be "top" or "bottom".`);let p=this.getSubcircuit(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_silkscreen_line.insert({pcb_component_id:x,layer:l,x1:a.x1,y1:a.y1,x2:a.x2,y2:a.y2,stroke_width:a.strokeWidth??.1,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:p?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=f.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:e}=this,a=Math.abs(e.x2-e.x1),s=Math.abs(e.y2-e.y1);return{width:a,height:s}}},i9e=class extends ma{constructor(e){super(e);q(this,"pcb_via_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0);q(this,"source_manually_placed_via_id",null);let a=this._getLayers();this._parsedProps.layers=a,this.initPorts()}get config(){return{componentName:"Via",zodProps:yAe}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:e}=this;return{width:e.outerDiameter,height:e.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_via.get(this.pcb_via_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y-s.height/2,right:a.x+s.width/2,bottom:a.y+s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}_getLayers(){let{fromLayer:e="top",toLayer:a="bottom"}=this._parsedProps;return e===a?[e]:[e,a]}initPorts(){let e=this._parsedProps.layers;for(let s of e){let l=new Ii({name:s,layer:s});l.registerMatch(this),this.add(l)}let a=new Ii({name:"pin1"});a.registerMatch(this),this.add(a)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.getSubcircuit(),p=e.pcb_component.insert({center:s,width:a.outerDiameter,height:a.outerDiameter,layer:a.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:l?.subcircuit_id??void 0});this.pcb_component_id=p.pcb_component_id}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getGroup(),l=this.getSubcircuit(),p=e.source_manually_placed_via.insert({source_group_id:s?.source_group_id,source_net_id:a.net??"",subcircuit_id:l?.subcircuit_id??void 0});this.source_component_id=p.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.getSubcircuit(),p=e.pcb_via.insert({x:s.x,y:s.y,hole_diameter:a.holeDiameter,outer_diameter:a.outerDiameter,layers:["bottom","top"],from_layer:a.fromLayer||"bottom",to_layer:a.toLayer||"top",subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=p.pcb_via_id}},o9e=class extends Za{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:sAe,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,a=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=a.source_component_id}},u9e=class extends Za{get config(){return{componentName:"PinHeader",zodProps:iAe,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,a=this._parsedProps.platedDiameter,s=this._parsedProps.pitch,l=this._parsedProps.showSilkscreenPinLabels;if(n>0){let p;if(s)!e&&!a?p=`pinrow${n}_p${s}`:p=`pinrow${n}_p${s}_id${e}_od${a}`;else if(!e&&!a)p=`pinrow${n}`;else return null;return l!==!0&&(p+="_nopinlabels"),p}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 a=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[e-1]:this._parsedProps.pinLabels?.[`pin${e}`];if(a){let s=Array.isArray(a)?a[0]:a,l=Array.isArray(a)?a.slice(1):[];this.add(new Ii({pinNumber:e,name:s,aliases:[`pin${e}`,...l]}))}else this.add(new Ii({pinNumber:e,name:`pin${e}`}))}}_getSchematicPortArrangement(){let n=this._parsedProps.pinCount??1,e=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",a=this._parsedProps.schPinArrangement;return e==="left"?{leftSide:{direction:a?.leftSide?.direction??"top-to-bottom",pins:a?.leftSide?.pins??Array.from({length:n},(s,l)=>`pin${l+1}`)}}:{rightSide:{direction:a?.rightSide?.direction??"top-to-bottom",pins:a?.rightSide?.pins??Array.from({length:n},(s,l)=>`pin${l+1}`)}}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=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=a.source_component_id}};function dGt(n){switch(n){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var c9e=class extends Za{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??dGt(this.props.pinVariant),zodProps:K_e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=e.pinVariant||"no_ground",s=n.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:a,are_pins_interchangeable:a==="no_ground"||a==="ground_pin"});this.source_component_id=s.source_component_id}_getSchematicSymbolDisplayValue(){let n=`${js(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${js(this._parsedProps.loadCapacitance)}F`:n}},l9e=class extends Za{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:dAe,sourceFtype:od.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${js(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({name:this.name,ftype:od.simple_inductor,inductance:a.inductance,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}};function pGt(n){switch(n){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var d9e=class extends Za{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??pGt(this.props.pinVariant),zodProps:H_e,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${js(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=e.pinVariant||"two_pin",s=n.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:e.maxResistance,pin_variant:a,are_pins_interchangeable:a==="two_pin"});this.source_component_id=s.source_component_id}},p9e=class extends Za{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:uAe,sourceFtype:od.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let n=Ps[this._getSchematicSymbolNameOrThrow()],e=n.ports.find(D=>D.labels.includes("1")),a=n.ports.find(D=>D.labels.includes("2")),s=this.selectAll("port"),l=s.find(D=>D.props.pinNumber===1),p=s.find(D=>D.props.pinNumber===2),x=s.find(D=>D.props.pinNumber===3),f=s.find(D=>D.props.pinNumber===4),{internallyConnectedPins:m}=this._parsedProps;l.schematicSymbolPortDef=e,(!m||m.length===0)&&(p.schematicSymbolPortDef=a);for(let[D,b]of[[2,p],[3,x],[4,f]]){let E=m?.find(([B,w])=>B===`pin${D}`||w===`pin${D}`);if(!E){b.schematicSymbolPortDef=a;break}(E?.[0]===`pin${D}`?E[1]:E?.[0])!=="pin1"&&(b.schematicSymbolPortDef=a)}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({name:this.name,ftype:od.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}},x9e=class extends Za{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:W_e,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=`${js(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${js(this._parsedProps.loadCapacitance)}F`:n}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=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=a.source_component_id}},f9e=class extends Za{constructor(){super(...arguments);q(this,"emitter",this.portMap.pin1);q(this,"collector",this.portMap.pin2);q(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:cAe,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:a}=this,s=e.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:a.type});this.source_component_id=s.source_component_id}},h9e=class extends Za{get config(){let n=this.props.mosfetMode==="depletion"?"d":"e",a=`${this.props.channelType}_channel_${n}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??a,zodProps:lAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=a.source_component_id}},m9e=class extends Za{_getSwitchType(){let{spst:n,spdt:e,dpst:a,dpdt:s,type:l}=this._parsedProps??{};return s?"dpdt":n?"spst":e?"spdt":a?"dpst":l??"spst"}get config(){let n=this._getSwitchType(),{isNormallyClosed:e}=this._parsedProps??{},s={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"}[n]??"spst_switch";return{componentName:"Switch",schematicSymbolName:this.props.symbolName??s,zodProps:mAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({ftype:"simple_switch",name:this.name,switch_type:e.type,is_normally_closed:e.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=a.source_component_id}},$W={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},g9e=class extends Za{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:bAe,sourceFtype:od.simple_test_point}}_getPropsWithDefaults(){let{padShape:n,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:p}=this._parsedProps;return!a&&e&&(a="through_hole"),a??(a="through_hole"),n??(n="circle"),a==="pad"?n==="circle"?s??(s=$W.SMT_CIRCLE_DIAMETER):n==="rect"&&(l??(l=$W.SMT_RECT_SIZE),p??(p=l)):a==="through_hole"&&(e??(e=$W.HOLE_DIAMETER)),{padShape:n,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:p}}_getImpliedFootprintString(){let{padShape:n,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:p}=this._getPropsWithDefaults();if(a==="through_hole")return`platedhole_d${e}`;if(a==="pad"){if(n==="circle")return`smtpad_circle_d${s}`;if(n==="rect")return`smtpad_rect_w${l}_h${p}`}throw new Error(`Footprint variant "${a}" with pad shape "${n}" not implemented`)}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,{padShape:a,holeDiameter:s,footprintVariant:l,padDiameter:p,width:x,height:f}=this._getPropsWithDefaults(),m=n.source_component.insert({ftype:od.simple_test_point,name:this.name,supplier_part_numbers:e.supplierPartNumbers,footprint_variant:l,pad_shape:a,pad_diameter:p,hole_diameter:s,width:x,height:f,are_pins_interchangeable:!0});this.source_component_id=m.source_component_id}},D9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:_Ae}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalSchematicPositionBeforeLayout();e.schematic_text.insert({anchor:a.anchor??"center",text:a.text,font_size:a.fontSize,color:a.color||"#000000",position:{x:s.x,y:s.y},rotation:a.schRotation??0})}};function xGt({anchor:n,x:e,y:a,width:s,height:l,isInside:p}){switch(n){case"top_left":return{x:e,y:a+l,textAnchor:p?"top_left":"bottom_left"};case"top_center":return{x:e+s/2,y:a+l,textAnchor:p?"top_center":"bottom_center"};case"top_right":return{x:e+s,y:a+l,textAnchor:p?"top_right":"bottom_right"};case"center_left":return{x:e,y:a+l/2,textAnchor:p?"center_left":"center_right"};case"center":return{x:e+s/2,y:a+l/2,textAnchor:"center"};case"center_right":return{x:e+s,y:a+l/2,textAnchor:p?"center_right":"center_left"};case"bottom_left":return{x:e,y:a,textAnchor:p?"bottom_left":"top_left"};case"bottom_center":return{x:e+s/2,y:a,textAnchor:p?"bottom_center":"top_center"};case"bottom_right":return{x:e+s,y:a,textAnchor:p?"bottom_right":"top_right"};default:return{x:e+s/2,y:a+l,textAnchor:"center"}}}var y9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:CAe,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=.6,l=typeof a.padding=="number"?a.padding:0,p=typeof a.paddingTop=="number"?a.paddingTop:l,x=typeof a.paddingBottom=="number"?a.paddingBottom:l,f=typeof a.paddingLeft=="number"?a.paddingLeft:l,m=typeof a.paddingRight=="number"?a.paddingRight:l,D=a.overlay&&a.overlay.length>0,b=typeof a.width=="number"&&typeof a.height=="number",E,A,B,w,P,N;if(D){let $=a.overlay.map(it=>({selector:it,port:this.getSubcircuit().selectOne(it,{type:"port"})})).filter(({port:it})=>it!=null).map(({port:it})=>({position:it._getGlobalSchematicPositionAfterLayout()}));if($.length===0)return;let ee=$.map(it=>it.position.x),X=$.map(it=>it.position.y),te=Math.min(...ee),L=Math.max(...ee),K=Math.min(...X),U=Math.max(...X),J=L-te,Q=U-K,de=J===0?s:0,ce=Q===0?s:0,Te=f+de/2,Ne=m+de/2,Ve=p+ce/2,et=x+ce/2,ct=te-Te,Mt=L+Ne,Dt=K-et,ot=U+Ve;E=Mt-ct,A=ot-Dt,B=ct+(a.schX??0),w=Dt+(a.schY??0),P=B+E/2,N=w+A/2}else if(b){E=a.width,A=a.height;let O=this._getGlobalSchematicPositionBeforeLayout();P=O.x,N=O.y,B=P-E/2,w=N-A/2}else return;if(e.schematic_box.insert({height:A,width:E,x:B,y:w,is_dashed:a.strokeStyle==="dashed"}),a.title){let O=a.titleInside,$=.1,ee=a.titleAlignment,X=xGt({anchor:ee,x:B,y:w,width:E,height:A,isInside:O}),te,L,K=X.textAnchor;O?(te=ee.includes("top")?-$:ee.includes("bottom")?$:0,L=ee.includes("left")?$:ee.includes("right")?-$:0):(te=ee.includes("top")?$:ee.includes("bottom")?-$:0,L=ee.includes("center_left")?-$:ee.includes("center_right")?$:0);let U=X.x+L,J=X.y+te;e.schematic_text.insert({anchor:K,text:a.title,font_size:a.titleFontSize??.18,color:a.titleColor??"#000000",position:{x:U,y:J},rotation:0})}}},b9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0);q(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:AAe}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.children.filter(A=>A.componentName==="SchematicRow");if(s.length===0)return;let l=[],p=0;for(let A of s){let B=A.children.filter(w=>w.componentName==="SchematicCell");p=Math.max(p,B.length)}for(let A=0;A<s.length;A++)l[A]=[];for(let A=0;A<s.length;A++){let w=s[A].children.filter(N=>N.componentName==="SchematicCell"),P=0;for(let N=0;N<w.length;N++){for(;l[A][P];)P++;let O=w[N],$=O._parsedProps.colSpan??1,ee=O._parsedProps.rowSpan??1;for(let X=0;X<ee;X++)for(let te=0;te<$;te++)l[A+X]||(l[A+X]=[]),l[A+X][P+te]=O;P+=$}}p=Math.max(0,...l.map(A=>A.length));let x=s.map((A,B)=>A._parsedProps.height??1),f=Array.from({length:p},(A,B)=>{let w=0;for(let P=0;P<s.length;P++){let N=l[P]?.[B];if(N){let O=N._parsedProps.text??N._parsedProps.children,$=N._parsedProps.width??(O?.length??2)*.5;$>w&&(w=$)}}return w||10}),m=this._getGlobalSchematicPositionBeforeLayout(),D=e.schematic_table.insert({anchor_position:m,column_widths:f,row_heights:x,cell_padding:a.cellPadding,border_width:a.borderWidth,anchor:a.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=D.schematic_table_id;let b=new Set,E=0;for(let A=0;A<s.length;A++){let B=0;for(let w=0;w<p;w++){let P=l[A]?.[w];if(P&&!b.has(P)){b.add(P);let N=P._parsedProps,O=N.rowSpan??1,$=N.colSpan??1,ee=0;for(let te=0;te<$;te++)ee+=f[w+te];let X=0;for(let te=0;te<O;te++)X+=x[A+te];e.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:A,end_row_index:A+O-1,start_column_index:w,end_column_index:w+$-1,text:N.text??N.children,center:{x:m.x+B+ee/2,y:m.y-E-X/2},width:ee,height:X,horizontal_align:N.horizontalAlign,vertical_align:N.verticalAlign,font_size:N.fontSize??a.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}f[w]&&(B+=f[w])}E+=x[A]}}},F9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:RAe}}},E9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0);q(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:SAe}}},fGt={name:"@tscircuit/core",type:"module",version:"0.0.705",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"'},devDependencies:{"@biomejs/biome":"^1.8.3","@tscircuit/capacity-autorouter":"^0.0.107","@tscircuit/checks":"^0.0.71","@tscircuit/circuit-json-util":"^0.0.67","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.21","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.305","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.35","@tscircuit/simple-3d-svg":"^0.0.38","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.245","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-simple-3d":"^0.0.6","circuit-to-svg":"^0.0.185",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.195","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.33","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"}},qg=class{constructor({platform:n,projectUrl:e}={}){q(this,"firstChild",null);q(this,"children");q(this,"db");q(this,"root",null);q(this,"isRoot",!0);q(this,"schematicDisabled",!1);q(this,"pcbDisabled",!1);q(this,"pcbRoutingDisabled",!1);q(this,"_featureMspSchematicTraceRouting",!0);q(this,"name");q(this,"platform");q(this,"projectUrl");q(this,"_hasRenderedAtleastOnce",!1);q(this,"_eventListeners",{});this.children=[],this.db=ia([]),this.root=this,this.platform=n,this.projectUrl=e,this.pcbDisabled=n?.pcbDisabled??!1}add(n){let e;(0,v9e.isValidElement)(n)?e=EBe(n):e=n,this.children.push(e)}_getBoard(){return this.children.find(n=>n.componentName==="Board")}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let n=new zg({subcircuit:!0});n.parent=this,n.addAll(this.children),this.children=[n],this.firstChild=n}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()?!0:n.children.some(e=>e._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(n){let e=await Promise.resolve().then(()=>(WSe(),HSe)).catch(a=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
|
|
1040
1040
|
|
|
1041
|
-
"${a.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,a]=fGt.version.split(".").map(Number);return`${n}.${e}.${a+1}`}async preview(n){let e=typeof n=="object"?n:{previewName:n};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return _i()}_computePcbGlobalTransformBeforeLayout(){return _i()}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 a of this._eventListeners[n])a(...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(a=>a!==e))}enableDebug(n){typeof n=="string"?HW.default.enable(n):(n===null||n===!1)&&HW.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},hGt=qg,mGt=qg,gGt=n=>{let[e,a]=Lg.default.useState(!0),[s,l]=Lg.default.useState(null),[p,x]=Lg.default.useState(),[f,m]=Lg.default.useState();return Lg.default.useEffect(()=>{a(!0),l(null),n&&setTimeout(()=>{try{let D=new qg;D.add(n),x(D),m(D.toJson())}catch(D){l(D)}a(!1)},1)},[n]),{isLoading:e,error:s,circuit:p,circuitJson:f}},Ug=(n,e)=>(a,s)=>{let l=[];Array.isArray(e)?l.push(...e.flat()):typeof e=="object"&&l.push(...Object.values(e).flat(),...Object.keys(e));let p=x=>{if(x?.name&&x.name!==a)throw new Error(`Component name mismatch. Hook name: ${a}, Component prop name: ${x.name}`);let f={...s,...x,name:a},m=[];for(let D of l)if(f[D]){let b=`.${a} > .${D}`,E=f[D];m.push({from:b,to:E}),delete f[D]}return(0,A1.jsxs)(A1.Fragment,{children:[(0,A1.jsx)(n,{...f}),m.map((D,b)=>(0,A1.jsx)("trace",{...D},b))]})};for(let x of l)p[x]=`.${a} > .${x}`;return p},DGt=Ug(n=>(0,C9e.jsx)("capacitor",{...n}),Z_e),yGt=n=>Ug(e=>(0,_9e.jsx)("chip",{pinLabels:n,...e}),n),bGt=Ug(n=>(0,A9e.jsx)("diode",{...n}),xAe),FGt=Ug(n=>(0,R9e.jsx)("led",{...n}),hAe),EGt=Ug(n=>(0,S9e.jsx)("resistor",{...n}),Y_e),vGt=new Proxy(n=>new Proxy({},{get:(e,a)=>`.${n} > .${a}`}),{get:(n,e)=>{let a=(...s)=>{let l=s[0];return new Proxy({},{get:(p,x)=>`.${e} > .${x}`})};return new Proxy(a,{get:(s,l)=>e==="net"?`net.${l}`:e==="subcircuit"?new Proxy({},{get:(p,x)=>new Proxy({},{get:(f,m)=>`subcircuit.${l} > .${x} > .${m}`})}):`.${e} > .${l}`,apply:(s,l,p)=>e==="net"?new Proxy({},{get:(x,f)=>`net.${f}`}):new Proxy({},{get:(x,f)=>{let m=`.${e} > .${f}`;return["U","J","CN"].some(b=>e.startsWith(b))?m:new Proxy(new String(m),{get:(b,E)=>typeof E=="symbol"||E==="toString"?()=>m:`.${e} > .${f} > .${E}`})}})})}});FBe(gBe);FBe({Bug:HS});var P9e=qr(Ic(),1);var sK=new Map,Eo=async(n,e)=>{let a=new URLSearchParams({...e,json:"true"}).toString();if(sK.has(a))return sK.get(a);let l=await(await fetch(`https://jlcsearch.tscircuit.com/${n}/list?${a}`)).json();return sK.set(a,l),l},w9e={findPart:async({sourceComponent:n,footprinterString:e})=>{if(n.type==="source_component"&&n.ftype==="simple_resistor"){let{resistors:a}=await Eo("resistors",{resistance:n.display_resistance??n.resistance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_capacitor"){e?.includes("cap")&&(e=e.replace("cap",""));let{capacitors:a}=await Eo("capacitors",{capacitance:n.display_capacitance??n.capacitance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_pin_header"){let a;e?.includes("_p")&&(a=Number(e.split("_p")[1]));let{headers:s}=await Eo("headers",a?{pitch:a,num_pins:n.pin_count,gender:n.gender}:{num_pins:n.pin_count,gender:n.gender});return{jlcpcb:(s??[]).map(l=>`C${l.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_potentiometer"){let{potentiometers:a}=await Eo("potentiometers",{resistance:n.max_resistance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_diode"){let{diodes:a}=await Eo("diodes",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_chip"){let{chips:a}=await Eo("chips",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_transistor"){let{transistors:a}=await Eo("transistors",{package:e,transistor_type:n.transistor_type});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_power_source"){let{power_sources:a}=await Eo("power_sources",{voltage:n.voltage,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_inductor"){let{inductors:a}=await Eo("inductors",{inductance:n.inductance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_crystal"){let{crystals:a}=await Eo("crystals",{frequency:n.frequency,load_capacitance:n.load_capacitance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_mosfet"){let{mosfets:a}=await Eo("mosfets",{package:e,mosfet_mode:n.mosfet_mode,channel_type:n.channel_type});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_resonator"){let{resonators:a}=await Eo("resonators",{frequency:n.frequency,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_switch"){let{switches:a}=await Eo("switches",{switch_type:n.type,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_led"){let{leds:a}=await Eo("leds",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_fuse"){let{fuses:a}=await Eo("fuses",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}return{}}};var CGt="https://kicad-mod-cache.tscircuit.com",T9e=()=>({partsEngine:w9e,footprintLibraryMap:{kicad:async n=>{let e=`${CGt}/${n}.circuit.json
|
|
1041
|
+
"${a.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,a]=fGt.version.split(".").map(Number);return`${n}.${e}.${a+1}`}async preview(n){let e=typeof n=="object"?n:{previewName:n};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return _i()}_computePcbGlobalTransformBeforeLayout(){return _i()}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 a of this._eventListeners[n])a(...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(a=>a!==e))}enableDebug(n){typeof n=="string"?HW.default.enable(n):(n===null||n===!1)&&HW.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},hGt=qg,mGt=qg,gGt=n=>{let[e,a]=Lg.default.useState(!0),[s,l]=Lg.default.useState(null),[p,x]=Lg.default.useState(),[f,m]=Lg.default.useState();return Lg.default.useEffect(()=>{a(!0),l(null),n&&setTimeout(()=>{try{let D=new qg;D.add(n),x(D),m(D.toJson())}catch(D){l(D)}a(!1)},1)},[n]),{isLoading:e,error:s,circuit:p,circuitJson:f}},Ug=(n,e)=>(a,s)=>{let l=[];Array.isArray(e)?l.push(...e.flat()):typeof e=="object"&&l.push(...Object.values(e).flat(),...Object.keys(e));let p=x=>{if(x?.name&&x.name!==a)throw new Error(`Component name mismatch. Hook name: ${a}, Component prop name: ${x.name}`);let f={...s,...x,name:a},m=[];for(let D of l)if(f[D]){let b=`.${a} > .${D}`,E=f[D];m.push({from:b,to:E}),delete f[D]}return(0,A1.jsxs)(A1.Fragment,{children:[(0,A1.jsx)(n,{...f}),m.map((D,b)=>(0,A1.jsx)("trace",{...D},b))]})};for(let x of l)p[x]=`.${a} > .${x}`;return p},DGt=Ug(n=>(0,C9e.jsx)("capacitor",{...n}),Z_e),yGt=n=>Ug(e=>(0,_9e.jsx)("chip",{pinLabels:n,...e}),n),bGt=Ug(n=>(0,A9e.jsx)("diode",{...n}),xAe),FGt=Ug(n=>(0,R9e.jsx)("led",{...n}),hAe),EGt=Ug(n=>(0,S9e.jsx)("resistor",{...n}),Y_e),vGt=new Proxy(n=>new Proxy({},{get:(e,a)=>`.${n} > .${a}`}),{get:(n,e)=>{let a=(...s)=>{let l=s[0];return new Proxy({},{get:(p,x)=>`.${e} > .${x}`})};return new Proxy(a,{get:(s,l)=>e==="net"?`net.${l}`:e==="subcircuit"?new Proxy({},{get:(p,x)=>new Proxy({},{get:(f,m)=>`subcircuit.${l} > .${x} > .${m}`})}):`.${e} > .${l}`,apply:(s,l,p)=>e==="net"?new Proxy({},{get:(x,f)=>`net.${f}`}):new Proxy({},{get:(x,f)=>{let m=`.${e} > .${f}`;return["U","J","CN"].some(b=>e.startsWith(b))?m:new Proxy(new String(m),{get:(b,E)=>typeof E=="symbol"||E==="toString"?()=>m:`.${e} > .${f} > .${E}`})}})})}});FBe(gBe);FBe({Bug:HS});var P9e=qr(Ic(),1);var sK=new Map,Eo=async(n,e)=>{let a=new URLSearchParams({...e,json:"true"}).toString();if(sK.has(a))return sK.get(a);let l=await(await fetch(`https://jlcsearch.tscircuit.com/${n}/list?${a}`)).json();return sK.set(a,l),l},w9e={findPart:async({sourceComponent:n,footprinterString:e})=>{if(n.type==="source_component"&&n.ftype==="simple_resistor"){let{resistors:a}=await Eo("resistors",{resistance:n.display_resistance??n.resistance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_capacitor"){e?.includes("cap")&&(e=e.replace("cap",""));let{capacitors:a}=await Eo("capacitors",{capacitance:n.display_capacitance??n.capacitance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_pin_header"){let a;e?.includes("_p")&&(a=Number(e.split("_p")[1]));let{headers:s}=await Eo("headers",a?{pitch:a,num_pins:n.pin_count,gender:n.gender}:{num_pins:n.pin_count,gender:n.gender});return{jlcpcb:(s??[]).map(l=>`C${l.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_potentiometer"){let{potentiometers:a}=await Eo("potentiometers",{resistance:n.max_resistance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_diode"){let{diodes:a}=await Eo("diodes",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_chip"){let{chips:a}=await Eo("chips",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_transistor"){let{transistors:a}=await Eo("transistors",{package:e,transistor_type:n.transistor_type});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_power_source"){let{power_sources:a}=await Eo("power_sources",{voltage:n.voltage,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_inductor"){let{inductors:a}=await Eo("inductors",{inductance:n.inductance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_crystal"){let{crystals:a}=await Eo("crystals",{frequency:n.frequency,load_capacitance:n.load_capacitance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_mosfet"){let{mosfets:a}=await Eo("mosfets",{package:e,mosfet_mode:n.mosfet_mode,channel_type:n.channel_type});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_resonator"){let{resonators:a}=await Eo("resonators",{frequency:n.frequency,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_switch"){let{switches:a}=await Eo("switches",{switch_type:n.type,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_led"){let{leds:a}=await Eo("leds",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_fuse"){let{fuses:a}=await Eo("fuses",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}return{}}};var CGt="https://kicad-mod-cache.tscircuit.com",T9e=()=>({partsEngine:w9e,footprintLibraryMap:{kicad:async n=>{let e=`${CGt}/${n}.circuit.json`,s=await(await fetch(e)).json();return{footprintCircuitJson:Array.isArray(s)?s.filter(p=>p?.type==="pcb_silkscreen_text"?p?.text==="REF**":!0):s}}}});var iK=qr(vs(),1),wgr=(0,iK.default)("tsci:eval:execution-context");function KS(n,e={}){globalThis.React=P9e;let a=new qg({platform:e.platform||T9e()});return e.name&&(a.name=e.name),e.debugNamespace&&a.enableDebug(e.debugNamespace),{fsMap:{},entrypoint:"",preSuppliedImports:{"@tscircuit/core":WS,tscircuit:WS,"@tscircuit/math-utils":_Y,react:P9e,debug:iK.default,"@tscircuit/props":{}},circuit:a,...n}}function zF(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 I9e(n){let e={};for(let[a,s]of Object.entries(n))e[zF(a)]=s;return e}function ud(n){if(!n)return".";let a=n.replace(/\\/g,"/").replace(/\/+$/,"");return a.indexOf("/")===-1?".":a.substring(0,a.lastIndexOf("/"))||"/"}function oK(n,e){if(n.startsWith("../")){let a=ud(e);return oK(n.slice(3),a)}return n.startsWith("./")?oK(n.slice(2),e):n.startsWith("/")?n.slice(1):`${e}/${n}`}var qF=(n,e,a)=>{let s=a?oK(n,a):n,l=new Set(Array.isArray(e)?e:Object.keys(e));if(l.has(s))return s;let p=new Map;for(let m of l)p.set(zF(m),m);let x=zF(s);if(p.has(x))return p.get(x);let f=["tsx","ts","json","js","jsx","obj"];for(let m of f){let D=`${x}.${m}`;if(p.has(D))return p.get(D)}if(!n.startsWith("./")&&!n.startsWith("../")){let m=zF(n);if(p.has(m))return p.get(m);for(let D of f){let b=`${m}.${D}`;if(p.has(b))return p.get(b)}}return null},JS=(n,e)=>{let a=qF(n,e);if(!a)throw new Error(`File not found "${n}", available paths:
|
|
1042
1042
|
|
|
1043
1043
|
${Object.keys(e).join(", ")}`);return a};function UF(n,e,a){globalThis.__tscircuit_require=l=>{let p=qF(l,e,a),x=p&&e[p];if(!e[l]&&!x)throw new Error(`Import "${l}" not found ${a?`in "${a}"`:""}`);let f=e[l]||e[p];return new Proxy(f,{get(m,D){if(!(D in m)){if(D==="default")return m.default!==void 0?m.default:m.__esModule?void 0:typeof m=="function"||typeof m=="object"?m:void 0;if(D==="__esModule")return!0;throw new Error(`Component "${String(D)}" is not exported by "${l}"`)}return m[D]}})};let s=`
|
|
1044
1044
|
var exports = {};
|