@tscircuit/eval 0.0.328 → 0.0.329

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.
@@ -1,4 +1,4 @@
1
- var FEt=Object.create;var vA=Object.defineProperty;var EEt=Object.getOwnPropertyDescriptor;var vEt=Object.getOwnPropertyNames;var CEt=Object.getPrototypeOf,_Et=Object.prototype.hasOwnProperty;var AEt=(r,e,a)=>e in r?vA(r,e,{enumerable:!0,configurable:!0,writable:!0,value:a}):r[e]=a;var fb=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,a)=>(typeof require<"u"?require:e)[a]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var Sr=(r,e)=>()=>(r&&(e=r(r=0)),e);var on=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Am=(r,e)=>{for(var a in e)vA(r,a,{get:e[a],enumerable:!0})},REt=(r,e,a,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let l of vEt(e))!_Et.call(r,l)&&l!==a&&vA(r,l,{get:()=>e[l],enumerable:!(s=EEt(e,l))||s.enumerable});return r};var Or=(r,e,a)=>(a=r!=null?FEt(CEt(r)):{},REt(e||!r||!r.__esModule?vA(a,"default",{value:r,enumerable:!0}):a,r));var z=(r,e,a)=>AEt(r,typeof e!="symbol"?e+"":e,a);var N2e=on(Rn=>{"use strict";var aq=Symbol.for("react.transitional.element"),qEt=Symbol.for("react.portal"),UEt=Symbol.for("react.fragment"),VEt=Symbol.for("react.strict_mode"),GEt=Symbol.for("react.profiler"),XEt=Symbol.for("react.consumer"),YEt=Symbol.for("react.context"),HEt=Symbol.for("react.forward_ref"),WEt=Symbol.for("react.suspense"),KEt=Symbol.for("react.memo"),w2e=Symbol.for("react.lazy"),_2e=Symbol.iterator;function JEt(r){return r===null||typeof r!="object"?null:(r=_2e&&r[_2e]||r["@@iterator"],typeof r=="function"?r:null)}var T2e={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},P2e=Object.assign,I2e={};function Bm(r,e,a){this.props=r,this.context=e,this.refs=I2e,this.updater=a||T2e}Bm.prototype.isReactComponent={};Bm.prototype.setState=function(r,e){if(typeof r!="object"&&typeof r!="function"&&r!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,r,e,"setState")};Bm.prototype.forceUpdate=function(r){this.updater.enqueueForceUpdate(this,r,"forceUpdate")};function j2e(){}j2e.prototype=Bm.prototype;function sq(r,e,a){this.props=r,this.context=e,this.refs=I2e,this.updater=a||T2e}var iq=sq.prototype=new j2e;iq.constructor=sq;P2e(iq,Bm.prototype);iq.isPureReactComponent=!0;var A2e=Array.isArray,Za={H:null,A:null,T:null,S:null,V:null},k2e=Object.prototype.hasOwnProperty;function oq(r,e,a,s,l,d){return a=d.ref,{$$typeof:aq,type:r,key:e,ref:a!==void 0?a:null,props:d}}function ZEt(r,e){return oq(r.type,e,void 0,void 0,void 0,r.props)}function uq(r){return typeof r=="object"&&r!==null&&r.$$typeof===aq}function QEt(r){var e={"=":"=0",":":"=2"};return"$"+r.replace(/[=:]/g,function(a){return e[a]})}var R2e=/\/+/g;function nq(r,e){return typeof r=="object"&&r!==null&&r.key!=null?QEt(""+r.key):e.toString(36)}function S2e(){}function evt(r){switch(r.status){case"fulfilled":return r.value;case"rejected":throw r.reason;default:switch(typeof r.status=="string"?r.then(S2e,S2e):(r.status="pending",r.then(function(e){r.status==="pending"&&(r.status="fulfilled",r.value=e)},function(e){r.status==="pending"&&(r.status="rejected",r.reason=e)})),r.status){case"fulfilled":return r.value;case"rejected":throw r.reason}}throw r}function Sm(r,e,a,s,l){var d=typeof r;(d==="undefined"||d==="boolean")&&(r=null);var x=!1;if(r===null)x=!0;else switch(d){case"bigint":case"string":case"number":x=!0;break;case"object":switch(r.$$typeof){case aq:case qEt:x=!0;break;case w2e:return x=r._init,Sm(x(r._payload),e,a,s,l)}}if(x)return l=l(r),x=s===""?"."+nq(r,0):s,A2e(l)?(a="",x!=null&&(a=x.replace(R2e,"$&/")+"/"),Sm(l,e,a,"",function(D){return D})):l!=null&&(uq(l)&&(l=ZEt(l,a+(l.key==null||r&&r.key===l.key?"":(""+l.key).replace(R2e,"$&/")+"/")+x)),e.push(l)),1;x=0;var f=s===""?".":s+":";if(A2e(r))for(var m=0;m<r.length;m++)s=r[m],d=f+nq(s,m),x+=Sm(s,e,a,d,l);else if(m=JEt(r),typeof m=="function")for(r=m.call(r),m=0;!(s=r.next()).done;)s=s.value,d=f+nq(s,m++),x+=Sm(s,e,a,d,l);else if(d==="object"){if(typeof r.then=="function")return Sm(evt(r),e,a,s,l);throw e=String(r),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(r).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return x}function wA(r,e,a){if(r==null)return r;var s=[],l=0;return Sm(r,s,"","",function(d){return e.call(a,d,l++)}),s}function tvt(r){if(r._status===-1){var e=r._result;e=e(),e.then(function(a){(r._status===0||r._status===-1)&&(r._status=1,r._result=a)},function(a){(r._status===0||r._status===-1)&&(r._status=2,r._result=a)}),r._status===-1&&(r._status=0,r._result=e)}if(r._status===1)return r._result.default;throw r._result}var B2e=typeof reportError=="function"?reportError:function(r){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof r=="object"&&r!==null&&typeof r.message=="string"?String(r.message):String(r),error:r});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",r);return}console.error(r)};function rvt(){}Rn.Children={map:wA,forEach:function(r,e,a){wA(r,function(){e.apply(this,arguments)},a)},count:function(r){var e=0;return wA(r,function(){e++}),e},toArray:function(r){return wA(r,function(e){return e})||[]},only:function(r){if(!uq(r))throw Error("React.Children.only expected to receive a single React element child.");return r}};Rn.Component=Bm;Rn.Fragment=UEt;Rn.Profiler=GEt;Rn.PureComponent=sq;Rn.StrictMode=VEt;Rn.Suspense=WEt;Rn.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Za;Rn.__COMPILER_RUNTIME={__proto__:null,c:function(r){return Za.H.useMemoCache(r)}};Rn.cache=function(r){return function(){return r.apply(null,arguments)}};Rn.cloneElement=function(r,e,a){if(r==null)throw Error("The argument must be a React element, but you passed "+r+".");var s=P2e({},r.props),l=r.key,d=void 0;if(e!=null)for(x in e.ref!==void 0&&(d=void 0),e.key!==void 0&&(l=""+e.key),e)!k2e.call(e,x)||x==="key"||x==="__self"||x==="__source"||x==="ref"&&e.ref===void 0||(s[x]=e[x]);var x=arguments.length-2;if(x===1)s.children=a;else if(1<x){for(var f=Array(x),m=0;m<x;m++)f[m]=arguments[m+2];s.children=f}return oq(r.type,l,void 0,void 0,d,s)};Rn.createContext=function(r){return r={$$typeof:YEt,_currentValue:r,_currentValue2:r,_threadCount:0,Provider:null,Consumer:null},r.Provider=r,r.Consumer={$$typeof:XEt,_context:r},r};Rn.createElement=function(r,e,a){var s,l={},d=null;if(e!=null)for(s in e.key!==void 0&&(d=""+e.key),e)k2e.call(e,s)&&s!=="key"&&s!=="__self"&&s!=="__source"&&(l[s]=e[s]);var x=arguments.length-2;if(x===1)l.children=a;else if(1<x){for(var f=Array(x),m=0;m<x;m++)f[m]=arguments[m+2];l.children=f}if(r&&r.defaultProps)for(s in x=r.defaultProps,x)l[s]===void 0&&(l[s]=x[s]);return oq(r,d,void 0,void 0,null,l)};Rn.createRef=function(){return{current:null}};Rn.forwardRef=function(r){return{$$typeof:HEt,render:r}};Rn.isValidElement=uq;Rn.lazy=function(r){return{$$typeof:w2e,_payload:{_status:-1,_result:r},_init:tvt}};Rn.memo=function(r,e){return{$$typeof:KEt,type:r,compare:e===void 0?null:e}};Rn.startTransition=function(r){var e=Za.T,a={};Za.T=a;try{var s=r(),l=Za.S;l!==null&&l(a,s),typeof s=="object"&&s!==null&&typeof s.then=="function"&&s.then(rvt,B2e)}catch(d){B2e(d)}finally{Za.T=e}};Rn.unstable_useCacheRefresh=function(){return Za.H.useCacheRefresh()};Rn.use=function(r){return Za.H.use(r)};Rn.useActionState=function(r,e,a){return Za.H.useActionState(r,e,a)};Rn.useCallback=function(r,e){return Za.H.useCallback(r,e)};Rn.useContext=function(r){return Za.H.useContext(r)};Rn.useDebugValue=function(){};Rn.useDeferredValue=function(r,e){return Za.H.useDeferredValue(r,e)};Rn.useEffect=function(r,e,a){var s=Za.H;if(typeof a=="function")throw Error("useEffect CRUD overload is not enabled in this build of React.");return s.useEffect(r,e)};Rn.useId=function(){return Za.H.useId()};Rn.useImperativeHandle=function(r,e,a){return Za.H.useImperativeHandle(r,e,a)};Rn.useInsertionEffect=function(r,e){return Za.H.useInsertionEffect(r,e)};Rn.useLayoutEffect=function(r,e){return Za.H.useLayoutEffect(r,e)};Rn.useMemo=function(r,e){return Za.H.useMemo(r,e)};Rn.useOptimistic=function(r,e){return Za.H.useOptimistic(r,e)};Rn.useReducer=function(r,e,a){return Za.H.useReducer(r,e,a)};Rn.useRef=function(r){return Za.H.useRef(r)};Rn.useState=function(r){return Za.H.useState(r)};Rn.useSyncExternalStore=function(r,e,a){return Za.H.useSyncExternalStore(r,e,a)};Rn.useTransition=function(){return Za.H.useTransition()};Rn.version="19.1.1"});var kc=on((cYt,M2e)=>{"use strict";M2e.exports=N2e()});var $n,cq,vr,$0,hb=Sr(()=>{"use strict";(function(r){r.assertEqual=l=>{};function e(l){}r.assertIs=e;function a(l){throw new Error}r.assertNever=a,r.arrayToEnum=l=>{let d={};for(let x of l)d[x]=x;return d},r.getValidEnumValues=l=>{let d=r.objectKeys(l).filter(f=>typeof l[l[f]]!="number"),x={};for(let f of d)x[f]=l[f];return r.objectValues(x)},r.objectValues=l=>r.objectKeys(l).map(function(d){return l[d]}),r.objectKeys=typeof Object.keys=="function"?l=>Object.keys(l):l=>{let d=[];for(let x in l)Object.prototype.hasOwnProperty.call(l,x)&&d.push(x);return d},r.find=(l,d)=>{for(let x of l)if(d(x))return x},r.isInteger=typeof Number.isInteger=="function"?l=>Number.isInteger(l):l=>typeof l=="number"&&Number.isFinite(l)&&Math.floor(l)===l;function s(l,d=" | "){return l.map(x=>typeof x=="string"?`'${x}'`:x).join(d)}r.joinValues=s,r.jsonStringifyReplacer=(l,d)=>typeof d=="bigint"?d.toString():d})($n||($n={}));(function(r){r.mergeShapes=(e,a)=>({...e,...a})})(cq||(cq={}));vr=$n.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),$0=r=>{switch(typeof r){case"undefined":return vr.undefined;case"string":return vr.string;case"number":return Number.isNaN(r)?vr.nan:vr.number;case"boolean":return vr.boolean;case"function":return vr.function;case"bigint":return vr.bigint;case"symbol":return vr.symbol;case"object":return Array.isArray(r)?vr.array:r===null?vr.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?vr.promise:typeof Map<"u"&&r instanceof Map?vr.map:typeof Set<"u"&&r instanceof Set?vr.set:typeof Date<"u"&&r instanceof Date?vr.date:vr.object;default:return vr.unknown}}});var nr,nvt,Wo,TA=Sr(()=>{"use strict";hb();nr=$n.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),nvt=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),Wo=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let a=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,a):this.__proto__=a,this.name="ZodError",this.issues=e}format(e){let a=e||function(d){return d.message},s={_errors:[]},l=d=>{for(let x of d.issues)if(x.code==="invalid_union")x.unionErrors.map(l);else if(x.code==="invalid_return_type")l(x.returnTypeError);else if(x.code==="invalid_arguments")l(x.argumentsError);else if(x.path.length===0)s._errors.push(a(x));else{let f=s,m=0;for(;m<x.path.length;){let D=x.path[m];m===x.path.length-1?(f[D]=f[D]||{_errors:[]},f[D]._errors.push(a(x))):f[D]=f[D]||{_errors:[]},f=f[D],m++}}};return l(this),s}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$n.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=a=>a.message){let a={},s=[];for(let l of this.issues)if(l.path.length>0){let d=l.path[0];a[d]=a[d]||[],a[d].push(e(l))}else s.push(e(l));return{formErrors:s,fieldErrors:a}}get formErrors(){return this.flatten()}};Wo.create=r=>new Wo(r)});var avt,ql,lq=Sr(()=>{"use strict";TA();hb();avt=(r,e)=>{let a;switch(r.code){case nr.invalid_type:r.received===vr.undefined?a="Required":a=`Expected ${r.expected}, received ${r.received}`;break;case nr.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(r.expected,$n.jsonStringifyReplacer)}`;break;case nr.unrecognized_keys:a=`Unrecognized key(s) in object: ${$n.joinValues(r.keys,", ")}`;break;case nr.invalid_union:a="Invalid input";break;case nr.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${$n.joinValues(r.options)}`;break;case nr.invalid_enum_value:a=`Invalid enum value. Expected ${$n.joinValues(r.options)}, received '${r.received}'`;break;case nr.invalid_arguments:a="Invalid function arguments";break;case nr.invalid_return_type:a="Invalid function return type";break;case nr.invalid_date:a="Invalid date";break;case nr.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(a=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(a=`${a} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?a=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?a=`Invalid input: must end with "${r.validation.endsWith}"`:$n.assertNever(r.validation):r.validation!=="regex"?a=`Invalid ${r.validation}`:a="Invalid";break;case nr.too_small:r.type==="array"?a=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?a=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?a=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?a=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?a=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:a="Invalid input";break;case nr.too_big:r.type==="array"?a=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?a=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?a=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?a=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?a=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:a="Invalid input";break;case nr.custom:a="Invalid input";break;case nr.invalid_intersection_types:a="Intersection results could not be merged";break;case nr.not_multiple_of:a=`Number must be a multiple of ${r.multipleOf}`;break;case nr.not_finite:a="Number must be finite";break;default:a=e.defaultError,$n.assertNever(r)}return{message:a}},ql=avt});function svt(r){O2e=r}function wm(){return O2e}var O2e,PA=Sr(()=>{"use strict";lq();O2e=ql});function gr(r,e){let a=wm(),s=mb({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,a,a===ql?void 0:ql].filter(l=>!!l)});r.common.issues.push(s)}var mb,ivt,Ri,rn,Bf,Wi,IA,jA,_p,Tm,dq=Sr(()=>{"use strict";PA();lq();mb=r=>{let{data:e,path:a,errorMaps:s,issueData:l}=r,d=[...a,...l.path||[]],x={...l,path:d};if(l.message!==void 0)return{...l,path:d,message:l.message};let f="",m=s.filter(D=>!!D).slice().reverse();for(let D of m)f=D(x,{data:e,defaultError:f}).message;return{...l,path:d,message:f}},ivt=[];Ri=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,a){let s=[];for(let l of a){if(l.status==="aborted")return rn;l.status==="dirty"&&e.dirty(),s.push(l.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,a){let s=[];for(let l of a){let d=await l.key,x=await l.value;s.push({key:d,value:x})}return r.mergeObjectSync(e,s)}static mergeObjectSync(e,a){let s={};for(let l of a){let{key:d,value:x}=l;if(d.status==="aborted"||x.status==="aborted")return rn;d.status==="dirty"&&e.dirty(),x.status==="dirty"&&e.dirty(),d.value!=="__proto__"&&(typeof x.value<"u"||l.alwaysSet)&&(s[d.value]=x.value)}return{status:e.value,value:s}}},rn=Object.freeze({status:"aborted"}),Bf=r=>({status:"dirty",value:r}),Wi=r=>({status:"valid",value:r}),IA=r=>r.status==="aborted",jA=r=>r.status==="dirty",_p=r=>r.status==="valid",Tm=r=>typeof Promise<"u"&&r instanceof Promise});var L2e=Sr(()=>{"use strict"});var Nr,$2e=Sr(()=>{"use strict";(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(Nr||(Nr={}))});function Fn(r){if(!r)return{};let{errorMap:e,invalid_type_error:a,required_error:s,description:l}=r;if(e&&(a||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:l}:{errorMap:(x,f)=>{let{message:m}=r;return x.code==="invalid_enum_value"?{message:m??f.defaultError}:typeof f.data>"u"?{message:m??s??f.defaultError}:x.code!=="invalid_type"?{message:f.defaultError}:{message:m??a??f.defaultError}},description:l}}function V2e(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let a=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${a}`}function vvt(r){return new RegExp(`^${V2e(r)}$`)}function G2e(r){let e=`${U2e}T${V2e(r)}`,a=[];return a.push(r.local?"Z?":"Z"),r.offset&&a.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${a.join("|")})`,new RegExp(`^${e}$`)}function Cvt(r,e){return!!((e==="v4"||!e)&&mvt.test(r)||(e==="v6"||!e)&&Dvt.test(r))}function _vt(r,e){if(!pvt.test(r))return!1;try{let[a]=r.split(".");if(!a)return!1;let s=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(a.length+(4-a.length%4)%4,"="),l=JSON.parse(atob(s));return!(typeof l!="object"||l===null||"typ"in l&&l?.typ!=="JWT"||!l.alg||e&&l.alg!==e)}catch{return!1}}function Avt(r,e){return!!((e==="v4"||!e)&&gvt.test(r)||(e==="v6"||!e)&&yvt.test(r))}function Rvt(r,e){let a=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,l=a>s?a:s,d=Number.parseInt(r.toFixed(l).replace(".","")),x=Number.parseInt(e.toFixed(l).replace(".",""));return d%x/10**l}function Pm(r){if(r instanceof Ko){let e={};for(let a in r.shape){let s=r.shape[a];e[a]=Hu.create(Pm(s))}return new Ko({...r._def,shape:()=>e})}else return r instanceof Gl?new Gl({...r._def,type:Pm(r.element)}):r instanceof Hu?Hu.create(Pm(r.unwrap())):r instanceof q0?q0.create(Pm(r.unwrap())):r instanceof z0?z0.create(r.items.map(e=>Pm(e))):r}function xq(r,e){let a=$0(r),s=$0(e);if(r===e)return{valid:!0,data:r};if(a===vr.object&&s===vr.object){let l=$n.objectKeys(e),d=$n.objectKeys(r).filter(f=>l.indexOf(f)!==-1),x={...r,...e};for(let f of d){let m=xq(r[f],e[f]);if(!m.valid)return{valid:!1};x[f]=m.data}return{valid:!0,data:x}}else if(a===vr.array&&s===vr.array){if(r.length!==e.length)return{valid:!1};let l=[];for(let d=0;d<r.length;d++){let x=r[d],f=e[d],m=xq(x,f);if(!m.valid)return{valid:!1};l.push(m.data)}return{valid:!0,data:l}}else return a===vr.date&&s===vr.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}function X2e(r,e){return new $f({values:r,typeName:un.ZodEnum,...Fn(e)})}function q2e(r,e){let a=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof a=="string"?{message:a}:a}function Y2e(r,e={},a){return r?Rp.create().superRefine((s,l)=>{let d=r(s);if(d instanceof Promise)return d.then(x=>{if(!x){let f=q2e(e,s),m=f.fatal??a??!0;l.addIssue({code:"custom",...f,fatal:m})}});if(!d){let x=q2e(e,s),f=x.fatal??a??!0;l.addIssue({code:"custom",...x,fatal:f})}}):Rp.create()}var Wu,z2e,Sn,ovt,uvt,cvt,lvt,dvt,pvt,xvt,fvt,hvt,pq,mvt,gvt,Dvt,yvt,bvt,Fvt,U2e,Evt,Ap,wf,Tf,Pf,If,Im,jf,kf,Rp,Vl,Nc,jm,Gl,Ko,Nf,Ul,kA,Mf,z0,NA,km,Nm,MA,Of,Lf,$f,zf,Sp,Ku,Hu,q0,qf,Uf,Mm,Svt,gb,Db,Vf,Bvt,un,wvt,H2e,W2e,Tvt,Pvt,K2e,Ivt,jvt,kvt,Nvt,Mvt,Ovt,Lvt,$vt,zvt,qvt,Uvt,Vvt,Gvt,Xvt,Yvt,Hvt,Wvt,Kvt,Jvt,Zvt,Qvt,eCt,tCt,rCt,nCt,aCt,sCt,iCt,oCt,uCt,cCt,lCt,dCt,pCt,J2e=Sr(()=>{"use strict";TA();PA();$2e();dq();hb();Wu=class{constructor(e,a,s,l){this._cachedPath=[],this.parent=e,this.data=a,this._path=s,this._key=l}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},z2e=(r,e)=>{if(_p(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let a=new Wo(r.common.issues);return this._error=a,this._error}}};Sn=class{get description(){return this._def.description}_getType(e){return $0(e.data)}_getOrReturnCtx(e,a){return a||{common:e.parent.common,data:e.data,parsedType:$0(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ri,ctx:{common:e.parent.common,data:e.data,parsedType:$0(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let a=this._parse(e);if(Tm(a))throw new Error("Synchronous parse encountered promise.");return a}_parseAsync(e){let a=this._parse(e);return Promise.resolve(a)}parse(e,a){let s=this.safeParse(e,a);if(s.success)return s.data;throw s.error}safeParse(e,a){let s={common:{issues:[],async:a?.async??!1,contextualErrorMap:a?.errorMap},path:a?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$0(e)},l=this._parseSync({data:e,path:s.path,parent:s});return z2e(s,l)}"~validate"(e){let a={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$0(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:a});return _p(s)?{value:s.value}:{issues:a.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),a.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:a}).then(s=>_p(s)?{value:s.value}:{issues:a.common.issues})}async parseAsync(e,a){let s=await this.safeParseAsync(e,a);if(s.success)return s.data;throw s.error}async safeParseAsync(e,a){let s={common:{issues:[],contextualErrorMap:a?.errorMap,async:!0},path:a?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$0(e)},l=this._parse({data:e,path:s.path,parent:s}),d=await(Tm(l)?l:Promise.resolve(l));return z2e(s,d)}refine(e,a){let s=l=>typeof a=="string"||typeof a>"u"?{message:a}:typeof a=="function"?a(l):a;return this._refinement((l,d)=>{let x=e(l),f=()=>d.addIssue({code:nr.custom,...s(l)});return typeof Promise<"u"&&x instanceof Promise?x.then(m=>m?!0:(f(),!1)):x?!0:(f(),!1)})}refinement(e,a){return this._refinement((s,l)=>e(s)?!0:(l.addIssue(typeof a=="function"?a(s,l):a),!1))}_refinement(e){return new Ku({schema:this,typeName:un.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:a=>this["~validate"](a)}}optional(){return Hu.create(this,this._def)}nullable(){return q0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Gl.create(this)}promise(){return Sp.create(this,this._def)}or(e){return Nf.create([this,e],this._def)}and(e){return Mf.create(this,e,this._def)}transform(e){return new Ku({...Fn(this._def),schema:this,typeName:un.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let a=typeof e=="function"?e:()=>e;return new qf({...Fn(this._def),innerType:this,defaultValue:a,typeName:un.ZodDefault})}brand(){return new gb({typeName:un.ZodBranded,type:this,...Fn(this._def)})}catch(e){let a=typeof e=="function"?e:()=>e;return new Uf({...Fn(this._def),innerType:this,catchValue:a,typeName:un.ZodCatch})}describe(e){let a=this.constructor;return new a({...this._def,description:e})}pipe(e){return Db.create(this,e)}readonly(){return Vf.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ovt=/^c[^\s-]{8,}$/i,uvt=/^[0-9a-z]+$/,cvt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,lvt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,dvt=/^[a-z0-9_-]{21}$/i,pvt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,xvt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,fvt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,hvt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",mvt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,gvt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Dvt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,yvt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bvt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Fvt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,U2e="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Evt=new RegExp(`^${U2e}$`);Ap=class r extends Sn{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==vr.string){let d=this._getOrReturnCtx(e);return gr(d,{code:nr.invalid_type,expected:vr.string,received:d.parsedType}),rn}let s=new Ri,l;for(let d of this._def.checks)if(d.kind==="min")e.data.length<d.value&&(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.too_small,minimum:d.value,type:"string",inclusive:!0,exact:!1,message:d.message}),s.dirty());else if(d.kind==="max")e.data.length>d.value&&(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.too_big,maximum:d.value,type:"string",inclusive:!0,exact:!1,message:d.message}),s.dirty());else if(d.kind==="length"){let x=e.data.length>d.value,f=e.data.length<d.value;(x||f)&&(l=this._getOrReturnCtx(e,l),x?gr(l,{code:nr.too_big,maximum:d.value,type:"string",inclusive:!0,exact:!0,message:d.message}):f&&gr(l,{code:nr.too_small,minimum:d.value,type:"string",inclusive:!0,exact:!0,message:d.message}),s.dirty())}else if(d.kind==="email")fvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"email",code:nr.invalid_string,message:d.message}),s.dirty());else if(d.kind==="emoji")pq||(pq=new RegExp(hvt,"u")),pq.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"emoji",code:nr.invalid_string,message:d.message}),s.dirty());else if(d.kind==="uuid")lvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"uuid",code:nr.invalid_string,message:d.message}),s.dirty());else if(d.kind==="nanoid")dvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"nanoid",code:nr.invalid_string,message:d.message}),s.dirty());else if(d.kind==="cuid")ovt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"cuid",code:nr.invalid_string,message:d.message}),s.dirty());else if(d.kind==="cuid2")uvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"cuid2",code:nr.invalid_string,message:d.message}),s.dirty());else if(d.kind==="ulid")cvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"ulid",code:nr.invalid_string,message:d.message}),s.dirty());else if(d.kind==="url")try{new URL(e.data)}catch{l=this._getOrReturnCtx(e,l),gr(l,{validation:"url",code:nr.invalid_string,message:d.message}),s.dirty()}else d.kind==="regex"?(d.regex.lastIndex=0,d.regex.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"regex",code:nr.invalid_string,message:d.message}),s.dirty())):d.kind==="trim"?e.data=e.data.trim():d.kind==="includes"?e.data.includes(d.value,d.position)||(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.invalid_string,validation:{includes:d.value,position:d.position},message:d.message}),s.dirty()):d.kind==="toLowerCase"?e.data=e.data.toLowerCase():d.kind==="toUpperCase"?e.data=e.data.toUpperCase():d.kind==="startsWith"?e.data.startsWith(d.value)||(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.invalid_string,validation:{startsWith:d.value},message:d.message}),s.dirty()):d.kind==="endsWith"?e.data.endsWith(d.value)||(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.invalid_string,validation:{endsWith:d.value},message:d.message}),s.dirty()):d.kind==="datetime"?G2e(d).test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.invalid_string,validation:"datetime",message:d.message}),s.dirty()):d.kind==="date"?Evt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.invalid_string,validation:"date",message:d.message}),s.dirty()):d.kind==="time"?vvt(d).test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.invalid_string,validation:"time",message:d.message}),s.dirty()):d.kind==="duration"?xvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"duration",code:nr.invalid_string,message:d.message}),s.dirty()):d.kind==="ip"?Cvt(e.data,d.version)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"ip",code:nr.invalid_string,message:d.message}),s.dirty()):d.kind==="jwt"?_vt(e.data,d.alg)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"jwt",code:nr.invalid_string,message:d.message}),s.dirty()):d.kind==="cidr"?Avt(e.data,d.version)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"cidr",code:nr.invalid_string,message:d.message}),s.dirty()):d.kind==="base64"?bvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"base64",code:nr.invalid_string,message:d.message}),s.dirty()):d.kind==="base64url"?Fvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"base64url",code:nr.invalid_string,message:d.message}),s.dirty()):$n.assertNever(d);return{status:s.value,value:e.data}}_regex(e,a,s){return this.refinement(l=>e.test(l),{validation:a,code:nr.invalid_string,...Nr.errToObj(s)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Nr.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Nr.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Nr.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Nr.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Nr.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Nr.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Nr.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Nr.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Nr.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Nr.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Nr.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Nr.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Nr.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Nr.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Nr.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Nr.errToObj(e)})}regex(e,a){return this._addCheck({kind:"regex",regex:e,...Nr.errToObj(a)})}includes(e,a){return this._addCheck({kind:"includes",value:e,position:a?.position,...Nr.errToObj(a?.message)})}startsWith(e,a){return this._addCheck({kind:"startsWith",value:e,...Nr.errToObj(a)})}endsWith(e,a){return this._addCheck({kind:"endsWith",value:e,...Nr.errToObj(a)})}min(e,a){return this._addCheck({kind:"min",value:e,...Nr.errToObj(a)})}max(e,a){return this._addCheck({kind:"max",value:e,...Nr.errToObj(a)})}length(e,a){return this._addCheck({kind:"length",value:e,...Nr.errToObj(a)})}nonempty(e){return this.min(1,Nr.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxLength(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e}};Ap.create=r=>new Ap({checks:[],typeName:un.ZodString,coerce:r?.coerce??!1,...Fn(r)});wf=class r extends Sn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==vr.number){let d=this._getOrReturnCtx(e);return gr(d,{code:nr.invalid_type,expected:vr.number,received:d.parsedType}),rn}let s,l=new Ri;for(let d of this._def.checks)d.kind==="int"?$n.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.invalid_type,expected:"integer",received:"float",message:d.message}),l.dirty()):d.kind==="min"?(d.inclusive?e.data<d.value:e.data<=d.value)&&(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.too_small,minimum:d.value,type:"number",inclusive:d.inclusive,exact:!1,message:d.message}),l.dirty()):d.kind==="max"?(d.inclusive?e.data>d.value:e.data>=d.value)&&(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.too_big,maximum:d.value,type:"number",inclusive:d.inclusive,exact:!1,message:d.message}),l.dirty()):d.kind==="multipleOf"?Rvt(e.data,d.value)!==0&&(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.not_multiple_of,multipleOf:d.value,message:d.message}),l.dirty()):d.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.not_finite,message:d.message}),l.dirty()):$n.assertNever(d);return{status:l.value,value:e.data}}gte(e,a){return this.setLimit("min",e,!0,Nr.toString(a))}gt(e,a){return this.setLimit("min",e,!1,Nr.toString(a))}lte(e,a){return this.setLimit("max",e,!0,Nr.toString(a))}lt(e,a){return this.setLimit("max",e,!1,Nr.toString(a))}setLimit(e,a,s,l){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:a,inclusive:s,message:Nr.toString(l)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Nr.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Nr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Nr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Nr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Nr.toString(e)})}multipleOf(e,a){return this._addCheck({kind:"multipleOf",value:e,message:Nr.toString(a)})}finite(e){return this._addCheck({kind:"finite",message:Nr.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Nr.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Nr.toString(e)})}get minValue(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxValue(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&$n.isInteger(e.value))}get isFinite(){let e=null,a=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(a===null||s.value>a)&&(a=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(a)&&Number.isFinite(e)}};wf.create=r=>new wf({checks:[],typeName:un.ZodNumber,coerce:r?.coerce||!1,...Fn(r)});Tf=class r extends Sn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==vr.bigint)return this._getInvalidInput(e);let s,l=new Ri;for(let d of this._def.checks)d.kind==="min"?(d.inclusive?e.data<d.value:e.data<=d.value)&&(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.too_small,type:"bigint",minimum:d.value,inclusive:d.inclusive,message:d.message}),l.dirty()):d.kind==="max"?(d.inclusive?e.data>d.value:e.data>=d.value)&&(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.too_big,type:"bigint",maximum:d.value,inclusive:d.inclusive,message:d.message}),l.dirty()):d.kind==="multipleOf"?e.data%d.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.not_multiple_of,multipleOf:d.value,message:d.message}),l.dirty()):$n.assertNever(d);return{status:l.value,value:e.data}}_getInvalidInput(e){let a=this._getOrReturnCtx(e);return gr(a,{code:nr.invalid_type,expected:vr.bigint,received:a.parsedType}),rn}gte(e,a){return this.setLimit("min",e,!0,Nr.toString(a))}gt(e,a){return this.setLimit("min",e,!1,Nr.toString(a))}lte(e,a){return this.setLimit("max",e,!0,Nr.toString(a))}lt(e,a){return this.setLimit("max",e,!1,Nr.toString(a))}setLimit(e,a,s,l){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:a,inclusive:s,message:Nr.toString(l)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Nr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Nr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Nr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Nr.toString(e)})}multipleOf(e,a){return this._addCheck({kind:"multipleOf",value:e,message:Nr.toString(a)})}get minValue(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxValue(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e}};Tf.create=r=>new Tf({checks:[],typeName:un.ZodBigInt,coerce:r?.coerce??!1,...Fn(r)});Pf=class extends Sn{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==vr.boolean){let s=this._getOrReturnCtx(e);return gr(s,{code:nr.invalid_type,expected:vr.boolean,received:s.parsedType}),rn}return Wi(e.data)}};Pf.create=r=>new Pf({typeName:un.ZodBoolean,coerce:r?.coerce||!1,...Fn(r)});If=class r extends Sn{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==vr.date){let d=this._getOrReturnCtx(e);return gr(d,{code:nr.invalid_type,expected:vr.date,received:d.parsedType}),rn}if(Number.isNaN(e.data.getTime())){let d=this._getOrReturnCtx(e);return gr(d,{code:nr.invalid_date}),rn}let s=new Ri,l;for(let d of this._def.checks)d.kind==="min"?e.data.getTime()<d.value&&(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.too_small,message:d.message,inclusive:!0,exact:!1,minimum:d.value,type:"date"}),s.dirty()):d.kind==="max"?e.data.getTime()>d.value&&(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.too_big,message:d.message,inclusive:!0,exact:!1,maximum:d.value,type:"date"}),s.dirty()):$n.assertNever(d);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,a){return this._addCheck({kind:"min",value:e.getTime(),message:Nr.toString(a)})}max(e,a){return this._addCheck({kind:"max",value:e.getTime(),message:Nr.toString(a)})}get minDate(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e!=null?new Date(e):null}};If.create=r=>new If({checks:[],coerce:r?.coerce||!1,typeName:un.ZodDate,...Fn(r)});Im=class extends Sn{_parse(e){if(this._getType(e)!==vr.symbol){let s=this._getOrReturnCtx(e);return gr(s,{code:nr.invalid_type,expected:vr.symbol,received:s.parsedType}),rn}return Wi(e.data)}};Im.create=r=>new Im({typeName:un.ZodSymbol,...Fn(r)});jf=class extends Sn{_parse(e){if(this._getType(e)!==vr.undefined){let s=this._getOrReturnCtx(e);return gr(s,{code:nr.invalid_type,expected:vr.undefined,received:s.parsedType}),rn}return Wi(e.data)}};jf.create=r=>new jf({typeName:un.ZodUndefined,...Fn(r)});kf=class extends Sn{_parse(e){if(this._getType(e)!==vr.null){let s=this._getOrReturnCtx(e);return gr(s,{code:nr.invalid_type,expected:vr.null,received:s.parsedType}),rn}return Wi(e.data)}};kf.create=r=>new kf({typeName:un.ZodNull,...Fn(r)});Rp=class extends Sn{constructor(){super(...arguments),this._any=!0}_parse(e){return Wi(e.data)}};Rp.create=r=>new Rp({typeName:un.ZodAny,...Fn(r)});Vl=class extends Sn{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Wi(e.data)}};Vl.create=r=>new Vl({typeName:un.ZodUnknown,...Fn(r)});Nc=class extends Sn{_parse(e){let a=this._getOrReturnCtx(e);return gr(a,{code:nr.invalid_type,expected:vr.never,received:a.parsedType}),rn}};Nc.create=r=>new Nc({typeName:un.ZodNever,...Fn(r)});jm=class extends Sn{_parse(e){if(this._getType(e)!==vr.undefined){let s=this._getOrReturnCtx(e);return gr(s,{code:nr.invalid_type,expected:vr.void,received:s.parsedType}),rn}return Wi(e.data)}};jm.create=r=>new jm({typeName:un.ZodVoid,...Fn(r)});Gl=class r extends Sn{_parse(e){let{ctx:a,status:s}=this._processInputParams(e),l=this._def;if(a.parsedType!==vr.array)return gr(a,{code:nr.invalid_type,expected:vr.array,received:a.parsedType}),rn;if(l.exactLength!==null){let x=a.data.length>l.exactLength.value,f=a.data.length<l.exactLength.value;(x||f)&&(gr(a,{code:x?nr.too_big:nr.too_small,minimum:f?l.exactLength.value:void 0,maximum:x?l.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:l.exactLength.message}),s.dirty())}if(l.minLength!==null&&a.data.length<l.minLength.value&&(gr(a,{code:nr.too_small,minimum:l.minLength.value,type:"array",inclusive:!0,exact:!1,message:l.minLength.message}),s.dirty()),l.maxLength!==null&&a.data.length>l.maxLength.value&&(gr(a,{code:nr.too_big,maximum:l.maxLength.value,type:"array",inclusive:!0,exact:!1,message:l.maxLength.message}),s.dirty()),a.common.async)return Promise.all([...a.data].map((x,f)=>l.type._parseAsync(new Wu(a,x,a.path,f)))).then(x=>Ri.mergeArray(s,x));let d=[...a.data].map((x,f)=>l.type._parseSync(new Wu(a,x,a.path,f)));return Ri.mergeArray(s,d)}get element(){return this._def.type}min(e,a){return new r({...this._def,minLength:{value:e,message:Nr.toString(a)}})}max(e,a){return new r({...this._def,maxLength:{value:e,message:Nr.toString(a)}})}length(e,a){return new r({...this._def,exactLength:{value:e,message:Nr.toString(a)}})}nonempty(e){return this.min(1,e)}};Gl.create=(r,e)=>new Gl({type:r,minLength:null,maxLength:null,exactLength:null,typeName:un.ZodArray,...Fn(e)});Ko=class r extends Sn{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),a=$n.objectKeys(e);return this._cached={shape:e,keys:a},this._cached}_parse(e){if(this._getType(e)!==vr.object){let D=this._getOrReturnCtx(e);return gr(D,{code:nr.invalid_type,expected:vr.object,received:D.parsedType}),rn}let{status:s,ctx:l}=this._processInputParams(e),{shape:d,keys:x}=this._getCached(),f=[];if(!(this._def.catchall instanceof Nc&&this._def.unknownKeys==="strip"))for(let D in l.data)x.includes(D)||f.push(D);let m=[];for(let D of x){let b=d[D],E=l.data[D];m.push({key:{status:"valid",value:D},value:b._parse(new Wu(l,E,l.path,D)),alwaysSet:D in l.data})}if(this._def.catchall instanceof Nc){let D=this._def.unknownKeys;if(D==="passthrough")for(let b of f)m.push({key:{status:"valid",value:b},value:{status:"valid",value:l.data[b]}});else if(D==="strict")f.length>0&&(gr(l,{code:nr.unrecognized_keys,keys:f}),s.dirty());else if(D!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let D=this._def.catchall;for(let b of f){let E=l.data[b];m.push({key:{status:"valid",value:b},value:D._parse(new Wu(l,E,l.path,b)),alwaysSet:b in l.data})}}return l.common.async?Promise.resolve().then(async()=>{let D=[];for(let b of m){let E=await b.key,A=await b.value;D.push({key:E,value:A,alwaysSet:b.alwaysSet})}return D}).then(D=>Ri.mergeObjectSync(s,D)):Ri.mergeObjectSync(s,m)}get shape(){return this._def.shape()}strict(e){return Nr.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(a,s)=>{let l=this._def.errorMap?.(a,s).message??s.defaultError;return a.code==="unrecognized_keys"?{message:Nr.errToObj(e).message??l}:{message:l}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:un.ZodObject})}setKey(e,a){return this.augment({[e]:a})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let a={};for(let s of $n.objectKeys(e))e[s]&&this.shape[s]&&(a[s]=this.shape[s]);return new r({...this._def,shape:()=>a})}omit(e){let a={};for(let s of $n.objectKeys(this.shape))e[s]||(a[s]=this.shape[s]);return new r({...this._def,shape:()=>a})}deepPartial(){return Pm(this)}partial(e){let a={};for(let s of $n.objectKeys(this.shape)){let l=this.shape[s];e&&!e[s]?a[s]=l:a[s]=l.optional()}return new r({...this._def,shape:()=>a})}required(e){let a={};for(let s of $n.objectKeys(this.shape))if(e&&!e[s])a[s]=this.shape[s];else{let d=this.shape[s];for(;d instanceof Hu;)d=d._def.innerType;a[s]=d}return new r({...this._def,shape:()=>a})}keyof(){return X2e($n.objectKeys(this.shape))}};Ko.create=(r,e)=>new Ko({shape:()=>r,unknownKeys:"strip",catchall:Nc.create(),typeName:un.ZodObject,...Fn(e)});Ko.strictCreate=(r,e)=>new Ko({shape:()=>r,unknownKeys:"strict",catchall:Nc.create(),typeName:un.ZodObject,...Fn(e)});Ko.lazycreate=(r,e)=>new Ko({shape:r,unknownKeys:"strip",catchall:Nc.create(),typeName:un.ZodObject,...Fn(e)});Nf=class extends Sn{_parse(e){let{ctx:a}=this._processInputParams(e),s=this._def.options;function l(d){for(let f of d)if(f.result.status==="valid")return f.result;for(let f of d)if(f.result.status==="dirty")return a.common.issues.push(...f.ctx.common.issues),f.result;let x=d.map(f=>new Wo(f.ctx.common.issues));return gr(a,{code:nr.invalid_union,unionErrors:x}),rn}if(a.common.async)return Promise.all(s.map(async d=>{let x={...a,common:{...a.common,issues:[]},parent:null};return{result:await d._parseAsync({data:a.data,path:a.path,parent:x}),ctx:x}})).then(l);{let d,x=[];for(let m of s){let D={...a,common:{...a.common,issues:[]},parent:null},b=m._parseSync({data:a.data,path:a.path,parent:D});if(b.status==="valid")return b;b.status==="dirty"&&!d&&(d={result:b,ctx:D}),D.common.issues.length&&x.push(D.common.issues)}if(d)return a.common.issues.push(...d.ctx.common.issues),d.result;let f=x.map(m=>new Wo(m));return gr(a,{code:nr.invalid_union,unionErrors:f}),rn}}get options(){return this._def.options}};Nf.create=(r,e)=>new Nf({options:r,typeName:un.ZodUnion,...Fn(e)});Ul=r=>r instanceof Of?Ul(r.schema):r instanceof Ku?Ul(r.innerType()):r instanceof Lf?[r.value]:r instanceof $f?r.options:r instanceof zf?$n.objectValues(r.enum):r instanceof qf?Ul(r._def.innerType):r instanceof jf?[void 0]:r instanceof kf?[null]:r instanceof Hu?[void 0,...Ul(r.unwrap())]:r instanceof q0?[null,...Ul(r.unwrap())]:r instanceof gb||r instanceof Vf?Ul(r.unwrap()):r instanceof Uf?Ul(r._def.innerType):[],kA=class r extends Sn{_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==vr.object)return gr(a,{code:nr.invalid_type,expected:vr.object,received:a.parsedType}),rn;let s=this.discriminator,l=a.data[s],d=this.optionsMap.get(l);return d?a.common.async?d._parseAsync({data:a.data,path:a.path,parent:a}):d._parseSync({data:a.data,path:a.path,parent:a}):(gr(a,{code:nr.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),rn)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,a,s){let l=new Map;for(let d of a){let x=Ul(d.shape[e]);if(!x.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let f of x){if(l.has(f))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(f)}`);l.set(f,d)}}return new r({typeName:un.ZodDiscriminatedUnion,discriminator:e,options:a,optionsMap:l,...Fn(s)})}};Mf=class extends Sn{_parse(e){let{status:a,ctx:s}=this._processInputParams(e),l=(d,x)=>{if(IA(d)||IA(x))return rn;let f=xq(d.value,x.value);return f.valid?((jA(d)||jA(x))&&a.dirty(),{status:a.value,value:f.data}):(gr(s,{code:nr.invalid_intersection_types}),rn)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([d,x])=>l(d,x)):l(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};Mf.create=(r,e,a)=>new Mf({left:r,right:e,typeName:un.ZodIntersection,...Fn(a)});z0=class r extends Sn{_parse(e){let{status:a,ctx:s}=this._processInputParams(e);if(s.parsedType!==vr.array)return gr(s,{code:nr.invalid_type,expected:vr.array,received:s.parsedType}),rn;if(s.data.length<this._def.items.length)return gr(s,{code:nr.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),rn;!this._def.rest&&s.data.length>this._def.items.length&&(gr(s,{code:nr.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),a.dirty());let d=[...s.data].map((x,f)=>{let m=this._def.items[f]||this._def.rest;return m?m._parse(new Wu(s,x,s.path,f)):null}).filter(x=>!!x);return s.common.async?Promise.all(d).then(x=>Ri.mergeArray(a,x)):Ri.mergeArray(a,d)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};z0.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new z0({items:r,typeName:un.ZodTuple,rest:null,...Fn(e)})};NA=class r extends Sn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:a,ctx:s}=this._processInputParams(e);if(s.parsedType!==vr.object)return gr(s,{code:nr.invalid_type,expected:vr.object,received:s.parsedType}),rn;let l=[],d=this._def.keyType,x=this._def.valueType;for(let f in s.data)l.push({key:d._parse(new Wu(s,f,s.path,f)),value:x._parse(new Wu(s,s.data[f],s.path,f)),alwaysSet:f in s.data});return s.common.async?Ri.mergeObjectAsync(a,l):Ri.mergeObjectSync(a,l)}get element(){return this._def.valueType}static create(e,a,s){return a instanceof Sn?new r({keyType:e,valueType:a,typeName:un.ZodRecord,...Fn(s)}):new r({keyType:Ap.create(),valueType:e,typeName:un.ZodRecord,...Fn(a)})}},km=class extends Sn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:a,ctx:s}=this._processInputParams(e);if(s.parsedType!==vr.map)return gr(s,{code:nr.invalid_type,expected:vr.map,received:s.parsedType}),rn;let l=this._def.keyType,d=this._def.valueType,x=[...s.data.entries()].map(([f,m],D)=>({key:l._parse(new Wu(s,f,s.path,[D,"key"])),value:d._parse(new Wu(s,m,s.path,[D,"value"]))}));if(s.common.async){let f=new Map;return Promise.resolve().then(async()=>{for(let m of x){let D=await m.key,b=await m.value;if(D.status==="aborted"||b.status==="aborted")return rn;(D.status==="dirty"||b.status==="dirty")&&a.dirty(),f.set(D.value,b.value)}return{status:a.value,value:f}})}else{let f=new Map;for(let m of x){let D=m.key,b=m.value;if(D.status==="aborted"||b.status==="aborted")return rn;(D.status==="dirty"||b.status==="dirty")&&a.dirty(),f.set(D.value,b.value)}return{status:a.value,value:f}}}};km.create=(r,e,a)=>new km({valueType:e,keyType:r,typeName:un.ZodMap,...Fn(a)});Nm=class r extends Sn{_parse(e){let{status:a,ctx:s}=this._processInputParams(e);if(s.parsedType!==vr.set)return gr(s,{code:nr.invalid_type,expected:vr.set,received:s.parsedType}),rn;let l=this._def;l.minSize!==null&&s.data.size<l.minSize.value&&(gr(s,{code:nr.too_small,minimum:l.minSize.value,type:"set",inclusive:!0,exact:!1,message:l.minSize.message}),a.dirty()),l.maxSize!==null&&s.data.size>l.maxSize.value&&(gr(s,{code:nr.too_big,maximum:l.maxSize.value,type:"set",inclusive:!0,exact:!1,message:l.maxSize.message}),a.dirty());let d=this._def.valueType;function x(m){let D=new Set;for(let b of m){if(b.status==="aborted")return rn;b.status==="dirty"&&a.dirty(),D.add(b.value)}return{status:a.value,value:D}}let f=[...s.data.values()].map((m,D)=>d._parse(new Wu(s,m,s.path,D)));return s.common.async?Promise.all(f).then(m=>x(m)):x(f)}min(e,a){return new r({...this._def,minSize:{value:e,message:Nr.toString(a)}})}max(e,a){return new r({...this._def,maxSize:{value:e,message:Nr.toString(a)}})}size(e,a){return this.min(e,a).max(e,a)}nonempty(e){return this.min(1,e)}};Nm.create=(r,e)=>new Nm({valueType:r,minSize:null,maxSize:null,typeName:un.ZodSet,...Fn(e)});MA=class r extends Sn{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==vr.function)return gr(a,{code:nr.invalid_type,expected:vr.function,received:a.parsedType}),rn;function s(f,m){return mb({data:f,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,wm(),ql].filter(D=>!!D),issueData:{code:nr.invalid_arguments,argumentsError:m}})}function l(f,m){return mb({data:f,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,wm(),ql].filter(D=>!!D),issueData:{code:nr.invalid_return_type,returnTypeError:m}})}let d={errorMap:a.common.contextualErrorMap},x=a.data;if(this._def.returns instanceof Sp){let f=this;return Wi(async function(...m){let D=new Wo([]),b=await f._def.args.parseAsync(m,d).catch(B=>{throw D.addIssue(s(m,B)),D}),E=await Reflect.apply(x,this,b);return await f._def.returns._def.type.parseAsync(E,d).catch(B=>{throw D.addIssue(l(E,B)),D})})}else{let f=this;return Wi(function(...m){let D=f._def.args.safeParse(m,d);if(!D.success)throw new Wo([s(m,D.error)]);let b=Reflect.apply(x,this,D.data),E=f._def.returns.safeParse(b,d);if(!E.success)throw new Wo([l(b,E.error)]);return E.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:z0.create(e).rest(Vl.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,a,s){return new r({args:e||z0.create([]).rest(Vl.create()),returns:a||Vl.create(),typeName:un.ZodFunction,...Fn(s)})}},Of=class extends Sn{get schema(){return this._def.getter()}_parse(e){let{ctx:a}=this._processInputParams(e);return this._def.getter()._parse({data:a.data,path:a.path,parent:a})}};Of.create=(r,e)=>new Of({getter:r,typeName:un.ZodLazy,...Fn(e)});Lf=class extends Sn{_parse(e){if(e.data!==this._def.value){let a=this._getOrReturnCtx(e);return gr(a,{received:a.data,code:nr.invalid_literal,expected:this._def.value}),rn}return{status:"valid",value:e.data}}get value(){return this._def.value}};Lf.create=(r,e)=>new Lf({value:r,typeName:un.ZodLiteral,...Fn(e)});$f=class r extends Sn{_parse(e){if(typeof e.data!="string"){let a=this._getOrReturnCtx(e),s=this._def.values;return gr(a,{expected:$n.joinValues(s),received:a.parsedType,code:nr.invalid_type}),rn}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let a=this._getOrReturnCtx(e),s=this._def.values;return gr(a,{received:a.data,code:nr.invalid_enum_value,options:s}),rn}return Wi(e.data)}get options(){return this._def.values}get enum(){let e={};for(let a of this._def.values)e[a]=a;return e}get Values(){let e={};for(let a of this._def.values)e[a]=a;return e}get Enum(){let e={};for(let a of this._def.values)e[a]=a;return e}extract(e,a=this._def){return r.create(e,{...this._def,...a})}exclude(e,a=this._def){return r.create(this.options.filter(s=>!e.includes(s)),{...this._def,...a})}};$f.create=X2e;zf=class extends Sn{_parse(e){let a=$n.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==vr.string&&s.parsedType!==vr.number){let l=$n.objectValues(a);return gr(s,{expected:$n.joinValues(l),received:s.parsedType,code:nr.invalid_type}),rn}if(this._cache||(this._cache=new Set($n.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let l=$n.objectValues(a);return gr(s,{received:s.data,code:nr.invalid_enum_value,options:l}),rn}return Wi(e.data)}get enum(){return this._def.values}};zf.create=(r,e)=>new zf({values:r,typeName:un.ZodNativeEnum,...Fn(e)});Sp=class extends Sn{unwrap(){return this._def.type}_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==vr.promise&&a.common.async===!1)return gr(a,{code:nr.invalid_type,expected:vr.promise,received:a.parsedType}),rn;let s=a.parsedType===vr.promise?a.data:Promise.resolve(a.data);return Wi(s.then(l=>this._def.type.parseAsync(l,{path:a.path,errorMap:a.common.contextualErrorMap})))}};Sp.create=(r,e)=>new Sp({type:r,typeName:un.ZodPromise,...Fn(e)});Ku=class extends Sn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===un.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:a,ctx:s}=this._processInputParams(e),l=this._def.effect||null,d={addIssue:x=>{gr(s,x),x.fatal?a.abort():a.dirty()},get path(){return s.path}};if(d.addIssue=d.addIssue.bind(d),l.type==="preprocess"){let x=l.transform(s.data,d);if(s.common.async)return Promise.resolve(x).then(async f=>{if(a.value==="aborted")return rn;let m=await this._def.schema._parseAsync({data:f,path:s.path,parent:s});return m.status==="aborted"?rn:m.status==="dirty"?Bf(m.value):a.value==="dirty"?Bf(m.value):m});{if(a.value==="aborted")return rn;let f=this._def.schema._parseSync({data:x,path:s.path,parent:s});return f.status==="aborted"?rn:f.status==="dirty"?Bf(f.value):a.value==="dirty"?Bf(f.value):f}}if(l.type==="refinement"){let x=f=>{let m=l.refinement(f,d);if(s.common.async)return Promise.resolve(m);if(m instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return f};if(s.common.async===!1){let f=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return f.status==="aborted"?rn:(f.status==="dirty"&&a.dirty(),x(f.value),{status:a.value,value:f.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(f=>f.status==="aborted"?rn:(f.status==="dirty"&&a.dirty(),x(f.value).then(()=>({status:a.value,value:f.value}))))}if(l.type==="transform")if(s.common.async===!1){let x=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!_p(x))return rn;let f=l.transform(x.value,d);if(f instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:a.value,value:f}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(x=>_p(x)?Promise.resolve(l.transform(x.value,d)).then(f=>({status:a.value,value:f})):rn);$n.assertNever(l)}};Ku.create=(r,e,a)=>new Ku({schema:r,typeName:un.ZodEffects,effect:e,...Fn(a)});Ku.createWithPreprocess=(r,e,a)=>new Ku({schema:e,effect:{type:"preprocess",transform:r},typeName:un.ZodEffects,...Fn(a)});Hu=class extends Sn{_parse(e){return this._getType(e)===vr.undefined?Wi(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Hu.create=(r,e)=>new Hu({innerType:r,typeName:un.ZodOptional,...Fn(e)});q0=class extends Sn{_parse(e){return this._getType(e)===vr.null?Wi(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};q0.create=(r,e)=>new q0({innerType:r,typeName:un.ZodNullable,...Fn(e)});qf=class extends Sn{_parse(e){let{ctx:a}=this._processInputParams(e),s=a.data;return a.parsedType===vr.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:a.path,parent:a})}removeDefault(){return this._def.innerType}};qf.create=(r,e)=>new qf({innerType:r,typeName:un.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Fn(e)});Uf=class extends Sn{_parse(e){let{ctx:a}=this._processInputParams(e),s={...a,common:{...a.common,issues:[]}},l=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Tm(l)?l.then(d=>({status:"valid",value:d.status==="valid"?d.value:this._def.catchValue({get error(){return new Wo(s.common.issues)},input:s.data})})):{status:"valid",value:l.status==="valid"?l.value:this._def.catchValue({get error(){return new Wo(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};Uf.create=(r,e)=>new Uf({innerType:r,typeName:un.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Fn(e)});Mm=class extends Sn{_parse(e){if(this._getType(e)!==vr.nan){let s=this._getOrReturnCtx(e);return gr(s,{code:nr.invalid_type,expected:vr.nan,received:s.parsedType}),rn}return{status:"valid",value:e.data}}};Mm.create=r=>new Mm({typeName:un.ZodNaN,...Fn(r)});Svt=Symbol("zod_brand"),gb=class extends Sn{_parse(e){let{ctx:a}=this._processInputParams(e),s=a.data;return this._def.type._parse({data:s,path:a.path,parent:a})}unwrap(){return this._def.type}},Db=class r extends Sn{_parse(e){let{status:a,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let d=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return d.status==="aborted"?rn:d.status==="dirty"?(a.dirty(),Bf(d.value)):this._def.out._parseAsync({data:d.value,path:s.path,parent:s})})();{let l=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return l.status==="aborted"?rn:l.status==="dirty"?(a.dirty(),{status:"dirty",value:l.value}):this._def.out._parseSync({data:l.value,path:s.path,parent:s})}}static create(e,a){return new r({in:e,out:a,typeName:un.ZodPipeline})}},Vf=class extends Sn{_parse(e){let a=this._def.innerType._parse(e),s=l=>(_p(l)&&(l.value=Object.freeze(l.value)),l);return Tm(a)?a.then(l=>s(l)):s(a)}unwrap(){return this._def.innerType}};Vf.create=(r,e)=>new Vf({innerType:r,typeName:un.ZodReadonly,...Fn(e)});Bvt={object:Ko.lazycreate};(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(un||(un={}));wvt=(r,e={message:`Input not instance of ${r.name}`})=>Y2e(a=>a instanceof r,e),H2e=Ap.create,W2e=wf.create,Tvt=Mm.create,Pvt=Tf.create,K2e=Pf.create,Ivt=If.create,jvt=Im.create,kvt=jf.create,Nvt=kf.create,Mvt=Rp.create,Ovt=Vl.create,Lvt=Nc.create,$vt=jm.create,zvt=Gl.create,qvt=Ko.create,Uvt=Ko.strictCreate,Vvt=Nf.create,Gvt=kA.create,Xvt=Mf.create,Yvt=z0.create,Hvt=NA.create,Wvt=km.create,Kvt=Nm.create,Jvt=MA.create,Zvt=Of.create,Qvt=Lf.create,eCt=$f.create,tCt=zf.create,rCt=Sp.create,nCt=Ku.create,aCt=Hu.create,sCt=q0.create,iCt=Ku.createWithPreprocess,oCt=Db.create,uCt=()=>H2e().optional(),cCt=()=>W2e().optional(),lCt=()=>K2e().optional(),dCt={string:(r=>Ap.create({...r,coerce:!0})),number:(r=>wf.create({...r,coerce:!0})),boolean:(r=>Pf.create({...r,coerce:!0})),bigint:(r=>Tf.create({...r,coerce:!0})),date:(r=>If.create({...r,coerce:!0}))},pCt=rn});var v={};Am(v,{BRAND:()=>Svt,DIRTY:()=>Bf,EMPTY_PATH:()=>ivt,INVALID:()=>rn,NEVER:()=>pCt,OK:()=>Wi,ParseStatus:()=>Ri,Schema:()=>Sn,ZodAny:()=>Rp,ZodArray:()=>Gl,ZodBigInt:()=>Tf,ZodBoolean:()=>Pf,ZodBranded:()=>gb,ZodCatch:()=>Uf,ZodDate:()=>If,ZodDefault:()=>qf,ZodDiscriminatedUnion:()=>kA,ZodEffects:()=>Ku,ZodEnum:()=>$f,ZodError:()=>Wo,ZodFirstPartyTypeKind:()=>un,ZodFunction:()=>MA,ZodIntersection:()=>Mf,ZodIssueCode:()=>nr,ZodLazy:()=>Of,ZodLiteral:()=>Lf,ZodMap:()=>km,ZodNaN:()=>Mm,ZodNativeEnum:()=>zf,ZodNever:()=>Nc,ZodNull:()=>kf,ZodNullable:()=>q0,ZodNumber:()=>wf,ZodObject:()=>Ko,ZodOptional:()=>Hu,ZodParsedType:()=>vr,ZodPipeline:()=>Db,ZodPromise:()=>Sp,ZodReadonly:()=>Vf,ZodRecord:()=>NA,ZodSchema:()=>Sn,ZodSet:()=>Nm,ZodString:()=>Ap,ZodSymbol:()=>Im,ZodTransformer:()=>Ku,ZodTuple:()=>z0,ZodType:()=>Sn,ZodUndefined:()=>jf,ZodUnion:()=>Nf,ZodUnknown:()=>Vl,ZodVoid:()=>jm,addIssueToContext:()=>gr,any:()=>Mvt,array:()=>zvt,bigint:()=>Pvt,boolean:()=>K2e,coerce:()=>dCt,custom:()=>Y2e,date:()=>Ivt,datetimeRegex:()=>G2e,defaultErrorMap:()=>ql,discriminatedUnion:()=>Gvt,effect:()=>nCt,enum:()=>eCt,function:()=>Jvt,getErrorMap:()=>wm,getParsedType:()=>$0,instanceof:()=>wvt,intersection:()=>Xvt,isAborted:()=>IA,isAsync:()=>Tm,isDirty:()=>jA,isValid:()=>_p,late:()=>Bvt,lazy:()=>Zvt,literal:()=>Qvt,makeIssue:()=>mb,map:()=>Wvt,nan:()=>Tvt,nativeEnum:()=>tCt,never:()=>Lvt,null:()=>Nvt,nullable:()=>sCt,number:()=>W2e,object:()=>qvt,objectUtil:()=>cq,oboolean:()=>lCt,onumber:()=>cCt,optional:()=>aCt,ostring:()=>uCt,pipeline:()=>oCt,preprocess:()=>iCt,promise:()=>rCt,quotelessJson:()=>nvt,record:()=>Hvt,set:()=>Kvt,setErrorMap:()=>svt,strictObject:()=>Uvt,string:()=>H2e,symbol:()=>jvt,transformer:()=>nCt,tuple:()=>Yvt,undefined:()=>kvt,union:()=>Vvt,unknown:()=>Ovt,util:()=>$n,void:()=>$vt});var fq=Sr(()=>{"use strict";PA();dq();L2e();hb();J2e();TA()});var Ue=Sr(()=>{"use strict";fq();fq()});var Hf={};Am(Hf,{all_layers:()=>$m,any_circuit_element:()=>zFe,any_soup_element:()=>Yf,any_source_component:()=>obe,battery_capacity:()=>tbe,brep_shape:()=>$be,cad_component:()=>NFe,capacitance:()=>Xl,circuit_json_footprint_load_error:()=>VA,current:()=>fCt,distance:()=>Be,external_footprint_load_error:()=>yb,frequency:()=>Oc,getZodPrefixedIdWithDefault:()=>Cr,inductance:()=>OA,layer_ref:()=>dn,layer_string:()=>mq,length:()=>pe,ninePointAnchor:()=>LA,pcb_autorouting_error:()=>AFe,pcb_board:()=>oFe,pcb_breakout_point:()=>RFe,pcb_component:()=>qbe,pcb_component_outside_board_error:()=>kFe,pcb_copper_pour:()=>jFe,pcb_copper_pour_brep:()=>PFe,pcb_copper_pour_polygon:()=>IFe,pcb_copper_pour_rect:()=>TFe,pcb_cutout:()=>vFe,pcb_cutout_circle:()=>FFe,pcb_cutout_polygon:()=>EFe,pcb_cutout_rect:()=>bFe,pcb_fabrication_note_path:()=>gFe,pcb_fabrication_note_text:()=>mFe,pcb_footprint_overlap_error:()=>DFe,pcb_ground_plane:()=>SFe,pcb_ground_plane_region:()=>BFe,pcb_group:()=>_Fe,pcb_hole:()=>Gbe,pcb_hole_circle_or_square_shape:()=>ECt,pcb_hole_oval_shape:()=>vCt,pcb_keepout:()=>yFe,pcb_manual_edit_conflict_warning:()=>GA,pcb_missing_footprint_error:()=>CFe,pcb_net:()=>sFe,pcb_placement_error:()=>uFe,pcb_plated_hole:()=>Xbe,pcb_port:()=>Ybe,pcb_port_not_connected_error:()=>aFe,pcb_port_not_matched_error:()=>nFe,pcb_route_hint:()=>zbe,pcb_route_hints:()=>FCt,pcb_silkscreen_circle:()=>fFe,pcb_silkscreen_line:()=>lFe,pcb_silkscreen_oval:()=>hFe,pcb_silkscreen_path:()=>dFe,pcb_silkscreen_rect:()=>xFe,pcb_silkscreen_text:()=>pFe,pcb_smtpad:()=>Wbe,pcb_smtpad_pill:()=>Hbe,pcb_solder_paste:()=>Kbe,pcb_text:()=>Jbe,pcb_thermal_spoke:()=>wFe,pcb_trace:()=>eFe,pcb_trace_error:()=>tFe,pcb_trace_hint:()=>cFe,pcb_trace_missing_error:()=>rFe,pcb_trace_route_point:()=>UA,pcb_trace_route_point_via:()=>Qbe,pcb_trace_route_point_wire:()=>Zbe,pcb_via:()=>iFe,point:()=>Hr,point3:()=>Gf,point_with_bulge:()=>Lbe,port_arrangement:()=>ybe,position:()=>mCt,position3:()=>gCt,resistance:()=>Bp,ring:()=>gq,rotation:()=>Gn,route_hint_point:()=>bo,schematic_arc:()=>Cbe,schematic_box:()=>fbe,schematic_circle:()=>vbe,schematic_component:()=>bbe,schematic_component_port_arrangement_by_sides:()=>Dbe,schematic_component_port_arrangement_by_size:()=>gbe,schematic_debug_line:()=>Pbe,schematic_debug_object:()=>jbe,schematic_debug_object_base:()=>zA,schematic_debug_point:()=>Ibe,schematic_debug_rect:()=>Tbe,schematic_error:()=>Bbe,schematic_group:()=>Nbe,schematic_layout_error:()=>wbe,schematic_line:()=>Fbe,schematic_manual_edit_conflict_warning:()=>qA,schematic_net_label:()=>Sbe,schematic_path:()=>hbe,schematic_pin_styles:()=>mbe,schematic_port:()=>Rbe,schematic_rect:()=>Ebe,schematic_table:()=>Mbe,schematic_table_cell:()=>Obe,schematic_text:()=>Abe,schematic_trace:()=>_be,schematic_voltage_probe:()=>kbe,simulation_ac_voltage_source:()=>LFe,simulation_dc_voltage_source:()=>OFe,simulation_voltage_source:()=>$Fe,size:()=>Dq,source_component_base:()=>Is,source_failed_to_create_component_error:()=>sbe,source_group:()=>lbe,source_manually_placed_via:()=>xbe,source_missing_property_error:()=>abe,source_net:()=>dbe,source_pcb_ground_plane:()=>pbe,source_pin_missing_trace_warning:()=>Mq,source_port:()=>ube,source_project_metadata:()=>kq,source_property_ignored_warning:()=>ibe,source_simple_battery:()=>Cq,source_simple_capacitor:()=>yq,source_simple_chip:()=>Eq,source_simple_crystal:()=>nbe,source_simple_diode:()=>$A,source_simple_ground:()=>rbe,source_simple_inductor:()=>_q,source_simple_led:()=>Fq,source_simple_mosfet:()=>Iq,source_simple_pin_header:()=>Sq,source_simple_pinout:()=>Bq,source_simple_potentiometer:()=>Rq,source_simple_power_source:()=>vq,source_simple_push_button:()=>Aq,source_simple_resistor:()=>bq,source_simple_resonator:()=>wq,source_simple_switch:()=>jq,source_simple_test_point:()=>Pq,source_simple_transistor:()=>Tq,source_trace:()=>cbe,source_trace_not_connected_error:()=>Nq,supplier_name:()=>Lm,time:()=>hCt,visible_layer:()=>zm,voltage:()=>Us,wave_shape:()=>MFe});function xCt(r){for(let[e,a]of Object.entries(ebe))if(r in a.variants)return{baseUnit:a.baseUnit,conversionFactor:a.variants[r]};return{baseUnit:r,conversionFactor:1}}var ebe,hq,Q2e,Mc,Bp,Xl,OA,Us,pe,Oc,Be,fCt,hCt,Gn,tbe,Pt,Xf,Hr,mCt,Gf,gCt,Dq,DCt,Cr,LA,Lm,Is,yq,bq,$A,Fq,rbe,Eq,vq,yCt,Cq,_q,Aq,Rq,nbe,Sq,Bq,wq,Tq,Pq,Iq,jq,kq,abe,sbe,Nq,ibe,Mq,obe,ube,cbe,lbe,dbe,pbe,$m,mq,dn,zm,xbe,fbe,hbe,mbe,gbe,Dbe,ybe,bbe,Fbe,Ebe,vbe,Cbe,_be,bCt,Abe,Rbe,Sbe,Bbe,wbe,zA,Tbe,Pbe,Ibe,jbe,kbe,qA,Nbe,Mbe,Obe,Lbe,gq,$be,zbe,FCt,bo,qbe,Ube,ECt,Vbe,vCt,Gbe,CCt,_Ct,ACt,RCt,SCt,Xbe,Ybe,BCt,wCt,TCt,Hbe,PCt,ICt,Wbe,jCt,kCt,NCt,MCt,OCt,Kbe,Jbe,Zbe,Qbe,UA,eFe,tFe,rFe,nFe,aFe,sFe,iFe,oFe,uFe,cFe,lFe,dFe,pFe,xFe,fFe,hFe,mFe,gFe,DFe,yFe,Oq,bFe,FFe,EFe,vFe,CFe,yb,VA,_Fe,AFe,GA,RFe,SFe,BFe,wFe,Lq,TFe,PFe,IFe,jFe,kFe,NFe,MFe,LCt,OFe,LFe,$Fe,zFe,Yf,qt=Sr(()=>{"use strict";Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();ebe={Hz:{baseUnit:"Hz",variants:{MHz:1e6,kHz:1e3,Hz:1}},g:{baseUnit:"g",variants:{kg:1e3,g:1}},\u03A9:{baseUnit:"\u03A9",variants:{m\u03A9:.001,\u03A9:1,k\u03A9:1e3,K\u03A9:1e3,kohm:1e3,M\u03A9:1e6,G\u03A9:1e9,T\u03A9:1e12}},V:{baseUnit:"V",variants:{mV:.001,V:1,kV:1e3,KV:1e3,MV:1e6,GV:1e9,TV:1e12}},A:{baseUnit:"A",variants:{\u00B5A:1e-6,mA:.001,ma:.001,A:1,kA:1e3,MA:1e6}},F:{baseUnit:"F",variants:{pF:1e-12,nF:1e-9,\u00B5F:1e-6,uF:1e-6,mF:.001,F:1}},ml:{baseUnit:"ml",variants:{ml:1,mL:1,l:1e3,L:1e3}},deg:{baseUnit:"deg",variants:{rad:180/Math.PI}},ms:{baseUnit:"ms",variants:{s:1e3}},mm:{baseUnit:"mm",variants:{nm:1e-6,\u00B5m:.001,um:.001,mm:1,cm:10,dm:100,m:1e3,km:1e6,in:25.4,ft:304.8,IN:25.4,FT:304.8,yd:914.4,mi:1609344,mil:.0254}}},hq=new Set;for(let[r,e]of Object.entries(ebe)){hq.add(r);for(let a of Object.keys(e.variants))hq.add(a)}Q2e={tera:1e12,T:1e12,giga:1e9,G:1e9,mega:1e6,M:1e6,kilo:1e3,k:1e3,deci:.1,d:.1,centi:.01,c:.01,milli:.001,m:.001,micro:1e-6,u:1e-6,\u00B5:1e-6,nano:1e-9,n:1e-9,pico:1e-12,p:1e-12},Mc=r=>{if(typeof r>"u")return{parsedUnit:null,unitOfValue:null,value:null};if(typeof r=="string"&&r.match(/^-?[\d\.]+$/))return{value:Number.parseFloat(r),parsedUnit:null,unitOfValue:null};if(typeof r=="number")return{value:r,parsedUnit:null,unitOfValue:null};if(typeof r=="object"&&"x"in r&&"y"in r){let{parsedUnit:f,unitOfValue:m}=Mc(r.x);return{parsedUnit:f,unitOfValue:m,value:{x:Mc(r.x).value,y:Mc(r.y).value}}}let a=r.toString().split("").reverse().join("").match(/[^\d\s]+/)?.[0];if(!a)throw new Error(`Could not determine unit: "${r}"`);let s=a.split("").reverse().join(""),l=r.slice(0,-s.length);if(s in Q2e&&!hq.has(s)){let f=Q2e[s];return{parsedUnit:null,unitOfValue:null,value:Number.parseFloat(l)*f}}let{baseUnit:d,conversionFactor:x}=xCt(s);return{parsedUnit:s,unitOfValue:d,value:x*Number.parseFloat(l)}},Bp=v.string().or(v.number()).transform(r=>Mc(r).value),Xl=v.string().or(v.number()).transform(r=>Mc(r).value).transform(r=>Number.parseFloat(r.toPrecision(12))),OA=v.string().or(v.number()).transform(r=>Mc(r).value),Us=v.string().or(v.number()).transform(r=>Mc(r).value),pe=v.string().or(v.number()).transform(r=>Mc(r).value),Oc=v.string().or(v.number()).transform(r=>Mc(r).value),Be=pe,fCt=v.string().or(v.number()).transform(r=>Mc(r).value),hCt=v.string().or(v.number()).transform(r=>Mc(r).value),Gn=v.string().or(v.number()).transform(r=>typeof r=="number"?r:r.endsWith("deg")?Number.parseFloat(r.split("deg")[0]):r.endsWith("rad")?Number.parseFloat(r.split("rad")[0])*180/Math.PI:Number.parseFloat(r)),tbe=v.number().or(v.string().endsWith("mAh")).transform(r=>{if(typeof r=="string"){let e=r.replace("mAh",""),a=Number.parseFloat(e);if(Number.isNaN(a))throw new Error("Invalid capacity");return a}return r}).describe("Battery capacity in mAh"),Pt=r=>{};Pt("extra props b");Pt("missing props b");Pt(!0);Pt("mismatched prop types: a");Xf=r=>{};Xf(!0);Xf('T1 has extra: "c", T2 has extra: "d"');Xf('T1 has extra: "c"');Xf('T2 has extra: "c"');Xf('T1 has extra: "d", T2 has extra: "c"');Xf(!0);Hr=v.object({x:Be,y:Be}),mCt=Hr;Pt(!0);Pt(!0);Gf=v.object({x:Be,y:Be,z:Be}),gCt=Gf;Pt(!0);Dq=v.object({width:v.number(),height:v.number()});Pt(!0);DCt=r=>{let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";return Array.from({length:r},()=>e[Math.floor(Math.random()*e.length)]).join("")},Cr=r=>v.string().optional().default(()=>`${r}_${DCt(10)}`),LA=v.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]);Pt(!0);Lm=v.enum(["jlcpcb","macrofab","pcbway","digikey","mouser","lcsc"]);Pt(!0);Is=v.object({type:v.literal("source_component"),ftype:v.string().optional(),source_component_id:v.string(),name:v.string(),manufacturer_part_number:v.string().optional(),supplier_part_numbers:v.record(Lm,v.array(v.string())).optional(),display_value:v.string().optional(),are_pins_interchangeable:v.boolean().optional(),internally_connected_source_port_ids:v.array(v.array(v.string())).optional(),source_group_id:v.string().optional(),subcircuit_id:v.string().optional()});Pt(!0);yq=Is.extend({ftype:v.literal("simple_capacitor"),capacitance:Xl,max_voltage_rating:Us.optional(),display_capacitance:v.string().optional(),max_decoupling_trace_length:Be.optional()});Pt(!0);bq=Is.extend({ftype:v.literal("simple_resistor"),resistance:Bp,display_resistance:v.string().optional()});Pt(!0);$A=Is.extend({ftype:v.literal("simple_diode")});Pt(!0);Fq=$A.extend({ftype:v.literal("simple_led"),color:v.string().optional(),wavelength:v.string().optional()});Pt(!0);rbe=Is.extend({ftype:v.literal("simple_ground")});Pt(!0);Eq=Is.extend({ftype:v.literal("simple_chip")});Pt(!0);vq=Is.extend({ftype:v.literal("simple_power_source"),voltage:Us});Pt(!0);yCt=Is.extend({ftype:v.literal("simple_fuse"),current_rating_amps:v.number().describe("Nominal current in amps the fuse is rated for"),voltage_rating_volts:v.number().describe("Voltage rating in volts, e.g. \xB15V would be 5")});Pt(!0);Cq=Is.extend({ftype:v.literal("simple_battery"),capacity:tbe});Pt(!0);_q=Is.extend({ftype:v.literal("simple_inductor"),inductance:OA,max_current_rating:v.number().optional()});Pt(!0);Aq=Is.extend({ftype:v.literal("simple_push_button")});Pt(!0);Rq=Is.extend({ftype:v.literal("simple_potentiometer"),max_resistance:Bp});Pt(!0);nbe=Is.extend({ftype:v.literal("simple_crystal"),frequency:v.number().describe("Frequency in Hz"),load_capacitance:v.number().optional().describe("Load capacitance in pF")});Pt(!0);Sq=Is.extend({ftype:v.literal("simple_pin_header"),pin_count:v.number(),gender:v.enum(["male","female"]).optional().default("male")});Pt(!0);Bq=Is.extend({ftype:v.literal("simple_pinout")});Pt(!0);wq=Is.extend({ftype:v.literal("simple_resonator"),load_capacitance:Xl,equivalent_series_resistance:Bp.optional(),frequency:Oc});Pt(!0);Tq=Is.extend({ftype:v.literal("simple_transistor"),transistor_type:v.enum(["npn","pnp"])});Pt(!0);Pq=Is.extend({ftype:v.literal("simple_test_point"),footprint_variant:v.enum(["pad","through_hole"]).optional(),pad_shape:v.enum(["rect","circle"]).optional(),pad_diameter:v.union([v.number(),v.string()]).optional(),hole_diameter:v.union([v.number(),v.string()]).optional(),width:v.union([v.number(),v.string()]).optional(),height:v.union([v.number(),v.string()]).optional()});Pt(!0);Iq=Is.extend({ftype:v.literal("simple_mosfet"),channel_type:v.enum(["n","p"]),mosfet_mode:v.enum(["enhancement","depletion"])});Pt(!0);jq=Is.extend({ftype:v.literal("simple_switch")});Pt(!0);kq=v.object({type:v.literal("source_project_metadata"),name:v.string().optional(),software_used_string:v.string().optional(),project_url:v.string().optional(),created_at:v.string().datetime().optional()});Pt(!0);abe=v.object({type:v.literal("source_missing_property_error"),source_missing_property_error_id:Cr("source_missing_property_error"),source_component_id:v.string(),property_name:v.string(),subcircuit_id:v.string().optional(),error_type:v.literal("source_missing_property_error").default("source_missing_property_error"),message:v.string()}).describe("The source code is missing a property");Pt(!0);sbe=v.object({type:v.literal("source_failed_to_create_component_error"),source_failed_to_create_component_error_id:Cr("source_failed_to_create_component_error"),error_type:v.literal("source_failed_to_create_component_error").default("source_failed_to_create_component_error"),component_name:v.string().optional(),subcircuit_id:v.string().optional(),parent_source_component_id:v.string().optional(),message:v.string(),pcb_center:v.object({x:v.number().optional(),y:v.number().optional()}).optional(),schematic_center:v.object({x:v.number().optional(),y:v.number().optional()}).optional()}).describe("Error emitted when a component fails to be constructed");Pt(!0);Nq=v.object({type:v.literal("source_trace_not_connected_error"),source_trace_not_connected_error_id:Cr("source_trace_not_connected_error"),error_type:v.literal("source_trace_not_connected_error").default("source_trace_not_connected_error"),message:v.string(),subcircuit_id:v.string().optional(),source_group_id:v.string().optional(),source_trace_id:v.string().optional(),connected_source_port_ids:v.array(v.string()).optional(),selectors_not_found:v.array(v.string()).optional()}).describe("Occurs when a source trace selector does not match any ports");Pt(!0);ibe=v.object({type:v.literal("source_property_ignored_warning"),source_property_ignored_warning_id:Cr("source_property_ignored_warning"),source_component_id:v.string(),property_name:v.string(),subcircuit_id:v.string().optional(),error_type:v.literal("source_property_ignored_warning").default("source_property_ignored_warning"),message:v.string()}).describe("The source property was ignored");Pt(!0);Mq=v.object({type:v.literal("source_pin_missing_trace_warning"),source_pin_missing_trace_warning_id:Cr("source_pin_missing_trace_warning"),warning_type:v.literal("source_pin_missing_trace_warning").default("source_pin_missing_trace_warning"),message:v.string(),source_component_id:v.string(),source_port_id:v.string(),subcircuit_id:v.string().optional()}).describe("Warning emitted when a source component pin is missing a trace connection");Pt(!0);obe=v.union([bq,yq,$A,Fq,rbe,Eq,vq,Cq,_q,Aq,Rq,nbe,Sq,Bq,wq,jq,Tq,Pq,Iq,yCt,kq,abe,sbe,Nq,ibe,Mq]);Pt(!0);ube=v.object({type:v.literal("source_port"),pin_number:v.number().optional(),port_hints:v.array(v.string()).optional(),name:v.string(),source_port_id:v.string(),source_component_id:v.string(),subcircuit_id:v.string().optional(),subcircuit_connectivity_map_key:v.string().optional()});Pt(!0);cbe=v.object({type:v.literal("source_trace"),source_trace_id:v.string(),connected_source_port_ids:v.array(v.string()),connected_source_net_ids:v.array(v.string()),subcircuit_id:v.string().optional(),subcircuit_connectivity_map_key:v.string().optional(),max_length:v.number().optional(),min_trace_thickness:v.number().optional(),display_name:v.string().optional()});Pt(!0);lbe=v.object({type:v.literal("source_group"),source_group_id:v.string(),subcircuit_id:v.string().optional(),parent_subcircuit_id:v.string().optional(),parent_source_group_id:v.string().optional(),is_subcircuit:v.boolean().optional(),show_as_schematic_box:v.boolean().optional(),name:v.string().optional()});Pt(!0);dbe=v.object({type:v.literal("source_net"),source_net_id:v.string(),name:v.string(),member_source_group_ids:v.array(v.string()),is_power:v.boolean().optional(),is_ground:v.boolean().optional(),is_digital_signal:v.boolean().optional(),is_analog_signal:v.boolean().optional(),is_positive_voltage_source:v.boolean().optional(),trace_width:v.number().optional(),subcircuit_id:v.string().optional(),subcircuit_connectivity_map_key:v.string().optional()});Pt(!0);pbe=v.object({type:v.literal("source_pcb_ground_plane"),source_pcb_ground_plane_id:v.string(),source_group_id:v.string(),source_net_id:v.string(),subcircuit_id:v.string().optional()}).describe("Defines a ground plane in the source domain");Pt(!0);$m=["top","bottom","inner1","inner2","inner3","inner4","inner5","inner6"],mq=v.enum($m),dn=mq.or(v.object({name:mq})).transform(r=>typeof r=="string"?r:r.name);Pt(!0);zm=v.enum(["top","bottom"]),xbe=v.object({type:v.literal("source_manually_placed_via"),source_manually_placed_via_id:v.string(),source_group_id:v.string(),source_net_id:v.string(),subcircuit_id:v.string().optional(),source_trace_id:v.string().optional()}).describe("Defines a via that is manually placed in the source domain");Pt(!0);fbe=v.object({type:v.literal("schematic_box"),schematic_component_id:v.string().optional(),width:Be,height:Be,is_dashed:v.boolean().default(!1),x:Be,y:Be,subcircuit_id:v.string().optional()}).describe("Draws a box on the schematic");Pt(!0);hbe=v.object({type:v.literal("schematic_path"),schematic_component_id:v.string(),fill_color:v.enum(["red","blue"]).optional(),is_filled:v.boolean().optional(),points:v.array(Hr),subcircuit_id:v.string().optional()});Pt(!0);mbe=v.record(v.object({left_margin:pe.optional(),right_margin:pe.optional(),top_margin:pe.optional(),bottom_margin:pe.optional()})),gbe=v.object({left_size:v.number(),right_size:v.number(),top_size:v.number().optional(),bottom_size:v.number().optional()});Pt(!0);Dbe=v.object({left_side:v.object({pins:v.array(v.number()),direction:v.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),right_side:v.object({pins:v.array(v.number()),direction:v.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),top_side:v.object({pins:v.array(v.number()),direction:v.enum(["left-to-right","right-to-left"]).optional()}).optional(),bottom_side:v.object({pins:v.array(v.number()),direction:v.enum(["left-to-right","right-to-left"]).optional()}).optional()});Pt(!0);ybe=v.union([gbe,Dbe]),bbe=v.object({type:v.literal("schematic_component"),size:Dq,center:Hr,source_component_id:v.string().optional(),schematic_component_id:v.string(),pin_spacing:pe.optional(),pin_styles:mbe.optional(),box_width:pe.optional(),symbol_name:v.string().optional(),port_arrangement:ybe.optional(),port_labels:v.record(v.string()).optional(),symbol_display_value:v.string().optional(),subcircuit_id:v.string().optional(),schematic_group_id:v.string().optional(),is_schematic_group:v.boolean().optional(),source_group_id:v.string().optional()});Pt(!0);Fbe=v.object({type:v.literal("schematic_line"),schematic_line_id:Cr("schematic_line"),schematic_component_id:v.string(),x1:Be,y1:Be,x2:Be,y2:Be,stroke_width:Be.nullable().optional(),color:v.string().default("#000000"),is_dashed:v.boolean().default(!1),subcircuit_id:v.string().optional()}).describe("Draws a styled line on the schematic");Pt(!0);Ebe=v.object({type:v.literal("schematic_rect"),schematic_rect_id:Cr("schematic_rect"),schematic_component_id:v.string(),center:Hr,width:Be,height:Be,rotation:Gn.default(0),stroke_width:Be.nullable().optional(),color:v.string().default("#000000"),is_filled:v.boolean().default(!1),fill_color:v.string().optional(),is_dashed:v.boolean().default(!1),subcircuit_id:v.string().optional()}).describe("Draws a styled rectangle on the schematic");Pt(!0);vbe=v.object({type:v.literal("schematic_circle"),schematic_circle_id:Cr("schematic_circle"),schematic_component_id:v.string(),center:Hr,radius:Be,stroke_width:Be.nullable().optional(),color:v.string().default("#000000"),is_filled:v.boolean().default(!1),fill_color:v.string().optional(),is_dashed:v.boolean().default(!1),subcircuit_id:v.string().optional()}).describe("Draws a styled circle on the schematic");Pt(!0);Cbe=v.object({type:v.literal("schematic_arc"),schematic_arc_id:Cr("schematic_arc"),schematic_component_id:v.string(),center:Hr,radius:Be,start_angle_degrees:Gn,end_angle_degrees:Gn,direction:v.enum(["clockwise","counterclockwise"]).default("counterclockwise"),stroke_width:Be.nullable().optional(),color:v.string().default("#000000"),is_dashed:v.boolean().default(!1),subcircuit_id:v.string().optional()}).describe("Draws a styled arc on the schematic");Pt(!0);_be=v.object({type:v.literal("schematic_trace"),schematic_trace_id:v.string(),source_trace_id:v.string().optional(),junctions:v.array(v.object({x:v.number(),y:v.number()})),edges:v.array(v.object({from:v.object({x:v.number(),y:v.number()}),to:v.object({x:v.number(),y:v.number()}),is_crossing:v.boolean().optional(),from_schematic_port_id:v.string().optional(),to_schematic_port_id:v.string().optional()})),subcircuit_id:v.string().optional(),subcircuit_connectivity_map_key:v.string().optional()});Pt(!0);bCt=v.enum(["center","left","right","top","bottom"]);Pt(!0);Abe=v.object({type:v.literal("schematic_text"),schematic_component_id:v.string().optional(),schematic_text_id:v.string(),text:v.string(),font_size:v.number().default(.18),position:v.object({x:Be,y:Be}),rotation:v.number().default(0),anchor:v.union([bCt.describe("legacy"),LA]).default("center"),color:v.string().default("#000000"),subcircuit_id:v.string().optional()});Pt(!0);Rbe=v.object({type:v.literal("schematic_port"),schematic_port_id:v.string(),source_port_id:v.string(),schematic_component_id:v.string().optional(),center:Hr,facing_direction:v.enum(["up","down","left","right"]).optional(),distance_from_component_edge:v.number().optional(),side_of_component:v.enum(["top","bottom","left","right"]).optional(),true_ccw_index:v.number().optional(),pin_number:v.number().optional(),display_pin_label:v.string().optional(),subcircuit_id:v.string().optional(),is_connected:v.boolean().optional(),has_input_arrow:v.boolean().optional(),has_output_arrow:v.boolean().optional()}).describe("Defines a port on a schematic component");Pt(!0);Sbe=v.object({type:v.literal("schematic_net_label"),schematic_net_label_id:Cr("schematic_net_label"),schematic_trace_id:v.string().optional(),source_trace_id:v.string().optional(),source_net_id:v.string(),center:Hr,anchor_position:Hr.optional(),anchor_side:v.enum(["top","bottom","left","right"]),text:v.string(),symbol_name:v.string().optional(),is_movable:v.boolean().optional(),subcircuit_id:v.string().optional()});Pt(!0);Bbe=v.object({type:v.literal("schematic_error"),schematic_error_id:v.string(),error_type:v.literal("schematic_port_not_found").default("schematic_port_not_found"),message:v.string(),subcircuit_id:v.string().optional()}).describe("Defines a schematic error on the schematic");Pt(!0);wbe=v.object({type:v.literal("schematic_layout_error"),schematic_layout_error_id:Cr("schematic_layout_error"),error_type:v.literal("schematic_layout_error").default("schematic_layout_error"),message:v.string(),source_group_id:v.string(),schematic_group_id:v.string(),subcircuit_id:v.string().optional()}).describe("Error emitted when schematic layout fails for a group");Pt(!0);zA=v.object({type:v.literal("schematic_debug_object"),label:v.string().optional(),subcircuit_id:v.string().optional()}),Tbe=zA.extend({shape:v.literal("rect"),center:Hr,size:Dq}),Pbe=zA.extend({shape:v.literal("line"),start:Hr,end:Hr}),Ibe=zA.extend({shape:v.literal("point"),center:Hr}),jbe=v.discriminatedUnion("shape",[Tbe,Pbe,Ibe]);Pt(!0);kbe=v.object({type:v.literal("schematic_voltage_probe"),schematic_voltage_probe_id:v.string(),position:Hr,schematic_trace_id:v.string(),voltage:Us.optional(),subcircuit_id:v.string().optional()}).describe("Defines a voltage probe measurement point on a schematic trace");Pt(!0);qA=v.object({type:v.literal("schematic_manual_edit_conflict_warning"),schematic_manual_edit_conflict_warning_id:Cr("schematic_manual_edit_conflict_warning"),warning_type:v.literal("schematic_manual_edit_conflict_warning").default("schematic_manual_edit_conflict_warning"),message:v.string(),schematic_component_id:v.string(),schematic_group_id:v.string().optional(),subcircuit_id:v.string().optional(),source_component_id:v.string()}).describe("Warning emitted when a component has both manual placement and explicit schX/schY coordinates");Pt(!0);Nbe=v.object({type:v.literal("schematic_group"),schematic_group_id:Cr("schematic_group"),source_group_id:v.string(),is_subcircuit:v.boolean().optional(),subcircuit_id:v.string().optional(),width:pe,height:pe,center:Hr,schematic_component_ids:v.array(v.string()),show_as_schematic_box:v.boolean().optional(),name:v.string().optional(),description:v.string().optional()}).describe("Defines a group of components on the schematic");Pt(!0);Mbe=v.object({type:v.literal("schematic_table"),schematic_table_id:Cr("schematic_table"),anchor_position:Hr,column_widths:v.array(Be),row_heights:v.array(Be),cell_padding:Be.optional(),border_width:Be.optional(),subcircuit_id:v.string().optional(),schematic_component_id:v.string().optional(),anchor:LA.optional()}).describe("Defines a table on the schematic");Pt(!0);Obe=v.object({type:v.literal("schematic_table_cell"),schematic_table_cell_id:Cr("schematic_table_cell"),schematic_table_id:v.string(),start_row_index:v.number(),end_row_index:v.number(),start_column_index:v.number(),end_column_index:v.number(),text:v.string().optional(),center:Hr,width:Be,height:Be,horizontal_align:v.enum(["left","center","right"]).optional(),vertical_align:v.enum(["top","middle","bottom"]).optional(),font_size:Be.optional(),subcircuit_id:v.string().optional()}).describe("Defines a cell within a schematic_table");Pt(!0);Lbe=v.object({x:Be,y:Be,bulge:v.number().optional()});Pt(!0);gq=v.object({vertices:v.array(Lbe)});Pt(!0);$be=v.object({outer_ring:gq,inner_rings:v.array(gq).default([])});Pt(!0);zbe=v.object({x:Be,y:Be,via:v.boolean().optional(),via_to_layer:dn.optional()}),FCt=v.array(zbe);Pt(!0);Pt(!0);bo=v.object({x:Be,y:Be,via:v.boolean().optional(),to_layer:dn.optional(),trace_width:Be.optional()});Pt(!0);qbe=v.object({type:v.literal("pcb_component"),pcb_component_id:Cr("pcb_component"),source_component_id:v.string(),center:Hr,layer:dn,rotation:Gn,width:pe,height:pe,subcircuit_id:v.string().optional(),pcb_group_id:v.string().optional()}).describe("Defines a component on the PCB");Pt(!0);Ube=v.object({type:v.literal("pcb_hole"),pcb_hole_id:Cr("pcb_hole"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),hole_shape:v.enum(["circle","square"]),hole_diameter:v.number(),x:Be,y:Be}),ECt=Ube.describe("Defines a circular or square hole on the PCB");Pt(!0);Vbe=v.object({type:v.literal("pcb_hole"),pcb_hole_id:Cr("pcb_hole"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),hole_shape:v.literal("oval"),hole_width:v.number(),hole_height:v.number(),x:Be,y:Be}),vCt=Vbe.describe("Defines an oval hole on the PCB");Pt(!0);Gbe=Ube.or(Vbe),CCt=v.object({type:v.literal("pcb_plated_hole"),shape:v.literal("circle"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),outer_diameter:v.number(),hole_diameter:v.number(),x:Be,y:Be,layers:v.array(dn),port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),pcb_plated_hole_id:Cr("pcb_plated_hole")}),_Ct=v.object({type:v.literal("pcb_plated_hole"),shape:v.enum(["oval","pill"]),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),outer_width:v.number(),outer_height:v.number(),hole_width:v.number(),hole_height:v.number(),x:Be,y:Be,ccw_rotation:Gn,layers:v.array(dn),port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),pcb_plated_hole_id:Cr("pcb_plated_hole")}),ACt=v.object({type:v.literal("pcb_plated_hole"),shape:v.literal("circular_hole_with_rect_pad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),hole_shape:v.literal("circle"),pad_shape:v.literal("rect"),hole_diameter:v.number(),rect_pad_width:v.number(),rect_pad_height:v.number(),rect_border_radius:v.number().optional(),hole_offset_x:Be.default(0),hole_offset_y:Be.default(0),x:Be,y:Be,layers:v.array(dn),port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),pcb_plated_hole_id:Cr("pcb_plated_hole")}),RCt=v.object({type:v.literal("pcb_plated_hole"),shape:v.literal("pill_hole_with_rect_pad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),hole_shape:v.literal("pill"),pad_shape:v.literal("rect"),hole_width:v.number(),hole_height:v.number(),rect_pad_width:v.number(),rect_pad_height:v.number(),rect_border_radius:v.number().optional(),hole_offset_x:Be.default(0),hole_offset_y:Be.default(0),x:Be,y:Be,layers:v.array(dn),port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),pcb_plated_hole_id:Cr("pcb_plated_hole")}),SCt=v.object({type:v.literal("pcb_plated_hole"),shape:v.literal("rotated_pill_hole_with_rect_pad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),hole_shape:v.literal("rotated_pill"),pad_shape:v.literal("rect"),hole_width:v.number(),hole_height:v.number(),hole_ccw_rotation:Gn,rect_pad_width:v.number(),rect_pad_height:v.number(),rect_border_radius:v.number().optional(),rect_ccw_rotation:Gn,hole_offset_x:Be.default(0),hole_offset_y:Be.default(0),x:Be,y:Be,layers:v.array(dn),port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),pcb_plated_hole_id:Cr("pcb_plated_hole")}),Xbe=v.union([CCt,_Ct,ACt,RCt,SCt]);Pt(!0);Pt(!0);Pt(!0);Pt(!0);Pt(!0);Ybe=v.object({type:v.literal("pcb_port"),pcb_port_id:Cr("pcb_port"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),source_port_id:v.string(),pcb_component_id:v.string(),x:Be,y:Be,layers:v.array(dn),is_board_pinout:v.boolean().optional()}).describe("Defines a port on the PCB");Pt(!0);BCt=v.object({type:v.literal("pcb_smtpad"),shape:v.literal("circle"),pcb_smtpad_id:Cr("pcb_smtpad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,radius:v.number(),layer:dn,port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),is_covered_with_solder_mask:v.boolean().optional()}),wCt=v.object({type:v.literal("pcb_smtpad"),shape:v.literal("rect"),pcb_smtpad_id:Cr("pcb_smtpad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),rect_border_radius:v.number().optional(),layer:dn,port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),is_covered_with_solder_mask:v.boolean().optional()}),TCt=v.object({type:v.literal("pcb_smtpad"),shape:v.literal("rotated_rect"),pcb_smtpad_id:Cr("pcb_smtpad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),rect_border_radius:v.number().optional(),ccw_rotation:Gn,layer:dn,port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),is_covered_with_solder_mask:v.boolean().optional()}),Hbe=v.object({type:v.literal("pcb_smtpad"),shape:v.literal("pill"),pcb_smtpad_id:Cr("pcb_smtpad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),radius:v.number(),layer:dn,port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),is_covered_with_solder_mask:v.boolean().optional()}),PCt=v.object({type:v.literal("pcb_smtpad"),shape:v.literal("rotated_pill"),pcb_smtpad_id:Cr("pcb_smtpad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),radius:v.number(),ccw_rotation:Gn,layer:dn,port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),is_covered_with_solder_mask:v.boolean().optional()}),ICt=v.object({type:v.literal("pcb_smtpad"),shape:v.literal("polygon"),pcb_smtpad_id:Cr("pcb_smtpad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),points:v.array(Hr),layer:dn,port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),is_covered_with_solder_mask:v.boolean().optional()}),Wbe=v.discriminatedUnion("shape",[BCt,wCt,TCt,PCt,Hbe,ICt]).describe("Defines an SMT pad on the PCB");Pt(!0);Pt(!0);Pt(!0);Pt(!0);Pt(!0);Pt(!0);jCt=v.object({type:v.literal("pcb_solder_paste"),shape:v.literal("circle"),pcb_solder_paste_id:Cr("pcb_solder_paste"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,radius:v.number(),layer:dn,pcb_component_id:v.string().optional(),pcb_smtpad_id:v.string().optional()}),kCt=v.object({type:v.literal("pcb_solder_paste"),shape:v.literal("rect"),pcb_solder_paste_id:Cr("pcb_solder_paste"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),layer:dn,pcb_component_id:v.string().optional(),pcb_smtpad_id:v.string().optional()}),NCt=v.object({type:v.literal("pcb_solder_paste"),shape:v.literal("pill"),pcb_solder_paste_id:Cr("pcb_solder_paste"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),radius:v.number(),layer:dn,pcb_component_id:v.string().optional(),pcb_smtpad_id:v.string().optional()}),MCt=v.object({type:v.literal("pcb_solder_paste"),shape:v.literal("rotated_rect"),pcb_solder_paste_id:Cr("pcb_solder_paste"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),ccw_rotation:Be,layer:dn,pcb_component_id:v.string().optional(),pcb_smtpad_id:v.string().optional()}),OCt=v.object({type:v.literal("pcb_solder_paste"),shape:v.literal("oval"),pcb_solder_paste_id:Cr("pcb_solder_paste"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),layer:dn,pcb_component_id:v.string().optional(),pcb_smtpad_id:v.string().optional()}),Kbe=v.union([jCt,kCt,NCt,MCt,OCt]).describe("Defines solderpaste on the PCB");Pt(!0);Pt(!0);Pt(!0);Pt(!0);Pt(!0);Jbe=v.object({type:v.literal("pcb_text"),pcb_text_id:Cr("pcb_text"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),text:v.string(),center:Hr,layer:dn,width:pe,height:pe,lines:v.number(),align:v.enum(["bottom-left"])}).describe("Defines text on the PCB");Pt(!0);Zbe=v.object({route_type:v.literal("wire"),x:Be,y:Be,width:Be,start_pcb_port_id:v.string().optional(),end_pcb_port_id:v.string().optional(),layer:dn}),Qbe=v.object({route_type:v.literal("via"),x:Be,y:Be,hole_diameter:Be.optional(),outer_diameter:Be.optional(),from_layer:v.string(),to_layer:v.string()}),UA=v.union([Zbe,Qbe]),eFe=v.object({type:v.literal("pcb_trace"),source_trace_id:v.string().optional(),pcb_component_id:v.string().optional(),pcb_trace_id:Cr("pcb_trace"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),route_thickness_mode:v.enum(["constant","interpolated"]).default("constant").optional(),route_order_index:v.number().optional(),should_round_corners:v.boolean().optional(),trace_length:v.number().optional(),rats_nest_color:v.string().optional(),route:v.array(UA)}).describe("Defines a trace on the PCB");Pt(!0);Pt(!0);tFe=v.object({type:v.literal("pcb_trace_error"),pcb_trace_error_id:Cr("pcb_trace_error"),error_type:v.literal("pcb_trace_error").default("pcb_trace_error"),message:v.string(),center:Hr.optional(),pcb_trace_id:v.string(),source_trace_id:v.string(),pcb_component_ids:v.array(v.string()),pcb_port_ids:v.array(v.string()),subcircuit_id:v.string().optional()}).describe("Defines a trace error on the PCB");Pt(!0);rFe=v.object({type:v.literal("pcb_trace_missing_error"),pcb_trace_missing_error_id:Cr("pcb_trace_missing_error"),error_type:v.literal("pcb_trace_missing_error").default("pcb_trace_missing_error"),message:v.string(),center:Hr.optional(),source_trace_id:v.string(),pcb_component_ids:v.array(v.string()),pcb_port_ids:v.array(v.string()),subcircuit_id:v.string().optional()}).describe("Defines an error when a source trace has no corresponding PCB trace");Pt(!0);nFe=v.object({type:v.literal("pcb_port_not_matched_error"),pcb_error_id:Cr("pcb_error"),error_type:v.literal("pcb_port_not_matched_error").default("pcb_port_not_matched_error"),message:v.string(),pcb_component_ids:v.array(v.string()),subcircuit_id:v.string().optional()}).describe("Defines a trace error on the PCB where a port is not matched");Pt(!0);aFe=v.object({type:v.literal("pcb_port_not_connected_error"),pcb_port_not_connected_error_id:Cr("pcb_port_not_connected_error"),error_type:v.literal("pcb_port_not_connected_error").default("pcb_port_not_connected_error"),message:v.string(),pcb_port_ids:v.array(v.string()),pcb_component_ids:v.array(v.string()),subcircuit_id:v.string().optional()}).describe("Defines an error when a pcb port is not connected to any trace");Pt(!0);sFe=v.object({type:v.literal("pcb_net"),pcb_net_id:Cr("pcb_net"),source_net_id:v.string().optional(),rats_nest_color:v.string().optional()}).describe("Defines a net on the PCB");Pt(!0);iFe=v.object({type:v.literal("pcb_via"),pcb_via_id:Cr("pcb_via"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,outer_diameter:Be.default("0.6mm"),hole_diameter:Be.default("0.25mm"),from_layer:dn.optional(),to_layer:dn.optional(),layers:v.array(dn),pcb_trace_id:v.string().optional()}).describe("Defines a via on the PCB");Pt(!0);oFe=v.object({type:v.literal("pcb_board"),pcb_board_id:Cr("pcb_board"),is_subcircuit:v.boolean().optional(),subcircuit_id:v.string().optional(),width:pe,height:pe,center:Hr,thickness:pe.optional().default(1.4),num_layers:v.number().optional().default(4),outline:v.array(Hr).optional(),material:v.enum(["fr4","fr1"]).default("fr4")}).describe("Defines the board outline of the PCB");Pt(!0);uFe=v.object({type:v.literal("pcb_placement_error"),pcb_placement_error_id:Cr("pcb_placement_error"),error_type:v.literal("pcb_placement_error").default("pcb_placement_error"),message:v.string(),subcircuit_id:v.string().optional()}).describe("Defines a placement error on the PCB");Pt(!0);cFe=v.object({type:v.literal("pcb_trace_hint"),pcb_trace_hint_id:Cr("pcb_trace_hint"),pcb_port_id:v.string(),pcb_component_id:v.string(),route:v.array(bo),subcircuit_id:v.string().optional()}).describe("A hint that can be used during generation of a PCB trace");Pt(!0);lFe=v.object({type:v.literal("pcb_silkscreen_line"),pcb_silkscreen_line_id:Cr("pcb_silkscreen_line"),pcb_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),stroke_width:Be.default("0.1mm"),x1:Be,y1:Be,x2:Be,y2:Be,layer:zm}).describe("Defines a silkscreen line on the PCB");Pt(!0);dFe=v.object({type:v.literal("pcb_silkscreen_path"),pcb_silkscreen_path_id:Cr("pcb_silkscreen_path"),pcb_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),layer:zm,route:v.array(Hr),stroke_width:pe}).describe("Defines a silkscreen path on the PCB");Pt(!0);pFe=v.object({type:v.literal("pcb_silkscreen_text"),pcb_silkscreen_text_id:Cr("pcb_silkscreen_text"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),font:v.literal("tscircuit2024").default("tscircuit2024"),font_size:Be.default("0.2mm"),pcb_component_id:v.string(),text:v.string(),is_knockout:v.boolean().default(!1).optional(),knockout_padding:v.object({left:pe,top:pe,bottom:pe,right:pe}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:v.number().optional(),layer:dn,is_mirrored:v.boolean().default(!1).optional(),anchor_position:Hr.default({x:0,y:0}),anchor_alignment:LA.default("center")}).describe("Defines silkscreen text on the PCB");Pt(!0);xFe=v.object({type:v.literal("pcb_silkscreen_rect"),pcb_silkscreen_rect_id:Cr("pcb_silkscreen_rect"),pcb_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),center:Hr,width:pe,height:pe,layer:dn,stroke_width:pe.default("1mm"),is_filled:v.boolean().default(!0).optional(),has_stroke:v.boolean().optional(),is_stroke_dashed:v.boolean().optional()}).describe("Defines a silkscreen rect on the PCB");Pt(!0);fFe=v.object({type:v.literal("pcb_silkscreen_circle"),pcb_silkscreen_circle_id:Cr("pcb_silkscreen_circle"),pcb_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),center:Hr,radius:pe,layer:zm,stroke_width:pe.default("1mm")}).describe("Defines a silkscreen circle on the PCB");Pt(!0);hFe=v.object({type:v.literal("pcb_silkscreen_oval"),pcb_silkscreen_oval_id:Cr("pcb_silkscreen_oval"),pcb_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),center:Hr,radius_x:Be,radius_y:Be,layer:zm}).describe("Defines a silkscreen oval on the PCB");Pt(!0);mFe=v.object({type:v.literal("pcb_fabrication_note_text"),pcb_fabrication_note_text_id:Cr("pcb_fabrication_note_text"),subcircuit_id:v.string().optional(),pcb_group_id:v.string().optional(),font:v.literal("tscircuit2024").default("tscircuit2024"),font_size:Be.default("1mm"),pcb_component_id:v.string(),text:v.string(),layer:zm,anchor_position:Hr.default({x:0,y:0}),anchor_alignment:v.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),color:v.string().optional()}).describe("Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators");Pt(!0);gFe=v.object({type:v.literal("pcb_fabrication_note_path"),pcb_fabrication_note_path_id:Cr("pcb_fabrication_note_path"),pcb_component_id:v.string(),subcircuit_id:v.string().optional(),layer:dn,route:v.array(Hr),stroke_width:pe,color:v.string().optional()}).describe("Defines a fabrication path on the PCB for fabricators or assemblers");Pt(!0);DFe=v.object({type:v.literal("pcb_footprint_overlap_error"),pcb_error_id:Cr("pcb_error"),error_type:v.literal("pcb_footprint_overlap_error").default("pcb_footprint_overlap_error"),message:v.string(),pcb_smtpad_ids:v.array(v.string()).optional(),pcb_plated_hole_ids:v.array(v.string()).optional(),pcb_hole_ids:v.array(v.string()).optional(),pcb_keepout_ids:v.array(v.string()).optional()}).describe("Error emitted when a pcb footprint overlaps with another element");Pt(!0);yFe=v.object({type:v.literal("pcb_keepout"),shape:v.literal("rect"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),center:Hr,width:Be,height:Be,pcb_keepout_id:v.string(),layers:v.array(v.string()),description:v.string().optional()}).or(v.object({type:v.literal("pcb_keepout"),shape:v.literal("circle"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),center:Hr,radius:Be,pcb_keepout_id:v.string(),layers:v.array(v.string()),description:v.string().optional()}));Pt(!0);Oq=v.object({type:v.literal("pcb_cutout"),pcb_cutout_id:Cr("pcb_cutout"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional()}),bFe=Oq.extend({shape:v.literal("rect"),center:Hr,width:pe,height:pe,rotation:Gn.optional()});Pt(!0);FFe=Oq.extend({shape:v.literal("circle"),center:Hr,radius:pe});Pt(!0);EFe=Oq.extend({shape:v.literal("polygon"),points:v.array(Hr)});Pt(!0);vFe=v.discriminatedUnion("shape",[bFe,FFe,EFe]).describe("Defines a cutout on the PCB, removing board material.");Pt(!0);CFe=v.object({type:v.literal("pcb_missing_footprint_error"),pcb_missing_footprint_error_id:Cr("pcb_missing_footprint_error"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),error_type:v.literal("pcb_missing_footprint_error").default("pcb_missing_footprint_error"),source_component_id:v.string(),message:v.string()}).describe("Defines a missing footprint error on the PCB");Pt(!0);yb=v.object({type:v.literal("external_footprint_load_error"),external_footprint_load_error_id:Cr("external_footprint_load_error"),pcb_component_id:v.string(),source_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),footprinter_string:v.string().optional(),error_type:v.literal("external_footprint_load_error").default("external_footprint_load_error"),message:v.string()}).describe("Defines an error when an external footprint fails to load");Pt(!0);VA=v.object({type:v.literal("circuit_json_footprint_load_error"),circuit_json_footprint_load_error_id:Cr("circuit_json_footprint_load_error"),pcb_component_id:v.string(),source_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),error_type:v.literal("circuit_json_footprint_load_error").default("circuit_json_footprint_load_error"),message:v.string(),circuit_json:v.array(v.any()).optional()}).describe("Defines an error when a circuit JSON footprint fails to load");Pt(!0);_Fe=v.object({type:v.literal("pcb_group"),pcb_group_id:Cr("pcb_group"),source_group_id:v.string(),is_subcircuit:v.boolean().optional(),subcircuit_id:v.string().optional(),width:pe,height:pe,center:Hr,pcb_component_ids:v.array(v.string()),name:v.string().optional(),description:v.string().optional(),layout_mode:v.string().optional(),autorouter_configuration:v.object({trace_clearance:pe}).optional(),autorouter_used_string:v.string().optional()}).describe("Defines a group of components on the PCB");Pt(!0);AFe=v.object({type:v.literal("pcb_autorouting_error"),pcb_error_id:Cr("pcb_autorouting_error"),error_type:v.literal("pcb_autorouting_error").default("pcb_autorouting_error"),message:v.string(),subcircuit_id:v.string().optional()}).describe("The autorouting has failed to route a portion of the board");Pt(!0);GA=v.object({type:v.literal("pcb_manual_edit_conflict_warning"),pcb_manual_edit_conflict_warning_id:Cr("pcb_manual_edit_conflict_warning"),warning_type:v.literal("pcb_manual_edit_conflict_warning").default("pcb_manual_edit_conflict_warning"),message:v.string(),pcb_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),source_component_id:v.string()}).describe("Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates");Pt(!0);RFe=v.object({type:v.literal("pcb_breakout_point"),pcb_breakout_point_id:Cr("pcb_breakout_point"),pcb_group_id:v.string(),subcircuit_id:v.string().optional(),source_trace_id:v.string().optional(),source_port_id:v.string().optional(),source_net_id:v.string().optional(),x:Be,y:Be}).describe("Defines a routing target within a pcb_group for a source_trace or source_net");Pt(!0);SFe=v.object({type:v.literal("pcb_ground_plane"),pcb_ground_plane_id:Cr("pcb_ground_plane"),source_pcb_ground_plane_id:v.string(),source_net_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional()}).describe("Defines a ground plane on the PCB");Pt(!0);BFe=v.object({type:v.literal("pcb_ground_plane_region"),pcb_ground_plane_region_id:Cr("pcb_ground_plane_region"),pcb_ground_plane_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),layer:dn,points:v.array(Hr)}).describe("Defines a polygon region of a ground plane");Pt(!0);wFe=v.object({type:v.literal("pcb_thermal_spoke"),pcb_thermal_spoke_id:Cr("pcb_thermal_spoke"),pcb_ground_plane_id:v.string(),shape:v.string(),spoke_count:v.number(),spoke_thickness:Be,spoke_inner_diameter:Be,spoke_outer_diameter:Be,pcb_plated_hole_id:v.string().optional(),subcircuit_id:v.string().optional()}).describe("Pattern for connecting a ground plane to a plated hole");Pt(!0);Lq=v.object({type:v.literal("pcb_copper_pour"),pcb_copper_pour_id:Cr("pcb_copper_pour"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),layer:dn,source_net_id:v.string().optional()}),TFe=Lq.extend({shape:v.literal("rect"),center:Hr,width:pe,height:pe,rotation:Gn.optional()});Pt(!0);PFe=Lq.extend({shape:v.literal("brep"),brep_shape:$be});Pt(!0);IFe=Lq.extend({shape:v.literal("polygon"),points:v.array(Hr)});Pt(!0);jFe=v.discriminatedUnion("shape",[TFe,PFe,IFe]).describe("Defines a copper pour on the PCB.");Pt(!0);kFe=v.object({type:v.literal("pcb_component_outside_board_error"),pcb_component_outside_board_error_id:Cr("pcb_component_outside_board_error"),error_type:v.literal("pcb_component_outside_board_error").default("pcb_component_outside_board_error"),message:v.string(),pcb_component_id:v.string(),pcb_board_id:v.string(),component_center:Hr,component_bounds:v.object({min_x:v.number(),max_x:v.number(),min_y:v.number(),max_y:v.number()}),subcircuit_id:v.string().optional(),source_component_id:v.string().optional()}).describe("Error emitted when a PCB component is placed outside the board boundaries");Pt(!0);NFe=v.object({type:v.literal("cad_component"),cad_component_id:v.string(),pcb_component_id:v.string(),source_component_id:v.string(),position:Gf,rotation:Gf.optional(),size:Gf.optional(),layer:dn.optional(),subcircuit_id:v.string().optional(),footprinter_string:v.string().optional(),model_obj_url:v.string().optional(),model_stl_url:v.string().optional(),model_3mf_url:v.string().optional(),model_gltf_url:v.string().optional(),model_glb_url:v.string().optional(),model_step_url:v.string().optional(),model_wrl_url:v.string().optional(),model_unit_to_mm_scale_factor:v.number().optional(),model_jscad:v.any().optional()}).describe("Defines a component on the PCB");Pt(!0);MFe=v.enum(["sinewave","square","triangle","sawtooth"]),LCt=v.union([v.string(),v.number()]).transform(r=>typeof r=="string"?r.endsWith("%")?parseFloat(r.slice(0,-1))/100:parseFloat(r):r).pipe(v.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),OFe=v.object({type:v.literal("simulation_voltage_source"),simulation_voltage_source_id:Cr("simulation_voltage_source"),is_dc_source:v.literal(!0).optional().default(!0),positive_source_port_id:v.string().optional(),negative_source_port_id:v.string().optional(),positive_source_net_id:v.string().optional(),negative_source_net_id:v.string().optional(),voltage:Us}).describe("Defines a DC voltage source for simulation"),LFe=v.object({type:v.literal("simulation_voltage_source"),simulation_voltage_source_id:Cr("simulation_voltage_source"),is_dc_source:v.literal(!1),terminal1_source_port_id:v.string().optional(),terminal2_source_port_id:v.string().optional(),terminal1_source_net_id:v.string().optional(),terminal2_source_net_id:v.string().optional(),voltage:Us.optional(),frequency:Oc.optional(),peak_to_peak_voltage:Us.optional(),wave_shape:MFe.optional(),phase:Gn.optional(),duty_cycle:LCt.optional()}).describe("Defines an AC voltage source for simulation"),$Fe=v.union([OFe,LFe]).describe("Defines a voltage source for simulation");Pt(!0);Pt(!0);Pt(!0);zFe=v.union([cbe,ube,obe,dbe,lbe,Eq,yq,$A,Fq,bq,vq,Cq,_q,Sq,Bq,wq,jq,Tq,Pq,Iq,Rq,Aq,pbe,xbe,kq,Nq,Mq,qbe,Gbe,CFe,yb,VA,GA,Xbe,yFe,Ybe,sFe,Jbe,eFe,iFe,Wbe,Kbe,oFe,_Fe,cFe,lFe,dFe,pFe,xFe,fFe,hFe,tFe,rFe,uFe,nFe,aFe,gFe,mFe,AFe,DFe,RFe,vFe,SFe,BFe,wFe,jFe,kFe,fbe,Abe,Fbe,Ebe,vbe,Cbe,bbe,Rbe,_be,hbe,Bbe,wbe,Sbe,jbe,kbe,qA,Nbe,Mbe,Obe,NFe,$Fe]),Yf=zFe;Pt(!0);Xf(!0)});var d3e=on((HJt,l3e)=>{"use strict";var qm=1e3,Um=qm*60,Vm=Um*60,Wf=Vm*24,t6t=Wf*7,r6t=Wf*365.25;l3e.exports=function(r,e){e=e||{};var a=typeof r;if(a==="string"&&r.length>0)return n6t(r);if(a==="number"&&isFinite(r))return e.long?s6t(r):a6t(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function n6t(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var a=parseFloat(e[1]),s=(e[2]||"ms").toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return a*r6t;case"weeks":case"week":case"w":return a*t6t;case"days":case"day":case"d":return a*Wf;case"hours":case"hour":case"hrs":case"hr":case"h":return a*Vm;case"minutes":case"minute":case"mins":case"min":case"m":return a*Um;case"seconds":case"second":case"secs":case"sec":case"s":return a*qm;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}function a6t(r){var e=Math.abs(r);return e>=Wf?Math.round(r/Wf)+"d":e>=Vm?Math.round(r/Vm)+"h":e>=Um?Math.round(r/Um)+"m":e>=qm?Math.round(r/qm)+"s":r+"ms"}function s6t(r){var e=Math.abs(r);return e>=Wf?e4(r,e,Wf,"day"):e>=Vm?e4(r,e,Vm,"hour"):e>=Um?e4(r,e,Um,"minute"):e>=qm?e4(r,e,qm,"second"):r+" ms"}function e4(r,e,a,s){var l=e>=a*1.5;return Math.round(r/a)+" "+s+(l?"s":"")}});var x3e=on((WJt,p3e)=>{"use strict";function i6t(r){a.debug=a,a.default=a,a.coerce=m,a.disable=x,a.enable=l,a.enabled=f,a.humanize=d3e(),a.destroy=D,Object.keys(r).forEach(b=>{a[b]=r[b]}),a.names=[],a.skips=[],a.formatters={};function e(b){let E=0;for(let A=0;A<b.length;A++)E=(E<<5)-E+b.charCodeAt(A),E|=0;return a.colors[Math.abs(E)%a.colors.length]}a.selectColor=e;function a(b){let E,A=null,B,w;function P(...j){if(!P.enabled)return;let O=P,q=Number(new Date),ee=q-(E||q);O.diff=ee,O.prev=E,O.curr=q,E=q,j[0]=a.coerce(j[0]),typeof j[0]!="string"&&j.unshift("%O");let W=0;j[0]=j[0].replace(/%([a-zA-Z%])/g,(L,K)=>{if(L==="%%")return"%";W++;let U=a.formatters[K];if(typeof U=="function"){let J=j[W];L=U.call(O,J),j.splice(W,1),W--}return L}),a.formatArgs.call(O,j),(O.log||a.log).apply(O,j)}return P.namespace=b,P.useColors=a.useColors(),P.color=a.selectColor(b),P.extend=s,P.destroy=a.destroy,Object.defineProperty(P,"enabled",{enumerable:!0,configurable:!1,get:()=>A!==null?A:(B!==a.namespaces&&(B=a.namespaces,w=a.enabled(b)),w),set:j=>{A=j}}),typeof a.init=="function"&&a.init(P),P}function s(b,E){let A=a(this.namespace+(typeof E>"u"?":":E)+b);return A.log=this.log,A}function l(b){a.save(b),a.namespaces=b,a.names=[],a.skips=[];let E=(typeof b=="string"?b:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let A of E)A[0]==="-"?a.skips.push(A.slice(1)):a.names.push(A)}function d(b,E){let A=0,B=0,w=-1,P=0;for(;A<b.length;)if(B<E.length&&(E[B]===b[A]||E[B]==="*"))E[B]==="*"?(w=B,P=A,B++):(A++,B++);else if(w!==-1)B=w+1,P++,A=P;else return!1;for(;B<E.length&&E[B]==="*";)B++;return B===E.length}function x(){let b=[...a.names,...a.skips.map(E=>"-"+E)].join(",");return a.enable(""),b}function f(b){for(let E of a.skips)if(d(b,E))return!1;for(let E of a.names)if(d(b,E))return!0;return!1}function m(b){return b instanceof Error?b.stack||b.message:b}function D(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return a.enable(a.load()),a}p3e.exports=i6t});var fs=on((Jo,t4)=>{"use strict";Jo.formatArgs=u6t;Jo.save=c6t;Jo.load=l6t;Jo.useColors=o6t;Jo.storage=d6t();Jo.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Jo.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function o6t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function u6t(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+t4.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let a=0,s=0;r[0].replace(/%[a-zA-Z%]/g,l=>{l!=="%%"&&(a++,l==="%c"&&(s=a))}),r.splice(s,0,e)}Jo.log=console.debug||console.log||(()=>{});function c6t(r){try{r?Jo.storage.setItem("debug",r):Jo.storage.removeItem("debug")}catch{}}function l6t(){let r;try{r=Jo.storage.getItem("debug")||Jo.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function d6t(){try{return localStorage}catch{}}t4.exports=x3e()(Jo);var{formatters:p6t}=t4.exports;p6t.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var v3e=on(Qa=>{"use strict";function Hq(r,e){var a=r.length;r.push(e);e:for(;0<a;){var s=a-1>>>1,l=r[s];if(0<r4(l,e))r[s]=e,r[a]=l,a=s;else break e}}function U0(r){return r.length===0?null:r[0]}function a4(r){if(r.length===0)return null;var e=r[0],a=r.pop();if(a!==e){r[0]=a;e:for(var s=0,l=r.length,d=l>>>1;s<d;){var x=2*(s+1)-1,f=r[x],m=x+1,D=r[m];if(0>r4(f,a))m<l&&0>r4(D,f)?(r[s]=D,r[m]=a,s=m):(r[s]=f,r[x]=a,s=x);else if(m<l&&0>r4(D,a))r[s]=D,r[m]=a,s=m;else break e}}return e}function r4(r,e){var a=r.sortIndex-e.sortIndex;return a!==0?a:r.id-e.id}Qa.unstable_now=void 0;typeof performance=="object"&&typeof performance.now=="function"?(f3e=performance,Qa.unstable_now=function(){return f3e.now()}):(Gq=Date,h3e=Gq.now(),Qa.unstable_now=function(){return Gq.now()-h3e});var f3e,Gq,h3e,Kl=[],Tp=[],x6t=1,Ju=null,Ki=3,Wq=!1,Fb=!1,Eb=!1,Kq=!1,D3e=typeof setTimeout=="function"?setTimeout:null,y3e=typeof clearTimeout=="function"?clearTimeout:null,m3e=typeof setImmediate<"u"?setImmediate:null;function n4(r){for(var e=U0(Tp);e!==null;){if(e.callback===null)a4(Tp);else if(e.startTime<=r)a4(Tp),e.sortIndex=e.expirationTime,Hq(Kl,e);else break;e=U0(Tp)}}function Jq(r){if(Eb=!1,n4(r),!Fb)if(U0(Kl)!==null)Fb=!0,Xm||(Xm=!0,Gm());else{var e=U0(Tp);e!==null&&Zq(Jq,e.startTime-r)}}var Xm=!1,vb=-1,b3e=5,F3e=-1;function E3e(){return Kq?!0:!(Qa.unstable_now()-F3e<b3e)}function Xq(){if(Kq=!1,Xm){var r=Qa.unstable_now();F3e=r;var e=!0;try{e:{Fb=!1,Eb&&(Eb=!1,y3e(vb),vb=-1),Wq=!0;var a=Ki;try{t:{for(n4(r),Ju=U0(Kl);Ju!==null&&!(Ju.expirationTime>r&&E3e());){var s=Ju.callback;if(typeof s=="function"){Ju.callback=null,Ki=Ju.priorityLevel;var l=s(Ju.expirationTime<=r);if(r=Qa.unstable_now(),typeof l=="function"){Ju.callback=l,n4(r),e=!0;break t}Ju===U0(Kl)&&a4(Kl),n4(r)}else a4(Kl);Ju=U0(Kl)}if(Ju!==null)e=!0;else{var d=U0(Tp);d!==null&&Zq(Jq,d.startTime-r),e=!1}}break e}finally{Ju=null,Ki=a,Wq=!1}e=void 0}}finally{e?Gm():Xm=!1}}}var Gm;typeof m3e=="function"?Gm=function(){m3e(Xq)}:typeof MessageChannel<"u"?(Yq=new MessageChannel,g3e=Yq.port2,Yq.port1.onmessage=Xq,Gm=function(){g3e.postMessage(null)}):Gm=function(){D3e(Xq,0)};var Yq,g3e;function Zq(r,e){vb=D3e(function(){r(Qa.unstable_now())},e)}Qa.unstable_IdlePriority=5;Qa.unstable_ImmediatePriority=1;Qa.unstable_LowPriority=4;Qa.unstable_NormalPriority=3;Qa.unstable_Profiling=null;Qa.unstable_UserBlockingPriority=2;Qa.unstable_cancelCallback=function(r){r.callback=null};Qa.unstable_forceFrameRate=function(r){0>r||125<r?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):b3e=0<r?Math.floor(1e3/r):5};Qa.unstable_getCurrentPriorityLevel=function(){return Ki};Qa.unstable_next=function(r){switch(Ki){case 1:case 2:case 3:var e=3;break;default:e=Ki}var a=Ki;Ki=e;try{return r()}finally{Ki=a}};Qa.unstable_requestPaint=function(){Kq=!0};Qa.unstable_runWithPriority=function(r,e){switch(r){case 1:case 2:case 3:case 4:case 5:break;default:r=3}var a=Ki;Ki=r;try{return e()}finally{Ki=a}};Qa.unstable_scheduleCallback=function(r,e,a){var s=Qa.unstable_now();switch(typeof a=="object"&&a!==null?(a=a.delay,a=typeof a=="number"&&0<a?s+a:s):a=s,r){case 1:var l=-1;break;case 2:l=250;break;case 5:l=1073741823;break;case 4:l=1e4;break;default:l=5e3}return l=a+l,r={id:x6t++,callback:e,priorityLevel:r,startTime:a,expirationTime:l,sortIndex:-1},a>s?(r.sortIndex=a,Hq(Tp,r),U0(Kl)===null&&r===U0(Tp)&&(Eb?(y3e(vb),vb=-1):Eb=!0,Zq(Jq,a-s))):(r.sortIndex=l,Hq(Kl,r),Fb||Wq||(Fb=!0,Xm||(Xm=!0,Gm()))),r};Qa.unstable_shouldYield=E3e;Qa.unstable_wrapCallback=function(r){var e=Ki;return function(){var a=Ki;Ki=e;try{return r.apply(this,arguments)}finally{Ki=a}}}});var _3e=on((JJt,C3e)=>{"use strict";C3e.exports=v3e()});var A3e=on((ZJt,Cb)=>{"use strict";Cb.exports=function(r){function e(C,_,T,M){return new eE(C,_,T,M)}function a(){}function s(C){var _="https://react.dev/errors/"+C;if(1<arguments.length){_+="?args[]="+encodeURIComponent(arguments[1]);for(var T=2;T<arguments.length;T++)_+="&args[]="+encodeURIComponent(arguments[T])}return"Minified React error #"+C+"; visit "+_+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function l(C){var _=C,T=C;if(C.alternate)for(;_.return;)_=_.return;else{C=_;do _=C,(_.flags&4098)!==0&&(T=_.return),C=_.return;while(C)}return _.tag===3?T:null}function d(C){if(l(C)!==C)throw Error(s(188))}function x(C){var _=C.alternate;if(!_){if(_=l(C),_===null)throw Error(s(188));return _!==C?null:C}for(var T=C,M=_;;){var Y=T.return;if(Y===null)break;var ce=Y.alternate;if(ce===null){if(M=Y.return,M!==null){T=M;continue}break}if(Y.child===ce.child){for(ce=Y.child;ce;){if(ce===T)return d(Y),C;if(ce===M)return d(Y),_;ce=ce.sibling}throw Error(s(188))}if(T.return!==M.return)T=Y,M=ce;else{for(var we=!1,Ze=Y.child;Ze;){if(Ze===T){we=!0,T=Y,M=ce;break}if(Ze===M){we=!0,M=Y,T=ce;break}Ze=Ze.sibling}if(!we){for(Ze=ce.child;Ze;){if(Ze===T){we=!0,T=ce,M=Y;break}if(Ze===M){we=!0,M=ce,T=Y;break}Ze=Ze.sibling}if(!we)throw Error(s(189))}}if(T.alternate!==M)throw Error(s(190))}if(T.tag!==3)throw Error(s(188));return T.stateNode.current===T?C:_}function f(C){var _=C.tag;if(_===5||_===26||_===27||_===6)return C;for(C=C.child;C!==null;){if(_=f(C),_!==null)return _;C=C.sibling}return null}function m(C){var _=C.tag;if(_===5||_===26||_===27||_===6)return C;for(C=C.child;C!==null;){if(C.tag!==4&&(_=m(C),_!==null))return _;C=C.sibling}return null}function D(C){return C===null||typeof C!="object"?null:(C=xh&&C[xh]||C["@@iterator"],typeof C=="function"?C:null)}function b(C){if(C==null)return null;if(typeof C=="function")return C.$$typeof===fh?null:C.displayName||C.name||null;if(typeof C=="string")return C;switch(C){case wd:return"Fragment";case Li:return"Profiler";case iE:return"StrictMode";case WD:return"Suspense";case KD:return"SuspenseList";case Os:return"Activity"}if(typeof C=="object")switch(C.$$typeof){case hl:return"Portal";case t0:return(C.displayName||"Context")+".Provider";case YD:return(C._context.displayName||"Context")+".Consumer";case HD:var _=C.render;return C=C.displayName,C||(C=_.displayName||_.name||"",C=C!==""?"ForwardRef("+C+")":"ForwardRef"),C;case ph:return _=C.displayName||null,_!==null?_:b(C.type)||"Memo";case To:_=C._payload,C=C._init;try{return b(C(_))}catch{}}return null}function E(C){return{current:C}}function A(C){0>u0||(C.current=fy[u0],fy[u0]=null,u0--)}function B(C,_){u0++,fy[u0]=C.current,C.current=_}function w(C){return C>>>=0,C===0?32:31-(Md(C)/c0|0)|0}function P(C){var _=C&42;if(_!==0)return _;switch(C&-C){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return C&4194048;case 4194304:case 8388608:case 16777216:case 33554432:return C&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return C}}function j(C,_,T){var M=C.pendingLanes;if(M===0)return 0;var Y=0,ce=C.suspendedLanes,we=C.pingedLanes;C=C.warmLanes;var Ze=M&134217727;return Ze!==0?(M=Ze&~ce,M!==0?Y=P(M):(we&=Ze,we!==0?Y=P(we):T||(T=Ze&~C,T!==0&&(Y=P(T))))):(Ze=M&~ce,Ze!==0?Y=P(Ze):we!==0?Y=P(we):T||(T=M&~C,T!==0&&(Y=P(T)))),Y===0?0:_!==0&&_!==Y&&(_&ce)===0&&(ce=Y&-Y,T=_&-_,ce>=T||ce===32&&(T&4194048)!==0)?_:Y}function O(C,_){return(C.pendingLanes&~(C.suspendedLanes&~C.pingedLanes)&_)===0}function q(C,_){switch(C){case 1:case 2:case 4:case 8:case 64:return _+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return _+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function ee(){var C=Od;return Od<<=1,(Od&4194048)===0&&(Od=256),C}function W(){var C=ir;return ir<<=1,(ir&62914560)===0&&(ir=4194304),C}function re(C){for(var _=[],T=0;31>T;T++)_.push(C);return _}function L(C,_){C.pendingLanes|=_,_!==268435456&&(C.suspendedLanes=0,C.pingedLanes=0,C.warmLanes=0)}function K(C,_,T,M,Y,ce){var we=C.pendingLanes;C.pendingLanes=T,C.suspendedLanes=0,C.pingedLanes=0,C.warmLanes=0,C.expiredLanes&=T,C.entangledLanes&=T,C.errorRecoveryDisabledLanes&=T,C.shellSuspendCounter=0;var Ze=C.entanglements,_t=C.expirationTimes,Kt=C.hiddenUpdates;for(T=we&~T;0<T;){var dr=31-ya(T),mr=1<<dr;Ze[dr]=0,_t[dr]=-1;var Fr=Kt[dr];if(Fr!==null)for(Kt[dr]=null,dr=0;dr<Fr.length;dr++){var mn=Fr[dr];mn!==null&&(mn.lane&=-536870913)}T&=~mr}M!==0&&U(C,M,0),ce!==0&&Y===0&&C.tag!==0&&(C.suspendedLanes|=ce&~(we&~_))}function U(C,_,T){C.pendingLanes|=_,C.suspendedLanes&=~_;var M=31-ya(_);C.entangledLanes|=_,C.entanglements[M]=C.entanglements[M]|1073741824|T&4194090}function J(C,_){var T=C.entangledLanes|=_;for(C=C.entanglements;T;){var M=31-ya(T),Y=1<<M;Y&_|C[M]&_&&(C[M]|=_),T&=~Y}}function Q(C){switch(C){case 2:C=1;break;case 8:C=4;break;case 32:C=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:C=128;break;case 268435456:C=134217728;break;default:C=0}return C}function de(C){return C&=-C,2<C?8<C?(C&134217727)!==0?32:268435456:8:2}function oe(C){if(typeof gi=="function"&&gy(C),Di&&typeof Di.setStrictMode=="function")try{Di.setStrictMode(xc,C)}catch{}}function Me(C){if(Sh===void 0)try{throw Error()}catch(T){var _=T.stack.trim().match(/\n( *(at )?)/);Sh=_&&_[1]||"",Dy=-1<T.stack.indexOf(`
1
+ var FEt=Object.create;var vA=Object.defineProperty;var EEt=Object.getOwnPropertyDescriptor;var vEt=Object.getOwnPropertyNames;var CEt=Object.getPrototypeOf,_Et=Object.prototype.hasOwnProperty;var AEt=(r,e,a)=>e in r?vA(r,e,{enumerable:!0,configurable:!0,writable:!0,value:a}):r[e]=a;var fb=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,a)=>(typeof require<"u"?require:e)[a]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var Sr=(r,e)=>()=>(r&&(e=r(r=0)),e);var on=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Am=(r,e)=>{for(var a in e)vA(r,a,{get:e[a],enumerable:!0})},REt=(r,e,a,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let l of vEt(e))!_Et.call(r,l)&&l!==a&&vA(r,l,{get:()=>e[l],enumerable:!(s=EEt(e,l))||s.enumerable});return r};var Or=(r,e,a)=>(a=r!=null?FEt(CEt(r)):{},REt(e||!r||!r.__esModule?vA(a,"default",{value:r,enumerable:!0}):a,r));var z=(r,e,a)=>AEt(r,typeof e!="symbol"?e+"":e,a);var N2e=on(Rn=>{"use strict";var aq=Symbol.for("react.transitional.element"),qEt=Symbol.for("react.portal"),UEt=Symbol.for("react.fragment"),VEt=Symbol.for("react.strict_mode"),GEt=Symbol.for("react.profiler"),XEt=Symbol.for("react.consumer"),YEt=Symbol.for("react.context"),HEt=Symbol.for("react.forward_ref"),WEt=Symbol.for("react.suspense"),KEt=Symbol.for("react.memo"),w2e=Symbol.for("react.lazy"),_2e=Symbol.iterator;function JEt(r){return r===null||typeof r!="object"?null:(r=_2e&&r[_2e]||r["@@iterator"],typeof r=="function"?r:null)}var T2e={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},P2e=Object.assign,I2e={};function Bm(r,e,a){this.props=r,this.context=e,this.refs=I2e,this.updater=a||T2e}Bm.prototype.isReactComponent={};Bm.prototype.setState=function(r,e){if(typeof r!="object"&&typeof r!="function"&&r!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,r,e,"setState")};Bm.prototype.forceUpdate=function(r){this.updater.enqueueForceUpdate(this,r,"forceUpdate")};function j2e(){}j2e.prototype=Bm.prototype;function sq(r,e,a){this.props=r,this.context=e,this.refs=I2e,this.updater=a||T2e}var iq=sq.prototype=new j2e;iq.constructor=sq;P2e(iq,Bm.prototype);iq.isPureReactComponent=!0;var A2e=Array.isArray,Za={H:null,A:null,T:null,S:null,V:null},k2e=Object.prototype.hasOwnProperty;function oq(r,e,a,s,l,d){return a=d.ref,{$$typeof:aq,type:r,key:e,ref:a!==void 0?a:null,props:d}}function ZEt(r,e){return oq(r.type,e,void 0,void 0,void 0,r.props)}function uq(r){return typeof r=="object"&&r!==null&&r.$$typeof===aq}function QEt(r){var e={"=":"=0",":":"=2"};return"$"+r.replace(/[=:]/g,function(a){return e[a]})}var R2e=/\/+/g;function nq(r,e){return typeof r=="object"&&r!==null&&r.key!=null?QEt(""+r.key):e.toString(36)}function S2e(){}function evt(r){switch(r.status){case"fulfilled":return r.value;case"rejected":throw r.reason;default:switch(typeof r.status=="string"?r.then(S2e,S2e):(r.status="pending",r.then(function(e){r.status==="pending"&&(r.status="fulfilled",r.value=e)},function(e){r.status==="pending"&&(r.status="rejected",r.reason=e)})),r.status){case"fulfilled":return r.value;case"rejected":throw r.reason}}throw r}function Sm(r,e,a,s,l){var d=typeof r;(d==="undefined"||d==="boolean")&&(r=null);var x=!1;if(r===null)x=!0;else switch(d){case"bigint":case"string":case"number":x=!0;break;case"object":switch(r.$$typeof){case aq:case qEt:x=!0;break;case w2e:return x=r._init,Sm(x(r._payload),e,a,s,l)}}if(x)return l=l(r),x=s===""?"."+nq(r,0):s,A2e(l)?(a="",x!=null&&(a=x.replace(R2e,"$&/")+"/"),Sm(l,e,a,"",function(D){return D})):l!=null&&(uq(l)&&(l=ZEt(l,a+(l.key==null||r&&r.key===l.key?"":(""+l.key).replace(R2e,"$&/")+"/")+x)),e.push(l)),1;x=0;var f=s===""?".":s+":";if(A2e(r))for(var m=0;m<r.length;m++)s=r[m],d=f+nq(s,m),x+=Sm(s,e,a,d,l);else if(m=JEt(r),typeof m=="function")for(r=m.call(r),m=0;!(s=r.next()).done;)s=s.value,d=f+nq(s,m++),x+=Sm(s,e,a,d,l);else if(d==="object"){if(typeof r.then=="function")return Sm(evt(r),e,a,s,l);throw e=String(r),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(r).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return x}function wA(r,e,a){if(r==null)return r;var s=[],l=0;return Sm(r,s,"","",function(d){return e.call(a,d,l++)}),s}function tvt(r){if(r._status===-1){var e=r._result;e=e(),e.then(function(a){(r._status===0||r._status===-1)&&(r._status=1,r._result=a)},function(a){(r._status===0||r._status===-1)&&(r._status=2,r._result=a)}),r._status===-1&&(r._status=0,r._result=e)}if(r._status===1)return r._result.default;throw r._result}var B2e=typeof reportError=="function"?reportError:function(r){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof r=="object"&&r!==null&&typeof r.message=="string"?String(r.message):String(r),error:r});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",r);return}console.error(r)};function rvt(){}Rn.Children={map:wA,forEach:function(r,e,a){wA(r,function(){e.apply(this,arguments)},a)},count:function(r){var e=0;return wA(r,function(){e++}),e},toArray:function(r){return wA(r,function(e){return e})||[]},only:function(r){if(!uq(r))throw Error("React.Children.only expected to receive a single React element child.");return r}};Rn.Component=Bm;Rn.Fragment=UEt;Rn.Profiler=GEt;Rn.PureComponent=sq;Rn.StrictMode=VEt;Rn.Suspense=WEt;Rn.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Za;Rn.__COMPILER_RUNTIME={__proto__:null,c:function(r){return Za.H.useMemoCache(r)}};Rn.cache=function(r){return function(){return r.apply(null,arguments)}};Rn.cloneElement=function(r,e,a){if(r==null)throw Error("The argument must be a React element, but you passed "+r+".");var s=P2e({},r.props),l=r.key,d=void 0;if(e!=null)for(x in e.ref!==void 0&&(d=void 0),e.key!==void 0&&(l=""+e.key),e)!k2e.call(e,x)||x==="key"||x==="__self"||x==="__source"||x==="ref"&&e.ref===void 0||(s[x]=e[x]);var x=arguments.length-2;if(x===1)s.children=a;else if(1<x){for(var f=Array(x),m=0;m<x;m++)f[m]=arguments[m+2];s.children=f}return oq(r.type,l,void 0,void 0,d,s)};Rn.createContext=function(r){return r={$$typeof:YEt,_currentValue:r,_currentValue2:r,_threadCount:0,Provider:null,Consumer:null},r.Provider=r,r.Consumer={$$typeof:XEt,_context:r},r};Rn.createElement=function(r,e,a){var s,l={},d=null;if(e!=null)for(s in e.key!==void 0&&(d=""+e.key),e)k2e.call(e,s)&&s!=="key"&&s!=="__self"&&s!=="__source"&&(l[s]=e[s]);var x=arguments.length-2;if(x===1)l.children=a;else if(1<x){for(var f=Array(x),m=0;m<x;m++)f[m]=arguments[m+2];l.children=f}if(r&&r.defaultProps)for(s in x=r.defaultProps,x)l[s]===void 0&&(l[s]=x[s]);return oq(r,d,void 0,void 0,null,l)};Rn.createRef=function(){return{current:null}};Rn.forwardRef=function(r){return{$$typeof:HEt,render:r}};Rn.isValidElement=uq;Rn.lazy=function(r){return{$$typeof:w2e,_payload:{_status:-1,_result:r},_init:tvt}};Rn.memo=function(r,e){return{$$typeof:KEt,type:r,compare:e===void 0?null:e}};Rn.startTransition=function(r){var e=Za.T,a={};Za.T=a;try{var s=r(),l=Za.S;l!==null&&l(a,s),typeof s=="object"&&s!==null&&typeof s.then=="function"&&s.then(rvt,B2e)}catch(d){B2e(d)}finally{Za.T=e}};Rn.unstable_useCacheRefresh=function(){return Za.H.useCacheRefresh()};Rn.use=function(r){return Za.H.use(r)};Rn.useActionState=function(r,e,a){return Za.H.useActionState(r,e,a)};Rn.useCallback=function(r,e){return Za.H.useCallback(r,e)};Rn.useContext=function(r){return Za.H.useContext(r)};Rn.useDebugValue=function(){};Rn.useDeferredValue=function(r,e){return Za.H.useDeferredValue(r,e)};Rn.useEffect=function(r,e,a){var s=Za.H;if(typeof a=="function")throw Error("useEffect CRUD overload is not enabled in this build of React.");return s.useEffect(r,e)};Rn.useId=function(){return Za.H.useId()};Rn.useImperativeHandle=function(r,e,a){return Za.H.useImperativeHandle(r,e,a)};Rn.useInsertionEffect=function(r,e){return Za.H.useInsertionEffect(r,e)};Rn.useLayoutEffect=function(r,e){return Za.H.useLayoutEffect(r,e)};Rn.useMemo=function(r,e){return Za.H.useMemo(r,e)};Rn.useOptimistic=function(r,e){return Za.H.useOptimistic(r,e)};Rn.useReducer=function(r,e,a){return Za.H.useReducer(r,e,a)};Rn.useRef=function(r){return Za.H.useRef(r)};Rn.useState=function(r){return Za.H.useState(r)};Rn.useSyncExternalStore=function(r,e,a){return Za.H.useSyncExternalStore(r,e,a)};Rn.useTransition=function(){return Za.H.useTransition()};Rn.version="19.1.1"});var kc=on((cYt,M2e)=>{"use strict";M2e.exports=N2e()});var $n,cq,vr,$0,hb=Sr(()=>{"use strict";(function(r){r.assertEqual=l=>{};function e(l){}r.assertIs=e;function a(l){throw new Error}r.assertNever=a,r.arrayToEnum=l=>{let d={};for(let x of l)d[x]=x;return d},r.getValidEnumValues=l=>{let d=r.objectKeys(l).filter(f=>typeof l[l[f]]!="number"),x={};for(let f of d)x[f]=l[f];return r.objectValues(x)},r.objectValues=l=>r.objectKeys(l).map(function(d){return l[d]}),r.objectKeys=typeof Object.keys=="function"?l=>Object.keys(l):l=>{let d=[];for(let x in l)Object.prototype.hasOwnProperty.call(l,x)&&d.push(x);return d},r.find=(l,d)=>{for(let x of l)if(d(x))return x},r.isInteger=typeof Number.isInteger=="function"?l=>Number.isInteger(l):l=>typeof l=="number"&&Number.isFinite(l)&&Math.floor(l)===l;function s(l,d=" | "){return l.map(x=>typeof x=="string"?`'${x}'`:x).join(d)}r.joinValues=s,r.jsonStringifyReplacer=(l,d)=>typeof d=="bigint"?d.toString():d})($n||($n={}));(function(r){r.mergeShapes=(e,a)=>({...e,...a})})(cq||(cq={}));vr=$n.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),$0=r=>{switch(typeof r){case"undefined":return vr.undefined;case"string":return vr.string;case"number":return Number.isNaN(r)?vr.nan:vr.number;case"boolean":return vr.boolean;case"function":return vr.function;case"bigint":return vr.bigint;case"symbol":return vr.symbol;case"object":return Array.isArray(r)?vr.array:r===null?vr.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?vr.promise:typeof Map<"u"&&r instanceof Map?vr.map:typeof Set<"u"&&r instanceof Set?vr.set:typeof Date<"u"&&r instanceof Date?vr.date:vr.object;default:return vr.unknown}}});var nr,nvt,Wo,TA=Sr(()=>{"use strict";hb();nr=$n.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),nvt=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),Wo=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let a=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,a):this.__proto__=a,this.name="ZodError",this.issues=e}format(e){let a=e||function(d){return d.message},s={_errors:[]},l=d=>{for(let x of d.issues)if(x.code==="invalid_union")x.unionErrors.map(l);else if(x.code==="invalid_return_type")l(x.returnTypeError);else if(x.code==="invalid_arguments")l(x.argumentsError);else if(x.path.length===0)s._errors.push(a(x));else{let f=s,m=0;for(;m<x.path.length;){let D=x.path[m];m===x.path.length-1?(f[D]=f[D]||{_errors:[]},f[D]._errors.push(a(x))):f[D]=f[D]||{_errors:[]},f=f[D],m++}}};return l(this),s}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$n.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=a=>a.message){let a={},s=[];for(let l of this.issues)if(l.path.length>0){let d=l.path[0];a[d]=a[d]||[],a[d].push(e(l))}else s.push(e(l));return{formErrors:s,fieldErrors:a}}get formErrors(){return this.flatten()}};Wo.create=r=>new Wo(r)});var avt,ql,lq=Sr(()=>{"use strict";TA();hb();avt=(r,e)=>{let a;switch(r.code){case nr.invalid_type:r.received===vr.undefined?a="Required":a=`Expected ${r.expected}, received ${r.received}`;break;case nr.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(r.expected,$n.jsonStringifyReplacer)}`;break;case nr.unrecognized_keys:a=`Unrecognized key(s) in object: ${$n.joinValues(r.keys,", ")}`;break;case nr.invalid_union:a="Invalid input";break;case nr.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${$n.joinValues(r.options)}`;break;case nr.invalid_enum_value:a=`Invalid enum value. Expected ${$n.joinValues(r.options)}, received '${r.received}'`;break;case nr.invalid_arguments:a="Invalid function arguments";break;case nr.invalid_return_type:a="Invalid function return type";break;case nr.invalid_date:a="Invalid date";break;case nr.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(a=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(a=`${a} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?a=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?a=`Invalid input: must end with "${r.validation.endsWith}"`:$n.assertNever(r.validation):r.validation!=="regex"?a=`Invalid ${r.validation}`:a="Invalid";break;case nr.too_small:r.type==="array"?a=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?a=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?a=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?a=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?a=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:a="Invalid input";break;case nr.too_big:r.type==="array"?a=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?a=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?a=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?a=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?a=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:a="Invalid input";break;case nr.custom:a="Invalid input";break;case nr.invalid_intersection_types:a="Intersection results could not be merged";break;case nr.not_multiple_of:a=`Number must be a multiple of ${r.multipleOf}`;break;case nr.not_finite:a="Number must be finite";break;default:a=e.defaultError,$n.assertNever(r)}return{message:a}},ql=avt});function svt(r){O2e=r}function wm(){return O2e}var O2e,PA=Sr(()=>{"use strict";lq();O2e=ql});function gr(r,e){let a=wm(),s=mb({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,a,a===ql?void 0:ql].filter(l=>!!l)});r.common.issues.push(s)}var mb,ivt,Ri,rn,Bf,Wi,IA,jA,_p,Tm,dq=Sr(()=>{"use strict";PA();lq();mb=r=>{let{data:e,path:a,errorMaps:s,issueData:l}=r,d=[...a,...l.path||[]],x={...l,path:d};if(l.message!==void 0)return{...l,path:d,message:l.message};let f="",m=s.filter(D=>!!D).slice().reverse();for(let D of m)f=D(x,{data:e,defaultError:f}).message;return{...l,path:d,message:f}},ivt=[];Ri=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,a){let s=[];for(let l of a){if(l.status==="aborted")return rn;l.status==="dirty"&&e.dirty(),s.push(l.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,a){let s=[];for(let l of a){let d=await l.key,x=await l.value;s.push({key:d,value:x})}return r.mergeObjectSync(e,s)}static mergeObjectSync(e,a){let s={};for(let l of a){let{key:d,value:x}=l;if(d.status==="aborted"||x.status==="aborted")return rn;d.status==="dirty"&&e.dirty(),x.status==="dirty"&&e.dirty(),d.value!=="__proto__"&&(typeof x.value<"u"||l.alwaysSet)&&(s[d.value]=x.value)}return{status:e.value,value:s}}},rn=Object.freeze({status:"aborted"}),Bf=r=>({status:"dirty",value:r}),Wi=r=>({status:"valid",value:r}),IA=r=>r.status==="aborted",jA=r=>r.status==="dirty",_p=r=>r.status==="valid",Tm=r=>typeof Promise<"u"&&r instanceof Promise});var L2e=Sr(()=>{"use strict"});var Nr,$2e=Sr(()=>{"use strict";(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(Nr||(Nr={}))});function Fn(r){if(!r)return{};let{errorMap:e,invalid_type_error:a,required_error:s,description:l}=r;if(e&&(a||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:l}:{errorMap:(x,f)=>{let{message:m}=r;return x.code==="invalid_enum_value"?{message:m??f.defaultError}:typeof f.data>"u"?{message:m??s??f.defaultError}:x.code!=="invalid_type"?{message:f.defaultError}:{message:m??a??f.defaultError}},description:l}}function V2e(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let a=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${a}`}function vvt(r){return new RegExp(`^${V2e(r)}$`)}function G2e(r){let e=`${U2e}T${V2e(r)}`,a=[];return a.push(r.local?"Z?":"Z"),r.offset&&a.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${a.join("|")})`,new RegExp(`^${e}$`)}function Cvt(r,e){return!!((e==="v4"||!e)&&mvt.test(r)||(e==="v6"||!e)&&Dvt.test(r))}function _vt(r,e){if(!pvt.test(r))return!1;try{let[a]=r.split(".");if(!a)return!1;let s=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(a.length+(4-a.length%4)%4,"="),l=JSON.parse(atob(s));return!(typeof l!="object"||l===null||"typ"in l&&l?.typ!=="JWT"||!l.alg||e&&l.alg!==e)}catch{return!1}}function Avt(r,e){return!!((e==="v4"||!e)&&gvt.test(r)||(e==="v6"||!e)&&yvt.test(r))}function Rvt(r,e){let a=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,l=a>s?a:s,d=Number.parseInt(r.toFixed(l).replace(".","")),x=Number.parseInt(e.toFixed(l).replace(".",""));return d%x/10**l}function Pm(r){if(r instanceof Ko){let e={};for(let a in r.shape){let s=r.shape[a];e[a]=Hu.create(Pm(s))}return new Ko({...r._def,shape:()=>e})}else return r instanceof Gl?new Gl({...r._def,type:Pm(r.element)}):r instanceof Hu?Hu.create(Pm(r.unwrap())):r instanceof q0?q0.create(Pm(r.unwrap())):r instanceof z0?z0.create(r.items.map(e=>Pm(e))):r}function xq(r,e){let a=$0(r),s=$0(e);if(r===e)return{valid:!0,data:r};if(a===vr.object&&s===vr.object){let l=$n.objectKeys(e),d=$n.objectKeys(r).filter(f=>l.indexOf(f)!==-1),x={...r,...e};for(let f of d){let m=xq(r[f],e[f]);if(!m.valid)return{valid:!1};x[f]=m.data}return{valid:!0,data:x}}else if(a===vr.array&&s===vr.array){if(r.length!==e.length)return{valid:!1};let l=[];for(let d=0;d<r.length;d++){let x=r[d],f=e[d],m=xq(x,f);if(!m.valid)return{valid:!1};l.push(m.data)}return{valid:!0,data:l}}else return a===vr.date&&s===vr.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}function X2e(r,e){return new $f({values:r,typeName:un.ZodEnum,...Fn(e)})}function q2e(r,e){let a=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof a=="string"?{message:a}:a}function Y2e(r,e={},a){return r?Rp.create().superRefine((s,l)=>{let d=r(s);if(d instanceof Promise)return d.then(x=>{if(!x){let f=q2e(e,s),m=f.fatal??a??!0;l.addIssue({code:"custom",...f,fatal:m})}});if(!d){let x=q2e(e,s),f=x.fatal??a??!0;l.addIssue({code:"custom",...x,fatal:f})}}):Rp.create()}var Wu,z2e,Sn,ovt,uvt,cvt,lvt,dvt,pvt,xvt,fvt,hvt,pq,mvt,gvt,Dvt,yvt,bvt,Fvt,U2e,Evt,Ap,wf,Tf,Pf,If,Im,jf,kf,Rp,Vl,Nc,jm,Gl,Ko,Nf,Ul,kA,Mf,z0,NA,km,Nm,MA,Of,Lf,$f,zf,Sp,Ku,Hu,q0,qf,Uf,Mm,Svt,gb,Db,Vf,Bvt,un,wvt,H2e,W2e,Tvt,Pvt,K2e,Ivt,jvt,kvt,Nvt,Mvt,Ovt,Lvt,$vt,zvt,qvt,Uvt,Vvt,Gvt,Xvt,Yvt,Hvt,Wvt,Kvt,Jvt,Zvt,Qvt,eCt,tCt,rCt,nCt,aCt,sCt,iCt,oCt,uCt,cCt,lCt,dCt,pCt,J2e=Sr(()=>{"use strict";TA();PA();$2e();dq();hb();Wu=class{constructor(e,a,s,l){this._cachedPath=[],this.parent=e,this.data=a,this._path=s,this._key=l}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},z2e=(r,e)=>{if(_p(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let a=new Wo(r.common.issues);return this._error=a,this._error}}};Sn=class{get description(){return this._def.description}_getType(e){return $0(e.data)}_getOrReturnCtx(e,a){return a||{common:e.parent.common,data:e.data,parsedType:$0(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ri,ctx:{common:e.parent.common,data:e.data,parsedType:$0(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let a=this._parse(e);if(Tm(a))throw new Error("Synchronous parse encountered promise.");return a}_parseAsync(e){let a=this._parse(e);return Promise.resolve(a)}parse(e,a){let s=this.safeParse(e,a);if(s.success)return s.data;throw s.error}safeParse(e,a){let s={common:{issues:[],async:a?.async??!1,contextualErrorMap:a?.errorMap},path:a?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$0(e)},l=this._parseSync({data:e,path:s.path,parent:s});return z2e(s,l)}"~validate"(e){let a={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$0(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:a});return _p(s)?{value:s.value}:{issues:a.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),a.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:a}).then(s=>_p(s)?{value:s.value}:{issues:a.common.issues})}async parseAsync(e,a){let s=await this.safeParseAsync(e,a);if(s.success)return s.data;throw s.error}async safeParseAsync(e,a){let s={common:{issues:[],contextualErrorMap:a?.errorMap,async:!0},path:a?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$0(e)},l=this._parse({data:e,path:s.path,parent:s}),d=await(Tm(l)?l:Promise.resolve(l));return z2e(s,d)}refine(e,a){let s=l=>typeof a=="string"||typeof a>"u"?{message:a}:typeof a=="function"?a(l):a;return this._refinement((l,d)=>{let x=e(l),f=()=>d.addIssue({code:nr.custom,...s(l)});return typeof Promise<"u"&&x instanceof Promise?x.then(m=>m?!0:(f(),!1)):x?!0:(f(),!1)})}refinement(e,a){return this._refinement((s,l)=>e(s)?!0:(l.addIssue(typeof a=="function"?a(s,l):a),!1))}_refinement(e){return new Ku({schema:this,typeName:un.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:a=>this["~validate"](a)}}optional(){return Hu.create(this,this._def)}nullable(){return q0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Gl.create(this)}promise(){return Sp.create(this,this._def)}or(e){return Nf.create([this,e],this._def)}and(e){return Mf.create(this,e,this._def)}transform(e){return new Ku({...Fn(this._def),schema:this,typeName:un.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let a=typeof e=="function"?e:()=>e;return new qf({...Fn(this._def),innerType:this,defaultValue:a,typeName:un.ZodDefault})}brand(){return new gb({typeName:un.ZodBranded,type:this,...Fn(this._def)})}catch(e){let a=typeof e=="function"?e:()=>e;return new Uf({...Fn(this._def),innerType:this,catchValue:a,typeName:un.ZodCatch})}describe(e){let a=this.constructor;return new a({...this._def,description:e})}pipe(e){return Db.create(this,e)}readonly(){return Vf.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ovt=/^c[^\s-]{8,}$/i,uvt=/^[0-9a-z]+$/,cvt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,lvt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,dvt=/^[a-z0-9_-]{21}$/i,pvt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,xvt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,fvt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,hvt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",mvt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,gvt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Dvt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,yvt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bvt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Fvt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,U2e="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Evt=new RegExp(`^${U2e}$`);Ap=class r extends Sn{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==vr.string){let d=this._getOrReturnCtx(e);return gr(d,{code:nr.invalid_type,expected:vr.string,received:d.parsedType}),rn}let s=new Ri,l;for(let d of this._def.checks)if(d.kind==="min")e.data.length<d.value&&(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.too_small,minimum:d.value,type:"string",inclusive:!0,exact:!1,message:d.message}),s.dirty());else if(d.kind==="max")e.data.length>d.value&&(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.too_big,maximum:d.value,type:"string",inclusive:!0,exact:!1,message:d.message}),s.dirty());else if(d.kind==="length"){let x=e.data.length>d.value,f=e.data.length<d.value;(x||f)&&(l=this._getOrReturnCtx(e,l),x?gr(l,{code:nr.too_big,maximum:d.value,type:"string",inclusive:!0,exact:!0,message:d.message}):f&&gr(l,{code:nr.too_small,minimum:d.value,type:"string",inclusive:!0,exact:!0,message:d.message}),s.dirty())}else if(d.kind==="email")fvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"email",code:nr.invalid_string,message:d.message}),s.dirty());else if(d.kind==="emoji")pq||(pq=new RegExp(hvt,"u")),pq.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"emoji",code:nr.invalid_string,message:d.message}),s.dirty());else if(d.kind==="uuid")lvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"uuid",code:nr.invalid_string,message:d.message}),s.dirty());else if(d.kind==="nanoid")dvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"nanoid",code:nr.invalid_string,message:d.message}),s.dirty());else if(d.kind==="cuid")ovt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"cuid",code:nr.invalid_string,message:d.message}),s.dirty());else if(d.kind==="cuid2")uvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"cuid2",code:nr.invalid_string,message:d.message}),s.dirty());else if(d.kind==="ulid")cvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"ulid",code:nr.invalid_string,message:d.message}),s.dirty());else if(d.kind==="url")try{new URL(e.data)}catch{l=this._getOrReturnCtx(e,l),gr(l,{validation:"url",code:nr.invalid_string,message:d.message}),s.dirty()}else d.kind==="regex"?(d.regex.lastIndex=0,d.regex.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"regex",code:nr.invalid_string,message:d.message}),s.dirty())):d.kind==="trim"?e.data=e.data.trim():d.kind==="includes"?e.data.includes(d.value,d.position)||(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.invalid_string,validation:{includes:d.value,position:d.position},message:d.message}),s.dirty()):d.kind==="toLowerCase"?e.data=e.data.toLowerCase():d.kind==="toUpperCase"?e.data=e.data.toUpperCase():d.kind==="startsWith"?e.data.startsWith(d.value)||(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.invalid_string,validation:{startsWith:d.value},message:d.message}),s.dirty()):d.kind==="endsWith"?e.data.endsWith(d.value)||(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.invalid_string,validation:{endsWith:d.value},message:d.message}),s.dirty()):d.kind==="datetime"?G2e(d).test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.invalid_string,validation:"datetime",message:d.message}),s.dirty()):d.kind==="date"?Evt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.invalid_string,validation:"date",message:d.message}),s.dirty()):d.kind==="time"?vvt(d).test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.invalid_string,validation:"time",message:d.message}),s.dirty()):d.kind==="duration"?xvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"duration",code:nr.invalid_string,message:d.message}),s.dirty()):d.kind==="ip"?Cvt(e.data,d.version)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"ip",code:nr.invalid_string,message:d.message}),s.dirty()):d.kind==="jwt"?_vt(e.data,d.alg)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"jwt",code:nr.invalid_string,message:d.message}),s.dirty()):d.kind==="cidr"?Avt(e.data,d.version)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"cidr",code:nr.invalid_string,message:d.message}),s.dirty()):d.kind==="base64"?bvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"base64",code:nr.invalid_string,message:d.message}),s.dirty()):d.kind==="base64url"?Fvt.test(e.data)||(l=this._getOrReturnCtx(e,l),gr(l,{validation:"base64url",code:nr.invalid_string,message:d.message}),s.dirty()):$n.assertNever(d);return{status:s.value,value:e.data}}_regex(e,a,s){return this.refinement(l=>e.test(l),{validation:a,code:nr.invalid_string,...Nr.errToObj(s)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Nr.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Nr.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Nr.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Nr.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Nr.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Nr.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Nr.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Nr.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Nr.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Nr.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Nr.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Nr.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Nr.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Nr.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Nr.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Nr.errToObj(e)})}regex(e,a){return this._addCheck({kind:"regex",regex:e,...Nr.errToObj(a)})}includes(e,a){return this._addCheck({kind:"includes",value:e,position:a?.position,...Nr.errToObj(a?.message)})}startsWith(e,a){return this._addCheck({kind:"startsWith",value:e,...Nr.errToObj(a)})}endsWith(e,a){return this._addCheck({kind:"endsWith",value:e,...Nr.errToObj(a)})}min(e,a){return this._addCheck({kind:"min",value:e,...Nr.errToObj(a)})}max(e,a){return this._addCheck({kind:"max",value:e,...Nr.errToObj(a)})}length(e,a){return this._addCheck({kind:"length",value:e,...Nr.errToObj(a)})}nonempty(e){return this.min(1,Nr.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxLength(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e}};Ap.create=r=>new Ap({checks:[],typeName:un.ZodString,coerce:r?.coerce??!1,...Fn(r)});wf=class r extends Sn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==vr.number){let d=this._getOrReturnCtx(e);return gr(d,{code:nr.invalid_type,expected:vr.number,received:d.parsedType}),rn}let s,l=new Ri;for(let d of this._def.checks)d.kind==="int"?$n.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.invalid_type,expected:"integer",received:"float",message:d.message}),l.dirty()):d.kind==="min"?(d.inclusive?e.data<d.value:e.data<=d.value)&&(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.too_small,minimum:d.value,type:"number",inclusive:d.inclusive,exact:!1,message:d.message}),l.dirty()):d.kind==="max"?(d.inclusive?e.data>d.value:e.data>=d.value)&&(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.too_big,maximum:d.value,type:"number",inclusive:d.inclusive,exact:!1,message:d.message}),l.dirty()):d.kind==="multipleOf"?Rvt(e.data,d.value)!==0&&(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.not_multiple_of,multipleOf:d.value,message:d.message}),l.dirty()):d.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.not_finite,message:d.message}),l.dirty()):$n.assertNever(d);return{status:l.value,value:e.data}}gte(e,a){return this.setLimit("min",e,!0,Nr.toString(a))}gt(e,a){return this.setLimit("min",e,!1,Nr.toString(a))}lte(e,a){return this.setLimit("max",e,!0,Nr.toString(a))}lt(e,a){return this.setLimit("max",e,!1,Nr.toString(a))}setLimit(e,a,s,l){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:a,inclusive:s,message:Nr.toString(l)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Nr.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Nr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Nr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Nr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Nr.toString(e)})}multipleOf(e,a){return this._addCheck({kind:"multipleOf",value:e,message:Nr.toString(a)})}finite(e){return this._addCheck({kind:"finite",message:Nr.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Nr.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Nr.toString(e)})}get minValue(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxValue(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&$n.isInteger(e.value))}get isFinite(){let e=null,a=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(a===null||s.value>a)&&(a=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(a)&&Number.isFinite(e)}};wf.create=r=>new wf({checks:[],typeName:un.ZodNumber,coerce:r?.coerce||!1,...Fn(r)});Tf=class r extends Sn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==vr.bigint)return this._getInvalidInput(e);let s,l=new Ri;for(let d of this._def.checks)d.kind==="min"?(d.inclusive?e.data<d.value:e.data<=d.value)&&(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.too_small,type:"bigint",minimum:d.value,inclusive:d.inclusive,message:d.message}),l.dirty()):d.kind==="max"?(d.inclusive?e.data>d.value:e.data>=d.value)&&(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.too_big,type:"bigint",maximum:d.value,inclusive:d.inclusive,message:d.message}),l.dirty()):d.kind==="multipleOf"?e.data%d.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),gr(s,{code:nr.not_multiple_of,multipleOf:d.value,message:d.message}),l.dirty()):$n.assertNever(d);return{status:l.value,value:e.data}}_getInvalidInput(e){let a=this._getOrReturnCtx(e);return gr(a,{code:nr.invalid_type,expected:vr.bigint,received:a.parsedType}),rn}gte(e,a){return this.setLimit("min",e,!0,Nr.toString(a))}gt(e,a){return this.setLimit("min",e,!1,Nr.toString(a))}lte(e,a){return this.setLimit("max",e,!0,Nr.toString(a))}lt(e,a){return this.setLimit("max",e,!1,Nr.toString(a))}setLimit(e,a,s,l){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:a,inclusive:s,message:Nr.toString(l)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Nr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Nr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Nr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Nr.toString(e)})}multipleOf(e,a){return this._addCheck({kind:"multipleOf",value:e,message:Nr.toString(a)})}get minValue(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxValue(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e}};Tf.create=r=>new Tf({checks:[],typeName:un.ZodBigInt,coerce:r?.coerce??!1,...Fn(r)});Pf=class extends Sn{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==vr.boolean){let s=this._getOrReturnCtx(e);return gr(s,{code:nr.invalid_type,expected:vr.boolean,received:s.parsedType}),rn}return Wi(e.data)}};Pf.create=r=>new Pf({typeName:un.ZodBoolean,coerce:r?.coerce||!1,...Fn(r)});If=class r extends Sn{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==vr.date){let d=this._getOrReturnCtx(e);return gr(d,{code:nr.invalid_type,expected:vr.date,received:d.parsedType}),rn}if(Number.isNaN(e.data.getTime())){let d=this._getOrReturnCtx(e);return gr(d,{code:nr.invalid_date}),rn}let s=new Ri,l;for(let d of this._def.checks)d.kind==="min"?e.data.getTime()<d.value&&(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.too_small,message:d.message,inclusive:!0,exact:!1,minimum:d.value,type:"date"}),s.dirty()):d.kind==="max"?e.data.getTime()>d.value&&(l=this._getOrReturnCtx(e,l),gr(l,{code:nr.too_big,message:d.message,inclusive:!0,exact:!1,maximum:d.value,type:"date"}),s.dirty()):$n.assertNever(d);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,a){return this._addCheck({kind:"min",value:e.getTime(),message:Nr.toString(a)})}max(e,a){return this._addCheck({kind:"max",value:e.getTime(),message:Nr.toString(a)})}get minDate(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e!=null?new Date(e):null}};If.create=r=>new If({checks:[],coerce:r?.coerce||!1,typeName:un.ZodDate,...Fn(r)});Im=class extends Sn{_parse(e){if(this._getType(e)!==vr.symbol){let s=this._getOrReturnCtx(e);return gr(s,{code:nr.invalid_type,expected:vr.symbol,received:s.parsedType}),rn}return Wi(e.data)}};Im.create=r=>new Im({typeName:un.ZodSymbol,...Fn(r)});jf=class extends Sn{_parse(e){if(this._getType(e)!==vr.undefined){let s=this._getOrReturnCtx(e);return gr(s,{code:nr.invalid_type,expected:vr.undefined,received:s.parsedType}),rn}return Wi(e.data)}};jf.create=r=>new jf({typeName:un.ZodUndefined,...Fn(r)});kf=class extends Sn{_parse(e){if(this._getType(e)!==vr.null){let s=this._getOrReturnCtx(e);return gr(s,{code:nr.invalid_type,expected:vr.null,received:s.parsedType}),rn}return Wi(e.data)}};kf.create=r=>new kf({typeName:un.ZodNull,...Fn(r)});Rp=class extends Sn{constructor(){super(...arguments),this._any=!0}_parse(e){return Wi(e.data)}};Rp.create=r=>new Rp({typeName:un.ZodAny,...Fn(r)});Vl=class extends Sn{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Wi(e.data)}};Vl.create=r=>new Vl({typeName:un.ZodUnknown,...Fn(r)});Nc=class extends Sn{_parse(e){let a=this._getOrReturnCtx(e);return gr(a,{code:nr.invalid_type,expected:vr.never,received:a.parsedType}),rn}};Nc.create=r=>new Nc({typeName:un.ZodNever,...Fn(r)});jm=class extends Sn{_parse(e){if(this._getType(e)!==vr.undefined){let s=this._getOrReturnCtx(e);return gr(s,{code:nr.invalid_type,expected:vr.void,received:s.parsedType}),rn}return Wi(e.data)}};jm.create=r=>new jm({typeName:un.ZodVoid,...Fn(r)});Gl=class r extends Sn{_parse(e){let{ctx:a,status:s}=this._processInputParams(e),l=this._def;if(a.parsedType!==vr.array)return gr(a,{code:nr.invalid_type,expected:vr.array,received:a.parsedType}),rn;if(l.exactLength!==null){let x=a.data.length>l.exactLength.value,f=a.data.length<l.exactLength.value;(x||f)&&(gr(a,{code:x?nr.too_big:nr.too_small,minimum:f?l.exactLength.value:void 0,maximum:x?l.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:l.exactLength.message}),s.dirty())}if(l.minLength!==null&&a.data.length<l.minLength.value&&(gr(a,{code:nr.too_small,minimum:l.minLength.value,type:"array",inclusive:!0,exact:!1,message:l.minLength.message}),s.dirty()),l.maxLength!==null&&a.data.length>l.maxLength.value&&(gr(a,{code:nr.too_big,maximum:l.maxLength.value,type:"array",inclusive:!0,exact:!1,message:l.maxLength.message}),s.dirty()),a.common.async)return Promise.all([...a.data].map((x,f)=>l.type._parseAsync(new Wu(a,x,a.path,f)))).then(x=>Ri.mergeArray(s,x));let d=[...a.data].map((x,f)=>l.type._parseSync(new Wu(a,x,a.path,f)));return Ri.mergeArray(s,d)}get element(){return this._def.type}min(e,a){return new r({...this._def,minLength:{value:e,message:Nr.toString(a)}})}max(e,a){return new r({...this._def,maxLength:{value:e,message:Nr.toString(a)}})}length(e,a){return new r({...this._def,exactLength:{value:e,message:Nr.toString(a)}})}nonempty(e){return this.min(1,e)}};Gl.create=(r,e)=>new Gl({type:r,minLength:null,maxLength:null,exactLength:null,typeName:un.ZodArray,...Fn(e)});Ko=class r extends Sn{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),a=$n.objectKeys(e);return this._cached={shape:e,keys:a},this._cached}_parse(e){if(this._getType(e)!==vr.object){let D=this._getOrReturnCtx(e);return gr(D,{code:nr.invalid_type,expected:vr.object,received:D.parsedType}),rn}let{status:s,ctx:l}=this._processInputParams(e),{shape:d,keys:x}=this._getCached(),f=[];if(!(this._def.catchall instanceof Nc&&this._def.unknownKeys==="strip"))for(let D in l.data)x.includes(D)||f.push(D);let m=[];for(let D of x){let b=d[D],E=l.data[D];m.push({key:{status:"valid",value:D},value:b._parse(new Wu(l,E,l.path,D)),alwaysSet:D in l.data})}if(this._def.catchall instanceof Nc){let D=this._def.unknownKeys;if(D==="passthrough")for(let b of f)m.push({key:{status:"valid",value:b},value:{status:"valid",value:l.data[b]}});else if(D==="strict")f.length>0&&(gr(l,{code:nr.unrecognized_keys,keys:f}),s.dirty());else if(D!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let D=this._def.catchall;for(let b of f){let E=l.data[b];m.push({key:{status:"valid",value:b},value:D._parse(new Wu(l,E,l.path,b)),alwaysSet:b in l.data})}}return l.common.async?Promise.resolve().then(async()=>{let D=[];for(let b of m){let E=await b.key,A=await b.value;D.push({key:E,value:A,alwaysSet:b.alwaysSet})}return D}).then(D=>Ri.mergeObjectSync(s,D)):Ri.mergeObjectSync(s,m)}get shape(){return this._def.shape()}strict(e){return Nr.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(a,s)=>{let l=this._def.errorMap?.(a,s).message??s.defaultError;return a.code==="unrecognized_keys"?{message:Nr.errToObj(e).message??l}:{message:l}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:un.ZodObject})}setKey(e,a){return this.augment({[e]:a})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let a={};for(let s of $n.objectKeys(e))e[s]&&this.shape[s]&&(a[s]=this.shape[s]);return new r({...this._def,shape:()=>a})}omit(e){let a={};for(let s of $n.objectKeys(this.shape))e[s]||(a[s]=this.shape[s]);return new r({...this._def,shape:()=>a})}deepPartial(){return Pm(this)}partial(e){let a={};for(let s of $n.objectKeys(this.shape)){let l=this.shape[s];e&&!e[s]?a[s]=l:a[s]=l.optional()}return new r({...this._def,shape:()=>a})}required(e){let a={};for(let s of $n.objectKeys(this.shape))if(e&&!e[s])a[s]=this.shape[s];else{let d=this.shape[s];for(;d instanceof Hu;)d=d._def.innerType;a[s]=d}return new r({...this._def,shape:()=>a})}keyof(){return X2e($n.objectKeys(this.shape))}};Ko.create=(r,e)=>new Ko({shape:()=>r,unknownKeys:"strip",catchall:Nc.create(),typeName:un.ZodObject,...Fn(e)});Ko.strictCreate=(r,e)=>new Ko({shape:()=>r,unknownKeys:"strict",catchall:Nc.create(),typeName:un.ZodObject,...Fn(e)});Ko.lazycreate=(r,e)=>new Ko({shape:r,unknownKeys:"strip",catchall:Nc.create(),typeName:un.ZodObject,...Fn(e)});Nf=class extends Sn{_parse(e){let{ctx:a}=this._processInputParams(e),s=this._def.options;function l(d){for(let f of d)if(f.result.status==="valid")return f.result;for(let f of d)if(f.result.status==="dirty")return a.common.issues.push(...f.ctx.common.issues),f.result;let x=d.map(f=>new Wo(f.ctx.common.issues));return gr(a,{code:nr.invalid_union,unionErrors:x}),rn}if(a.common.async)return Promise.all(s.map(async d=>{let x={...a,common:{...a.common,issues:[]},parent:null};return{result:await d._parseAsync({data:a.data,path:a.path,parent:x}),ctx:x}})).then(l);{let d,x=[];for(let m of s){let D={...a,common:{...a.common,issues:[]},parent:null},b=m._parseSync({data:a.data,path:a.path,parent:D});if(b.status==="valid")return b;b.status==="dirty"&&!d&&(d={result:b,ctx:D}),D.common.issues.length&&x.push(D.common.issues)}if(d)return a.common.issues.push(...d.ctx.common.issues),d.result;let f=x.map(m=>new Wo(m));return gr(a,{code:nr.invalid_union,unionErrors:f}),rn}}get options(){return this._def.options}};Nf.create=(r,e)=>new Nf({options:r,typeName:un.ZodUnion,...Fn(e)});Ul=r=>r instanceof Of?Ul(r.schema):r instanceof Ku?Ul(r.innerType()):r instanceof Lf?[r.value]:r instanceof $f?r.options:r instanceof zf?$n.objectValues(r.enum):r instanceof qf?Ul(r._def.innerType):r instanceof jf?[void 0]:r instanceof kf?[null]:r instanceof Hu?[void 0,...Ul(r.unwrap())]:r instanceof q0?[null,...Ul(r.unwrap())]:r instanceof gb||r instanceof Vf?Ul(r.unwrap()):r instanceof Uf?Ul(r._def.innerType):[],kA=class r extends Sn{_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==vr.object)return gr(a,{code:nr.invalid_type,expected:vr.object,received:a.parsedType}),rn;let s=this.discriminator,l=a.data[s],d=this.optionsMap.get(l);return d?a.common.async?d._parseAsync({data:a.data,path:a.path,parent:a}):d._parseSync({data:a.data,path:a.path,parent:a}):(gr(a,{code:nr.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),rn)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,a,s){let l=new Map;for(let d of a){let x=Ul(d.shape[e]);if(!x.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let f of x){if(l.has(f))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(f)}`);l.set(f,d)}}return new r({typeName:un.ZodDiscriminatedUnion,discriminator:e,options:a,optionsMap:l,...Fn(s)})}};Mf=class extends Sn{_parse(e){let{status:a,ctx:s}=this._processInputParams(e),l=(d,x)=>{if(IA(d)||IA(x))return rn;let f=xq(d.value,x.value);return f.valid?((jA(d)||jA(x))&&a.dirty(),{status:a.value,value:f.data}):(gr(s,{code:nr.invalid_intersection_types}),rn)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([d,x])=>l(d,x)):l(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};Mf.create=(r,e,a)=>new Mf({left:r,right:e,typeName:un.ZodIntersection,...Fn(a)});z0=class r extends Sn{_parse(e){let{status:a,ctx:s}=this._processInputParams(e);if(s.parsedType!==vr.array)return gr(s,{code:nr.invalid_type,expected:vr.array,received:s.parsedType}),rn;if(s.data.length<this._def.items.length)return gr(s,{code:nr.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),rn;!this._def.rest&&s.data.length>this._def.items.length&&(gr(s,{code:nr.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),a.dirty());let d=[...s.data].map((x,f)=>{let m=this._def.items[f]||this._def.rest;return m?m._parse(new Wu(s,x,s.path,f)):null}).filter(x=>!!x);return s.common.async?Promise.all(d).then(x=>Ri.mergeArray(a,x)):Ri.mergeArray(a,d)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};z0.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new z0({items:r,typeName:un.ZodTuple,rest:null,...Fn(e)})};NA=class r extends Sn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:a,ctx:s}=this._processInputParams(e);if(s.parsedType!==vr.object)return gr(s,{code:nr.invalid_type,expected:vr.object,received:s.parsedType}),rn;let l=[],d=this._def.keyType,x=this._def.valueType;for(let f in s.data)l.push({key:d._parse(new Wu(s,f,s.path,f)),value:x._parse(new Wu(s,s.data[f],s.path,f)),alwaysSet:f in s.data});return s.common.async?Ri.mergeObjectAsync(a,l):Ri.mergeObjectSync(a,l)}get element(){return this._def.valueType}static create(e,a,s){return a instanceof Sn?new r({keyType:e,valueType:a,typeName:un.ZodRecord,...Fn(s)}):new r({keyType:Ap.create(),valueType:e,typeName:un.ZodRecord,...Fn(a)})}},km=class extends Sn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:a,ctx:s}=this._processInputParams(e);if(s.parsedType!==vr.map)return gr(s,{code:nr.invalid_type,expected:vr.map,received:s.parsedType}),rn;let l=this._def.keyType,d=this._def.valueType,x=[...s.data.entries()].map(([f,m],D)=>({key:l._parse(new Wu(s,f,s.path,[D,"key"])),value:d._parse(new Wu(s,m,s.path,[D,"value"]))}));if(s.common.async){let f=new Map;return Promise.resolve().then(async()=>{for(let m of x){let D=await m.key,b=await m.value;if(D.status==="aborted"||b.status==="aborted")return rn;(D.status==="dirty"||b.status==="dirty")&&a.dirty(),f.set(D.value,b.value)}return{status:a.value,value:f}})}else{let f=new Map;for(let m of x){let D=m.key,b=m.value;if(D.status==="aborted"||b.status==="aborted")return rn;(D.status==="dirty"||b.status==="dirty")&&a.dirty(),f.set(D.value,b.value)}return{status:a.value,value:f}}}};km.create=(r,e,a)=>new km({valueType:e,keyType:r,typeName:un.ZodMap,...Fn(a)});Nm=class r extends Sn{_parse(e){let{status:a,ctx:s}=this._processInputParams(e);if(s.parsedType!==vr.set)return gr(s,{code:nr.invalid_type,expected:vr.set,received:s.parsedType}),rn;let l=this._def;l.minSize!==null&&s.data.size<l.minSize.value&&(gr(s,{code:nr.too_small,minimum:l.minSize.value,type:"set",inclusive:!0,exact:!1,message:l.minSize.message}),a.dirty()),l.maxSize!==null&&s.data.size>l.maxSize.value&&(gr(s,{code:nr.too_big,maximum:l.maxSize.value,type:"set",inclusive:!0,exact:!1,message:l.maxSize.message}),a.dirty());let d=this._def.valueType;function x(m){let D=new Set;for(let b of m){if(b.status==="aborted")return rn;b.status==="dirty"&&a.dirty(),D.add(b.value)}return{status:a.value,value:D}}let f=[...s.data.values()].map((m,D)=>d._parse(new Wu(s,m,s.path,D)));return s.common.async?Promise.all(f).then(m=>x(m)):x(f)}min(e,a){return new r({...this._def,minSize:{value:e,message:Nr.toString(a)}})}max(e,a){return new r({...this._def,maxSize:{value:e,message:Nr.toString(a)}})}size(e,a){return this.min(e,a).max(e,a)}nonempty(e){return this.min(1,e)}};Nm.create=(r,e)=>new Nm({valueType:r,minSize:null,maxSize:null,typeName:un.ZodSet,...Fn(e)});MA=class r extends Sn{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==vr.function)return gr(a,{code:nr.invalid_type,expected:vr.function,received:a.parsedType}),rn;function s(f,m){return mb({data:f,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,wm(),ql].filter(D=>!!D),issueData:{code:nr.invalid_arguments,argumentsError:m}})}function l(f,m){return mb({data:f,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,wm(),ql].filter(D=>!!D),issueData:{code:nr.invalid_return_type,returnTypeError:m}})}let d={errorMap:a.common.contextualErrorMap},x=a.data;if(this._def.returns instanceof Sp){let f=this;return Wi(async function(...m){let D=new Wo([]),b=await f._def.args.parseAsync(m,d).catch(B=>{throw D.addIssue(s(m,B)),D}),E=await Reflect.apply(x,this,b);return await f._def.returns._def.type.parseAsync(E,d).catch(B=>{throw D.addIssue(l(E,B)),D})})}else{let f=this;return Wi(function(...m){let D=f._def.args.safeParse(m,d);if(!D.success)throw new Wo([s(m,D.error)]);let b=Reflect.apply(x,this,D.data),E=f._def.returns.safeParse(b,d);if(!E.success)throw new Wo([l(b,E.error)]);return E.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:z0.create(e).rest(Vl.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,a,s){return new r({args:e||z0.create([]).rest(Vl.create()),returns:a||Vl.create(),typeName:un.ZodFunction,...Fn(s)})}},Of=class extends Sn{get schema(){return this._def.getter()}_parse(e){let{ctx:a}=this._processInputParams(e);return this._def.getter()._parse({data:a.data,path:a.path,parent:a})}};Of.create=(r,e)=>new Of({getter:r,typeName:un.ZodLazy,...Fn(e)});Lf=class extends Sn{_parse(e){if(e.data!==this._def.value){let a=this._getOrReturnCtx(e);return gr(a,{received:a.data,code:nr.invalid_literal,expected:this._def.value}),rn}return{status:"valid",value:e.data}}get value(){return this._def.value}};Lf.create=(r,e)=>new Lf({value:r,typeName:un.ZodLiteral,...Fn(e)});$f=class r extends Sn{_parse(e){if(typeof e.data!="string"){let a=this._getOrReturnCtx(e),s=this._def.values;return gr(a,{expected:$n.joinValues(s),received:a.parsedType,code:nr.invalid_type}),rn}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let a=this._getOrReturnCtx(e),s=this._def.values;return gr(a,{received:a.data,code:nr.invalid_enum_value,options:s}),rn}return Wi(e.data)}get options(){return this._def.values}get enum(){let e={};for(let a of this._def.values)e[a]=a;return e}get Values(){let e={};for(let a of this._def.values)e[a]=a;return e}get Enum(){let e={};for(let a of this._def.values)e[a]=a;return e}extract(e,a=this._def){return r.create(e,{...this._def,...a})}exclude(e,a=this._def){return r.create(this.options.filter(s=>!e.includes(s)),{...this._def,...a})}};$f.create=X2e;zf=class extends Sn{_parse(e){let a=$n.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==vr.string&&s.parsedType!==vr.number){let l=$n.objectValues(a);return gr(s,{expected:$n.joinValues(l),received:s.parsedType,code:nr.invalid_type}),rn}if(this._cache||(this._cache=new Set($n.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let l=$n.objectValues(a);return gr(s,{received:s.data,code:nr.invalid_enum_value,options:l}),rn}return Wi(e.data)}get enum(){return this._def.values}};zf.create=(r,e)=>new zf({values:r,typeName:un.ZodNativeEnum,...Fn(e)});Sp=class extends Sn{unwrap(){return this._def.type}_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==vr.promise&&a.common.async===!1)return gr(a,{code:nr.invalid_type,expected:vr.promise,received:a.parsedType}),rn;let s=a.parsedType===vr.promise?a.data:Promise.resolve(a.data);return Wi(s.then(l=>this._def.type.parseAsync(l,{path:a.path,errorMap:a.common.contextualErrorMap})))}};Sp.create=(r,e)=>new Sp({type:r,typeName:un.ZodPromise,...Fn(e)});Ku=class extends Sn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===un.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:a,ctx:s}=this._processInputParams(e),l=this._def.effect||null,d={addIssue:x=>{gr(s,x),x.fatal?a.abort():a.dirty()},get path(){return s.path}};if(d.addIssue=d.addIssue.bind(d),l.type==="preprocess"){let x=l.transform(s.data,d);if(s.common.async)return Promise.resolve(x).then(async f=>{if(a.value==="aborted")return rn;let m=await this._def.schema._parseAsync({data:f,path:s.path,parent:s});return m.status==="aborted"?rn:m.status==="dirty"?Bf(m.value):a.value==="dirty"?Bf(m.value):m});{if(a.value==="aborted")return rn;let f=this._def.schema._parseSync({data:x,path:s.path,parent:s});return f.status==="aborted"?rn:f.status==="dirty"?Bf(f.value):a.value==="dirty"?Bf(f.value):f}}if(l.type==="refinement"){let x=f=>{let m=l.refinement(f,d);if(s.common.async)return Promise.resolve(m);if(m instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return f};if(s.common.async===!1){let f=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return f.status==="aborted"?rn:(f.status==="dirty"&&a.dirty(),x(f.value),{status:a.value,value:f.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(f=>f.status==="aborted"?rn:(f.status==="dirty"&&a.dirty(),x(f.value).then(()=>({status:a.value,value:f.value}))))}if(l.type==="transform")if(s.common.async===!1){let x=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!_p(x))return rn;let f=l.transform(x.value,d);if(f instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:a.value,value:f}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(x=>_p(x)?Promise.resolve(l.transform(x.value,d)).then(f=>({status:a.value,value:f})):rn);$n.assertNever(l)}};Ku.create=(r,e,a)=>new Ku({schema:r,typeName:un.ZodEffects,effect:e,...Fn(a)});Ku.createWithPreprocess=(r,e,a)=>new Ku({schema:e,effect:{type:"preprocess",transform:r},typeName:un.ZodEffects,...Fn(a)});Hu=class extends Sn{_parse(e){return this._getType(e)===vr.undefined?Wi(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Hu.create=(r,e)=>new Hu({innerType:r,typeName:un.ZodOptional,...Fn(e)});q0=class extends Sn{_parse(e){return this._getType(e)===vr.null?Wi(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};q0.create=(r,e)=>new q0({innerType:r,typeName:un.ZodNullable,...Fn(e)});qf=class extends Sn{_parse(e){let{ctx:a}=this._processInputParams(e),s=a.data;return a.parsedType===vr.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:a.path,parent:a})}removeDefault(){return this._def.innerType}};qf.create=(r,e)=>new qf({innerType:r,typeName:un.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Fn(e)});Uf=class extends Sn{_parse(e){let{ctx:a}=this._processInputParams(e),s={...a,common:{...a.common,issues:[]}},l=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Tm(l)?l.then(d=>({status:"valid",value:d.status==="valid"?d.value:this._def.catchValue({get error(){return new Wo(s.common.issues)},input:s.data})})):{status:"valid",value:l.status==="valid"?l.value:this._def.catchValue({get error(){return new Wo(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};Uf.create=(r,e)=>new Uf({innerType:r,typeName:un.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Fn(e)});Mm=class extends Sn{_parse(e){if(this._getType(e)!==vr.nan){let s=this._getOrReturnCtx(e);return gr(s,{code:nr.invalid_type,expected:vr.nan,received:s.parsedType}),rn}return{status:"valid",value:e.data}}};Mm.create=r=>new Mm({typeName:un.ZodNaN,...Fn(r)});Svt=Symbol("zod_brand"),gb=class extends Sn{_parse(e){let{ctx:a}=this._processInputParams(e),s=a.data;return this._def.type._parse({data:s,path:a.path,parent:a})}unwrap(){return this._def.type}},Db=class r extends Sn{_parse(e){let{status:a,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let d=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return d.status==="aborted"?rn:d.status==="dirty"?(a.dirty(),Bf(d.value)):this._def.out._parseAsync({data:d.value,path:s.path,parent:s})})();{let l=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return l.status==="aborted"?rn:l.status==="dirty"?(a.dirty(),{status:"dirty",value:l.value}):this._def.out._parseSync({data:l.value,path:s.path,parent:s})}}static create(e,a){return new r({in:e,out:a,typeName:un.ZodPipeline})}},Vf=class extends Sn{_parse(e){let a=this._def.innerType._parse(e),s=l=>(_p(l)&&(l.value=Object.freeze(l.value)),l);return Tm(a)?a.then(l=>s(l)):s(a)}unwrap(){return this._def.innerType}};Vf.create=(r,e)=>new Vf({innerType:r,typeName:un.ZodReadonly,...Fn(e)});Bvt={object:Ko.lazycreate};(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(un||(un={}));wvt=(r,e={message:`Input not instance of ${r.name}`})=>Y2e(a=>a instanceof r,e),H2e=Ap.create,W2e=wf.create,Tvt=Mm.create,Pvt=Tf.create,K2e=Pf.create,Ivt=If.create,jvt=Im.create,kvt=jf.create,Nvt=kf.create,Mvt=Rp.create,Ovt=Vl.create,Lvt=Nc.create,$vt=jm.create,zvt=Gl.create,qvt=Ko.create,Uvt=Ko.strictCreate,Vvt=Nf.create,Gvt=kA.create,Xvt=Mf.create,Yvt=z0.create,Hvt=NA.create,Wvt=km.create,Kvt=Nm.create,Jvt=MA.create,Zvt=Of.create,Qvt=Lf.create,eCt=$f.create,tCt=zf.create,rCt=Sp.create,nCt=Ku.create,aCt=Hu.create,sCt=q0.create,iCt=Ku.createWithPreprocess,oCt=Db.create,uCt=()=>H2e().optional(),cCt=()=>W2e().optional(),lCt=()=>K2e().optional(),dCt={string:(r=>Ap.create({...r,coerce:!0})),number:(r=>wf.create({...r,coerce:!0})),boolean:(r=>Pf.create({...r,coerce:!0})),bigint:(r=>Tf.create({...r,coerce:!0})),date:(r=>If.create({...r,coerce:!0}))},pCt=rn});var v={};Am(v,{BRAND:()=>Svt,DIRTY:()=>Bf,EMPTY_PATH:()=>ivt,INVALID:()=>rn,NEVER:()=>pCt,OK:()=>Wi,ParseStatus:()=>Ri,Schema:()=>Sn,ZodAny:()=>Rp,ZodArray:()=>Gl,ZodBigInt:()=>Tf,ZodBoolean:()=>Pf,ZodBranded:()=>gb,ZodCatch:()=>Uf,ZodDate:()=>If,ZodDefault:()=>qf,ZodDiscriminatedUnion:()=>kA,ZodEffects:()=>Ku,ZodEnum:()=>$f,ZodError:()=>Wo,ZodFirstPartyTypeKind:()=>un,ZodFunction:()=>MA,ZodIntersection:()=>Mf,ZodIssueCode:()=>nr,ZodLazy:()=>Of,ZodLiteral:()=>Lf,ZodMap:()=>km,ZodNaN:()=>Mm,ZodNativeEnum:()=>zf,ZodNever:()=>Nc,ZodNull:()=>kf,ZodNullable:()=>q0,ZodNumber:()=>wf,ZodObject:()=>Ko,ZodOptional:()=>Hu,ZodParsedType:()=>vr,ZodPipeline:()=>Db,ZodPromise:()=>Sp,ZodReadonly:()=>Vf,ZodRecord:()=>NA,ZodSchema:()=>Sn,ZodSet:()=>Nm,ZodString:()=>Ap,ZodSymbol:()=>Im,ZodTransformer:()=>Ku,ZodTuple:()=>z0,ZodType:()=>Sn,ZodUndefined:()=>jf,ZodUnion:()=>Nf,ZodUnknown:()=>Vl,ZodVoid:()=>jm,addIssueToContext:()=>gr,any:()=>Mvt,array:()=>zvt,bigint:()=>Pvt,boolean:()=>K2e,coerce:()=>dCt,custom:()=>Y2e,date:()=>Ivt,datetimeRegex:()=>G2e,defaultErrorMap:()=>ql,discriminatedUnion:()=>Gvt,effect:()=>nCt,enum:()=>eCt,function:()=>Jvt,getErrorMap:()=>wm,getParsedType:()=>$0,instanceof:()=>wvt,intersection:()=>Xvt,isAborted:()=>IA,isAsync:()=>Tm,isDirty:()=>jA,isValid:()=>_p,late:()=>Bvt,lazy:()=>Zvt,literal:()=>Qvt,makeIssue:()=>mb,map:()=>Wvt,nan:()=>Tvt,nativeEnum:()=>tCt,never:()=>Lvt,null:()=>Nvt,nullable:()=>sCt,number:()=>W2e,object:()=>qvt,objectUtil:()=>cq,oboolean:()=>lCt,onumber:()=>cCt,optional:()=>aCt,ostring:()=>uCt,pipeline:()=>oCt,preprocess:()=>iCt,promise:()=>rCt,quotelessJson:()=>nvt,record:()=>Hvt,set:()=>Kvt,setErrorMap:()=>svt,strictObject:()=>Uvt,string:()=>H2e,symbol:()=>jvt,transformer:()=>nCt,tuple:()=>Yvt,undefined:()=>kvt,union:()=>Vvt,unknown:()=>Ovt,util:()=>$n,void:()=>$vt});var fq=Sr(()=>{"use strict";PA();dq();L2e();hb();J2e();TA()});var Ue=Sr(()=>{"use strict";fq();fq()});var Hf={};Am(Hf,{all_layers:()=>$m,any_circuit_element:()=>zFe,any_soup_element:()=>Yf,any_source_component:()=>obe,battery_capacity:()=>tbe,brep_shape:()=>$be,cad_component:()=>NFe,capacitance:()=>Xl,circuit_json_footprint_load_error:()=>VA,current:()=>fCt,distance:()=>Be,external_footprint_load_error:()=>yb,frequency:()=>Oc,getZodPrefixedIdWithDefault:()=>Cr,inductance:()=>OA,layer_ref:()=>dn,layer_string:()=>mq,length:()=>pe,ninePointAnchor:()=>LA,pcb_autorouting_error:()=>AFe,pcb_board:()=>oFe,pcb_breakout_point:()=>RFe,pcb_component:()=>qbe,pcb_component_outside_board_error:()=>kFe,pcb_copper_pour:()=>jFe,pcb_copper_pour_brep:()=>PFe,pcb_copper_pour_polygon:()=>IFe,pcb_copper_pour_rect:()=>TFe,pcb_cutout:()=>vFe,pcb_cutout_circle:()=>FFe,pcb_cutout_polygon:()=>EFe,pcb_cutout_rect:()=>bFe,pcb_fabrication_note_path:()=>gFe,pcb_fabrication_note_text:()=>mFe,pcb_footprint_overlap_error:()=>DFe,pcb_ground_plane:()=>SFe,pcb_ground_plane_region:()=>BFe,pcb_group:()=>_Fe,pcb_hole:()=>Gbe,pcb_hole_circle_or_square_shape:()=>ECt,pcb_hole_oval_shape:()=>vCt,pcb_keepout:()=>yFe,pcb_manual_edit_conflict_warning:()=>GA,pcb_missing_footprint_error:()=>CFe,pcb_net:()=>sFe,pcb_placement_error:()=>uFe,pcb_plated_hole:()=>Xbe,pcb_port:()=>Ybe,pcb_port_not_connected_error:()=>aFe,pcb_port_not_matched_error:()=>nFe,pcb_route_hint:()=>zbe,pcb_route_hints:()=>FCt,pcb_silkscreen_circle:()=>fFe,pcb_silkscreen_line:()=>lFe,pcb_silkscreen_oval:()=>hFe,pcb_silkscreen_path:()=>dFe,pcb_silkscreen_rect:()=>xFe,pcb_silkscreen_text:()=>pFe,pcb_smtpad:()=>Wbe,pcb_smtpad_pill:()=>Hbe,pcb_solder_paste:()=>Kbe,pcb_text:()=>Jbe,pcb_thermal_spoke:()=>wFe,pcb_trace:()=>eFe,pcb_trace_error:()=>tFe,pcb_trace_hint:()=>cFe,pcb_trace_missing_error:()=>rFe,pcb_trace_route_point:()=>UA,pcb_trace_route_point_via:()=>Qbe,pcb_trace_route_point_wire:()=>Zbe,pcb_via:()=>iFe,point:()=>Hr,point3:()=>Gf,point_with_bulge:()=>Lbe,port_arrangement:()=>ybe,position:()=>mCt,position3:()=>gCt,resistance:()=>Bp,ring:()=>gq,rotation:()=>Gn,route_hint_point:()=>bo,schematic_arc:()=>Cbe,schematic_box:()=>fbe,schematic_circle:()=>vbe,schematic_component:()=>bbe,schematic_component_port_arrangement_by_sides:()=>Dbe,schematic_component_port_arrangement_by_size:()=>gbe,schematic_debug_line:()=>Pbe,schematic_debug_object:()=>jbe,schematic_debug_object_base:()=>zA,schematic_debug_point:()=>Ibe,schematic_debug_rect:()=>Tbe,schematic_error:()=>Bbe,schematic_group:()=>Nbe,schematic_layout_error:()=>wbe,schematic_line:()=>Fbe,schematic_manual_edit_conflict_warning:()=>qA,schematic_net_label:()=>Sbe,schematic_path:()=>hbe,schematic_pin_styles:()=>mbe,schematic_port:()=>Rbe,schematic_rect:()=>Ebe,schematic_table:()=>Mbe,schematic_table_cell:()=>Obe,schematic_text:()=>Abe,schematic_trace:()=>_be,schematic_voltage_probe:()=>kbe,simulation_ac_voltage_source:()=>LFe,simulation_dc_voltage_source:()=>OFe,simulation_voltage_source:()=>$Fe,size:()=>Dq,source_component_base:()=>Is,source_failed_to_create_component_error:()=>sbe,source_group:()=>lbe,source_manually_placed_via:()=>xbe,source_missing_property_error:()=>abe,source_net:()=>dbe,source_pcb_ground_plane:()=>pbe,source_pin_missing_trace_warning:()=>Mq,source_port:()=>ube,source_project_metadata:()=>kq,source_property_ignored_warning:()=>ibe,source_simple_battery:()=>Cq,source_simple_capacitor:()=>yq,source_simple_chip:()=>Eq,source_simple_crystal:()=>nbe,source_simple_diode:()=>$A,source_simple_ground:()=>rbe,source_simple_inductor:()=>_q,source_simple_led:()=>Fq,source_simple_mosfet:()=>Iq,source_simple_pin_header:()=>Sq,source_simple_pinout:()=>Bq,source_simple_potentiometer:()=>Rq,source_simple_power_source:()=>vq,source_simple_push_button:()=>Aq,source_simple_resistor:()=>bq,source_simple_resonator:()=>wq,source_simple_switch:()=>jq,source_simple_test_point:()=>Pq,source_simple_transistor:()=>Tq,source_trace:()=>cbe,source_trace_not_connected_error:()=>Nq,supplier_name:()=>Lm,time:()=>hCt,visible_layer:()=>zm,voltage:()=>Us,wave_shape:()=>MFe});function xCt(r){for(let[e,a]of Object.entries(ebe))if(r in a.variants)return{baseUnit:a.baseUnit,conversionFactor:a.variants[r]};return{baseUnit:r,conversionFactor:1}}var ebe,hq,Q2e,Mc,Bp,Xl,OA,Us,pe,Oc,Be,fCt,hCt,Gn,tbe,Pt,Xf,Hr,mCt,Gf,gCt,Dq,DCt,Cr,LA,Lm,Is,yq,bq,$A,Fq,rbe,Eq,vq,yCt,Cq,_q,Aq,Rq,nbe,Sq,Bq,wq,Tq,Pq,Iq,jq,kq,abe,sbe,Nq,ibe,Mq,obe,ube,cbe,lbe,dbe,pbe,$m,mq,dn,zm,xbe,fbe,hbe,mbe,gbe,Dbe,ybe,bbe,Fbe,Ebe,vbe,Cbe,_be,bCt,Abe,Rbe,Sbe,Bbe,wbe,zA,Tbe,Pbe,Ibe,jbe,kbe,qA,Nbe,Mbe,Obe,Lbe,gq,$be,zbe,FCt,bo,qbe,Ube,ECt,Vbe,vCt,Gbe,CCt,_Ct,ACt,RCt,SCt,Xbe,Ybe,BCt,wCt,TCt,Hbe,PCt,ICt,Wbe,jCt,kCt,NCt,MCt,OCt,Kbe,Jbe,Zbe,Qbe,UA,eFe,tFe,rFe,nFe,aFe,sFe,iFe,oFe,uFe,cFe,lFe,dFe,pFe,xFe,fFe,hFe,mFe,gFe,DFe,yFe,Oq,bFe,FFe,EFe,vFe,CFe,yb,VA,_Fe,AFe,GA,RFe,SFe,BFe,wFe,Lq,TFe,PFe,IFe,jFe,kFe,NFe,MFe,LCt,OFe,LFe,$Fe,zFe,Yf,qt=Sr(()=>{"use strict";Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();ebe={Hz:{baseUnit:"Hz",variants:{MHz:1e6,kHz:1e3,Hz:1}},g:{baseUnit:"g",variants:{kg:1e3,g:1}},\u03A9:{baseUnit:"\u03A9",variants:{m\u03A9:.001,\u03A9:1,k\u03A9:1e3,K\u03A9:1e3,kohm:1e3,M\u03A9:1e6,G\u03A9:1e9,T\u03A9:1e12}},V:{baseUnit:"V",variants:{mV:.001,V:1,kV:1e3,KV:1e3,MV:1e6,GV:1e9,TV:1e12}},A:{baseUnit:"A",variants:{\u00B5A:1e-6,mA:.001,ma:.001,A:1,kA:1e3,MA:1e6}},F:{baseUnit:"F",variants:{pF:1e-12,nF:1e-9,\u00B5F:1e-6,uF:1e-6,mF:.001,F:1}},ml:{baseUnit:"ml",variants:{ml:1,mL:1,l:1e3,L:1e3}},deg:{baseUnit:"deg",variants:{rad:180/Math.PI}},ms:{baseUnit:"ms",variants:{s:1e3}},mm:{baseUnit:"mm",variants:{nm:1e-6,\u00B5m:.001,um:.001,mm:1,cm:10,dm:100,m:1e3,km:1e6,in:25.4,ft:304.8,IN:25.4,FT:304.8,yd:914.4,mi:1609344,mil:.0254}}},hq=new Set;for(let[r,e]of Object.entries(ebe)){hq.add(r);for(let a of Object.keys(e.variants))hq.add(a)}Q2e={tera:1e12,T:1e12,giga:1e9,G:1e9,mega:1e6,M:1e6,kilo:1e3,k:1e3,deci:.1,d:.1,centi:.01,c:.01,milli:.001,m:.001,micro:1e-6,u:1e-6,\u00B5:1e-6,nano:1e-9,n:1e-9,pico:1e-12,p:1e-12},Mc=r=>{if(typeof r>"u")return{parsedUnit:null,unitOfValue:null,value:null};if(typeof r=="string"&&r.match(/^-?[\d\.]+$/))return{value:Number.parseFloat(r),parsedUnit:null,unitOfValue:null};if(typeof r=="number")return{value:r,parsedUnit:null,unitOfValue:null};if(typeof r=="object"&&"x"in r&&"y"in r){let{parsedUnit:f,unitOfValue:m}=Mc(r.x);return{parsedUnit:f,unitOfValue:m,value:{x:Mc(r.x).value,y:Mc(r.y).value}}}let a=r.toString().split("").reverse().join("").match(/[^\d\s]+/)?.[0];if(!a)throw new Error(`Could not determine unit: "${r}"`);let s=a.split("").reverse().join(""),l=r.slice(0,-s.length);if(s in Q2e&&!hq.has(s)){let f=Q2e[s];return{parsedUnit:null,unitOfValue:null,value:Number.parseFloat(l)*f}}let{baseUnit:d,conversionFactor:x}=xCt(s);return{parsedUnit:s,unitOfValue:d,value:x*Number.parseFloat(l)}},Bp=v.string().or(v.number()).transform(r=>Mc(r).value),Xl=v.string().or(v.number()).transform(r=>Mc(r).value).transform(r=>Number.parseFloat(r.toPrecision(12))),OA=v.string().or(v.number()).transform(r=>Mc(r).value),Us=v.string().or(v.number()).transform(r=>Mc(r).value),pe=v.string().or(v.number()).transform(r=>Mc(r).value),Oc=v.string().or(v.number()).transform(r=>Mc(r).value),Be=pe,fCt=v.string().or(v.number()).transform(r=>Mc(r).value),hCt=v.string().or(v.number()).transform(r=>Mc(r).value),Gn=v.string().or(v.number()).transform(r=>typeof r=="number"?r:r.endsWith("deg")?Number.parseFloat(r.split("deg")[0]):r.endsWith("rad")?Number.parseFloat(r.split("rad")[0])*180/Math.PI:Number.parseFloat(r)),tbe=v.number().or(v.string().endsWith("mAh")).transform(r=>{if(typeof r=="string"){let e=r.replace("mAh",""),a=Number.parseFloat(e);if(Number.isNaN(a))throw new Error("Invalid capacity");return a}return r}).describe("Battery capacity in mAh"),Pt=r=>{};Pt("extra props b");Pt("missing props b");Pt(!0);Pt("mismatched prop types: a");Xf=r=>{};Xf(!0);Xf('T1 has extra: "c", T2 has extra: "d"');Xf('T1 has extra: "c"');Xf('T2 has extra: "c"');Xf('T1 has extra: "d", T2 has extra: "c"');Xf(!0);Hr=v.object({x:Be,y:Be}),mCt=Hr;Pt(!0);Pt(!0);Gf=v.object({x:Be,y:Be,z:Be}),gCt=Gf;Pt(!0);Dq=v.object({width:v.number(),height:v.number()});Pt(!0);DCt=r=>{let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";return Array.from({length:r},()=>e[Math.floor(Math.random()*e.length)]).join("")},Cr=r=>v.string().optional().default(()=>`${r}_${DCt(10)}`),LA=v.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]);Pt(!0);Lm=v.enum(["jlcpcb","macrofab","pcbway","digikey","mouser","lcsc"]);Pt(!0);Is=v.object({type:v.literal("source_component"),ftype:v.string().optional(),source_component_id:v.string(),name:v.string(),manufacturer_part_number:v.string().optional(),supplier_part_numbers:v.record(Lm,v.array(v.string())).optional(),display_value:v.string().optional(),are_pins_interchangeable:v.boolean().optional(),internally_connected_source_port_ids:v.array(v.array(v.string())).optional(),source_group_id:v.string().optional(),subcircuit_id:v.string().optional()});Pt(!0);yq=Is.extend({ftype:v.literal("simple_capacitor"),capacitance:Xl,max_voltage_rating:Us.optional(),display_capacitance:v.string().optional(),max_decoupling_trace_length:Be.optional()});Pt(!0);bq=Is.extend({ftype:v.literal("simple_resistor"),resistance:Bp,display_resistance:v.string().optional()});Pt(!0);$A=Is.extend({ftype:v.literal("simple_diode")});Pt(!0);Fq=$A.extend({ftype:v.literal("simple_led"),color:v.string().optional(),wavelength:v.string().optional()});Pt(!0);rbe=Is.extend({ftype:v.literal("simple_ground")});Pt(!0);Eq=Is.extend({ftype:v.literal("simple_chip")});Pt(!0);vq=Is.extend({ftype:v.literal("simple_power_source"),voltage:Us});Pt(!0);yCt=Is.extend({ftype:v.literal("simple_fuse"),current_rating_amps:v.number().describe("Nominal current in amps the fuse is rated for"),voltage_rating_volts:v.number().describe("Voltage rating in volts, e.g. \xB15V would be 5")});Pt(!0);Cq=Is.extend({ftype:v.literal("simple_battery"),capacity:tbe});Pt(!0);_q=Is.extend({ftype:v.literal("simple_inductor"),inductance:OA,max_current_rating:v.number().optional()});Pt(!0);Aq=Is.extend({ftype:v.literal("simple_push_button")});Pt(!0);Rq=Is.extend({ftype:v.literal("simple_potentiometer"),max_resistance:Bp});Pt(!0);nbe=Is.extend({ftype:v.literal("simple_crystal"),frequency:v.number().describe("Frequency in Hz"),load_capacitance:v.number().optional().describe("Load capacitance in pF")});Pt(!0);Sq=Is.extend({ftype:v.literal("simple_pin_header"),pin_count:v.number(),gender:v.enum(["male","female"]).optional().default("male")});Pt(!0);Bq=Is.extend({ftype:v.literal("simple_pinout")});Pt(!0);wq=Is.extend({ftype:v.literal("simple_resonator"),load_capacitance:Xl,equivalent_series_resistance:Bp.optional(),frequency:Oc});Pt(!0);Tq=Is.extend({ftype:v.literal("simple_transistor"),transistor_type:v.enum(["npn","pnp"])});Pt(!0);Pq=Is.extend({ftype:v.literal("simple_test_point"),footprint_variant:v.enum(["pad","through_hole"]).optional(),pad_shape:v.enum(["rect","circle"]).optional(),pad_diameter:v.union([v.number(),v.string()]).optional(),hole_diameter:v.union([v.number(),v.string()]).optional(),width:v.union([v.number(),v.string()]).optional(),height:v.union([v.number(),v.string()]).optional()});Pt(!0);Iq=Is.extend({ftype:v.literal("simple_mosfet"),channel_type:v.enum(["n","p"]),mosfet_mode:v.enum(["enhancement","depletion"])});Pt(!0);jq=Is.extend({ftype:v.literal("simple_switch")});Pt(!0);kq=v.object({type:v.literal("source_project_metadata"),name:v.string().optional(),software_used_string:v.string().optional(),project_url:v.string().optional(),created_at:v.string().datetime().optional()});Pt(!0);abe=v.object({type:v.literal("source_missing_property_error"),source_missing_property_error_id:Cr("source_missing_property_error"),source_component_id:v.string(),property_name:v.string(),subcircuit_id:v.string().optional(),error_type:v.literal("source_missing_property_error").default("source_missing_property_error"),message:v.string()}).describe("The source code is missing a property");Pt(!0);sbe=v.object({type:v.literal("source_failed_to_create_component_error"),source_failed_to_create_component_error_id:Cr("source_failed_to_create_component_error"),error_type:v.literal("source_failed_to_create_component_error").default("source_failed_to_create_component_error"),component_name:v.string().optional(),subcircuit_id:v.string().optional(),parent_source_component_id:v.string().optional(),message:v.string(),pcb_center:v.object({x:v.number().optional(),y:v.number().optional()}).optional(),schematic_center:v.object({x:v.number().optional(),y:v.number().optional()}).optional()}).describe("Error emitted when a component fails to be constructed");Pt(!0);Nq=v.object({type:v.literal("source_trace_not_connected_error"),source_trace_not_connected_error_id:Cr("source_trace_not_connected_error"),error_type:v.literal("source_trace_not_connected_error").default("source_trace_not_connected_error"),message:v.string(),subcircuit_id:v.string().optional(),source_group_id:v.string().optional(),source_trace_id:v.string().optional(),connected_source_port_ids:v.array(v.string()).optional(),selectors_not_found:v.array(v.string()).optional()}).describe("Occurs when a source trace selector does not match any ports");Pt(!0);ibe=v.object({type:v.literal("source_property_ignored_warning"),source_property_ignored_warning_id:Cr("source_property_ignored_warning"),source_component_id:v.string(),property_name:v.string(),subcircuit_id:v.string().optional(),error_type:v.literal("source_property_ignored_warning").default("source_property_ignored_warning"),message:v.string()}).describe("The source property was ignored");Pt(!0);Mq=v.object({type:v.literal("source_pin_missing_trace_warning"),source_pin_missing_trace_warning_id:Cr("source_pin_missing_trace_warning"),warning_type:v.literal("source_pin_missing_trace_warning").default("source_pin_missing_trace_warning"),message:v.string(),source_component_id:v.string(),source_port_id:v.string(),subcircuit_id:v.string().optional()}).describe("Warning emitted when a source component pin is missing a trace connection");Pt(!0);obe=v.union([bq,yq,$A,Fq,rbe,Eq,vq,Cq,_q,Aq,Rq,nbe,Sq,Bq,wq,jq,Tq,Pq,Iq,yCt,kq,abe,sbe,Nq,ibe,Mq]);Pt(!0);ube=v.object({type:v.literal("source_port"),pin_number:v.number().optional(),port_hints:v.array(v.string()).optional(),name:v.string(),source_port_id:v.string(),source_component_id:v.string(),subcircuit_id:v.string().optional(),subcircuit_connectivity_map_key:v.string().optional()});Pt(!0);cbe=v.object({type:v.literal("source_trace"),source_trace_id:v.string(),connected_source_port_ids:v.array(v.string()),connected_source_net_ids:v.array(v.string()),subcircuit_id:v.string().optional(),subcircuit_connectivity_map_key:v.string().optional(),max_length:v.number().optional(),min_trace_thickness:v.number().optional(),display_name:v.string().optional()});Pt(!0);lbe=v.object({type:v.literal("source_group"),source_group_id:v.string(),subcircuit_id:v.string().optional(),parent_subcircuit_id:v.string().optional(),parent_source_group_id:v.string().optional(),is_subcircuit:v.boolean().optional(),show_as_schematic_box:v.boolean().optional(),name:v.string().optional()});Pt(!0);dbe=v.object({type:v.literal("source_net"),source_net_id:v.string(),name:v.string(),member_source_group_ids:v.array(v.string()),is_power:v.boolean().optional(),is_ground:v.boolean().optional(),is_digital_signal:v.boolean().optional(),is_analog_signal:v.boolean().optional(),is_positive_voltage_source:v.boolean().optional(),trace_width:v.number().optional(),subcircuit_id:v.string().optional(),subcircuit_connectivity_map_key:v.string().optional()});Pt(!0);pbe=v.object({type:v.literal("source_pcb_ground_plane"),source_pcb_ground_plane_id:v.string(),source_group_id:v.string(),source_net_id:v.string(),subcircuit_id:v.string().optional()}).describe("Defines a ground plane in the source domain");Pt(!0);$m=["top","bottom","inner1","inner2","inner3","inner4","inner5","inner6"],mq=v.enum($m),dn=mq.or(v.object({name:mq})).transform(r=>typeof r=="string"?r:r.name);Pt(!0);zm=v.enum(["top","bottom"]),xbe=v.object({type:v.literal("source_manually_placed_via"),source_manually_placed_via_id:v.string(),source_group_id:v.string(),source_net_id:v.string(),subcircuit_id:v.string().optional(),source_trace_id:v.string().optional()}).describe("Defines a via that is manually placed in the source domain");Pt(!0);fbe=v.object({type:v.literal("schematic_box"),schematic_component_id:v.string().optional(),width:Be,height:Be,is_dashed:v.boolean().default(!1),x:Be,y:Be,subcircuit_id:v.string().optional()}).describe("Draws a box on the schematic");Pt(!0);hbe=v.object({type:v.literal("schematic_path"),schematic_component_id:v.string(),fill_color:v.enum(["red","blue"]).optional(),is_filled:v.boolean().optional(),points:v.array(Hr),subcircuit_id:v.string().optional()});Pt(!0);mbe=v.record(v.object({left_margin:pe.optional(),right_margin:pe.optional(),top_margin:pe.optional(),bottom_margin:pe.optional()})),gbe=v.object({left_size:v.number(),right_size:v.number(),top_size:v.number().optional(),bottom_size:v.number().optional()});Pt(!0);Dbe=v.object({left_side:v.object({pins:v.array(v.number()),direction:v.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),right_side:v.object({pins:v.array(v.number()),direction:v.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),top_side:v.object({pins:v.array(v.number()),direction:v.enum(["left-to-right","right-to-left"]).optional()}).optional(),bottom_side:v.object({pins:v.array(v.number()),direction:v.enum(["left-to-right","right-to-left"]).optional()}).optional()});Pt(!0);ybe=v.union([gbe,Dbe]),bbe=v.object({type:v.literal("schematic_component"),size:Dq,center:Hr,source_component_id:v.string().optional(),schematic_component_id:v.string(),pin_spacing:pe.optional(),pin_styles:mbe.optional(),box_width:pe.optional(),symbol_name:v.string().optional(),port_arrangement:ybe.optional(),port_labels:v.record(v.string()).optional(),symbol_display_value:v.string().optional(),subcircuit_id:v.string().optional(),schematic_group_id:v.string().optional(),is_schematic_group:v.boolean().optional(),source_group_id:v.string().optional(),is_box_with_pins:v.boolean().optional().default(!0)});Pt(!0);Fbe=v.object({type:v.literal("schematic_line"),schematic_line_id:Cr("schematic_line"),schematic_component_id:v.string(),x1:Be,y1:Be,x2:Be,y2:Be,stroke_width:Be.nullable().optional(),color:v.string().default("#000000"),is_dashed:v.boolean().default(!1),subcircuit_id:v.string().optional()}).describe("Draws a styled line on the schematic");Pt(!0);Ebe=v.object({type:v.literal("schematic_rect"),schematic_rect_id:Cr("schematic_rect"),schematic_component_id:v.string(),center:Hr,width:Be,height:Be,rotation:Gn.default(0),stroke_width:Be.nullable().optional(),color:v.string().default("#000000"),is_filled:v.boolean().default(!1),fill_color:v.string().optional(),is_dashed:v.boolean().default(!1),subcircuit_id:v.string().optional()}).describe("Draws a styled rectangle on the schematic");Pt(!0);vbe=v.object({type:v.literal("schematic_circle"),schematic_circle_id:Cr("schematic_circle"),schematic_component_id:v.string(),center:Hr,radius:Be,stroke_width:Be.nullable().optional(),color:v.string().default("#000000"),is_filled:v.boolean().default(!1),fill_color:v.string().optional(),is_dashed:v.boolean().default(!1),subcircuit_id:v.string().optional()}).describe("Draws a styled circle on the schematic");Pt(!0);Cbe=v.object({type:v.literal("schematic_arc"),schematic_arc_id:Cr("schematic_arc"),schematic_component_id:v.string(),center:Hr,radius:Be,start_angle_degrees:Gn,end_angle_degrees:Gn,direction:v.enum(["clockwise","counterclockwise"]).default("counterclockwise"),stroke_width:Be.nullable().optional(),color:v.string().default("#000000"),is_dashed:v.boolean().default(!1),subcircuit_id:v.string().optional()}).describe("Draws a styled arc on the schematic");Pt(!0);_be=v.object({type:v.literal("schematic_trace"),schematic_trace_id:v.string(),source_trace_id:v.string().optional(),junctions:v.array(v.object({x:v.number(),y:v.number()})),edges:v.array(v.object({from:v.object({x:v.number(),y:v.number()}),to:v.object({x:v.number(),y:v.number()}),is_crossing:v.boolean().optional(),from_schematic_port_id:v.string().optional(),to_schematic_port_id:v.string().optional()})),subcircuit_id:v.string().optional(),subcircuit_connectivity_map_key:v.string().optional()});Pt(!0);bCt=v.enum(["center","left","right","top","bottom"]);Pt(!0);Abe=v.object({type:v.literal("schematic_text"),schematic_component_id:v.string().optional(),schematic_text_id:v.string(),text:v.string(),font_size:v.number().default(.18),position:v.object({x:Be,y:Be}),rotation:v.number().default(0),anchor:v.union([bCt.describe("legacy"),LA]).default("center"),color:v.string().default("#000000"),subcircuit_id:v.string().optional()});Pt(!0);Rbe=v.object({type:v.literal("schematic_port"),schematic_port_id:v.string(),source_port_id:v.string(),schematic_component_id:v.string().optional(),center:Hr,facing_direction:v.enum(["up","down","left","right"]).optional(),distance_from_component_edge:v.number().optional(),side_of_component:v.enum(["top","bottom","left","right"]).optional(),true_ccw_index:v.number().optional(),pin_number:v.number().optional(),display_pin_label:v.string().optional(),subcircuit_id:v.string().optional(),is_connected:v.boolean().optional(),has_input_arrow:v.boolean().optional(),has_output_arrow:v.boolean().optional()}).describe("Defines a port on a schematic component");Pt(!0);Sbe=v.object({type:v.literal("schematic_net_label"),schematic_net_label_id:Cr("schematic_net_label"),schematic_trace_id:v.string().optional(),source_trace_id:v.string().optional(),source_net_id:v.string(),center:Hr,anchor_position:Hr.optional(),anchor_side:v.enum(["top","bottom","left","right"]),text:v.string(),symbol_name:v.string().optional(),is_movable:v.boolean().optional(),subcircuit_id:v.string().optional()});Pt(!0);Bbe=v.object({type:v.literal("schematic_error"),schematic_error_id:v.string(),error_type:v.literal("schematic_port_not_found").default("schematic_port_not_found"),message:v.string(),subcircuit_id:v.string().optional()}).describe("Defines a schematic error on the schematic");Pt(!0);wbe=v.object({type:v.literal("schematic_layout_error"),schematic_layout_error_id:Cr("schematic_layout_error"),error_type:v.literal("schematic_layout_error").default("schematic_layout_error"),message:v.string(),source_group_id:v.string(),schematic_group_id:v.string(),subcircuit_id:v.string().optional()}).describe("Error emitted when schematic layout fails for a group");Pt(!0);zA=v.object({type:v.literal("schematic_debug_object"),label:v.string().optional(),subcircuit_id:v.string().optional()}),Tbe=zA.extend({shape:v.literal("rect"),center:Hr,size:Dq}),Pbe=zA.extend({shape:v.literal("line"),start:Hr,end:Hr}),Ibe=zA.extend({shape:v.literal("point"),center:Hr}),jbe=v.discriminatedUnion("shape",[Tbe,Pbe,Ibe]);Pt(!0);kbe=v.object({type:v.literal("schematic_voltage_probe"),schematic_voltage_probe_id:v.string(),position:Hr,schematic_trace_id:v.string(),voltage:Us.optional(),subcircuit_id:v.string().optional()}).describe("Defines a voltage probe measurement point on a schematic trace");Pt(!0);qA=v.object({type:v.literal("schematic_manual_edit_conflict_warning"),schematic_manual_edit_conflict_warning_id:Cr("schematic_manual_edit_conflict_warning"),warning_type:v.literal("schematic_manual_edit_conflict_warning").default("schematic_manual_edit_conflict_warning"),message:v.string(),schematic_component_id:v.string(),schematic_group_id:v.string().optional(),subcircuit_id:v.string().optional(),source_component_id:v.string()}).describe("Warning emitted when a component has both manual placement and explicit schX/schY coordinates");Pt(!0);Nbe=v.object({type:v.literal("schematic_group"),schematic_group_id:Cr("schematic_group"),source_group_id:v.string(),is_subcircuit:v.boolean().optional(),subcircuit_id:v.string().optional(),width:pe,height:pe,center:Hr,schematic_component_ids:v.array(v.string()),show_as_schematic_box:v.boolean().optional(),name:v.string().optional(),description:v.string().optional()}).describe("Defines a group of components on the schematic");Pt(!0);Mbe=v.object({type:v.literal("schematic_table"),schematic_table_id:Cr("schematic_table"),anchor_position:Hr,column_widths:v.array(Be),row_heights:v.array(Be),cell_padding:Be.optional(),border_width:Be.optional(),subcircuit_id:v.string().optional(),schematic_component_id:v.string().optional(),anchor:LA.optional()}).describe("Defines a table on the schematic");Pt(!0);Obe=v.object({type:v.literal("schematic_table_cell"),schematic_table_cell_id:Cr("schematic_table_cell"),schematic_table_id:v.string(),start_row_index:v.number(),end_row_index:v.number(),start_column_index:v.number(),end_column_index:v.number(),text:v.string().optional(),center:Hr,width:Be,height:Be,horizontal_align:v.enum(["left","center","right"]).optional(),vertical_align:v.enum(["top","middle","bottom"]).optional(),font_size:Be.optional(),subcircuit_id:v.string().optional()}).describe("Defines a cell within a schematic_table");Pt(!0);Lbe=v.object({x:Be,y:Be,bulge:v.number().optional()});Pt(!0);gq=v.object({vertices:v.array(Lbe)});Pt(!0);$be=v.object({outer_ring:gq,inner_rings:v.array(gq).default([])});Pt(!0);zbe=v.object({x:Be,y:Be,via:v.boolean().optional(),via_to_layer:dn.optional()}),FCt=v.array(zbe);Pt(!0);Pt(!0);bo=v.object({x:Be,y:Be,via:v.boolean().optional(),to_layer:dn.optional(),trace_width:Be.optional()});Pt(!0);qbe=v.object({type:v.literal("pcb_component"),pcb_component_id:Cr("pcb_component"),source_component_id:v.string(),center:Hr,layer:dn,rotation:Gn,width:pe,height:pe,subcircuit_id:v.string().optional(),pcb_group_id:v.string().optional()}).describe("Defines a component on the PCB");Pt(!0);Ube=v.object({type:v.literal("pcb_hole"),pcb_hole_id:Cr("pcb_hole"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),hole_shape:v.enum(["circle","square"]),hole_diameter:v.number(),x:Be,y:Be}),ECt=Ube.describe("Defines a circular or square hole on the PCB");Pt(!0);Vbe=v.object({type:v.literal("pcb_hole"),pcb_hole_id:Cr("pcb_hole"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),hole_shape:v.literal("oval"),hole_width:v.number(),hole_height:v.number(),x:Be,y:Be}),vCt=Vbe.describe("Defines an oval hole on the PCB");Pt(!0);Gbe=Ube.or(Vbe),CCt=v.object({type:v.literal("pcb_plated_hole"),shape:v.literal("circle"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),outer_diameter:v.number(),hole_diameter:v.number(),x:Be,y:Be,layers:v.array(dn),port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),pcb_plated_hole_id:Cr("pcb_plated_hole")}),_Ct=v.object({type:v.literal("pcb_plated_hole"),shape:v.enum(["oval","pill"]),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),outer_width:v.number(),outer_height:v.number(),hole_width:v.number(),hole_height:v.number(),x:Be,y:Be,ccw_rotation:Gn,layers:v.array(dn),port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),pcb_plated_hole_id:Cr("pcb_plated_hole")}),ACt=v.object({type:v.literal("pcb_plated_hole"),shape:v.literal("circular_hole_with_rect_pad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),hole_shape:v.literal("circle"),pad_shape:v.literal("rect"),hole_diameter:v.number(),rect_pad_width:v.number(),rect_pad_height:v.number(),rect_border_radius:v.number().optional(),hole_offset_x:Be.default(0),hole_offset_y:Be.default(0),x:Be,y:Be,layers:v.array(dn),port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),pcb_plated_hole_id:Cr("pcb_plated_hole")}),RCt=v.object({type:v.literal("pcb_plated_hole"),shape:v.literal("pill_hole_with_rect_pad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),hole_shape:v.literal("pill"),pad_shape:v.literal("rect"),hole_width:v.number(),hole_height:v.number(),rect_pad_width:v.number(),rect_pad_height:v.number(),rect_border_radius:v.number().optional(),hole_offset_x:Be.default(0),hole_offset_y:Be.default(0),x:Be,y:Be,layers:v.array(dn),port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),pcb_plated_hole_id:Cr("pcb_plated_hole")}),SCt=v.object({type:v.literal("pcb_plated_hole"),shape:v.literal("rotated_pill_hole_with_rect_pad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),hole_shape:v.literal("rotated_pill"),pad_shape:v.literal("rect"),hole_width:v.number(),hole_height:v.number(),hole_ccw_rotation:Gn,rect_pad_width:v.number(),rect_pad_height:v.number(),rect_border_radius:v.number().optional(),rect_ccw_rotation:Gn,hole_offset_x:Be.default(0),hole_offset_y:Be.default(0),x:Be,y:Be,layers:v.array(dn),port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),pcb_plated_hole_id:Cr("pcb_plated_hole")}),Xbe=v.union([CCt,_Ct,ACt,RCt,SCt]);Pt(!0);Pt(!0);Pt(!0);Pt(!0);Pt(!0);Ybe=v.object({type:v.literal("pcb_port"),pcb_port_id:Cr("pcb_port"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),source_port_id:v.string(),pcb_component_id:v.string(),x:Be,y:Be,layers:v.array(dn),is_board_pinout:v.boolean().optional()}).describe("Defines a port on the PCB");Pt(!0);BCt=v.object({type:v.literal("pcb_smtpad"),shape:v.literal("circle"),pcb_smtpad_id:Cr("pcb_smtpad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,radius:v.number(),layer:dn,port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),is_covered_with_solder_mask:v.boolean().optional()}),wCt=v.object({type:v.literal("pcb_smtpad"),shape:v.literal("rect"),pcb_smtpad_id:Cr("pcb_smtpad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),rect_border_radius:v.number().optional(),layer:dn,port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),is_covered_with_solder_mask:v.boolean().optional()}),TCt=v.object({type:v.literal("pcb_smtpad"),shape:v.literal("rotated_rect"),pcb_smtpad_id:Cr("pcb_smtpad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),rect_border_radius:v.number().optional(),ccw_rotation:Gn,layer:dn,port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),is_covered_with_solder_mask:v.boolean().optional()}),Hbe=v.object({type:v.literal("pcb_smtpad"),shape:v.literal("pill"),pcb_smtpad_id:Cr("pcb_smtpad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),radius:v.number(),layer:dn,port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),is_covered_with_solder_mask:v.boolean().optional()}),PCt=v.object({type:v.literal("pcb_smtpad"),shape:v.literal("rotated_pill"),pcb_smtpad_id:Cr("pcb_smtpad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),radius:v.number(),ccw_rotation:Gn,layer:dn,port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),is_covered_with_solder_mask:v.boolean().optional()}),ICt=v.object({type:v.literal("pcb_smtpad"),shape:v.literal("polygon"),pcb_smtpad_id:Cr("pcb_smtpad"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),points:v.array(Hr),layer:dn,port_hints:v.array(v.string()).optional(),pcb_component_id:v.string().optional(),pcb_port_id:v.string().optional(),is_covered_with_solder_mask:v.boolean().optional()}),Wbe=v.discriminatedUnion("shape",[BCt,wCt,TCt,PCt,Hbe,ICt]).describe("Defines an SMT pad on the PCB");Pt(!0);Pt(!0);Pt(!0);Pt(!0);Pt(!0);Pt(!0);jCt=v.object({type:v.literal("pcb_solder_paste"),shape:v.literal("circle"),pcb_solder_paste_id:Cr("pcb_solder_paste"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,radius:v.number(),layer:dn,pcb_component_id:v.string().optional(),pcb_smtpad_id:v.string().optional()}),kCt=v.object({type:v.literal("pcb_solder_paste"),shape:v.literal("rect"),pcb_solder_paste_id:Cr("pcb_solder_paste"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),layer:dn,pcb_component_id:v.string().optional(),pcb_smtpad_id:v.string().optional()}),NCt=v.object({type:v.literal("pcb_solder_paste"),shape:v.literal("pill"),pcb_solder_paste_id:Cr("pcb_solder_paste"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),radius:v.number(),layer:dn,pcb_component_id:v.string().optional(),pcb_smtpad_id:v.string().optional()}),MCt=v.object({type:v.literal("pcb_solder_paste"),shape:v.literal("rotated_rect"),pcb_solder_paste_id:Cr("pcb_solder_paste"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),ccw_rotation:Be,layer:dn,pcb_component_id:v.string().optional(),pcb_smtpad_id:v.string().optional()}),OCt=v.object({type:v.literal("pcb_solder_paste"),shape:v.literal("oval"),pcb_solder_paste_id:Cr("pcb_solder_paste"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,width:v.number(),height:v.number(),layer:dn,pcb_component_id:v.string().optional(),pcb_smtpad_id:v.string().optional()}),Kbe=v.union([jCt,kCt,NCt,MCt,OCt]).describe("Defines solderpaste on the PCB");Pt(!0);Pt(!0);Pt(!0);Pt(!0);Pt(!0);Jbe=v.object({type:v.literal("pcb_text"),pcb_text_id:Cr("pcb_text"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),text:v.string(),center:Hr,layer:dn,width:pe,height:pe,lines:v.number(),align:v.enum(["bottom-left"])}).describe("Defines text on the PCB");Pt(!0);Zbe=v.object({route_type:v.literal("wire"),x:Be,y:Be,width:Be,start_pcb_port_id:v.string().optional(),end_pcb_port_id:v.string().optional(),layer:dn}),Qbe=v.object({route_type:v.literal("via"),x:Be,y:Be,hole_diameter:Be.optional(),outer_diameter:Be.optional(),from_layer:v.string(),to_layer:v.string()}),UA=v.union([Zbe,Qbe]),eFe=v.object({type:v.literal("pcb_trace"),source_trace_id:v.string().optional(),pcb_component_id:v.string().optional(),pcb_trace_id:Cr("pcb_trace"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),route_thickness_mode:v.enum(["constant","interpolated"]).default("constant").optional(),route_order_index:v.number().optional(),should_round_corners:v.boolean().optional(),trace_length:v.number().optional(),rats_nest_color:v.string().optional(),route:v.array(UA)}).describe("Defines a trace on the PCB");Pt(!0);Pt(!0);tFe=v.object({type:v.literal("pcb_trace_error"),pcb_trace_error_id:Cr("pcb_trace_error"),error_type:v.literal("pcb_trace_error").default("pcb_trace_error"),message:v.string(),center:Hr.optional(),pcb_trace_id:v.string(),source_trace_id:v.string(),pcb_component_ids:v.array(v.string()),pcb_port_ids:v.array(v.string()),subcircuit_id:v.string().optional()}).describe("Defines a trace error on the PCB");Pt(!0);rFe=v.object({type:v.literal("pcb_trace_missing_error"),pcb_trace_missing_error_id:Cr("pcb_trace_missing_error"),error_type:v.literal("pcb_trace_missing_error").default("pcb_trace_missing_error"),message:v.string(),center:Hr.optional(),source_trace_id:v.string(),pcb_component_ids:v.array(v.string()),pcb_port_ids:v.array(v.string()),subcircuit_id:v.string().optional()}).describe("Defines an error when a source trace has no corresponding PCB trace");Pt(!0);nFe=v.object({type:v.literal("pcb_port_not_matched_error"),pcb_error_id:Cr("pcb_error"),error_type:v.literal("pcb_port_not_matched_error").default("pcb_port_not_matched_error"),message:v.string(),pcb_component_ids:v.array(v.string()),subcircuit_id:v.string().optional()}).describe("Defines a trace error on the PCB where a port is not matched");Pt(!0);aFe=v.object({type:v.literal("pcb_port_not_connected_error"),pcb_port_not_connected_error_id:Cr("pcb_port_not_connected_error"),error_type:v.literal("pcb_port_not_connected_error").default("pcb_port_not_connected_error"),message:v.string(),pcb_port_ids:v.array(v.string()),pcb_component_ids:v.array(v.string()),subcircuit_id:v.string().optional()}).describe("Defines an error when a pcb port is not connected to any trace");Pt(!0);sFe=v.object({type:v.literal("pcb_net"),pcb_net_id:Cr("pcb_net"),source_net_id:v.string().optional(),rats_nest_color:v.string().optional()}).describe("Defines a net on the PCB");Pt(!0);iFe=v.object({type:v.literal("pcb_via"),pcb_via_id:Cr("pcb_via"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),x:Be,y:Be,outer_diameter:Be.default("0.6mm"),hole_diameter:Be.default("0.25mm"),from_layer:dn.optional(),to_layer:dn.optional(),layers:v.array(dn),pcb_trace_id:v.string().optional()}).describe("Defines a via on the PCB");Pt(!0);oFe=v.object({type:v.literal("pcb_board"),pcb_board_id:Cr("pcb_board"),is_subcircuit:v.boolean().optional(),subcircuit_id:v.string().optional(),width:pe,height:pe,center:Hr,thickness:pe.optional().default(1.4),num_layers:v.number().optional().default(4),outline:v.array(Hr).optional(),material:v.enum(["fr4","fr1"]).default("fr4")}).describe("Defines the board outline of the PCB");Pt(!0);uFe=v.object({type:v.literal("pcb_placement_error"),pcb_placement_error_id:Cr("pcb_placement_error"),error_type:v.literal("pcb_placement_error").default("pcb_placement_error"),message:v.string(),subcircuit_id:v.string().optional()}).describe("Defines a placement error on the PCB");Pt(!0);cFe=v.object({type:v.literal("pcb_trace_hint"),pcb_trace_hint_id:Cr("pcb_trace_hint"),pcb_port_id:v.string(),pcb_component_id:v.string(),route:v.array(bo),subcircuit_id:v.string().optional()}).describe("A hint that can be used during generation of a PCB trace");Pt(!0);lFe=v.object({type:v.literal("pcb_silkscreen_line"),pcb_silkscreen_line_id:Cr("pcb_silkscreen_line"),pcb_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),stroke_width:Be.default("0.1mm"),x1:Be,y1:Be,x2:Be,y2:Be,layer:zm}).describe("Defines a silkscreen line on the PCB");Pt(!0);dFe=v.object({type:v.literal("pcb_silkscreen_path"),pcb_silkscreen_path_id:Cr("pcb_silkscreen_path"),pcb_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),layer:zm,route:v.array(Hr),stroke_width:pe}).describe("Defines a silkscreen path on the PCB");Pt(!0);pFe=v.object({type:v.literal("pcb_silkscreen_text"),pcb_silkscreen_text_id:Cr("pcb_silkscreen_text"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),font:v.literal("tscircuit2024").default("tscircuit2024"),font_size:Be.default("0.2mm"),pcb_component_id:v.string(),text:v.string(),is_knockout:v.boolean().default(!1).optional(),knockout_padding:v.object({left:pe,top:pe,bottom:pe,right:pe}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:v.number().optional(),layer:dn,is_mirrored:v.boolean().default(!1).optional(),anchor_position:Hr.default({x:0,y:0}),anchor_alignment:LA.default("center")}).describe("Defines silkscreen text on the PCB");Pt(!0);xFe=v.object({type:v.literal("pcb_silkscreen_rect"),pcb_silkscreen_rect_id:Cr("pcb_silkscreen_rect"),pcb_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),center:Hr,width:pe,height:pe,layer:dn,stroke_width:pe.default("1mm"),is_filled:v.boolean().default(!0).optional(),has_stroke:v.boolean().optional(),is_stroke_dashed:v.boolean().optional()}).describe("Defines a silkscreen rect on the PCB");Pt(!0);fFe=v.object({type:v.literal("pcb_silkscreen_circle"),pcb_silkscreen_circle_id:Cr("pcb_silkscreen_circle"),pcb_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),center:Hr,radius:pe,layer:zm,stroke_width:pe.default("1mm")}).describe("Defines a silkscreen circle on the PCB");Pt(!0);hFe=v.object({type:v.literal("pcb_silkscreen_oval"),pcb_silkscreen_oval_id:Cr("pcb_silkscreen_oval"),pcb_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),center:Hr,radius_x:Be,radius_y:Be,layer:zm}).describe("Defines a silkscreen oval on the PCB");Pt(!0);mFe=v.object({type:v.literal("pcb_fabrication_note_text"),pcb_fabrication_note_text_id:Cr("pcb_fabrication_note_text"),subcircuit_id:v.string().optional(),pcb_group_id:v.string().optional(),font:v.literal("tscircuit2024").default("tscircuit2024"),font_size:Be.default("1mm"),pcb_component_id:v.string(),text:v.string(),layer:zm,anchor_position:Hr.default({x:0,y:0}),anchor_alignment:v.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),color:v.string().optional()}).describe("Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators");Pt(!0);gFe=v.object({type:v.literal("pcb_fabrication_note_path"),pcb_fabrication_note_path_id:Cr("pcb_fabrication_note_path"),pcb_component_id:v.string(),subcircuit_id:v.string().optional(),layer:dn,route:v.array(Hr),stroke_width:pe,color:v.string().optional()}).describe("Defines a fabrication path on the PCB for fabricators or assemblers");Pt(!0);DFe=v.object({type:v.literal("pcb_footprint_overlap_error"),pcb_error_id:Cr("pcb_error"),error_type:v.literal("pcb_footprint_overlap_error").default("pcb_footprint_overlap_error"),message:v.string(),pcb_smtpad_ids:v.array(v.string()).optional(),pcb_plated_hole_ids:v.array(v.string()).optional(),pcb_hole_ids:v.array(v.string()).optional(),pcb_keepout_ids:v.array(v.string()).optional()}).describe("Error emitted when a pcb footprint overlaps with another element");Pt(!0);yFe=v.object({type:v.literal("pcb_keepout"),shape:v.literal("rect"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),center:Hr,width:Be,height:Be,pcb_keepout_id:v.string(),layers:v.array(v.string()),description:v.string().optional()}).or(v.object({type:v.literal("pcb_keepout"),shape:v.literal("circle"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),center:Hr,radius:Be,pcb_keepout_id:v.string(),layers:v.array(v.string()),description:v.string().optional()}));Pt(!0);Oq=v.object({type:v.literal("pcb_cutout"),pcb_cutout_id:Cr("pcb_cutout"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional()}),bFe=Oq.extend({shape:v.literal("rect"),center:Hr,width:pe,height:pe,rotation:Gn.optional()});Pt(!0);FFe=Oq.extend({shape:v.literal("circle"),center:Hr,radius:pe});Pt(!0);EFe=Oq.extend({shape:v.literal("polygon"),points:v.array(Hr)});Pt(!0);vFe=v.discriminatedUnion("shape",[bFe,FFe,EFe]).describe("Defines a cutout on the PCB, removing board material.");Pt(!0);CFe=v.object({type:v.literal("pcb_missing_footprint_error"),pcb_missing_footprint_error_id:Cr("pcb_missing_footprint_error"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),error_type:v.literal("pcb_missing_footprint_error").default("pcb_missing_footprint_error"),source_component_id:v.string(),message:v.string()}).describe("Defines a missing footprint error on the PCB");Pt(!0);yb=v.object({type:v.literal("external_footprint_load_error"),external_footprint_load_error_id:Cr("external_footprint_load_error"),pcb_component_id:v.string(),source_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),footprinter_string:v.string().optional(),error_type:v.literal("external_footprint_load_error").default("external_footprint_load_error"),message:v.string()}).describe("Defines an error when an external footprint fails to load");Pt(!0);VA=v.object({type:v.literal("circuit_json_footprint_load_error"),circuit_json_footprint_load_error_id:Cr("circuit_json_footprint_load_error"),pcb_component_id:v.string(),source_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),error_type:v.literal("circuit_json_footprint_load_error").default("circuit_json_footprint_load_error"),message:v.string(),circuit_json:v.array(v.any()).optional()}).describe("Defines an error when a circuit JSON footprint fails to load");Pt(!0);_Fe=v.object({type:v.literal("pcb_group"),pcb_group_id:Cr("pcb_group"),source_group_id:v.string(),is_subcircuit:v.boolean().optional(),subcircuit_id:v.string().optional(),width:pe,height:pe,center:Hr,pcb_component_ids:v.array(v.string()),name:v.string().optional(),description:v.string().optional(),layout_mode:v.string().optional(),autorouter_configuration:v.object({trace_clearance:pe}).optional(),autorouter_used_string:v.string().optional()}).describe("Defines a group of components on the PCB");Pt(!0);AFe=v.object({type:v.literal("pcb_autorouting_error"),pcb_error_id:Cr("pcb_autorouting_error"),error_type:v.literal("pcb_autorouting_error").default("pcb_autorouting_error"),message:v.string(),subcircuit_id:v.string().optional()}).describe("The autorouting has failed to route a portion of the board");Pt(!0);GA=v.object({type:v.literal("pcb_manual_edit_conflict_warning"),pcb_manual_edit_conflict_warning_id:Cr("pcb_manual_edit_conflict_warning"),warning_type:v.literal("pcb_manual_edit_conflict_warning").default("pcb_manual_edit_conflict_warning"),message:v.string(),pcb_component_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),source_component_id:v.string()}).describe("Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates");Pt(!0);RFe=v.object({type:v.literal("pcb_breakout_point"),pcb_breakout_point_id:Cr("pcb_breakout_point"),pcb_group_id:v.string(),subcircuit_id:v.string().optional(),source_trace_id:v.string().optional(),source_port_id:v.string().optional(),source_net_id:v.string().optional(),x:Be,y:Be}).describe("Defines a routing target within a pcb_group for a source_trace or source_net");Pt(!0);SFe=v.object({type:v.literal("pcb_ground_plane"),pcb_ground_plane_id:Cr("pcb_ground_plane"),source_pcb_ground_plane_id:v.string(),source_net_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional()}).describe("Defines a ground plane on the PCB");Pt(!0);BFe=v.object({type:v.literal("pcb_ground_plane_region"),pcb_ground_plane_region_id:Cr("pcb_ground_plane_region"),pcb_ground_plane_id:v.string(),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),layer:dn,points:v.array(Hr)}).describe("Defines a polygon region of a ground plane");Pt(!0);wFe=v.object({type:v.literal("pcb_thermal_spoke"),pcb_thermal_spoke_id:Cr("pcb_thermal_spoke"),pcb_ground_plane_id:v.string(),shape:v.string(),spoke_count:v.number(),spoke_thickness:Be,spoke_inner_diameter:Be,spoke_outer_diameter:Be,pcb_plated_hole_id:v.string().optional(),subcircuit_id:v.string().optional()}).describe("Pattern for connecting a ground plane to a plated hole");Pt(!0);Lq=v.object({type:v.literal("pcb_copper_pour"),pcb_copper_pour_id:Cr("pcb_copper_pour"),pcb_group_id:v.string().optional(),subcircuit_id:v.string().optional(),layer:dn,source_net_id:v.string().optional()}),TFe=Lq.extend({shape:v.literal("rect"),center:Hr,width:pe,height:pe,rotation:Gn.optional()});Pt(!0);PFe=Lq.extend({shape:v.literal("brep"),brep_shape:$be});Pt(!0);IFe=Lq.extend({shape:v.literal("polygon"),points:v.array(Hr)});Pt(!0);jFe=v.discriminatedUnion("shape",[TFe,PFe,IFe]).describe("Defines a copper pour on the PCB.");Pt(!0);kFe=v.object({type:v.literal("pcb_component_outside_board_error"),pcb_component_outside_board_error_id:Cr("pcb_component_outside_board_error"),error_type:v.literal("pcb_component_outside_board_error").default("pcb_component_outside_board_error"),message:v.string(),pcb_component_id:v.string(),pcb_board_id:v.string(),component_center:Hr,component_bounds:v.object({min_x:v.number(),max_x:v.number(),min_y:v.number(),max_y:v.number()}),subcircuit_id:v.string().optional(),source_component_id:v.string().optional()}).describe("Error emitted when a PCB component is placed outside the board boundaries");Pt(!0);NFe=v.object({type:v.literal("cad_component"),cad_component_id:v.string(),pcb_component_id:v.string(),source_component_id:v.string(),position:Gf,rotation:Gf.optional(),size:Gf.optional(),layer:dn.optional(),subcircuit_id:v.string().optional(),footprinter_string:v.string().optional(),model_obj_url:v.string().optional(),model_stl_url:v.string().optional(),model_3mf_url:v.string().optional(),model_gltf_url:v.string().optional(),model_glb_url:v.string().optional(),model_step_url:v.string().optional(),model_wrl_url:v.string().optional(),model_unit_to_mm_scale_factor:v.number().optional(),model_jscad:v.any().optional()}).describe("Defines a component on the PCB");Pt(!0);MFe=v.enum(["sinewave","square","triangle","sawtooth"]),LCt=v.union([v.string(),v.number()]).transform(r=>typeof r=="string"?r.endsWith("%")?parseFloat(r.slice(0,-1))/100:parseFloat(r):r).pipe(v.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),OFe=v.object({type:v.literal("simulation_voltage_source"),simulation_voltage_source_id:Cr("simulation_voltage_source"),is_dc_source:v.literal(!0).optional().default(!0),positive_source_port_id:v.string().optional(),negative_source_port_id:v.string().optional(),positive_source_net_id:v.string().optional(),negative_source_net_id:v.string().optional(),voltage:Us}).describe("Defines a DC voltage source for simulation"),LFe=v.object({type:v.literal("simulation_voltage_source"),simulation_voltage_source_id:Cr("simulation_voltage_source"),is_dc_source:v.literal(!1),terminal1_source_port_id:v.string().optional(),terminal2_source_port_id:v.string().optional(),terminal1_source_net_id:v.string().optional(),terminal2_source_net_id:v.string().optional(),voltage:Us.optional(),frequency:Oc.optional(),peak_to_peak_voltage:Us.optional(),wave_shape:MFe.optional(),phase:Gn.optional(),duty_cycle:LCt.optional()}).describe("Defines an AC voltage source for simulation"),$Fe=v.union([OFe,LFe]).describe("Defines a voltage source for simulation");Pt(!0);Pt(!0);Pt(!0);zFe=v.union([cbe,ube,obe,dbe,lbe,Eq,yq,$A,Fq,bq,vq,Cq,_q,Sq,Bq,wq,jq,Tq,Pq,Iq,Rq,Aq,pbe,xbe,kq,Nq,Mq,qbe,Gbe,CFe,yb,VA,GA,Xbe,yFe,Ybe,sFe,Jbe,eFe,iFe,Wbe,Kbe,oFe,_Fe,cFe,lFe,dFe,pFe,xFe,fFe,hFe,tFe,rFe,uFe,nFe,aFe,gFe,mFe,AFe,DFe,RFe,vFe,SFe,BFe,wFe,jFe,kFe,fbe,Abe,Fbe,Ebe,vbe,Cbe,bbe,Rbe,_be,hbe,Bbe,wbe,Sbe,jbe,kbe,qA,Nbe,Mbe,Obe,NFe,$Fe]),Yf=zFe;Pt(!0);Xf(!0)});var d3e=on((HJt,l3e)=>{"use strict";var qm=1e3,Um=qm*60,Vm=Um*60,Wf=Vm*24,t6t=Wf*7,r6t=Wf*365.25;l3e.exports=function(r,e){e=e||{};var a=typeof r;if(a==="string"&&r.length>0)return n6t(r);if(a==="number"&&isFinite(r))return e.long?s6t(r):a6t(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function n6t(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var a=parseFloat(e[1]),s=(e[2]||"ms").toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return a*r6t;case"weeks":case"week":case"w":return a*t6t;case"days":case"day":case"d":return a*Wf;case"hours":case"hour":case"hrs":case"hr":case"h":return a*Vm;case"minutes":case"minute":case"mins":case"min":case"m":return a*Um;case"seconds":case"second":case"secs":case"sec":case"s":return a*qm;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}function a6t(r){var e=Math.abs(r);return e>=Wf?Math.round(r/Wf)+"d":e>=Vm?Math.round(r/Vm)+"h":e>=Um?Math.round(r/Um)+"m":e>=qm?Math.round(r/qm)+"s":r+"ms"}function s6t(r){var e=Math.abs(r);return e>=Wf?e4(r,e,Wf,"day"):e>=Vm?e4(r,e,Vm,"hour"):e>=Um?e4(r,e,Um,"minute"):e>=qm?e4(r,e,qm,"second"):r+" ms"}function e4(r,e,a,s){var l=e>=a*1.5;return Math.round(r/a)+" "+s+(l?"s":"")}});var x3e=on((WJt,p3e)=>{"use strict";function i6t(r){a.debug=a,a.default=a,a.coerce=m,a.disable=x,a.enable=l,a.enabled=f,a.humanize=d3e(),a.destroy=D,Object.keys(r).forEach(b=>{a[b]=r[b]}),a.names=[],a.skips=[],a.formatters={};function e(b){let E=0;for(let A=0;A<b.length;A++)E=(E<<5)-E+b.charCodeAt(A),E|=0;return a.colors[Math.abs(E)%a.colors.length]}a.selectColor=e;function a(b){let E,A=null,B,w;function P(...j){if(!P.enabled)return;let O=P,q=Number(new Date),ee=q-(E||q);O.diff=ee,O.prev=E,O.curr=q,E=q,j[0]=a.coerce(j[0]),typeof j[0]!="string"&&j.unshift("%O");let W=0;j[0]=j[0].replace(/%([a-zA-Z%])/g,(L,K)=>{if(L==="%%")return"%";W++;let U=a.formatters[K];if(typeof U=="function"){let J=j[W];L=U.call(O,J),j.splice(W,1),W--}return L}),a.formatArgs.call(O,j),(O.log||a.log).apply(O,j)}return P.namespace=b,P.useColors=a.useColors(),P.color=a.selectColor(b),P.extend=s,P.destroy=a.destroy,Object.defineProperty(P,"enabled",{enumerable:!0,configurable:!1,get:()=>A!==null?A:(B!==a.namespaces&&(B=a.namespaces,w=a.enabled(b)),w),set:j=>{A=j}}),typeof a.init=="function"&&a.init(P),P}function s(b,E){let A=a(this.namespace+(typeof E>"u"?":":E)+b);return A.log=this.log,A}function l(b){a.save(b),a.namespaces=b,a.names=[],a.skips=[];let E=(typeof b=="string"?b:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let A of E)A[0]==="-"?a.skips.push(A.slice(1)):a.names.push(A)}function d(b,E){let A=0,B=0,w=-1,P=0;for(;A<b.length;)if(B<E.length&&(E[B]===b[A]||E[B]==="*"))E[B]==="*"?(w=B,P=A,B++):(A++,B++);else if(w!==-1)B=w+1,P++,A=P;else return!1;for(;B<E.length&&E[B]==="*";)B++;return B===E.length}function x(){let b=[...a.names,...a.skips.map(E=>"-"+E)].join(",");return a.enable(""),b}function f(b){for(let E of a.skips)if(d(b,E))return!1;for(let E of a.names)if(d(b,E))return!0;return!1}function m(b){return b instanceof Error?b.stack||b.message:b}function D(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return a.enable(a.load()),a}p3e.exports=i6t});var fs=on((Jo,t4)=>{"use strict";Jo.formatArgs=u6t;Jo.save=c6t;Jo.load=l6t;Jo.useColors=o6t;Jo.storage=d6t();Jo.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Jo.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function o6t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function u6t(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+t4.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let a=0,s=0;r[0].replace(/%[a-zA-Z%]/g,l=>{l!=="%%"&&(a++,l==="%c"&&(s=a))}),r.splice(s,0,e)}Jo.log=console.debug||console.log||(()=>{});function c6t(r){try{r?Jo.storage.setItem("debug",r):Jo.storage.removeItem("debug")}catch{}}function l6t(){let r;try{r=Jo.storage.getItem("debug")||Jo.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function d6t(){try{return localStorage}catch{}}t4.exports=x3e()(Jo);var{formatters:p6t}=t4.exports;p6t.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var v3e=on(Qa=>{"use strict";function Hq(r,e){var a=r.length;r.push(e);e:for(;0<a;){var s=a-1>>>1,l=r[s];if(0<r4(l,e))r[s]=e,r[a]=l,a=s;else break e}}function U0(r){return r.length===0?null:r[0]}function a4(r){if(r.length===0)return null;var e=r[0],a=r.pop();if(a!==e){r[0]=a;e:for(var s=0,l=r.length,d=l>>>1;s<d;){var x=2*(s+1)-1,f=r[x],m=x+1,D=r[m];if(0>r4(f,a))m<l&&0>r4(D,f)?(r[s]=D,r[m]=a,s=m):(r[s]=f,r[x]=a,s=x);else if(m<l&&0>r4(D,a))r[s]=D,r[m]=a,s=m;else break e}}return e}function r4(r,e){var a=r.sortIndex-e.sortIndex;return a!==0?a:r.id-e.id}Qa.unstable_now=void 0;typeof performance=="object"&&typeof performance.now=="function"?(f3e=performance,Qa.unstable_now=function(){return f3e.now()}):(Gq=Date,h3e=Gq.now(),Qa.unstable_now=function(){return Gq.now()-h3e});var f3e,Gq,h3e,Kl=[],Tp=[],x6t=1,Ju=null,Ki=3,Wq=!1,Fb=!1,Eb=!1,Kq=!1,D3e=typeof setTimeout=="function"?setTimeout:null,y3e=typeof clearTimeout=="function"?clearTimeout:null,m3e=typeof setImmediate<"u"?setImmediate:null;function n4(r){for(var e=U0(Tp);e!==null;){if(e.callback===null)a4(Tp);else if(e.startTime<=r)a4(Tp),e.sortIndex=e.expirationTime,Hq(Kl,e);else break;e=U0(Tp)}}function Jq(r){if(Eb=!1,n4(r),!Fb)if(U0(Kl)!==null)Fb=!0,Xm||(Xm=!0,Gm());else{var e=U0(Tp);e!==null&&Zq(Jq,e.startTime-r)}}var Xm=!1,vb=-1,b3e=5,F3e=-1;function E3e(){return Kq?!0:!(Qa.unstable_now()-F3e<b3e)}function Xq(){if(Kq=!1,Xm){var r=Qa.unstable_now();F3e=r;var e=!0;try{e:{Fb=!1,Eb&&(Eb=!1,y3e(vb),vb=-1),Wq=!0;var a=Ki;try{t:{for(n4(r),Ju=U0(Kl);Ju!==null&&!(Ju.expirationTime>r&&E3e());){var s=Ju.callback;if(typeof s=="function"){Ju.callback=null,Ki=Ju.priorityLevel;var l=s(Ju.expirationTime<=r);if(r=Qa.unstable_now(),typeof l=="function"){Ju.callback=l,n4(r),e=!0;break t}Ju===U0(Kl)&&a4(Kl),n4(r)}else a4(Kl);Ju=U0(Kl)}if(Ju!==null)e=!0;else{var d=U0(Tp);d!==null&&Zq(Jq,d.startTime-r),e=!1}}break e}finally{Ju=null,Ki=a,Wq=!1}e=void 0}}finally{e?Gm():Xm=!1}}}var Gm;typeof m3e=="function"?Gm=function(){m3e(Xq)}:typeof MessageChannel<"u"?(Yq=new MessageChannel,g3e=Yq.port2,Yq.port1.onmessage=Xq,Gm=function(){g3e.postMessage(null)}):Gm=function(){D3e(Xq,0)};var Yq,g3e;function Zq(r,e){vb=D3e(function(){r(Qa.unstable_now())},e)}Qa.unstable_IdlePriority=5;Qa.unstable_ImmediatePriority=1;Qa.unstable_LowPriority=4;Qa.unstable_NormalPriority=3;Qa.unstable_Profiling=null;Qa.unstable_UserBlockingPriority=2;Qa.unstable_cancelCallback=function(r){r.callback=null};Qa.unstable_forceFrameRate=function(r){0>r||125<r?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):b3e=0<r?Math.floor(1e3/r):5};Qa.unstable_getCurrentPriorityLevel=function(){return Ki};Qa.unstable_next=function(r){switch(Ki){case 1:case 2:case 3:var e=3;break;default:e=Ki}var a=Ki;Ki=e;try{return r()}finally{Ki=a}};Qa.unstable_requestPaint=function(){Kq=!0};Qa.unstable_runWithPriority=function(r,e){switch(r){case 1:case 2:case 3:case 4:case 5:break;default:r=3}var a=Ki;Ki=r;try{return e()}finally{Ki=a}};Qa.unstable_scheduleCallback=function(r,e,a){var s=Qa.unstable_now();switch(typeof a=="object"&&a!==null?(a=a.delay,a=typeof a=="number"&&0<a?s+a:s):a=s,r){case 1:var l=-1;break;case 2:l=250;break;case 5:l=1073741823;break;case 4:l=1e4;break;default:l=5e3}return l=a+l,r={id:x6t++,callback:e,priorityLevel:r,startTime:a,expirationTime:l,sortIndex:-1},a>s?(r.sortIndex=a,Hq(Tp,r),U0(Kl)===null&&r===U0(Tp)&&(Eb?(y3e(vb),vb=-1):Eb=!0,Zq(Jq,a-s))):(r.sortIndex=l,Hq(Kl,r),Fb||Wq||(Fb=!0,Xm||(Xm=!0,Gm()))),r};Qa.unstable_shouldYield=E3e;Qa.unstable_wrapCallback=function(r){var e=Ki;return function(){var a=Ki;Ki=e;try{return r.apply(this,arguments)}finally{Ki=a}}}});var _3e=on((JJt,C3e)=>{"use strict";C3e.exports=v3e()});var A3e=on((ZJt,Cb)=>{"use strict";Cb.exports=function(r){function e(C,_,T,M){return new eE(C,_,T,M)}function a(){}function s(C){var _="https://react.dev/errors/"+C;if(1<arguments.length){_+="?args[]="+encodeURIComponent(arguments[1]);for(var T=2;T<arguments.length;T++)_+="&args[]="+encodeURIComponent(arguments[T])}return"Minified React error #"+C+"; visit "+_+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function l(C){var _=C,T=C;if(C.alternate)for(;_.return;)_=_.return;else{C=_;do _=C,(_.flags&4098)!==0&&(T=_.return),C=_.return;while(C)}return _.tag===3?T:null}function d(C){if(l(C)!==C)throw Error(s(188))}function x(C){var _=C.alternate;if(!_){if(_=l(C),_===null)throw Error(s(188));return _!==C?null:C}for(var T=C,M=_;;){var Y=T.return;if(Y===null)break;var ce=Y.alternate;if(ce===null){if(M=Y.return,M!==null){T=M;continue}break}if(Y.child===ce.child){for(ce=Y.child;ce;){if(ce===T)return d(Y),C;if(ce===M)return d(Y),_;ce=ce.sibling}throw Error(s(188))}if(T.return!==M.return)T=Y,M=ce;else{for(var we=!1,Ze=Y.child;Ze;){if(Ze===T){we=!0,T=Y,M=ce;break}if(Ze===M){we=!0,M=Y,T=ce;break}Ze=Ze.sibling}if(!we){for(Ze=ce.child;Ze;){if(Ze===T){we=!0,T=ce,M=Y;break}if(Ze===M){we=!0,M=ce,T=Y;break}Ze=Ze.sibling}if(!we)throw Error(s(189))}}if(T.alternate!==M)throw Error(s(190))}if(T.tag!==3)throw Error(s(188));return T.stateNode.current===T?C:_}function f(C){var _=C.tag;if(_===5||_===26||_===27||_===6)return C;for(C=C.child;C!==null;){if(_=f(C),_!==null)return _;C=C.sibling}return null}function m(C){var _=C.tag;if(_===5||_===26||_===27||_===6)return C;for(C=C.child;C!==null;){if(C.tag!==4&&(_=m(C),_!==null))return _;C=C.sibling}return null}function D(C){return C===null||typeof C!="object"?null:(C=xh&&C[xh]||C["@@iterator"],typeof C=="function"?C:null)}function b(C){if(C==null)return null;if(typeof C=="function")return C.$$typeof===fh?null:C.displayName||C.name||null;if(typeof C=="string")return C;switch(C){case wd:return"Fragment";case Li:return"Profiler";case iE:return"StrictMode";case WD:return"Suspense";case KD:return"SuspenseList";case Os:return"Activity"}if(typeof C=="object")switch(C.$$typeof){case hl:return"Portal";case t0:return(C.displayName||"Context")+".Provider";case YD:return(C._context.displayName||"Context")+".Consumer";case HD:var _=C.render;return C=C.displayName,C||(C=_.displayName||_.name||"",C=C!==""?"ForwardRef("+C+")":"ForwardRef"),C;case ph:return _=C.displayName||null,_!==null?_:b(C.type)||"Memo";case To:_=C._payload,C=C._init;try{return b(C(_))}catch{}}return null}function E(C){return{current:C}}function A(C){0>u0||(C.current=fy[u0],fy[u0]=null,u0--)}function B(C,_){u0++,fy[u0]=C.current,C.current=_}function w(C){return C>>>=0,C===0?32:31-(Md(C)/c0|0)|0}function P(C){var _=C&42;if(_!==0)return _;switch(C&-C){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return C&4194048;case 4194304:case 8388608:case 16777216:case 33554432:return C&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return C}}function j(C,_,T){var M=C.pendingLanes;if(M===0)return 0;var Y=0,ce=C.suspendedLanes,we=C.pingedLanes;C=C.warmLanes;var Ze=M&134217727;return Ze!==0?(M=Ze&~ce,M!==0?Y=P(M):(we&=Ze,we!==0?Y=P(we):T||(T=Ze&~C,T!==0&&(Y=P(T))))):(Ze=M&~ce,Ze!==0?Y=P(Ze):we!==0?Y=P(we):T||(T=M&~C,T!==0&&(Y=P(T)))),Y===0?0:_!==0&&_!==Y&&(_&ce)===0&&(ce=Y&-Y,T=_&-_,ce>=T||ce===32&&(T&4194048)!==0)?_:Y}function O(C,_){return(C.pendingLanes&~(C.suspendedLanes&~C.pingedLanes)&_)===0}function q(C,_){switch(C){case 1:case 2:case 4:case 8:case 64:return _+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return _+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function ee(){var C=Od;return Od<<=1,(Od&4194048)===0&&(Od=256),C}function W(){var C=ir;return ir<<=1,(ir&62914560)===0&&(ir=4194304),C}function re(C){for(var _=[],T=0;31>T;T++)_.push(C);return _}function L(C,_){C.pendingLanes|=_,_!==268435456&&(C.suspendedLanes=0,C.pingedLanes=0,C.warmLanes=0)}function K(C,_,T,M,Y,ce){var we=C.pendingLanes;C.pendingLanes=T,C.suspendedLanes=0,C.pingedLanes=0,C.warmLanes=0,C.expiredLanes&=T,C.entangledLanes&=T,C.errorRecoveryDisabledLanes&=T,C.shellSuspendCounter=0;var Ze=C.entanglements,_t=C.expirationTimes,Kt=C.hiddenUpdates;for(T=we&~T;0<T;){var dr=31-ya(T),mr=1<<dr;Ze[dr]=0,_t[dr]=-1;var Fr=Kt[dr];if(Fr!==null)for(Kt[dr]=null,dr=0;dr<Fr.length;dr++){var mn=Fr[dr];mn!==null&&(mn.lane&=-536870913)}T&=~mr}M!==0&&U(C,M,0),ce!==0&&Y===0&&C.tag!==0&&(C.suspendedLanes|=ce&~(we&~_))}function U(C,_,T){C.pendingLanes|=_,C.suspendedLanes&=~_;var M=31-ya(_);C.entangledLanes|=_,C.entanglements[M]=C.entanglements[M]|1073741824|T&4194090}function J(C,_){var T=C.entangledLanes|=_;for(C=C.entanglements;T;){var M=31-ya(T),Y=1<<M;Y&_|C[M]&_&&(C[M]|=_),T&=~Y}}function Q(C){switch(C){case 2:C=1;break;case 8:C=4;break;case 32:C=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:C=128;break;case 268435456:C=134217728;break;default:C=0}return C}function de(C){return C&=-C,2<C?8<C?(C&134217727)!==0?32:268435456:8:2}function oe(C){if(typeof gi=="function"&&gy(C),Di&&typeof Di.setStrictMode=="function")try{Di.setStrictMode(xc,C)}catch{}}function Me(C){if(Sh===void 0)try{throw Error()}catch(T){var _=T.stack.trim().match(/\n( *(at )?)/);Sh=_&&_[1]||"",Dy=-1<T.stack.indexOf(`
2
2
  at`)?" (<anonymous>)":-1<T.stack.indexOf("@")?"@unknown:0:0":""}return`
3
3
  `+Sh+C+Dy}function Ne(C,_){if(!C||kx)return"";kx=!0;var T=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var M={DetermineComponentFrameRoot:function(){try{if(_){var mr=function(){throw Error()};if(Object.defineProperty(mr.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(mr,[])}catch(mn){var Fr=mn}Reflect.construct(C,[],mr)}else{try{mr.call()}catch(mn){Fr=mn}C.call(mr.prototype)}}else{try{throw Error()}catch(mn){Fr=mn}(mr=C())&&typeof mr.catch=="function"&&mr.catch(function(){})}}catch(mn){if(mn&&Fr&&typeof mn.stack=="string")return[mn.stack,Fr.stack]}return[null,null]}};M.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var Y=Object.getOwnPropertyDescriptor(M.DetermineComponentFrameRoot,"name");Y&&Y.configurable&&Object.defineProperty(M.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var ce=M.DetermineComponentFrameRoot(),we=ce[0],Ze=ce[1];if(we&&Ze){var _t=we.split(`
4
4
  `),Kt=Ze.split(`
@@ -93,7 +93,7 @@ $1`).replace(/>(\s*)(?=<!--\s*\/)/g,"> ")}});var LSe=on(TS=>{"use strict";var nU
93
93
  stroke: #fff;
94
94
  stroke-width: 0.2;
95
95
  }
96
- `,name:"",attributes:{},children:[]}],value:"",attributes:{}},{name:"rect",type:"element",attributes:{fill:"#fff",x:"0",y:"0",width:D.toString(),height:b.toString()},value:"",children:[]},XUt(j,a,s,l,d),...q].filter(L=>L!==null)};return(0,pBe.stringify)(re)}function GUt(r,e,a){let s=ua(a).source_component.list();switch(r.type){case"pcb_board":return jUt(r,e.transform);case"pcb_component":{let l=s.find(f=>f.source_component_id===r.source_component_id),x=ua(a).pcb_port.list().filter(f=>f.pcb_component_id===r.pcb_component_id)[0];if(l&&x){let f=l.are_pins_interchangeable,m=NUt({elm:r,portPosition:{x:x.x,y:x.y},name:l.name,arePinsInterchangeable:f},e);return m?[m]:[]}return[]}case"pcb_smtpad":return UUt(r,e);case"pcb_hole":return zUt(r,e);case"pcb_plated_hole":return qUt(r,e);default:return[]}}function XUt(r,e,a,s,l){let[d,x]=mt(r,[e,a]),[f,m]=mt(r,[s,l]),D=Math.abs(f-d),b=Math.abs(m-x),E=Math.min(d,f),A=Math.min(x,m);return{name:"rect",type:"element",value:"",children:[],attributes:{class:"assembly-boundary",x:E.toString(),y:A.toString(),width:D.toString(),height:b.toString()}}}function YUt(r){let{minX:e,minY:a,maxX:s,maxY:l}=r.bounds,d=r.cellSize??1,x=r.labelCells??!1,f=[],m=(D,b)=>{let[E,A]=mt(r.transform,[D,b]);return{x:E,y:A}};for(let D=Math.floor(e);D<=Math.ceil(s);D+=d){let b=m(D,a),E=m(D,l);f.push({name:"line",type:"element",attributes:{x1:b.x.toString(),y1:b.y.toString(),x2:E.x.toString(),y2:E.y.toString(),stroke:nl.schematic.grid,"stroke-width":(.01*Math.abs(r.transform.a)).toString(),"stroke-opacity":"0.5"}})}for(let D=Math.floor(a);D<=Math.ceil(l);D+=d){let b=m(e,D),E=m(s,D);f.push({name:"line",type:"element",attributes:{x1:b.x.toString(),y1:b.y.toString(),x2:E.x.toString(),y2:E.y.toString(),stroke:nl.schematic.grid,"stroke-width":(.01*Math.abs(r.transform.a)).toString(),"stroke-opacity":"0.5"}})}if(x){let D=(b,E)=>d<=.1?`${b.toFixed(1)},${E.toFixed(1)}`:`${b},${E}`;for(let b=Math.floor(e);b<=Math.ceil(s);b+=d)for(let E=Math.floor(a);E<=Math.ceil(l);E+=d){let A=m(b,E);f.push({name:"text",type:"element",attributes:{x:(A.x-2.5).toString(),y:(A.y-5).toString(),fill:nl.schematic.grid,"font-size":(d/5*Math.abs(r.transform.a)).toString(),"fill-opacity":"0.5","text-anchor":"middle","dominant-baseline":"middle","font-family":"sans-serif"},children:[{type:"text",value:D(b,E),name:"",attributes:{},children:[]}]})}}return{name:"g",value:"",type:"element",attributes:{class:"grid"},children:f}}function HUt(r){let{points:e,transform:a}=r,s=[];for(let l of e){let[d,x]=mt(a,[l.x-.1,l.y-.1]),[f,m]=mt(a,[l.x+.1,l.y+.1]),[D,b]=mt(a,[l.x-.1,l.y+.1]),[E,A]=mt(a,[l.x+.1,l.y-.1]);s.push({name:"path",type:"element",attributes:{d:`M${d},${x} L${f},${m} M${D},${b} L${E},${A}`,stroke:nl.schematic.grid,"stroke-width":(.02*Math.abs(a.a)).toString(),"stroke-opacity":"0.7"}});let[B,w]=mt(a,[l.x+.15,l.y-.15]);s.push({name:"text",type:"element",attributes:{x:B.toString(),y:w.toString(),fill:nl.schematic.grid,"font-size":(.1*Math.abs(a.a)).toString(),"fill-opacity":"0.7","text-anchor":"start","font-family":"sans-serif","dominant-baseline":"middle"},children:[{type:"text",value:l.label||`(${l.x},${l.y})`,name:"",attributes:{},children:[]}]})}return{name:"g",value:"",type:"element",attributes:{class:"labeled-points"},children:s}}function JUt(r){return{left:180,top:90,bottom:-90,right:0}[r]??0}function ZUt(r,e,a){let s=a+rx*2+Lg*r.text.length+Og,l=zg(r.anchor_side);return r.anchor_position??{x:r.center.x-l.x*s*e/2,y:r.center.y-l.y*s*e/2}}function QUt(r,e=.5){let a=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY,d=Number.NEGATIVE_INFINITY,x=.2;for(let m of r)if(m.type==="schematic_component")f(m.center,m.size,0);else if(m.type==="schematic_port")f(m.center,{width:x,height:x},0);else if(m.type==="schematic_debug_object")m.shape==="rect"?f(m.center,m.size,0):m.shape==="line"&&(f(m.start,{width:.1,height:.1},0),f(m.end,{width:.1,height:.1},0));else if(m.type==="schematic_net_label"){let D=$g("net_label"),b=MS(m.text||""),A=(b+rx*2+Lg*(m.text?.length||0)+Og)*D,B=1.2*D,w=JUt(m.anchor_side)/180*Math.PI,P=ZUt(m,D,b),j=zg(m.anchor_side),O={x:P.x+j.x*A/2,y:P.y+j.y*A/2};f(O,{width:A,height:B},w)}else if(m.type==="schematic_trace")for(let D of m.edges)f(D.from,{width:.1,height:.1},0),f(D.to,{width:.1,height:.1},0);else if(m.type==="schematic_text"){let b=$g("reference_designator",m.font_size)??.18,A=(m.text??"").length*b,B=b;f(m.position,{width:A,height:B},m.rotation??0)}else if(m.type==="schematic_voltage_probe")f(m.position,{width:.2,height:.4},0);else if(m.type==="schematic_box")f({x:m.x+m.width/2,y:m.y+m.height/2},{width:m.width,height:m.height},0);else if(m.type==="schematic_table"){let{column_widths:D,row_heights:b}=fBe(m,r),E=D.reduce((q,ee)=>q+ee,0),A=b.reduce((q,ee)=>q+ee,0),B=m.anchor??"center",w=m.anchor_position.x,P=m.anchor_position.y;B.includes("center")?w-=E/2:B.includes("right")&&(w-=E),B.includes("center")?P+=A/2:B.includes("bottom")&&(P+=A);let j=w+E/2,O=P-A/2;f({x:j,y:O},{width:E,height:A},0)}else m.type==="schematic_line"?(f({x:m.x1,y:m.y1},{width:.02,height:.02},0),f({x:m.x2,y:m.y2},{width:.02,height:.02},0)):m.type==="schematic_circle"?f(m.center,{width:m.radius*2,height:m.radius*2},0):m.type==="schematic_rect"?f(m.center,{width:m.width,height:m.height},m.rotation):m.type==="schematic_arc"&&f(m.center,{width:m.radius*2,height:m.radius*2},0);return a-=e,s-=e,l+=e,d+=e,{minX:a,minY:s,maxX:l,maxY:d};function f(m,D,b){let E=[{x:-D.width/2,y:-D.height/2},{x:D.width/2,y:-D.height/2},{x:D.width/2,y:D.height/2},{x:-D.width/2,y:D.height/2}];for(let A of E){let B=A.x*Math.cos(b)-A.y*Math.sin(b)+m.x,w=A.x*Math.sin(b)+A.y*Math.cos(b)+m.y;a=Math.min(a,B),s=Math.min(s,w),l=Math.max(l,B),d=Math.max(d,w)}}}function rVt(r,e,a,s){let l=e.x-r.x,d=e.y-r.y,x=Math.sqrt((a.x-r.x)**2+(a.y-r.y)**2),m=Math.sqrt((s.x-e.x)**2+(s.y-e.y)**2)/x,D=Ra(l,d),b=ji(m,m);return jn(D,b)}function lVt(r){let{component:e}=r,a=e.symbol_name?aVt(r):cVt(r);return[{type:"element",name:"g",attributes:{"data-circuit-json-type":"schematic_component","data-schematic-component-id":e.schematic_component_id},children:a,value:""}]}function dVt({probe:r,transform:e,colorMap:a}){let[s,l]=mt(e,[r.position.x,r.position.y]),d=Math.abs(e.a)*.6,x=Math.abs(e.a)*.28,f=s+d*Math.cos(-50*Math.PI/180),m=l+d*Math.sin(-50*Math.PI/180),D=s,b=l;return[{name:"path",type:"element",attributes:{d:[`M ${f},${m}`,`L ${D},${b}`,`M ${D},${b}`,`L ${D-x*Math.cos(100*Math.PI/180)},${b-x*Math.sin(100*Math.PI/180)}`,`L ${D-x*Math.cos(160*Math.PI/180)},${b-x*Math.sin(160*Math.PI/180)}`,"Z"].join(" "),stroke:a.schematic.reference,fill:a.schematic.reference,"stroke-width":`${ui(e)}px`},value:"",children:[]},{type:"element",name:"text",value:"",attributes:{x:(f+8-(f-f)).toString(),y:(m-10+(m-m)).toString(),fill:a.schematic.reference,"text-anchor":"middle","dominant-baseline":"middle","font-family":"sans-serif","font-size":`${cd(e,"reference_designator")}px`,"font-weight":"bold","data-schematic-voltage-probe-id":r.schematic_voltage_probe_id},children:[{type:"text",value:r.voltage?`${r.voltage}V`:"",name:"",attributes:{},children:[]}]}]}function pVt({debugObject:r,transform:e}){if(r.shape==="rect"){let[a,s]=mt(e,[r.center.x-r.size.width/2,r.center.y-r.size.height/2]),[l,d]=mt(e,[r.center.x+r.size.width/2,r.center.y+r.size.height/2]);[s,d]=[Math.min(s,d),Math.max(s,d)];let x=Math.abs(l-a),f=Math.abs(d-s),[m,D]=mt(e,[r.center.x,r.center.y]);return[{name:"rect",type:"element",value:"",attributes:{x:a.toString(),y:s.toString(),width:x.toString(),height:f.toString(),fill:"none",stroke:"red","stroke-width":(.02*Math.abs(e.a)).toString(),"stroke-dasharray":"5,5"},children:r.label?[{name:"text",type:"element",value:"",attributes:{x:m.toString(),y:(D-10).toString(),"text-anchor":"middle","font-size":(.2*Math.abs(e.a)).toString(),fill:"red"},children:[{type:"text",value:r.label,name:"",attributes:{},children:[]}]}]:[]}]}if(r.shape==="line"){let[a,s]=mt(e,[r.start.x,r.start.y]),[l,d]=mt(e,[r.end.x,r.end.y]),x=(a+l)/2,f=(s+d)/2;return[{name:"line",type:"element",value:"",attributes:{x1:a.toString(),y1:s.toString(),x2:l.toString(),y2:d.toString(),stroke:"red","stroke-width":(.02*Math.abs(e.a)).toString(),"stroke-dasharray":"5,5"},children:r.label?[{name:"text",type:"element",value:"",attributes:{x:x.toString(),y:(f-10).toString(),"text-anchor":"middle","font-size":(.2*Math.abs(e.a)).toString(),fill:"red"},children:[{type:"text",value:r.label,name:"",attributes:{},children:[]}]}]:[]}]}return[]}function xVt({trace:r,transform:e,colorMap:a}){let s=r.edges;if(s.length===0)return[];let l=[],d=[],x="";for(let f=0;f<s.length;f++){let m=s[f];if(m.is_crossing)continue;let[D,b]=mt(e,[m.from.x,m.from.y]),[E,A]=mt(e,[m.to.x,m.to.y]);f===0||s[f-1]?.is_crossing?x+=`M ${D} ${b} L ${E} ${A}`:x+=` L ${E} ${A}`}x&&(l.push({name:"path",type:"element",attributes:{d:x,class:"trace-invisible-hover-outline",stroke:a.schematic.wire,fill:"none","stroke-width":`${ui(e)*8}px`,"stroke-linecap":"round",opacity:"0","stroke-linejoin":"round"},value:"",children:[]}),l.push({name:"path",type:"element",attributes:{d:x,stroke:a.schematic.wire,fill:"none","stroke-width":`${ui(e)}px`,"stroke-linecap":"round","stroke-linejoin":"round"},value:"",children:[]}));for(let f of s){if(!f.is_crossing)continue;let[m,D]=mt(e,[f.from.x,f.from.y]),[b,E]=mt(e,[f.to.x,f.to.y]),A=(m+b)/2,B=(D+E)/2,w=b-m,P=E-D,j=Math.sqrt(w*w+P*P),O=j*.7,q=-P/j*O,ee=w/j*O,W=A+q,re=B-Math.abs(ee);d.push({name:"path",type:"element",attributes:{class:"trace-crossing-outline",d:`M ${m} ${D} Q ${W} ${re} ${b} ${E}`,stroke:a.schematic.background,fill:"none","stroke-width":`${ui(e)*1.5}px`,"stroke-linecap":"butt"},value:"",children:[]}),d.push({name:"path",type:"element",attributes:{d:`M ${m} ${D} Q ${W} ${re} ${b} ${E}`,stroke:a.schematic.wire,fill:"none","stroke-width":`${ui(e)}px`,"stroke-linecap":"round"},value:"",children:[]})}if(r.junctions)for(let f of r.junctions){let[m,D]=mt(e,[f.x,f.y]);d.push({name:"circle",type:"element",attributes:{cx:m.toString(),cy:D.toString(),r:(Math.abs(e.a)*.03).toString(),class:"trace-junction",fill:a.schematic.junction},value:"",children:[]})}return[{name:"g",type:"element",value:"",attributes:{class:"trace","data-layer":"base","data-circuit-json-type":"schematic_trace","data-schematic-trace-id":r.schematic_trace_id,...r.subcircuit_connectivity_map_key&&{"data-subcircuit-connectivity-map-key":r.subcircuit_connectivity_map_key}},children:l},{name:"g",type:"element",value:"",attributes:{class:"trace-overlays","data-layer":"overlay","data-circuit-json-type":"schematic_trace","data-schematic-trace-id":r.schematic_trace_id,...r.subcircuit_connectivity_map_key&&{"data-subcircuit-connectivity-map-key":r.subcircuit_connectivity_map_key}},children:d}]}function bVt({schLine:r,transform:e,colorMap:a}){let s=mt(e,{x:r.x1,y:r.y1}),l=mt(e,{x:r.x2,y:r.y2}),d=r.stroke_width??.02,x=Math.abs(e.a)*d;return[{name:"line",type:"element",attributes:{x1:s.x.toString(),y1:s.y.toString(),x2:l.x.toString(),y2:l.y.toString(),stroke:r.color,"stroke-width":x.toString(),...r.is_dashed&&{"stroke-dasharray":(x*3).toString()},"data-schematic-line-id":r.schematic_line_id,...r.schematic_component_id&&{"data-schematic-component-id":r.schematic_component_id}},children:[],value:""}]}function FVt({schCircle:r,transform:e,colorMap:a}){let s=mt(e,r.center),l=Math.abs(e.a)*r.radius,d=r.stroke_width??.02,x=Math.abs(e.a)*d;return[{name:"circle",type:"element",attributes:{cx:s.x.toString(),cy:s.y.toString(),r:l.toString(),fill:r.is_filled?r.fill_color??r.color:"none",stroke:r.color,"stroke-width":x.toString(),...r.is_dashed&&{"stroke-dasharray":(x*3).toString()},"data-schematic-circle-id":r.schematic_circle_id,...r.schematic_component_id&&{"data-schematic-component-id":r.schematic_component_id}},children:[],value:""}]}function EVt({schRect:r,transform:e,colorMap:a}){let s=mt(e,r.center),l=Math.abs(e.a)*r.width,d=Math.abs(e.d)*r.height,x=r.stroke_width??.02,f=Math.abs(e.a)*x,m=s.x-l/2,D=s.y-d/2;return[{name:"rect",type:"element",attributes:{x:m.toString(),y:D.toString(),width:l.toString(),height:d.toString(),fill:r.is_filled?r.fill_color??r.color:"none",stroke:r.color,"stroke-width":f.toString(),...r.is_dashed&&{"stroke-dasharray":(f*3).toString()},...r.rotation!==0&&{transform:`rotate(${r.rotation} ${s.x} ${s.y})`},"data-schematic-rect-id":r.schematic_rect_id,...r.schematic_component_id&&{"data-schematic-component-id":r.schematic_component_id}},children:[],value:""}]}function vVt({schArc:r,transform:e,colorMap:a}){let s=mt(e,r.center),l=Math.abs(e.a)*r.radius,d=r.stroke_width??.02,x=Math.abs(e.a)*d,f=r.start_angle_degrees*Math.PI/180,m=r.end_angle_degrees*Math.PI/180,D=s.x+l*Math.cos(f),b=s.y+l*Math.sin(f),E=s.x+l*Math.cos(m),A=s.y+l*Math.sin(m),B=r.end_angle_degrees-r.start_angle_degrees;r.direction==="clockwise"&&(B=-B),B<0&&(B+=360);let w=B>180?1:0,P=r.direction==="clockwise"?1:0;return[{name:"path",type:"element",attributes:{d:`M ${D} ${b} A ${l} ${l} 0 ${w} ${P} ${E} ${A}`,fill:"none",stroke:r.color,"stroke-width":x.toString(),...r.is_dashed&&{"stroke-dasharray":(x*3).toString()},"data-schematic-arc-id":r.schematic_arc_id,...r.schematic_component_id&&{"data-schematic-component-id":r.schematic_component_id}},children:[],value:""}]}function CVt(r){let e=[],a=s=>String(s).replace(/"/g,'\\"');for(let s of r){let d=`[data-subcircuit-connectivity-map-key="${a(s)}"]`,x=`g.trace${d}`,f=`g.trace-overlays${d}`,m=`:is(${x}, ${f}):hover`,D=`:is(${x}, ${f})`;e.push(`svg:has(${m}) ${D} { filter: invert(1); }`),e.push(`svg:has(${m}) ${f} .trace-crossing-outline { opacity: 0; }`)}return e.join(`
96
+ `,name:"",attributes:{},children:[]}],value:"",attributes:{}},{name:"rect",type:"element",attributes:{fill:"#fff",x:"0",y:"0",width:D.toString(),height:b.toString()},value:"",children:[]},XUt(j,a,s,l,d),...q].filter(L=>L!==null)};return(0,pBe.stringify)(re)}function GUt(r,e,a){let s=ua(a).source_component.list();switch(r.type){case"pcb_board":return jUt(r,e.transform);case"pcb_component":{let l=s.find(f=>f.source_component_id===r.source_component_id),x=ua(a).pcb_port.list().filter(f=>f.pcb_component_id===r.pcb_component_id)[0];if(l&&x){let f=l.are_pins_interchangeable,m=NUt({elm:r,portPosition:{x:x.x,y:x.y},name:l.name,arePinsInterchangeable:f},e);return m?[m]:[]}return[]}case"pcb_smtpad":return UUt(r,e);case"pcb_hole":return zUt(r,e);case"pcb_plated_hole":return qUt(r,e);default:return[]}}function XUt(r,e,a,s,l){let[d,x]=mt(r,[e,a]),[f,m]=mt(r,[s,l]),D=Math.abs(f-d),b=Math.abs(m-x),E=Math.min(d,f),A=Math.min(x,m);return{name:"rect",type:"element",value:"",children:[],attributes:{class:"assembly-boundary",x:E.toString(),y:A.toString(),width:D.toString(),height:b.toString()}}}function YUt(r){let{minX:e,minY:a,maxX:s,maxY:l}=r.bounds,d=r.cellSize??1,x=r.labelCells??!1,f=[],m=(D,b)=>{let[E,A]=mt(r.transform,[D,b]);return{x:E,y:A}};for(let D=Math.floor(e);D<=Math.ceil(s);D+=d){let b=m(D,a),E=m(D,l);f.push({name:"line",type:"element",attributes:{x1:b.x.toString(),y1:b.y.toString(),x2:E.x.toString(),y2:E.y.toString(),stroke:nl.schematic.grid,"stroke-width":(.01*Math.abs(r.transform.a)).toString(),"stroke-opacity":"0.5"}})}for(let D=Math.floor(a);D<=Math.ceil(l);D+=d){let b=m(e,D),E=m(s,D);f.push({name:"line",type:"element",attributes:{x1:b.x.toString(),y1:b.y.toString(),x2:E.x.toString(),y2:E.y.toString(),stroke:nl.schematic.grid,"stroke-width":(.01*Math.abs(r.transform.a)).toString(),"stroke-opacity":"0.5"}})}if(x){let D=(b,E)=>d<=.1?`${b.toFixed(1)},${E.toFixed(1)}`:`${b},${E}`;for(let b=Math.floor(e);b<=Math.ceil(s);b+=d)for(let E=Math.floor(a);E<=Math.ceil(l);E+=d){let A=m(b,E);f.push({name:"text",type:"element",attributes:{x:(A.x-2.5).toString(),y:(A.y-5).toString(),fill:nl.schematic.grid,"font-size":(d/5*Math.abs(r.transform.a)).toString(),"fill-opacity":"0.5","text-anchor":"middle","dominant-baseline":"middle","font-family":"sans-serif"},children:[{type:"text",value:D(b,E),name:"",attributes:{},children:[]}]})}}return{name:"g",value:"",type:"element",attributes:{class:"grid"},children:f}}function HUt(r){let{points:e,transform:a}=r,s=[];for(let l of e){let[d,x]=mt(a,[l.x-.1,l.y-.1]),[f,m]=mt(a,[l.x+.1,l.y+.1]),[D,b]=mt(a,[l.x-.1,l.y+.1]),[E,A]=mt(a,[l.x+.1,l.y-.1]);s.push({name:"path",type:"element",attributes:{d:`M${d},${x} L${f},${m} M${D},${b} L${E},${A}`,stroke:nl.schematic.grid,"stroke-width":(.02*Math.abs(a.a)).toString(),"stroke-opacity":"0.7"}});let[B,w]=mt(a,[l.x+.15,l.y-.15]);s.push({name:"text",type:"element",attributes:{x:B.toString(),y:w.toString(),fill:nl.schematic.grid,"font-size":(.1*Math.abs(a.a)).toString(),"fill-opacity":"0.7","text-anchor":"start","font-family":"sans-serif","dominant-baseline":"middle"},children:[{type:"text",value:l.label||`(${l.x},${l.y})`,name:"",attributes:{},children:[]}]})}return{name:"g",value:"",type:"element",attributes:{class:"labeled-points"},children:s}}function JUt(r){return{left:180,top:90,bottom:-90,right:0}[r]??0}function ZUt(r,e,a){let s=a+rx*2+Lg*r.text.length+Og,l=zg(r.anchor_side);return r.anchor_position??{x:r.center.x-l.x*s*e/2,y:r.center.y-l.y*s*e/2}}function QUt(r,e=.5){let a=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY,d=Number.NEGATIVE_INFINITY,x=.2;for(let m of r)if(m.type==="schematic_component")f(m.center,m.size,0);else if(m.type==="schematic_port")f(m.center,{width:x,height:x},0);else if(m.type==="schematic_debug_object")m.shape==="rect"?f(m.center,m.size,0):m.shape==="line"&&(f(m.start,{width:.1,height:.1},0),f(m.end,{width:.1,height:.1},0));else if(m.type==="schematic_net_label"){let D=$g("net_label"),b=MS(m.text||""),A=(b+rx*2+Lg*(m.text?.length||0)+Og)*D,B=1.2*D,w=JUt(m.anchor_side)/180*Math.PI,P=ZUt(m,D,b),j=zg(m.anchor_side),O={x:P.x+j.x*A/2,y:P.y+j.y*A/2};f(O,{width:A,height:B},w)}else if(m.type==="schematic_trace")for(let D of m.edges)f(D.from,{width:.1,height:.1},0),f(D.to,{width:.1,height:.1},0);else if(m.type==="schematic_text"){let b=$g("reference_designator",m.font_size)??.18,A=(m.text??"").length*b,B=b;f(m.position,{width:A,height:B},m.rotation??0)}else if(m.type==="schematic_voltage_probe")f(m.position,{width:.2,height:.4},0);else if(m.type==="schematic_box")f({x:m.x+m.width/2,y:m.y+m.height/2},{width:m.width,height:m.height},0);else if(m.type==="schematic_table"){let{column_widths:D,row_heights:b}=fBe(m,r),E=D.reduce((q,ee)=>q+ee,0),A=b.reduce((q,ee)=>q+ee,0),B=m.anchor??"center",w=m.anchor_position.x,P=m.anchor_position.y;B.includes("center")?w-=E/2:B.includes("right")&&(w-=E),B.includes("center")?P+=A/2:B.includes("bottom")&&(P+=A);let j=w+E/2,O=P-A/2;f({x:j,y:O},{width:E,height:A},0)}else m.type==="schematic_line"?(f({x:m.x1,y:m.y1},{width:.02,height:.02},0),f({x:m.x2,y:m.y2},{width:.02,height:.02},0)):m.type==="schematic_circle"?f(m.center,{width:m.radius*2,height:m.radius*2},0):m.type==="schematic_rect"?f(m.center,{width:m.width,height:m.height},m.rotation):m.type==="schematic_arc"&&f(m.center,{width:m.radius*2,height:m.radius*2},0);return a-=e,s-=e,l+=e,d+=e,{minX:a,minY:s,maxX:l,maxY:d};function f(m,D,b){let E=[{x:-D.width/2,y:-D.height/2},{x:D.width/2,y:-D.height/2},{x:D.width/2,y:D.height/2},{x:-D.width/2,y:D.height/2}];for(let A of E){let B=A.x*Math.cos(b)-A.y*Math.sin(b)+m.x,w=A.x*Math.sin(b)+A.y*Math.cos(b)+m.y;a=Math.min(a,B),s=Math.min(s,w),l=Math.max(l,B),d=Math.max(d,w)}}}function rVt(r,e,a,s){let l=e.x-r.x,d=e.y-r.y,x=Math.sqrt((a.x-r.x)**2+(a.y-r.y)**2),m=Math.sqrt((s.x-e.x)**2+(s.y-e.y)**2)/x,D=Ra(l,d),b=ji(m,m);return jn(D,b)}function lVt(r){let{component:e}=r;if(e.is_box_with_pins===!1)return[];let a=e.symbol_name?aVt(r):cVt(r);return[{type:"element",name:"g",attributes:{"data-circuit-json-type":"schematic_component","data-schematic-component-id":e.schematic_component_id},children:a,value:""}]}function dVt({probe:r,transform:e,colorMap:a}){let[s,l]=mt(e,[r.position.x,r.position.y]),d=Math.abs(e.a)*.6,x=Math.abs(e.a)*.28,f=s+d*Math.cos(-50*Math.PI/180),m=l+d*Math.sin(-50*Math.PI/180),D=s,b=l;return[{name:"path",type:"element",attributes:{d:[`M ${f},${m}`,`L ${D},${b}`,`M ${D},${b}`,`L ${D-x*Math.cos(100*Math.PI/180)},${b-x*Math.sin(100*Math.PI/180)}`,`L ${D-x*Math.cos(160*Math.PI/180)},${b-x*Math.sin(160*Math.PI/180)}`,"Z"].join(" "),stroke:a.schematic.reference,fill:a.schematic.reference,"stroke-width":`${ui(e)}px`},value:"",children:[]},{type:"element",name:"text",value:"",attributes:{x:(f+8-(f-f)).toString(),y:(m-10+(m-m)).toString(),fill:a.schematic.reference,"text-anchor":"middle","dominant-baseline":"middle","font-family":"sans-serif","font-size":`${cd(e,"reference_designator")}px`,"font-weight":"bold","data-schematic-voltage-probe-id":r.schematic_voltage_probe_id},children:[{type:"text",value:r.voltage?`${r.voltage}V`:"",name:"",attributes:{},children:[]}]}]}function pVt({debugObject:r,transform:e}){if(r.shape==="rect"){let[a,s]=mt(e,[r.center.x-r.size.width/2,r.center.y-r.size.height/2]),[l,d]=mt(e,[r.center.x+r.size.width/2,r.center.y+r.size.height/2]);[s,d]=[Math.min(s,d),Math.max(s,d)];let x=Math.abs(l-a),f=Math.abs(d-s),[m,D]=mt(e,[r.center.x,r.center.y]);return[{name:"rect",type:"element",value:"",attributes:{x:a.toString(),y:s.toString(),width:x.toString(),height:f.toString(),fill:"none",stroke:"red","stroke-width":(.02*Math.abs(e.a)).toString(),"stroke-dasharray":"5,5"},children:r.label?[{name:"text",type:"element",value:"",attributes:{x:m.toString(),y:(D-10).toString(),"text-anchor":"middle","font-size":(.2*Math.abs(e.a)).toString(),fill:"red"},children:[{type:"text",value:r.label,name:"",attributes:{},children:[]}]}]:[]}]}if(r.shape==="line"){let[a,s]=mt(e,[r.start.x,r.start.y]),[l,d]=mt(e,[r.end.x,r.end.y]),x=(a+l)/2,f=(s+d)/2;return[{name:"line",type:"element",value:"",attributes:{x1:a.toString(),y1:s.toString(),x2:l.toString(),y2:d.toString(),stroke:"red","stroke-width":(.02*Math.abs(e.a)).toString(),"stroke-dasharray":"5,5"},children:r.label?[{name:"text",type:"element",value:"",attributes:{x:x.toString(),y:(f-10).toString(),"text-anchor":"middle","font-size":(.2*Math.abs(e.a)).toString(),fill:"red"},children:[{type:"text",value:r.label,name:"",attributes:{},children:[]}]}]:[]}]}return[]}function xVt({trace:r,transform:e,colorMap:a}){let s=r.edges;if(s.length===0)return[];let l=[],d=[],x="";for(let f=0;f<s.length;f++){let m=s[f];if(m.is_crossing)continue;let[D,b]=mt(e,[m.from.x,m.from.y]),[E,A]=mt(e,[m.to.x,m.to.y]);f===0||s[f-1]?.is_crossing?x+=`M ${D} ${b} L ${E} ${A}`:x+=` L ${E} ${A}`}x&&(l.push({name:"path",type:"element",attributes:{d:x,class:"trace-invisible-hover-outline",stroke:a.schematic.wire,fill:"none","stroke-width":`${ui(e)*8}px`,"stroke-linecap":"round",opacity:"0","stroke-linejoin":"round"},value:"",children:[]}),l.push({name:"path",type:"element",attributes:{d:x,stroke:a.schematic.wire,fill:"none","stroke-width":`${ui(e)}px`,"stroke-linecap":"round","stroke-linejoin":"round"},value:"",children:[]}));for(let f of s){if(!f.is_crossing)continue;let[m,D]=mt(e,[f.from.x,f.from.y]),[b,E]=mt(e,[f.to.x,f.to.y]),A=(m+b)/2,B=(D+E)/2,w=b-m,P=E-D,j=Math.sqrt(w*w+P*P),O=j*.7,q=-P/j*O,ee=w/j*O,W=A+q,re=B-Math.abs(ee);d.push({name:"path",type:"element",attributes:{class:"trace-crossing-outline",d:`M ${m} ${D} Q ${W} ${re} ${b} ${E}`,stroke:a.schematic.background,fill:"none","stroke-width":`${ui(e)*1.5}px`,"stroke-linecap":"butt"},value:"",children:[]}),d.push({name:"path",type:"element",attributes:{d:`M ${m} ${D} Q ${W} ${re} ${b} ${E}`,stroke:a.schematic.wire,fill:"none","stroke-width":`${ui(e)}px`,"stroke-linecap":"round"},value:"",children:[]})}if(r.junctions)for(let f of r.junctions){let[m,D]=mt(e,[f.x,f.y]);d.push({name:"circle",type:"element",attributes:{cx:m.toString(),cy:D.toString(),r:(Math.abs(e.a)*.03).toString(),class:"trace-junction",fill:a.schematic.junction},value:"",children:[]})}return[{name:"g",type:"element",value:"",attributes:{class:"trace","data-layer":"base","data-circuit-json-type":"schematic_trace","data-schematic-trace-id":r.schematic_trace_id,...r.subcircuit_connectivity_map_key&&{"data-subcircuit-connectivity-map-key":r.subcircuit_connectivity_map_key}},children:l},{name:"g",type:"element",value:"",attributes:{class:"trace-overlays","data-layer":"overlay","data-circuit-json-type":"schematic_trace","data-schematic-trace-id":r.schematic_trace_id,...r.subcircuit_connectivity_map_key&&{"data-subcircuit-connectivity-map-key":r.subcircuit_connectivity_map_key}},children:d}]}function bVt({schLine:r,transform:e,colorMap:a}){let s=mt(e,{x:r.x1,y:r.y1}),l=mt(e,{x:r.x2,y:r.y2}),d=r.stroke_width??.02,x=Math.abs(e.a)*d;return[{name:"line",type:"element",attributes:{x1:s.x.toString(),y1:s.y.toString(),x2:l.x.toString(),y2:l.y.toString(),stroke:r.color,"stroke-width":x.toString(),...r.is_dashed&&{"stroke-dasharray":(x*3).toString()},"data-schematic-line-id":r.schematic_line_id,...r.schematic_component_id&&{"data-schematic-component-id":r.schematic_component_id}},children:[],value:""}]}function FVt({schCircle:r,transform:e,colorMap:a}){let s=mt(e,r.center),l=Math.abs(e.a)*r.radius,d=r.stroke_width??.02,x=Math.abs(e.a)*d;return[{name:"circle",type:"element",attributes:{cx:s.x.toString(),cy:s.y.toString(),r:l.toString(),fill:r.is_filled?r.fill_color??r.color:"none",stroke:r.color,"stroke-width":x.toString(),...r.is_dashed&&{"stroke-dasharray":(x*3).toString()},"data-schematic-circle-id":r.schematic_circle_id,...r.schematic_component_id&&{"data-schematic-component-id":r.schematic_component_id}},children:[],value:""}]}function EVt({schRect:r,transform:e,colorMap:a}){let s=mt(e,r.center),l=Math.abs(e.a)*r.width,d=Math.abs(e.d)*r.height,x=r.stroke_width??.02,f=Math.abs(e.a)*x,m=s.x-l/2,D=s.y-d/2;return[{name:"rect",type:"element",attributes:{x:m.toString(),y:D.toString(),width:l.toString(),height:d.toString(),fill:r.is_filled?r.fill_color??r.color:"none",stroke:r.color,"stroke-width":f.toString(),...r.is_dashed&&{"stroke-dasharray":(f*3).toString()},...r.rotation!==0&&{transform:`rotate(${r.rotation} ${s.x} ${s.y})`},"data-schematic-rect-id":r.schematic_rect_id,...r.schematic_component_id&&{"data-schematic-component-id":r.schematic_component_id}},children:[],value:""}]}function vVt({schArc:r,transform:e,colorMap:a}){let s=mt(e,r.center),l=Math.abs(e.a)*r.radius,d=r.stroke_width??.02,x=Math.abs(e.a)*d,f=r.start_angle_degrees*Math.PI/180,m=r.end_angle_degrees*Math.PI/180,D=s.x+l*Math.cos(f),b=s.y+l*Math.sin(f),E=s.x+l*Math.cos(m),A=s.y+l*Math.sin(m),B=r.end_angle_degrees-r.start_angle_degrees;r.direction==="clockwise"&&(B=-B),B<0&&(B+=360);let w=B>180?1:0,P=r.direction==="clockwise"?1:0;return[{name:"path",type:"element",attributes:{d:`M ${D} ${b} A ${l} ${l} 0 ${w} ${P} ${E} ${A}`,fill:"none",stroke:r.color,"stroke-width":x.toString(),...r.is_dashed&&{"stroke-dasharray":(x*3).toString()},"data-schematic-arc-id":r.schematic_arc_id,...r.schematic_component_id&&{"data-schematic-component-id":r.schematic_component_id}},children:[],value:""}]}function CVt(r){let e=[],a=s=>String(s).replace(/"/g,'\\"');for(let s of r){let d=`[data-subcircuit-connectivity-map-key="${a(s)}"]`,x=`g.trace${d}`,f=`g.trace-overlays${d}`,m=`:is(${x}, ${f}):hover`,D=`:is(${x}, ${f})`;e.push(`svg:has(${m}) ${D} { filter: invert(1); }`),e.push(`svg:has(${m}) ${f} .trace-crossing-outline { opacity: 0; }`)}return e.join(`
97
97
  `)}function DBe(r,e){let a=QUt(r),s=a.maxX-a.minX,l=a.maxY-a.minY,d=e?.width??1200,x=e?.height??600,f=e?.colorOverrides,m={...nl,schematic:{...nl.schematic,...f?.schematic??{}}},D=s/l,b=d/x,E;if(D>b){let He=d/D;E={x:0,y:(x-He)/2}}else{let He=x*D;E={x:(d-He)/2,y:0}}let A=HSe([{x:a.minX,y:a.maxY},{x:a.maxX,y:a.maxY},{x:a.maxX,y:a.minY}],[{x:E.x,y:E.y},{x:d-E.x,y:E.y},{x:d-E.x,y:x-E.y}]),B=[];if(B.push({name:"rect",type:"element",attributes:{class:"boundary",x:"0",y:"0",width:d.toString(),height:x.toString()},children:[],value:""}),e?.grid){let He=typeof e.grid=="object"?e.grid:{};B.push(YUt({bounds:a,transform:A,...He}))}let w=[],P=[],j=[],O=new Set,q=[],ee=[],W=[],re=[],L=[],K=[],U=[],J=[],Q=[],de=[];for(let He of r)He.type==="schematic_debug_object"?w.push(...pVt({debugObject:He,transform:A})):He.type==="schematic_component"?(P.push(...lVt({component:He,transform:A,circuitJson:r,colorMap:m})),K.push(...gBe({component:He,transform:A,circuitJson:r}))):He.type==="schematic_box"?re.push(...mVt({schematicBox:He,transform:A,colorMap:m})):He.type==="schematic_trace"?(j.push(...xVt({trace:He,transform:A,colorMap:m})),O.add(He.subcircuit_connectivity_map_key)):He.type==="schematic_net_label"?q.push(...hVt({schNetLabel:He,realToScreenTransform:A,colorMap:m})):He.type==="schematic_text"&&!He.schematic_component_id?ee.push(mBe({elm:He,transform:A,colorMap:m})):He.type==="schematic_voltage_probe"?W.push(...dVt({probe:He,transform:A,colorMap:m})):He.type==="schematic_table"?L.push(...gVt({schematicTable:He,transform:A,colorMap:m,circuitJson:r})):He.type==="schematic_line"?U.push(...bVt({schLine:He,transform:A,colorMap:m})):He.type==="schematic_circle"?J.push(...FVt({schCircle:He,transform:A,colorMap:m})):He.type==="schematic_rect"?Q.push(...EVt({schRect:He,transform:A,colorMap:m})):He.type==="schematic_arc"&&de.push(...vVt({schArc:He,transform:A,colorMap:m}));let oe=j.filter(He=>He.attributes?.["data-layer"]!=="overlay"),Me=j.filter(He=>He.attributes?.["data-layer"]==="overlay");B.push(...w,...oe,...Me,...U,...J,...Q,...de,...P,...K,...q,...ee,...re,...W,...L),e?.labeledPoints&&B.push(HUt({points:e.labeledPoints,transform:A}));let Ne=$F(r),Ge=zF,tt={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:d.toString(),height:x.toString(),style:`background-color: ${m.schematic.background}`,"data-real-to-screen-transform":GSe(A),...Ne&&{"data-software-used-string":Ne},...e?.includeVersion&&{"data-circuit-to-svg-version":Ge}},children:[{name:"style",type:"element",children:[{type:"text",value:`
98
98
  .boundary { fill: ${m.schematic.background}; }
99
99
  .schematic-boundary { fill: none; stroke: #fff; }
@@ -118,7 +118,7 @@ $1`).replace(/>(\s*)(?=<!--\s*\/)/g,"> ")}});var LSe=on(TS=>{"use strict";var nU
118
118
  .pin-number { fill: ${m.schematic.pin_number}; }
119
119
  .port-label { fill: ${m.schematic.reference}; }
120
120
  .component-name { fill: ${m.schematic.reference}; }
121
- `,name:"",attributes:{},children:[]}],value:"",attributes:{}},...B],value:""};return(0,xBe.stringify)(tt)}function AVt(r,e){let{transform:a,layer:s}=e;if(s&&r.layer!==s)return[];let[l,d]=mt(a,[r.x,r.y]);if(r.shape==="rect"||r.shape==="rotated_rect"){let x=r.width*Math.abs(a.a),f=r.height*Math.abs(a.d);return r.shape==="rotated_rect"&&r.ccw_rotation?[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:kS(r.layer),x:(-x/2).toString(),y:(-f/2).toString(),width:x.toString(),height:f.toString(),transform:`translate(${l} ${d}) rotate(${-r.ccw_rotation})`}}]:[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:kS(r.layer),x:(l-x/2).toString(),y:(d-f/2).toString(),width:x.toString(),height:f.toString()}}]}if(r.shape==="pill"){let x=r.width*Math.abs(a.a),f=r.height*Math.abs(a.d),m=r.radius*Math.abs(a.a);return[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:kS(r.layer),x:(l-x/2).toString(),y:(d-f/2).toString(),width:x.toString(),height:f.toString(),rx:m.toString()}}]}if(r.shape==="circle"){let x=r.radius*Math.abs(a.a);return[{name:"circle",type:"element",attributes:{class:"pcb-solder-paste",fill:kS(r.layer),cx:l.toString(),cy:d.toString(),r:x.toString()}}]}}function RVt(r,e){let a=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY,d=Number.NEGATIVE_INFINITY,x=r.filter(J=>J.type==="pcb_board"||J.type==="pcb_solder_paste"&&J.layer===e.layer);for(let J of x)J.type==="pcb_board"?J.outline&&Array.isArray(J.outline)&&J.outline.length>=3?U(J.outline):"center"in J&&"width"in J&&"height"in J&&K(J.center,J.width,J.height):J.type==="pcb_solder_paste"&&"x"in J&&"y"in J&&K({x:J.x,y:J.y},0,0);let f=1,m=l-a+2*f,D=d-s+2*f,b=e.width??800,E=e.height??600,A=b/m,B=E/D,w=Math.min(A,B),P=(b-m*w)/2,j=(E-D*w)/2,O=jn(Ra(P-a*w+f*w,E-j+s*w-f*w),ji(w,-w)),q={transform:O,layer:e.layer,colorMap:ki},ee=x.sort((J,Q)=>(uBe.indexOf(Q.type)??9999)-(uBe.indexOf(J.type)??9999)).flatMap(J=>SVt({elm:J,ctx:q})),W=$F(r),re=zF,L={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:b.toString(),height:E.toString(),...W&&{"data-software-used-string":W},...e.includeVersion&&{"data-circuit-to-svg-version":re}},value:"",children:[{name:"style",type:"element",children:[{type:"text",value:""}]},{name:"rect",type:"element",attributes:{class:"boundary",x:"0",y:"0",fill:"#000",width:b.toString(),height:E.toString()}},BVt(O,a,s,l,d),...ee].filter(J=>J!==null)};try{return(0,yBe.stringify)(L)}catch(J){throw console.error("Error stringifying SVG object:",J),J}function K(J,Q,de){let oe=Q/2,Me=de/2;a=Math.min(a,J.x-oe),s=Math.min(s,J.y-Me),l=Math.max(l,J.x+oe),d=Math.max(d,J.y+Me)}function U(J){for(let Q of J)a=Math.min(a,Q.x),s=Math.min(s,Q.y),l=Math.max(l,Q.x),d=Math.max(d,Q.y)}}function SVt({elm:r,ctx:e}){let{transform:a}=e;switch(r.type){case"pcb_board":return lBe(r,e);case"pcb_solder_paste":return AVt(r,e);default:return[]}}function BVt(r,e,a,s,l){let[d,x]=mt(r,[e,a]),[f,m]=mt(r,[s,l]),D=Math.abs(f-d),b=Math.abs(m-x),E=Math.min(d,f),A=Math.min(x,m);return{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-boundary",fill:"none",stroke:"#fff","stroke-width":"0.3",x:E.toString(),y:A.toString(),width:D.toString(),height:b.toString()}}}var cBe,i1r,pBe,xBe,w1r,N1r,yBe,ki,Jfr,Zfr,Qfr,e1r,yUt,CUt,_Ut,wUt,zF,nBe,IUt,NS,kUt,$g,cd,qW,NF,MF,OF,aBe,nl,sBe,MS,fBe,zg,rx,Og,Lg,WUt,KUt,ui,eVt,tVt,UW,hBe,nVt,aVt,LF,iBe,sVt,iVt,oBe,oVt,uVt,mBe,cVt,fVt,hVt,mVt,gVt,DVt,yVt,gBe,_Vt,uBe,FBe=Sr(()=>{"use strict";cBe=Or(nd(),1);Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Fo();i1r=Or(nd(),1);Ur();ra();Fo();ra();Ur();Ur();Ur();Ur();pBe=Or(nd(),1);ra();Ur();Ur();Ur();Ur();Ur();Ur();Ur();xBe=Or(nd(),1);Ur();Ur();Ur();Ur();Jl();ra();Jl();w1r=Or(nd(),1);Ur();Ur();Ur();ra();Jl();N1r=Or(nd(),1);Ur();Ur();ra();Ur();ra();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Jl();Ur();Ur();ra();Ur();Ur();Ur();Ur();Ur();yBe=Or(nd(),1);Ur();Ur();ki={copper:{top:"rgb(200, 52, 52)",bottom:"rgb(77, 127, 196)"},soldermask:{top:"rgb(200, 52, 52)",bottom:"rgb(77, 127, 196)"},drill:"#FF26E2",silkscreen:{top:"#f2eda1",bottom:"#5da9e9"},boardOutline:"rgba(255, 255, 255, 0.5)",debugComponent:{fill:null,stroke:null}},Jfr=ki.drill,Zfr=ki.silkscreen.top,Qfr=ki.silkscreen.bottom,e1r={top:ki.copper.top,bottom:ki.copper.bottom};yUt={bottom:"rgb(105, 105, 105)",top:"rgb(105, 105, 105)"};CUt=(r,e)=>{let a=ua(e).pcb_smtpad.get(r);if(a&&"x"in a&&"y"in a)return{x:a.x,y:a.y};let s=ua(e).pcb_plated_hole.get(r);return s&&"x"in s&&"y"in s?{x:s.x,y:s.y}:null},_Ut=(r,e,a,s)=>{let l=a.getIdsConnectedToNet(e),d=null,x=1/0;for(let f of l){let m=CUt(f,s);if(m){let D=r.x-m.x,b=r.y-m.y,E=Math.sqrt(D*D+b*b);E>0&&E<x&&(x=E,d=m)}}return d};wUt={name:"circuit-to-svg",type:"module",version:"0.0.195",description:"Convert Circuit JSON to SVG",main:"dist/index.js",files:["dist"],scripts:{start:"cosmos",prepublish:"npm run build",build:"tsup-node ./lib/index.ts --format esm --dts --sourcemap",format:"biome format . --write","format:check":"biome format .",cosmos:"cosmos","cosmos-export":"cosmos-export"},license:"ISC",devDependencies:{"@biomejs/biome":"^1.9.4","@types/bun":"^1.2.8","@vitejs/plugin-react":"5.0.0",biome:"^0.3.3","bun-match-svg":"^0.0.12",esbuild:"^0.20.2","performance-now":"^2.1.0","circuit-json":"^0.0.260",react:"19.1.0","react-cosmos":"7.0.0","react-cosmos-plugin-vite":"7.0.0","react-dom":"19.1.0",tscircuit:"^0.0.654",tsup:"^8.0.2",typescript:"^5.4.5","vite-tsconfig-paths":"^5.0.1"},peerDependencies:{tscircuit:"*"},dependencies:{"@types/node":"^22.5.5","bun-types":"^1.1.40",svgson:"^5.3.1","transformation-matrix":"^2.16.1"}},zF=wUt.version,nBe=["pcb_trace_error","pcb_plated_hole","pcb_fabrication_note_text","pcb_fabrication_note_path","pcb_silkscreen_text","pcb_silkscreen_path","pcb_via","pcb_cutout","pcb_copper_pour","pcb_smtpad","pcb_trace","pcb_component","pcb_board"];IUt=dBe,NS={fill:"none",stroke:"rgb(0,0,0)",strokeOpacity:"0.8",strokeWidthFactor:.2};kUt={pin_number:.15,negated_pin_number:.15*.8,reference_designator:.18,manufacturer_number:.18,net_label:.18,error:.05},$g=(r,e)=>e??kUt[r],cd=(r,e,a)=>Math.abs(r.a)*$g(e,a);qW="rgb(190, 190, 190)";NF="rgb(210, 210, 210)",MF="rgb(190, 190, 190)";OF="rgb(210, 210, 210)";aBe=["pcb_component","pcb_smtpad","pcb_hole","pcb_plated_hole","pcb_board"];nl={"3d_viewer":{background_bottom:"rgb(102, 102, 128)",background_top:"rgb(204, 204, 230)",board:"rgb(51, 43, 23)",copper:"rgb(179, 156, 0)",silkscreen_bottom:"rgb(230, 230, 230)",silkscreen_top:"rgb(230, 230, 230)",soldermask:"rgb(20, 51, 36)",solderpaste:"rgb(128, 128, 128)"},board:{anchor:"rgb(255, 38, 226)",aux_items:"rgb(255, 255, 255)",b_adhes:"rgb(0, 0, 132)",b_crtyd:"rgb(255, 38, 226)",b_fab:"rgb(88, 93, 132)",b_mask:"rgba(2, 255, 238, 0.400)",b_paste:"rgb(0, 194, 194)",b_silks:"rgb(232, 178, 167)",background:"rgb(0, 16, 35)",cmts_user:"rgb(89, 148, 220)",copper:{b:"rgb(77, 127, 196)",f:"rgb(200, 52, 52)",in1:"rgb(127, 200, 127)",in10:"rgb(237, 124, 51)",in11:"rgb(91, 195, 235)",in12:"rgb(247, 111, 142)",in13:"rgb(167, 165, 198)",in14:"rgb(40, 204, 217)",in15:"rgb(232, 178, 167)",in16:"rgb(242, 237, 161)",in17:"rgb(237, 124, 51)",in18:"rgb(91, 195, 235)",in19:"rgb(247, 111, 142)",in2:"rgb(206, 125, 44)",in20:"rgb(167, 165, 198)",in21:"rgb(40, 204, 217)",in22:"rgb(232, 178, 167)",in23:"rgb(242, 237, 161)",in24:"rgb(237, 124, 51)",in25:"rgb(91, 195, 235)",in26:"rgb(247, 111, 142)",in27:"rgb(167, 165, 198)",in28:"rgb(40, 204, 217)",in29:"rgb(232, 178, 167)",in3:"rgb(79, 203, 203)",in30:"rgb(242, 237, 161)",in4:"rgb(219, 98, 139)",in5:"rgb(167, 165, 198)",in6:"rgb(40, 204, 217)",in7:"rgb(232, 178, 167)",in8:"rgb(242, 237, 161)",in9:"rgb(141, 203, 129)"},cursor:"rgb(255, 255, 255)",drc:"rgb(194, 194, 194)",drc_error:"rgba(215, 91, 107, 0.800)",drc_exclusion:"rgb(255, 255, 255)",drc_warning:"rgba(255, 208, 66, 0.902)",dwgs_user:"rgb(194, 194, 194)",eco1_user:"rgb(180, 219, 210)",eco2_user:"rgb(216, 200, 82)",edge_cuts:"rgb(208, 210, 205)",f_adhes:"rgb(132, 0, 132)",f_crtyd:"rgb(255, 0, 245)",f_fab:"rgb(175, 175, 175)",f_mask:"rgba(216, 100, 255, 0.400)",f_paste:"rgba(180, 160, 154, 0.902)",f_silks:"rgb(242, 237, 161)",footprint_text_back:"rgb(0, 0, 132)",footprint_text_front:"rgb(194, 194, 194)",footprint_text_invisible:"rgb(132, 132, 132)",grid:"rgb(132, 132, 132)",grid_axes:"rgb(194, 194, 194)",margin:"rgb(255, 38, 226)",microvia:"rgb(0, 132, 132)",no_connect:"rgb(0, 0, 132)",pad_back:"rgb(77, 127, 196)",pad_front:"rgb(200, 52, 52)",pad_plated_hole:"rgb(194, 194, 0)",pad_through_hole:"rgb(227, 183, 46)",plated_hole:"rgb(26, 196, 210)",ratsnest:"rgba(245, 255, 213, 0.702)",select_overlay:"rgb(4, 255, 67)",through_via:"rgb(236, 236, 236)",user_1:"rgb(194, 194, 194)",user_2:"rgb(89, 148, 220)",user_3:"rgb(180, 219, 210)",user_4:"rgb(216, 200, 82)",user_5:"rgb(194, 194, 194)",user_6:"rgb(89, 148, 220)",user_7:"rgb(180, 219, 210)",user_8:"rgb(216, 200, 82)",user_9:"rgb(232, 178, 167)",via_blind_buried:"rgb(187, 151, 38)",via_hole:"rgb(227, 183, 46)",via_micro:"rgb(0, 132, 132)",via_through:"rgb(236, 236, 236)",worksheet:"rgb(200, 114, 171)"},gerbview:{axes:"rgb(0, 0, 132)",background:"rgb(0, 0, 0)",dcodes:"rgb(255, 255, 255)",grid:"rgb(132, 132, 132)",layers:["rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)","rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)","rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)","rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)"],negative_objects:"rgb(132, 132, 132)",worksheet:"rgb(0, 0, 132)"},meta:{filename:"kicad_2020",name:"KiCad 2020",version:2},palette:["rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)"],schematic:{aux_items:"rgb(46, 46, 46)",background:"rgb(245, 241, 237)",brightened:"rgb(255, 0, 255)",bus:"rgb(0, 0, 132)",bus_junction:"rgb(0, 0, 132)",component_body:"rgb(255, 255, 194)",component_outline:"rgb(132, 0, 0)",cursor:"rgb(15, 15, 15)",erc_error:"rgba(230, 9, 13, 0.800)",erc_warning:"rgba(209, 146, 0, 0.800)",fields:"rgb(132, 0, 132)",grid:"rgb(181, 181, 181)",grid_axes:"rgb(0, 0, 132)",hidden:"rgb(194, 194, 194)",junction:"rgb(0, 150, 0)",label_global:"rgb(132, 0, 0)",label_background:"rgba(255, 255, 255, 0.6)",label_hier:"rgb(114, 86, 0)",label_local:"rgb(15, 15, 15)",net_name:"rgb(132, 132, 132)",no_connect:"rgb(0, 0, 132)",note:"rgb(0, 0, 194)",override_item_colors:!1,pin:"rgb(132, 0, 0)",pin_name:"rgb(0, 100, 100)",pin_number:"rgb(169, 0, 0)",reference:"rgb(0, 100, 100)",shadow:"rgba(102, 179, 255, 0.800)",sheet:"rgb(132, 0, 0)",sheet_background:"rgba(253, 255, 231, 0.000)",sheet_fields:"rgb(132, 0, 132)",sheet_filename:"rgb(114, 86, 0)",sheet_label:"rgb(0, 100, 100)",sheet_name:"rgb(0, 100, 100)",table:"rgb(102, 102, 102)",value:"rgb(0, 100, 100)",wire:"rgb(0, 150, 0)",wire_crossing:"rgb(30, 180, 30)",worksheet:"rgb(132, 0, 0)"}};sBe={0:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},1:{width:13,height:27,ascent:22,descent:5,left:-3,right:9},2:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},3:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},4:{width:13,height:27,ascent:22,descent:5,left:0,right:12},5:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},6:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},7:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},8:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},9:{width:13,height:27,ascent:22,descent:5,left:-1,right:12}," ":{width:7,height:27,ascent:22,descent:5,left:0,right:0},"!":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},'"':{width:9,height:27,ascent:22,descent:5,left:-1,right:7},"#":{width:13,height:27,ascent:22,descent:5,left:0,right:13},$:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},"%":{width:21,height:27,ascent:22,descent:5,left:-1,right:20},"&":{width:16,height:27,ascent:22,descent:5,left:-1,right:15},"'":{width:5,height:27,ascent:22,descent:5,left:-1,right:3},"(":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},")":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"*":{width:9,height:27,ascent:22,descent:5,left:-1,right:8},"+":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},",":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"-":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},".":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"/":{width:7,height:27,ascent:22,descent:5,left:0,right:7},":":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},";":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"<":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},"=":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},">":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},"?":{width:13,height:27,ascent:22,descent:5,left:-1,right:12},"@":{width:24,height:27,ascent:22,descent:5,left:-1,right:23},A:{width:16,height:27,ascent:22,descent:5,left:0,right:16},B:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},C:{width:17,height:27,ascent:22,descent:5,left:-1,right:16},D:{width:17,height:27,ascent:22,descent:5,left:-2,right:16},E:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},F:{width:15,height:27,ascent:22,descent:5,left:-2,right:14},G:{width:19,height:27,ascent:22,descent:5,left:-1,right:17},H:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},I:{width:7,height:27,ascent:22,descent:5,left:-2,right:5},J:{width:12,height:27,ascent:22,descent:5,left:-1,right:10},K:{width:16,height:27,ascent:22,descent:5,left:-2,right:16},L:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},M:{width:20,height:27,ascent:22,descent:5,left:-2,right:18},N:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},O:{width:19,height:27,ascent:22,descent:5,left:-1,right:18},P:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},Q:{width:19,height:27,ascent:22,descent:5,left:-1,right:18},R:{width:17,height:27,ascent:22,descent:5,left:-2,right:17},S:{width:16,height:27,ascent:22,descent:5,left:-1,right:15},T:{width:15,height:27,ascent:22,descent:5,left:-1,right:14},U:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},V:{width:16,height:27,ascent:22,descent:5,left:0,right:16},W:{width:23,height:27,ascent:22,descent:5,left:0,right:22},X:{width:16,height:27,ascent:22,descent:5,left:0,right:16},Y:{width:16,height:27,ascent:22,descent:5,left:0,right:16},Z:{width:15,height:27,ascent:22,descent:5,left:0,right:14},"[":{width:7,height:27,ascent:22,descent:5,left:-2,right:6},"\\":{width:7,height:27,ascent:22,descent:5,left:0,right:7},"]":{width:7,height:27,ascent:22,descent:5,left:0,right:5},"^":{width:11,height:27,ascent:22,descent:5,left:-1,right:11},_:{width:13,height:27,ascent:22,descent:5,left:0,right:14},"`":{width:8,height:27,ascent:22,descent:5,left:-1,right:5},a:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},b:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},c:{width:12,height:27,ascent:22,descent:5,left:-1,right:12},d:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},e:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},f:{width:7,height:27,ascent:22,descent:5,left:0,right:8},g:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},h:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},i:{width:5,height:27,ascent:22,descent:5,left:-2,right:4},j:{width:5,height:27,ascent:22,descent:5,left:1,right:4},k:{width:12,height:27,ascent:22,descent:5,left:-2,right:12},l:{width:5,height:27,ascent:22,descent:5,left:-2,right:4},m:{width:20,height:27,ascent:22,descent:5,left:-2,right:18},n:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},o:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},p:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},q:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},r:{width:8,height:27,ascent:22,descent:5,left:-2,right:8},s:{width:12,height:27,ascent:22,descent:5,left:-1,right:11},t:{width:7,height:27,ascent:22,descent:5,left:0,right:6},u:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},v:{width:12,height:27,ascent:22,descent:5,left:0,right:12},w:{width:17,height:27,ascent:22,descent:5,left:0,right:17},x:{width:12,height:27,ascent:22,descent:5,left:0,right:12},y:{width:12,height:27,ascent:22,descent:5,left:0,right:12},z:{width:12,height:27,ascent:22,descent:5,left:0,right:11},"{":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"|":{width:6,height:27,ascent:22,descent:5,left:-2,right:4},"}":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"~":{width:14,height:27,ascent:22,descent:5,left:-1,right:13}},MS=r=>{if(!r)return 0;let e=0;for(let a of r){let s=sBe[a];s?e+=s.width:e+=sBe["?"].width}return e/27},fBe=(r,e)=>{if(r.column_widths&&r.column_widths.length>0&&r.row_heights&&r.row_heights.length>0){let b=E=>typeof E=="number"?E:E.endsWith("mm")?parseFloat(E):E.endsWith("in")?parseFloat(E)*25.4:parseFloat(E);return{column_widths:r.column_widths.map(b),row_heights:r.row_heights.map(b)}}let a=e.filter(b=>b.type==="schematic_table_cell"&&b.schematic_table_id===r.schematic_table_id);if(a.length===0)return{column_widths:[],row_heights:[]};let s=a.reduce((b,E)=>Math.max(b,E.end_column_index),-1)+1,l=a.reduce((b,E)=>Math.max(b,E.end_row_index),-1)+1,{cell_padding:d=.2}=r,x=new Array(s).fill(0),f=new Array(l).fill(0),m={},D={};for(let b of a){let E=$g("reference_designator",b.font_size),B=MS(b.text??"")*E+2*d,w=E*1.2+2*d,P=`${b.start_row_index}-${b.start_column_index}`;m[P]=B,D[P]=w}for(let b=0;b<l;b++)for(let E=0;E<s;E++){let A=`${b}-${E}`;m[A]&&m[A]>x[E]&&(x[E]=m[A]),D[A]&&D[A]>f[b]&&(f[b]=D[A])}for(let b of a){if(b.start_column_index===b.end_column_index&&b.start_row_index===b.end_row_index)continue;let E=`${b.start_row_index}-${b.start_column_index}`,A=m[E],B=D[E];if(A===void 0||B===void 0)continue;let w=0;for(let j=b.start_column_index;j<=b.end_column_index;j++)w+=x[j];if(A>w){let O=(A-w)/(b.end_column_index-b.start_column_index+1);for(let q=b.start_column_index;q<=b.end_column_index;q++)x[q]+=O}let P=0;for(let j=b.start_row_index;j<=b.end_row_index;j++)P+=f[j];if(B>P){let O=(B-P)/(b.end_row_index-b.start_row_index+1);for(let q=b.start_row_index;q<=b.end_row_index;q++)f[q]+=O}}return{column_widths:x,row_heights:f}},zg=r=>{switch(r){case"top":return{x:0,y:-1};case"bottom":return{x:0,y:1};case"left":return{x:1,y:0};case"right":return{x:-1,y:0}}throw new Error(`Invalid side: ${r}`)},rx=.3,Og=.3,Lg=.06,WUt={top_left:"start",top_right:"end",middle_left:"start",middle_right:"end",bottom_left:"start",bottom_right:"end",center:"middle",middle_top:"middle",middle_bottom:"middle"},KUt={top_left:"hanging",top_right:"hanging",bottom_left:"ideographic",bottom_right:"ideographic",center:"middle",middle_left:"middle",middle_right:"middle",middle_top:"hanging",middle_bottom:"ideographic"};ui=r=>Math.abs(r.a)*.02,eVt=(r,e)=>{let a=r<0?r+2*Math.PI:r,s=e<0?e+2*Math.PI:e,l=Math.abs(a-s);return l>Math.PI&&(l=2*Math.PI-l),l},tVt=({schPorts:r,symbol:e,schComponent:a})=>{let s=r.map(f=>{let m=f.center.x-a.center.x,D=f.center.y-a.center.y;return{port:f,angle:Math.atan2(D,m)}}),l=e.ports.map(f=>{let m=f.x-e.center.x,D=f.y-e.center.y;return{port:f,angle:Math.atan2(D,m)}});s.sort((f,m)=>f.angle-m.angle),l.sort((f,m)=>f.angle-m.angle);let d=[],x=new Set;for(let f of s){let m=null;for(let D of l){if(x.has(D.port))continue;let b=eVt(f.angle,D.angle);(m===null||b<m.angleDiff)&&(m={symbolPort:D.port,angleDiff:b})}m&&m.angleDiff<Math.PI/4&&(d.push({schPort:f.port,symbolPort:m.symbolPort}),x.add(m.symbolPort))}return d};UW=({text:r,realCenter:e,realToScreenTransform:a})=>{let s=mt(a,e);return{type:"element",name:"text",value:"",attributes:{x:s.x.toString(),y:s.y.toString(),fill:"red","text-anchor":"middle","dominant-baseline":"middle","font-family":"sans-serif","font-size":`${cd(a,"error")}px`},children:[{type:"text",value:r,name:"",attributes:{},children:[]}]}},hBe=(r,e)=>{for(let a of r){if(a.type!=="source_trace")continue;let s=a;if(Array.isArray(s.connected_source_port_ids)&&s.connected_source_port_ids.includes(e))return!0}return!1},nVt={top_left:"start",top_right:"end",middle_left:"start",middle_right:"end",bottom_left:"start",bottom_right:"end",center:"middle",middle_top:"middle",middle_bottom:"middle"},aVt=({component:r,transform:e,circuitJson:a,colorMap:s})=>{let l=[],d=ks[r.symbol_name];if(!d)return[UW({text:`Symbol not found: ${r.symbol_name}`,realCenter:r.center,realToScreenTransform:e})];let x=ua(a).schematic_port.list({schematic_component_id:r.schematic_component_id}),f=ua(a).source_component.get(r.source_component_id),m=tVt({schPorts:x,symbol:d,schComponent:r});if(!m[0])return[UW({text:`Could not match ports for symbol ${r.symbol_name}`,realCenter:r.center,realToScreenTransform:e})];let D=rVt(m[1]?.symbolPort??d.center,m[1]?.schPort.center??r.center,m[0].symbolPort,m[0].schPort.center),b=d.primitives.filter(U=>U.type==="path"),E=d.primitives.filter(U=>U.type==="text"),A=d.primitives.filter(U=>U.type==="circle"),B=d.primitives.filter(U=>U.type==="box"),w=new Set;for(let U of m)hBe(a,U.schPort.source_port_id)&&w.add(U.symbolPort);let P={minX:Math.min(...b.flatMap(U=>U.points.map(J=>J.x))),maxX:Math.max(...b.flatMap(U=>U.points.map(J=>J.x))),minY:Math.min(...b.flatMap(U=>U.points.map(J=>J.y))),maxY:Math.max(...b.flatMap(U=>U.points.map(J=>J.y)))},[j,O]=mt(jn(e,D),[P.minX,P.minY]),[q,ee]=mt(jn(e,D),[P.maxX,P.maxY]),W=Math.abs(ee-O),re=Math.min(O,ee),L=Math.abs(q-j),K=Math.min(j,q);l.push({name:"rect",type:"element",value:"",attributes:{class:"component-overlay",x:K.toString(),y:re.toString(),width:L.toString(),height:W.toString(),fill:"transparent"},children:[]});for(let U of b){let{points:J,color:Q,closed:de,fill:oe}=U;l.push({type:"element",name:"path",attributes:{d:J.map((Me,Ne)=>{let[Ge,tt]=mt(jn(e,D),[Me.x,Me.y]);return`${Ne===0?"M":"L"} ${Ge} ${tt}`}).join(" ")+(de?" Z":""),stroke:s.schematic.component_outline,fill:"none","stroke-width":`${ui(e)}px`,"stroke-linecap":"round"},value:"",children:[]})}for(let U of E){let J=mt(jn(e,D),U),Q="";U.text==="{REF}"?Q=f?.name??"":U.text==="{VAL}"&&(Q=r.symbol_display_value??"");let Me=Math.abs(P.maxY-P.minY)*.1,Ne=Math.abs(D.a),Ge=0;U.anchor.includes("bottom")?Ge=Me*Ne:U.anchor.includes("top")&&(Ge=-Me*Ne);let tt=U.anchor.includes("bottom")?"auto":U.anchor.includes("top")?"hanging":"middle",He=U.text==="{REF}";l.push({name:"text",type:"element",attributes:{x:J.x.toString(),y:(J.y+Ge).toString(),...He?{stroke:s.schematic.background,"stroke-width":`${ui(e)}px`,"paint-order":"stroke"}:{},fill:s.schematic.label_local,"font-family":"sans-serif","text-anchor":nVt[U.anchor],"dominant-baseline":tt,"font-size":`${cd(e,"reference_designator")}px`},value:"",children:[{type:"text",value:Q,name:"",attributes:{},children:[]}]})}for(let U of B){let J=mt(jn(e,D),U),Q=jn(e,D).a;l.push({name:"rect",type:"element",attributes:{x:J.x.toString(),y:J.y.toString(),width:(U.width*Q).toString(),height:(U.height*Q).toString(),fill:"red"},value:"",children:[]})}for(let U of d.ports){if(w.has(U))continue;let J=mt(jn(e,D),U);l.push({type:"element",name:"circle",attributes:{cx:J.x.toString(),cy:J.y.toString(),r:`${Math.abs(e.a)*.02}px`,"stroke-width":`${ui(e)}px`,fill:"none",stroke:s.schematic.component_outline},value:"",children:[]})}for(let U of A){let J=mt(jn(e,D),U),Q=Math.abs(U.radius*e.a);l.push({type:"element",name:"circle",attributes:{cx:J.x.toString(),cy:J.y.toString(),r:`${Q}px`,"stroke-width":`${ui(e)}px`,fill:"none",stroke:s.schematic.component_outline},value:"",children:[]})}return l},LF=.02,iBe=(r,e,a,s,l)=>{let d=Math.PI/6,x={x:r.x-a*Math.cos(e-d),y:r.y-a*Math.sin(e-d)},f={x:r.x-a*Math.cos(e+d),y:r.y-a*Math.sin(e+d)};return{name:"polygon",type:"element",attributes:{points:`${r.x},${r.y} ${x.x},${x.y} ${f.x},${f.y}`,fill:"white",stroke:s,"stroke-width":`${l}px`},value:"",children:[]}},sVt=({schPort:r,schComponent:e,transform:a,circuitJson:s})=>{let l=[],d=ua(s).source_port.get(r.source_port_id),x={x:r.center.x,y:r.center.y},f=r.distance_from_component_edge??.4;switch(r.side_of_component){case"left":x.x+=f;break;case"right":x.x-=f;break;case"top":x.y-=f;break;case"bottom":x.y+=f;break}let m=mt(a,r.center),D=mt(a,x),b={...r.center};switch(r.side_of_component){case"left":b.x+=LF;break;case"right":b.x-=LF;break;case"top":b.y-=LF;break;case"bottom":b.y+=LF;break}let E=mt(a,b);l.push({name:"line",type:"element",attributes:{class:"component-pin",x1:E.x.toString(),y1:E.y.toString(),x2:D.x.toString(),y2:D.y.toString(),"stroke-width":`${ui(a)}px`},value:"",children:[]});let A=hBe(s,r.source_port_id),B=Math.abs(a.a)*LF,w=[];A||w.push({name:"circle",type:"element",attributes:{class:"component-pin",cx:m.x.toString(),cy:m.y.toString(),r:B.toString(),"stroke-width":`${ui(a)}px`},value:"",children:[]}),w.push({name:"rect",type:"element",attributes:{x:(m.x-B).toString(),y:(m.y-B).toString(),width:(B*2).toString(),height:(B*2).toString(),opacity:"0"},value:"",children:[]}),l.push({name:"g",type:"element",value:"",attributes:{"data-schematic-port-id":r.source_port_id},children:w});let{has_input_arrow:P,has_output_arrow:j}=r;if((P||j)&&r.side_of_component){let O=Math.abs(a.a)*.1,q=nl.schematic.component_outline,ee=O*Math.cos(Math.PI/6),W=ui(a)/3,re=0,L=0;r.side_of_component==="left"?(re=0,L=Math.PI):r.side_of_component==="right"?(re=Math.PI,L=0):r.side_of_component==="top"?(re=Math.PI/2,L=-Math.PI/2):r.side_of_component==="bottom"&&(re=-Math.PI/2,L=Math.PI/2);let K=P&&j,U={...D},J={...D};if(K){let Q=ee;r.side_of_component==="left"?J.x-=Q:r.side_of_component==="right"?J.x+=Q:r.side_of_component==="top"?J.y-=Q:r.side_of_component==="bottom"&&(J.y+=Q)}if(P&&l.push(iBe(U,re,O,q,W)),j){let Q={x:J.x+O*Math.cos(L),y:J.y+O*Math.sin(L)};l.push(iBe(Q,L,O,q,W))}}return l},iVt=r=>{let e=[],{schPort:a,schComponent:s,transform:l,circuitJson:d}=r,x={x:a.center.x,y:a.center.y};if(!a.side_of_component)return[];let f=zg(a.side_of_component),m=a.distance_from_component_edge??.4;x.x+=f.x*m/2,x.y+=f.y*m/2,a.side_of_component==="top"||a.side_of_component==="bottom"?x.x-=.02:x.y+=.02;let D=mt(l,x);return e.push({name:"text",type:"element",attributes:{class:"pin-number",x:D.x.toString(),y:D.y.toString(),style:"font-family: sans-serif;",fill:nl.schematic.pin_number,"text-anchor":"middle","dominant-baseline":"auto","font-size":`${cd(l,"pin_number")}px`,transform:a.side_of_component==="top"||a.side_of_component==="bottom"?`rotate(-90 ${D.x} ${D.y})`:""},children:[{type:"text",value:a.pin_number?.toString()||"",name:"",attributes:{},children:[]}],value:""}),e},oBe=.1,oVt=r=>{let e=[],{schPort:a,schComponent:s,transform:l,circuitJson:d}=r,x={x:a.center.x,y:a.center.y};if(!a.side_of_component)return[];let f=zg(a.side_of_component),m=a.distance_from_component_edge??.4;x.x+=f.x*(m+oBe),x.y+=f.y*(m+oBe);let D=mt(l,x),b=a.display_pin_label??s.port_labels?.[`${a.pin_number}`];if(!b)return[];let E=b.startsWith("N_"),A=E?b.slice(2):b,B=cd(l,E?"negated_pin_number":"pin_number");return e.push({name:"text",type:"element",attributes:{class:"pin-number",x:D.x.toString(),y:D.y.toString(),style:`font-family: sans-serif;${E?" text-decoration: overline;":""}`,fill:nl.schematic.pin_number,"text-anchor":a.side_of_component==="left"||a.side_of_component==="bottom"?"start":"end","dominant-baseline":"middle","font-size":`${B}px`,transform:a.side_of_component==="top"||a.side_of_component==="bottom"?`rotate(-90 ${D.x} ${D.y})`:""},children:[{type:"text",value:A||"",name:"",attributes:{},children:[]}],value:""}),e},uVt=r=>{let e=[],{schPort:a,schComponent:s,transform:l,circuitJson:d}=r;return e.push(...sVt(r)),e.push(...iVt(r)),e.push(...oVt(r)),e},mBe=({elm:r,transform:e,colorMap:a})=>{let s=mt(e,r.position),l={center:"middle",center_right:"end",bottom_left:"start",bottom_center:"middle",bottom_right:"end",left:"start",right:"end",top:"middle",bottom:"middle",top_left:"start",top_center:"middle",top_right:"end",center_left:"start"},d={center:"middle",center_right:"middle",bottom_left:"ideographic",bottom_center:"ideographic",bottom_right:"ideographic",left:"middle",right:"middle",top:"hanging",bottom:"ideographic",top_left:"hanging",top_center:"hanging",top_right:"hanging",center_left:"middle"},x=r.text.split(`
121
+ `,name:"",attributes:{},children:[]}],value:"",attributes:{}},...B],value:""};return(0,xBe.stringify)(tt)}function AVt(r,e){let{transform:a,layer:s}=e;if(s&&r.layer!==s)return[];let[l,d]=mt(a,[r.x,r.y]);if(r.shape==="rect"||r.shape==="rotated_rect"){let x=r.width*Math.abs(a.a),f=r.height*Math.abs(a.d);return r.shape==="rotated_rect"&&r.ccw_rotation?[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:kS(r.layer),x:(-x/2).toString(),y:(-f/2).toString(),width:x.toString(),height:f.toString(),transform:`translate(${l} ${d}) rotate(${-r.ccw_rotation})`}}]:[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:kS(r.layer),x:(l-x/2).toString(),y:(d-f/2).toString(),width:x.toString(),height:f.toString()}}]}if(r.shape==="pill"){let x=r.width*Math.abs(a.a),f=r.height*Math.abs(a.d),m=r.radius*Math.abs(a.a);return[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:kS(r.layer),x:(l-x/2).toString(),y:(d-f/2).toString(),width:x.toString(),height:f.toString(),rx:m.toString()}}]}if(r.shape==="circle"){let x=r.radius*Math.abs(a.a);return[{name:"circle",type:"element",attributes:{class:"pcb-solder-paste",fill:kS(r.layer),cx:l.toString(),cy:d.toString(),r:x.toString()}}]}}function RVt(r,e){let a=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY,d=Number.NEGATIVE_INFINITY,x=r.filter(J=>J.type==="pcb_board"||J.type==="pcb_solder_paste"&&J.layer===e.layer);for(let J of x)J.type==="pcb_board"?J.outline&&Array.isArray(J.outline)&&J.outline.length>=3?U(J.outline):"center"in J&&"width"in J&&"height"in J&&K(J.center,J.width,J.height):J.type==="pcb_solder_paste"&&"x"in J&&"y"in J&&K({x:J.x,y:J.y},0,0);let f=1,m=l-a+2*f,D=d-s+2*f,b=e.width??800,E=e.height??600,A=b/m,B=E/D,w=Math.min(A,B),P=(b-m*w)/2,j=(E-D*w)/2,O=jn(Ra(P-a*w+f*w,E-j+s*w-f*w),ji(w,-w)),q={transform:O,layer:e.layer,colorMap:ki},ee=x.sort((J,Q)=>(uBe.indexOf(Q.type)??9999)-(uBe.indexOf(J.type)??9999)).flatMap(J=>SVt({elm:J,ctx:q})),W=$F(r),re=zF,L={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:b.toString(),height:E.toString(),...W&&{"data-software-used-string":W},...e.includeVersion&&{"data-circuit-to-svg-version":re}},value:"",children:[{name:"style",type:"element",children:[{type:"text",value:""}]},{name:"rect",type:"element",attributes:{class:"boundary",x:"0",y:"0",fill:"#000",width:b.toString(),height:E.toString()}},BVt(O,a,s,l,d),...ee].filter(J=>J!==null)};try{return(0,yBe.stringify)(L)}catch(J){throw console.error("Error stringifying SVG object:",J),J}function K(J,Q,de){let oe=Q/2,Me=de/2;a=Math.min(a,J.x-oe),s=Math.min(s,J.y-Me),l=Math.max(l,J.x+oe),d=Math.max(d,J.y+Me)}function U(J){for(let Q of J)a=Math.min(a,Q.x),s=Math.min(s,Q.y),l=Math.max(l,Q.x),d=Math.max(d,Q.y)}}function SVt({elm:r,ctx:e}){let{transform:a}=e;switch(r.type){case"pcb_board":return lBe(r,e);case"pcb_solder_paste":return AVt(r,e);default:return[]}}function BVt(r,e,a,s,l){let[d,x]=mt(r,[e,a]),[f,m]=mt(r,[s,l]),D=Math.abs(f-d),b=Math.abs(m-x),E=Math.min(d,f),A=Math.min(x,m);return{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-boundary",fill:"none",stroke:"#fff","stroke-width":"0.3",x:E.toString(),y:A.toString(),width:D.toString(),height:b.toString()}}}var cBe,i1r,pBe,xBe,w1r,N1r,yBe,ki,Jfr,Zfr,Qfr,e1r,yUt,CUt,_Ut,wUt,zF,nBe,IUt,NS,kUt,$g,cd,qW,NF,MF,OF,aBe,nl,sBe,MS,fBe,zg,rx,Og,Lg,WUt,KUt,ui,eVt,tVt,UW,hBe,nVt,aVt,LF,iBe,sVt,iVt,oBe,oVt,uVt,mBe,cVt,fVt,hVt,mVt,gVt,DVt,yVt,gBe,_Vt,uBe,FBe=Sr(()=>{"use strict";cBe=Or(nd(),1);Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Fo();i1r=Or(nd(),1);Ur();ra();Fo();ra();Ur();Ur();Ur();Ur();pBe=Or(nd(),1);ra();Ur();Ur();Ur();Ur();Ur();Ur();Ur();xBe=Or(nd(),1);Ur();Ur();Ur();Ur();Jl();ra();Jl();w1r=Or(nd(),1);Ur();Ur();Ur();ra();Jl();N1r=Or(nd(),1);Ur();Ur();ra();Ur();ra();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Ur();Jl();Ur();Ur();ra();Ur();Ur();Ur();Ur();Ur();yBe=Or(nd(),1);Ur();Ur();ki={copper:{top:"rgb(200, 52, 52)",bottom:"rgb(77, 127, 196)"},soldermask:{top:"rgb(200, 52, 52)",bottom:"rgb(77, 127, 196)"},drill:"#FF26E2",silkscreen:{top:"#f2eda1",bottom:"#5da9e9"},boardOutline:"rgba(255, 255, 255, 0.5)",debugComponent:{fill:null,stroke:null}},Jfr=ki.drill,Zfr=ki.silkscreen.top,Qfr=ki.silkscreen.bottom,e1r={top:ki.copper.top,bottom:ki.copper.bottom};yUt={bottom:"rgb(105, 105, 105)",top:"rgb(105, 105, 105)"};CUt=(r,e)=>{let a=ua(e).pcb_smtpad.get(r);if(a&&"x"in a&&"y"in a)return{x:a.x,y:a.y};let s=ua(e).pcb_plated_hole.get(r);return s&&"x"in s&&"y"in s?{x:s.x,y:s.y}:null},_Ut=(r,e,a,s)=>{let l=a.getIdsConnectedToNet(e),d=null,x=1/0;for(let f of l){let m=CUt(f,s);if(m){let D=r.x-m.x,b=r.y-m.y,E=Math.sqrt(D*D+b*b);E>0&&E<x&&(x=E,d=m)}}return d};wUt={name:"circuit-to-svg",type:"module",version:"0.0.196",description:"Convert Circuit JSON to SVG",main:"dist/index.js",files:["dist"],scripts:{start:"cosmos",prepublish:"npm run build",build:"tsup-node ./lib/index.ts --format esm --dts --sourcemap",format:"biome format . --write","format:check":"biome format .",cosmos:"cosmos","cosmos-export":"cosmos-export"},license:"ISC",devDependencies:{"@biomejs/biome":"^1.9.4","@types/bun":"^1.2.8","@vitejs/plugin-react":"5.0.0",biome:"^0.3.3","bun-match-svg":"^0.0.12",esbuild:"^0.20.2","performance-now":"^2.1.0","circuit-json":"^0.0.261",react:"19.1.0","react-cosmos":"7.0.0","react-cosmos-plugin-vite":"7.0.0","react-dom":"19.1.0",tscircuit:"^0.0.654",tsup:"^8.0.2",typescript:"^5.4.5","vite-tsconfig-paths":"^5.0.1"},peerDependencies:{tscircuit:"*"},dependencies:{"@types/node":"^22.5.5","bun-types":"^1.1.40",svgson:"^5.3.1","transformation-matrix":"^2.16.1"}},zF=wUt.version,nBe=["pcb_trace_error","pcb_plated_hole","pcb_fabrication_note_text","pcb_fabrication_note_path","pcb_silkscreen_text","pcb_silkscreen_path","pcb_via","pcb_cutout","pcb_copper_pour","pcb_smtpad","pcb_trace","pcb_component","pcb_board"];IUt=dBe,NS={fill:"none",stroke:"rgb(0,0,0)",strokeOpacity:"0.8",strokeWidthFactor:.2};kUt={pin_number:.15,negated_pin_number:.15*.8,reference_designator:.18,manufacturer_number:.18,net_label:.18,error:.05},$g=(r,e)=>e??kUt[r],cd=(r,e,a)=>Math.abs(r.a)*$g(e,a);qW="rgb(190, 190, 190)";NF="rgb(210, 210, 210)",MF="rgb(190, 190, 190)";OF="rgb(210, 210, 210)";aBe=["pcb_component","pcb_smtpad","pcb_hole","pcb_plated_hole","pcb_board"];nl={"3d_viewer":{background_bottom:"rgb(102, 102, 128)",background_top:"rgb(204, 204, 230)",board:"rgb(51, 43, 23)",copper:"rgb(179, 156, 0)",silkscreen_bottom:"rgb(230, 230, 230)",silkscreen_top:"rgb(230, 230, 230)",soldermask:"rgb(20, 51, 36)",solderpaste:"rgb(128, 128, 128)"},board:{anchor:"rgb(255, 38, 226)",aux_items:"rgb(255, 255, 255)",b_adhes:"rgb(0, 0, 132)",b_crtyd:"rgb(255, 38, 226)",b_fab:"rgb(88, 93, 132)",b_mask:"rgba(2, 255, 238, 0.400)",b_paste:"rgb(0, 194, 194)",b_silks:"rgb(232, 178, 167)",background:"rgb(0, 16, 35)",cmts_user:"rgb(89, 148, 220)",copper:{b:"rgb(77, 127, 196)",f:"rgb(200, 52, 52)",in1:"rgb(127, 200, 127)",in10:"rgb(237, 124, 51)",in11:"rgb(91, 195, 235)",in12:"rgb(247, 111, 142)",in13:"rgb(167, 165, 198)",in14:"rgb(40, 204, 217)",in15:"rgb(232, 178, 167)",in16:"rgb(242, 237, 161)",in17:"rgb(237, 124, 51)",in18:"rgb(91, 195, 235)",in19:"rgb(247, 111, 142)",in2:"rgb(206, 125, 44)",in20:"rgb(167, 165, 198)",in21:"rgb(40, 204, 217)",in22:"rgb(232, 178, 167)",in23:"rgb(242, 237, 161)",in24:"rgb(237, 124, 51)",in25:"rgb(91, 195, 235)",in26:"rgb(247, 111, 142)",in27:"rgb(167, 165, 198)",in28:"rgb(40, 204, 217)",in29:"rgb(232, 178, 167)",in3:"rgb(79, 203, 203)",in30:"rgb(242, 237, 161)",in4:"rgb(219, 98, 139)",in5:"rgb(167, 165, 198)",in6:"rgb(40, 204, 217)",in7:"rgb(232, 178, 167)",in8:"rgb(242, 237, 161)",in9:"rgb(141, 203, 129)"},cursor:"rgb(255, 255, 255)",drc:"rgb(194, 194, 194)",drc_error:"rgba(215, 91, 107, 0.800)",drc_exclusion:"rgb(255, 255, 255)",drc_warning:"rgba(255, 208, 66, 0.902)",dwgs_user:"rgb(194, 194, 194)",eco1_user:"rgb(180, 219, 210)",eco2_user:"rgb(216, 200, 82)",edge_cuts:"rgb(208, 210, 205)",f_adhes:"rgb(132, 0, 132)",f_crtyd:"rgb(255, 0, 245)",f_fab:"rgb(175, 175, 175)",f_mask:"rgba(216, 100, 255, 0.400)",f_paste:"rgba(180, 160, 154, 0.902)",f_silks:"rgb(242, 237, 161)",footprint_text_back:"rgb(0, 0, 132)",footprint_text_front:"rgb(194, 194, 194)",footprint_text_invisible:"rgb(132, 132, 132)",grid:"rgb(132, 132, 132)",grid_axes:"rgb(194, 194, 194)",margin:"rgb(255, 38, 226)",microvia:"rgb(0, 132, 132)",no_connect:"rgb(0, 0, 132)",pad_back:"rgb(77, 127, 196)",pad_front:"rgb(200, 52, 52)",pad_plated_hole:"rgb(194, 194, 0)",pad_through_hole:"rgb(227, 183, 46)",plated_hole:"rgb(26, 196, 210)",ratsnest:"rgba(245, 255, 213, 0.702)",select_overlay:"rgb(4, 255, 67)",through_via:"rgb(236, 236, 236)",user_1:"rgb(194, 194, 194)",user_2:"rgb(89, 148, 220)",user_3:"rgb(180, 219, 210)",user_4:"rgb(216, 200, 82)",user_5:"rgb(194, 194, 194)",user_6:"rgb(89, 148, 220)",user_7:"rgb(180, 219, 210)",user_8:"rgb(216, 200, 82)",user_9:"rgb(232, 178, 167)",via_blind_buried:"rgb(187, 151, 38)",via_hole:"rgb(227, 183, 46)",via_micro:"rgb(0, 132, 132)",via_through:"rgb(236, 236, 236)",worksheet:"rgb(200, 114, 171)"},gerbview:{axes:"rgb(0, 0, 132)",background:"rgb(0, 0, 0)",dcodes:"rgb(255, 255, 255)",grid:"rgb(132, 132, 132)",layers:["rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)","rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)","rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)","rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)"],negative_objects:"rgb(132, 132, 132)",worksheet:"rgb(0, 0, 132)"},meta:{filename:"kicad_2020",name:"KiCad 2020",version:2},palette:["rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)"],schematic:{aux_items:"rgb(46, 46, 46)",background:"rgb(245, 241, 237)",brightened:"rgb(255, 0, 255)",bus:"rgb(0, 0, 132)",bus_junction:"rgb(0, 0, 132)",component_body:"rgb(255, 255, 194)",component_outline:"rgb(132, 0, 0)",cursor:"rgb(15, 15, 15)",erc_error:"rgba(230, 9, 13, 0.800)",erc_warning:"rgba(209, 146, 0, 0.800)",fields:"rgb(132, 0, 132)",grid:"rgb(181, 181, 181)",grid_axes:"rgb(0, 0, 132)",hidden:"rgb(194, 194, 194)",junction:"rgb(0, 150, 0)",label_global:"rgb(132, 0, 0)",label_background:"rgba(255, 255, 255, 0.6)",label_hier:"rgb(114, 86, 0)",label_local:"rgb(15, 15, 15)",net_name:"rgb(132, 132, 132)",no_connect:"rgb(0, 0, 132)",note:"rgb(0, 0, 194)",override_item_colors:!1,pin:"rgb(132, 0, 0)",pin_name:"rgb(0, 100, 100)",pin_number:"rgb(169, 0, 0)",reference:"rgb(0, 100, 100)",shadow:"rgba(102, 179, 255, 0.800)",sheet:"rgb(132, 0, 0)",sheet_background:"rgba(253, 255, 231, 0.000)",sheet_fields:"rgb(132, 0, 132)",sheet_filename:"rgb(114, 86, 0)",sheet_label:"rgb(0, 100, 100)",sheet_name:"rgb(0, 100, 100)",table:"rgb(102, 102, 102)",value:"rgb(0, 100, 100)",wire:"rgb(0, 150, 0)",wire_crossing:"rgb(30, 180, 30)",worksheet:"rgb(132, 0, 0)"}};sBe={0:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},1:{width:13,height:27,ascent:22,descent:5,left:-3,right:9},2:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},3:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},4:{width:13,height:27,ascent:22,descent:5,left:0,right:12},5:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},6:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},7:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},8:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},9:{width:13,height:27,ascent:22,descent:5,left:-1,right:12}," ":{width:7,height:27,ascent:22,descent:5,left:0,right:0},"!":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},'"':{width:9,height:27,ascent:22,descent:5,left:-1,right:7},"#":{width:13,height:27,ascent:22,descent:5,left:0,right:13},$:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},"%":{width:21,height:27,ascent:22,descent:5,left:-1,right:20},"&":{width:16,height:27,ascent:22,descent:5,left:-1,right:15},"'":{width:5,height:27,ascent:22,descent:5,left:-1,right:3},"(":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},")":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"*":{width:9,height:27,ascent:22,descent:5,left:-1,right:8},"+":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},",":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"-":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},".":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"/":{width:7,height:27,ascent:22,descent:5,left:0,right:7},":":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},";":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"<":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},"=":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},">":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},"?":{width:13,height:27,ascent:22,descent:5,left:-1,right:12},"@":{width:24,height:27,ascent:22,descent:5,left:-1,right:23},A:{width:16,height:27,ascent:22,descent:5,left:0,right:16},B:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},C:{width:17,height:27,ascent:22,descent:5,left:-1,right:16},D:{width:17,height:27,ascent:22,descent:5,left:-2,right:16},E:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},F:{width:15,height:27,ascent:22,descent:5,left:-2,right:14},G:{width:19,height:27,ascent:22,descent:5,left:-1,right:17},H:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},I:{width:7,height:27,ascent:22,descent:5,left:-2,right:5},J:{width:12,height:27,ascent:22,descent:5,left:-1,right:10},K:{width:16,height:27,ascent:22,descent:5,left:-2,right:16},L:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},M:{width:20,height:27,ascent:22,descent:5,left:-2,right:18},N:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},O:{width:19,height:27,ascent:22,descent:5,left:-1,right:18},P:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},Q:{width:19,height:27,ascent:22,descent:5,left:-1,right:18},R:{width:17,height:27,ascent:22,descent:5,left:-2,right:17},S:{width:16,height:27,ascent:22,descent:5,left:-1,right:15},T:{width:15,height:27,ascent:22,descent:5,left:-1,right:14},U:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},V:{width:16,height:27,ascent:22,descent:5,left:0,right:16},W:{width:23,height:27,ascent:22,descent:5,left:0,right:22},X:{width:16,height:27,ascent:22,descent:5,left:0,right:16},Y:{width:16,height:27,ascent:22,descent:5,left:0,right:16},Z:{width:15,height:27,ascent:22,descent:5,left:0,right:14},"[":{width:7,height:27,ascent:22,descent:5,left:-2,right:6},"\\":{width:7,height:27,ascent:22,descent:5,left:0,right:7},"]":{width:7,height:27,ascent:22,descent:5,left:0,right:5},"^":{width:11,height:27,ascent:22,descent:5,left:-1,right:11},_:{width:13,height:27,ascent:22,descent:5,left:0,right:14},"`":{width:8,height:27,ascent:22,descent:5,left:-1,right:5},a:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},b:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},c:{width:12,height:27,ascent:22,descent:5,left:-1,right:12},d:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},e:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},f:{width:7,height:27,ascent:22,descent:5,left:0,right:8},g:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},h:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},i:{width:5,height:27,ascent:22,descent:5,left:-2,right:4},j:{width:5,height:27,ascent:22,descent:5,left:1,right:4},k:{width:12,height:27,ascent:22,descent:5,left:-2,right:12},l:{width:5,height:27,ascent:22,descent:5,left:-2,right:4},m:{width:20,height:27,ascent:22,descent:5,left:-2,right:18},n:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},o:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},p:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},q:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},r:{width:8,height:27,ascent:22,descent:5,left:-2,right:8},s:{width:12,height:27,ascent:22,descent:5,left:-1,right:11},t:{width:7,height:27,ascent:22,descent:5,left:0,right:6},u:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},v:{width:12,height:27,ascent:22,descent:5,left:0,right:12},w:{width:17,height:27,ascent:22,descent:5,left:0,right:17},x:{width:12,height:27,ascent:22,descent:5,left:0,right:12},y:{width:12,height:27,ascent:22,descent:5,left:0,right:12},z:{width:12,height:27,ascent:22,descent:5,left:0,right:11},"{":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"|":{width:6,height:27,ascent:22,descent:5,left:-2,right:4},"}":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"~":{width:14,height:27,ascent:22,descent:5,left:-1,right:13}},MS=r=>{if(!r)return 0;let e=0;for(let a of r){let s=sBe[a];s?e+=s.width:e+=sBe["?"].width}return e/27},fBe=(r,e)=>{if(r.column_widths&&r.column_widths.length>0&&r.row_heights&&r.row_heights.length>0){let b=E=>typeof E=="number"?E:E.endsWith("mm")?parseFloat(E):E.endsWith("in")?parseFloat(E)*25.4:parseFloat(E);return{column_widths:r.column_widths.map(b),row_heights:r.row_heights.map(b)}}let a=e.filter(b=>b.type==="schematic_table_cell"&&b.schematic_table_id===r.schematic_table_id);if(a.length===0)return{column_widths:[],row_heights:[]};let s=a.reduce((b,E)=>Math.max(b,E.end_column_index),-1)+1,l=a.reduce((b,E)=>Math.max(b,E.end_row_index),-1)+1,{cell_padding:d=.2}=r,x=new Array(s).fill(0),f=new Array(l).fill(0),m={},D={};for(let b of a){let E=$g("reference_designator",b.font_size),B=MS(b.text??"")*E+2*d,w=E*1.2+2*d,P=`${b.start_row_index}-${b.start_column_index}`;m[P]=B,D[P]=w}for(let b=0;b<l;b++)for(let E=0;E<s;E++){let A=`${b}-${E}`;m[A]&&m[A]>x[E]&&(x[E]=m[A]),D[A]&&D[A]>f[b]&&(f[b]=D[A])}for(let b of a){if(b.start_column_index===b.end_column_index&&b.start_row_index===b.end_row_index)continue;let E=`${b.start_row_index}-${b.start_column_index}`,A=m[E],B=D[E];if(A===void 0||B===void 0)continue;let w=0;for(let j=b.start_column_index;j<=b.end_column_index;j++)w+=x[j];if(A>w){let O=(A-w)/(b.end_column_index-b.start_column_index+1);for(let q=b.start_column_index;q<=b.end_column_index;q++)x[q]+=O}let P=0;for(let j=b.start_row_index;j<=b.end_row_index;j++)P+=f[j];if(B>P){let O=(B-P)/(b.end_row_index-b.start_row_index+1);for(let q=b.start_row_index;q<=b.end_row_index;q++)f[q]+=O}}return{column_widths:x,row_heights:f}},zg=r=>{switch(r){case"top":return{x:0,y:-1};case"bottom":return{x:0,y:1};case"left":return{x:1,y:0};case"right":return{x:-1,y:0}}throw new Error(`Invalid side: ${r}`)},rx=.3,Og=.3,Lg=.06,WUt={top_left:"start",top_right:"end",middle_left:"start",middle_right:"end",bottom_left:"start",bottom_right:"end",center:"middle",middle_top:"middle",middle_bottom:"middle"},KUt={top_left:"hanging",top_right:"hanging",bottom_left:"ideographic",bottom_right:"ideographic",center:"middle",middle_left:"middle",middle_right:"middle",middle_top:"hanging",middle_bottom:"ideographic"};ui=r=>Math.abs(r.a)*.02,eVt=(r,e)=>{let a=r<0?r+2*Math.PI:r,s=e<0?e+2*Math.PI:e,l=Math.abs(a-s);return l>Math.PI&&(l=2*Math.PI-l),l},tVt=({schPorts:r,symbol:e,schComponent:a})=>{let s=r.map(f=>{let m=f.center.x-a.center.x,D=f.center.y-a.center.y;return{port:f,angle:Math.atan2(D,m)}}),l=e.ports.map(f=>{let m=f.x-e.center.x,D=f.y-e.center.y;return{port:f,angle:Math.atan2(D,m)}});s.sort((f,m)=>f.angle-m.angle),l.sort((f,m)=>f.angle-m.angle);let d=[],x=new Set;for(let f of s){let m=null;for(let D of l){if(x.has(D.port))continue;let b=eVt(f.angle,D.angle);(m===null||b<m.angleDiff)&&(m={symbolPort:D.port,angleDiff:b})}m&&m.angleDiff<Math.PI/4&&(d.push({schPort:f.port,symbolPort:m.symbolPort}),x.add(m.symbolPort))}return d};UW=({text:r,realCenter:e,realToScreenTransform:a})=>{let s=mt(a,e);return{type:"element",name:"text",value:"",attributes:{x:s.x.toString(),y:s.y.toString(),fill:"red","text-anchor":"middle","dominant-baseline":"middle","font-family":"sans-serif","font-size":`${cd(a,"error")}px`},children:[{type:"text",value:r,name:"",attributes:{},children:[]}]}},hBe=(r,e)=>{for(let a of r){if(a.type!=="source_trace")continue;let s=a;if(Array.isArray(s.connected_source_port_ids)&&s.connected_source_port_ids.includes(e))return!0}return!1},nVt={top_left:"start",top_right:"end",middle_left:"start",middle_right:"end",bottom_left:"start",bottom_right:"end",center:"middle",middle_top:"middle",middle_bottom:"middle"},aVt=({component:r,transform:e,circuitJson:a,colorMap:s})=>{let l=[],d=ks[r.symbol_name];if(!d)return[UW({text:`Symbol not found: ${r.symbol_name}`,realCenter:r.center,realToScreenTransform:e})];let x=ua(a).schematic_port.list({schematic_component_id:r.schematic_component_id}),f=ua(a).source_component.get(r.source_component_id),m=tVt({schPorts:x,symbol:d,schComponent:r});if(!m[0])return[UW({text:`Could not match ports for symbol ${r.symbol_name}`,realCenter:r.center,realToScreenTransform:e})];let D=rVt(m[1]?.symbolPort??d.center,m[1]?.schPort.center??r.center,m[0].symbolPort,m[0].schPort.center),b=d.primitives.filter(U=>U.type==="path"),E=d.primitives.filter(U=>U.type==="text"),A=d.primitives.filter(U=>U.type==="circle"),B=d.primitives.filter(U=>U.type==="box"),w=new Set;for(let U of m)hBe(a,U.schPort.source_port_id)&&w.add(U.symbolPort);let P={minX:Math.min(...b.flatMap(U=>U.points.map(J=>J.x))),maxX:Math.max(...b.flatMap(U=>U.points.map(J=>J.x))),minY:Math.min(...b.flatMap(U=>U.points.map(J=>J.y))),maxY:Math.max(...b.flatMap(U=>U.points.map(J=>J.y)))},[j,O]=mt(jn(e,D),[P.minX,P.minY]),[q,ee]=mt(jn(e,D),[P.maxX,P.maxY]),W=Math.abs(ee-O),re=Math.min(O,ee),L=Math.abs(q-j),K=Math.min(j,q);l.push({name:"rect",type:"element",value:"",attributes:{class:"component-overlay",x:K.toString(),y:re.toString(),width:L.toString(),height:W.toString(),fill:"transparent"},children:[]});for(let U of b){let{points:J,color:Q,closed:de,fill:oe}=U;l.push({type:"element",name:"path",attributes:{d:J.map((Me,Ne)=>{let[Ge,tt]=mt(jn(e,D),[Me.x,Me.y]);return`${Ne===0?"M":"L"} ${Ge} ${tt}`}).join(" ")+(de?" Z":""),stroke:s.schematic.component_outline,fill:"none","stroke-width":`${ui(e)}px`,"stroke-linecap":"round"},value:"",children:[]})}for(let U of E){let J=mt(jn(e,D),U),Q="";U.text==="{REF}"?Q=f?.name??"":U.text==="{VAL}"&&(Q=r.symbol_display_value??"");let Me=Math.abs(P.maxY-P.minY)*.1,Ne=Math.abs(D.a),Ge=0;U.anchor.includes("bottom")?Ge=Me*Ne:U.anchor.includes("top")&&(Ge=-Me*Ne);let tt=U.anchor.includes("bottom")?"auto":U.anchor.includes("top")?"hanging":"middle",He=U.text==="{REF}";l.push({name:"text",type:"element",attributes:{x:J.x.toString(),y:(J.y+Ge).toString(),...He?{stroke:s.schematic.background,"stroke-width":`${ui(e)}px`,"paint-order":"stroke"}:{},fill:s.schematic.label_local,"font-family":"sans-serif","text-anchor":nVt[U.anchor],"dominant-baseline":tt,"font-size":`${cd(e,"reference_designator")}px`},value:"",children:[{type:"text",value:Q,name:"",attributes:{},children:[]}]})}for(let U of B){let J=mt(jn(e,D),U),Q=jn(e,D).a;l.push({name:"rect",type:"element",attributes:{x:J.x.toString(),y:J.y.toString(),width:(U.width*Q).toString(),height:(U.height*Q).toString(),fill:"red"},value:"",children:[]})}for(let U of d.ports){if(w.has(U))continue;let J=mt(jn(e,D),U);l.push({type:"element",name:"circle",attributes:{cx:J.x.toString(),cy:J.y.toString(),r:`${Math.abs(e.a)*.02}px`,"stroke-width":`${ui(e)}px`,fill:"none",stroke:s.schematic.component_outline},value:"",children:[]})}for(let U of A){let J=mt(jn(e,D),U),Q=Math.abs(U.radius*e.a);l.push({type:"element",name:"circle",attributes:{cx:J.x.toString(),cy:J.y.toString(),r:`${Q}px`,"stroke-width":`${ui(e)}px`,fill:"none",stroke:s.schematic.component_outline},value:"",children:[]})}return l},LF=.02,iBe=(r,e,a,s,l)=>{let d=Math.PI/6,x={x:r.x-a*Math.cos(e-d),y:r.y-a*Math.sin(e-d)},f={x:r.x-a*Math.cos(e+d),y:r.y-a*Math.sin(e+d)};return{name:"polygon",type:"element",attributes:{points:`${r.x},${r.y} ${x.x},${x.y} ${f.x},${f.y}`,fill:"white",stroke:s,"stroke-width":`${l}px`},value:"",children:[]}},sVt=({schPort:r,schComponent:e,transform:a,circuitJson:s})=>{let l=[],d=ua(s).source_port.get(r.source_port_id),x={x:r.center.x,y:r.center.y},f=r.distance_from_component_edge??.4;switch(r.side_of_component){case"left":x.x+=f;break;case"right":x.x-=f;break;case"top":x.y-=f;break;case"bottom":x.y+=f;break}let m=mt(a,r.center),D=mt(a,x),b={...r.center};switch(r.side_of_component){case"left":b.x+=LF;break;case"right":b.x-=LF;break;case"top":b.y-=LF;break;case"bottom":b.y+=LF;break}let E=mt(a,b);l.push({name:"line",type:"element",attributes:{class:"component-pin",x1:E.x.toString(),y1:E.y.toString(),x2:D.x.toString(),y2:D.y.toString(),"stroke-width":`${ui(a)}px`},value:"",children:[]});let A=hBe(s,r.source_port_id),B=Math.abs(a.a)*LF,w=[];A||w.push({name:"circle",type:"element",attributes:{class:"component-pin",cx:m.x.toString(),cy:m.y.toString(),r:B.toString(),"stroke-width":`${ui(a)}px`},value:"",children:[]}),w.push({name:"rect",type:"element",attributes:{x:(m.x-B).toString(),y:(m.y-B).toString(),width:(B*2).toString(),height:(B*2).toString(),opacity:"0"},value:"",children:[]}),l.push({name:"g",type:"element",value:"",attributes:{"data-schematic-port-id":r.source_port_id},children:w});let{has_input_arrow:P,has_output_arrow:j}=r;if((P||j)&&r.side_of_component){let O=Math.abs(a.a)*.1,q=nl.schematic.component_outline,ee=O*Math.cos(Math.PI/6),W=ui(a)/3,re=0,L=0;r.side_of_component==="left"?(re=0,L=Math.PI):r.side_of_component==="right"?(re=Math.PI,L=0):r.side_of_component==="top"?(re=Math.PI/2,L=-Math.PI/2):r.side_of_component==="bottom"&&(re=-Math.PI/2,L=Math.PI/2);let K=P&&j,U={...D},J={...D};if(K){let Q=ee;r.side_of_component==="left"?J.x-=Q:r.side_of_component==="right"?J.x+=Q:r.side_of_component==="top"?J.y-=Q:r.side_of_component==="bottom"&&(J.y+=Q)}if(P&&l.push(iBe(U,re,O,q,W)),j){let Q={x:J.x+O*Math.cos(L),y:J.y+O*Math.sin(L)};l.push(iBe(Q,L,O,q,W))}}return l},iVt=r=>{let e=[],{schPort:a,schComponent:s,transform:l,circuitJson:d}=r,x={x:a.center.x,y:a.center.y};if(!a.side_of_component)return[];let f=zg(a.side_of_component),m=a.distance_from_component_edge??.4;x.x+=f.x*m/2,x.y+=f.y*m/2,a.side_of_component==="top"||a.side_of_component==="bottom"?x.x-=.02:x.y+=.02;let D=mt(l,x);return e.push({name:"text",type:"element",attributes:{class:"pin-number",x:D.x.toString(),y:D.y.toString(),style:"font-family: sans-serif;",fill:nl.schematic.pin_number,"text-anchor":"middle","dominant-baseline":"auto","font-size":`${cd(l,"pin_number")}px`,transform:a.side_of_component==="top"||a.side_of_component==="bottom"?`rotate(-90 ${D.x} ${D.y})`:""},children:[{type:"text",value:a.pin_number?.toString()||"",name:"",attributes:{},children:[]}],value:""}),e},oBe=.1,oVt=r=>{let e=[],{schPort:a,schComponent:s,transform:l,circuitJson:d}=r,x={x:a.center.x,y:a.center.y};if(!a.side_of_component)return[];let f=zg(a.side_of_component),m=a.distance_from_component_edge??.4;x.x+=f.x*(m+oBe),x.y+=f.y*(m+oBe);let D=mt(l,x),b=a.display_pin_label??s.port_labels?.[`${a.pin_number}`];if(!b)return[];let E=b.startsWith("N_"),A=E?b.slice(2):b,B=cd(l,E?"negated_pin_number":"pin_number");return e.push({name:"text",type:"element",attributes:{class:"pin-number",x:D.x.toString(),y:D.y.toString(),style:`font-family: sans-serif;${E?" text-decoration: overline;":""}`,fill:nl.schematic.pin_number,"text-anchor":a.side_of_component==="left"||a.side_of_component==="bottom"?"start":"end","dominant-baseline":"middle","font-size":`${B}px`,transform:a.side_of_component==="top"||a.side_of_component==="bottom"?`rotate(-90 ${D.x} ${D.y})`:""},children:[{type:"text",value:A||"",name:"",attributes:{},children:[]}],value:""}),e},uVt=r=>{let e=[],{schPort:a,schComponent:s,transform:l,circuitJson:d}=r;return e.push(...sVt(r)),e.push(...iVt(r)),e.push(...oVt(r)),e},mBe=({elm:r,transform:e,colorMap:a})=>{let s=mt(e,r.position),l={center:"middle",center_right:"end",bottom_left:"start",bottom_center:"middle",bottom_right:"end",left:"start",right:"end",top:"middle",bottom:"middle",top_left:"start",top_center:"middle",top_right:"end",center_left:"start"},d={center:"middle",center_right:"middle",bottom_left:"ideographic",bottom_center:"ideographic",bottom_right:"ideographic",left:"middle",right:"middle",top:"hanging",bottom:"ideographic",top_left:"hanging",top_center:"hanging",top_right:"hanging",center_left:"middle"},x=r.text.split(`
122
122
  `),f=x.length===1?[{type:"text",value:r.text,name:r.schematic_text_id,attributes:{},children:[]}]:x.map((m,D)=>({type:"element",name:"tspan",value:"",attributes:{x:s.x.toString(),...D>0?{dy:"1em"}:{}},children:[{type:"text",value:m,name:D===0?r.schematic_text_id:"",attributes:{},children:[]}]}));return{type:"element",name:"text",value:"",attributes:{x:s.x.toString(),y:s.y.toString(),fill:r.color??a.schematic.sheet_label,"text-anchor":l[r.anchor],"dominant-baseline":d[r.anchor],"font-family":"sans-serif","font-size":`${cd(e,"reference_designator",r.font_size)}px`,transform:`rotate(${r.rotation}, ${s.x}, ${s.y})`},children:f}},cVt=({component:r,transform:e,circuitJson:a,colorMap:s})=>{let l=[],d=mt(e,{x:r.center.x-r.size.width/2,y:r.center.y+r.size.height/2}),x=mt(e,{x:r.center.x+r.size.width/2,y:r.center.y-r.size.height/2}),f=x.x-d.x,m=x.y-d.y;l.push({name:"rect",type:"element",value:"",attributes:{class:"component chip",x:d.x.toString(),y:d.y.toString(),width:f.toString(),height:m.toString(),"stroke-width":`${ui(e)}px`,fill:s.schematic.component_body,stroke:s.schematic.component_outline},children:[]}),l.push({name:"rect",type:"element",value:"",attributes:{class:"component-overlay",x:d.x.toString(),y:d.y.toString(),width:f.toString(),height:m.toString(),fill:"transparent"},children:[]});let D=ua(a).schematic_text.list();for(let E of D)E.schematic_component_id===r.schematic_component_id&&l.push(mBe({elm:E,transform:e,colorMap:s}));let b=ua(a).schematic_port.list({schematic_component_id:r.schematic_component_id});for(let E of b)l.push(...uVt({schPort:E,schComponent:r,transform:e,circuitJson:a}));return l};fVt=({schNetLabel:r,realToScreenTransform:e,colorMap:a})=>{if(!r.text)return[];let s=r.text.startsWith("N_"),l=s?r.text.slice(2):r.text,d=[],x=ks[r.symbol_name];if(!x)return d.push(UW({text:`Symbol not found: ${r.symbol_name}`,realCenter:r.center,realToScreenTransform:e})),d;let f=x.primitives.filter(Ge=>Ge.type==="path"),m=x.primitives.filter(Ge=>Ge.type==="text"),D=x.primitives.filter(Ge=>Ge.type==="circle"),b=x.primitives.filter(Ge=>Ge.type==="box"),E={minX:Math.min(...f.flatMap(Ge=>Ge.points.map(tt=>tt.x))),maxX:Math.max(...f.flatMap(Ge=>Ge.points.map(tt=>tt.x))),minY:Math.min(...f.flatMap(Ge=>Ge.points.map(tt=>tt.y))),maxY:Math.max(...f.flatMap(Ge=>Ge.points.map(tt=>tt.y)))},A=$g("net_label"),w=MS(l||"")+rx*2+Lg*l.length+Og,P=zg(r.anchor_side),j=r.anchor_position??{x:r.center.x-P.x*w*A/2,y:r.center.y-P.y*w*A/2},q=Du(0/180*Math.PI),ee={minX:Math.min(...x.primitives.flatMap(Ge=>Ge.type==="path"?Ge.points.map(tt=>tt.x):[])),maxX:Math.max(...x.primitives.flatMap(Ge=>Ge.type==="path"?Ge.points.map(tt=>tt.x):[])),minY:Math.min(...x.primitives.flatMap(Ge=>Ge.type==="path"?Ge.points.map(tt=>tt.y):[])),maxY:Math.max(...x.primitives.flatMap(Ge=>Ge.type==="path"?Ge.points.map(tt=>tt.y):[]))},W=x.ports?.[0]?{x:x.ports[0].x,y:x.ports[0].y}:{x:ee.minX,y:(ee.minY+ee.maxY)/2},re=mt(q,W),L=jn(Ra(j.x-re.x,j.y-re.y),q,ji(1)),[K,U]=mt(jn(e,L),[E.minX,E.minY]),[J,Q]=mt(jn(e,L),[E.maxX,E.maxY]),de=Math.abs(Q-U),oe=Math.min(U,Q),Me=Math.abs(J-K),Ne=Math.min(K,J);d.push({name:"rect",type:"element",value:"",attributes:{class:"component-overlay",x:Ne.toString(),y:oe.toString(),width:Me.toString(),height:de.toString(),fill:"transparent"},children:[]});for(let Ge of f){let tt=Ge.points.map((He,$t)=>{let[bt,ct]=mt(jn(e,L),[He.x,He.y]);return`${$t===0?"M":"L"} ${bt} ${ct}`}).join(" ");d.push({name:"path",type:"element",attributes:{d:tt+(Ge.closed?" Z":""),stroke:a.schematic.component_outline,fill:"none","stroke-width":`${ui(e)}px`,"stroke-linecap":"round"},value:"",children:[]})}for(let Ge of m){let tt=mt(jn(e,L),Ge),He=Ge.text;He==="{REF}"?He=l||"":He==="{VAL}"&&(He="");let bt=Math.abs(e.a)*.1,ct={x:tt.x,y:tt.y};d.push({name:"text",type:"element",attributes:{x:ct.x.toString(),y:ct.y.toString(),fill:a.schematic.label_local,"font-family":"sans-serif","text-anchor":WUt[Ge.anchor],"dominant-baseline":KUt[Ge.anchor],"font-size":`${cd(e,"reference_designator")}px`,...s&&He===l?{style:"text-decoration: overline;"}:{}},children:[{type:"text",value:He,name:"",attributes:{},children:[]}],value:""})}for(let Ge of b){let tt=mt(jn(e,L),Ge),He=jn(e,L).a;d.push({name:"rect",type:"element",attributes:{x:tt.x.toString(),y:tt.y.toString(),width:(Ge.width*He).toString(),height:(Ge.height*He).toString(),fill:"red"},value:"",children:[]})}for(let Ge of D){let tt=mt(jn(e,L),Ge),He=jn(e,L).a;d.push({name:"circle",type:"element",attributes:{cx:tt.x.toString(),cy:tt.y.toString(),r:(Ge.radius*He).toString(),fill:"none",stroke:a.schematic.component_outline,"stroke-width":`${ui(e)}px`},value:"",children:[]})}return d},hVt=({schNetLabel:r,realToScreenTransform:e,colorMap:a})=>{if(!r.text)return[];let s=r.text;if(r.symbol_name)return fVt({schNetLabel:r,realToScreenTransform:e,colorMap:a});let l=[],d=cd(e,"net_label"),x=$g("net_label"),f=MS(s||""),m=mt(e,r.center),D=zg(r.anchor_side),b={...D};b.y*=-1;let E=f+rx*2+Lg*s.length+Og,A=r.anchor_position?mt(e,r.anchor_position):{x:m.x-b.x*E*d/2,y:m.y-b.y*E*d/2},B=r.anchor_position??{x:r.center.x-D.x*E*x/2,y:r.center.y-D.y*E*x/2},w={left:0,top:-90,bottom:90,right:180}[r.anchor_side],P=[{x:0,y:0},{x:rx,y:.6},{x:rx*2+Og+Lg*s.length+f,y:.6},{x:rx*2+Og+Lg*s.length+f,y:-.6},{x:rx,y:-.6}].map(W=>mt(jn(e,Ra(B.x,B.y),ji(x),Du(w/180*Math.PI)),W)),j=`
123
123
  M ${P[0].x},${P[0].y}
124
124
  L ${P[1].x},${P[1].y}
@@ -948,7 +948,7 @@ Using plugins:`),be.forEach(function(je){Lbt(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 Qu=Or(t1(),1);var aY={};function sY(r,e){return r===Qu.default.falseFunc?Qu.default.falseFunc:a=>e.isTag(a)&&r(a)}function iY(r,e){let a=e.getSiblings(r);if(a.length<=1)return[];let s=a.indexOf(r);return s<0||s===a.length-1?[]:a.slice(s+1).filter(e.isTag)}function nY(r){return{xmlMode:!!r.xmlMode,lowerCaseAttributeNames:!!r.lowerCaseAttributeNames,lowerCaseTags:!!r.lowerCaseTags,quirksMode:!!r.quirksMode,cacheResults:!!r.cacheResults,pseudos:r.pseudos,adapter:r.adapter,equals:r.equals}}var rY=(r,e,a,s,l)=>{let d=l(e,nY(a),s);return d===Qu.default.trueFunc?r:d===Qu.default.falseFunc?Qu.default.falseFunc:x=>d(x)&&r(x)},JR={is:rY,matches:rY,where:rY,not(r,e,a,s,l){let d=l(e,nY(a),s);return d===Qu.default.falseFunc?r:d===Qu.default.trueFunc?Qu.default.falseFunc:x=>!d(x)&&r(x)},has(r,e,a,s,l){let{adapter:d}=a,x=nY(a);x.relativeSelector=!0;let f=e.some(b=>b.some(Ib))?[aY]:void 0,m=l(e,x,f);if(m===Qu.default.falseFunc)return Qu.default.falseFunc;let D=sY(m,d);if(f&&m!==Qu.default.trueFunc){let{shouldTestNextSiblings:b=!1}=m;return E=>{if(!r(E))return!1;f[0]=E;let A=d.getChildren(E),B=b?[...A,...iY(E,d)]:A;return d.existsOne(D,B)}}return b=>r(b)&&d.existsOne(D,d.getChildren(b))}};function s_e(r,e,a,s,l){var d;let{name:x,data:f}=e;if(Array.isArray(f)){if(!(x in JR))throw new Error(`Unknown pseudo-class :${x}(${f})`);return JR[x](r,f,a,s,l)}let m=(d=a.pseudos)===null||d===void 0?void 0:d[x],D=typeof m=="string"?m:tY[x];if(typeof D=="string"){if(f!=null)throw new Error(`Pseudo ${x} doesn't have any arguments`);let b=Pb(D);return JR.is(r,b,a,s,l)}if(typeof m=="function")return eY(m,x,f,1),b=>m(b,f)&&r(b);if(x in kb)return kb[x](r,f,a,s);if(x in KR){let b=KR[x];return eY(b,x,f,2),E=>b(E,a,f)&&r(E)}throw new Error(`Unknown pseudo-class :${x}`)}function oY(r,e){let a=e.getParent(r);return a&&e.isTag(a)?a:null}function i_e(r,e,a,s,l){let{adapter:d,equals:x}=a;switch(e.type){case Zr.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case Zr.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case Zr.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()),t_e[e.action](r,e,a)}case Zr.Pseudo:return s_e(r,e,a,s,l);case Zr.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 d.getName(D)===f&&r(D)}}case Zr.Descendant:{if(a.cacheResults===!1||typeof WeakSet>"u")return function(D){let b=D;for(;b=oY(b,d);)if(r(b))return!0;return!1};let f=new WeakSet;return function(D){let b=D;for(;b=oY(b,d);)if(!f.has(b)){if(d.isTag(b)&&r(b))return!0;f.add(b)}return!1}}case"_flexibleDescendant":return function(m){let D=m;do if(r(D))return!0;while(D=oY(D,d));return!1};case Zr.Parent:return function(m){return d.getChildren(m).some(D=>d.isTag(D)&&r(D))};case Zr.Child:return function(m){let D=d.getParent(m);return D!=null&&d.isTag(D)&&r(D)};case Zr.Sibling:return function(m){let D=d.getSiblings(m);for(let b=0;b<D.length;b++){let E=D[b];if(x(m,E))break;if(d.isTag(E)&&r(E))return!0}return!1};case Zr.Adjacent:return d.prevElementSibling?function(m){let D=d.prevElementSibling(m);return D!=null&&r(D)}:function(m){let D=d.getSiblings(m),b;for(let E=0;E<D.length;E++){let A=D[E];if(x(m,A))break;d.isTag(A)&&(b=A)}return!!b&&r(b)};case Zr.Universal:{if(e.namespace!=null&&e.namespace!=="*")throw new Error("Namespaced universal selectors are not yet supported by css-select");return r}}}function o_e(r,e,a){let s=ZR(r,e,a);return sY(s,e.adapter)}function ZR(r,e,a){let s=typeof r=="string"?Pb(r):r;return QR(s,e,a)}function u_e(r){return r.type===Zr.Pseudo&&(r.name==="scope"||Array.isArray(r.data)&&r.data.some(e=>e.some(u_e)))}var jjt={type:Zr.Descendant},kjt={type:"_flexibleDescendant"},Njt={type:Zr.Pseudo,name:"scope",data:null};function Mjt(r,{adapter:e},a){let s=!!a?.every(l=>{let d=e.isTag(l)&&e.getParent(l);return l===aY||d&&e.isTag(d)});for(let l of r){if(!(l.length>0&&Ib(l[0])&&l[0].type!==Zr.Descendant))if(s&&!l.some(u_e))l.unshift(jjt);else continue;l.unshift(Njt)}}function QR(r,e,a){var s;r.forEach(JX),a=(s=e.context)!==null&&s!==void 0?s:a;let l=Array.isArray(a),d=a&&(Array.isArray(a)?a:[a]);if(e.relativeSelector!==!1)Mjt(r,e,d);else if(r.some(m=>m.length>0&&Ib(m[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let x=!1,f=r.map(m=>{if(m.length>=2){let[D,b]=m;D.type!==Zr.Pseudo||D.name!=="scope"||(l&&b.type===Zr.Descendant?m[1]=kjt:(b.type===Zr.Adjacent||b.type===Zr.Sibling)&&(x=!0))}return Ojt(m,e,d)}).reduce(Ljt,ed.default.falseFunc);return f.shouldTestNextSiblings=x,f}function Ojt(r,e,a){var s;return r.reduce((l,d)=>l===ed.default.falseFunc?ed.default.falseFunc:i_e(l,d,e,a,QR),(s=e.rootFunc)!==null&&s!==void 0?s:ed.default.trueFunc)}function Ljt(r,e){return e===ed.default.falseFunc||r===ed.default.trueFunc?r:r===ed.default.falseFunc||e===ed.default.trueFunc?e:function(s){return r(s)||e(s)}}var c_e=(r,e)=>r===e,$jt={adapter:HR,equals:c_e};function l_e(r){var e,a,s,l;let d=r??$jt;return(e=d.adapter)!==null&&e!==void 0||(d.adapter=HR),(a=d.equals)!==null&&a!==void 0||(d.equals=(l=(s=d.adapter)===null||s===void 0?void 0:s.equals)!==null&&l!==void 0?l:c_e),d}function cY(r){return function(a,s,l){let d=l_e(s);return r(a,d,l)}}var jnr=cY(o_e),knr=cY(ZR),Nnr=cY(QR);function d_e(r){return function(a,s,l){let d=l_e(l);typeof a!="function"&&(a=ZR(a,d,s));let x=zjt(s,d.adapter,a.shouldTestNextSiblings);return r(a,x,d)}}function zjt(r,e,a=!1){return a&&(r=qjt(r,e)),Array.isArray(r)?e.removeSubsets(r):e.getChildren(r)}function qjt(r,e){let a=Array.isArray(r)?r.slice(0):[r],s=a.length;for(let l=0;l<s;l++){let d=iY(a[l],e);a.push(...d)}return a}var lY=d_e((r,e,a)=>r===uY.default.falseFunc||!e||e.length===0?[]:a.adapter.findAll(r,e)),e5=d_e((r,e,a)=>r===uY.default.falseFunc||!e||e.length===0?null:a.adapter.findOne(r,e));Ue();qt();Ue();var U_e=Or(fs(),1);qt();var X_e=Or(fs(),1),H_e=Or(fs(),1);qt();V0();gY();var DY=(r,e={})=>{let a=r._internal_store;if(!a){a={counts:{}},r._internal_store=a;for(let l of r){let d=l.type,x=l[`${d}_id`];if(!x)continue;let f=Number.parseInt(x.split("_").pop());Number.isNaN(f)||(a.counts[d]=Math.max(a.counts[d]??0,f))}}return new Proxy({},{get:(l,d)=>d==="toArray"?()=>r:{get:x=>r.find(f=>f.type===d&&f[`${d}_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=r.find(E=>E.type===D&&E[m]===x[m]);return b?r.find(E=>E.type===d&&E[`${d}_id`]===b[`${d}_id`]):null},getWhere:x=>{let f=Object.keys(x);return r.find(m=>m.type===d&&f.every(D=>m[D]===x[D]))},list:x=>{let f=x?Object.keys(x):[];return r.filter(m=>m.type===d&&f.every(D=>m[D]===x[D]))},insert:x=>{var D;(D=a.counts)[d]??(D[d]=-1),a.counts[d]++;let f=a.counts[d],m={type:d,[`${d}_id`]:`${d}_${f}`,...x};return e.validateInserts&&(Hf[d]??Yf).parse(m),r.push(m),m},delete:x=>{let f=r.find(m=>m[`${d}_id`]===x);f&&r.splice(r.indexOf(f),1)},update:(x,f)=>{let m=r.find(D=>D[`${d}_id`]===x);if(m)return Object.assign(m,f),m},select:x=>{if(d==="source_component")return r.find(f=>f.type==="source_component"&&f.name===x.replace(/\./g,""));if(d==="pcb_port"||d==="source_port"||d==="schematic_port"){let[f,m]=x.replace(/\./g,"").split(/[\s\>]+/),D=r.find(E=>E.type==="source_component"&&E.name===f);if(!D)return null;let b=r.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(d==="source_port")return b;if(d==="pcb_port")return r.find(E=>E.type==="pcb_port"&&E.source_port_id===b.source_port_id);if(d==="schematic_port")return r.find(E=>E.type==="schematic_port"&&E.source_port_id===b.source_port_id)}}}})};DY.unparsed=DY;var __e=DY;var $sr=Or(R_e(),1);Fo();function td(r){let e=r.width/2,a=r.height/2;return{minX:r.center.x-e,maxX:r.center.x+e,minY:r.center.y-a,maxY:r.center.y+a}}function sg(r,e){let a=td(r),s=td(e),l=Math.max(a.minX-s.maxX,s.minX-a.maxX,0),d=Math.max(a.minY-s.maxY,s.minY-a.maxY,0),x={x:0,y:0},f={x:0,y:0};return l===0&&d===0?{distance:0,pointA:r.center,pointB:e.center}:(x.x=ms(r.center.x,s.minX,s.maxX),x.y=ms(r.center.y,s.minY,s.maxY),f.x=ms(e.center.x,a.minX,a.maxX),f.y=ms(e.center.y,a.minY,a.maxY),{distance:Math.hypot(x.x-f.x,x.y-f.y),pointA:x,pointB:f})}function ms(r,e,a){return Math.max(e,Math.min(a,r))}function zb(r,e){let a=Number.POSITIVE_INFINITY,s={x:0,y:0},l={x:0,y:0};for(let d of r)for(let x of e){let{distance:f,pointA:m,pointB:D}=sg(d,x);f<a&&(a=f,s=m,l=D)}return{pointA:s,pointB:l,distance:a}}Fo();Fo();var j_e="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var k_e=(r=21)=>{let e="",a=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=j_e[a[r]&63];return e};Fo();var c1=(r,e)=>Math.abs(r.x-e.x)+Math.abs(r.y-e.y),N_e=(r,e)=>{let a=e.x-r.x,s=e.y-r.y;return Math.abs(a)>Math.abs(s)?{dx:Math.sign(a),dy:0}:{dx:0,dy:Math.sign(s)}},z_e=(r,e,a)=>Math.abs(r.x-e.x)*Math.abs(a.dx)+Math.abs(r.y-e.y)*Math.abs(a.dy),q_e=(r,e=.1)=>`${Math.round(r.x/e)},${Math.round(r.y/e)}`,M_e=(r,e)=>Math.abs(r-e)<1e-4,V_e=(r,e,{viaDiameter:a=.5}={})=>{let s=[];for(let l=0;l<r.length-1;l++){let[d,x]=[r[l],r[l+1]],f=l-1>=0?r[l-1]:null,m=M_e(d.y,x.y),D=M_e(d.x,x.x);if(!m&&!D)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${d.x}, ${d.y}), end: (${x.x}, ${x.y})`);let b={type:"rect",layers:[d.layer],center:{x:(d.x+x.x)/2,y:(d.y+x.y)/2},width:m?Math.abs(d.x-x.x):.1,height:D?Math.abs(d.y-x.y):.1,connectedTo:[e]};if(s.push(b),f&&f.layer===d.layer&&d.layer!==x.layer){let E={type:"rect",layers:[d.layer,x.layer],center:{x:d.x,y:d.y},connectedTo:[e],width:a,height:a};s.push(E)}}return s},G_e=class{constructor(r){z(this,"obstacles");z(this,"GRID_STEP",.1);this.obstacles=r.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(r,e,a){a??(a=this.GRID_STEP);for(let s of this.obstacles){let l=s.width/2+a,d=s.height/2+a;if(r>=s.center.x-l&&r<=s.center.x+l&&e>=s.center.y-d&&e<=s.center.y+d)return s}return null}isObstacleAt(r,e,a){return this.getObstacleAt(r,e,a)!==null}getDirectionDistancesToNearestObstacle(r,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 d=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&&r>d&&(s.left=Math.min(s.left,r-x)),e>=m&&e<=f&&r<x&&(s.right=Math.min(s.right,d-r)),r>=d&&r<=x&&e<f&&(s.top=Math.min(s.top,m-e)),r>=d&&r<=x&&e>m&&(s.bottom=Math.min(s.bottom,e-f))}return s}getOrthoDirectionCollisionInfo(r,e,{margin:a=0}={}){let{x:s,y:l}=r,{dx:d,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;d===1&&x===0?l>B&&l<A&&s<D.left&&(w=D.left-s):d===-1&&x===0?l>B&&l<A&&s>D.right&&(w=s-D.right):d===0&&x===1?s>b&&s<E&&l<D.bottom&&(w=D.bottom-l):d===0&&x===-1&&s>b&&s<E&&l>D.top&&(w=l-D.top),w!==null&&w<f&&(f=w,m=D)}return{dx:d,dy:x,wallDistance:f,obstacle:m}}getObstaclesOverlappingRegion(r){let e=[];for(let a of this.obstacles){let{left:s,right:l,top:d,bottom:x}=a;s<=r.maxX&&l>=r.minX&&d<=r.maxY&&x>=r.minY&&e.push(a)}return e}};function Hjt(r){if(r.length<4)return r;let e=[{...r[0]}],a=r[0].layer;for(let s=1;s<r.length;s++){let l={start:r[s-1],end:r[s]},d=r[s].route_type==="via"||r[s-1].route_type==="via";if(r[s].layer!==a||d){e.push({...r[s]}),a=r[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=Wjt(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!==r[s].x||D.y!==r[s].y)&&e.push(r[s])}return e}function Wjt(r,e){if(r.start.x===r.end.x&&e.start.x===e.end.x||r.start.y===r.end.y&&e.start.y===e.end.y)return null;let a;if(r.start.x===r.end.x){let s=r.start.x,l=e.start.y;a={...r.start,x:s,y:l}}else{let s=e.start.x,l=r.start.y;a={...r.start,x:s,y:l}}return O_e(a,r)&&O_e(a,e)?a:null}function O_e(r,e){return r.x>=Math.min(e.start.x,e.end.x)&&r.x<=Math.max(e.start.x,e.end.x)&&r.y>=Math.min(e.start.y,e.end.y)&&r.y<=Math.max(e.start.y,e.end.y)}function Kjt(r){let e=[r[0]];for(let a=1;a<r.length-1;a++){let[s,l,d]=[r[a-1],r[a],r[a+1]];e.push(l),!(l.route_type!=="wire"||s.route_type!=="wire"||d.route_type!=="wire")&&s.layer===l.layer&&l.layer!==d.layer&&e.push({route_type:"via",from_layer:l.layer,to_layer:d.layer,x:l.x,y:l.y})}return e.push(r[r.length-1]),e}var Osr=(0,X_e.default)("autorouter:shortenPathWithShortcuts");function Jjt(r,e){if(r.length<=2)return r;let a=[r[0]];for(let s=1;s<r.length;s++){let l={start:a[a.length-1],end:r[s]},d=-1,x=l.start.x===l.end.x,f=l.start.y===l.end.y;for(let m=s+1;m<r.length;m++){if(m<=d)continue;let D={start:r[m],end:r[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,j=Math.min(l.start.x,l.end.x),O=Math.max(l.start.x,l.end.x),q=Math.min(D.start.x,D.end.x),ee=Math.max(D.start.x,D.end.x),W=Math.min(l.start.y,l.end.y),re=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=j<=ee&&O>=q:A&&(P=W<=K&&re>=L),!P)continue;let U=[],J=a[a.length-1],Q=r[m+2];if(!Q)continue;B&&q<O&&Q.x===q&&U.push({x:q,y:l.start.y,layer:l.start.layer}),B&&ee>j&&Q.x===ee&&U.push({x:ee,y:l.start.y,layer:l.start.layer}),A&&L<re&&Q.y===L&&U.push({x:l.start.x,y:L,layer:l.start.layer}),A&&K>W&&Q.y===K&&U.push({x:l.start.x,y:K,layer:l.start.layer});let de=null;for(let oe of U)if(!(e(J,oe)||e(Q,oe))){de=oe;break}if(de){a.push(de),s=m+1,d=m+1;break}}d===-1&&a.push(r[s])}return a[a.length-1]!==r[r.length-1]&&a.push(r[r.length-1]),a}var u1=(0,U_e.default)("autorouting-dataset:astar"),Y_e=class{constructor(r){z(this,"openSet",[]);z(this,"closedSet",new Set);z(this,"debug",!1);z(this,"debugSolutions");z(this,"debugMessage",null);z(this,"debugTraceCount",0);z(this,"input");z(this,"obstacles");z(this,"allObstacles");z(this,"startNode");z(this,"goalPoint");z(this,"GRID_STEP");z(this,"OBSTACLE_MARGIN");z(this,"MAX_ITERATIONS");z(this,"isRemovePathLoopsEnabled");z(this,"isShortenPathWithShortcutsEnabled");z(this,"GREEDY_MULTIPLIER",1.1);z(this,"iterations",-1);this.input=r.input,this.allObstacles=r.input.obstacles,this.startNode=r.startNode,this.goalPoint=r.goalPoint?{l:0,...r.goalPoint}:void 0,this.GRID_STEP=r.GRID_STEP??.1,this.OBSTACLE_MARGIN=r.OBSTACLE_MARGIN??.15,this.MAX_ITERATIONS=r.MAX_ITERATIONS??100,this.debug=r.debug??u1.enabled,this.isRemovePathLoopsEnabled=r.isRemovePathLoopsEnabled??!1,this.isShortenPathWithShortcutsEnabled=r.isShortenPathWithShortcutsEnabled??!1,this.debug&&(u1.enabled=!0),u1.enabled&&(this.debugSolutions={},this.debugMessage="")}getNeighbors(r){return[]}isSameNode(r,e){return c1(r,e)<this.GRID_STEP}computeG(r,e){return r.g+c1(r,e)}computeH(r){return c1(r,this.goalPoint)}getNodeName(r){return q_e(r,this.GRID_STEP)}solveOneStep(){this.iterations+=1;let{openSet:r,closedSet:e,GRID_STEP:a,goalPoint:s}=this;r.sort((f,m)=>f.f-m.f);let l=r.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:c1(l,f),nodesInPath:l.nodesInPath+1,parent:l,enterMarginCost:f.enterMarginCost,travelMarginCostFactor:f.travelMarginCostFactor};r.push(A),x.push(A)}}return u1.enabled&&(r.sort((f,m)=>f.f-m.f),this.drawDebugSolution({current:l,newNeighbors:x})),{solved:!1,current:l,newNeighbors:x}}getStartNode(r){return{x:r.pointsToConnect[0].x,y:r.pointsToConnect[0].y,manDistFromParent:0,f:0,g:0,h:0,nodesInPath:0,parent:null}}layerToIndex(r){return 0}indexToLayer(r){return"top"}preprocessConnectionBeforeSolving(r){return r}solveConnection(r){if(r.pointsToConnect.length>2)throw new Error("GeneralizedAstarAutorouter doesn't currently support 2+ points in a connection");r=this.preprocessConnectionBeforeSolving(r);let{pointsToConnect:e}=r;for(this.iterations=0,this.closedSet=new Set,this.startNode=this.getStartNode(r),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=[],d=s;for(;d;){let x=d.l;l.unshift({x:d.x,y:d.y,layer:x!==void 0?this.indexToLayer(x):e[0].layer}),d=d.parent}return u1.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 Qu=Or(t1(),1);var aY={};function sY(r,e){return r===Qu.default.falseFunc?Qu.default.falseFunc:a=>e.isTag(a)&&r(a)}function iY(r,e){let a=e.getSiblings(r);if(a.length<=1)return[];let s=a.indexOf(r);return s<0||s===a.length-1?[]:a.slice(s+1).filter(e.isTag)}function nY(r){return{xmlMode:!!r.xmlMode,lowerCaseAttributeNames:!!r.lowerCaseAttributeNames,lowerCaseTags:!!r.lowerCaseTags,quirksMode:!!r.quirksMode,cacheResults:!!r.cacheResults,pseudos:r.pseudos,adapter:r.adapter,equals:r.equals}}var rY=(r,e,a,s,l)=>{let d=l(e,nY(a),s);return d===Qu.default.trueFunc?r:d===Qu.default.falseFunc?Qu.default.falseFunc:x=>d(x)&&r(x)},JR={is:rY,matches:rY,where:rY,not(r,e,a,s,l){let d=l(e,nY(a),s);return d===Qu.default.falseFunc?r:d===Qu.default.trueFunc?Qu.default.falseFunc:x=>!d(x)&&r(x)},has(r,e,a,s,l){let{adapter:d}=a,x=nY(a);x.relativeSelector=!0;let f=e.some(b=>b.some(Ib))?[aY]:void 0,m=l(e,x,f);if(m===Qu.default.falseFunc)return Qu.default.falseFunc;let D=sY(m,d);if(f&&m!==Qu.default.trueFunc){let{shouldTestNextSiblings:b=!1}=m;return E=>{if(!r(E))return!1;f[0]=E;let A=d.getChildren(E),B=b?[...A,...iY(E,d)]:A;return d.existsOne(D,B)}}return b=>r(b)&&d.existsOne(D,d.getChildren(b))}};function s_e(r,e,a,s,l){var d;let{name:x,data:f}=e;if(Array.isArray(f)){if(!(x in JR))throw new Error(`Unknown pseudo-class :${x}(${f})`);return JR[x](r,f,a,s,l)}let m=(d=a.pseudos)===null||d===void 0?void 0:d[x],D=typeof m=="string"?m:tY[x];if(typeof D=="string"){if(f!=null)throw new Error(`Pseudo ${x} doesn't have any arguments`);let b=Pb(D);return JR.is(r,b,a,s,l)}if(typeof m=="function")return eY(m,x,f,1),b=>m(b,f)&&r(b);if(x in kb)return kb[x](r,f,a,s);if(x in KR){let b=KR[x];return eY(b,x,f,2),E=>b(E,a,f)&&r(E)}throw new Error(`Unknown pseudo-class :${x}`)}function oY(r,e){let a=e.getParent(r);return a&&e.isTag(a)?a:null}function i_e(r,e,a,s,l){let{adapter:d,equals:x}=a;switch(e.type){case Zr.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case Zr.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case Zr.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()),t_e[e.action](r,e,a)}case Zr.Pseudo:return s_e(r,e,a,s,l);case Zr.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 d.getName(D)===f&&r(D)}}case Zr.Descendant:{if(a.cacheResults===!1||typeof WeakSet>"u")return function(D){let b=D;for(;b=oY(b,d);)if(r(b))return!0;return!1};let f=new WeakSet;return function(D){let b=D;for(;b=oY(b,d);)if(!f.has(b)){if(d.isTag(b)&&r(b))return!0;f.add(b)}return!1}}case"_flexibleDescendant":return function(m){let D=m;do if(r(D))return!0;while(D=oY(D,d));return!1};case Zr.Parent:return function(m){return d.getChildren(m).some(D=>d.isTag(D)&&r(D))};case Zr.Child:return function(m){let D=d.getParent(m);return D!=null&&d.isTag(D)&&r(D)};case Zr.Sibling:return function(m){let D=d.getSiblings(m);for(let b=0;b<D.length;b++){let E=D[b];if(x(m,E))break;if(d.isTag(E)&&r(E))return!0}return!1};case Zr.Adjacent:return d.prevElementSibling?function(m){let D=d.prevElementSibling(m);return D!=null&&r(D)}:function(m){let D=d.getSiblings(m),b;for(let E=0;E<D.length;E++){let A=D[E];if(x(m,A))break;d.isTag(A)&&(b=A)}return!!b&&r(b)};case Zr.Universal:{if(e.namespace!=null&&e.namespace!=="*")throw new Error("Namespaced universal selectors are not yet supported by css-select");return r}}}function o_e(r,e,a){let s=ZR(r,e,a);return sY(s,e.adapter)}function ZR(r,e,a){let s=typeof r=="string"?Pb(r):r;return QR(s,e,a)}function u_e(r){return r.type===Zr.Pseudo&&(r.name==="scope"||Array.isArray(r.data)&&r.data.some(e=>e.some(u_e)))}var jjt={type:Zr.Descendant},kjt={type:"_flexibleDescendant"},Njt={type:Zr.Pseudo,name:"scope",data:null};function Mjt(r,{adapter:e},a){let s=!!a?.every(l=>{let d=e.isTag(l)&&e.getParent(l);return l===aY||d&&e.isTag(d)});for(let l of r){if(!(l.length>0&&Ib(l[0])&&l[0].type!==Zr.Descendant))if(s&&!l.some(u_e))l.unshift(jjt);else continue;l.unshift(Njt)}}function QR(r,e,a){var s;r.forEach(JX),a=(s=e.context)!==null&&s!==void 0?s:a;let l=Array.isArray(a),d=a&&(Array.isArray(a)?a:[a]);if(e.relativeSelector!==!1)Mjt(r,e,d);else if(r.some(m=>m.length>0&&Ib(m[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let x=!1,f=r.map(m=>{if(m.length>=2){let[D,b]=m;D.type!==Zr.Pseudo||D.name!=="scope"||(l&&b.type===Zr.Descendant?m[1]=kjt:(b.type===Zr.Adjacent||b.type===Zr.Sibling)&&(x=!0))}return Ojt(m,e,d)}).reduce(Ljt,ed.default.falseFunc);return f.shouldTestNextSiblings=x,f}function Ojt(r,e,a){var s;return r.reduce((l,d)=>l===ed.default.falseFunc?ed.default.falseFunc:i_e(l,d,e,a,QR),(s=e.rootFunc)!==null&&s!==void 0?s:ed.default.trueFunc)}function Ljt(r,e){return e===ed.default.falseFunc||r===ed.default.trueFunc?r:r===ed.default.falseFunc||e===ed.default.trueFunc?e:function(s){return r(s)||e(s)}}var c_e=(r,e)=>r===e,$jt={adapter:HR,equals:c_e};function l_e(r){var e,a,s,l;let d=r??$jt;return(e=d.adapter)!==null&&e!==void 0||(d.adapter=HR),(a=d.equals)!==null&&a!==void 0||(d.equals=(l=(s=d.adapter)===null||s===void 0?void 0:s.equals)!==null&&l!==void 0?l:c_e),d}function cY(r){return function(a,s,l){let d=l_e(s);return r(a,d,l)}}var jnr=cY(o_e),knr=cY(ZR),Nnr=cY(QR);function d_e(r){return function(a,s,l){let d=l_e(l);typeof a!="function"&&(a=ZR(a,d,s));let x=zjt(s,d.adapter,a.shouldTestNextSiblings);return r(a,x,d)}}function zjt(r,e,a=!1){return a&&(r=qjt(r,e)),Array.isArray(r)?e.removeSubsets(r):e.getChildren(r)}function qjt(r,e){let a=Array.isArray(r)?r.slice(0):[r],s=a.length;for(let l=0;l<s;l++){let d=iY(a[l],e);a.push(...d)}return a}var lY=d_e((r,e,a)=>r===uY.default.falseFunc||!e||e.length===0?[]:a.adapter.findAll(r,e)),e5=d_e((r,e,a)=>r===uY.default.falseFunc||!e||e.length===0?null:a.adapter.findOne(r,e));Ue();qt();Ue();var U_e=Or(fs(),1);qt();var X_e=Or(fs(),1),H_e=Or(fs(),1);qt();V0();gY();var DY=(r,e={})=>{let a=r._internal_store;if(!a){a={counts:{}},r._internal_store=a;for(let l of r){let d=l.type,x=l[`${d}_id`];if(!x)continue;let f=Number.parseInt(x.split("_").pop());Number.isNaN(f)||(a.counts[d]=Math.max(a.counts[d]??0,f))}}return new Proxy({},{get:(l,d)=>d==="toArray"?()=>r:{get:x=>r.find(f=>f.type===d&&f[`${d}_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=r.find(E=>E.type===D&&E[m]===x[m]);return b?r.find(E=>E.type===d&&E[`${d}_id`]===b[`${d}_id`]):null},getWhere:x=>{let f=Object.keys(x);return r.find(m=>m.type===d&&f.every(D=>m[D]===x[D]))},list:x=>{let f=x?Object.keys(x):[];return r.filter(m=>m.type===d&&f.every(D=>m[D]===x[D]))},insert:x=>{var D;(D=a.counts)[d]??(D[d]=-1),a.counts[d]++;let f=a.counts[d],m={type:d,[`${d}_id`]:`${d}_${f}`,...x};return e.validateInserts&&(Hf[d]??Yf).parse(m),r.push(m),m},delete:x=>{let f=r.find(m=>m[`${d}_id`]===x);f&&r.splice(r.indexOf(f),1)},update:(x,f)=>{let m=r.find(D=>D.type===d&&D[`${d}_id`]===x);if(m)return Object.assign(m,f),m},select:x=>{if(d==="source_component")return r.find(f=>f.type==="source_component"&&f.name===x.replace(/\./g,""));if(d==="pcb_port"||d==="source_port"||d==="schematic_port"){let[f,m]=x.replace(/\./g,"").split(/[\s\>]+/),D=r.find(E=>E.type==="source_component"&&E.name===f);if(!D)return null;let b=r.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(d==="source_port")return b;if(d==="pcb_port")return r.find(E=>E.type==="pcb_port"&&E.source_port_id===b.source_port_id);if(d==="schematic_port")return r.find(E=>E.type==="schematic_port"&&E.source_port_id===b.source_port_id)}}}})};DY.unparsed=DY;var __e=DY;var $sr=Or(R_e(),1);Fo();function td(r){let e=r.width/2,a=r.height/2;return{minX:r.center.x-e,maxX:r.center.x+e,minY:r.center.y-a,maxY:r.center.y+a}}function sg(r,e){let a=td(r),s=td(e),l=Math.max(a.minX-s.maxX,s.minX-a.maxX,0),d=Math.max(a.minY-s.maxY,s.minY-a.maxY,0),x={x:0,y:0},f={x:0,y:0};return l===0&&d===0?{distance:0,pointA:r.center,pointB:e.center}:(x.x=ms(r.center.x,s.minX,s.maxX),x.y=ms(r.center.y,s.minY,s.maxY),f.x=ms(e.center.x,a.minX,a.maxX),f.y=ms(e.center.y,a.minY,a.maxY),{distance:Math.hypot(x.x-f.x,x.y-f.y),pointA:x,pointB:f})}function ms(r,e,a){return Math.max(e,Math.min(a,r))}function zb(r,e){let a=Number.POSITIVE_INFINITY,s={x:0,y:0},l={x:0,y:0};for(let d of r)for(let x of e){let{distance:f,pointA:m,pointB:D}=sg(d,x);f<a&&(a=f,s=m,l=D)}return{pointA:s,pointB:l,distance:a}}Fo();Fo();var j_e="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var k_e=(r=21)=>{let e="",a=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=j_e[a[r]&63];return e};Fo();var c1=(r,e)=>Math.abs(r.x-e.x)+Math.abs(r.y-e.y),N_e=(r,e)=>{let a=e.x-r.x,s=e.y-r.y;return Math.abs(a)>Math.abs(s)?{dx:Math.sign(a),dy:0}:{dx:0,dy:Math.sign(s)}},z_e=(r,e,a)=>Math.abs(r.x-e.x)*Math.abs(a.dx)+Math.abs(r.y-e.y)*Math.abs(a.dy),q_e=(r,e=.1)=>`${Math.round(r.x/e)},${Math.round(r.y/e)}`,M_e=(r,e)=>Math.abs(r-e)<1e-4,V_e=(r,e,{viaDiameter:a=.5}={})=>{let s=[];for(let l=0;l<r.length-1;l++){let[d,x]=[r[l],r[l+1]],f=l-1>=0?r[l-1]:null,m=M_e(d.y,x.y),D=M_e(d.x,x.x);if(!m&&!D)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${d.x}, ${d.y}), end: (${x.x}, ${x.y})`);let b={type:"rect",layers:[d.layer],center:{x:(d.x+x.x)/2,y:(d.y+x.y)/2},width:m?Math.abs(d.x-x.x):.1,height:D?Math.abs(d.y-x.y):.1,connectedTo:[e]};if(s.push(b),f&&f.layer===d.layer&&d.layer!==x.layer){let E={type:"rect",layers:[d.layer,x.layer],center:{x:d.x,y:d.y},connectedTo:[e],width:a,height:a};s.push(E)}}return s},G_e=class{constructor(r){z(this,"obstacles");z(this,"GRID_STEP",.1);this.obstacles=r.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(r,e,a){a??(a=this.GRID_STEP);for(let s of this.obstacles){let l=s.width/2+a,d=s.height/2+a;if(r>=s.center.x-l&&r<=s.center.x+l&&e>=s.center.y-d&&e<=s.center.y+d)return s}return null}isObstacleAt(r,e,a){return this.getObstacleAt(r,e,a)!==null}getDirectionDistancesToNearestObstacle(r,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 d=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&&r>d&&(s.left=Math.min(s.left,r-x)),e>=m&&e<=f&&r<x&&(s.right=Math.min(s.right,d-r)),r>=d&&r<=x&&e<f&&(s.top=Math.min(s.top,m-e)),r>=d&&r<=x&&e>m&&(s.bottom=Math.min(s.bottom,e-f))}return s}getOrthoDirectionCollisionInfo(r,e,{margin:a=0}={}){let{x:s,y:l}=r,{dx:d,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;d===1&&x===0?l>B&&l<A&&s<D.left&&(w=D.left-s):d===-1&&x===0?l>B&&l<A&&s>D.right&&(w=s-D.right):d===0&&x===1?s>b&&s<E&&l<D.bottom&&(w=D.bottom-l):d===0&&x===-1&&s>b&&s<E&&l>D.top&&(w=l-D.top),w!==null&&w<f&&(f=w,m=D)}return{dx:d,dy:x,wallDistance:f,obstacle:m}}getObstaclesOverlappingRegion(r){let e=[];for(let a of this.obstacles){let{left:s,right:l,top:d,bottom:x}=a;s<=r.maxX&&l>=r.minX&&d<=r.maxY&&x>=r.minY&&e.push(a)}return e}};function Hjt(r){if(r.length<4)return r;let e=[{...r[0]}],a=r[0].layer;for(let s=1;s<r.length;s++){let l={start:r[s-1],end:r[s]},d=r[s].route_type==="via"||r[s-1].route_type==="via";if(r[s].layer!==a||d){e.push({...r[s]}),a=r[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=Wjt(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!==r[s].x||D.y!==r[s].y)&&e.push(r[s])}return e}function Wjt(r,e){if(r.start.x===r.end.x&&e.start.x===e.end.x||r.start.y===r.end.y&&e.start.y===e.end.y)return null;let a;if(r.start.x===r.end.x){let s=r.start.x,l=e.start.y;a={...r.start,x:s,y:l}}else{let s=e.start.x,l=r.start.y;a={...r.start,x:s,y:l}}return O_e(a,r)&&O_e(a,e)?a:null}function O_e(r,e){return r.x>=Math.min(e.start.x,e.end.x)&&r.x<=Math.max(e.start.x,e.end.x)&&r.y>=Math.min(e.start.y,e.end.y)&&r.y<=Math.max(e.start.y,e.end.y)}function Kjt(r){let e=[r[0]];for(let a=1;a<r.length-1;a++){let[s,l,d]=[r[a-1],r[a],r[a+1]];e.push(l),!(l.route_type!=="wire"||s.route_type!=="wire"||d.route_type!=="wire")&&s.layer===l.layer&&l.layer!==d.layer&&e.push({route_type:"via",from_layer:l.layer,to_layer:d.layer,x:l.x,y:l.y})}return e.push(r[r.length-1]),e}var Osr=(0,X_e.default)("autorouter:shortenPathWithShortcuts");function Jjt(r,e){if(r.length<=2)return r;let a=[r[0]];for(let s=1;s<r.length;s++){let l={start:a[a.length-1],end:r[s]},d=-1,x=l.start.x===l.end.x,f=l.start.y===l.end.y;for(let m=s+1;m<r.length;m++){if(m<=d)continue;let D={start:r[m],end:r[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,j=Math.min(l.start.x,l.end.x),O=Math.max(l.start.x,l.end.x),q=Math.min(D.start.x,D.end.x),ee=Math.max(D.start.x,D.end.x),W=Math.min(l.start.y,l.end.y),re=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=j<=ee&&O>=q:A&&(P=W<=K&&re>=L),!P)continue;let U=[],J=a[a.length-1],Q=r[m+2];if(!Q)continue;B&&q<O&&Q.x===q&&U.push({x:q,y:l.start.y,layer:l.start.layer}),B&&ee>j&&Q.x===ee&&U.push({x:ee,y:l.start.y,layer:l.start.layer}),A&&L<re&&Q.y===L&&U.push({x:l.start.x,y:L,layer:l.start.layer}),A&&K>W&&Q.y===K&&U.push({x:l.start.x,y:K,layer:l.start.layer});let de=null;for(let oe of U)if(!(e(J,oe)||e(Q,oe))){de=oe;break}if(de){a.push(de),s=m+1,d=m+1;break}}d===-1&&a.push(r[s])}return a[a.length-1]!==r[r.length-1]&&a.push(r[r.length-1]),a}var u1=(0,U_e.default)("autorouting-dataset:astar"),Y_e=class{constructor(r){z(this,"openSet",[]);z(this,"closedSet",new Set);z(this,"debug",!1);z(this,"debugSolutions");z(this,"debugMessage",null);z(this,"debugTraceCount",0);z(this,"input");z(this,"obstacles");z(this,"allObstacles");z(this,"startNode");z(this,"goalPoint");z(this,"GRID_STEP");z(this,"OBSTACLE_MARGIN");z(this,"MAX_ITERATIONS");z(this,"isRemovePathLoopsEnabled");z(this,"isShortenPathWithShortcutsEnabled");z(this,"GREEDY_MULTIPLIER",1.1);z(this,"iterations",-1);this.input=r.input,this.allObstacles=r.input.obstacles,this.startNode=r.startNode,this.goalPoint=r.goalPoint?{l:0,...r.goalPoint}:void 0,this.GRID_STEP=r.GRID_STEP??.1,this.OBSTACLE_MARGIN=r.OBSTACLE_MARGIN??.15,this.MAX_ITERATIONS=r.MAX_ITERATIONS??100,this.debug=r.debug??u1.enabled,this.isRemovePathLoopsEnabled=r.isRemovePathLoopsEnabled??!1,this.isShortenPathWithShortcutsEnabled=r.isShortenPathWithShortcutsEnabled??!1,this.debug&&(u1.enabled=!0),u1.enabled&&(this.debugSolutions={},this.debugMessage="")}getNeighbors(r){return[]}isSameNode(r,e){return c1(r,e)<this.GRID_STEP}computeG(r,e){return r.g+c1(r,e)}computeH(r){return c1(r,this.goalPoint)}getNodeName(r){return q_e(r,this.GRID_STEP)}solveOneStep(){this.iterations+=1;let{openSet:r,closedSet:e,GRID_STEP:a,goalPoint:s}=this;r.sort((f,m)=>f.f-m.f);let l=r.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:c1(l,f),nodesInPath:l.nodesInPath+1,parent:l,enterMarginCost:f.enterMarginCost,travelMarginCostFactor:f.travelMarginCostFactor};r.push(A),x.push(A)}}return u1.enabled&&(r.sort((f,m)=>f.f-m.f),this.drawDebugSolution({current:l,newNeighbors:x})),{solved:!1,current:l,newNeighbors:x}}getStartNode(r){return{x:r.pointsToConnect[0].x,y:r.pointsToConnect[0].y,manDistFromParent:0,f:0,g:0,h:0,nodesInPath:0,parent:null}}layerToIndex(r){return 0}indexToLayer(r){return"top"}preprocessConnectionBeforeSolving(r){return r}solveConnection(r){if(r.pointsToConnect.length>2)throw new Error("GeneralizedAstarAutorouter doesn't currently support 2+ points in a connection");r=this.preprocessConnectionBeforeSolving(r);let{pointsToConnect:e}=r;for(this.iterations=0,this.closedSet=new Set,this.startNode=this.getStartNode(r),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=[],d=s;for(;d;){let x=d.l;l.unshift({x:d.x,y:d.y,layer:x!==void 0?this.indexToLayer(x):e[0].layer}),d=d.parent}return u1.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations
952
952
  `),this.isRemovePathLoopsEnabled&&(l=Hjt(l)),this.isShortenPathWithShortcutsEnabled&&(l=Jjt(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:r.name}}if(this.openSet.length===0)break}return u1.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations (failed)
953
953
  `),{solved:!1,connectionName:r.name}}createObstacleList({dominantLayer:r,connection:e,obstaclesFromTraces:a}){return new G_e(this.allObstacles.filter(s=>!s.connectedTo.includes(e.name)).filter(s=>s.layers.includes(r)).concat(a??[]))}postprocessConnectionSolveResult(r,e){return e}solve(){let r=[],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),r.push(l),u1.enabled&&this.drawDebugTraceObstacles(e),l.solved&&e.push(...V_e(l.route.map(d=>({x:d.x,y:d.y,layer:d.layer??s})),a.name))}return r}solveAndMapToTraces(){return this.solve().flatMap(e=>e.solved?[{type:"pcb_trace",pcb_trace_id:`pcb_trace_for_${e.connectionName}`,route:Kjt(e.route.map(a=>({route_type:"wire",x:a.x,y:a.y,width:this.input.minTraceWidth,layer:a.layer})))}]:[])}getDebugGroup(){let r=`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?r:null}drawDebugTraceObstacles(r){let{debugTraceCount:e,debugSolutions:a}=this;for(let s in a)s.startsWith(`t${e}_`)&&a[s].push(...r.map((l,d)=>({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_${d}`,height:l.height})))}drawDebugSolution({current:r,newNeighbors:e}){let a=this.getDebugGroup();if(!a)return;let{openSet:s,debugTraceCount:l,debugSolutions:d}=this;d[a]??(d[a]=[]);let x=d[a];x.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${r.x}_${r.y}`,font:"tscircuit2024",font_size:.25,text:"X"+(r.l!==void 0?r.l:""),pcb_component_id:"",layer:"top",anchor_position:{x:r.x,y:r.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(r.parent){let f=[],m=r;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_${r.x}_${r.y}`,layer:"top",route:f,stroke_width:.01})}}},Zjt=(0,H_e.default)("autorouting-dataset:infinite-grid-ijump-astar:get-distance-to-overcome-obstacle");function EY({node:r,travelDir:e,wallDir:a,obstacle:s,obstacles:l,obstaclesInRow:d=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-r.y:D=r.y-(s.center.y-s.height/2):e.dx>0?D=s.center.x+s.width/2-r.x:D=r.x-(s.center.x-s.width/2),D+=x,f&&d<m){let b=l.getObstacleAt(r.x+e.dx*D+a.dx*(a.wallDistance+.001),r.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 Zjt("next obstacle on path is bigger, not trying to overcome it"),D;let w=EY({node:{x:r.x+e.dx*D,y:r.y+e.dy*D},travelDir:e,wallDir:a,obstacle:b,obstacles:l,obstaclesInRow:d+1,SHOULD_DETECT_CONJOINED_OBSTACLES:f,MAX_CONJOINED_OBSTACLES:m,OBSTACLE_MARGIN:x});D+=w}}return D}var Qjt=class extends Y_e{constructor(){super(...arguments);z(this,"MAX_ITERATIONS",200)}getNeighbors(e){let a=this.obstacles,s=this.goalPoint,l;e.parent?l=N_e(e.parent,e):l=N_e(e,s);let d=[{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 d){let m=null;e?.obstacleHit&&(m=EY({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=z_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 ekt(r,e=4){let{center:a,width:s,height:l,rotation:d}=r,x=[],f=d*Math.PI/180,m=Math.cos(f),D=Math.sin(f),b=(d%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,j=-w*D,O=A*1.1,q=Math.abs(l*m)+Math.abs(A*D);x.push({center:{x:a.x+P,y:a.y+j},width:O,height:q})}}else{let A=l/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*D,j=w*m,O=Math.abs(s*m)+Math.abs(A*D),q=A*1.1;x.push({center:{x:a.x+P,y:a.y+j},width:O,height:q})}}return x}var i5=["top","inner1","inner2","bottom"],W_e=(r,e)=>{let a=l=>e?l.concat(l.map(d=>e?.getNetConnectedToId(d)).filter(Boolean)):l,s=[];for(let l of r)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 d={center:{x:l.x,y:l.y},width:l.width,height:l.height,rotation:l.ccw_rotation},x=ekt(d);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:i5,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:i5,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:i5,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:i5,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 d=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(...d)}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 L_e(r){let{pcbConnMap:e,goalElementId:a}=r;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 W_e(s).map(l=>({...l,connectedTo:[a]}))}var K_e=r=>{let{connection:e,pcbConnMap:a}=r;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 d=L_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=L_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(d.length<=1&&x.length<=1)return{...e,startPoint:s,endPoint:l,goalBoxes:[]};let f=zb(d,x),m,D,b;return d.length>=x.length?(m={...l,...f.pointB},D={...s,...f.pointA},b=d):(m={...s,...f.pointA},D={...l,...f.pointB},b=x),{startPoint:m,endPoint:D,goalBoxes:b,name:e.name,pointsToConnect:[m,D]}},tkt=(r,e={})=>{let a={minTraceWidth:.1};a.layerCount=e.layerCount??1,a.obstacles=W_e(r,e.connMap),a.connections=[];for(let l of r)if(l.type==="source_trace"){let d={name:l.source_trace_id,pointsToConnect:l.connected_source_port_ids.map(x=>{let f=__e(r).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 s5(r);d=K_e({connection:d,pcbConnMap:x})}a.connections.push(d),rkt(a.obstacles,d.pointsToConnect,d.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 d of l.pointsToConnect)s.minX=Math.min(s.minX,d.x),s.maxX=Math.max(s.maxX,d.x),s.minY=Math.min(s.minY,d.y),s.maxY=Math.max(s.maxY,d.y);return a.bounds=s,a},rkt=(r,e,a)=>{for(let s of e)for(let l of r)nkt(s,l)&&l.connectedTo.push(a)};function nkt(r,e){let a=e.width/2,s=e.height/2;if(e.type==="rect")return r.x>=e.center.x-a&&r.x<=e.center.x+a&&r.y>=e.center.y-s&&r.y<=e.center.y+s;if(e.type==="oval"){let l=(r.x-e.center.x)/a,d=(r.y-e.center.y)/s;return l*l+d*d<=1}return!1}function $_e(r,e){let a=e.x>r.x?1:e.x<r.x?-1:0,s=e.y>r.y?1:e.y<r.y?-1:0,l=e.l>r.l?1:e.l<r.l?-1:0;return{dx:a,dy:s,dl:l}}var vY={1:["top"],2:["top","bottom"],4:["top","inner1","inner2","bottom"]},akt=r=>vY[r];function J_e(r,e){let s=vY[r].indexOf(e);if(s===-1)throw new Error(`Invalid layer for getLayerIndex (for layerCount === ${r}): "${e}"`);return s}function skt(r,e){let s=vY[r][e];if(!s)throw new Error(`Invalid index for indexToLayer (for layerCount === ${r}): "${e}"`);return s}var ikt=class extends G_e{constructor(e,a){super([]);z(this,"obstacles");z(this,"GRID_STEP",.1);z(this,"layerCount");this.layerCount=e;let s=akt(e);this.obstacles=a.flatMap(l=>l.layers.filter(d=>s.includes(d)).map(d=>({...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:J_e(e,d)})))}getObstacleAt(e,a,s,l){l??(l=this.GRID_STEP);for(let d of this.obstacles){if(d.l!==s)continue;let x=d.width/2+l,f=d.height/2+l;if(e>=d.center.x-x&&e<=d.center.x+x&&a>=d.center.y-f&&a<=d.center.y+f)return d}return null}isObstacleAt(e,a,s,l){return this.getObstacleAt(e,a,s,l)!==null}getDirectionDistancesToNearestObstacle3d(e,a,s){let{GRID_STEP:l}=this,d={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&&(d.left=Math.min(d.left,e-m)),a>=b&&a<=D&&e<m&&(d.right=Math.min(d.right,f-e)),e>=f&&e<=m&&a<D&&(d.top=Math.min(d.top,b-a)),e>=f&&e<=m&&a>b&&(d.bottom=Math.min(d.bottom,a-D))}return d}getOrthoDirectionCollisionInfo(e,a,{margin:s=0}={}){let{x:l,y:d,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,d,A,s)?(b=1,E=this.getObstacleAt(l,d,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,j=A.bottom-s,O=null;f===1&&m===0?d>j&&d<P&&l<A.left&&(O=A.left-l):f===-1&&m===0?d>j&&d<P&&l>A.right&&(O=l-A.right):f===0&&m===1?l>B&&l<w&&d<A.bottom&&(O=A.bottom-d):f===0&&m===-1&&l>B&&l<w&&d>A.top&&(O=d-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:d,top:x,bottom:f}=s;l<=e.maxX&&d>=e.minX&&x>=e.minY&&f<=e.maxY&&a.push(s)}return a}},o5=class extends Y_e{constructor(e){super(e);z(this,"MAX_ITERATIONS",500);z(this,"VIA_COST",4);z(this,"VIA_DIAMETER",.5);z(this,"allowLayerChange",!0);z(this,"layerCount");z(this,"obstacles");z(this,"optimizeWithGoalBoxes");z(this,"connMap");z(this,"pcbConnMap");z(this,"GOAL_RUSH_FACTOR",1.1);z(this,"defaultGoalViaMargin",.5);z(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 s5,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?K_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_${k_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 ikt(this.layerCount,this.allObstacles.filter(d=>!d.connectedTo.includes(l)).concat(s??[]))}computeG(e,a){let s=e.g+c1(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 J_e(this.layerCount,e)}indexToLayer(e){return skt(this.layerCount,e)}getNodeName(e){return`${q_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=[],d=[{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 d){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=c1(e,s);if(l<=this.OBSTACLE_MARGIN)return this.getNeighborsSurroundingGoal(e);let d;e.parent?d=$_e(e.parent,e):d=$_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=c1(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===d.dx*-1&&E.dy===d.dy*-1&&E.dl===d.dl*-1?!1:!(E.dx===d.dx&&E.dy===d.dy&&E.dl===d.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(q=>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:q}).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=EY({node:e,travelDir:E,wallDir:{...d,wallDistance:this.OBSTACLE_MARGIN},obstacle:e.obstacleHit,obstacles:a,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let P=z_e(e,s,E),j=(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&&j){let O=e.l===s.l,q=0;!O&&Math.abs(P-l)<this.GRID_STEP&&(q=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin),b.push({...E,travelDistance:P-q,enterMarginCost:0,travelMarginCostFactor:1})}else if(w!==null&&w<E.wallDistance){for(let{margin:O,enterCost:q,travelCostFactor:ee}of this.marginsWithCosts)w-this.OBSTACLE_MARGIN+O*2<E.wallDistance&&b.push({...E,travelDistance:w-this.OBSTACLE_MARGIN+O,enterMarginCost:q,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:q,travelCostFactor:ee}of this.marginsWithCosts)E.wallDistance>this.largestMargin+O&&b.push({...E,travelDistance:E.wallDistance-O,enterMarginCost:q,travelMarginCostFactor:ee})}else if(E.wallDistance!==1/0)for(let{margin:O,enterCost:q,travelCostFactor:ee}of this.marginsWithCosts)E.wallDistance>O&&b.push({...E,travelDistance:E.wallDistance-O,enterMarginCost:q,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 Z_e(r){let e=tkt(r),a=new Qjt({input:e});return{solution:a.solveAndMapToTraces(),debugSolutions:a.debugSolutions,debugMessage:a.debugMessage}}Ue();Ue();qt();Ue();Ue();qt();qt();Ue();Ue();Ue();Ue();Ue();qt();Ue();Ue();Ue();qt();Ue();Ue();qt();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();qt();Ue();qt();Ue();qt();Ue();qt();qt();Ue();qt();Ue();Ue();qt();Ue();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();qt();Ue();qt();Ue();Ue();qt();Ue();qt();Ue();Ue();Ue();qt();Ue();qt();Ue();Ue();qt();Ue();Ue();Ue();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();Ue();qt();Ue();Ue();qt();qt();Ue();Ue();qt();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();qt();Ue();qt();Ue();qt();Ue();Ue();Ue();var cr=r=>{};cr("extra props b");cr("missing props b");cr(!0);cr("property a has mismatched types");var okt=v.enum(["up","down","left","right"]),rir=v.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);cr(!0);cr(!0);var G0=v.array(v.string().or(v.number()));cr(!0);var l5=v.object({x:Be,y:Be,z:Be}),ukt=v.object({x:v.union([v.number(),v.string()]),y:v.union([v.number(),v.string()]),z:v.union([v.number(),v.string()])}),Mp=v.object({rotationOffset:v.number().or(ukt).optional(),positionOffset:l5.optional(),size:l5.optional(),modelUnitToMmScale:Be.optional()});cr(!0);var ckt=Mp.extend({stlUrl:v.string()}),lkt=Mp.extend({objUrl:v.string(),mtlUrl:v.string().optional()}),dkt=Mp.extend({gltfUrl:v.string()}),pkt=Mp.extend({glbUrl:v.string()}),xkt=Mp.extend({stepUrl:v.string()}),fkt=Mp.extend({wrlUrl:v.string()}),hkt=Mp.extend({jscad:v.record(v.any())}),nAe=v.union([v.null(),v.string(),v.custom(r=>r&&typeof r=="object"&&"type"in r&&"props"in r),ckt,lkt,dkt,pkt,xkt,fkt,hkt]);cr(!0);var mkt=v.custom(r=>!0),gkt=v.custom(r=>!0),Ta=v.object({pcbX:Be.optional(),pcbY:Be.optional(),pcbRotation:Gn.optional(),pcbPositionAnchor:v.string().optional(),layer:dn.optional(),pcbMarginTop:Be.optional(),pcbMarginRight:Be.optional(),pcbMarginBottom:Be.optional(),pcbMarginLeft:Be.optional(),pcbMarginX:Be.optional(),pcbMarginY:Be.optional(),pcbRelative:v.boolean().optional(),relative:v.boolean().optional()});cr(!0);var d5=v.object({pcbX:Be.optional(),pcbY:Be.optional(),pcbRotation:Gn.optional(),pcbPositionAnchor:v.string().optional(),pcbMarginTop:Be.optional(),pcbMarginRight:Be.optional(),pcbMarginBottom:Be.optional(),pcbMarginLeft:Be.optional(),pcbMarginX:Be.optional(),pcbMarginY:Be.optional(),schMarginTop:Be.optional(),schMarginRight:Be.optional(),schMarginBottom:Be.optional(),schMarginLeft:Be.optional(),schMarginX:Be.optional(),schMarginY:Be.optional(),schX:Be.optional(),schY:Be.optional(),schRotation:Gn.optional(),layer:dn.optional(),footprint:mkt.optional(),symbol:gkt.optional(),relative:v.boolean().optional(),schRelative:v.boolean().optional(),pcbRelative:v.boolean().optional()});cr(!0);var Dkt=v.object({supplierPartNumbers:v.record(Lm,v.array(v.string())).optional()});cr(!0);var ykt=v.object({providesPower:v.boolean().optional(),requiresPower:v.boolean().optional(),providesGround:v.boolean().optional(),requiresGround:v.boolean().optional(),providesVoltage:v.union([v.string(),v.number()]).optional(),requiresVoltage:v.union([v.string(),v.number()]).optional(),doNotConnect:v.boolean().optional(),includeInBoardPinout:v.boolean().optional(),ratsNestColor:v.string().optional()});cr(!0);var gs=d5.merge(Dkt).extend({key:v.any().optional(),name:v.string(),cadModel:nAe.optional(),children:v.any().optional(),symbolName:v.string().optional(),doNotPlace:v.boolean().optional(),pinAttributes:v.record(v.string(),ykt).optional()});cr(!0);var _Y=["pin1","left","pin2","right"],p5=["pin1","left","anode","pos","pin2","right","cathode","neg"],xir=Be.or(v.enum(["2x","3x","4x"])),Op=v.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)");cr(!0);var u5=v.object({pins:v.array(v.union([v.number(),v.string()])),direction:v.union([v.literal("top-to-bottom"),v.literal("left-to-right"),v.literal("bottom-to-top"),v.literal("right-to-left")])}),Ub=v.object({leftSize:v.number().optional().describe("@deprecated, use leftPinCount"),topSize:v.number().optional().describe("@deprecated, use topPinCount"),rightSize:v.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:v.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:v.number().optional(),rightPinCount:v.number().optional(),topPinCount:v.number().optional(),bottomPinCount:v.number().optional(),leftSide:u5.optional(),rightSide:u5.optional(),topSide:u5.optional(),bottomSide:u5.optional()}),AY=Ub;cr(!0);var x5=v.record(v.object({marginLeft:Be.optional(),marginRight:Be.optional(),marginTop:Be.optional(),marginBottom:Be.optional(),leftMargin:Be.optional(),rightMargin:Be.optional(),topMargin:Be.optional(),bottomMargin:Be.optional()}));cr(!0);var ec=v.string().regex(/^[A-Za-z0-9_]+$/),Vb=v.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),ig=v.object({x:Be,y:Be}),Gb=v.object({edit_event_id:v.string(),in_progress:v.boolean().optional(),created_at:v.number()});cr(!0);var bkt=Gb.extend({pcb_edit_event_type:v.literal("edit_component_location").describe("deprecated"),edit_event_type:v.literal("edit_pcb_component_location"),pcb_component_id:v.string(),original_center:v.object({x:v.number(),y:v.number()}),new_center:v.object({x:v.number(),y:v.number()})});cr(!0);var Fkt=Gb.extend({pcb_edit_event_type:v.literal("edit_trace_hint").describe("deprecated"),edit_event_type:v.literal("edit_pcb_trace_hint").optional(),pcb_port_id:v.string(),pcb_trace_hint_id:v.string().optional(),route:v.array(v.object({x:v.number(),y:v.number(),via:v.boolean().optional()}))});cr(!0);var Ekt=Gb.extend({edit_event_type:v.literal("edit_schematic_component_location"),schematic_component_id:v.string(),original_center:v.object({x:v.number(),y:v.number()}),new_center:v.object({x:v.number(),y:v.number()})});cr(!0);var wir=Gb.extend({edit_event_type:v.literal("edit_pcb_group_location"),pcb_group_id:v.string(),original_center:v.object({x:v.number(),y:v.number()}),new_center:v.object({x:v.number(),y:v.number()})});cr(!0);var Pir=Gb.extend({edit_event_type:v.literal("edit_schematic_group_location"),schematic_group_id:v.string(),original_center:v.object({x:v.number(),y:v.number()}),new_center:v.object({x:v.number(),y:v.number()})});cr(!0);var jir=v.union([bkt,Fkt,Ekt]);cr(!0);var vkt=v.object({selector:v.string(),relative_to:v.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Hr});cr(!0);var Ckt=v.object({pcb_port_selector:v.string(),offsets:v.array(bo)});cr(!0);var _kt=v.object({selector:v.string(),relative_to:v.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Hr});cr(!0);var Akt=v.object({pcb_placements:v.array(vkt).optional(),manual_trace_hints:v.array(Ckt).optional(),schematic_placements:v.array(_kt).optional()});cr(!0);var f5=v.string().or(v.array(v.string()).readonly()).or(v.array(v.string())),l1=r=>v.record(v.enum(r),f5),qb=v.object({layoutMode:v.enum(["grid","flex","match-adapt","relative","none"]).optional(),position:v.enum(["absolute","relative"]).optional(),grid:v.boolean().optional(),gridCols:v.number().or(v.string()).optional(),gridRows:v.number().or(v.string()).optional(),gridTemplateRows:v.string().optional(),gridTemplateColumns:v.string().optional(),gridTemplate:v.string().optional(),gridGap:v.number().or(v.string()).optional(),gridRowGap:v.number().or(v.string()).optional(),gridColumnGap:v.number().or(v.string()).optional(),flex:v.boolean().or(v.string()).optional(),flexDirection:v.enum(["row","column"]).optional(),alignItems:v.enum(["start","center","end","stretch"]).optional(),justifyContent:v.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),flexRow:v.boolean().optional(),flexColumn:v.boolean().optional(),gap:v.number().or(v.string()).optional(),pack:v.boolean().optional().describe("Pack the contents of this group using a packing strategy"),packOrderStrategy:v.enum(["largest_to_smallest","first_to_last","highest_to_lowest_pin_count"]).optional(),packPlacementStrategy:v.enum(["shortest_connection_along_outline"]).optional(),padding:pe.optional(),paddingLeft:pe.optional(),paddingRight:pe.optional(),paddingTop:pe.optional(),paddingBottom:pe.optional(),paddingX:pe.optional(),paddingY:pe.optional(),width:pe.optional(),height:pe.optional(),matchAdapt:v.boolean().optional(),matchAdaptTemplate:v.any().optional()});cr(!0);var Q_e=v.object({strokeWidth:pe.optional(),dashed:v.boolean().optional(),solid:v.boolean().optional()}),Rkt=v.object({serverUrl:v.string().optional(),inputFormat:v.enum(["simplified","circuit-json"]).optional(),serverMode:v.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:v.boolean().optional(),cache:v.custom(r=>!0).optional(),traceClearance:pe.optional(),groupMode:v.enum(["sequential_trace","subcircuit","sequential-trace"]).optional(),algorithmFn:v.custom(r=>typeof r=="function"||r===void 0).optional(),preset:v.enum(["sequential_trace","subcircuit","auto","auto_local","auto_cloud","freerouting","sequential-trace","auto-local","auto-cloud"]).optional(),local:v.boolean().optional()}),aAe=v.union([Rkt,v.literal("sequential_trace"),v.literal("subcircuit"),v.literal("auto"),v.literal("auto_local"),v.literal("auto_cloud"),v.literal("freerouting"),v.literal("sequential-trace"),v.literal("auto-local"),v.literal("auto-cloud")]),sAe=d5.extend({name:v.string().optional(),children:v.any().optional(),schTitle:v.string().optional(),key:v.any().optional(),showAsSchematicBox:v.boolean().optional(),connections:v.record(v.string(),f5.optional()).optional(),schPinArrangement:AY.optional(),...qb.shape,grid:qb.shape.grid.describe("@deprecated use pcbGrid"),flex:qb.shape.flex.describe("@deprecated use pcbFlex"),pcbGrid:v.boolean().optional(),pcbGridCols:v.number().or(v.string()).optional(),pcbGridRows:v.number().or(v.string()).optional(),pcbGridTemplateRows:v.string().optional(),pcbGridTemplateColumns:v.string().optional(),pcbGridTemplate:v.string().optional(),pcbGridGap:v.number().or(v.string()).optional(),pcbGridRowGap:v.number().or(v.string()).optional(),pcbGridColumnGap:v.number().or(v.string()).optional(),pcbFlex:v.boolean().or(v.string()).optional(),pcbFlexGap:v.number().or(v.string()).optional(),pcbFlexDirection:v.enum(["row","column"]).optional(),pcbAlignItems:v.enum(["start","center","end","stretch"]).optional(),pcbJustifyContent:v.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),pcbFlexRow:v.boolean().optional(),pcbFlexColumn:v.boolean().optional(),pcbGap:v.number().or(v.string()).optional(),pcbPack:v.boolean().optional(),pcbPackGap:v.number().or(v.string()).optional(),schGrid:v.boolean().optional(),schGridCols:v.number().or(v.string()).optional(),schGridRows:v.number().or(v.string()).optional(),schGridTemplateRows:v.string().optional(),schGridTemplateColumns:v.string().optional(),schGridTemplate:v.string().optional(),schGridGap:v.number().or(v.string()).optional(),schGridRowGap:v.number().or(v.string()).optional(),schGridColumnGap:v.number().or(v.string()).optional(),schFlex:v.boolean().or(v.string()).optional(),schFlexGap:v.number().or(v.string()).optional(),schFlexDirection:v.enum(["row","column"]).optional(),schAlignItems:v.enum(["start","center","end","stretch"]).optional(),schJustifyContent:v.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),schFlexRow:v.boolean().optional(),schFlexColumn:v.boolean().optional(),schGap:v.number().or(v.string()).optional(),schPack:v.boolean().optional(),schMatchAdapt:v.boolean().optional(),pcbWidth:pe.optional(),pcbHeight:pe.optional(),schWidth:pe.optional(),schHeight:pe.optional(),pcbLayout:qb.optional(),schLayout:qb.optional(),cellBorder:Q_e.nullable().optional(),border:Q_e.nullable().optional(),schPadding:pe.optional(),schPaddingLeft:pe.optional(),schPaddingRight:pe.optional(),schPaddingTop:pe.optional(),schPaddingBottom:pe.optional(),pcbPadding:pe.optional(),pcbPaddingLeft:pe.optional(),pcbPaddingRight:pe.optional(),pcbPaddingTop:pe.optional(),pcbPaddingBottom:pe.optional()}),iAe=v.custom(r=>"findPart"in r),RY=sAe.extend({manualEdits:Akt.optional(),schAutoLayoutEnabled:v.boolean().optional(),schTraceAutoLabelEnabled:v.boolean().optional(),schMaxTraceDistance:Be.optional(),routingDisabled:v.boolean().optional(),defaultTraceWidth:pe.optional(),minTraceWidth:pe.optional(),partsEngine:iAe.optional(),pcbRouteCache:v.custom(r=>!0).optional(),autorouter:aAe.optional(),square:v.boolean().optional(),emptyArea:v.string().optional(),filledArea:v.string().optional(),width:Be.optional(),height:Be.optional(),outline:v.array(ig).optional(),outlineOffsetX:Be.optional(),outlineOffsetY:Be.optional()}),Skt=RY.extend({subcircuit:v.literal(!0)}),oAe=v.discriminatedUnion("subcircuit",[sAe.extend({subcircuit:v.literal(!1).optional()}),Skt]);cr(!0);cr(!0);cr(!0);var SY=RY.extend({material:v.enum(["fr4","fr1"]).default("fr4"),layers:v.union([v.literal(2),v.literal(4)]).default(2),borderRadius:Be.optional(),boardAnchorPosition:ig.optional(),boardAnchorAlignment:Vb.optional()});cr(!0);var Vir=RY.extend({padding:Be.optional(),paddingLeft:Be.optional(),paddingRight:Be.optional(),paddingTop:Be.optional(),paddingBottom:Be.optional()});cr(!0);var Bkt=v.string().or(v.array(v.string()).readonly()).or(v.array(v.string())),wkt=v.custom().pipe(v.record(v.string(),Bkt)),Tkt=v.record(ec,ec.or(v.array(ec).readonly()).or(v.array(ec)));cr(!0);var Pkt=v.object({manufacturerPartNumber:v.string().optional(),supplierPartNumber:v.record(Lm,v.array(v.string())).optional()}),og=gs.extend({manufacturerPartNumber:v.string().optional(),pinLabels:Tkt.optional(),showPinAliases:v.boolean().optional(),pcbPinLabels:v.record(v.string(),v.string()).optional(),internallyConnectedPins:v.array(v.array(v.union([v.string(),v.number()]))).optional(),externallyConnectedPins:v.array(v.array(v.string())).optional(),schPinArrangement:Ub.optional(),schPortArrangement:Ub.optional(),pinCompatibleVariants:v.array(Pkt).optional(),schPinStyle:x5.optional(),schPinSpacing:Be.optional(),schWidth:Be.optional(),schHeight:Be.optional(),noSchematicRepresentation:v.boolean().optional(),connections:wkt.optional()});cr(!0);var uAe=og;cr(!0);var BY=gs.extend({manufacturerPartNumber:v.string().optional(),pinLabels:v.record(v.number().or(ec),ec.or(v.array(ec))).optional(),schPinStyle:x5.optional(),schPinSpacing:Be.optional(),schWidth:Be.optional(),schHeight:Be.optional(),schDirection:v.enum(["left","right"]).optional(),schPinArrangement:AY.optional(),schPortArrangement:Ub.optional(),pcbPinLabels:v.record(v.string(),v.string()).optional(),pinCount:v.union([v.literal(2),v.literal(3)]).optional(),internallyConnectedPins:v.array(v.array(v.union([v.string(),v.number()]))).optional(),connections:v.custom().pipe(v.record(v.string(),f5)).optional()});cr(!0);var cAe=BY.extend({bridgedPins:v.array(v.array(v.string())).optional(),bridged:v.boolean().optional()});cr(!0);var Zir=gs.extend({manufacturerPartNumber:v.string().optional(),pinLabels:v.record(v.number().or(ec),ec.or(v.array(ec))).optional(),schPinStyle:x5.optional(),schPinSpacing:Be.optional(),schWidth:Be.optional(),schHeight:Be.optional(),schDirection:v.enum(["left","right"]).optional(),schPortArrangement:Ub.optional(),internallyConnectedPins:v.array(v.array(v.union([v.string(),v.number()]))).optional(),standard:v.enum(["usb_c","m2"]).optional()});cr(!0);var lAe=gs.extend({currentRating:v.union([v.number(),v.string()]),voltageRating:v.union([v.number(),v.string()]).optional(),schShowRatings:v.boolean().optional(),schOrientation:Op.optional(),connections:v.record(v.string(),v.union([v.string(),v.array(v.string()).readonly(),v.array(v.string())])).optional()}),c5=v.custom().transform(r=>{if(r!==void 0)return Be.parse(r)}),dAe=v.discriminatedUnion("shape",[Ta.omit({pcbRotation:!0,layer:!0}).extend({name:v.string().optional(),connectsTo:v.string().or(v.array(v.string())).optional(),shape:v.literal("circle"),holeDiameter:Be,outerDiameter:Be,portHints:G0.optional()}),Ta.omit({layer:!0}).extend({name:v.string().optional(),connectsTo:v.string().or(v.array(v.string())).optional(),shape:v.literal("oval"),outerWidth:Be,outerHeight:Be,holeWidth:c5,holeHeight:c5,innerWidth:Be.optional().describe("DEPRECATED use holeWidth"),innerHeight:Be.optional().describe("DEPRECATED use holeHeight"),portHints:G0.optional()}),Ta.omit({layer:!0}).extend({name:v.string().optional(),connectsTo:v.string().or(v.array(v.string())).optional(),shape:v.literal("pill"),rectPad:v.boolean().optional(),outerWidth:Be,outerHeight:Be,holeWidth:c5,holeHeight:c5,innerWidth:Be.optional().describe("DEPRECATED use holeWidth"),innerHeight:Be.optional().describe("DEPRECATED use holeHeight"),portHints:G0.optional(),holeOffsetX:Be.optional(),holeOffsetY:Be.optional()}),Ta.omit({pcbRotation:!0,layer:!0}).extend({name:v.string().optional(),connectsTo:v.string().or(v.array(v.string())).optional(),shape:v.literal("circular_hole_with_rect_pad"),holeDiameter:Be,rectPadWidth:Be,rectPadHeight:Be,rectBorderRadius:Be.optional(),holeShape:v.literal("circle").optional(),padShape:v.literal("rect").optional(),portHints:G0.optional(),holeOffsetX:Be.optional(),holeOffsetY:Be.optional()}),Ta.omit({pcbRotation:!0,layer:!0}).extend({name:v.string().optional(),connectsTo:v.string().or(v.array(v.string())).optional(),shape:v.literal("pill_hole_with_rect_pad"),holeShape:v.literal("pill"),padShape:v.literal("rect"),holeWidth:Be,holeHeight:Be,rectPadWidth:Be,rectPadHeight:Be,portHints:G0.optional(),holeOffsetX:Be.optional(),holeOffsetY:Be.optional()})]).refine(r=>("innerWidth"in r&&r.innerWidth!==void 0&&(r.holeWidth??(r.holeWidth=r.innerWidth)),"innerHeight"in r&&r.innerHeight!==void 0&&(r.holeHeight??(r.holeHeight=r.innerHeight)),r));cr(!0);var Ikt=["pin1","pin2","pos","neg"],pAe=gs.extend({resistance:Bp,pullupFor:v.string().optional(),pullupTo:v.string().optional(),pulldownFor:v.string().optional(),pulldownTo:v.string().optional(),schOrientation:Op.optional(),connections:l1(Ikt).optional()}),xAe=_Y;cr(!0);var fAe=gs.extend({maxResistance:Bp,pinVariant:v.enum(["two_pin","three_pin"]).optional()});cr(!0);var jkt=_Y,hAe=gs.extend({frequency:Oc,loadCapacitance:Xl,manufacturerPartNumber:v.string().optional(),mpn:v.string().optional(),pinVariant:v.enum(["two_pin","four_pin"]).optional(),schOrientation:Op.optional(),connections:l1(jkt).optional()});cr(!0);var mAe=gs.extend({frequency:Oc,loadCapacitance:Xl,pinVariant:v.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});cr(!0);var por=SY.extend({leftPinCount:v.number().optional(),rightPinCount:v.number().optional(),topPinCount:v.number().optional(),bottomPinCount:v.number().optional(),leftPins:v.array(v.string()).optional(),rightPins:v.array(v.string()).optional(),topPins:v.array(v.string()).optional(),bottomPins:v.array(v.string()).optional(),pinPitch:Be.optional(),innerHoles:v.boolean().optional()});cr(!0);var kkt=["pin1","pin2","pos","neg","anode","cathode"],gAe=gs.extend({capacitance:Xl,maxVoltageRating:Us.optional(),schShowRatings:v.boolean().optional().default(!1),polarized:v.boolean().optional().default(!1),decouplingFor:v.string().optional(),decouplingTo:v.string().optional(),bypassFor:v.string().optional(),bypassTo:v.string().optional(),maxDecouplingTraceLength:v.number().optional(),schOrientation:Op.optional(),connections:l1(kkt).optional()}),DAe=p5;cr(!0);var gor=v.object({name:v.string(),connectsTo:v.string().or(v.array(v.string())).optional(),ratsNestColor:v.string().optional()});cr(!0);var yor=v.object({name:v.string().optional(),pcbOnly:v.boolean().optional(),schOnly:v.boolean().optional()});cr(!0);var Nkt=v.object({pcb:v.literal(!0).optional(),xDist:Be,left:v.string(),right:v.string(),edgeToEdge:v.literal(!0).optional(),centerToCenter:v.literal(!0).optional()});cr(!0);var Mkt=v.object({pcb:v.literal(!0).optional(),yDist:Be,top:v.string(),bottom:v.string(),edgeToEdge:v.literal(!0).optional(),centerToCenter:v.literal(!0).optional()});cr(!0);var Okt=v.object({pcb:v.literal(!0).optional(),sameY:v.literal(!0).optional(),for:v.array(v.string())});cr(!0);var Lkt=v.object({pcb:v.literal(!0).optional(),sameX:v.literal(!0).optional(),for:v.array(v.string())});cr(!0);var yAe=v.union([Nkt,Mkt,Okt,Lkt]);cr(!0);var $kt=Ta.omit({layer:!0,pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("rect"),width:Be,height:Be});cr(!0);var zkt=Ta.omit({layer:!0,pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("circle"),radius:Be});cr(!0);var qkt=Ta.omit({layer:!0,pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("polygon"),points:v.array(ig)});cr(!0);var bAe=v.discriminatedUnion("shape",[$kt,zkt,qkt]),Ukt=Ta.omit({pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("rect"),width:Be,height:Be,rectBorderRadius:Be.optional(),portHints:G0.optional(),coveredWithSolderMask:v.boolean().optional()});cr(!0);var Vkt=Ta.omit({pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("rotated_rect"),width:Be,height:Be,ccwRotation:v.number(),portHints:G0.optional(),coveredWithSolderMask:v.boolean().optional()});cr(!0);var Gkt=Ta.omit({pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("circle"),radius:Be,portHints:G0.optional(),coveredWithSolderMask:v.boolean().optional()});cr(!0);var Xkt=Ta.omit({pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("pill"),width:Be,height:Be,radius:Be,portHints:G0.optional(),coveredWithSolderMask:v.boolean().optional()});cr(!0);var Ykt=Ta.omit({pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("polygon"),points:v.array(ig),portHints:G0.optional(),coveredWithSolderMask:v.boolean().optional()});cr(!0);var FAe=v.discriminatedUnion("shape",[Gkt,Ukt,Vkt,Xkt,Ykt]);cr(!0);var Hkt=Ta.omit({pcbRotation:!0}).extend({shape:v.literal("rect"),width:Be,height:Be});cr(!0);var Wkt=Ta.omit({pcbRotation:!0}).extend({shape:v.literal("circle"),radius:Be});cr(!0);var Cor=v.union([Wkt,Hkt]);cr(!0);var Kkt=Ta.extend({name:v.string().optional(),shape:v.literal("circle").optional(),diameter:Be.optional(),radius:Be.optional()}).transform(r=>({...r,diameter:r.diameter??2*r.radius,radius:r.radius??r.diameter/2})),Jkt=Ta.extend({name:v.string().optional(),shape:v.literal("pill"),width:Be,height:Be}),EAe=v.union([Kkt,Jkt]);cr(!0);var CY=v.union([v.string(),v.custom(r=>!!r.getPortSelector)]),eAe=v.object({key:v.string().optional(),thickness:Be.optional(),schematicRouteHints:v.array(ig).optional(),pcbRouteHints:v.array(bo).optional(),pcbPathRelativeTo:v.string().optional(),pcbPath:v.array(ig).optional(),schDisplayLabel:v.string().optional(),schStroke:v.string().optional(),ratsNestColor:v.string().optional(),maxLength:Be.optional()}),vAe=v.union([eAe.extend({path:v.array(CY)}),eAe.extend({from:CY,to:CY})]),CAe=v.object({originalLayer:dn.default("top").optional()});cr(!0);var _Ae=v.object({originalFacingDirection:v.enum(["up","down","left","right"]).default("right").optional()});cr(!0);var Zkt=v.number().or(v.string().endsWith("mAh")).transform(r=>{if(typeof r=="string"){let e=r.replace("mAh",""),a=Number.parseFloat(e);if(Number.isNaN(a))throw new Error("Invalid capacity");return a}return r}).describe("Battery capacity in mAh"),AAe=gs.extend({capacity:Zkt.optional(),voltage:Us.optional(),standard:v.enum(["AA","AAA","9V","CR2032","18650","C"]).optional(),schOrientation:Op.optional()});cr(!0);var Qkt=v.enum(["vertical","horizontal"]).describe("vertical means pins go 1->2 downward and horizontal means pins go 1->2 rightward");cr(!0);var RAe=gs.extend({pinCount:v.number(),pitch:Be.optional(),schFacingDirection:v.enum(["up","down","left","right"]).optional(),gender:v.enum(["male","female","unpopulated"]).optional().default("male"),showSilkscreenPinLabels:v.boolean().optional(),pcbPinLabels:v.record(v.string(),v.string()).optional(),doubleRow:v.boolean().optional(),rightAngle:v.boolean().optional(),pcbOrientation:Qkt.optional(),holeDiameter:Be.optional(),platedDiameter:Be.optional(),pinLabels:v.record(v.string(),ec).or(v.array(ec)).optional(),connections:v.custom().pipe(v.record(v.string(),f5)).optional(),facingDirection:v.enum(["left","right"]).optional(),schPinArrangement:AY.optional(),schPinStyle:x5.optional(),schPinSpacing:Be.optional(),schWidth:Be.optional(),schHeight:Be.optional()});cr(!0);var Oor=v.object({net:v.string().optional(),connection:v.string().optional(),schX:Be.optional(),schY:Be.optional(),schRotation:Gn.optional(),anchorSide:v.enum(["left","top","right","bottom"]).optional()});cr(!0);var SAe=v.object({net:v.string().optional(),connection:v.string().optional(),connectsTo:v.string().or(v.array(v.string())).optional(),schX:Be.optional(),schY:Be.optional(),schRotation:Gn.optional(),anchorSide:v.enum(["left","top","right","bottom"]).optional()});cr(!0);var BAe=og.extend({});cr(!0);cr(!0);var eNt=["pin1","pin2","pin3","emitter","collector","base","gate","source","drain"],wAe=gs.extend({type:v.enum(["npn","pnp","bjt","jfet","mosfet","igbt"]),connections:l1(eNt).optional()});cr(!0);var TAe=gs.extend({channelType:v.enum(["n","p"]),mosfetMode:v.enum(["enhancement","depletion"])});cr(!0);var tNt=_Y,PAe=gs.extend({inductance:OA,maxCurrentRating:v.union([v.string(),v.number()]).optional(),schOrientation:Op.optional(),connections:l1(tNt).optional()});cr(!0);var rNt=v.enum(["anode","cathode","pin1","pin2","pos","neg"]),nNt=v.string().or(v.array(v.string()).readonly()).or(v.array(v.string())),aNt=v.record(rNt,nNt),sNt=v.enum(["standard","schottky","zener","avalanche","photo","tvs"]),IAe=gs.extend({connections:aNt.optional(),variant:sNt.optional().default("standard"),standard:v.boolean().optional(),schottky:v.boolean().optional(),zener:v.boolean().optional(),avalanche:v.boolean().optional(),photo:v.boolean().optional(),tvs:v.boolean().optional(),schOrientation:Op.optional()}).superRefine((r,e)=>{if([r.standard,r.schottky,r.zener,r.avalanche,r.photo,r.tvs].filter(Boolean).length>1)return e.addIssue({code:v.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),v.INVALID}).transform(r=>{let e={...r,standard:!1,schottky:!1,zener:!1,avalanche:!1,photo:!1,tvs:!1};if(r.standard)e.standard=!0;else if(r.schottky)e.schottky=!0;else if(r.zener)e.zener=!0;else if(r.photo)e.photo=!0;else if(r.tvs)e.tvs=!0;else switch(r.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}),jAe=p5;cr(!0);var kAe=gs.extend({color:v.string().optional(),wavelength:v.string().optional(),schDisplayValue:v.string().optional(),schOrientation:Op.optional(),connections:l1(p5).optional(),laser:v.boolean().optional()}),NAe=p5,MAe=gs.extend({type:v.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:v.boolean().optional().default(!1),spst:v.boolean().optional(),spdt:v.boolean().optional(),dpst:v.boolean().optional(),dpdt:v.boolean().optional()}).transform(r=>{let e={...r};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});cr(!0);var OAe=Ta.extend({text:v.string(),anchorAlignment:v.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:v.enum(["tscircuit2024"]).optional(),fontSize:pe.optional(),color:v.string().optional()}),LAe=Ta.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:v.array(bo),strokeWidth:pe.optional(),color:v.string().optional()}),eur=v.object({layer:v.string().optional(),thickness:Be.optional(),route:v.array(bo)}),$Ae=d5.extend({name:v.string().optional(),fromLayer:dn,toLayer:dn,holeDiameter:Be,outerDiameter:Be,connectsTo:v.string().or(v.array(v.string())).optional()});cr(!0);var zAe=gs.extend({footprintVariant:v.enum(["pad","through_hole"]).optional(),padShape:v.enum(["rect","circle"]).optional().default("circle"),padDiameter:Be.optional(),holeDiameter:Be.optional(),width:Be.optional(),height:Be.optional()}).refine(r=>r.footprintVariant!=="through_hole"||r.holeDiameter!==void 0,{message:"holeDiameter is required for through_hole testpoints"});cr(!0);var qAe=Ta.omit({pcbRotation:!0,layer:!0}).extend({connection:v.string()});cr(!0);var UAe=v.union([Ta.omit({pcbRotation:!0}).extend({shape:v.literal("circle"),radius:Be}),Ta.extend({shape:v.literal("rect"),width:Be,height:Be})]),VAe=v.object({name:v.string().optional(),layer:dn,connectsTo:v.string(),padMargin:Be.optional(),traceMargin:Be.optional()});cr(!0);var GAe=v.object({originalLayer:dn.default("top").optional(),children:v.any().optional()});cr(!0);var iNt=v.object({pcbX:Be.optional(),pcbY:Be.optional(),pcbZ:Be.optional()}),oNt=Mp.extend({modelUrl:v.string()}),uNt=oNt.merge(iNt);cr(!0);var XAe=v.union([v.null(),v.string(),uNt]),YAe=gs.extend({voltage:Us}),cNt=["pin1","pin2","pos","neg"],lNt=v.union([v.string(),v.number()]).transform(r=>typeof r=="string"?r.endsWith("%")?parseFloat(r.slice(0,-1))/100:parseFloat(r):r).pipe(v.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),mur=gs.extend({voltage:Us.optional(),frequency:Oc.optional(),peakToPeakVoltage:Us.optional(),waveShape:v.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Gn.optional(),dutyCycle:lNt.optional(),connections:l1(cNt).optional()});cr(!0);var yur=v.object({center:Hr,radius:Be,startAngleDegrees:Gn,endAngleDegrees:Gn,direction:v.enum(["clockwise","counterclockwise"]).default("counterclockwise"),strokeWidth:Be.optional(),color:v.string().optional().default("#000000"),isDashed:v.boolean().optional().default(!1)}),HAe=v.object({schX:Be.optional(),schY:Be.optional(),width:Be.optional(),height:Be.optional(),overlay:v.array(v.string()).optional(),padding:Be.optional(),paddingLeft:Be.optional(),paddingRight:Be.optional(),paddingTop:Be.optional(),paddingBottom:Be.optional(),title:v.string().optional(),titleAlignment:Vb.default("top_left"),titleColor:v.string().optional(),titleFontSize:Be.optional(),titleInside:v.boolean().default(!1),strokeStyle:v.enum(["solid","dashed"]).default("solid")}).refine(r=>r.width!==void 0&&r.height!==void 0||Array.isArray(r.overlay)&&r.overlay.length>0,{message:"Must provide either both `width` and `height`, or a non-empty `overlay` array."}).refine(r=>!(r.width!==void 0&&r.height!==void 0&&Array.isArray(r.overlay)&&r.overlay.length>0),{message:"Cannot provide both `width`/`height` and `overlay` at the same time."}),Cur=v.object({center:Hr,radius:Be,strokeWidth:Be.optional(),color:v.string().optional().default("#000000"),isFilled:v.boolean().optional().default(!1),fillColor:v.string().optional(),isDashed:v.boolean().optional().default(!1)}),WAe=v.object({center:Hr,width:Be,height:Be,rotation:Gn.default(0),strokeWidth:Be.optional(),color:v.string().optional().default("#000000"),isFilled:v.boolean().optional().default(!1),fillColor:v.string().optional(),isDashed:v.boolean().optional().default(!1)}),KAe=v.object({x1:Be,y1:Be,x2:Be,y2:Be,strokeWidth:Be.optional(),color:v.string().optional().default("#000000"),isDashed:v.boolean().optional().default(!1)}),dNt=v.enum(["center","left","right","top","bottom"]),JAe=v.object({schX:Be.optional(),schY:Be.optional(),text:v.string(),fontSize:v.number().default(1),anchor:v.union([dNt.describe("legacy"),Vb]).default("center"),color:v.string().default("#000000"),schRotation:Gn.default(0)}),jur=v.object({points:v.array(Hr),isFilled:v.boolean().optional().default(!1),fillColor:v.enum(["red","blue"]).optional()}),ZAe=v.object({schX:Be.optional(),schY:Be.optional(),children:v.any().optional(),cellPadding:Be.optional(),borderWidth:Be.optional(),anchor:Vb.optional(),fontSize:Be.optional()});cr(!0);var QAe=v.object({children:v.any().optional(),height:Be.optional()});cr(!0);var e4e=v.object({children:v.string().optional(),horizontalAlign:v.enum(["left","center","right"]).optional(),verticalAlign:v.enum(["top","middle","bottom"]).optional(),fontSize:Be.optional(),rowSpan:v.number().optional(),colSpan:v.number().optional(),width:Be.optional(),text:v.string().optional()});cr(!0);var t4e=Ta.extend({text:v.string(),anchorAlignment:Vb.default("center"),font:v.enum(["tscircuit2024"]).optional(),fontSize:pe.optional(),isKnockout:v.boolean().optional(),knockoutPadding:pe.optional(),knockoutPaddingLeft:pe.optional(),knockoutPaddingRight:pe.optional(),knockoutPaddingTop:pe.optional(),knockoutPaddingBottom:pe.optional(),layers:v.array(dn).optional()}),r4e=Ta.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:v.array(bo),strokeWidth:pe.optional()}),n4e=Ta.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({strokeWidth:Be,x1:Be,y1:Be,x2:Be,y2:Be}),a4e=Ta.omit({pcbRotation:!0}).extend({filled:v.boolean().default(!0).optional(),stroke:v.enum(["dashed","solid","none"]).optional(),strokeWidth:Be.optional(),width:Be,height:Be}),s4e=Ta.omit({pcbRotation:!0}).extend({isFilled:v.boolean().optional(),isOutline:v.boolean().optional(),strokeWidth:Be.optional(),radius:Be}),tAe=v.object({x:Be,y:Be,via:v.boolean().optional(),toLayer:dn.optional()}),i4e=v.object({for:v.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:v.number().optional(),offset:bo.or(tAe).optional(),offsets:v.array(bo).or(v.array(tAe)).optional(),traceWidth:v.number().optional()}),Qur=d5.extend({name:v.string(),pinNumber:v.number().optional(),aliases:v.array(v.string()).optional(),direction:okt}),pNt=v.array(v.any()).describe("Circuit JSON"),o4e=v.object({footprintCircuitJson:v.array(v.any()),cadModel:nAe.optional()}),rAe=v.function().args(v.string()).returns(v.promise(o4e)).describe("A function that takes a path and returns Circuit JSON"),xNt=v.object({loadFromUrl:v.function().args(v.string()).returns(v.promise(o4e)).describe("A function that takes a footprint file URL and returns Circuit JSON")}),fNt=v.object({partsEngine:iAe.optional(),autorouter:aAe.optional(),registryApiUrl:v.string().optional(),cloudAutorouterUrl:v.string().optional(),projectName:v.string().optional(),projectBaseUrl:v.string().optional(),version:v.string().optional(),url:v.string().optional(),printBoardInformationToSilkscreen:v.boolean().optional(),localCacheEngine:v.any().optional(),pcbDisabled:v.boolean().optional(),schematicDisabled:v.boolean().optional(),partsEngineDisabled:v.boolean().optional(),footprintLibraryMap:v.record(v.string(),v.union([rAe,v.record(v.string(),v.union([pNt,rAe]))])).optional(),footprintFileParserMap:v.record(v.string(),xNt).optional()});cr(!0);var hNt=fNt,tcr=hNt.pick({projectName:!0,projectBaseUrl:!0,version:!0,url:!0,printBoardInformationToSilkscreen:!0});cr(!0);Ue();qt();Jl();Ue();var ax=Or(kc(),1);Jl();Ue();function Lp(){return new wY}var wY=class r{constructor(){z(this,"index",{});z(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 h5(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 h5(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 r;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}},h5=class r{constructor(e,a){z(this,"first");z(this,"second");this.first=e,this.second=a}copy(){return new r(this.first,this.second)}};var rd=class{constructor(e=""){z(this,"_name");z(this,"_value",0);z(this,"_context",null);z(this,"_id",mNt++);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 Xa(this,e)}minus(e){return new Xa(this,typeof e=="number"?-e:[-1,e])}multiply(e){return new Xa([e,this])}divide(e){return new Xa([1/e,this])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},mNt=0;var Xa=class r{constructor(){z(this,"_terms");z(this,"_constant");let e=gNt(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 r(this,e)}minus(e){return new r(this,typeof e=="number"?-e:[-1,e])}multiply(e){return new r([e,this])}divide(e){return new r([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 gNt(r){let e=0,a=()=>0,s=Lp();for(let l=0,d=r.length;l<d;++l){let x=r[l];if(typeof x=="number")e+=x;else if(x instanceof rd)s.setDefault(x,a).second+=1;else if(x instanceof Xa){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 rd)s.setDefault(m,a).second+=f;else if(m instanceof Xa){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 $c=class $c{static create(e,a,s,l=1){let d=0;return d+=Math.max(0,Math.min(1e3,e*l))*1e6,d+=Math.max(0,Math.min(1e3,a*l))*1e3,d+=Math.max(0,Math.min(1e3,s*l)),d}static clip(e){return Math.max(0,Math.min($c.required,e))}};z($c,"required",$c.create(1e3,1e3,1e3)),z($c,"strong",$c.create(1,0,0)),z($c,"medium",$c.create(0,1,0)),z($c,"weak",$c.create(0,0,1));var Oa=$c;var Ds;(function(r){r[r.Le=0]="Le",r[r.Ge=1]="Ge",r[r.Eq=2]="Eq"})(Ds||(Ds={}));var Vs=class{constructor(e,a,s,l=Oa.required){z(this,"_expression");z(this,"_operator");z(this,"_strength");z(this,"_id",DNt++);this._operator=a,this._strength=Oa.clip(l),s===void 0&&e instanceof Xa?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()+")"}},DNt=0;var ug=class{constructor(){z(this,"maxIterations",1e3);z(this,"_cnMap",yNt());z(this,"_rowMap",bNt());z(this,"_varMap",FNt());z(this,"_editMap",ENt());z(this,"_infeasibleRows",[]);z(this,"_objective",new D5);z(this,"_artificial",null);z(this,"_idTick",0)}createConstraint(e,a,s,l=Oa.required){let d=new Vs(e,a,s,l);return this.addConstraint(d),d}addConstraint(e){if(this._cnMap.find(e)!==void 0)throw new Error("duplicate constraint");let s=this._createRow(e),l=s.row,d=s.tag,x=this._chooseSubject(l,d);if(x.type()===ta.Invalid&&l.allDummies())if(m5(l.constant()))x=d.marker;else throw new Error("unsatisfiable constraint");if(x.type()===ta.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,d),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 d=this._getMarkerLeavingSymbol(s);if(d.type()===ta.Invalid)throw new Error("failed to find leaving row");l=this._rowMap.erase(d),l.second.solveForEx(d,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=Oa.clip(a),a===Oa.required)throw new Error("bad required strength");let l=new Xa(e),d=new Vs(l,Ds.Eq,void 0,a);this.addConstraint(d);let f={tag:this._cnMap.find(d).second,constraint:d,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,d=s.second,x=a-d.constant;d.constant=a;let f=d.tag.marker,m=l.find(f);if(m!==void 0){m.second.add(-x)<0&&this._infeasibleRows.push(f),this._dualOptimize();return}let D=d.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()!==ta.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 d=e.itemAt(s),x=a.find(d.second);x!==void 0?d.first.setValue(x.second.constant()):d.first.setValue(0)}}_getVarSymbol(e){let a=()=>this._makeSymbol(ta.External);return this._varMap.setDefault(e,a).second}_createRow(e){let a=e.expression(),s=new D5(a.constant()),l=a.terms();for(let m=0,D=l.size();m<D;++m){let b=l.itemAt(m);if(!m5(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 d=this._objective,x=e.strength(),f={marker:$p,other:$p};switch(e.op()){case Ds.Le:case Ds.Ge:{let m=e.op()===Ds.Le?1:-1,D=this._makeSymbol(ta.Slack);if(f.marker=D,s.insertSymbol(D,m),x<Oa.required){let b=this._makeSymbol(ta.Error);f.other=b,s.insertSymbol(b,-m),d.insertSymbol(b,x)}break}case Ds.Eq:{if(x<Oa.required){let m=this._makeSymbol(ta.Error),D=this._makeSymbol(ta.Error);f.marker=m,f.other=D,s.insertSymbol(m,-1),s.insertSymbol(D,1),d.insertSymbol(m,x),d.insertSymbol(D,x)}else{let m=this._makeSymbol(ta.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 d=0,x=s.size();d<x;++d){let f=s.itemAt(d);if(f.first.type()===ta.External)return f.first}let l=a.marker.type();return(l===ta.Slack||l===ta.Error)&&e.coefficientFor(a.marker)<0?a.marker:(l=a.other.type(),(l===ta.Slack||l===ta.Error)&&e.coefficientFor(a.other)<0?a.other:$p)}_addWithArtificialVariable(e){let a=this._makeSymbol(ta.Slack);this._rowMap.insert(a,e.copy()),this._artificial=e.copy(),this._optimize(this._artificial);let s=m5(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()===ta.Invalid)return!1;x.solveForEx(a,f),this._substitute(f,x),this._rowMap.insert(f,x)}let d=this._rowMap;for(let x=0,f=d.size();x<f;++x)d.itemAt(x).second.removeSymbol(a);return this._objective.removeSymbol(a),s}_substitute(e,a){let s=this._rowMap;for(let l=0,d=s.size();l<d;++l){let x=s.itemAt(l);x.second.substitute(e,a),x.second.constant()<0&&x.first.type()!==ta.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()===ta.Invalid)return;let l=this._getLeavingSymbol(s);if(l.type()===ta.Invalid)throw new Error("the objective is unbounded");let d=this._rowMap.erase(l).second;d.solveForEx(l,s),this._substitute(s,d),this._rowMap.insert(s,d),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 d=this._getDualEnteringSymbol(l.second);if(d.type()===ta.Invalid)throw new Error("dual optimize failed");let x=l.second;e.erase(s),x.solveForEx(s,d),this._substitute(d,x),e.insert(d,x)}}}_getEnteringSymbol(e){let a=e.cells();for(let s=0,l=a.size();s<l;++s){let d=a.itemAt(s),x=d.first;if(d.second<0&&x.type()!==ta.Dummy)return x}return $p}_getDualEnteringSymbol(e){let a=Number.MAX_VALUE,s=$p,l=e.cells();for(let d=0,x=l.size();d<x;++d){let f=l.itemAt(d),m=f.first,D=f.second;if(D>0&&m.type()!==ta.Dummy){let E=this._objective.coefficientFor(m)/D;E<a&&(a=E,s=m)}}return s}_getLeavingSymbol(e){let a=Number.MAX_VALUE,s=$p,l=this._rowMap;for(let d=0,x=l.size();d<x;++d){let f=l.itemAt(d),m=f.first;if(m.type()!==ta.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,d=$p,x=d,f=d,m=d,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()===ta.External)m=P;else if(w<0){let j=-B.constant()/w;j<s&&(s=j,x=P)}else{let j=B.constant()/w;j<l&&(l=j,f=P)}}return x!==d?x:f!==d?f:m}_removeConstraintEffects(e,a){a.marker.type()===ta.Error&&this._removeMarkerEffects(a.marker,e.strength()),a.other.type()===ta.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 d=a.itemAt(s),x=d.first.type();if(x===ta.Slack||x===ta.Error)return d.first}return $p}_makeSymbol(e){return new g5(e,this._idTick++)}};function m5(r){let e=1e-8;return r<0?-r<e:r<e}function yNt(){return Lp()}function bNt(){return Lp()}function FNt(){return Lp()}function ENt(){return Lp()}var ta;(function(r){r[r.Invalid=0]="Invalid",r[r.External=1]="External",r[r.Slack=2]="Slack",r[r.Error=3]="Error",r[r.Dummy=4]="Dummy"})(ta||(ta={}));var g5=class{constructor(e,a){z(this,"_id");z(this,"_type");this._id=a,this._type=e}id(){return this._id}type(){return this._type}},$p=new g5(ta.Invalid,-1),D5=class r{constructor(e=0){z(this,"_cellMap",Lp());z(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()!==ta.Dummy)return!1;return!0}copy(){let e=new r(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);m5(s.second+=a)&&this._cellMap.erase(e)}insertRow(e,a=1){this._constant+=e._constant*a;let s=e._cellMap;for(let l=0,d=s.size();l<d;++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 d=0,x=a.size();d<x;++d)a.itemAt(d).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 t9e=Or(fs(),1);Ue();qt();Fo();var TY={};Am(TY,{boundsAreaOverlap:()=>D4e,boundsDistance:()=>y4e,clamp:()=>ms,computeDistanceBetweenBoxes:()=>sg,distSq:()=>f4e,distance:()=>wi,doBoundsOverlap:()=>Yb,doSegmentsIntersect:()=>tu,doesLineIntersectLine:()=>zp,doesSegmentIntersectRect:()=>l4e,findNearestPointsBetweenBoxSets:()=>zb,getBoundingBox:()=>td,getSegmentIntersection:()=>c4e,getUnitVectorFromDirection:()=>E5,getUnitVectorFromPointAToB:()=>F5,grid:()=>b4e,midpoint:()=>x4e,onSegment:()=>lg,orientation:()=>cg,pointToBoundsDistance:()=>p4e,pointToBoxDistance:()=>d4e,pointToSegmentClosestPoint:()=>g4e,pointToSegmentDistance:()=>Gs,range:()=>h4e,segmentToBoundsMinDistance:()=>Xb,segmentToBoxMinDistance:()=>m4e,segmentToCircleMinDistance:()=>b5,segmentToSegmentMinDistance:()=>y5});function zp([r,e],[a,s],{lineThickness:l=0}={}){return l===0?tu(r,e,a,s):vNt(r,e,a,s)<=l}function tu(r,e,a,s){let l=cg(r,e,a),d=cg(r,e,s),x=cg(a,s,r),f=cg(a,s,e);return!!(l!==d&&x!==f||l===0&&lg(r,a,e)||d===0&&lg(r,s,e)||x===0&&lg(a,r,s)||f===0&&lg(a,e,s))}function cg(r,e,a){let s=(e.y-r.y)*(a.x-e.x)-(e.x-r.x)*(a.y-e.y);return s===0?0:s>0?1:2}function lg(r,e,a){return e.x<=Math.max(r.x,a.x)&&e.x>=Math.min(r.x,a.x)&&e.y<=Math.max(r.y,a.y)&&e.y>=Math.min(r.y,a.y)}function vNt(r,e,a,s){if(r.x===e.x&&r.y===e.y)return Gs(r,a,s);if(a.x===s.x&&a.y===s.y)return Gs(a,r,e);if(tu(r,e,a,s))return 0;let l=[Gs(r,a,s),Gs(e,a,s),Gs(a,r,e),Gs(s,r,e)];return Math.min(...l)}function Gs(r,e,a){let s=(a.x-e.x)**2+(a.y-e.y)**2;if(s===0)return wi(r,e);let l=((r.x-e.x)*(a.x-e.x)+(r.y-e.y)*(a.y-e.y))/s;l=Math.max(0,Math.min(1,l));let d={x:e.x+l*(a.x-e.x),y:e.y+l*(a.y-e.y)};return wi(r,d)}function wi(r,e){let a=r.x-e.x,s=r.y-e.y;return Math.sqrt(a*a+s*s)}function c4e(r,e,a,s){let l=e.x-r.x,d=e.y-r.y,x=s.x-a.x,f=s.y-a.y,m=r.x-a.x,D=r.y-a.y,b=l*f-d*x;if(Math.abs(b)<1e-10)return null;let E=(D*x-m*f)/b,A=(l*D-d*m)/b,B=1e-9;if(E>=-B&&E<=1+B&&A>=-B&&A<=1+B){let w=r.x+E*l,P=r.y+E*d;return{x:w,y:P}}return null}function l4e(r,e,a){let s=m=>m.x>=a.minX&&m.x<=a.maxX&&m.y>=a.minY&&m.y<=a.maxY;if(s(r)||s(e))return!0;let l={x:a.minX,y:a.minY},d={x:a.maxX,y:a.minY},x={x:a.minX,y:a.maxY},f={x:a.maxX,y:a.maxY};return tu(r,e,l,d)||tu(r,e,d,f)||tu(r,e,f,x)||tu(r,e,x,l)}function d4e(r,e){let a=e.width/2,s=e.height/2,l=e.center.x-a,d=e.center.x+a,x=e.center.y-s,f=e.center.y+s;if(r.x>=l&&r.x<=d&&r.y>=x&&r.y<=f)return 0;let m=ms(r.x,l,d),D=ms(r.y,x,f);return wi(r,{x:m,y:D})}function p4e(r,e){if(r.x>=e.minX&&r.x<=e.maxX&&r.y>=e.minY&&r.y<=e.maxY)return 0;let a=ms(r.x,e.minX,e.maxX),s=ms(r.y,e.minY,e.maxY);return wi(r,{x:a,y:s})}function x4e(r,e){return{x:(r.x+e.x)/2,y:(r.y+e.y)/2}}function f4e(r,e){let a=r.x-e.x,s=r.y-e.y;return a*a+s*s}function h4e(r,e,a=1){if(a===0)throw new Error("step cannot be 0");let s,l;e===void 0?(s=0,l=r):(s=r,l=e);let d=[];if(a>0)for(let x=s;x<l;x+=a)d.push(x);else for(let x=s;x>l;x+=a)d.push(x);return d}function y5(r,e,a,s){if(r.x===e.x&&r.y===e.y)return Gs(r,a,s);if(a.x===s.x&&a.y===s.y)return Gs(a,r,e);if(tu(r,e,a,s))return 0;let l=[Gs(r,a,s),Gs(e,a,s),Gs(a,r,e),Gs(s,r,e)];return Math.min(...l)}function Xb(r,e,a){let s={x:a.minX,y:a.minY},l={x:a.maxX,y:a.minY},d={x:a.minX,y:a.maxY},x={x:a.maxX,y:a.maxY};if(tu(r,e,s,l)||tu(r,e,l,x)||tu(r,e,x,d)||tu(r,e,d,s)||r.x>=a.minX&&r.x<=a.maxX&&r.y>=a.minY&&r.y<=a.maxY&&e.x>=a.minX&&e.x<=a.maxX&&e.y>=a.minY&&e.y<=a.maxY)return 0;let f=[Gs(s,r,e),Gs(l,r,e),Gs(d,r,e),Gs(x,r,e)];if(r.x>=a.minX&&r.x<=a.maxX&&r.y>=a.minY&&r.y<=a.maxY||e.x>=a.minX&&e.x<=a.maxX&&e.y>=a.minY&&e.y<=a.maxY)return 0;if(r.x<a.minX||r.x>a.maxX||r.y<a.minY||r.y>a.maxY){let m=ms(r.x,a.minX,a.maxX),D=ms(r.y,a.minY,a.maxY);f.push(wi(r,{x:m,y:D}))}if(e.x<a.minX||e.x>a.maxX||e.y<a.minY||e.y>a.maxY){let m=ms(e.x,a.minX,a.maxX),D=ms(e.y,a.minY,a.maxY);f.push(wi(e,{x:m,y:D}))}return Math.min(...f)}function m4e(r,e,a){let s=a.width/2,l=a.height/2,d={minX:a.center.x-s,maxX:a.center.x+s,minY:a.center.y-l,maxY:a.center.y+l};return Xb(r,e,d)}function b5(r,e,a){let s={x:a.x,y:a.y};if(r.x===e.x&&r.y===e.y)return Math.max(0,wi(r,s)-a.radius);let l={x:e.x-r.x,y:e.y-r.y},d={x:s.x-r.x,y:s.y-r.y},x=l.x*l.x+l.y*l.y,f=Math.max(0,Math.min(1,(l.x*d.x+l.y*d.y)/x)),m={x:r.x+f*l.x,y:r.y+f*l.y},D=wi(m,s);return Math.max(0,D-a.radius)}function g4e(r,e,a){let s=a.x-e.x,l=a.y-e.y,d=s*s+l*l;if(d===0)return{x:e.x,y:e.y};let x=((r.x-e.x)*s+(r.y-e.y)*l)/d;return x=Math.max(0,Math.min(1,x)),{x:e.x+x*s,y:e.y+x*l}}var D4e=(r,e)=>{let a=Math.max(0,Math.min(r.maxX,e.maxX)-Math.max(r.minX,e.minX)),s=Math.max(0,Math.min(r.maxY,e.maxY)-Math.max(r.minY,e.minY));return a*s};var y4e=(r,e)=>{let a=r.maxX<e.minX?e.minX-r.maxX:e.maxX<r.minX?r.minX-e.maxX:0,s=r.maxY<e.minY?e.minY-r.maxY:e.maxY<r.minY?r.minY-e.maxY:0;return Math.sqrt(a*a+s*s)};var Yb=(r,e)=>!(r.maxX<e.minX||e.maxX<r.minX||r.maxY<e.minY||e.maxY<r.minY);var F5=(r,e)=>{let a={x:e.x-r.x,y:e.y-r.y},s=Math.sqrt(a.x**2+a.y**2);return{x:a.x/s,y:a.y/s}},E5=r=>{switch(r){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 b4e({rows:r,cols:e,xSpacing:a,ySpacing:s,width:l,height:d,offsetX:x=0,offsetY:f=0,yDirection:m="cartesian",centered:D=!0}){let b=a??1,E=s??1,A=l??e*b,B=d??r*E,w=D?-A/2:0,P=D?-B/2:0,j=l?l/e:b,O=d?d/r:E,q=[];for(let ee=0;ee<r;ee++)for(let W=0;W<e;W++){let re=ee*e+W,L=x+w+W*j+j/2,K=f+ee*O+O/2,U=m==="cartesian"?f+P+(r-1-ee)*O+O/2:f+P+ee*O+O/2;q.push({index:re,center:{x:L,y:U},topLeft:{x:L-j/2,y:U+O/2},bottomRight:{x:L+j/2,y:U-O/2},row:ee,col:W})}return q}qt();var CNt=(r,e,a)=>{let s=[{x:r.x,y:r.y}],l=(r.x+e.x)/2,d=(r.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=r.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(r.y-e.y)<=Math.max(1e-6,a*.1),E=Math.abs(r.x-e.x)<=Math.max(1e-6,a*.1);if(f==="none"&&m==="none")D({x:l,y:r.y}),D({x:l,y:e.y});else if(f==="x+"&&m==="y+")r.x>e.x&&r.y<e.y?(D({x:r.x+a,y:r.y}),D({x:r.x+a,y:e.y+a}),D({x:e.x,y:e.y+a})):!E&&!b&&r.x<e.x&&r.y>e.y?D({x:e.x,y:r.y}):E?(D({x:r.x+a,y:r.y}),D({x:r.x+a,y:e.y+a}),D({x:e.x,y:e.y+a})):r.x<e.x?(D({x:l,y:r.y}),D({x:l,y:x.y}),D({x:e.x,y:x.y})):r.y<=e.y+a?(D({x:r.x+a,y:r.y}),D({x:r.x+a,y:r.y+a}),D({x:e.x,y:r.y+a}),D({x:e.x,y:e.y})):(D({x:r.x+a,y:r.y}),D({x:r.x+a,y:(r.y+e.y)/2}),D({x:e.x,y:(r.y+e.y)/2}));else if(f==="x+"&&m==="x+"&&!b){let A=Math.max(r.x+a,x.x);D({x:A,y:r.y}),D({x:A,y:e.y})}else if(f==="x+"&&m==="x+"&&b)D({x:r.x+a,y:r.y}),D({x:r.x+a,y:r.y+a}),D({x:e.x+a,y:r.y+a}),D({x:e.x+a,y:e.y});else if(f==="x+"&&m==="y-")if(E&&r.y<=e.y)D({x:r.x+a,y:r.y}),D({x:r.x+a,y:d}),D({x:e.x,y:d});else if(E&&r.y>e.y)D({x:r.x+a,y:r.y}),D({x:r.x+a,y:e.y-a}),D({x:e.x,y:e.y-a});else if(r.x<e.x&&r.y<e.y)D({x:e.x,y:r.y});else if(r.x>e.x&&r.y<e.y){let A=r.x+a;D({x:A,y:r.y}),D({x:A,y:d}),D({x:e.x,y:d})}else if(r.x>e.x&&r.y>e.y){let A=r.x+a;D({x:A,y:r.y}),D({x:A,y:x.y}),D({x:e.x,y:x.y})}else r.y===e.y?(D({x:r.x+a,y:r.y}),D({x:r.x+a,y:r.y-a}),D({x:e.x,y:r.y-a})):(D({x:l,y:r.y}),D({x:l,y:x.y}),D({x:e.x,y:x.y}));else if(f==="x+"&&m==="x-"&&r.x+a>=e.x-a&&!b){let A=r.x+a;D({x:A,y:r.y}),D({x:A,y:d}),D({x:x.x,y:d}),D({x:x.x,y:x.y})}else f==="x+"&&m==="x-"&&b&&e.x>r.x||(f==="x+"&&m==="x-"&&b?(D({x:r.x+a,y:r.y}),D({x:r.x+a,y:r.y+a}),D({x:e.x-a,y:r.y+a}),D({x:e.x-a,y:r.y})):(f==="x+"&&D({x:r.x+a,y:r.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},dg=(r,e,a={})=>{let s=r,l=e,d=!1;(s.x>l.x||s.x===l.x&&s.y>l.y)&&(d=!0,[s,l]=[l,s]);let x=s.facingDirection==="x-",f=s.facingDirection==="y-",m=q=>{let ee=x?s.x-(q.x-s.x):q.x,W=f?s.y-(q.y-s.y):q.y,re=q.facingDirection;return x&&(re==="x+"?re="x-":re==="x-"&&(re="x+")),f&&(re==="y+"?re="y-":re==="y-"&&(re="y+")),{x:ee,y:W,facingDirection:re}},D=(q,ee)=>{let W=q.x-ee.x,re=q.y-ee.y,L=ee.x+re,K=ee.y-W,U=q.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=(q,ee)=>{let W=q.x-ee.x,re=q.y-ee.y;return{x:ee.x-re,y:ee.y+W}},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 j=a?.overshoot??.1*Math.max(Math.abs(B.x-w.x),Math.abs(B.y-w.y)),O=CNt(B,w,j);return P&&(O=O.map(q=>b(q,B))),(x||f)&&(O=O.map(({x:q,y:ee})=>({x:x?s.x-(q-s.x):q,y:f?s.y-(ee-s.y):ee}))),d?O.reverse():O};var F4e={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"}};qt();Fo();ra();var tK=Or(kc(),1);qt();var A6e=Or(kY(),1),B6e=Or(kY(),1);var L5=(...r)=>{let e={points:[],lines:[],circles:[],rects:[]};return r.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(){z(this,"MAX_ITERATIONS",1e3);z(this,"solved",!1);z(this,"failed",!1);z(this,"iterations",0);z(this,"progress",0);z(this,"error",null);z(this,"activeSubSolver");z(this,"failedSubSolvers");z(this,"timeToSolve");z(this,"stats",{});z(this,"cacheHit");z(this,"cacheKey");z(this,"cacheToSolveSpaceTransform")}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(r){throw this.error=`${this.constructor.name} error: ${r}`,console.error(this.error),this.failed=!0,r}!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 r=Date.now();for(;!this.solved&&!this.failed;)this.step();let e=Date.now();this.timeToSolve=e-r}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function nu(){return nu=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var a=arguments[e];for(var s in a)({}).hasOwnProperty.call(a,s)&&(r[s]=a[s])}return r},nu.apply(null,arguments)}function U5(r,e){return(U5=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(a,s){return a.__proto__=s,a})(r,e)}function d6e(r){return(d6e=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(r)}function p6e(){try{var r=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(p6e=function(){return!!r})()}function YY(r){var e=typeof Map=="function"?new Map:void 0;return YY=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,d,x){if(p6e())return Reflect.construct.apply(null,arguments);var f=[null];f.push.apply(f,d);var m=new(l.bind.apply(l,f));return x&&U5(m,x.prototype),m})(a,arguments,d6e(this).constructor)}return s.prototype=Object.create(a.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),U5(s,a)},YY(r)}var ru=(function(r){var e,a;function s(l){var d;if(1)d=r.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})(d)}return a=r,(e=s).prototype=Object.create(a.prototype),e.prototype.constructor=e,U5(e,a),s})(YY(Error));function N4e(r,e){return r.substr(-e.length)===e}var NNt=/^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;function M4e(r){return typeof r!="string"?r:r.match(NNt)?parseFloat(r):r}var O4e=function(r){return function(e,a){a===void 0&&(a="16px");var s=e,l=a;if(typeof e=="string"){if(!N4e(e,"px"))throw new ru(69,r,e);s=M4e(e)}if(typeof a=="string"){if(!N4e(a,"px"))throw new ru(70,r,a);l=M4e(a)}if(typeof s=="string")throw new ru(71,e,r);if(typeof l=="string")throw new ru(72,a,r);return""+s/l+r}};O4e("em"),O4e("rem");function NY(r){return Math.round(255*r)}function MNt(r,e,a){return NY(r)+","+NY(e)+","+NY(a)}function rF(r,e,a,s){if(s===void 0&&(s=MNt),e===0)return s(a,a,a);var l=(r%360+360)%360/60,d=(1-Math.abs(2*a-1))*e,x=d*(1-Math.abs(l%2-1)),f=0,m=0,D=0;l>=0&&l<1?(f=d,m=x):l>=1&&l<2?(f=x,m=d):l>=2&&l<3?(m=d,D=x):l>=3&&l<4?(m=x,D=d):l>=4&&l<5?(f=x,D=d):l>=5&&l<6&&(f=d,D=x);var b=a-d/2;return s(f+b,m+b,D+b)}var L4e={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"},ONt=/^#[a-fA-F0-9]{6}$/,LNt=/^#[a-fA-F0-9]{8}$/,$Nt=/^#[a-fA-F0-9]{3}$/,zNt=/^#[a-fA-F0-9]{4}$/,MY=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,qNt=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,UNt=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,VNt=/^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(r){if(typeof r!="string")throw new ru(3);var e=(function(A){if(typeof A!="string")return A;var B=A.toLowerCase();return L4e[B]?"#"+L4e[B]:A})(r);if(e.match(ONt))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(LNt)){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($Nt))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(zNt)){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=MY.exec(e);if(l)return{red:parseInt(""+l[1],10),green:parseInt(""+l[2],10),blue:parseInt(""+l[3],10)};var d=qNt.exec(e.substring(0,50));if(d)return{red:parseInt(""+d[1],10),green:parseInt(""+d[2],10),blue:parseInt(""+d[3],10),alpha:parseFloat(""+d[4])>1?parseFloat(""+d[4])/100:parseFloat(""+d[4])};var x=UNt.exec(e);if(x){var f="rgb("+rF(parseInt(""+x[1],10),parseInt(""+x[2],10)/100,parseInt(""+x[3],10)/100)+")",m=MY.exec(f);if(!m)throw new ru(4,e,f);return{red:parseInt(""+m[1],10),green:parseInt(""+m[2],10),blue:parseInt(""+m[3],10)}}var D=VNt.exec(e.substring(0,50));if(D){var b="rgb("+rF(parseInt(""+D[1],10),parseInt(""+D[2],10)/100,parseInt(""+D[3],10)/100)+")",E=MY.exec(b);if(!E)throw new ru(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 ru(5)}function Up(r){return(function(e){var a,s=e.red/255,l=e.green/255,d=e.blue/255,x=Math.max(s,l,d),f=Math.min(s,l,d),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-d)/D+(l<d?6:0);break;case l:a=(d-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(r))}var HY=function(r){return r.length===7&&r[1]===r[2]&&r[3]===r[4]&&r[5]===r[6]?"#"+r[1]+r[3]+r[5]:r};function x1(r){var e=r.toString(16);return e.length===1?"0"+e:e}function OY(r){return x1(Math.round(255*r))}function GNt(r,e,a){return HY("#"+OY(r)+OY(e)+OY(a))}function R5(r,e,a){return rF(r,e,a,GNt)}function WY(r,e,a){if(typeof r=="number"&&typeof e=="number"&&typeof a=="number")return HY("#"+x1(r)+x1(e)+x1(a));if(typeof r=="object"&&e===void 0&&a===void 0)return HY("#"+x1(r.red)+x1(r.green)+x1(r.blue));throw new ru(6)}function H5(r,e,a,s){if(typeof r=="string"&&typeof e=="number"){var l=Dg(r);return"rgba("+l.red+","+l.green+","+l.blue+","+e+")"}if(typeof r=="number"&&typeof e=="number"&&typeof a=="number"&&typeof s=="number")return s>=1?WY(r,e,a):"rgba("+r+","+e+","+a+","+s+")";if(typeof r=="object"&&e===void 0&&a===void 0&&s===void 0)return r.alpha>=1?WY(r.red,r.green,r.blue):"rgba("+r.red+","+r.green+","+r.blue+","+r.alpha+")";throw new ru(7)}function Vp(r){if(typeof r!="object")throw new ru(8);if((function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&typeof e.alpha=="number"})(r))return H5(r);if((function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&(typeof e.alpha!="number"||e.alpha===void 0)})(r))return WY(r);if((function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&typeof e.alpha=="number"})(r))return(function(e,a,s,l){if(typeof e=="number"&&typeof a=="number"&&typeof s=="number"&&typeof l=="number")return l>=1?R5(e,a,s):"rgba("+rF(e,a,s)+","+l+")";if(typeof e=="object"&&a===void 0&&s===void 0&&l===void 0)return e.alpha>=1?R5(e.hue,e.saturation,e.lightness):"rgba("+rF(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new ru(2)})(r);if((function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&(typeof e.alpha!="number"||e.alpha===void 0)})(r))return(function(e,a,s){if(typeof e=="number"&&typeof a=="number"&&typeof s=="number")return R5(e,a,s);if(typeof e=="object"&&a===void 0&&s===void 0)return R5(e.hue,e.saturation,e.lightness);throw new ru(1)})(r);throw new ru(8)}function x6e(r,e,a){return function(){var s=a.concat(Array.prototype.slice.call(arguments));return s.length>=e?r.apply(this,s):x6e(r,e,s)}}function mu(r){return x6e(r,r.length,[])}mu(function(r,e){if(e==="transparent")return e;var a=Up(e);return Vp(nu({},a,{hue:a.hue+parseFloat(r)}))});function bg(r,e,a){return Math.max(r,Math.min(e,a))}mu(function(r,e){if(e==="transparent")return e;var a=Up(e);return Vp(nu({},a,{lightness:bg(0,1,a.lightness-parseFloat(r))}))});mu(function(r,e){if(e==="transparent")return e;var a=Up(e);return Vp(nu({},a,{saturation:bg(0,1,a.saturation-parseFloat(r))}))});mu(function(r,e){if(e==="transparent")return e;var a=Up(e);return Vp(nu({},a,{lightness:bg(0,1,a.lightness+parseFloat(r))}))});var f6e=mu(function(r,e,a){if(e==="transparent")return a;if(a==="transparent")return e;if(r===0)return a;var s=Dg(e),l=nu({},s,{alpha:typeof s.alpha=="number"?s.alpha:1}),d=Dg(a),x=nu({},d,{alpha:typeof d.alpha=="number"?d.alpha:1}),f=l.alpha-x.alpha,m=2*parseFloat(r)-1,D=((m*f===-1?m:m+f)/(1+m*f)+1)/2,b=1-D;return H5({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(r)+x.alpha*(1-parseFloat(r))})});mu(function(r,e){if(e==="transparent")return e;var a=Dg(e);return H5(nu({},a,{alpha:bg(0,1,(100*(typeof a.alpha=="number"?a.alpha:1)+100*parseFloat(r))/100)}))});mu(function(r,e){if(e==="transparent")return e;var a=Up(e);return Vp(nu({},a,{saturation:bg(0,1,a.saturation+parseFloat(r))}))});mu(function(r,e){return e==="transparent"?e:Vp(nu({},Up(e),{hue:parseFloat(r)}))});mu(function(r,e){return e==="transparent"?e:Vp(nu({},Up(e),{lightness:parseFloat(r)}))});mu(function(r,e){return e==="transparent"?e:Vp(nu({},Up(e),{saturation:parseFloat(r)}))});mu(function(r,e){return e==="transparent"?e:f6e(parseFloat(r),"rgb(0, 0, 0)",e)});mu(function(r,e){return e==="transparent"?e:f6e(parseFloat(r),"rgb(255, 255, 255)",e)});var XNt=mu(function(r,e){if(e==="transparent")return e;var a=Dg(e);return H5(nu({},a,{alpha:bg(0,1,+(100*(typeof a.alpha=="number"?a.alpha:1)-100*parseFloat(r)).toFixed(2)/100)}))}),$4e=["blue","orange","purple","cyan","magenta","yellowgreen","darkgoldenrod","deeppink"],KY=(r,e)=>{let a={};for(let s=0;s<r.connections.length;s++){let l=r.connections[s],d=e?.getNetConnectedToId(l.name);d&&!a[d]&&(a[d]=`hsl(${300*s/r.connections.length}, 100%, 50%)`),a[l.name]=(d?a[d]:null)??`hsl(${340*s/r.connections.length}, 100%, 50%)`}return a},ys=(r,e)=>{try{return XNt(e,r)}catch(a){return console.error(a),r}},nF=(r,e)=>r==="top"?0:r==="bottom"?e-1:parseInt(r.slice(5)),X0=(r,e=1)=>{let a=(("width"in r?r.width:r)/.5/2)**1.1*e;return r.availableZ?.length===1&&a>1?1:a},YNt=(r,e=.5,a=16)=>{let s=0,l=r;for(;s<a&&!(X0({width:l})<=e);)l/=2,s++;return Math.max(1,s)};function h6e(r,e,a=0,s=r.length-1,l=HNt){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);h6e(r,e,Math.max(a,Math.floor(e-D*E/m+A)),Math.min(s,Math.floor(e+(m-D)*E/m+A)),l)}let d=r[e],x=a,f=s;for(Wb(r,a,e),l(r[s],d)>0&&Wb(r,a,s);x<f;){for(Wb(r,x,f),x++,f--;l(r[x],d)<0;)x++;for(;l(r[f],d)>0;)f--}l(r[a],d)===0?Wb(r,a,f):(f++,Wb(r,f,s)),f<=e&&(a=f+1),e<=f&&(s=f-1)}}function Wb(r,e,a){let s=r[e];r[e]=r[a],r[a]=s}function HNt(r,e){return r<e?-1:r>e?1:0}var WNt=class{constructor(r=9){this._maxEntries=Math.max(4,r),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(r){let e=this.data,a=[];if(!B5(r,e))return a;let s=this.toBBox,l=[];for(;e;){for(let d=0;d<e.children.length;d++){let x=e.children[d],f=e.leaf?s(x):x;B5(r,f)&&(e.leaf?a.push(x):$Y(r,f)?this._all(x,a):l.push(x))}e=l.pop()}return a}collides(r){let e=this.data;if(!B5(r,e))return!1;let a=[];for(;e;){for(let s=0;s<e.children.length;s++){let l=e.children[s],d=e.leaf?this.toBBox(l):l;if(B5(r,d)){if(e.leaf||$Y(r,d))return!0;a.push(l)}}e=a.pop()}return!1}load(r){if(!r||!r.length)return this;if(r.length<this._minEntries){for(let a=0;a<r.length;a++)this.insert(r[a]);return this}let e=this._build(r.slice(),0,r.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(r){return r&&this._insert(r,this.data.height-1),this}clear(){return this.data=hg([]),this}remove(r,e){if(!r)return this;let a=this.data,s=this.toBBox(r),l=[],d=[],x,f,m;for(;a||l.length;){if(a||(a=l.pop(),f=l[l.length-1],x=d.pop(),m=!0),a.leaf){let D=KNt(r,a.children,e);if(D!==-1)return a.children.splice(D,1),l.push(a),this._condense(l),this}m||a.leaf||!$Y(a,s)?f?(x++,a=f.children[x],m=!1):a=null:(l.push(a),d.push(x),x=0,f=a,a=a.children[0])}return this}toBBox(r){return r}compareMinX(r,e){return r.minX-e.minX}compareMinY(r,e){return r.minY-e.minY}toJSON(){return this.data}fromJSON(r){return this.data=r,this}_all(r,e){let a=[];for(;r;)r.leaf?e.push(...r.children):a.push(...r.children),r=a.pop();return e}_build(r,e,a,s){let l=a-e+1,d,x=this._maxEntries;if(l<=x)return d=hg(r.slice(e,a+1)),fg(d,this.toBBox),d;s||(s=Math.ceil(Math.log(l)/Math.log(x)),x=Math.ceil(l/Math.pow(x,s-1))),d=hg([]),d.leaf=!1,d.height=s;let f=Math.ceil(l/x),m=f*Math.ceil(Math.sqrt(x));z4e(r,e,a,m,this.compareMinX);for(let D=e;D<=a;D+=m){let b=Math.min(D+m-1,a);z4e(r,D,b,f,this.compareMinY);for(let E=D;E<=b;E+=f){let A=Math.min(E+f-1,b);d.children.push(this._build(r,E,A,s-1))}}return fg(d,this.toBBox),d}_chooseSubtree(r,e,a,s){for(;s.push(e),!e.leaf&&s.length-1!==a;){let l,d=1/0,x=1/0;for(let f=0;f<e.children.length;f++){let m=e.children[f],D=LY(m),b=QNt(r,m)-D;b<x?(x=b,d=D<d?D:d,l=m):b===x&&D<d&&(d=D,l=m)}e=l||e.children[0]}return e}_insert(r,e,a){let s=a?r:this.toBBox(r),l=[],d=this._chooseSubtree(s,this.data,e,l);for(d.children.push(r),Jb(d,s);e>=0&&l[e].children.length>this._maxEntries;)this._split(l,e),e--;this._adjustParentBBoxes(s,l,e)}_split(r,e){let a=r[e],s=a.children.length,l=this._minEntries;this._chooseSplitAxis(a,l,s);let d=this._chooseSplitIndex(a,l,s),x=hg(a.children.splice(d,a.children.length-d));x.height=a.height,x.leaf=a.leaf,fg(a,this.toBBox),fg(x,this.toBBox),e?r[e-1].children.push(x):this._splitRoot(a,x)}_splitRoot(r,e){this.data=hg([r,e]),this.data.height=r.height+1,this.data.leaf=!1,fg(this.data,this.toBBox)}_chooseSplitIndex(r,e,a){let s,l=1/0,d=1/0;for(let x=e;x<=a-e;x++){let f=Kb(r,0,x,this.toBBox),m=Kb(r,x,a,this.toBBox),D=eMt(f,m),b=LY(f)+LY(m);D<l?(l=D,s=x,d=b<d?b:d):D===l&&b<d&&(d=b,s=x)}return s||a-e}_chooseSplitAxis(r,e,a){let s=r.leaf?this.compareMinX:JNt,l=r.leaf?this.compareMinY:ZNt;this._allDistMargin(r,e,a,s)<this._allDistMargin(r,e,a,l)&&r.children.sort(s)}_allDistMargin(r,e,a,s){r.children.sort(s);let l=this.toBBox,d=Kb(r,0,e,l),x=Kb(r,a-e,a,l),f=S5(d)+S5(x);for(let m=e;m<a-e;m++){let D=r.children[m];Jb(d,r.leaf?l(D):D),f+=S5(d)}for(let m=a-e-1;m>=e;m--){let D=r.children[m];Jb(x,r.leaf?l(D):D),f+=S5(x)}return f}_adjustParentBBoxes(r,e,a){for(let s=a;s>=0;s--)Jb(e[s],r)}_condense(r){for(let e,a=r.length-1;a>=0;a--)r[a].children.length===0?a>0?(e=r[a-1].children,e.splice(e.indexOf(r[a]),1)):this.clear():fg(r[a],this.toBBox)}};function KNt(r,e,a){if(!a)return e.indexOf(r);for(let s=0;s<e.length;s++)if(a(r,e[s]))return s;return-1}function fg(r,e){Kb(r,0,r.children.length,e,r)}function Kb(r,e,a,s,l){l||(l=hg(null)),l.minX=1/0,l.minY=1/0,l.maxX=-1/0,l.maxY=-1/0;for(let d=e;d<a;d++){let x=r.children[d];Jb(l,r.leaf?s(x):x)}return l}function Jb(r,e){return r.minX=Math.min(r.minX,e.minX),r.minY=Math.min(r.minY,e.minY),r.maxX=Math.max(r.maxX,e.maxX),r.maxY=Math.max(r.maxY,e.maxY),r}function JNt(r,e){return r.minX-e.minX}function ZNt(r,e){return r.minY-e.minY}function LY(r){return(r.maxX-r.minX)*(r.maxY-r.minY)}function S5(r){return r.maxX-r.minX+(r.maxY-r.minY)}function QNt(r,e){return(Math.max(e.maxX,r.maxX)-Math.min(e.minX,r.minX))*(Math.max(e.maxY,r.maxY)-Math.min(e.minY,r.minY))}function eMt(r,e){let a=Math.max(r.minX,e.minX),s=Math.max(r.minY,e.minY),l=Math.min(r.maxX,e.maxX),d=Math.min(r.maxY,e.maxY);return Math.max(0,l-a)*Math.max(0,d-s)}function $Y(r,e){return r.minX<=e.minX&&r.minY<=e.minY&&e.maxX<=r.maxX&&e.maxY<=r.maxY}function B5(r,e){return e.minX<=r.maxX&&e.minY<=r.maxY&&e.maxX>=r.minX&&e.maxY>=r.minY}function hg(r){return{children:r,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function z4e(r,e,a,s,l){let d=[e,a];for(;d.length;){if((a=d.pop())-(e=d.pop())<=s)continue;let x=e+Math.ceil((a-e)/s/2)*s;h6e(r,x,e,a,l),d.push(e,x,x,a)}}var q4e=class{constructor(r=9){z(this,"tree");this.tree=new WNt(r)}insert(r,e,a,s,l){this.tree.insert({minX:e,minY:a,maxX:s,maxY:l,data:r})}bulkLoad(r){let e=r.map(({item:a,minX:s,minY:l,maxX:d,maxY:x})=>({minX:s,minY:l,maxX:d,maxY:x,data:a}));this.tree.load(e)}search(r,e,a,s){return this.tree.search({minX:r,minY:e,maxX:a,maxY:s}).map(l=>l.data)}clear(){this.tree.clear()}},tMt=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(r,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]=r,this.values[a]=e}pop(){if(this.length===0)return;let r=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 d=1+(l<<1),x=d+1,f=this.ids[d],m=this.values[d],D=this.values[x];if(x<this.length&&D<m&&(d=x,f=this.ids[x],m=D),m>=a)break;this.ids[l]=f,this.values[l]=m,l=d}this.ids[l]=e,this.values[l]=a}return r}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}},U4e=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],V4e=class m6e{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 d=l>>4;if(d!==3)throw new Error(`Got v${d} data when expected v3.`);let x=U4e[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 m6e(m,f,x,void 0,e,a)}constructor(e,a=16,s=Float64Array,l=ArrayBuffer,d,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=U4e.indexOf(this.ArrayType),b=4*m*this.ArrayType.BYTES_PER_ELEMENT;if(D<0)throw new Error(`Unexpected typed array class: ${s}.`);d&&d.byteLength!==void 0&&!d.buffer?(this.data=d,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 tMt}add(e,a,s=e,l=a){let d=this._pos>>2,x=this._boxes;return this._indices[d]=d,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),d}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 d=0,x=0;d<this.numItems;d++){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[d]=nMt(E,A)}JY(l,e,this._indices,0,this.numItems-1,this.nodeSize);for(let d=0,x=0;d<this._levelBounds.length-1;d++){let f=this._levelBounds[d];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,d){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,X4e(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):(d===void 0||d(E))&&m.push(E)}x=f.pop()}return m}neighbors(e,a,s=1/0,l=1/0,d){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,X4e(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):(d===void 0||d(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(r,e,a){return r<e?e-r:r<=a?0:r-a}function X4e(r,e){let a=0,s=e.length-1;for(;a<s;){let l=a+s>>1;e[l]>r?s=l:a=l+1}return e[a]}function JY(r,e,a,s,l,d){if(Math.floor(s/d)>=Math.floor(l/d))return;let x=r[s+l>>1],f=s-1,m=l+1;for(;;){do f++;while(r[f]<x);do m--;while(r[m]>x);if(f>=m)break;rMt(r,e,a,f,m)}JY(r,e,a,s,m,d),JY(r,e,a,m+1,l,d)}function rMt(r,e,a,s,l){let d=r[s];r[s]=r[l],r[l]=d;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 nMt(r,e){let a=r^e,s=65535^a,l=65535^(r|e),d=r&(65535^e),x=a|s>>1,f=a>>1^a,m=l>>1^s&d>>1^l,D=a&l>>1^d>>1^d;a=x,s=f,l=m,d=D,x=a&a>>2^s&s>>2,f=a&s>>2^s&(a^s)>>2,m^=a&l>>2^s&d>>2,D^=s&l>>2^(a^s)&d>>2,a=x,s=f,l=m,d=D,x=a&a>>4^s&s>>4,f=a&s>>4^s&(a^s)>>4,m^=a&l>>4^s&d>>4,D^=s&l>>4^(a^s)&d>>4,a=x,s=f,l=m,d=D,m^=a&l>>8^s&d>>8,D^=s&l>>8^(a^s)&d>>8,a=m^m>>1,s=D^D>>1;let b=r^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 aMt=class{constructor(r){z(this,"index");z(this,"items",[]);z(this,"currentIndex",0);z(this,"capacity");this.capacity=Math.max(1,r),this.index=new V4e(this.capacity)}insert(r,e,a,s,l){if(this.currentIndex>=this.index.numItems)throw new Error("Exceeded initial capacity");this.items[this.currentIndex]=r,this.index.add(e,a,s,l),this.currentIndex++}finish(){this.index.finish()}search(r,e,a,s){return this.index.search(r,e,a,s).map(l=>this.items[l]||null).filter(Boolean)}clear(){this.items=[],this.currentIndex=0,this.index=new V4e(this.capacity)}},g6e=class{constructor(r="native",e=[]){z(this,"idx");z(this,"storage",[]);r==="flatbush"?e.length===0?(this.idx=new q4e,r="rbush"):this.idx=new aMt(e.length):this.idx=r==="rbush"?new q4e:new class{constructor(){z(this,"shi",new sMt(e))}insert(a){}search(a,s,l,d){let x=(a+l)/2,f=(s+d)/2,m=l-a,D=d-s;return this.shi.getNodesInArea(x,f,m,D)}clear(){}},e.forEach(a=>this.insert(a)),r==="flatbush"&&e.length>0&&this.idx.finish?.()}insert(r){this.storage.push(r),this.idx.insert(r,r.center.x-r.width/2,r.center.y-r.height/2,r.center.x+r.width/2,r.center.y+r.height/2)}search(r){return this.idx.search(r.minX,r.minY,r.maxX,r.maxY)}searchArea(r,e,a,s){return this.search({minX:r-a/2,minY:e-s/2,maxX:r+a/2,maxY:e+s/2})}},sMt=class{constructor(r){z(this,"buckets");z(this,"CELL_SIZE",.4);this.obstacles=r,this.buckets=new Map;for(let e=0;e<r.length;e++){let a=r[e],s=a.center.x-a.width/2,l=a.center.y-a.height/2,d=a.center.x+a.width/2,x=a.center.y+a.height/2;for(let f=s;f<=d;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(r,e){return`${Math.floor(r/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getNodesInArea(r,e,a,s){let l=[],d=new Set,x=e-s/2,f=r+a/2,m=e+s/2;for(let D=r-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)d.has(B[1])||(d.add(B[1]),l.push(B[0]))}return l}},iMt=class{constructor(r){z(this,"buckets");z(this,"CELL_SIZE",5);this.targets=r,this.buckets=new Map;for(let e=0;e<r.length;e++){let a=r[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,d=a.bounds.maxX,x=a.bounds.maxY;for(let f=s;f<=d;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(r,e){return`${Math.floor(r/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getTargetsInArea(r,e,a,s){let l=[],d=new Set,x=Math.floor((r-a/2)/this.CELL_SIZE)*this.CELL_SIZE,f=Math.floor((e-s/2)/this.CELL_SIZE)*this.CELL_SIZE,m=r+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)d.has(w[1])||(d.add(w[1]),l.push(w[0]))}return l}},oMt=class extends Aa{constructor(e,a={}){super();z(this,"unfinishedNodes");z(this,"finishedNodes");z(this,"nodeToXYOverlappingObstaclesMap");z(this,"layerCount");z(this,"MAX_DEPTH",4);z(this,"targets");z(this,"targetTree");z(this,"obstacleTree");z(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(nF(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},d=Math.max(l.width,l.height);this.unfinishedNodes=[{capacityMeshNodeId:this.getNextNodeId(),center:s,width:d,height:d,layer:"top",availableZ:[0,1],_depth:0,_containsTarget:!0,_containsObstacle:!0,_completelyInsideObstacle:!1}],this.finishedNodes=[],this.nodeToXYOverlappingObstaclesMap=new Map,this.obstacleTree=new g6e("flatbush",this.srj.obstacles),this.targets=this.computeTargets(),this.targetTree=new iMt(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)),d={minX:s.x-.005,minY:s.y-.005,maxX:s.x+.005,maxY:s.y+.005};l.length>0&&(d={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:d};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,d=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;(d>=b&&l<=E&&f>=A&&x<=B||l>=b&&d<=E&&x>=A&&f<=B||b>=l&&E<=d&&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(d=>l.zLayers.includes(d))&&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,d=e.center.y+e.height/2;return a<this.srj.bounds.minX||s>this.srj.bounds.maxX||l<this.srj.bounds.minY||d>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,d=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&&d>=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 d of l){let x={capacityMeshNodeId:this.getNextNodeId(),center:d,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 d of a){let x=this.shouldNodeBeXYSubdivided(d);x?l.push(d):x||d._containsObstacle?!x&&d._containsTarget&&s.push(d):s.push(d)}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),d=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:d?"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: ${X0(s).toFixed(2)}`].join(`
@@ -1034,8 +1034,8 @@ ${B.join(`
1034
1034
  `)}
1035
1035
  </div>`},gqt=r=>{let e=r.layout(),a={title:"CssGrid",coordinateSystem:"screen",lines:[],circles:[],points:[],rects:[],texts:[]},{cells:s}=e;for(let l of s){let{x:d,y:x,width:f,height:m,key:D}=l;a.rects.push({center:{x:d+f/2,y:x+m/2},width:f,height:m,fill:mSe(D),label:D})}return a};function AS(r){return r.replace(/repeat\((\d+),\s*([^)]+)\)/g,(e,a,s)=>Array(Number(a)).fill(s.trim()).join(" "))}function RS(r){return r.trim().split(/\s+/).filter(Boolean)}function xSe(r){return r?RS(AS(r)).length:0}function fSe(r,e){if(r==="auto")return{fr:1};if(r.endsWith("%")){let s=parseFloat(r);return e!=null?e*s/100:0}if(r.endsWith("px"))return parseFloat(r);if(r.endsWith("em"))return parseFloat(r)*16;if(r.endsWith("fr"))return{fr:parseFloat(r)};let a=parseFloat(r);return Number.isNaN(a)?0:a}function hSe(r,e){return r>0?r:e+2+r}var Dqt=r=>{let e=r.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 d=xSe(l),x=xSe(s);function f(L,K,U,J){if(!L)return 0;let Q=AS(L),de=RS(Q),oe=de.length,Me=0,Ne=!1;for(let tt=0;tt<de.length;tt++){let He=de[tt];if(He.endsWith("px"))Me+=parseFloat(He);else if(He.endsWith("em"))Me+=parseFloat(He)*16;else if(He.endsWith("fr")||He==="auto"){Ne=!0;let $t=0;for(let bt of K){let ct=U?bt.columnStart||bt.column:bt.rowStart||bt.row,ot=U?bt.columnSpan||1:bt.rowSpan||1,Ut=U?bt.contentWidth:bt.contentHeight,It=(typeof ct=="number"?ct:parseInt(ct||"1"))-1,tr=typeof ot=="number"?ot:parseInt(ot.toString());if(It<=tt&&tt<It+tr&&Ut){let Dr=typeof Ut=="string"&&Ut.endsWith("px")?parseFloat(Ut):typeof Ut=="number"?Ut:0;$t=Math.max($t,Dr/tr)}}Me+=$t}}let Ge=J*(oe-1);return Me+Ge}function m(L,K,U,J=!0,Q=1){if(!L)return[];if(K==null){let ot=AS(L),Ut=RS(ot),It=Ut.length,tr=Fe=>Fe===void 0?0:typeof Fe=="number"?Fe:(Fe.endsWith("px"),parseFloat(Fe)),Dr=new Array(It).fill(0),vt=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,Qe=tr(_e)/Pe,Ft;J?(Fe.columnStart!==void 0||Fe.column!==void 0)&&(Ft=parseInt(Fe.columnStart??Fe.column)-1):(Fe.rowStart!==void 0||Fe.row!==void 0)&&(Ft=parseInt(Fe.rowStart??Fe.row)-1),(Ft===void 0||Number.isNaN(Ft))&&(J?Ft=vt%It:Ft=Math.floor(vt/Q),vt+=Pe);for(let St=0;St<Pe&&Ft+St<It;St++)Dr[Ft+St]=Math.max(Dr[Ft+St],Qe)}return Ut.forEach((Fe,Pe)=>{let _e=fSe(Fe,void 0);typeof _e=="number"&&(Dr[Pe]=_e)}),Dr}let de=AS(L),oe=RS(de),Me=oe.length,Ne=K;Ne==null&&(Ne=f(L,a,J,U));let Ge=Ne-U*(Me-1),tt=0,He=0,$t=[],bt=[];oe.forEach((ot,Ut)=>{let It=fSe(ot,Ge);typeof It=="number"?(bt.push(It),tt+=It):It&&typeof It=="object"&&"fr"in It?(bt.push(It),He+=It.fr,$t.push({idx:Ut,fr:It.fr})):(bt.push(0),tt+=0)});let ct=Math.max(Ge-tt,0);return bt.map(ot=>typeof ot=="number"?ot:He>0?ct/He*ot.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,d||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=[],j=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 Me=typeof L.rowEnd=="string"?parseInt(L.rowEnd):L.rowEnd;K!==void 0?J=Me-(typeof K=="string"?parseInt(K):K):K=Me-J}if(L.columnEnd!==void 0){let Me=typeof L.columnEnd=="string"?parseInt(L.columnEnd):L.columnEnd;U!==void 0?Q=Me-(typeof U=="string"?parseInt(U):U):U=Me-Q}if(typeof K=="string"&&(K=parseInt(K)),typeof U=="string"&&(U=parseInt(U)),typeof K=="number"&&K<0&&(K=hSe(K,B)),typeof U=="number"&&U<0&&(U=hSe(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 Me=j;K=Math.floor(Me/w)+1,U=Me%w+1}let de=K-1,oe=U-1;J=Math.max(1,J),Q=Math.max(1,Q),P.push({key:L.key,row:de,column:oe,rowSpan:J,columnSpan:Q,x:0,y:0,width:0,height:0}),j+=Q}let O=E.length,q=A.length;for(let L of P)L.row+L.rowSpan>O&&(O=L.row+L.rowSpan),L.column+L.columnSpan>q&&(q=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&&q>0&&e.containerWidth){let L=q,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<q;)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},W=(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},re={};for(let L of P){let K=a.find(bt=>bt.key===L.key),U=ee(L.column,A,b),J=ee(L.row,E,D),Q=W(L.column,L.columnSpan,A,b),de=W(L.row,L.rowSpan,E,D),oe=bt=>bt===void 0?0:typeof bt=="string"?bt.endsWith("px")?parseFloat(bt):bt.endsWith("%")?0:parseFloat(bt):bt,Me=oe(K?.contentWidth),Ne=oe(K?.contentHeight),Ge=Q,tt=de,He=U,$t=J;if(Me>0)switch(Ge=Me,e.justifyItems||"stretch"){case"start":He=U;break;case"end":He=U+Q-Ge;break;case"center":He=U+(Q-Ge)/2;break;case"stretch":Ge=Q,He=U;break}if(Ne>0)switch(tt=Ne,e.alignItems||"stretch"){case"start":$t=J;break;case"end":$t=J+de-tt;break;case"center":$t=J+(de-tt)/2;break;case"stretch":tt=de,$t=J;break}L.x=He,L.y=$t,L.width=Ge,L.height=tt,re[L.key]={x:He,y:$t,width:Ge,height:tt}}return{cells:P,rowSizes:E,columnSizes:A,rowGap:D,columnGap:b,itemCoordinates:re}},gSe=class{constructor(r){z(this,"opts");this.opts=r}layout(){return Dqt(this)}convertToHtml(){return mqt(this)}visualize(){return gqt(this)}};qt();var p9e=Or(fs(),1);ra();ra();qt();var vW=class{constructor(r){z(this,"netMap");z(this,"idToNetMap");this.netMap=r,this.idToNetMap={};for(let[e,a]of Object.entries(r))for(let s of a)this.idToNetMap[s]=e}addConnections(r){for(let e of r){let a=new Set;for(let l of e){let d=this.idToNetMap[l];d&&a.add(d)}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 d=this.netMap[s],x=this.netMap[l];if(d&&x){d.push(...x),this.netMap[l]=d;for(let f of d)this.idToNetMap[f]=s}}}for(let l of e){let d=this.netMap[s];d&&!d.includes(l)&&d.push(l),this.idToNetMap[l]=s}}}getIdsConnectedToNet(r){return this.netMap[r]||[]}getNetConnectedToId(r){return this.idToNetMap[r]}areIdsConnected(r,e){if(r===e)return!0;let a=this.getNetConnectedToId(r);if(!a)return!1;let s=this.getNetConnectedToId(e);return s?a===s||s===r||s===r:!1}areAllIdsConnected(r){if(r.length===0)return!0;let e=this.getNetConnectedToId(r[0]);if(!e)return!1;for(let a of r){let s=this.getNetConnectedToId(a);if(s===void 0||s!==e)return!1}return!0}};var TF=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,d=this.values[l];if(a>=d)break;this.ids[s]=this.ids[l],this.values[s]=d,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 d=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]=d,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 DSe=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],CW=3,PF=class r{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 d=l>>4;if(d!==CW)throw new Error(`Got v${d} data when expected v${CW}.`);let x=DSe[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 r(m,f,x,void 0,e,a)}constructor(e,a=16,s=Float64Array,l=ArrayBuffer,d,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=DSe.indexOf(s),b=m*4*s.BYTES_PER_ELEMENT;if(D<0)throw new Error(`Unexpected typed array class: ${s}.`);if(d)this.data=d,this._boxes=new s(d,x+8,m*4),this._indices=new this.IndexArrayType(d,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,(CW<<4)+D]),new Uint16Array(E,2,1)[0]=a,new Uint32Array(E,4,1)[0]=e}this._queue=new TF}add(e,a,s=e,l=a){let d=this._pos>>2,x=this._boxes;return this._indices[d]=d,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),d}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),d=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(d*((m+b)/2-this.minX)/a),B=Math.floor(d*((D+E)/2-this.minY)/s);l[x]=bqt(A,B)}_W(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,d){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,ySe(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):(d===void 0||d(P,E,A,B,w))&&m.push(P)}x=f.pop()}return m}neighbors(e,a,s=1/0,l=1/0,d){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,ySe(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],j=this._boxes[E+3],O=e<B?B-e:e>P?e-P:0,q=a<w?w-a:a>j?a-j:0,ee=O*O+q*q;ee>D||(x>=this.numItems*4?f.push(A<<1,ee):(d===void 0||d(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 ySe(r,e){let a=0,s=e.length-1;for(;a<s;){let l=a+s>>1;e[l]>r?s=l:a=l+1}return e[a]}function _W(r,e,a,s,l,d){if(Math.floor(s/d)>=Math.floor(l/d))return;let x=r[s],f=r[s+l>>1],m=r[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(r[E]<D);do A--;while(r[A]>D);if(E>=A)break;yqt(r,e,a,E,A)}_W(r,e,a,s,A,d),_W(r,e,a,A+1,l,d)}function yqt(r,e,a,s,l){let d=r[s];r[s]=r[l],r[l]=d;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 bqt(r,e){let a=r^e,s=65535^a,l=65535^(r|e),d=r&(e^65535),x=a|s>>1,f=a>>1^a,m=l>>1^s&d>>1^l,D=a&l>>1^d>>1^d;a=x,s=f,l=m,d=D,x=a&a>>2^s&s>>2,f=a&s>>2^s&(a^s)>>2,m^=a&l>>2^s&d>>2,D^=s&l>>2^(a^s)&d>>2,a=x,s=f,l=m,d=D,x=a&a>>4^s&s>>4,f=a&s>>4^s&(a^s)>>4,m^=a&l>>4^s&d>>4,D^=s&l>>4^(a^s)&d>>4,a=x,s=f,l=m,d=D,m^=a&l>>8^s&d>>8,D^=s&l>>8^(a^s)&d>>8,a=m^m>>1,s=D^D>>1;let b=r^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 ex=class{constructor(){z(this,"MAX_ITERATIONS",1e5);z(this,"solved",!1);z(this,"failed",!1);z(this,"iterations",0);z(this,"progress",0);z(this,"error",null);z(this,"activeSubSolver");z(this,"failedSubSolvers");z(this,"timeToSolve");z(this,"stats",{})}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(r){throw this.error=`${this.constructor.name} error: ${r}`,this.failed=!0,r}!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 r=Date.now();for(;!this.solved&&!this.failed;)this.step();let e=Date.now();this.timeToSolve=e-r}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}},_Se=r=>{let e=new vW({});for(let s of r.directConnections)e.addConnections([s.netId?[s.netId,...s.pinIds]:s.pinIds]);let a=new vW(e.netMap);for(let s of r.netConnections)a.addConnections([[s.netId,...s.pinIds]]);return{directConnMap:e,netConnMap:a}};function Fqt(r,e={}){let a=r.length,s=e?.maxDistance??Number.POSITIVE_INFINITY;if(a<=1)return[];{let b=new Set;for(let E of r){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),d=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++)r[b].pinId<r[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(!d[w]){let P=x[w];(P<A||P===A&&(B===""||r[w].pinId<B))&&(A=P,B=r[w].pinId,E=w)}d[E]=!0,f[E]!==-1&&D.push([r[E].pinId,r[f[E]].pinId]);for(let w=0;w<a;w++)if(!d[w]){let P=l(r[E],r[w]),j=e?.forbidEdge?.(r[E],r[w])??!1,O=P>s||j?Number.POSITIVE_INFINITY:P;(O<x[w]||O===x[w]&&r[E].pinId<r[f[w]]?.pinId)&&(x[w]=O,f[w]=E)}}return D}var IF=(r,e)=>{let{x:a,y:s}=r,{center:l,width:d,height:x}=e,f=l.y+x/2,m=l.y-x/2,D=l.x+d/2,b=l.x-d/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-"},Eqt=r=>{let{pins:e,inputProblem:a,pinIdMap:s,chipMap:l}=r,d=A=>{let B=new Set,w=[A];B.add(A);let P=a.directConnections||[];for(;w.length;){let j=w.shift();for(let O of P)if(O.pinIds.includes(j))for(let q of O.pinIds)B.has(q)||(B.add(q),w.push(q))}return B},x=e[0].pinId,f=e[1].pinId,m=new Set([...d(x),...d(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??IF(B,w),j=b.get(w.chipId);if(!j){j={center:w.center};let O={xPos:0,xNeg:0,yPos:0,yNeg:0};for(let q of w.pins){let ee=q._facingDirection??IF(q,w);ee==="x+"&&O.xPos++,ee==="x-"&&O.xNeg++,ee==="y+"&&O.yPos++,ee==="y-"&&O.yNeg++}j.counts=O,b.set(w.chipId,j)}P==="x+"&&(j.hasXPos=!0),P==="x-"&&(j.hasXNeg=!0),P==="y+"&&(j.hasYPos=!0),P==="y-"&&(j.hasYNeg=!0)}for(let[A,B]of b){let w=new Set,P={axes:w},j=B.counts;!!!(j&&(j.xPos>1||j.xNeg>1||j.yPos>1||j.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},AW=r=>{let{inputProblem:e,chipMap:a,pinIdMap:s,p1:l,p2:d}=r,x=Eqt({pins:[l,d],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-d.x)<f||Math.abs(l.y-d.y)<f)return m({x:l.x,y:l.y},{x:d.x,y:d.y});let D={x:d.x,y:l.y},b={x:l.x,y:d.y},E=m({x:l.x,y:l.y},D)||m(D,{x:d.x,y:d.y}),A=m({x:l.x,y:l.y},b)||m(b,{x:d.x,y:d.y});return E&&A},tl=(r,e=1)=>`hsl(${r.split("").reduce((s,l)=>s*31+l.charCodeAt(0),0)%360}, 100%, 50%, ${e})`,_1=(r,e={})=>{let{connectionAlpha:a=.8,chipAlpha:s=.8}=e,l={lines:[],points:[],rects:[]},d=new Map;for(let x of r.chips)for(let f of x.pins)d.set(f.pinId,f);for(let x of r.chips){l.rects.push({label:x.chipId,center:x.center,width:x.width,height:x.height,fill:tl(x.chipId,s)});for(let f of x.pins)l.points.push({label:`${f.pinId}
1036
1036
  ${f._facingDirection??IF(f,x)}`,x:f.x,y:f.y,color:tl(f.pinId,.8)})}for(let x of r.directConnections){let[f,m]=x.pinIds,D=d.get(f),b=d.get(m);l.lines.push({points:[{x:D.x,y:D.y},{x:b.x,y:b.y}],strokeColor:tl(x.netId??`${f}-${m}`,a)})}for(let x of r.netConnections){let f=x.pinIds.map(m=>d.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:tl(x.netId,a),strokeDash:"4 2"})}}return l},vqt=class extends ex{constructor({inputProblem:e}){super();z(this,"inputProblem");z(this,"mspConnectionPairs",[]);z(this,"dcConnMap");z(this,"globalConnMap");z(this,"queuedDcNetIds");z(this,"chipMap");z(this,"maxMspPairDistance");z(this,"pinMap");z(this,"userNetIdByPinId");this.inputProblem=e,this.maxMspPairDistance=e.maxMspPairDistance??1;let{directConnMap:a,netConnMap:s}=_Se(e);this.dcConnMap=a,this.globalConnMap=s,this.pinMap={};for(let l of e.chips)for(let d of l.pins)this.pinMap[d.pinId]={...d,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[d,x]=l.pinIds;this.userNetIdByPinId[d]=l.netId,this.userNetIdByPinId[x]=l.netId}for(let l of e.netConnections)for(let d of l.pinIds)this.userNetIdByPinId[d]=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(AW({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)),d=Fqt(s.map(x=>this.pinMap[x]).filter(Boolean),{maxDistance:this.maxMspPairDistance,forbidEdge:(x,f)=>AW({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:l,p1:x,p2:f})});for(let[x,f]of d){let m=this.pinMap[x],D=this.pinMap[f];if(AW({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=_1(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:tl(a.mspPairId,.75)});return e}};function BW(r){let e=r.width/2,a=r.height/2;return{minX:r.center.x-e,maxX:r.center.x+e,minY:r.center.y-a,maxY:r.center.y+a}}var Cqt=r=>{let e=BW(r);return{chipId:r.chipId,...e}},_qt=r=>r.chips.map(Cqt),wW=1e-9,BS=(r,e,a=wW)=>Math.abs(r.x-e.x)<a,wS=(r,e,a=wW)=>Math.abs(r.y-e.y)<a,Aqt=(r,e,a,s=wW)=>{let l=BS(r,e,s),d=wS(r,e,s);if(!l&&!d)return!1;if(l){let x=r.x;if(x<a.minX-s||x>a.maxX+s)return!1;let f=Math.min(r.y,e.y),m=Math.max(r.y,e.y);return Math.min(m,a.maxY)-Math.max(f,a.minY)>s}else{let x=r.y;if(x<a.minY-s||x>a.maxY+s)return!1;let f=Math.min(r.x,e.x),m=Math.max(r.x,e.x);return Math.min(m,a.maxX)-Math.max(f,a.minX)>s}},Rqt=(r,e,a={})=>{for(let s=0;s<r.length-1;s++){let l=r[s],d=r[s+1],x=a.excludeRectIdsForSegment?.(s)??new Set;for(let f of e)if(!x.has(f.chipId)&&Aqt(l,d,f))return{segIndex:s,rect:f}}return null},ASe=1e-9,Sqt=(r,e)=>({minX:Math.min(r.x,e.x),maxX:Math.max(r.x,e.x),minY:Math.min(r.y,e.y),maxY:Math.max(r.y,e.y)}),bSe=(r,e,a,s=ASe)=>r==="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],Bqt=(r,e,a,s,l,d=ASe)=>{let x=[...s].map(f=>a.get(f)).filter(f=>!!f);if(r==="x"){let f=[l.minX,...x.map(A=>A.maxX)].filter(A=>A<e.minX-d),m=[l.maxX,...x.map(A=>A.minX)].filter(A=>A>e.maxX+d),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-d),m=[l.maxY,...x.map(A=>A.minY)].filter(A=>A>e.maxY+d),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}},wqt=1e-9,Tqt=(r,e,a,s,l=wqt)=>{if(e<0||e>=r.length-1)return null;let d=r[e],x=r[e+1],f=BS(d,x,l),m=wS(d,x,l);if(!f&&!m||f&&a!=="x"||m&&a!=="y")return null;let D=r.map(b=>({...b}));if(a==="x"){if(Math.abs(d.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(d.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(!wS(E,A,l)&&!BS(E,A,l))return null}return D},FSe=(r,e=6)=>r.map(a=>`${a.x.toFixed(e)},${a.y.toFixed(e)}`).join("|"),Pqt=class extends ex{constructor(e){super();z(this,"pins");z(this,"inputProblem");z(this,"chipMap");z(this,"obstacles");z(this,"rectById");z(this,"aabb");z(this,"baseElbow");z(this,"solvedTracePath",null);z(this,"queue",[]);z(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 d=this.chipMap[l.chipId];l._facingDirection=IF(l,d)}this.obstacles=_qt(this.inputProblem),this.rectById=new Map(this.obstacles.map(l=>[l.chipId,l]));let[a,s]=this.pins;this.baseElbow=dg({x:a.x,y:a.y,facingDirection:a._facingDirection},{x:s.x,y:s.y,facingDirection:s._facingDirection},{overshoot:.2}),this.aabb=Sqt({x:a.x,y:a.y},{x:s.x,y:s.y}),this.queue.push({path:this.baseElbow,collisionChipIds:new Set}),this.visited.add(FSe(this.baseElbow))}getConstructorParams(){return{chipMap:this.chipMap,pins:this.pins,inputProblem:this.inputProblem}}axisOfSegment(e,a){return BS(e,a)?"x":wS(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,d]=this.pins,x=Rqt(a,this.obstacles);if(!x){let j=a[0],O=a[a.length-1],q=1e-9,ee=(W,re)=>Math.abs(W.x-re.x)<q&&Math.abs(W.y-re.y)<q;ee(j,{x:l.x,y:l.y})&&ee(O,{x:d.x,y:d.y})&&(this.solvedTracePath=a,this.solved=!0);return}let{segIndex:f,rect:m}=x,D=f===0,b=f===a.length-2;if(D){if(a.length<3)return;f=1}else if(b){if(a.length<3)return;f=a.length-3}let E=a[f],A=a[f+1],B=this.axisOfSegment(E,A);if(!B)return;let w=[];if(s.size===0){let j=bSe(B,{x:l.x,y:l.y},m),O=bSe(B,{x:d.x,y:d.y},m),q=[...j,...O],ee=[...new Set(q)];w.push(...ee)}else{let j=Bqt(B,m,this.rectById,s,this.aabb);w.push(...j)}let P=[];for(let j of w){let O=Tqt(a,f,B,j);if(!O)continue;let q=FSe(O);if(this.visited.has(q))continue;this.visited.add(q);let ee=new Set(s);ee.add(m.chipId);let W=this.pathLength(O);P.push({path:O,collisionRectIds:ee,len:W})}P.sort((j,O)=>j.len-O.len);for(let j of P)this.queue.push({path:j.path,collisionChipIds:j.collisionRectIds})}visualize(){let e=_1(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:d}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}},Iqt=class extends ex{constructor(e){super();z(this,"inputProblem");z(this,"mspConnectionPairs");z(this,"dcConnMap");z(this,"globalConnMap");z(this,"queuedConnectionPairs");z(this,"chipMap");z(this,"currentConnectionPair",null);z(this,"solvedTracePaths",[]);z(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 Pqt({inputProblem:this.inputProblem,pins:a,chipMap:this.chipMap})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=_1(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}},jqt=({pts:r,segmentIndex:e,offset:a,JOG_SIZE:s,EPS:l=1e-6})=>{if(e!==0&&e!==r.length-2)return;let d=r[e],x=r[e+1],f=Math.abs(d.x-x.x)<l,m=Math.abs(d.y-x.y)<l;if(!f&&!m)return;let D=f?x.y>d.y?1:-1:x.x>d.x?1:-1;if(e===0)if(f){let b=d.y+D*s;r.splice(1,1,{x:d.x,y:b},{x:d.x+a,y:b},{x:x.x+a,y:x.y})}else{let b=d.x+D*s;r.splice(1,1,{x:b,y:d.y},{x:b,y:d.y+a},{x:x.x,y:x.y+a})}else if(f){let b=x.y-D*s;r.splice(e,1,{x:d.x+a,y:d.y},{x:x.x+a,y:b},{x:x.x,y:b})}else{let b=x.x-D*s;r.splice(e,1,{x:d.x,y:d.y+a},{x:b,y:x.y+a},{x:b,y:x.y})}},kqt=class extends ex{constructor(e){super();z(this,"overlappingTraceSegments");z(this,"traceNetIslands");z(this,"SHIFT_DISTANCE",.1);z(this,"correctedTraceMap",{});this.overlappingTraceSegments=e.overlappingTraceSegments,this.traceNetIslands=e.traceNetIslands;for(let{connNetId:a,pathsWithOverlap:s}of this.overlappingTraceSegments)for(let{solvedTracePathIndex:l,traceSegmentIndex:d}of s){let x=this.traceNetIslands[a][l].mspPairId;this.correctedTraceMap[x]=this.traceNetIslands[a][l]}}_step(){let a=this.overlappingTraceSegments.map((d,x)=>{let f=Math.floor(x/2)+1;return(x%2===0?-f:f)*this.SHIFT_DISTANCE}),s=(d,x)=>Math.abs(d-x)<1e-6,l=(d,x)=>!!d&&!!x&&s(d.x,x.x)&&s(d.y,x.y);this.overlappingTraceSegments.forEach((d,x)=>{let f=a[x],m=new Map;for(let D of d.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[d.connNetId][D],A=this.correctedTraceMap[E.mspPairId]??E,B=A.tracePath.map(q=>({...q})),w=Array.from(b).sort((q,ee)=>q-ee),P=Array.from(b).sort((q,ee)=>q-ee).reverse(),j=this.SHIFT_DISTANCE;for(let q of P)if(!(q<0||q>=B.length-1))if(q===0||q===B.length-2)jqt({pts:B,segmentIndex:q,offset:f,JOG_SIZE:j,EPS:1e-6});else{let ee=B[q],W=B[q+1],re=Math.abs(ee.x-W.x)<1e-6,L=Math.abs(ee.y-W.y)<1e-6;if(!re&&!L)continue;re?(ee.x+=f,W.x+=f):(ee.y+=f,W.y+=f)}let O=[];for(let q of B)(O.length===0||!l(O[O.length-1],q))&&O.push(q);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 d=this.traceNetIslands[a.connNetId][s],x=d.tracePath[l],f=d.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}},Nqt=class extends ex{constructor(e){super();z(this,"inputProblem");z(this,"inputTracePaths");z(this,"globalConnMap");z(this,"traceNetIslands",{});z(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 d=a[s],x=a[l],f=this.traceNetIslands[d]||[],m=this.traceNetIslands[x]||[],D=[],b=[],E=new Set,A=new Set,B=(w,P,j,O)=>{let q=Math.min(w,P),ee=Math.max(w,P),W=Math.min(j,O),re=Math.max(j,O);return Math.min(ee,re)-Math.max(q,W)>.002};for(let w=0;w<f.length;w++){let j=f[w].tracePath;for(let O=0;O<j.length-1;O++){let q=j[O],ee=j[O+1],W=Math.abs(q.x-ee.x)<.002,re=Math.abs(q.y-ee.y)<.002;if(!(!W&&!re))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],oe=Math.abs(Q.x-de.x)<.002,Me=Math.abs(Q.y-de.y)<.002;if(!(!oe&&!Me)){if(W&&oe){if(Math.abs(q.x-Q.x)<.002&&B(q.y,ee.y,Q.y,de.y)){let Ne=`${w}:${O}`,Ge=`${L}:${J}`;E.has(Ne)||(D.push({solvedTracePathIndex:w,traceSegmentIndex:O}),E.add(Ne)),A.has(Ge)||(b.push({solvedTracePathIndex:L,traceSegmentIndex:J}),A.add(Ge))}}else if(re&&Me&&Math.abs(q.y-Q.y)<.002&&B(q.x,ee.x,Q.x,de.x)){let Ne=`${w}:${O}`,Ge=`${L}:${J}`;E.has(Ne)||(D.push({solvedTracePathIndex:w,traceSegmentIndex:O}),E.add(Ne)),A.has(Ge)||(b.push({solvedTracePathIndex:L,traceSegmentIndex:J}),A.add(Ge))}}}}}}if(D.length>0&&b.length>0)return{overlappingTraceSegments:[{connNetId:d,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 kqt({overlappingTraceSegments:a,traceNetIslands:this.traceNetIslands})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=_1(this.inputProblem);for(let a of Object.values(this.correctedTraceMap))e.lines.push({points:a.tracePath,strokeColor:"purple"});return e}},Mqt=class{constructor(r){z(this,"chips");z(this,"spatialIndex");z(this,"spatialIndexIdToChip");this.chips=r.map(e=>({...e,bounds:BW(e),spatialIndexId:null})),this.spatialIndexIdToChip=new Map,this.spatialIndex=new PF(r.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(r){return this.spatialIndex.search(r.minX,r.minY,r.maxX,r.maxY).map(a=>this.spatialIndexIdToChip.get(a))}doesOrthogonalLineIntersectChip(r,e={}){let a=e.excludeChipIds??[],[s,l]=r,{x:d,y:x}=s,{x:f,y:m}=l;return this.getChipsInBounds({minX:Math.min(d,f),minY:Math.min(x,m),maxX:Math.max(d,f),maxY:Math.max(x,m)}).filter(b=>!a.includes(b.chipId)).length>0}},Oqt=.45,ESe=.2;function RW(r){let{orientation:e,netLabelWidth:a}=r,s=typeof a=="number"?a:Oqt;return e==="y+"||e==="y-"?{width:ESe,height:s}:{width:s,height:ESe}}function SW(r,e,a,s){switch(e){case"x+":return{x:r.x+a/2,y:r.y};case"x-":return{x:r.x-a/2,y:r.y};case"y+":return{x:r.x,y:r.y+s/2};case"y-":return{x:r.x,y:r.y-s/2}}}function RSe(r,e,a){return{minX:r.x-e/2,minY:r.y-a/2,maxX:r.x+e/2,maxY:r.y+a/2}}function Lqt(r,e,a,s=1e-9){let l=Math.abs(r.x-e.x)<s,d=Math.abs(r.y-e.y)<s;if(!l&&!d)return!1;if(l){let x=r.x;if(x<a.minX-s||x>a.maxX+s)return!1;let f=Math.min(r.y,e.y),m=Math.max(r.y,e.y);return Math.min(m,a.maxY)-Math.max(f,a.minY)>s}else{let x=r.y;if(x<a.minY-s||x>a.maxY+s)return!1;let f=Math.min(r.x,e.x),m=Math.max(r.x,e.x);return Math.min(m,a.maxX)-Math.max(f,a.minX)>s}}function SSe(r,e,a,s){for(let[l,d]of Object.entries(e)){let x=d.tracePath;for(let f=0;f<x.length-1;f++)if(!(l===a&&f===s)&&Lqt(x[f],x[f+1],r))return{hasIntersection:!0,mspPairId:l,segIndex:f}}return{hasIntersection:!1}}function vSe(r){let e=0,a=r.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 BSe(r){let{inputProblem:e,inputTraceMap:a,globalConnNetId:s,fallbackTrace:l,mspConnectionPairIds:d}=r,x=Object.fromEntries(e.chips.map(A=>[A.chipId,A])),f=Object.values(a).filter(A=>A.globalConnNetId===s);if(d&&d.length>0){let A=new Set(d);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)=>vSe(A)>=vSe(B)?A:B):l}function $qt(r,e){return[{x:r.x,y:r.y},{x:(r.x+e.x)/2,y:(r.y+e.y)/2},{x:e.x,y:e.y}]}function zqt(r){let{inputProblem:e,inputTraceMap:a,chipObstacleSpatialIndex:s,overlappingSameNetTraceGroup:l,availableOrientations:d,netLabelWidth:x}=r,f=l.portOnlyPinId;if(!f)return{placement:null,testedCandidates:[],error:"No portOnlyPinId provided"};let m=null,D=null;for(let L of e.chips){let K=L.pins.find(U=>U.pinId===f);if(K){m={x:K.x,y:K.y},D=K._facingDirection||IF(K,L);break}}if(!m||!D)return{placement:null,testedCandidates:[],error:`Port-only pin not found: ${f}`};let b=d.length>0?d:["x+","x-","y+","y-"],E={x:m.x,y:m.y},A=L=>L==="x+"?{x:1,y:0}:L==="x-"?{x:-1,y:0}:L==="y+"?{x:0,y:1}:{x:0,y:-1},B=[];for(let L of b){let{width:K,height:U}=RW({orientation:L,netLabelWidth:x}),J=SW(E,L,K,U),Q=A(L),de=.001,oe={x:J.x+Q.x*de,y:J.y+Q.y*de},Me=RSe(oe,K,U);if(s.getChipsInBounds(Me).length>0){B.push({center:oe,width:K,height:U,bounds:Me,anchor:E,orientation:L,status:"chip-collision",hostSegIndex:-1});continue}if(SSe(Me,a,"",-1).hasIntersection){B.push({center:oe,width:K,height:U,bounds:Me,anchor:E,orientation:L,status:"trace-collision",hostSegIndex:-1});continue}return B.push({center:oe,width:K,height:U,bounds:Me,anchor:E,orientation:L,status:"ok",hostSegIndex:-1}),{placement:{globalConnNetId:l.globalConnNetId,dcConnNetId:void 0,netId:l.netId,mspConnectionPairIds:[],pinIds:[f],orientation:L,anchorPoint:E,width:K,height:U,center:oe},testedCandidates:B}}let w=D,{width:P,height:j}=RW({orientation:w,netLabelWidth:x}),O=SW(E,w,P,j),q=A(w),ee=.001,W={x:O.x+q.x*ee,y:O.y+q.y*ee};return{placement:{globalConnNetId:l.globalConnNetId,dcConnNetId:void 0,netId:l.netId,mspConnectionPairIds:[],pinIds:[f],orientation:w,anchorPoint:E,width:P,height:j,center:W},testedCandidates:B}}function qqt(r){let e=_1(r.inputProblem),a=r.overlappingSameNetTraceGroup.globalConnNetId,s=BSe({inputProblem:r.inputProblem,inputTraceMap:r.inputTraceMap,globalConnNetId:a,fallbackTrace:r.overlappingSameNetTraceGroup.overlappingTraces}),l=tl(a,.9),d=tl(a,.5);for(let x of Object.values(r.inputTraceMap)){let f=s?x.mspPairId===s.mspPairId:!1;e.lines.push({points:x.tracePath})}for(let x of r.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(r.netLabelPlacement){let x=r.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 CSe=class extends ex{constructor(e){super();z(this,"inputProblem");z(this,"inputTraceMap");z(this,"overlappingSameNetTraceGroup");z(this,"availableOrientations");z(this,"chipObstacleSpatialIndex");z(this,"netLabelWidth");z(this,"netLabelPlacement",null);z(this,"testedCandidates",[]);this.inputProblem=e.inputProblem,this.inputTraceMap=e.inputTraceMap,this.overlappingSameNetTraceGroup=e.overlappingSameNetTraceGroup,this.availableOrientations=e.availableOrientations,this.netLabelWidth=e.netLabelWidth,this.chipObstacleSpatialIndex=e.inputProblem._chipObstacleSpatialIndex??new Mqt(e.inputProblem.chips)}getConstructorParams(){return{inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth}}_step(){if(this.netLabelPlacement){this.solved=!0;return}if(this.overlappingSameNetTraceGroup.portOnlyPinId){let A=zqt({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,chipObstacleSpatialIndex:this.chipObstacleSpatialIndex,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth});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=BSe({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)))),d=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 d){let B=A.tracePath.slice();for(let w=0;w<B.length-1;w++){let P=B[w],j=B[w+1],O=Math.abs(P.y-j.y)<E,q=Math.abs(P.x-j.x)<E;if(!O&&!q)continue;let ee=O?["y+","y-"]:["x+","x-"],W=x.filter(L=>ee.includes(L));if(W.length===0)continue;let re=$qt(P,j);for(let L of re)for(let K of W){let{width:U,height:J}=RW({orientation:K,netLabelWidth:this.netLabelWidth}),Q=SW(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},oe=1e-4,Me={x:Q.x+de.x*oe,y:Q.y+de.y*oe},Ne=RSe(Me,U,J);if(this.chipObstacleSpatialIndex.getChipsInBounds(Ne).length>0){this.testedCandidates.push({center:Me,width:U,height:J,bounds:Ne,anchor:L,orientation:K,status:"chip-collision",hostSegIndex:w});continue}if(SSe(Ne,this.inputTraceMap,A.mspPairId,w).hasIntersection){this.testedCandidates.push({center:Me,width:U,height:J,bounds:Ne,anchor:L,orientation:K,status:"trace-collision",hostSegIndex:w});continue}if(this.testedCandidates.push({center:Me,width:U,height:J,bounds:Ne,anchor:L,orientation:K,status:"ok",hostSegIndex:w}),f){let He=m(K,L);He>b+1e-9&&(b=He,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 qqt(this)}},Uqt=class extends ex{constructor(e){super();z(this,"inputProblem");z(this,"inputTraceMap");z(this,"overlappingSameNetTraceGroups");z(this,"queuedOverlappingSameNetTraceGroups");z(this,"netLabelPlacements",[]);z(this,"currentGroup",null);z(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}=_Se(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 d=[],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 q of E[O]??[])A.has(q)||(A.add(q),w.push(q))}let j=(e[m]??[]).filter(O=>P.has(O.pins[0].pinId)&&P.has(O.pins[1].pinId));if(j.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},q=j[0],ee=O(q);for(let K=1;K<j.length;K++){let U=O(j[K]);U>ee&&(q=j[K],ee=U)}let W=j.find(K=>K.userNetId!=null)?.userNetId;if(!W){for(let K of P)if(l[K]){W=l[K];break}}let re=Array.from(new Set(j.flatMap(K=>K.mspConnectionPairIds??[K.mspPairId]))),L={globalConnNetId:m,netId:W,overlappingTraces:q,mspConnectionPairIds:re};d.push(L)}else for(let O of P){let q=l[O];q&&d.push({globalConnNetId:m,netId:q,portOnlyPinId:O})}}}return d}_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 l=["x+","x-","y+","y-"],d=this.activeSubSolver.availableOrientations,x=d.length===4&&l.every(f=>d.includes(f));if(!this.triedAnyOrientationFallbackForCurrentGroup&&!x&&this.currentGroup){this.triedAnyOrientationFallbackForCurrentGroup=!0;let f=this.currentGroup.netId?this.inputProblem.netConnections.find(m=>m.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new CSe({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.currentGroup,availableOrientations:l,netLabelWidth:f});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;let s=this.currentGroup.netId?this.inputProblem.netConnections.find(l=>l.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new CSe({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:e,availableOrientations:this.inputProblem.availableNetLabelOrientations[a]??["x+","x-","y+","y-"],netLabelWidth:s})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=_1(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:tl(a.globalConnNetId,.35),strokeColor:tl(a.globalConnNetId,.9)}),e.points.push({x:a.anchorPoint.x,y:a.anchorPoint.y,color:tl(a.globalConnNetId,.9)});return e}},Vqt=r=>{for(let e of r.chips){let a=BW(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 d=s.x-a.minX,x=a.maxX-s.x,f=s.y-a.minY,m=a.maxY-s.y,D=Math.min(d,x,f,m);D===d?s.x=a.minX:D===x?s.x=a.maxX:D===f?s.y=a.minY:s.y=a.maxY,s._facingDirection=void 0}}},Gqt=r=>{for(let e of r.chips){let a=e.width/2,s=e.height/2,l=0,d=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>d&&(d=b)}let x=Math.max(a,l),f=Math.max(s,d);if(x>a||f>s){e.width=x*2,e.height=f*2;for(let m of e.pins)m._facingDirection=void 0}}};function SS(r,e,a,s={}){return{solverName:r,solverClass:e,getConstructorParams:a,onSolved:s.onSolved}}var wSe=class extends ex{constructor(e){super();z(this,"mspConnectionPairSolver");z(this,"schematicTraceLinesSolver");z(this,"traceOverlapShiftSolver");z(this,"netLabelPlacementSolver");z(this,"startTimeOfPhase");z(this,"endTimeOfPhase");z(this,"timeSpentOnPhase");z(this,"firstIterationOfPhase");z(this,"inputProblem");z(this,"pipelineDef",[SS("mspConnectionPairSolver",vqt,()=>[{inputProblem:this.inputProblem}],{onSolved:e=>{}}),SS("schematicTraceLinesSolver",Iqt,()=>[{mspConnectionPairs:this.mspConnectionPairSolver.mspConnectionPairs,dcConnMap:this.mspConnectionPairSolver.dcConnMap,globalConnMap:this.mspConnectionPairSolver.globalConnMap,inputProblem:this.inputProblem,chipMap:this.mspConnectionPairSolver.chipMap}],{onSolved:e=>{}}),SS("traceOverlapShiftSolver",Nqt,()=>[{inputProblem:this.inputProblem,inputTracePaths:this.schematicTraceLinesSolver.solvedTracePaths,globalConnMap:this.mspConnectionPairSolver.globalConnMap}],{onSolved:e=>{}}),SS("netLabelPlacementSolver",Uqt,()=>[{inputProblem:this.inputProblem,inputTraceMap:this.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(this.schematicTraceLinesSolver.solvedTracePaths.map(e=>[e.mspPairId,e]))}],{onSolved:e=>{}})]);z(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 Gqt(a),Vqt(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=[_1(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 x9e=Or(fs(),1);var f9e=Or(fs(),1);var h9e=Or(fs(),1);Fo();ra();Fo();ra();ra();qt();ra();ra();V0();ra();Fo();ra();function TSe(r,e,a,s){return Math.sqrt((a-r)**2+(s-e)**2)}var Xqt=r=>{let e=r.filter(d=>d.type==="pcb_port"),a=r.filter(d=>d.type==="pcb_smtpad"),s=r.filter(d=>d.type==="pcb_trace");function l(d,x={}){let f=x.traceWidth||0,m=e.find(D=>TSe(D.x,D.y,d.x,d.y)<.01);if(m)return m.pcb_port_id;if(x.isFirstOrLastPoint){let D=a.find(b=>{if(b.shape==="rect")return Math.abs(d.x-b.x)<b.width/2+f/2&&Math.abs(d.y-b.y)<b.height/2+f/2;if(b.shape==="circle")return TSe(d.x,d.y,b.x,b.y)<b.radius});if(D)return D.pcb_port_id??null}return null}for(let d of s)for(let x=0;x<d.route.length;x++){let f=d.route[x],m=x===0||x===d.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===d.route.length-1){let D=l(f,{isFirstOrLastPoint:m,traceWidth:f.width});D&&(f.end_pcb_port_id=D)}}}};function ISe(r){Xqt(r);let e=r.filter(x=>x.type==="source_trace"),a=r.filter(x=>x.type==="pcb_port"),s=[],l=eu(r),d=new Map;for(let x of a)d.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=d.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=>r.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 Yqt=class{constructor({objects:r,getBounds:e,getId:a,CELL_SIZE:s}){z(this,"buckets");z(this,"objectsById");z(this,"getBounds");z(this,"getId");z(this,"CELL_SIZE",.4);z(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 r)this.addObject(l)}_getNextId(){return`${this._idCounter++}`}addObject(r){let e=this.getBounds(r),a=this.getId(r),s={...r,spatialIndexId:a};this.objectsById.set(a,s);let l=Math.floor(e.minX/this.CELL_SIZE),d=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=d;D<=f;D++){let b=`${m}x${D}`,E=this.buckets.get(b);E?E.push(s):this.buckets.set(b,[s])}}removeObject(r){let e=this.objectsById.get(r);if(!e)return!1;this.objectsById.delete(r);let a=this.getBounds(e),s=Math.floor(a.minX/this.CELL_SIZE),l=Math.floor(a.minY/this.CELL_SIZE),d=Math.floor(a.maxX/this.CELL_SIZE),x=Math.floor(a.maxY/this.CELL_SIZE);for(let f=s;f<=d;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===r);E!==-1&&(b.splice(E,1),b.length===0&&this.buckets.delete(D))}}return!0}getBucketKey(r,e){return`${Math.floor(r/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getObjectsInBounds(r,e=0){let a=[],s=new Set,l=Math.floor((r.minX-e)/this.CELL_SIZE),d=Math.floor((r.minY-e)/this.CELL_SIZE),x=Math.floor((r.maxX+e)/this.CELL_SIZE),f=Math.floor((r.maxY+e)/this.CELL_SIZE);for(let m=l;m<=x;m++)for(let D=d;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}},jF=r=>r.type==="pcb_trace_segment"?{minX:Math.min(r.x1,r.x2),minY:Math.min(r.y1,r.y2),maxX:Math.max(r.x1,r.x2),maxY:Math.max(r.y1,r.y2)}:S4e([r]),TW=.1,Hqt=.15;var PW=.005;function Wqt(r){let e=new Set;for(let a of r.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 IW(r){let e=new Set;for(let a of r)for(let s of Wqt(a))e.add(s);return Array.from(e)}var Kqt=(r,e)=>{let a={x:r.x1,y:r.y1},s={x:r.x2,y:r.y2},l={x:e.x1,y:e.y1},d={x:e.x2,y:e.y2},x={x:s.x-a.x,y:s.y-a.y},f={x:d.x-l.x,y:d.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=rl(((a.x-l.x)*f.x+(a.y-l.y)*f.y)/D,0,1),oe={x:l.x+de*f.x,y:l.y+de*f.y};return{x:(a.x+oe.x)/2,y:(a.y+oe.y)/2}}let J=rl(((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,j=E*w-A*A;if(j<1e-10)return Jqt(a,s,l,d,x,f,m,D);let O=(A*P-w*B)/j,q=(E*P-A*B)/j;O=rl(O,0,1),q=rl(q,0,1),q=(O*A+P)/w,q=rl(q,0,1),O=(q*A-B)/E,O=rl(O,0,1);let ee={x:a.x+O*x.x,y:a.y+O*x.y},W={x:l.x+q*f.x,y:l.y+q*f.y},re=ee.x-W.x,L=ee.y-W.y,K=Math.sqrt(re*re+L*L);return{x:(ee.x+W.x)/2,y:(ee.y+W.y)/2}},Jqt=(r,e,a,s,l,d,x,f)=>{let m=((a.x-r.x)*l.x+(a.y-r.y)*l.y)/x;m=rl(m,0,1);let D={x:r.x+m*l.x,y:r.y+m*l.y},b=((s.x-r.x)*l.x+(s.y-r.y)*l.y)/x;b=rl(b,0,1);let E={x:r.x+b*l.x,y:r.y+b*l.y},A=((r.x-a.x)*d.x+(r.y-a.y)*d.y)/f;A=rl(A,0,1);let B={x:a.x+A*d.x,y:a.y+A*d.y},w=((e.x-a.x)*d.x+(e.y-a.y)*d.y)/f;w=rl(w,0,1);let P={x:a.x+w*d.x,y:a.y+w*d.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:r,pointB:B,distance:Math.sqrt((r.x-B.x)**2+(r.y-B.y)**2)},{pointA:e,pointB:P,distance:Math.sqrt((e.x-P.x)**2+(e.y-P.y)**2)}].reduce((q,ee)=>ee.distance<q.distance?ee:q);return{x:(O.pointA.x+O.pointB.x)/2,y:(O.pointA.y+O.pointB.y)/2}},rl=(r,e,a)=>Math.max(e,Math.min(a,r)),Zqt=r=>{if(r.type==="pcb_via"||r.type==="pcb_plated_hole"&&r.shape==="circle")return r.outer_diameter/2;if(r.type==="pcb_hole"&&r.hole_shape==="circle")return r.hole_diameter/2;if(r.type==="pcb_smtpad"&&r.shape==="circle")return r.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(r)}`)},PSe=(r,e)=>{let a={x:r.x1,y:r.y1},s={x:r.x2,y:r.y2},l=e.minX,d=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(d,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?(d-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 j={x:Math.max(l,Math.min(x,a.x)),y:Math.max(d,Math.min(f,a.y))},O={x:Math.max(l,Math.min(x,s.x)),y:Math.max(d,Math.min(f,s.y))},q=(j.x-a.x)**2+(j.y-a.y)**2,ee=(O.x-s.x)**2+(O.y-s.y)**2,W=[{start:{x:l,y:d},end:{x,y:d}},{start:{x,y:d},end:{x,y:f}},{start:{x,y:f},end:{x:l,y:f}},{start:{x:l,y:f},end:{x:l,y:d}}],re=Math.min(q,ee),L=q<=ee?j:O,K=(U,J,Q)=>Math.max(J,Math.min(Q,U));for(let U of W){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},oe=J.x*J.x+J.y*J.y,Me=J.x*Q.x+J.y*Q.y,Ne=J.x*de.x+J.y*de.y,Ge=Q.x*Q.x+Q.y*Q.y,tt=Q.x*de.x+Q.y*de.y,He=oe*Ge-Me*Me;if(Math.abs(He)<1e-10)continue;let $t=(Me*tt-Ge*Ne)/He,bt=(oe*tt-Me*Ne)/He;$t=K($t,0,1),bt=K(bt,0,1);let ct={x:a.x+$t*J.x,y:a.y+$t*J.y},ot={x:U.start.x+bt*Q.x,y:U.start.y+bt*Q.y},Ut=ct.x-ot.x,It=ct.y-ot.y,tr=Ut*Ut+It*It;tr<re&&(re=tr,L={x:(ct.x+ot.x)/2,y:(ct.y+ot.y)/2})}return L};function Qqt(r){return r.type==="pcb_trace_segment"?[r.layer]:r.type==="pcb_smtpad"?[r.layer]:r.type==="pcb_plated_hole"?Array.isArray(r.layers)?r.layers:[...$m]:r.type==="pcb_hole"?[...$m]:r.type==="pcb_via"?Array.isArray(r.layers)?r.layers:[...$m]:r.type==="pcb_keepout"?Array.isArray(r.layers)?r.layers:[]:[]}function jSe(r,{connMap:e}={}){let a=[];e??(e=eu(r));let l=La(r).pcb_trace.list().flatMap(w=>{let P=[];for(let j=0;j<w.route.length-1;j++){let O=w.route[j],q=w.route[j+1];O.route_type==="wire"&&q.route_type==="wire"&&O.layer===q.layer&&P.push({type:"pcb_trace_segment",pcb_trace_id:w.pcb_trace_id,_pcbTrace:w,thickness:"width"in O?O.width:"width"in q?q.width:Hqt,layer:O.layer,x1:O.x,y1:O.y,x2:q.x,y2:q.y})}return P}),d=La(r).pcb_smtpad.list(),x=La(r).pcb_plated_hole.list(),f=La(r).pcb_hole.list(),m=La(r).pcb_via.list(),D=La(r).pcb_keepout.list(),b=[...l,...d,...x,...f,...m,...D],E=new Yqt({objects:b,getBounds:jF}),A=w=>d1(r,w),B=new Set;for(let w of l){let P=TW,j=jF(w),O=E.getObjectsInBounds(j,P+w.thickness/2);if(!(w.x1===w.x2&&w.y1===w.y2))for(let q of O){if(!Qqt(q).includes(w.layer))continue;if(q.type==="pcb_trace_segment"){let L=q;if(w.layer!==L.layer||e.areIdsConnected(w.pcb_trace_id,L.pcb_trace_id))continue;let K=y5({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>TW-PW)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:Kqt(w,L),pcb_port_ids:IW([w._pcbTrace,L._pcbTrace])});continue}let ee=v5(q);if(e.areIdsConnected(w.pcb_trace_id,"pcb_trace_id"in q?q.pcb_trace_id:ee))continue;if(q.type==="pcb_via"||q.type==="pcb_plated_hole"&&q.shape==="circle"||q.type==="pcb_hole"||q.type==="pcb_smtpad"&&q.shape==="circle"){let L=Zqt(q),U=b5({x:w.x1,y:w.y1},{x:w.x2,y:w.y2},{x:q.x,y:q.y,radius:L})-w.thickness/2;if(U>TW-PW)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 ${q.type} "${A(v5(q))}" ${U<0?"(accidental contact)":`(gap: ${U.toFixed(3)}mm)`}`,pcb_trace_id:w.pcb_trace_id,center:PSe(w,jF(q)),source_trace_id:"",pcb_trace_error_id:J,pcb_component_ids:["pcb_component_id"in q?q.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...IW([w._pcbTrace]),"pcb_port_id"in q?q.pcb_port_id:void 0].filter(Boolean)})}let re=Xb({x:w.x1,y:w.y1},{x:w.x2,y:w.y2},jF(q))-w.thickness/2;if(re+PW<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 ${q.type} "${A(v5(q))}" ${re<0?"(accidental contact)":`(gap: ${re.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 q?q.pcb_component_id:void 0].filter(Boolean),center:PSe(w,jF(q)),pcb_port_ids:[...IW([w._pcbTrace]),"pcb_port_id"in q?q.pcb_port_id:void 0].filter(Boolean)})}}}return a}function kSe(r){return r.area()>=0}function NSe({center:r,size:e,rotationDeg:a=0}){let s=r.x,l=r.y,d=e.width/2,x=e.height/2,f=[new el(s-d,l-x),new el(s+d,l-x),new el(s+d,l+x),new el(s-d,l+x)],m=new BF(f);if(a){let D=r5(a,s,l),b=f.map(E=>{let A=wa(D,{x:E.x,y:E.y});return new el(A.x,A.y)});m=new BF(b)}return kSe(m)||m.reverse(),m}function eUt({board:r}){if(r.outline&&r.outline.length>0){let e=r.outline.map(s=>new el(s.x,s.y)),a=new BF(e);return kSe(a)||a.reverse(),a}return r.center&&typeof r.width=="number"&&typeof r.height=="number"?NSe({center:r.center,size:{width:r.width,height:r.height},rotationDeg:0}):null}function tUt({circuitJson:r,component:e}){if(e.source_component_id){let a=r.find(s=>s.type==="source_component"&&s.source_component_id===e.source_component_id);if(a&&"name"in a&&a.name)return a.name}return d1(r,e.pcb_component_id)||"Unknown"}function rUt(r,e,a,s,l,d){let x=new el(a.x,a.y);if(!e.contains(x)){let P=e.distanceTo(x);return Array.isArray(P)?P[0]:Number(P)||0}let f=s/2,m=l/2,D=[{x:a.x-f,y:a.y-m},{x:a.x+f,y:a.y-m},{x:a.x+f,y:a.y+m},{x:a.x-f,y:a.y+m}],b=[];for(let P=0;P<4;P++){let j=(P+1)%4;b.push({x:(D[P].x+D[j].x)/2,y:(D[P].y+D[j].y)/2})}let E=r5(d,a.x,a.y),A=P=>{let j=wa(E,P);return new el(j.x,j.y)},B=D.concat(b).map(A),w=0;for(let P of B)if(!e.contains(P)){let j=e.distanceTo(P),O=Array.isArray(j)?j[0]:Number(j)||0;O>w&&(w=O)}if(w>0)return w;try{let P=dW.intersect(r,e),j=0;P?Array.isArray(P)?j=P.reduce((q,ee)=>q+(typeof ee.area=="function"?ee.area():0),0):typeof P.area=="function"?j=P.area():j=0:j=0;let O=r.area();if(j>0&&j<O){let q=1-j/O,ee=Math.abs(s),W=Math.abs(l);return Math.min(ee,W)*q}else return .1}catch{return .1}}function MSe(r){let e=r.find(d=>d.type==="pcb_board");if(!e)return[];let a=eUt({board:e});if(!a)return[];let s=r.filter(d=>d.type==="pcb_component");if(s.length===0)return[];let l=[];for(let d of s){if(!d.center||typeof d.width!="number"||typeof d.height!="number"||d.width<=0||d.height<=0)continue;let x=NSe({center:d.center,size:{width:d.width,height:d.height},rotationDeg:d.rotation||0});if(x.area()===0||a.contains(x))continue;let m=rUt(x,a,d.center,d.width,d.height,d.rotation||0),D=tUt({circuitJson:r,component:d}),b=Math.round(m*100)/100;l.push({type:"pcb_component_outside_board_error",error_type:"pcb_component_outside_board_error",pcb_component_outside_board_error_id:`pcb_component_outside_board_${d.pcb_component_id}`,message:`Component ${D} (${d.pcb_component_id}) extends outside board boundaries by ${b}mm`,pcb_component_id:d.pcb_component_id,pcb_board_id:e.pcb_board_id,component_center:d.center,component_bounds:{min_x:x.box.xmin,max_x:x.box.xmax,min_y:x.box.ymin,max_y:x.box.ymax},subcircuit_id:d.subcircuit_id,source_component_id:d.source_component_id})}return l}var jW=[{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 Ns(r){if(r==null)return"";if(r===0)return"0";let e=Math.abs(r),a=jW.find(d=>{let x=e/d.value;return x>=1&&x<1e3})||jW[jW.length-1],l=(r/a.value).toPrecision(3);return l.includes(".")&&!/\.0+$/.test(l)&&(l=l.replace(/0+$/,"")),l=l.replace(/\.0+$/,""),`${l}${a.symbol}`}qt();Ue();Fo();Jl();ra();var iwe=Or(kc(),1);var aK=Or(fs(),1),Xg=Or(kc(),1),nDr=Or(kc(),1);var w1=Or(A1(),1);var owe=Or(A1(),1),uwe=Or(A1(),1);var cwe=Or(A1(),1);var lwe=Or(A1(),1);var dwe=Or(A1(),1),pwe=Or(kc(),1);var wVt=Object.defineProperty,TVt=(r,e)=>{for(var a in e)wVt(r,a,{get:e[a],enumerable:!0})},GBe={};TVt(GBe,{Battery:()=>z9e,Board:()=>m9e,Breakout:()=>I9e,BreakoutPoint:()=>j9e,CadAssembly:()=>a9e,CadModel:()=>n9e,Capacitor:()=>y9e,Chip:()=>QS,Constraint:()=>B9e,CopperPour:()=>$9e,Crystal:()=>Y9e,Cutout:()=>XF,Diode:()=>F9e,FabricationNotePath:()=>w9e,FabricationNoteText:()=>T9e,Footprint:()=>r9e,Fuse:()=>E9e,Group:()=>Wg,Hole:()=>dK,Inductor:()=>V9e,Jumper:()=>v9e,Keepout:()=>XS,Led:()=>_9e,Mosfet:()=>W9e,Net:()=>oK,NetLabel:()=>k9e,NormalComponent:()=>es,PcbTrace:()=>lK,PinHeader:()=>q9e,Pinout:()=>b9e,PlatedHole:()=>Yg,Port:()=>Ni,Potentiometer:()=>G9e,PowerSource:()=>A9e,PrimitiveComponent:()=>qn,PushButton:()=>X9e,Renderable:()=>sK,Resistor:()=>S9e,Resonator:()=>U9e,SchematicBox:()=>twe,SchematicCell:()=>awe,SchematicLine:()=>Q9e,SchematicRect:()=>ewe,SchematicRow:()=>nwe,SchematicTable:()=>rwe,SchematicText:()=>Z9e,SilkscreenCircle:()=>N9e,SilkscreenLine:()=>O9e,SilkscreenPath:()=>cK,SilkscreenRect:()=>M9e,SilkscreenText:()=>JS,SmtPad:()=>GS,SolderJumper:()=>C9e,Subcircuit:()=>P9e,Switch:()=>K9e,Symbol:()=>swe,TestPoint:()=>J9e,Trace:()=>qc,TraceHint:()=>fK,Transistor:()=>H9e,Via:()=>L9e,VoltageSource:()=>R9e});var PVt=(0,HBe.default)("tscircuit:renderable"),ld=["ReactSubtreesRender","SourceNameDuplicateComponentRemoval","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","AssignFallbackProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SourceDesignRuleChecks","SimulationRender","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicComponentSizeCalculation","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbComponentAnchorAlignment","PcbLayout","PcbBoardAutoSize","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbCopperPourRender","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender"],IVt={PcbFootprintLayout:["PcbFootprintStringRender"],PcbComponentSizeCalculation:["PcbFootprintStringRender"],PcbLayout:["PcbFootprintStringRender"],PcbBoardAutoSize:["PcbFootprintStringRender"],PcbTraceHintRender:["PcbFootprintStringRender"],PcbManualTraceRender:["PcbFootprintStringRender"],PcbCopperPourRender:["PcbFootprintStringRender","PcbTraceRender","PcbRouteNetIslands"],PcbTraceRender:["PcbFootprintStringRender"],PcbRouteNetIslands:["PcbFootprintStringRender"],PcbDesignRuleChecks:["PcbFootprintStringRender"],SilkscreenOverlapAdjustment:["PcbFootprintStringRender"],CadModelRender:["PcbFootprintStringRender"],PartsEngineRender:["PcbFootprintStringRender"],PcbComponentAnchorAlignment:["PcbFootprintStringRender"]},jVt=0,sK=class{constructor(r){z(this,"renderPhaseStates");z(this,"shouldBeRemoved",!1);z(this,"children");z(this,"isPcbPrimitive",!1);z(this,"isSchematicPrimitive",!1);z(this,"_renderId");z(this,"_currentRenderPhase",null);z(this,"_asyncEffects",[]);z(this,"parent",null);this._renderId=`${jVt++}`,this.children=[],this.renderPhaseStates={};for(let e of ld)this.renderPhaseStates[e]={initialized:!1,dirty:!1}}_markDirty(r){this.renderPhaseStates[r].dirty=!0;let e=ld.indexOf(r);for(let a=e+1;a<ld.length;a++)this.renderPhaseStates[ld[a]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(r)}_queueAsyncEffect(r,e){let a={promise:e(),phase:this._currentRenderPhase,effectName:r,complete:!1};this._asyncEffects.push(a),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:r,componentDisplayName:this.getString(),phase:a.phase}),a.promise.then(()=>{a.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:r,componentDisplayName:this.getString(),phase:a.phase})}).catch(s=>{console.error(`Async effect error in ${a.phase} "${r}":
1037
- ${s.stack}`),a.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:r,componentDisplayName:this.getString(),phase:a.phase,error:s.toString()})})}_emitRenderLifecycleEvent(r,e){PVt(`${r}:${e} ${this.getString()}`);let a=`renderable:renderLifecycle:${r}:${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(r=>!r.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(r){for(let e of this._asyncEffects)if(!e.complete&&e.phase===r)return!0;for(let e of this.children)if(e._hasIncompleteAsyncEffectsInSubtreeForPhase(r))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(r=>r.getRenderGraph())}}runRenderCycle(){for(let r of ld)this.runRenderPhaseForChildren(r),this.runRenderPhase(r)}runRenderPhase(r){this._currentRenderPhase=r;let e=this.renderPhaseStates[r],a=e.initialized,s=e.dirty;if(!a&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&a){this._emitRenderLifecycleEvent(r,"start"),this?.[`remove${r}`]?.(),e.initialized=!1,e.dirty=!1,this._emitRenderLifecycleEvent(r,"end");return}let l=ld.indexOf(r)-1;if(l>=0){let x=ld[l];if(this._asyncEffects.filter(m=>m.phase===x).some(m=>!m.complete))return}let d=IVt[r]||[];for(let x of d)if(this._hasIncompleteAsyncEffectsInSubtreeForPhase(x))return;if(this._emitRenderLifecycleEvent(r,"start"),a){s&&(this?.[`update${r}`]?.(),e.dirty=!1),this._emitRenderLifecycleEvent(r,"end");return}e.dirty=!1,this?.[`doInitial${r}`]?.(),e.initialized=!0,this._emitRenderLifecycleEvent(r,"end")}runRenderPhaseForChildren(r){for(let e of this.children)e.runRenderPhaseForChildren(r),e.runRenderPhase(r)}renderError(r){throw typeof r=="string"?new Error(r):new Error(JSON.stringify(r,null,2))}},VS={},WBe=r=>{let e=Object.fromEntries(Object.entries(r).map(([a,s])=>[a.toLowerCase(),s]));Object.assign(VS,r),Object.assign(VS,e)},kVt=class extends Error{constructor(r,e,a){let s,l=Object.keys(a).filter(m=>m!=="_errors"),d=[],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(" "))&&d.push(`pinLabels.${m} ("${E}" has leading or trailing spaces)`)}let f=l.map(m=>m==="pinLabels"&&d.length>0?d.join(", "):a[m]._errors[0]?`${m} (${a[m]._errors[0]})`:`${m} (${JSON.stringify(a[m])})`).join(", ");"name"in e?s=`Invalid props for ${r} "${e.name}": ${f}`:"footprint"in e&&typeof e.footprint=="string"?s=`Invalid props for ${r} (unnamed ${e.footprint} component): ${f}`:s=`Invalid props for ${r} (unnamed): ${f}`,super(s),this.componentName=r,this.originalProps=e,this.formattedError=a}};function VW(r,e){let a=e.match(/^#(\w+)/);if(a)return r.props.id===a[1];let s=e.match(/^\.(\w+)/);if(s)return r.isMatchingNameOrAlias(s[1]);let[l,...d]=e.split(/(?=[#.[])/);return l==="pin"&&(l="port"),l&&l!=="*"&&r.lowercaseComponentName!==l.toLowerCase()?!1:d.every(x=>{if(x.startsWith("#"))return r.props.id===x.slice(1);if(x.startsWith("."))return r.isMatchingNameOrAlias(x.slice(1));let f=x.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!f)return!0;let[,m,D]=f;return r.props[m].toString()===D})}var iK={isTag:r=>!0,getParent:r=>r.parent,getChildren:r=>r.children,getName:r=>r.lowercaseComponentName,getAttributeValue:(r,e)=>{if(e==="class"&&"getNameAndAliases"in r)return r.getNameAndAliases().join(" ");if(e==="name"&&r._parsedProps?.name)return r._parsedProps.name;if(r._parsedProps&&e in r._parsedProps){let s=r._parsedProps[e];return typeof s=="string"?s:s!=null?String(s):null}if(e in r){let s=r[e];return typeof s=="string"?s:s!=null?String(s):null}let a=r._attributeLowerToCamelNameMap;if(a){let s=a[e];if(s&&s in r){let l=r[s];return typeof l=="string"?l:l!=null?String(l):null}}return null},hasAttrib:(r,e)=>{if(e==="class")return!!r._parsedProps?.name;if(r._parsedProps&&e in r._parsedProps||e in r)return!0;let a=r._attributeLowerToCamelNameMap;if(a){let s=a[e];if(s&&s in r)return!0}return!1},getSiblings:r=>r.parent?r.parent.children:[],prevElementSibling:r=>{if(!r.parent)return null;let e=r.parent.children,a=e.indexOf(r);return a>0?e[a-1]:null},getText:()=>"",removeSubsets:r=>r.filter((e,a)=>!r.some((s,l)=>a!==l&&s!==e&&s.getDescendants().includes(e))),existsOne:(r,e)=>e.some(r),findAll:(r,e)=>{let a=[],s=l=>{r(l)&&a.push(l);for(let d of l.children)s(d)};for(let l of e)s(l);return a},findOne:(r,e)=>{for(let a of e){if(r(a))return a;let s=a.children;if(s.length>0){let l=iK.findOne(r,s);if(l)return l}}return null},equals:(r,e)=>r._renderId===e._renderId,isHovered:r=>!1,isVisited:r=>!1,isActive:r=>!1},NVt={...iK,getChildren:r=>r.children.filter(e=>!e.isSubcircuit)},EBe={...iK,getChildren:r=>r.children.filter(e=>e.isSubcircuit)},vBe=r=>{if(/net\.[^\s>]*\./.test(r))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(r))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(r)){let e=r.match(/net\.([^ >]+)/),a=e?e[1]:"";throw new Error(`Net name "${a}" cannot start with a number, try using a prefix like "VBUS1"`)}return r.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 d=/^\d+$/.test(l)?`pin${l}`:l;return`${a}.${s} > .${d}`}).trim()},GW={adapter:NVt,cacheResults:!0},qn=class extends sK{constructor(e){super(e);z(this,"parent",null);z(this,"children");z(this,"childrenPendingRemoval");z(this,"props");z(this,"_parsedProps");z(this,"externallyAddedAliases");z(this,"isPrimitiveContainer",!1);z(this,"canHaveTextChildren",!1);z(this,"source_group_id",null);z(this,"source_component_id",null);z(this,"schematic_component_id",null);z(this,"pcb_component_id",null);z(this,"cad_component_id",null);z(this,"fallbackUnassignedName");z(this,"_cachedSelectAllQueries",new Map);z(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 kVt(this.lowercaseComponentName,this.props,s.error.format())}get config(){return{componentName:"",zodProps:v.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)}_getPcbRotationBeforeLayout(){let{pcbRotation:e}=this.props;return typeof e=="string"?parseFloat(e):e??null}computePcbPropsTransform(){let{_parsedProps:e}=this,a=this._getPcbRotationBeforeLayout()??0;return js(Ma(e.pcbX??0,e.pcbY??0),Ip(a*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let e=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(e&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let a=this._getPcbRotationBeforeLayout()??0;return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),js(Ma(e.x,e.y),Ip(a*Math.PI/180)))}if(this.isPcbPrimitive){let a=this.getPrimitiveContainer();if(a&&a._parsedProps.layer==="bottom")return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),P3e(),this.computePcbPropsTransform())}return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),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 js(Ma(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){let e=this._getSchematicGlobalManualPlacementTransform(this);return e||js(this.parent?.computeSchematicGlobalTransform?.()??Si(),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 d=`${a}_horz`,x=`${a}_vert`,f=`${a}_up`,m=`${a}_down`,D=`${a}_left`,b=`${a}_right`;if(b in ks&&l===0)return b;if(f in ks&&l===90)return f;if(D in ks&&l===180)return D;if(m in ks&&l===270)return m;if(d in ks&&(l===0||l===180))return d;if(x in ks&&(l===90||l===270))return x;if(a in ks)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?ks[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(VW(e,l.selector)||e.props.name===l.selector)return as(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(VW(e,l.selector)||e.props.name===l.selector)return as(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((VW(e,s.selector)||e.props.name===s.selector)&&s.relative_to==="group_center")return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),Ma(s.center.x,s.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return as(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return as(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],d=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(d)&&a.includes(d))}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 d of s)for(let x of l){let f=[`.${d} > .${x}`,`.${d} .${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=vBe(e),s=lY(a,this,GW);if(s.length>0)return this._cachedSelectAllQueries.set(e,s),s;let[l,...d]=a.split(" "),x=e5(l,this,{adapter:EBe});if(!x)return[];let f=x.selectAll(d.join(" "));return this._cachedSelectAllQueries.set(e,f),f}selectOne(e,a){if(this._cachedSelectOneQueries.has(e))return this._cachedSelectOneQueries.get(e);let s=vBe(e);a?.port&&(a.type="port");let l=null;if(a?.type&&(l=lY(s,this,GW).find(D=>D.lowercaseComponentName===a.type)),l??(l=e5(s,this,GW)),l)return this._cachedSelectOneQueries.set(e,l),l;let[d,...x]=s.split(" "),f=e5(d,this,{adapter:EBe});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()}},MVt=class extends qn{constructor(r,e){super(r),this._parsedProps={...r,error:e,type:r.type||"unknown",component_name:r.name,error_type:"source_failed_to_create_component_error",message:e instanceof Error?e.message:String(e),pcbX:r.pcbX,pcbY:r.pcbY,schX:r.schX,schY:r.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:v.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let r=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:r,schematic_center:e})}}};function OVt(r,e){return new MVt(r,e)}function LVt(r,e){let a=r;return a.__tsci={...e},r}var $Vt={supportsMutation:!0,createInstance(r,e){let a=VS[r];if(!a)throw Object.keys(VS).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 "${r}". 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 LVt(new a(e),{})}catch(s){return OVt({...e,componentType:r},s)}},createTextInstance(r){return{__text:r}},appendInitialChild(r,e){r.add(e)},appendChild(r,e){r.add(e)},appendChildToContainer(r,e){r.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(r){return r},preparePortalMount(r){throw new Error("Function not implemented.")},scheduleTimeout(r,e){throw new Error("Function not implemented.")},cancelTimeout(r){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(r){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(r,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:r=>{throw new Error("Function not implemented.")},detachDeletedInstance:r=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>zS.DefaultEventPriority,getCurrentUpdatePriority:()=>zS.DefaultEventPriority,resolveUpdatePriority:()=>zS.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},OS=(0,YBe.default)($Vt),KBe=r=>{let e={children:[],props:{name:"$root"},add(d){d.parent=this,this.children.push(d)},computePcbGlobalTransform(){return Si()}},a=[],s=OS.createContainer(e,0,null,!1,null,"tsci",d=>{console.log("Error in createContainer"),console.error(d),a.push(d)},null);if(OS.updateContainerSync(r,s,null,()=>{}),OS.flushSyncWork(),a.length>0)throw a[0];let l=OS.getPublicRootInstance(s);return l||e.children[0]},YF=(r,e)=>{if(typeof r=="number")return r;if(r.startsWith("pin"))return Number(r.slice(3));if(!e)throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`);for(let a in e)if((Array.isArray(e[a])?e[a]:[e[a]]).includes(r))return Number(a.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`)},zVt=(r,e)=>{if(!r)return;let a={},s={};for(let[l,d]of Object.entries(r)){let x=YF(l,e);s[x]={...s[x],...d}}for(let[l,d]of Object.entries(s)){let x=`pin${l}`;a[x]={bottom_margin:d.bottomMargin,left_margin:d.leftMargin,right_margin:d.rightMargin,top_margin:d.topMargin}}return a},qVt=r=>{if(r){if("leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r)return{left_side:r.leftSide,right_side:r.rightSide,top_side:r.topSide,bottom_side:r.bottomSide};if("leftPinCount"in r||"rightPinCount"in r||"topPinCount"in r||"bottomPinCount"in r)return{left_size:r.leftPinCount,right_size:r.rightPinCount,top_size:r.topPinCount,bottom_size:r.bottomPinCount};if("leftSize"in r||"rightSize"in r||"topSize"in r||"bottomSize"in r)return{left_size:r.leftSize,right_size:r.rightSize,top_size:r.topSize,bottom_size:r.bottomSize}}};function JBe(r){let e=[];for(let a=0;a<r.length-1;a++)e.push([r[a],r[a+1]]);return e}var UVt=v.object({name:v.string().refine(r=>!/[+-]/.test(r),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),oK=class extends qn{constructor(){super(...arguments);z(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:UVt}}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"),d=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=d.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 d of l)if(d._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 d=JBe(l);for(let[x,f]of d){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 q=m[O];for(let ee=0;ee<D.length;ee++){let W=D[ee],re=Math.sqrt((q.x-W.x)**2+(q.y-W.y)**2);re<b&&(b=re,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}=Z_e(w.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[A.source_port_id,B.source_port_id]}])),j=P[0];if(!j){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(j)}}renderError(e){if(typeof e=="string")return super.renderError(e);this.root?.db.pcb_trace_error.insert(e)}},uK=(r,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=r.getSubcircuit();if(!s.selectOne(a)){let l=new oK({name:a.split("net.")[1]});s.add(l)}}},GS=class extends qn{constructor(){super(...arguments);z(this,"pcb_smtpad_id",null);z(this,"matchedPort",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:FAe}}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),d=Math.min(...s),x=Math.max(...s),f=Math.min(...l),m=Math.max(...l);return{width:x-d,height:m-f}}if(e.shape==="pill")return{width:e.width,height:e.height};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let 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(),d=this._getGlobalPcbPositionBeforeLayout(),x=s?._getGlobalPcbPositionBeforeLayout(),f=i4(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()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,x:d.x,y:d.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()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,x:d.x,y:d.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:d.x,y:d.y,ccw_rotation:b,port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,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+d.x,y:B.y+d.y})),port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):a.shape==="pill"&&(E=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"pill",x:d.x,y:d.y,radius:a.radius,height:a.height,width:a.width,port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,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),d=Math.sin(s),x=a.width/2,f=a.height/2,m=Math.abs(x*l)+Math.abs(f*d),D=Math.abs(x*d)+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),d=s.map(b=>b.y),x=Math.min(...l),f=Math.max(...l),m=Math.min(...d),D=Math.max(...d);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}}if(a.shape==="pill"){let s=a.width/2,l=a.height/2;return{center:{x:a.x,y:a.y},bounds:{left:a.x-s,top:a.y-l,right:a.x+s,bottom:a.y+l},width:a.width,height:a.height}}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)}},cK=class extends qn{constructor(){super(...arguments);z(this,"pcb_silkscreen_path_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:r4e}}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 d=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=as(d,{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 d=0,x=0;for(let b of l.route)d+=b.x,x+=b.y;d/=l.route.length,x/=l.route.length;let f=e.x-d,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,d=-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),d=Math.max(d,x.y);return{width:s-a,height:d-l}}},VVt=v.object({route:v.array(UA),source_trace_id:v.string().optional()}),lK=class extends qn{constructor(){super(...arguments);z(this,"pcb_trace_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:VVt}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer(),l=this.getSubcircuit(),{maybeFlipLayer:d}=this._getPcbPrimitiveFlippedHelpers(),x=this._computePcbGlobalTransformBeforeLayout(),f=a.route.map(D=>{let{x:b,y:E,...A}=D,B=as(x,{x:b,y:E});return D.route_type==="wire"&&D.layer?{...B,...A,layer:d(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,d=-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),d=Math.max(d,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),d=Math.max(d,x.y+x.width/2));return a===1/0||s===-1/0||l===1/0||d===-1/0?{width:0,height:0}:{width:s-a,height:d-l}}},Yg=class extends qn{constructor(){super(...arguments);z(this,"pcb_plated_hole_id",null);z(this,"matchedPort",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:dAe}}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,d=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:d?.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:d?.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:d?.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:d?.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,hole_offset_x:a.holeOffsetX,hole_offset_y:a.holeOffsetY});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:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:a.pcbRotation??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:d?.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:d?.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:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:a.holeOffsetX,hole_offset_y:a.holeOffsetY,rect_border_radius:a.rectBorderRadius??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,hole_offset_x:a.holeOffsetX,hole_offset_y:a.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:d?.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})}},XS=class extends qn{constructor(){super(...arguments);z(this,"pcb_keepout_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:UAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let e=this.getSubcircuit(),{db:a}=this.root,{_parsedProps:s}=this,l=this._getGlobalPcbPositionBeforeLayout(),d=i4(this._computePcbGlobalTransformBeforeLayout()),x=Math.abs(d.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)}},dK=class extends qn{constructor(){super(...arguments);z(this,"pcb_hole_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:EAe}}getPcbSize(){let{_parsedProps:e}=this,a=e.shape==="pill";return{width:a?e.width:e.diameter,height:a?e.height:e.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=this._getGlobalPcbPositionBeforeLayout(),d=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=d.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})}},JS=class extends qn{constructor(){super(...arguments);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:t4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer(),l=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:d}=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:d(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,d=a;return{width:l*a,height:d*a}}},XF=class extends qn{constructor(){super(...arguments);z(this,"pcb_cutout_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:bAe}}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,d=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:d,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:d,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=>as(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,d=-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),d=Math.max(d,x.y);return{width:s-a,height:d-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,d=1/0,x=-1/0;for(let f of a.points)s=Math.min(s,f.x),l=Math.max(l,f.x),d=Math.min(d,f.y),x=Math.max(x,f.y);return{center:{x:(s+l)/2,y:(d+x)/2},bounds:{left:s,top:x,right:l,bottom:d},width:l-s,height:x-d}}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,d=e.x-l.x,x=e.y-l.y,f=s.points.map(m=>({x:m.x+d,y:m.y+x}));a.pcb_cutout.update(this.pcb_cutout_id,{...s,points:f})}}}},GVt=({elm:r,pinLabels:e,layer:a,readableRotation:s,anchorAlignment:l})=>{let d=r.text.replace(/[{}]/g,"").toLowerCase(),x=d;if(Array.isArray(e)){let f=parseInt(d.replace(/[^\d]/g,""),10)-1;x=String(e[f]??d)}else typeof e=="object"&&(x=String(e[d]??d));return new JS({anchorAlignment:l||"center",text:x??d,layer:a||"top",fontSize:r.font_size+.2,pcbX:isNaN(r.anchor_position.x)?0:r.anchor_position.x,pcbY:r.anchor_position.y,pcbRotation:s??0})},XVt=(r,e)=>((-parseInt(r||"0",10)+(e??0))%360+360)%360,qS=({componentName:r,componentRotation:e,footprint:a,pinLabels:s,pcbPinLabels:l},d)=>{let x=[];for(let f of d)if(f.type==="pcb_smtpad"&&f.shape==="rect")x.push(new GS({pcbX:f.x,pcbY:f.y,layer:f.layer,shape:"rect",height:f.height,width:f.width,portHints:f.port_hints,rectBorderRadius:f.rect_border_radius}));else if(f.type==="pcb_smtpad"&&f.shape==="circle")x.push(new GS({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 cK({layer:f.layer,route:f.route,strokeWidth:f.stroke_width}));else if(f.type==="pcb_plated_hole")f.shape==="circle"?x.push(new Yg({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 Yg({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,rectBorderRadius:f.rect_border_radius,holeOffsetX:f.hole_offset_x,holeOffsetY:f.hole_offset_y})):f.shape==="pill"||f.shape==="oval"?x.push(new Yg({pcbX:f.x,pcbY:f.y,shape:f.shape,holeWidth:f.hole_width,holeHeight:f.hole_height,outerWidth:f.outer_width,outerHeight:f.outer_height,portHints:f.port_hints})):f.shape==="pill_hole_with_rect_pad"&&x.push(new Yg({pcbX:f.x,pcbY:f.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:f.hole_width,holeHeight:f.hole_height,rectPadWidth:f.rect_pad_width,rectPadHeight:f.rect_pad_height,portHints:f.port_hints,holeOffsetX:f.hole_offset_x,holeOffsetY:f.hole_offset_y}));else if(f.type==="pcb_keepout"&&f.shape==="circle")x.push(new XS({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 XS({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 dK({pcbX:f.x,pcbY:f.y,diameter:f.hole_diameter}));else if(f.type==="pcb_cutout")f.shape==="rect"?x.push(new XF({pcbX:f.center.x,pcbY:f.center.y,shape:"rect",width:f.width,height:f.height})):f.shape==="circle"?x.push(new XF({pcbX:f.center.x,pcbY:f.center.y,shape:"circle",radius:f.radius})):f.shape==="polygon"&&x.push(new XF({shape:"polygon",points:f.points}));else if(f.type==="pcb_silkscreen_text"){let m=XVt(e,f.ccw_rotation);a.includes("pinrow")&&f.text.includes("PIN")?x.push(GVt({elm:f,pinLabels:l??s,layer:f.layer,readableRotation:m,anchorAlignment:f.anchor_alignment})):x.push(new JS({anchorAlignment:f.anchor_alignment||"center",text:r,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 lK({route:f.route}));return x};function ZS(r){let e=1/0,a=1/0,s=-1/0,l=-1/0,d=!1;for(let m of r)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),d=!0}else if(m.children.length>0){let D=ZS(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),d=!0)}if(!d)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 ZBe(r){let e=1/0,a=1/0,s=-1/0,l=-1/0;for(let d of r){let x,f,m,D;if(d.type==="schematic_component")x=d.center?.x,f=d.center?.y,m=d.size?.width,D=d.size?.height;else if(d.type==="schematic_box")x=d.x,f=d.y,m=d.width,D=d.height;else if(d.type==="schematic_port")x=d.center?.x,f=d.center?.y,m=.2,D=.2;else if(d.type==="schematic_text")x=d.position?.x,f=d.position?.y,m=(d.text?.length??0)*.1,D=.2;else if(d.type==="schematic_line"){let b=d.x1??0,E=d.y1??0,A=d.x2??0,B=d.y2??0;x=(b+A)/2,f=(E+B)/2,m=Math.abs(A-b),D=Math.abs(B-E)}else d.type==="schematic_rect"&&(x=d.center?.x,f=d.center?.y,m=d.width,D=d.height);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 YVt(r,e){let a=e.x-r.x,s=e.y-r.y;return Math.abs(a)>Math.abs(s)?a>=0?"right":"left":s>=0?"up":"down"}var CBe=r=>{if(r.length<=1)return!0;let e=r.map(d=>{let x=d._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 d=0;d<e.length;d++)for(let x=d+1;x<e.length;x++){let f=e[d],m=e[x];a[d][x]=a[x][d]=!(f.right<m.left||f.left>m.right||f.bottom>m.top||f.top<m.bottom)}let s=new Set,l=d=>{s.add(d);for(let x=0;x<e.length;x++)a[d][x]&&!s.has(x)&&l(x)};return l(0),s.size===e.length},_Be=r=>{if(r.length===0)throw new Error("Cannot get center of empty PCB primitives array");let e=r.map(l=>l._getPcbCircuitJsonBounds().center).filter(Boolean),a=e.reduce((l,d)=>l+d.x,0),s=e.reduce((l,d)=>l+d.y,0);return{x:a/e.length,y:s/e.length}},HVt=v.object({name:v.string().optional(),pinNumber:v.number().optional(),aliases:v.array(v.string()).optional(),layer:v.string().optional(),layers:v.array(v.string()).optional()}),Ni=class extends qn{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);z(this,"source_port_id",null);z(this,"pcb_port_id",null);z(this,"schematic_port_id",null);z(this,"schematicSymbolPortDef",null);z(this,"matchedComponents");z(this,"facingDirection",null);z(this,"originDescription",null);a.originDescription&&(this.originDescription=a.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:HVt}}_isBoardPinoutFromAttributes(){let e=this.parent;if(e?._parsedProps?.pinAttributes){let a=e._parsedProps.pinAttributes;for(let s of this.getNameAndAliases())if(a[s]?.includeInBoardPinout)return!0}}_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(d=>d.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=js(this.parent.computeSchematicGlobalTransform(),Ma(-e.center.x,-e.center.y));return as(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 as(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??[]]))}_getMatchingPinAttributes(){let e=this.parent?._parsedProps?.pinAttributes;if(!e)return[];let a=[];for(let s of this.getNameAndAliases()){let l=e[s];l&&a.push(l)}return a}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(e=>e.includeInBoardPinout===!0)}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(d=>d.isPcbPrimitive);if(s.length===0)return;let l=null;if(s.length===1&&(l=s[0]._getPcbCircuitJsonBounds().center),s.length>1){if(!CBe(s))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${s.map(d=>d.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=_Be(s)}if(l){let d=this.getSubcircuit(),x=this._shouldIncludeInBoardPinout(),f=e.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...x?{is_board_pinout:!0}:{},...l,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=f.pcb_port_id}else{let d=s[0];throw new Error(`${d.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(f=>f.isPcbPrimitive);if(a.length===0)return;let s=null;if(a.length===1&&(s=a[0]._getPcbCircuitJsonBounds().center),a.length>1)try{CBe(a)&&(s=_Be(a))}catch{}if(!s)return;let l=this.getSubcircuit(),d=this._shouldIncludeInBoardPinout(),x=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,...d?{is_board_pinout:!0}:{},...s,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=x.pcb_port_id}doInitialSchematicPortRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer();if(!s||!this._hasSchematicPort())return;let l=s._getGlobalSchematicPositionBeforeLayout(),d=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:d,size:{width:.1,height:.1},label:"obstacle"}),x?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[x.side]:this.facingDirection=YVt(l,d);let m=e.source_port.get(this.source_port_id),D=[];for(let w of m?.port_hints??[])w.match(/^(pin)?\d+$/)||w.match(/^(left|right)/)&&!m?.name.match(/^(left|right)/)||D.push(w);let b;this.parent?.props?.showPinAliases&&D.length>0?b=D.join("/"):D.length>0&&(b=D[0]);let A={type:"schematic_port",schematic_component_id:this.parent?.schematic_component_id,center:d,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};for(let w of this._getMatchingPinAttributes())w.requiresPower&&(A.has_input_arrow=!0),w.providesPower&&(A.has_output_arrow=!0);let B=e.schematic_port.insert(A);this.schematic_port_id=B.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}`}},QBe=r=>{let e=r.find(a=>/^(pin)?\d+$/.test(a));return e?Number.parseInt(e.replace(/^pin/,"")):null};function qF(r,e){let a=QBe(r);if(!a)return null;let l=[...r.filter(d=>d.toString()!==a.toString()&&d!==`pin${a}`),...e?.additionalAliases?.[`pin${a}`]??[]];return new Ni({pinNumber:a,aliases:l})}var WVt=r=>{for(let e of["leftSide","rightSide","topSide","bottomSide"])if(e in r&&typeof r[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r},KVt=r=>{if(WVt(r))return{leftSize:r.leftSide?.pins.length??0,rightSize:r.rightSide?.pins.length??0,topSize:r.topSide?.pins.length??0,bottomSize:r.bottomSide?.pins.length??0};let{leftSize:e=0,rightSize:a=0,topSize:s=0,bottomSize:l=0}=r;return{leftSize:e,rightSize:a,topSize:s,bottomSize:l}};function e9e(r){let e=r;return e.leftSide!==void 0||e.rightSide!==void 0||e.topSide!==void 0||e.bottomSide!==void 0}var JVt=r=>{let e=r.portDistanceFromEdge??.4,a=r.schPortArrangement?KVt(r.schPortArrangement):null,s={left:0,right:0,top:0,bottom:0},l=r.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 d=({side:w,sideIndex:P,truePinIndex:j})=>{if(!r.schPortArrangement||!e9e(r.schPortArrangement))return j+1;let O={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[w],q=r.schPortArrangement?.[`${w}Side`]?.direction??O,ee=r.schPortArrangement?.[`${w}Side`]?.pins,W=P;return q!==O&&(W=ee.length-P-1),YF(ee[W],r.pinLabels)},x=[],f=0,m=0;for(let w=0;w<a.leftSize;w++){let P=d({side:"left",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.topMargin&&(f+=j.topMargin),x.push({trueIndex:m,pinNumber:P,side:"left",distanceFromOrthogonalEdge:f}),j?.bottomMargin&&(f+=j.bottomMargin),w===a.leftSize-1?s.left=f:f+=r.schPinSpacing,m++}f=0;for(let w=0;w<a.bottomSize;w++){let P=d({side:"bottom",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.leftMargin&&(f+=j.leftMargin),x.push({trueIndex:m,pinNumber:P,side:"bottom",distanceFromOrthogonalEdge:f}),j?.rightMargin&&(f+=j.rightMargin),w===a.bottomSize-1?s.bottom=f:f+=r.schPinSpacing,m++}f=0;for(let w=0;w<a.rightSize;w++){let P=d({side:"right",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.bottomMargin&&(f+=j.bottomMargin),x.push({trueIndex:m,pinNumber:P,side:"right",distanceFromOrthogonalEdge:f}),j?.topMargin&&(f+=j.topMargin),w===a.rightSize-1?s.right=f:f+=r.schPinSpacing,m++}f=0;for(let w=0;w<a.topSize;w++){let P=d({side:"top",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.rightMargin&&(f+=j.rightMargin),x.push({trueIndex:m,pinNumber:P,side:"top",distanceFromOrthogonalEdge:f}),j?.leftMargin&&(f+=j.leftMargin),w===a.topSize-1?s.top=f:f+=r.schPinSpacing,m++}let D=r.schWidth;if(D===void 0){D=Math.max(s.top+r.schPinSpacing*2,s.bottom+r.schPinSpacing*2);let w=r.pinLabels?Math.max(...Object.values(r.pinLabels).map(j=>j.length*.1)):0,P=w>0?1.1:0;D=Math.max(D,w+P)}let b=r.schHeight;b||(b=Math.max(s.left+r.schPinSpacing*2,s.right+r.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:j}=w,O=E[j],q=A[j];return{x:O.x+P*q.x,y:O.y+P*q.y,...w}});return{getPortPositionByPinNumber(w){let P=B.find(j=>j.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}},ZVt=(0,t9e.default)("tscircuit:core:footprint"),r9e=class extends qn{get config(){return{componentName:"Footprint",zodProps:CAe}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let r=this.children.filter(E=>E.componentName==="Constraint");if(r.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=r.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 d=new ug,x={};function f(E){return E in x||(x[E]=new rd(E),d.addEditVariable(x[E],Oa.weak)),x[E]}for(let{selector:E,bounds:A}of s){let B=f(`${E}_x`),w=f(`${E}_y`);d.suggestValue(B,A.center.x),d.suggestValue(w,A.center.y)}for(let E of r){let A=E._parsedProps;if("xDist"in A){let{xDist:B,left:w,right:P,edgeToEdge:j,centerToCenter:O}=a(A),q=f(`${w}_x`),ee=f(`${P}_x`),W=l(w)?.bounds,re=l(P)?.bounds;if(O){let L=new Xa(ee,[-1,q]);d.addConstraint(new Vs(L,Ds.Eq,A.xDist,Oa.required))}else if(j){let L=new Xa(ee,-re.width/2,[-1,q],-W.width/2);d.addConstraint(new Vs(L,Ds.Eq,A.xDist,Oa.required))}}else if("yDist"in A){let{yDist:B,top:w,bottom:P,edgeToEdge:j,centerToCenter:O}=A,q=f(`${w}_y`),ee=f(`${P}_y`),W=l(w)?.bounds,re=l(P)?.bounds;if(O){let L=new Xa(q,[-1,ee]);d.addConstraint(new Vs(L,Ds.Eq,A.yDist,Oa.required))}else if(j){let L=new Xa(q,W.height/2,[-1,ee],-re.height/2);d.addConstraint(new Vs(L,Ds.Eq,A.yDist,Oa.required))}}else if("sameY"in A){let{for:B}=A;if(B.length<2)continue;let w=B.map(j=>f(`${j}_y`)),P=new Xa(...w.slice(1));d.addConstraint(new Vs(P,Ds.Eq,w[0],Oa.required))}else if("sameX"in A){let{for:B}=A;if(B.length<2)continue;let w=B.map(j=>f(`${j}_x`)),P=new Xa(...w.slice(1));d.addConstraint(new Vs(P,Ds.Eq,w[0],Oa.required))}}d.updateVariables(),ZVt.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`),j=w.value()-A/2,O=w.value()+A/2,q=P.value()+B/2,ee=P.value()-B/2;m.left=Math.min(m.left,j),m.right=Math.max(m.right,O),m.top=Math.max(m.top,q),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})}}},XW=v.union([v.number(),v.string()]),ABe=v.object({x:XW,y:XW,z:XW}),n9e=class extends qn{get config(){return{componentName:"CadModel",zodProps:XAe}}doInitialCadModelRender(){let r=this._findParentWithPcbComponent();if(!r||!r.pcb_component_id)return;let{db:e}=this.root,{boardThickness:a=0}=this.root?._getBoard()??{},s=r._getPcbCircuitJsonBounds(),l=e.pcb_component.get(r.pcb_component_id),d=this._parsedProps;if(!d||typeof d.modelUrl!="string")return;let x=ABe.parse({x:0,y:0,z:0});if(typeof d.rotationOffset=="number")x.z=Number(d.rotationOffset);else if(typeof d.rotationOffset=="object"){let A=ABe.parse(d.rotationOffset);x.x=Number(A.x),x.y=Number(A.y),x.z=Number(A.z)}let f=l5.parse({x:d.pcbX??0,y:d.pcbY??0,z:d.pcbZ??0,...typeof d.positionOffset=="object"?d.positionOffset:{}}),m=r.props.layer==="bottom"?"bottom":"top",D=new URL(d.modelUrl).pathname.split(".").pop()?.toLowerCase(),b={};D==="stl"?b.model_stl_url=this._addCachebustToModelUrl(d.modelUrl):D==="obj"?b.model_obj_url=this._addCachebustToModelUrl(d.modelUrl):D==="gltf"?b.model_gltf_url=this._addCachebustToModelUrl(d.modelUrl):D==="glb"?b.model_glb_url=this._addCachebustToModelUrl(d.modelUrl):D==="step"||D==="stp"?b.model_step_url=this._addCachebustToModelUrl(d.modelUrl):D==="wrl"||D==="vrml"?b.model_wrl_url=this._addCachebustToModelUrl(d.modelUrl):b.model_stl_url=this._addCachebustToModelUrl(d.modelUrl);let E=e.cad_component.insert({position:{x:s.center.x+Number(f.x),y:s.center.y+Number(f.y),z:(m==="bottom"?-a/2:a/2)+Number(f.z)},rotation:{x:Number(x.x),y:(m==="top"?0:180)+Number(x.y),z:m==="bottom"?-((l?.rotation??0)+Number(x.z))+180:(l?.rotation??0)+Number(x.z)},pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,model_unit_to_mm_scale_factor:typeof d.modelUnitToMmScale=="number"?d.modelUnitToMmScale:void 0,...b});this.cad_component_id=E.cad_component_id}_findParentWithPcbComponent(){let r=this.parent;for(;r&&!r.pcb_component_id;)r=r.parent;return r}_addCachebustToModelUrl(r){if(!r||!r.includes("modelcdn.tscircuit.com"))return r;let e=this.root?.getClientOrigin()??"";return`${r}${r.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(e)}`}},a9e=class extends qn{constructor(){super(...arguments);z(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:GAe}}},QVt=(r,e)=>{if(!r)return;let a={};for(let[s,l]of Object.entries(r)){let d=YF(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${d}`]={...a[`pin${d}`],...x}}return a},RBe=class{constructor({input:r}){z(this,"input");this.input=r}solveAndMapToTraces(){let r=[];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}]};r.push(l)}return r}},eGt=r=>{let e=Math.min(...r.map(d=>d.center.x)),a=Math.max(...r.map(d=>d.center.x)),s=Math.min(...r.map(d=>d.center.y)),l=Math.max(...r.map(d=>d.center.y));return{minX:e,maxX:a,minY:s,maxY:l}},SBe=["top","bottom","inner1","inner2"],US=(r,e=[])=>{let a=[];if(e.length===0){let f=r[0].layers;for(let m of f)a.push(...US(r.slice(1),[m]));return a}if(r.length===0)return[];let s=r[0],l=s.via||s.optional_via,d=e[e.length-1];if(r.length===1){let f=s;return f.layers&&l?f.layers.map(m=>({layer_path:[...e,m]})):f.layers?.includes(d)?[{layer_path:[...e,d]}]:[]}if(!l)return s.layers&&!s.layers.includes(d)?[]:US(r.slice(1),e.concat([d]));let x=(s.optional_via?SBe:SBe.filter(f=>f!==d)).filter(f=>!s.layers||s.layers?.includes(f));for(let f of x)a.push(...US(r.slice(1),e.concat(f)));return a};function BBe(r){let e={x:r.to.x-r.from.x,y:r.to.y-r.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 qg(r,e){return Math.hypot(r.x-e.x,r.y-e.y)}var tGt=r=>{if(r.length===1)return r[0];if(r.some(m=>m.length===0))throw new Error("Cannot merge routes with zero length");let e=[],a=r[0][0],s=r[0][r[0].length-1],l=r[1][0],d=r[1][r[1].length-1],x=Math.min(qg(a,l),qg(a,d)),f=Math.min(qg(s,l),qg(s,d));x<f?e.push(...r[0].reverse()):e.push(...r[0]);for(let m=1;m<r.length;m++){let D=e[e.length-1],b=r[m],E=b[0],A=b[b.length-1],B=qg(D,E),w=qg(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},rGt=(r,e)=>{let a="_getGlobalPcbPositionBeforeLayout"in r?r._getGlobalPcbPositionBeforeLayout():r,s="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((a.x-s.x)**2+(a.y-s.y)**2)};function nGt(r,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 d=rGt(r,l);d<s&&(a=l,s=d)}return a}var aGt=(r,e)=>{let a=0;a+=r.length??0,a+=e.filter(s=>s.is_crossing).length;for(let s=1;s<e.length;s++){let l=e[s-1],d=e[s],x=Math.abs(l.from.x-l.to.x)<.01,f=Math.abs(d.from.x-d.to.x)<.01;x!==f&&a++}return a},HF=r=>({up:"bottom",down:"top",left:"right",right:"left"})[r]??null,ZW=({firstEdge:r,firstEdgePort:e,firstDominantDirection:a,lastEdge:s,lastEdgePort:l,lastDominantDirection:d})=>{if(r&&e)return ZW({lastEdge:{from:r.to,to:r.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};d==="left"||d==="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=>wi(f.from,f.to)>.01),x};function sGt(r){try{return[r(),null]}catch(e){return[null,e]}}var iGt=(r,{db:e})=>{let a=r.map(s=>{let l=e.source_port.get(s.source_port_id);if(!l?.source_component_id)return null;let d=e.source_component.get(l.source_component_id);return d?.ftype==="simple_capacitor"?d.max_decoupling_trace_length:null}).filter(s=>s!==null);if(a.length!==0)return Math.min(...a)};function oGt({ports:r,nets:e}){if(r.length>=2)return`${r[0]?.selector} to ${r[1]?.selector}`;if(r.length===1&&e.length===1)return`${r[0]?.selector} to net.${e[0]._parsedProps.name}`}var uGt=(r,{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,j=E[B].y,O=E[w].x,q=E[w].y;j>b.y!=q>b.y&&b.x<(O-P)*(b.y-j)/(q-j)+P&&(A=!A)}return A};return r.some(b=>!D(b,m))}let s=a.width,l=a.height,d=a.center.x,x=a.center.y;return r.some(m=>m.x<d-s/2||m.y<x-l/2||m.x>d+s/2||m.y>x+l/2)},wBe=(r,e)=>Math.abs(r-e)<1e-4,cGt=(r,e,{viaDiameter:a=.5}={})=>{let s=[];for(let l=0;l<r.length-1;l++){let[d,x]=[r[l],r[l+1]],f=l-1>=0?r[l-1]:null,m=wBe(d.y,x.y),D=wBe(d.x,x.x);if(!m&&!D)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${d.x}, ${d.y}), end: (${x.x}, ${x.y})`);let b={type:"rect",layers:[d.layer],center:{x:(d.x+x.x)/2,y:(d.y+x.y)/2},width:m?Math.abs(d.x-x.x):.1,height:D?Math.abs(d.y-x.y):.1,connectedTo:[e]};if(s.push(b),f&&f.layer===d.layer&&d.layer!==x.layer){let E={type:"rect",layers:[d.layer,x.layer],center:{x:d.x,y:d.y},connectedTo:[e],width:a,height:a};s.push(E)}}return s};function s9e(r,e=4){let{center:a,width:s,height:l,rotation:d}=r,x=[],f=d*Math.PI/180,m=Math.cos(f),D=Math.sin(f),b=(d%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,j=-w*D,O=A*1.1,q=Math.abs(l*m)+Math.abs(A*D);x.push({center:{x:a.x+P,y:a.y+j},width:O,height:q})}}else{let A=l/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*D,j=w*m,O=Math.abs(s*m)+Math.abs(A*D),q=A*1.1;x.push({center:{x:a.x+P,y:a.y+j},width:O,height:q})}}return x}function lGt(r,e={}){if(r.length<3)return[];let{rectHeight:a=.1}=e,s=[],l=r.map(f=>f.y),d=Math.min(...l),x=Math.max(...l);for(let f=d;f<x;f+=a){let m=f+a/2,D=[];for(let b=0;b<r.length;b++){let E=r[b],A=r[(b+1)%r.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 dGt(r,e={}){let{center:a,radius:s}=r,{rectHeight:l=.1}=e,d=[],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&&d.push({center:{x:a.x,y:m},width:b*2,height:l})}return d}var nx=["top","inner1","inner2","bottom"],pK=(r,e)=>{let a=l=>e?l.concat(l.map(d=>e?.getNetConnectedToId(d)).filter(Boolean)):l,s=[];for(let l of r)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 d={center:{x:l.x,y:l.y},width:l.width,height:l.height,rotation:l.ccw_rotation},x=s9e(d);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:nx,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.shape==="circle"){let d=dGt({center:l.center,radius:l.radius},{rectHeight:.6});for(let x of d)s.push({type:"rect",layers:nx,center:x.center,width:x.width,height:x.height,connectedTo:[]})}else if(l.shape==="polygon"){let d=lGt(l.points,{rectHeight:.6});for(let x of d)s.push({type:"rect",layers:nx,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:nx,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:nx,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:nx,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:nx,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:nx,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 d=cGt(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(...d)}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},sx=({anchor_position:r,anchor_side:e,text:a,font_size:s=.18})=>{let l=.1*(s/.18),d=a.length*l,x=s,f={...r};switch(e){case"right":f.x-=d/2;break;case"left":f.x+=d/2;break;case"top":f.y-=x/2;break;case"bottom":f.y+=x/2;break}return f},xK=({db:r,source_trace_id:e,sameNetOnly:a,differentNetOnly:s})=>{!a&&!s&&(s=!0);let l=r.source_trace.get(e),d=[];for(let x of r.schematic_trace.list()){if(x.source_trace_id===e)continue;let m=r.source_trace.get(x.source_trace_id)?.subcircuit_connectivity_map_key===l.subcircuit_connectivity_map_key;s&&m||a&&!m||d.push(x)}return d},pGt=({edges:r,otherEdges:e})=>{let a=[...r];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],d=Math.abs(l.from.x-l.to.x)<.01?"vertical":l.from.y===l.to.y?"horizontal":"not-orthogonal";if(d==="not-orthogonal")continue;let x=[];for(let P of e){let j=P.from.x===P.to.x?"vertical":P.from.y===P.to.y?"horizontal":"not-orthogonal";if(j==="not-orthogonal"||d===j)continue;if(zp([l.from,l.to],[P.from,P.to],{lineThickness:.01})){let q=d==="vertical"?l.from.x:P.from.x,ee=d==="vertical"?P.from.y:l.from.y,W={x:q,y:ee};x.push({otherEdge:P,crossingPoint:W,distanceFromEdgeFrom:wi(l.from,W)})}}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=F5(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=wi(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},QW=.001,Ug=(r,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),d=Math.max(e.from.y,e.to.y);return r.x>=a&&r.x<=s&&r.y>=l&&r.y<=d},TBe=r=>{let e=Math.abs(r.from.x-r.to.x)<QW,a=Math.abs(r.from.y-r.to.y)<QW;return e?"vertical":a?"horizontal":"diagonal"},xGt=(r,e)=>{let a=TBe(r),s=TBe(e);if(a===s)return null;if(a==="vertical"&&s==="horizontal"||a==="horizontal"&&s==="vertical"){let E=a==="vertical"?r:e,A=a==="horizontal"?r:e,B=E.from.x,w=A.from.y,P={x:B,y:w};return Ug(P,r)&&Ug(P,e)?P:null}if(a==="vertical"||s==="vertical"){let E=a==="vertical"?r:e,A=a==="vertical"?e:r,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,j=w*B+P,O={x:B,y:j};return Ug(O,r)&&Ug(O,e)?O:null}let l=(r.to.y-r.from.y)/(r.to.x-r.from.x),d=r.from.y-l*r.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)<QW)return null;let m=(f-d)/(l-x),D=l*m+d,b={x:m,y:D};return Ug(b,r)&&Ug(b,e)?b:null},fGt=({edges:r,db:e,source_trace_id:a})=>{let s=xK({db:e,source_trace_id:a,sameNetOnly:!0}).flatMap(d=>d.edges),l=new Map;for(let d of r)for(let x of s){let f=xGt(d,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 hGt(r,e={}){let{minX:a,maxX:s,minY:l,maxY:d}=r,x=e.padding??1;if(!isFinite(a)||!isFinite(s)||!isFinite(l)||!isFinite(d))return[];let f=a-x,m=s+x,D=d+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 mGt=r=>{let e=r.root.db,a=r._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?E5(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 d=ZBe(e.toArray());return l.push(...hGt(d,{padding:1})),l},gGt=({edges:r,db:e,source_trace_id:a})=>{let s=e.source_trace.get(a),l=xK({db:e,source_trace_id:a,differentNetOnly:!0}).flatMap(x=>x.edges),d=x=>{let{from:f,to:m}=x;return f.x===m.x?"vertical":"horizontal"};for(let x of r){let f=d(x),m=()=>l.find(b=>d(b)===f&&zp([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()}},eK=r=>{switch(r){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},DGt=F4e.version??"unknown",UF=class extends Error{constructor(r){super(`${r} (capacity-autorouter@${DGt})`),this.name="AutorouterError"}},YS=class extends Error{constructor(r){super(r.message),this.errorData=r,this.name="TraceConnectionError"}},yGt=r=>{if(r.root?._featureMspSchematicTraceRouting||r._couldNotFindPort||r.root?.schematicDisabled)return;let{db:e}=r.root,{_parsedProps:a,parent:s}=r;if(!s)throw new Error("Trace has no parent");let l,d;try{let Ne=r._findConnectedPorts();l=Ne.allPortsFound,d=Ne.portsWithSelectors??[]}catch(Ne){if(Ne instanceof YS){e.source_trace_not_connected_error.insert({...Ne.errorData,error_type:"source_trace_not_connected_error"});return}throw Ne}let{netsWithSelectors:x}=r._findConnectedNets();if(!l)return;let m=d.map(Ne=>Ne.port.schematic_port_id).sort().join(","),D=r.root?._getBoard();if(D?._connectedSchematicPortPairs&&D._connectedSchematicPortPairs.has(m))return;let b={name:r.source_trace_id,pointsToConnect:[]},E=mGt(r),A=d.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:Ge,position:tt}=A[0],He=r.getSubcircuit().selectAll("netlabel").find(ct=>{let ot=ct._parsedProps.connection??ct._parsedProps.connectsTo;return ot?Array.isArray(ot)?ot.some(It=>r.getSubcircuit().selectOne(It,{port:!0})===Ge):r.getSubcircuit().selectOne(ot,{port:!0})===Ge:!1});if(!He){let ct=e.schematic_net_label.getWhere({source_trace_id:r.source_trace_id});ct&&(He=ct)}if(He){let ct="_getGlobalSchematicPositionBeforeLayout"in He?He._getGlobalSchematicPositionBeforeLayout():He.anchor_position,ot=[];tt.x===ct.x||tt.y===ct.y?ot.push({from:tt,to:ct}):(ot.push({from:tt,to:{x:ct.x,y:tt.y}}),ot.push({from:{x:ct.x,y:tt.y},to:ct}));let Ut=e.schematic_trace.insert({source_trace_id:r.source_trace_id,edges:ot,junctions:[],subcircuit_connectivity_map_key:r.subcircuit_connectivity_map_key??void 0});r.schematic_trace_id=Ut.schematic_trace_id;return}if(r.props.schDisplayLabel){let ct=HF(Ge.facingDirection)??"bottom";e.schematic_net_label.insert({text:r.props.schDisplayLabel,source_net_id:Ne.source_net_id,anchor_position:tt,center:sx({anchor_position:tt,anchor_side:ct,text:r.props.schDisplayLabel}),anchor_side:ct});return}let $t=HF(Ge.facingDirection)??"bottom",bt=e.schematic_net_label.insert({text:Ne._parsedProps.name,source_net_id:Ne.source_net_id,anchor_position:tt,center:sx({anchor_position:tt,anchor_side:$t,text:Ne._parsedProps.name}),anchor_side:$t});return}if(r.props.schDisplayLabel&&("from"in r.props&&"to"in r.props||"path"in r.props)){r._doInitialSchematicTraceRenderWithDisplayLabel();return}if(A.length<2)return;let P=(()=>{let Ne=[];for(let tt=0;tt<A.length-1;tt++){let He=A[tt],$t=A[tt+1],bt=dg({x:He.position.x,y:He.position.y,facingDirection:eK(He.facingDirection)},{x:$t.position.x,y:$t.position.y,facingDirection:eK($t.facingDirection)});for(let ct=0;ct<bt.length-1;ct++)Ne.push({from:bt[ct],to:bt[ct+1]})}let Ge=(tt,He)=>{let $t=He.width/2,bt=He.height/2,ct=He.center.x-$t,ot=He.center.x+$t,Ut=He.center.y-bt,It=He.center.y+bt,tr=vt=>vt.x>=ct&&vt.x<=ot&&vt.y>=Ut&&vt.y<=It;return tr(tt.from)||tr(tt.to)?!0:[[{x:ct,y:Ut},{x:ot,y:Ut}],[{x:ot,y:Ut},{x:ot,y:It}],[{x:ot,y:It},{x:ct,y:It}],[{x:ct,y:It},{x:ct,y:Ut}]].some(vt=>zp([tt.from,tt.to],vt,{lineThickness:0}))};for(let tt of Ne)for(let He of E)if(Ge(tt,He))return null;return Ne})();P&&P.length===0&&(P=null),b.pointsToConnect=A.map(({position:Ne})=>({...Ne,layer:"top"}));let j=eGt(E),O=2,q={minTraceWidth:.1,obstacles:E,connections:[b],bounds:{minX:j.minX-O,maxX:j.maxX+O,minY:j.minY-O,maxY:j.maxY+O},layerCount:1},ee=o5,W=!1;if(r.getSubcircuit().props._schDirectLineRoutingEnabled&&(ee=RBe,W=!0),!P){let Ge=new ee({input:q,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(Ge.length===0){if(r._isSymbolToChipConnection()||r._isSymbolToSymbolConnection()||r._isChipToChipConnection()){r._doInitialSchematicTraceRenderWithDisplayLabel();return}Ge=new RBe({input:q}).solveAndMapToTraces(),W=!0}let[{route:tt}]=Ge;P=[];for(let He=0;He<tt.length-1;He++)P.push({from:tt[He],to:tt[He+1]})}let re=r.source_trace_id,L=[];if(!W){gGt({edges:P,db:e,source_trace_id:re});let Ne=xK({db:e,source_trace_id:re,differentNetOnly:!0}).flatMap(Ge=>Ge.edges);P=pGt({edges:P,otherEdges:Ne}),L=fGt({edges:P,db:e,source_trace_id:r.source_trace_id})}if(!P||P.length===0)return;let K=P[P.length-1],U=A[A.length-1],J=BBe(K);P.push(...ZW({lastEdge:K,lastEdgePort:U,lastDominantDirection:J}));let Q=P[0],de=A[0],oe=BBe(Q);if(P.unshift(...ZW({firstEdge:Q,firstEdgePort:de,firstDominantDirection:oe})),!r.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(r.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&aGt(L,P)>=5&&(r._isSymbolToChipConnection()||r._isSymbolToSymbolConnection()||r._isChipToChipConnection())){r._doInitialSchematicTraceRenderWithDisplayLabel();return}let Me=e.schematic_trace.insert({source_trace_id:r.source_trace_id,edges:P,junctions:L,subcircuit_connectivity_map_key:r.subcircuit_connectivity_map_key??void 0});r.schematic_trace_id=Me.schematic_trace_id;for(let{port:Ne}of d)Ne.schematic_port_id&&e.schematic_port.update(Ne.schematic_port_id,{is_connected:!0});D?._connectedSchematicPortPairs&&D._connectedSchematicPortPairs.add(m)};function i9e(r){let e=0;for(let a=0;a<r.length;a++){let s=r[a];if(s.route_type==="wire"){let l=r[a+1];if(l){let d=l.x-s.x,x=l.y-s.y;e+=Math.sqrt(d*d+x*x)}}else s.route_type==="via"&&(e+=1.6)}return e}var LS=r=>({...r._getGlobalPcbPositionAfterLayout(),layers:r.getAvailablePcbLayers()}),bGt=!1;function FGt(r){if(r.root?.pcbDisabled)return;let{db:e}=r.root,{_parsedProps:a,parent:s}=r,l=r.getSubcircuit();if(!s)throw new Error("Trace has no parent");if(l._parsedProps.routingDisabled)return;let d=l._parsedProps.pcbRouteCache?.pcbTraces;if(d){let J=e.pcb_trace.insert({route:d.flatMap(Q=>Q.route),source_trace_id:r.source_trace_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0});r.pcb_trace_id=J.pcb_trace_id;return}if(a.pcbPath&&a.pcbPath.length>0||!l._shouldUseTraceByTraceRouting())return;let{allPortsFound:x,ports:f}=r._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:r.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, ${r} wasn't routed. Missing ports: ${D.map(J=>J.getString()).join(", ")}`,pcb_trace_id:r.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:D.map(J=>J.pcb_port_id).filter(Boolean)});return}let b=r._findConnectedNets().netsWithSelectors;if(f.length===0&&b.length===2){r.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(Me=>Me!==J);if(de.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let oe=nGt(J,de);m.push(oe),f.push(oe)}else if(f.length>1&&b.length>=1){r.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=(r._parsedProps.pcbRouteHints??[]).concat(E.flatMap(J=>J.getPcbRouteHints()));if(f.length>2){r.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(r.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=[LS(f[0]),LS(f[1])]:P=[LS(f[0]),...A,LS(f[1])];let j=US(P);if(bGt&&j.length===0){r.renderError(`Could not find a common layer (using hints) for trace ${r.getString()}`);return}let O=eu(r.root.db.toArray()),[q,ee]=sGt(()=>pK(r.root.db.toArray()));if(ee){r.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:r.pcb_trace_id,message:`Error getting obstacles for autorouting: ${ee.message}`,source_trace_id:r.source_trace_id,center:{x:0,y:0},pcb_port_ids:f.map(J=>J.pcb_port_id),pcb_trace_id:r.pcb_trace_id,pcb_component_ids:[]});return}for(let J of q)if(J.connectedTo.length>0){let de=O.getNetConnectedToId(J.connectedTo[0]);de&&J.connectedTo.push(de)}let W=[];if(j.length===0)W=P;else{let J=j[0].layer_path;W=P.map((Q,de)=>Q.via?{...Q,via_to_layer:J[de]}:{...Q,layers:[J[de]]})}W[0].pcb_port_id=f[0].pcb_port_id,W[W.length-1].pcb_port_id=f[1].pcb_port_id;let re=[];for(let[J,Q]of JBe(W)){let de="via_to_layer"in J?J.via_to_layer:null,oe=2,Me="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",Ge="pcb_port_id"in J?J.pcb_port_id:null,tt="pcb_port_id"in Q?Q.pcb_port_id:null,He=r.getSubcircuit()._parsedProps.minTraceWidth??.16,$t=new o5({OBSTACLE_MARGIN:He*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Ge&&tt),connMap:O,input:{obstacles:q,minTraceWidth:He,connections:[{name:r.source_trace_id,pointsToConnect:[{...J,layer:Me,pcb_port_id:Ge},{...Q,layer:Ne,pcb_port_id:tt}]}],layerCount:r.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(J.x,Q.x)-oe,maxX:Math.max(J.x,Q.x)+oe,minY:Math.min(J.y,Q.y)-oe,maxY:Math.max(J.y,Q.y)+oe}}}),bt=null;try{bt=$t.solveAndMapToTraces()}catch(Ut){r.renderError({type:"pcb_trace_error",pcb_trace_error_id:r.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${Ut.message}`,source_trace_id:r.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:r.pcb_trace_id,pcb_component_ids:f.map(It=>It.pcb_component_id)})}if(!bt)return;if(bt.length===0){r.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:r.pcb_trace_id,message:`Could not find a route for ${r}`,source_trace_id:r.source_trace_id,center:{x:(J.x+Q.x)/2,y:(J.y+Q.y)/2},pcb_port_ids:f.map(Ut=>Ut.pcb_port_id),pcb_trace_id:r.pcb_trace_id,pcb_component_ids:f.map(Ut=>Ut.pcb_component_id)});return}let[ct]=bt;de&&(ct.route=ct.route.map(Ut=>(Ut.route_type==="wire"&&!Ut.layer&&(Ut.layer=de),Ut))),Ge&&ct.route[0].route_type==="wire"&&(ct.route[0].start_pcb_port_id=Ge);let ot=ct.route[ct.route.length-1];tt&&ot.route_type==="wire"&&(ot.end_pcb_port_id=tt),re.push(ct.route)}let L=tGt(re),K=i9e(L),U=e.pcb_trace.insert({route:L,source_trace_id:r.source_trace_id,subcircuit_id:r.getSubcircuit()?.subcircuit_id,trace_length:K});r._portsRoutedOnPcb=f,r.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});r._insertErrorIfTraceIsOutsideBoard(L,f)}function EGt(r){if(r.root?.pcbDisabled)return;let{db:e}=r.root,{_parsedProps:a}=r,s=r.getSubcircuit();if(!a.pcbPath||a.pcbPath.length===0)return;let{allPortsFound:l,ports:d,portsWithSelectors:x}=r._findConnectedPorts();if(!l)return;let f=[];for(let q of d)q._hasMatchedPcbPrimitive()||f.push(q);if(f.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:r.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, ${r} wasn't routed. Missing ports: ${f.map(q=>q.getString()).join(", ")}`,pcb_trace_id:r.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:f.map(q=>q.pcb_port_id).filter(Boolean)});return}let m;a.pcbPathRelativeTo&&(m=x.find(q=>q.selector===a.pcbPathRelativeTo)?.port,m||(m=r.getSubcircuit().selectOne(a.pcbPathRelativeTo))),m||(m=d[0]);let D=d.find(q=>q!==m)??d[1],b=m.getAvailablePcbLayers()[0]||"top",E=a.thickness??r.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?.()||Si();for(let q of a.pcbPath){let ee=as(P,{x:q.x,y:q.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 j=i9e(w),O=e.pcb_trace.insert({route:w,source_trace_id:r.source_trace_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0,trace_length:j});r._portsRoutedOnPcb=d,r.pcb_trace_id=O.pcb_trace_id,r._insertErrorIfTraceIsOutsideBoard(w,d)}function vGt(r){if(r.root?.schematicDisabled)return;let{db:e}=r.root,{_parsedProps:a,parent:s}=r;if(!s)throw new Error("Trace has no parent");let{allPortsFound:l,portsWithSelectors:d}=r._findConnectedPorts();if(!l)return;let x=d.map(({port:W})=>({port:W,position:W._getGlobalSchematicPositionAfterLayout(),schematic_port_id:W.schematic_port_id,facingDirection:W.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 r.props){if(r.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[f,m]=r.props.path}else{if(!("from"in r.props&&"to"in r.props))throw new Error("Missing 'from' or 'to' properties in props.");f=r.props.from,m=r.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(W=>W.source_net_id===b.source_port_id),w=e.schematic_net_label.list().find(W=>W.source_net_id===A.source_port_id),[P,j]=d.map(({port:W})=>W),q=P.parent?.config.shouldRenderAsSchematicBox?`${P?.parent?.props.name}_${P?.props.name}`:`${j?.parent?.props.name}_${j?.props.name}`,ee=r.props.schDisplayLabel??q;if(B&&B.text!==ee&&(B.text=`${ee} / ${B.text}`),w&&w?.text!==ee&&(w.text=`${ee} / ${w.text}`),!w){let W=HF(A.facingDirection)??"bottom";e.schematic_net_label.insert({text:r.props.schDisplayLabel??q,source_net_id:A.source_port_id,anchor_position:E,center:sx({anchor_position:E,anchor_side:W,text:r.props.schDisplayLabel??q}),anchor_side:W})}if(!B){let W=HF(b.facingDirection)??"bottom";e.schematic_net_label.insert({text:r.props.schDisplayLabel??q,source_net_id:b.source_port_id,anchor_position:D,center:sx({anchor_position:D,anchor_side:W,text:r.props.schDisplayLabel??q}),anchor_side:W})}}function CGt(r){let{_parsedProps:e,parent:a}=r;if(!a)throw new Error("Trace has no parent");let l=r.getTracePortPathSelectors().map(d=>({selector:d,port:r.getSubcircuit().selectOne(d,{type:"port"})??null}));for(let{selector:d,port:x}of l)if(!x){let f,m,D=d.lastIndexOf(".");if(D!==-1&&D>d.lastIndexOf(" "))f=d.slice(0,D),m=d.slice(D+1);else{let W=d.match(/^(.*[ >])?([^ >]+)$/);f=W?.[1]?.trim()??"",m=W?.[2]??d}let b=f?r.getSubcircuit().selectOne(f):null;if(!b&&f&&!/[.#\[]/.test(f)&&(b=r.getSubcircuit().selectOne(`.${f}`)),!b){let W=f?`Could not find port for selector "${d}". Component "${f}" not found`:`Could not find port for selector "${d}"`,re=r.getSubcircuit(),L=re.getGroup();throw new YS({error_type:"source_trace_not_connected_error",message:W,subcircuit_id:re.subcircuit_id??void 0,source_group_id:L?.source_group_id??void 0,source_trace_id:r.source_trace_id??void 0,selectors_not_found:[d]})}let E=b.children.filter(W=>W.componentName==="Port"),A=m.includes(".")?m.split(".").pop()??"":m,B=E.flatMap(W=>W.getNameAndAliases()),w=B.some(W=>!/^(pin\d+|\d+)$/.test(W)),P=Array.from(new Set(B)).join(", "),j;E.length===0?j="It has no ports":w?j=`It has [${P}]`:j=`It has ${E.length} pins and no pinLabels (consider adding pinLabels)`;let O=`Could not find port for selector "${d}". Component "${b.props.name??f}" found, but does not have pin "${A}". ${j}`,q=r.getSubcircuit(),ee=q.getGroup();throw new YS({error_type:"source_trace_not_connected_error",message:O,subcircuit_id:q.subcircuit_id??void 0,source_group_id:ee?.source_group_id??void 0,source_trace_id:r.source_trace_id??void 0,selectors_not_found:[d]})}return l.some(d=>!d.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:l,ports:l.map(({port:d})=>d)}}var qc=class extends qn{constructor(e){super(e);z(this,"source_trace_id",null);z(this,"pcb_trace_id",null);z(this,"schematic_trace_id",null);z(this,"_portsRoutedOnPcb");z(this,"subcircuit_connectivity_map_key",null);z(this,"_traceConnectionHash",null);z(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}get config(){return{zodProps:vAe,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 CGt(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 d=l._findConnectedNets().nets,x=l._findConnectedPorts().ports??[];return d.some(f=>a.includes(f))||x.some(f=>s.includes(f))})}_isExplicitlyConnectedToPort(e){let{allPortsFound:a,portsWithSelectors:s}=this._findConnectedPorts();return a?s.map(d=>d.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){uK(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();return!e||!a?null:[...a].sort((d,x)=>(d.pcb_port_id||"").localeCompare(x.pcb_port_id||"")).map(d=>d.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,d;try{let E=this._findConnectedPorts();l=E.allPortsFound,d=E.portsWithSelectors??[]}catch(E){if(E instanceof YS){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=oGt({ports:d,nets:m}),b=e.source_trace.insert({connected_source_port_ids:d.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:iGt(d.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;uGt(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(d=>d.pcb_port_id)})}doInitialPcbManualTraceRender(){EGt(this)}doInitialPcbTraceRender(){FGt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){vGt(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 d=s.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return d&&!x||!d&&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 d=!s.parent.config.shouldRenderAsSchematicBox,x=!l.parent.config.shouldRenderAsSchematicBox;return d&&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 d=s.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return d&&x}doInitialSchematicTraceRender(){yGt(this)}},_Gt=r=>{let{db:e}=r.root;if(r.pcb_component_id){let a=e.pcb_component.get(r.pcb_component_id);return a?{width:a.width,height:a.height}:null}if(r.pcb_group_id){let a=e.pcb_group.get(r.pcb_group_id);return a?{width:a.width,height:a.height}:null}return null},AGt=(r,e)=>{let{db:a}=r.root,s=a.toArray();if(r.pcb_component_id){C5(s,r.pcb_component_id,e);return}if(r.source_group_id){_5(s,r.source_group_id,e);return}throw new Error(`Cannot reposition component ${r.getString()}: no pcb_component_id or source_group_id`)},RGt=r=>{let{db:e}=r.root;if(!r.source_component_id)return;let a=r.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 d=r._getInternallyConnectedPins();for(let x of d)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&&SGt(r,x)&&(l.has(x.source_port_id)||e.source_pin_missing_trace_warning.insert({message:`Port ${x.getNameAndAliases()[0]} on ${r.props.name} is missing a trace`,source_component_id:r.source_component_id,source_port_id:x.source_port_id,subcircuit_id:r.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},SGt=(r,e)=>{if(r.config.componentName==="Chip"){let a=r.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 BGt(r){let e=r.font_size,a=r.text.length*e*.6,s=e,l=r.anchor_alignment||"center",d=r.anchor_position.x,x=r.anchor_position.y;switch(l){case"top_left":d=r.anchor_position.x+a/2,x=r.anchor_position.y+s/2;break;case"top_center":d=r.anchor_position.x,x=r.anchor_position.y+s/2;break;case"top_right":d=r.anchor_position.x-a/2,x=r.anchor_position.y+s/2;break;case"center_left":d=r.anchor_position.x+a/2,x=r.anchor_position.y;break;case"center":d=r.anchor_position.x,x=r.anchor_position.y;break;case"center_right":d=r.anchor_position.x-a/2,x=r.anchor_position.y;break;case"bottom_left":d=r.anchor_position.x+a/2,x=r.anchor_position.y-s/2;break;case"bottom_center":d=r.anchor_position.x,x=r.anchor_position.y-s/2;break;case"bottom_right":d=r.anchor_position.x-a/2,x=r.anchor_position.y-s/2;break;default:d=r.anchor_position.x,x=r.anchor_position.y;break}return{x:d-a/2,y:x-s/2,width:a,height:s}}function wGt(r){if(!r._adjustSilkscreenTextAutomatically||r.root?.pcbDisabled||!r.pcb_component_id)return;let{db:e}=r.root,s=r._getPcbCircuitJsonBounds().center,l=e.pcb_silkscreen_text.list({pcb_component_id:r.pcb_component_id}).filter(m=>m.text===r.name);if(l.length===0)return;let f=r.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(m=>m!==r&&m.pcb_component_id).map(m=>{let D=m._getPcbCircuitJsonBounds(),b={center:D.center,width:D.width,height:D.height};return td(b)});for(let m of l){let D=m.anchor_position,b=BGt(m),E={center:{x:b.x+b.width/2,y:b.y+b.height/2},width:b.width,height:b.height},A=td(E);if(!f.some(ee=>Yb(A,ee)))continue;let w=2*s.x-D.x,P=2*s.y-D.y,j={center:{x:w,y:P},width:b.width,height:b.height},O=td(j);f.some(ee=>Yb(O,ee))||e.pcb_silkscreen_text.update(m.pcb_silkscreen_text_id,{anchor_position:{x:w,y:P}})}}function TGt(r){if(!r)return{validPinLabels:r,invalidPinLabelsMessages:[]};let e={},a=[];for(let[s,l]of Object.entries(r)){let d=Array.isArray(l)?l.slice():[l],x=[];for(let f of d)PGt(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 PGt(r,e){try{let a={name:"test",footprint:"test",pinLabels:{[r]:e}};return og.safeParse(a).success}catch{return!1}}var HS=r=>r.startsWith("http://")||r.startsWith("https://"),rK=r=>{if(HS(r))return null;let e=r.indexOf(":");if(e<=0)return null;let a=r.slice(0,e),s=r.slice(e+1);return!a||!s?null:{footprintLib:a,footprintName:s}};function IGt(r,e){let{footprint:a}=r.props;if(a??(a=r._getImpliedFootprintString?.()),!a)return;let{pcbRotation:s,pinLabels:l,pcbPinLabels:d}=r.props;if(typeof a=="string"&&HS(a)){if(r._hasStartedFootprintUrlLoad)return;r._hasStartedFootprintUrlLoad=!0;let x=a;e("load-footprint-url",async()=>{try{let f=await fetch(x);if(!f.ok)throw new Error(`Failed to fetch footprint: ${f.status}`);let m=await f.json(),D=qS({componentName:r.name,componentRotation:s,footprint:x,pinLabels:l,pcbPinLabels:d},m);r.addAll(D),r._markDirty("InitializePortsFromChildren")}catch(f){let m=r.root?.db;if(m&&r.source_component_id&&r.pcb_component_id){let D=r.getSubcircuit(),b=`${r.getString()} failed to load external footprint "${x}": `+(f instanceof Error?f.message:String(f)),E=yb.parse({type:"external_footprint_load_error",message:b,pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,subcircuit_id:D.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0,footprinter_string:x});m.external_footprint_load_error.insert(E)}throw f}});return}if(typeof a=="string"){let x=rK(a);if(!x||r._hasStartedFootprintUrlLoad)return;r._hasStartedFootprintUrlLoad=!0;let m=r.root?.platform?.footprintLibraryMap?.[x.footprintLib],D;if(typeof m=="function"&&(D=m),!D)return;e("load-lib-footprint",async()=>{try{let b=await D(x.footprintName),E=null;if(Array.isArray(b)?E=b:Array.isArray(b.footprintCircuitJson)&&(E=b.footprintCircuitJson),!E)return;let A=qS({componentName:r.name,componentRotation:s,footprint:a,pinLabels:l,pcbPinLabels:d},E);r.addAll(A),!Array.isArray(b)&&b.cadModel&&(r._asyncFootprintCadModel=b.cadModel);for(let B of r.children)B.componentName==="Port"&&B._markDirty?.("PcbPortRender");r._markDirty("InitializePortsFromChildren")}catch(b){let E=r.root?.db;if(E&&r.source_component_id&&r.pcb_component_id){let A=r.getSubcircuit(),B=`${r.getString()} failed to load external footprint "${a}": `+(b instanceof Error?b.message:String(b)),w=yb.parse({type:"external_footprint_load_error",message:B,pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,subcircuit_id:A.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0,footprinter_string:a});E.external_footprint_load_error.insert(w)}throw b}});return}if(!(0,tK.isValidElement)(a)&&a.componentName==="Footprint"&&r.add(a),Array.isArray(a)&&!(0,tK.isValidElement)(a)&&a.length>0){try{let x=qS({componentName:r.name,componentRotation:s,footprint:"",pinLabels:l,pcbPinLabels:d},a);r.addAll(x)}catch(x){let f=r.root?.db;if(f&&r.source_component_id&&r.pcb_component_id){let m=r.getSubcircuit(),D=`${r.getString()} failed to load json footprint: `+(x instanceof Error?x.message:String(x)),b=VA.parse({type:"circuit_json_footprint_load_error",message:D,pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,subcircuit_id:m.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0});f.circuit_json_footprint_load_error.insert(b)}throw x}return}}function jGt(r){if(r.root?.pcbDisabled||!r.pcb_component_id)return;let{pcbX:e,pcbY:a}=r._parsedProps,s=r.props?.pcbPositionAnchor;if(!s||e===void 0&&a===void 0)return;let l=ZS(r.children);if(l.width===0||l.height===0)return;let x={...{x:(l.minX+l.maxX)/2,y:(l.minY+l.maxY)/2}},f=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(s)){let b={left:l.minX,right:l.maxX,top:l.minY,bottom:l.maxY};switch(s){case"center":f=x;break;case"top_left":f={x:b.left,y:b.top};break;case"top_center":f={x:x.x,y:b.top};break;case"top_right":f={x:b.right,y:b.top};break;case"center_left":f={x:b.left,y:x.y};break;case"center_right":f={x:b.right,y:x.y};break;case"bottom_left":f={x:b.left,y:b.bottom};break;case"bottom_center":f={x:x.x,y:b.bottom};break;case"bottom_right":f={x:b.right,y:b.bottom};break}}else try{let b=r.portMap[s];b&&(f=b._getGlobalPcbPositionBeforeLayout())}catch{}if(!f)return;let D={...x};e!==void 0&&(D.x+=e-f.x),a!==void 0&&(D.y+=a-f.y),(Math.abs(D.x-x.x)>1e-6||Math.abs(D.y-x.y)>1e-6)&&r._repositionOnPcb(D)}var kGt=(0,XBe.default)("tscircuit:core"),NGt=v.object({x:Gn,y:Gn,z:Gn}),es=class extends qn{constructor(e){let a={...e},s=[];if(a.pinLabels&&!Array.isArray(a.pinLabels)){let{validPinLabels:l,invalidPinLabelsMessages:d}=TGt(a.pinLabels);a.pinLabels=l,s=d}super(a);z(this,"reactSubtrees",[]);z(this,"_impliedFootprint");z(this,"isPrimitiveContainer",!0);z(this,"_isNormalComponent",!0);z(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});z(this,"_asyncSupplierPartNumbers");z(this,"_asyncFootprintCadModel");z(this,"_isCadModelChild");z(this,"pcb_missing_footprint_error_id");z(this,"_hasStartedFootprintUrlLoad",!1);z(this,"_invalidPinLabelMessages",[]);z(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(),d=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:d}),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=YF(E,this._parsedProps.pinLabels);s.push(new Ni({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 Ni({pinNumber:m++,aliases:e.additionalAliases?.[`pin${m}`]??[]},{originDescription:`schPortArrangement:${D}`}))}}let d=this._parsedProps.pinLabels;if(d)for(let[f,m]of Object.entries(d)){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 Ni({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=ks[this._getSchematicSymbolNameOrThrow()];if(!f)return;for(let m of f.ports){let D=QBe(m.labels);if(!D)continue;let b=s.find(E=>E._parsedProps.pinNumber===Number(D));if(b)b.schematicSymbolPortDef=m;else{let E=qF(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 Ni({pinNumber:f,aliases:e.additionalAliases?.[`pin${f}`]??[]}));continue}let m=[...l.leftSide?.pins??[],...l.rightSide?.pins??[],...l.topSide?.pins??[],...l.bottomSide?.pins??[]].map(D=>YF(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 Ni({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(HS(l)||rK(l))return;let d=Vq.string(l).soup(),x=qS({componentName:this.name??this.componentName,componentRotation:e,footprint:l,pinLabels:a,pcbPinLabels:s},d);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 d of this._invalidPinLabelMessages){let x="pinLabels",f=d.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);f&&(x=`pinLabels['${f[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:x,message:d,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:a}=this.config,{_parsedProps:s}=this;s.symbol&&(0,ax.isValidElement)(s.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(s.symbol):a?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let l=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&l){if(!this.schematic_component_id)return;let d=qA.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(d)}}_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=ks[s],d=this._getGlobalSchematicPositionBeforeLayout();if(l){let x=e.schematic_component.insert({center:d,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}}_doInitialSchematicComponentRenderWithReactSymbol(e){if(this.root?.schematicDisabled)return;let{db:a}=this.root,s=this._getGlobalSchematicPositionBeforeLayout(),l=a.schematic_component.insert({center:s,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_name:"custom_symbol",symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=l.schematic_component_id,this.add(e)}_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 d=this._getGlobalSchematicPositionBeforeLayout(),x=this._getSchematicPortArrangement(),f=e.schematic_component.insert({center:d,rotation:a.schRotation??0,size:s.getSize(),port_arrangement:qVt(x),pin_spacing:a.schPinSpacing??.2,pin_styles:zVt(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?d.x+(D??0)/2+.1:d.x-(D??0)/2,y:m?d.y+(b??0)/2+.35:d.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?d.x+(D??0)/2+.1:d.x-(D??0)/2,y:m?d.y+(b??0)/2+.55:d.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=GA.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=ZS(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()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db:e}=this.root,a=e.schematic_component.get(this.schematic_component_id);if(!a||a.symbol_name!=="custom_symbol")return;let s=[],l=m=>{for(let D of m){if(D.isSchematicPrimitive&&D.componentName==="SchematicLine"){let b=e.schematic_line.get(D.schematic_line_id);b&&s.push(b)}if(D.isSchematicPrimitive&&D.componentName==="SchematicRect"){let b=e.schematic_rect.get(D.schematic_rect_id);b&&s.push(b)}if(D.isSchematicPrimitive&&D.componentName==="SchematicText"){let b=e.schematic_text.get(D.schematic_text_id);b&&s.push(b)}D.children&&D.children.length>0&&l(D.children)}};if(l(this.children),s.length===0)return;let d=ZBe(s),x=Math.abs(d.maxX-d.minX),f=Math.abs(d.maxY-d.minY);x===0&&f===0||e.schematic_component.update(this.schematic_component_id,{size:{width:x,height:f}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){jGt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(e){let a=KBe(e);return{element:e,component:a}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let e=this.props.footprint;(0,ax.isValidElement)(e)&&(this.children.some(l=>l.componentName==="Footprint")||this.add(e));let a=this.props.cadModel;if((0,ax.isValidElement)(a)){this._isCadModelChild=!0;let s=this.children.some(d=>d.componentName==="CadAssembly"),l=this.children.some(d=>d.componentName==="CadModel");!s&&!l&&this.add(a)}}doInitialPcbFootprintStringRender(){IGt(this,(e,a)=>this._queueAsyncEffect(e,a))}_hasExistingPortExactly(e){return this.children.filter(s=>s.componentName==="Port").some(s=>{let l=e.getNameAndAliases(),d=s.getNameAndAliases();return l.length===d.length&&l.every(x=>d.includes(x))})}add(e){let a;if((0,ax.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(d=>d.componentName==="Port").find(d=>d.isMatchingAnyOf(a.getNameAndAliases()));l&&kGt(`Similar ports added. Port 1: ${l}, Port 2: ${a}`)}super.add(a)}getPortsFromFootprint(e){let{footprint:a}=this.props;if((!a||(0,ax.isValidElement)(a))&&(a=this.children.find(l=>l.componentName==="Footprint")),typeof a=="string"){if(HS(a))return[];if(rK(a))return[];let l=Vq.string(a).soup(),d=[];for(let x of l)if("port_hints"in x&&x.port_hints){let f=qF(x.port_hints,e);if(!f)continue;f.originDescription=`footprint:string:${a}:port_hints[0]:${x.port_hints[0]}`,d.push(f)}return d}if(!(0,ax.isValidElement)(a)&&a&&a.componentName==="Footprint"){let l=a,d=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${d}`]),d++;let b=qF(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 d=qF(l.props.portHints);d&&s.push(d)}}return s}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:e}=this;if(!e.schematicSymbolName)return[];let a=ks[e.schematicSymbolName];if(!a)return[];let s=[];for(let l of a.ports){let d=qF(l.labels);d&&(d.schematicSymbolPortDef=l,s.push(d))}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 d=Array.isArray(l)?l:[l];for(let x of d)a.push(x)}return a}_createNetsFromProps(e){uK(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(!e9e(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:d,bottomSide:x}=e;return Math.max(...s?.pins??[],...l?.pins??[],...d?.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(d=>d.startsWith("pin")?parseInt(d.slice(3)):parseInt(d)).filter(d=>!Number.isNaN(d));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 JVt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:s,numericSchPinStyle:QVt(e.schPinStyle,e.pinLabels),pinCount:a,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:e.pinLabels})}doInitialCadModelRender(){if(this._isCadModelChild)return;let{db:e}=this.root,{boardThickness:a=0}=this.root?._getBoard()??{},s=this._parsedProps.cadModel,l=s===void 0?this._asyncFootprintCadModel:s,d=this.props.footprint??this._getImpliedFootprintString();if(!this.pcb_component_id||!l&&!d||l===null)return;let x=this._getPcbCircuitJsonBounds(),f=e.pcb_component.get(this.pcb_component_id);if(typeof l=="string")throw new Error("String cadModel not yet implemented");let m=NGt.parse({x:0,y:0,z:typeof l?.rotationOffset=="number"?l.rotationOffset:0,...typeof l?.rotationOffset=="object"?l.rotationOffset??{}:{}}),D=Gf.parse({x:0,y:0,z:0,...typeof l?.positionOffset=="object"?l.positionOffset:{}}),b=this.props.layer==="bottom"?"bottom":"top",E=e.cad_component.insert({position:{x:x.center.x+D.x,y:x.center.y+D.y,z:(b==="bottom"?-a/2:a/2)+D.z},rotation:{x:m.x,y:(b==="top"?0:180)+m.y,z:b==="bottom"?-((f?.rotation??0)+m.z)+180:(f?.rotation??0)+m.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(l??{})?this._addCachebustToModelUrl(l.stlUrl):void 0,model_obj_url:"objUrl"in(l??{})?this._addCachebustToModelUrl(l.objUrl):void 0,model_mtl_url:"mtlUrl"in(l??{})?this._addCachebustToModelUrl(l.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(l??{})?this._addCachebustToModelUrl(l.gltfUrl):void 0,model_glb_url:"glbUrl"in(l??{})?this._addCachebustToModelUrl(l.glbUrl):void 0,model_step_url:"stepUrl"in(l??{})?this._addCachebustToModelUrl(l.stepUrl):void 0,model_wrl_url:"wrlUrl"in(l??{})?this._addCachebustToModelUrl(l.wrlUrl):void 0,model_jscad:"jscad"in(l??{})?l.jscad:void 0,model_unit_to_mm_scale_factor:typeof l?.modelUnitToMmScale=="number"?l.modelUnitToMmScale:void 0,footprinter_string:typeof d=="string"&&!l?d:void 0});this.cad_component_id=E.cad_component_id}_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,d=this._getPartsEngineCacheKey(a,s);if(l){let m=await l.getItem(d);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(d,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 d=this._getSupplierPartNumbers(e,s,l);if(!(d instanceof Promise)){a.source_component.update(this.source_component_id,{supplier_part_numbers:d});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await d,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 d of l)this.add(new qc({from:`${this.getSubcircuitSelector()} > port.${a}`,to:d}))}}doInitialSourceDesignRuleChecks(){RGt(this)}_getMinimumFlexContainerSize(){return _Gt(this)}_repositionOnPcb(e){return AGt(this,e)}doInitialSilkscreenOverlapAdjustment(){return wGt(this)}},MGt=class{constructor(r,e={}){z(this,"input");z(this,"isRouting",!1);z(this,"solver");z(this,"eventHandlers",{complete:[],error:[],progress:[]});z(this,"cycleCount",0);z(this,"stepDelay");z(this,"timeoutId");this.input=r;let{capacityDepth:a,targetMinCapacity:s,stepDelay:l=0}=e;this.solver=new w6e(r,{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 UF(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let r=Date.now(),e=this.solver.iterations;for(;Date.now()-r<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let a=(this.solver.iterations-e)/(Date.now()-r)*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(r){this.emitEvent({type:"error",error:r instanceof Error?new UF(r.message):new UF(String(r))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(r,e){r==="complete"?this.eventHandlers.complete.push(e):r==="error"?this.eventHandlers.error.push(e):r==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(r){if(r.type==="complete")for(let e of this.eventHandlers.complete)e(r);else if(r.type==="error")for(let e of this.eventHandlers.error)e(r);else if(r.type==="progress")for(let e of this.eventHandlers.progress)e(r)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new UF(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},fK=class extends qn{constructor(){super(...arguments);z(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:i4e}}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=>({...as(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()})}},o9e=({circuitJson:r,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:d,new_center:x}=l,f=ua(r).pcb_component.get(d);if(!f)continue;let m=ua(r).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},u9e=({circuitJson:r,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:d,new_center:x}=l,f=ua(r).schematic_component.get(d);if(!f||!f.source_component_id)continue;let m=ua(r).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},OGt=({circuitJson:r,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"),d=a;return s.length>0&&(d=u9e({circuitJson:r,editEvents:s,manualEditsFile:d})),l.length>0&&(d=o9e({circuitJson:r,editEvents:l,manualEditsFile:d})),d},LGt=(r,e)=>{if(ua(r).pcb_trace_hint.get(e.pcb_trace_hint_id))r=r.map(s=>s.pcb_trace_hint_id===e.pcb_trace_hint_id?{...s,route:e.route}:s);else{let s=ua(r).pcb_port.get(e.pcb_port_id);r=r.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 r},$Gt=({circuitJson:r,editEvents:e})=>{r=JSON.parse(JSON.stringify(r));for(let a of e)if(a.edit_event_type==="edit_pcb_component_location"){let s=r.find(d=>d.type==="pcb_component"&&d.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 d=Ma(a.new_center.x-a.original_center.x,a.new_center.y-a.original_center.y);r=r.map(x=>x.pcb_component_id!==a.pcb_component_id?x:IY(x,d))}}else a.edit_event_type==="edit_schematic_component_location"?r=r.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"&&(r=LGt(r,a));return r},c9e=(r,e)=>{let a=r.source_group.list(),s=[],l=d=>{let x=a.filter(f=>f.parent_subcircuit_id===d);for(let f of x)f.subcircuit_id&&(s.push(f.subcircuit_id),l(f.subcircuit_id))};return l(e),s},nK=({db:r,circuitJson:e,subcircuit_id:a,minTraceWidth:s=.1})=>{if(!r&&e&&(r=ua(e)),!r)throw new Error("db or circuitJson is required");let l=r.pcb_trace_hint.list(),d=a?new Set([a]):null;if(a){let K=c9e(r,a);for(let U of K)d.add(U)}let x=(e??r.toArray()).filter(K=>!a||"subcircuit_id"in K&&d.has(K.subcircuit_id)),f=r.pcb_board.list()[0];r=ua(x);let m=eu(x),D=pK([...r.pcb_component.list(),...r.pcb_smtpad.list(),...r.pcb_plated_hole.list(),...r.pcb_hole.list(),...r.pcb_via.list(),...r.pcb_cutout.list()].filter(K=>!a||d?.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=r.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(r.pcb_trace.list().map(K=>K.source_trace_id).filter(K=>!!K)),B=r.source_trace.list().filter(K=>!A.has(K.source_trace_id)).map(K=>{let U=K.connected_source_port_ids.map(Ge=>{let tt=r.source_port.get(Ge),He=r.pcb_port.getWhere({source_port_id:Ge});return{...tt,...He}});if(U.length<2)return null;let[J,Q]=U,de=J.layers?.[0]??"top",oe=Q.layers?.[0]??"top",Me=l.filter(Ge=>Ge.pcb_port_id===J.pcb_port_id||Ge.pcb_port_id===Q.pcb_port_id),Ne=[];for(let Ge of Me){let He=r.pcb_port.get(Ge.pcb_port_id)?.layers?.[0]??"top";for(let $t of Ge.route)Ne.push({x:$t.x,y:$t.y,layer:He})}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:oe,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=r.source_net.list().filter(K=>!a||d?.has(K.subcircuit_id)),j=[];for(let K of P){let U=r.source_trace.list().filter(J=>J.connected_source_net_ids?.includes(K.source_net_id));j.push({name:K.source_net_id??m.getNetConnectedToId(K.source_net_id),pointsToConnect:U.flatMap(J=>r.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=r.pcb_breakout_point.list().filter(K=>!a||d?.has(K.subcircuit_id)),q=[],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]};q.push(Q),ee.set(K.source_trace_id,Q)}}else if(K.source_net_id){let J=j.find(Q=>Q.name===K.source_net_id);J?J.pointsToConnect.push(U):q.push({name:K.source_net_id,pointsToConnect:[U]})}else if(K.source_port_id){let J=r.pcb_port.getWhere({source_port_id:K.source_port_id});J&&q.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 W=[...B,...j,...q],re=new Map;for(let K of W)for(let U of K.pointsToConnect)U.pointId&&re.set(U.pointId,K);let L=r.pcb_trace.list().filter(K=>!a||d?.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=re.get(J);Q&&[...U].every(de=>re.get(de)===Q)&&(Q.externallyConnectedPointIds??(Q.externallyConnectedPointIds=[]),Q.externallyConnectedPointIds.push([...U]))}return{simpleRouteJson:{bounds:E,obstacles:D,connections:W,layerCount:f?.num_layers??2,minTraceWidth:s},connMap:m}},zGt=r=>{let e={};if(!r)return e;for(let s of ld)e[s]=0;let a=new Map;for(let s of r){let[,,l,d]=s.type.split(":");if(d==="start"){a.set(`${l}:${s.renderId}`,s);continue}if(d==="end"){let x=a.get(`${l}:${s.renderId}`);if(x){let f=s.createdAt-x.createdAt;e[l]=(e[l]||0)+f}}}return e},qGt=r=>{let e=r.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,d=new Set;for(let m=0;m<s.length;m++){let D=s[m];if(D===null||D<1)continue;if(!d.has(D)){d.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},PBe=(0,l9e.default)("Group_doInitialSchematicLayoutMatchAdapt");function UGt(r){let{db:e}=r.root,a=Hb(e.toArray(),{source_group_id:r.source_group_id}),s=uH(a);PBe.enabled&&global.debugGraphics?.push(Wp(s,{title:`floatingBpcGraph-${r.name}`}));let l=uH(a),d={boxes:l.boxes,pins:l.pins.map(m=>({...m,color:m.color.replace("not_connected","normal")}))},{result:x}=s5e([{variantName:"default",floatingGraph:l},{variantName:"noNotConnected",floatingGraph:d}],{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:{}});PBe.enabled&&global.debugGraphics?.push(Wp(x,{title:`laidOutBpcGraph-${r.name}`}));let f=r._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 an=(0,d9e.default)("Group_doInitialSchematicLayoutMatchpack");function IBe(r){switch(r){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function jBe(r,e){let a=["right","up","left","down"],s=a.indexOf(r);if(s===-1)return r;let l=Math.round(e/90),d=(s+l)%4;return a[d<0?d+4:d]}function VGt(r,e,a){let s={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};an(`[${a.name}] Processing ${r.childNodes.length} child nodes for input problem`),r.childNodes.forEach((d,x)=>{if(an(`[${a.name}] Processing child ${x}: nodeType=${d.nodeType}`),d.nodeType==="component"?an(`[${a.name}] - Component: ${d.sourceComponent?.name}`):d.nodeType==="group"&&an(`[${a.name}] - Group: ${d.sourceGroup?.name}`),d.nodeType==="component"&&d.sourceComponent){let f=d.sourceComponent.name||`chip_${x}`,m=e.schematic_component.getWhere({source_component_id:d.sourceComponent.source_component_id});if(!m)return;let D=a.children.find(q=>q.source_component_id===d.sourceComponent?.source_component_id),b=[0,90,180,270];D?._parsedProps?.schOrientation&&(b=[0]),D?._parsedProps?.schRotation!==void 0&&(b=[0]);let E=D?._parsedProps?.schMarginLeft??D?._parsedProps?.schMarginX??0,A=D?._parsedProps?.schMarginRight??D?._parsedProps?.schMarginX??0,B=D?._parsedProps?.schMarginTop??D?._parsedProps?.schMarginY??0,w=D?._parsedProps?.schMarginBottom??D?._parsedProps?.schMarginY??0;D?.config.shouldRenderAsSchematicBox&&(B+=.4,w+=.4);let P=(A-E)/2,j=(B-w)/2;s.chipMap[f]={chipId:f,pins:[],size:{x:(m.size?.width||1)+E+A,y:(m.size?.height||1)+B+w},availableRotations:b};let O=e.schematic_port.list({schematic_component_id:m.schematic_component_id});for(let q of O){let ee=e.source_port.get(q.source_port_id);if(!ee)continue;let W=`${f}.${ee.pin_number||ee.name||q.schematic_port_id}`;s.chipMap[f].pins.push(W);let re=IBe(q.facing_direction);s.chipPinMap[W]={pinId:W,offset:{x:(q.center?.x||0)-(m.center.x||0)+P,y:(q.center?.y||0)-(m.center.y||0)+j},side:re}}}else if(d.nodeType==="group"&&d.sourceGroup){let f=d.sourceGroup.name||`group_${x}`;an(`[${a.name}] Processing nested group: ${f}`);let m=e.schematic_group?.getWhere?.({source_group_id:d.sourceGroup.source_group_id}),D=a.children.find(b=>b.source_group_id===d.sourceGroup?.source_group_id);if(an(`[${a.name}] Found schematic_group for ${f}:`,m),m){an(`[${a.name}] Treating group ${f} as composite chip`);let b=e.schematic_component.list({schematic_group_id:m.schematic_group_id});an(`[${a.name}] Group ${f} has ${b.length} components:`,b.map(J=>J.source_component_id));let E=1/0,A=-1/0,B=1/0,w=-1/0,P=!1;for(let J of b)if(J.center&&J.size){P=!0;let Q=J.size.width/2,de=J.size.height/2;E=Math.min(E,J.center.x-Q),A=Math.max(A,J.center.x+Q),B=Math.min(B,J.center.y-de),w=Math.max(w,J.center.y+de)}let j=D?._parsedProps?.schMarginLeft??D?._parsedProps?.schMarginX??0,O=D?._parsedProps?.schMarginRight??D?._parsedProps?.schMarginX??0,q=D?._parsedProps?.schMarginTop??D?._parsedProps?.schMarginY??0,ee=D?._parsedProps?.schMarginBottom??D?._parsedProps?.schMarginY??0,W=(O-j)/2,re=(q-ee)/2,L=(P?A-E:2)+j+O,K=(P?w-B:2)+q+ee;an(`[${a.name}] Group ${f} computed size: ${L} x ${K}`);let U=[];for(let J of b){let Q=e.schematic_port.list({schematic_component_id:J.schematic_component_id});for(let de of Q){let oe=e.source_port.get(de.source_port_id);if(!oe)continue;let Me=`${f}.${oe.pin_number||oe.name||de.schematic_port_id}`;U.push(Me);let Ne=m.center||{x:0,y:0},Ge=IBe(de.facing_direction);s.chipPinMap[Me]={pinId:Me,offset:{x:(de.center?.x||0)-Ne.x+W,y:(de.center?.y||0)-Ne.y+re},side:Ge}}}an(`[${a.name}] Group ${f} has ${U.length} pins:`,U),s.chipMap[f]={chipId:f,pins:U,size:{x:L,y:K}},an(`[${a.name}] Added group ${f} to chipMap`)}else an(`[${a.name}] Warning: No schematic_group found for group ${f}`)}}),an(`[${a.name}] Creating connections using connectivity keys`);let l=new Map;for(let[d,x]of Object.entries(s.chipMap))for(let f of x.pins){let m=f.split(".").pop(),D=r.childNodes.find(b=>b.nodeType==="component"&&b.sourceComponent?b.sourceComponent.name===d:b.nodeType==="group"&&b.sourceGroup?`group_${r.childNodes.indexOf(b)}`===d:!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 j=w.subcircuit_connectivity_map_key;l.has(j)||l.set(j,[]),l.get(j).push(f),an(`[${a.name}] \u2713 Pin ${f} has connectivity key: ${j}`)}else an(`[${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),an(`[${a.name}] Pin ${f} has connectivity key: ${B}`)}}}}an(`[${a.name}] Found ${l.size} connectivity groups:`,Array.from(l.entries()).map(([d,x])=>({key:d,pins:x})));for(let[d,x]of l)if(x.length>=2){let f=e.source_trace.list().filter(b=>b.subcircuit_connectivity_map_key===d),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(an(`[${a.name}] Connectivity ${d}: 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 j=B.split(".")[0],O=r.childNodes.find(q=>q.nodeType==="component"&&q.sourceComponent?q.sourceComponent.name===j:q.nodeType==="group"&&q.sourceGroup?`group_${r.childNodes.indexOf(q)}`===j:!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,an(`[${a.name}] Created strong connection: ${w} <-> ${P}`)}}}if(m){let b=e.source_net.getWhere({subcircuit_connectivity_map_key:d}),E=b?.is_ground??!1,A=b?.is_power??!1;s.netMap[d]={netId:d,isGround:E,isPositiveVoltageSource:A};for(let B of x)s.netConnMap[`${B}-${d}`]=!0;an(`[${a.name}] Created net ${d} with ${x.length} pins:`,x)}}return s}function GGt(r){let{db:e}=r.root,a=xg(e.toArray(),{source_group_id:r.source_group_id});if(an(`[${r.name}] Starting matchpack layout with ${a.childNodes.length} children`),an(`[${r.name}] Tree structure:`,JSON.stringify(a,null,2)),a.childNodes.length<=1){an(`[${r.name}] Only ${a.childNodes.length} children, skipping layout`);return}an("Converting circuit tree to InputProblem...");let s=VGt(a,e,r);an.enabled&&r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${r.name}`,content:JSON.stringify(s,null,2)});let l=new uSe(s);if(an("Starting LayoutPipelineSolver..."),an.enabled&&global.debugGraphics){let m=l.visualize();global.debugGraphics.push({...m,title:`matchpack-initial-${r.name}`})}if(l.solve(),an(`Solver completed in ${l.iterations} iterations`),an(`Solved: ${l.solved}, Failed: ${l.failed}`),l.failed)throw an(`Solver failed with error: ${l.error}`),new Error(`Matchpack layout solver failed: ${l.error}`);let d=l.getOutputLayout();if(an("OutputLayout:",JSON.stringify(d,null,2)),an("Solver completed successfully:",!l.failed),an.enabled&&global.debugGraphics){let m=l.visualize();global.debugGraphics.push({...m,title:`matchpack-final-${r.name}`})}let x=l.checkForOverlaps(d);if(x.length>0){an(`Warning: Found ${x.length} overlapping components:`);for(let m of x)an(` ${m.chip1} overlaps ${m.chip2} (area: ${m.overlapArea})`)}let f=r._getGlobalSchematicPositionBeforeLayout();an(`Group offset: x=${f.x}, y=${f.y}`),an(`Applying layout results for ${Object.keys(d.chipPlacements).length} chip placements`);for(let[m,D]of Object.entries(d.chipPlacements)){an(`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 an(` 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 an(` Checking group ${B} (expected chipId: ${w}): matches=${P}`),P}return!1});if(!b){an(`Warning: No tree node found for chip: ${m}`),an("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){an(`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 j of B)j.center.x+=P.x,j.center.y+=P.y;for(let j of w)j.position.x+=P.x,j.position.y+=P.y;if(A.center=E,D.ccwRotationDegrees!==0){an(`Component ${m} has rotation: ${D.ccwRotationDegrees}\xB0`);let j=D.ccwRotationDegrees*Math.PI/180,O=Math.cos(j),q=Math.sin(j);for(let ee of B){let W=ee.center.x-E.x,re=ee.center.y-E.y,L=W*O-re*q,K=W*q+re*O;ee.center.x=E.x+L,ee.center.y=E.y+K;let U=ee.facing_direction||"right";ee.facing_direction=jBe(U,D.ccwRotationDegrees)}for(let ee of w){let W=ee.position.x-E.x,re=ee.position.y-E.y,L=W*O-re*q,K=W*q+re*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],`_${jBe(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){an(`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});an(`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};an(`Position delta for group ${m}: (${P.x}, ${P.y})`);for(let j of B)if(j.center){let O={...j.center};j.center.x+=P.x,j.center.y+=P.y,an(`Moved component ${j.source_component_id} from (${O.x}, ${O.y}) to (${j.center.x}, ${j.center.y})`);let q=e.schematic_port.list({schematic_component_id:j.schematic_component_id}),ee=e.schematic_text.list({schematic_component_id:j.schematic_component_id});for(let W of q)W.center&&(W.center.x+=P.x,W.center.y+=P.y);for(let W of ee)W.position&&(W.position.x+=P.x,W.position.y+=P.y)}A.center=E,an(`Updated group ${m} center to (${E.x}, ${E.y})`)}}}an("Matchpack layout completed successfully")}function XGt(r){if(!r.isSubcircuit)return;let{db:e}=r.root,a=r.selectAll("trace"),s=new $b({});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}=r._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${r._renderId}`}_${m}`,e.source_trace.update(f.source_trace_id,{subcircuit_connectivity_map_key:f.subcircuit_connectivity_map_key}))}let d=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)d.add(D)}for(let f of d){let m=s.getNetConnectedToId(f);if(!m)continue;let D=`${l??`unnamedsubcircuit${r._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${r._renderId}`}_${m}`;e.source_net.update(f,{subcircuit_connectivity_map_key:D})}}function YGt(r){let{db:e}=r.root,a=r._parsedProps,s=r.children.filter(re=>{let L=re._parsedProps?.schX!==void 0||re._parsedProps?.schY!==void 0;return re.schematic_component_id&&!L});if(s.length===0)return;let l=0,d=0;for(let re of s){let L=e.schematic_component.get(re.schematic_component_id);L?.size&&(l=Math.max(l,L.size.width),d=Math.max(d,L.size.height))}l===0&&s.length>0&&(l=1),d===0&&s.length>0&&(d=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=re=>{if(re!==void 0)return typeof re=="number"?re:pe.parse(re)};if(D!==void 0||b!==void 0){let re=typeof m=="object"&&m!==null?m.x:m,L=typeof m=="object"&&m!==null?m.y:m;B=P(b??re)??1,w=P(D??L)??1}else if(typeof m=="number")B=m,w=m;else if(typeof m=="string"){let re=pe.parse(m);B=re,w=re}else if(typeof m=="object"&&m!==null){let re=m.x,L=m.y;B=typeof re=="number"?re:pe.parse(re??"0mm"),w=typeof L=="number"?L:pe.parse(L??"0mm")}else B=1,w=1;let j=E*l+Math.max(0,E-1)*B,O=A*d+Math.max(0,A-1)*w,q=r._getGlobalSchematicPositionBeforeLayout(),ee=q.x-j/2+l/2,W=q.y+O/2-d/2;for(let re=0;re<s.length;re++){let L=s[re];if(!L.schematic_component_id)continue;let K=Math.floor(re/E),U=re%E;if(K>=A||U>=E){console.warn(`Schematic grid layout: Child ${L.getString()} at index ${re} (row ${K}, col ${U}) exceeds specified grid dimensions (${A}x${E}). Skipping placement.`);continue}let J=ee+U*(l+B),Q=W-K*(d+w),de=e.schematic_component.get(L.schematic_component_id);if(de){let oe=de.center,Me={x:J,y:Q};e.schematic_component.update(L.schematic_component_id,{center:Me});let Ne=Me.x-oe.x,Ge=Me.y-oe.y,tt=e.schematic_port.list({schematic_component_id:L.schematic_component_id});for(let $t of tt)e.schematic_port.update($t.schematic_port_id,{center:{x:$t.center.x+Ne,y:$t.center.y+Ge}});let He=e.schematic_text.list({schematic_component_id:L.schematic_component_id});for(let $t of He)e.schematic_text.update($t.schematic_text_id,{position:{x:$t.position.x+Ne,y:$t.position.y+Ge}})}}r.schematic_group_id&&e.schematic_group.update(r.schematic_group_id,{width:j,height:O,center:q})}var kBe=(r,e)=>{let{sourceComponent:a,sourceGroup:s}=e;if(e.nodeType==="component"){let l=r.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=r.schematic_group.getWhere({source_group_id:s?.source_group_id});if(l?.width&&l?.height)return{width:l.width,height:l.height};let d=r.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 d)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},HGt=r=>{let{db:e}=r.root,a=r._parsedProps,s=xg(e.toArray(),{source_group_id:r.source_group_id}),l=a.schJustifyContent??a.justifyContent,d=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"}[d??"center"];if(!m)throw new Error(`Invalid justifyContent value: "${l}"`);if(!D)throw new Error(`Invalid alignItems value: "${d}"`);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=pe.parse(x),E=pe.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=A5(s.childNodes.map(W=>kBe(e,W)).filter(W=>W!==null),{alignItems:D,justifyContent:m,direction:f,rowGap:b,columnGap:E}),B=A.width,w=A.height);let j=new _S(B,w,{alignItems:D,justifyContent:m,direction:f,rowGap:b,columnGap:E});for(let W of s.childNodes){let re=kBe(e,W);j.addChild({metadata:W,width:re?.width??0,height:re?.height??0,flexBasis:re?f==="row"?re.width:re.height:void 0})}j.build();let O={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let W of j.children)O.minX=Math.min(O.minX,W.position.x),O.minY=Math.min(O.minY,W.position.y),O.maxX=Math.max(O.maxX,W.position.x+W.size.width),O.maxY=Math.max(O.maxY,W.position.y+W.size.height);O.width=O.maxX-O.minX,O.height=O.maxY-O.minY;let q={x:-(O.maxX+O.minX)/2,y:-(O.maxY+O.minY)/2},ee=e.toArray();for(let W of j.children){let{sourceComponent:re,sourceGroup:L}=W.metadata;if(re){let K=e.schematic_component.getWhere({source_component_id:re.source_component_id});if(!K)continue;T4e(ee,K.schematic_component_id,{x:W.position.x+W.size.width/2+q.x,y:W.position.y+W.size.height/2+q.y})}if(L){if(!e.schematic_group.getWhere({source_group_id:L.source_group_id}))continue;I4e(ee,L.source_group_id,{x:W.position.x+W.size.width/2+q.x,y:W.position.y+W.size.height/2+q.y})}}r.schematic_group_id&&e.schematic_group.update(r.schematic_group_id,{width:O.width,height:O.height})},YW=1;function WGt(r){let{db:e}=r.root,a=r._parsedProps,s=KGt(r);if(s.length===0)return;let l=JGt({db:e,pcbChildren:s}),d=ZGt(a),x=QGt({props:a,pcbChildren:s,childDimensions:l,gridConfig:d}),f=rXt({pcbChildren:s,childDimensions:l,gridLayout:x,gridConfig:d}),{itemCoordinates:m}=f.layout();nXt({db:e,group:r,pcbChildren:s,itemCoordinates:m,gridLayout:x}),aXt({db:e,group:r,props:a,gridLayout:x})}function KGt(r){return r.children.filter(e=>e.pcb_component_id||e.pcb_group_id)}function JGt(r){let{db:e,pcbChildren:a}=r,s=0,l=0;for(let d of a){let x=0,f=0;if(d.pcb_group_id){let m=e.pcb_group.get(d.pcb_group_id);x=m?.width??0,f=m?.height??0}else if(d.pcb_component_id){let m=e.pcb_component.get(d.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 ZGt(r){let e=r.pcbGridCols??r.gridCols??r.pcbLayout?.grid?.cols,a=r.pcbGridRows??r.pcbLayout?.grid?.rows,s=r.pcbGridTemplateColumns,l=r.pcbGridTemplateRows,d=E=>E===void 0?YW:typeof E=="number"?E:pe.parse(E),x=r.pcbGridGap??r.gridGap??r.pcbLayout?.gridGap,f=r.pcbGridRowGap??r.gridRowGap??r.pcbLayout?.gridRowGap,m=r.pcbGridColumnGap??r.gridColumnGap??r.pcbLayout?.gridColumnGap,D=YW,b=YW;if(f!==void 0||m!==void 0){let E=typeof x=="object"?x?.x:x,A=typeof x=="object"?x?.y:x;D=d(m??E),b=d(f??A)}else if(typeof x=="object"&&x!==null)D=d(x.x),b=d(x.y);else{let E=d(x);D=E,b=E}return{cols:e,rows:a,gapX:D,gapY:b,templateColumns:s,templateRows:l}}function QGt(r){let{props:e,pcbChildren:a,childDimensions:s,gridConfig:l}=r;return e.pcbGridTemplateColumns||e.pcbGridTemplateRows?eXt({props:e,gridConfig:l,pcbChildren:a,childDimensions:s}):tXt({gridConfig:l,pcbChildren:a,childDimensions:s})}function eXt(r){let{props:e,gridConfig:a,pcbChildren:s,childDimensions:l}=r,d=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(d):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:d,gridTemplateRows:x,containerWidth:b,containerHeight:E}}function tXt(r){let{gridConfig:e,pcbChildren:a,childDimensions:s}=r,l,d;e.cols!==void 0&&e.rows!==void 0?(l=e.cols,d=e.rows):e.cols!==void 0?(l=e.cols,d=Math.ceil(a.length/l)):e.rows!==void 0?(d=e.rows,l=Math.ceil(a.length/d)):(l=Math.ceil(Math.sqrt(a.length)),d=Math.ceil(a.length/l)),l=Math.max(1,l),d=Math.max(1,d);let x=l*s.width+Math.max(0,l-1)*e.gapX,f=d*s.height+Math.max(0,d-1)*e.gapY,m=`repeat(${l}, ${s.width}px)`,D=`repeat(${d}, ${s.height}px)`;return{gridTemplateColumns:m,gridTemplateRows:D,containerWidth:x,containerHeight:f}}function rXt(r){let{pcbChildren:e,childDimensions:a,gridLayout:s,gridConfig:l}=r,d=e.map((x,f)=>({key:x.getString()||`child-${f}`,contentWidth:a.width,contentHeight:a.height}));return new gSe({containerWidth:s.containerWidth,containerHeight:s.containerHeight,gridTemplateColumns:s.gridTemplateColumns,gridTemplateRows:s.gridTemplateRows,gap:[l.gapY,l.gapX],children:d})}function nXt(r){let{db:e,group:a,pcbChildren:s,itemCoordinates:l,gridLayout:d}=r,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-d.containerWidth/2+E.x+E.width/2,B=x.y+d.containerHeight/2-E.y-E.height/2;if(D.pcb_component_id)C5(f,D.pcb_component_id,{x:A,y:B});else{let w=D;w.pcb_group_id&&w.source_group_id&&_5(f,w.source_group_id,{x:A,y:B})}}}function aXt(r){let{db:e,group:a,props:s,gridLayout:l}=r;if(a.pcb_group_id){let d=a._getGlobalPcbPositionBeforeLayout();e.pcb_group.update(a.pcb_group_id,{width:s.width??l.containerWidth,height:s.height??l.containerHeight,center:d})}}function sXt(r){let e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof r=="object"&&!r.preset)return{local:!(r.serverUrl||r.serverMode||r.serverCacheEnabled),...e,...r};let a=typeof r=="object"?r.preset:r,s=typeof r=="object"?r:{};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:d,groupMode:x,...f}=s;return{local:!1,groupMode:"subcircuit",...e,...f}}default:return{local:!0,groupMode:"subcircuit"}}}var iXt=(r,e)=>{let a=r.children.filter(E=>E.componentName==="Constraint"&&E._parsedProps.pcb),s=new Map,l={},d=E=>(l[E]!==E&&(l[E]=d(l[E])),l[E]),x=(E,A)=>{let B=d(E),w=d(A);B!==w&&(l[w]=B)},f=E=>{E in l||(l[E]=E)},m=E=>{let A=E.startsWith(".")?E.slice(1):E;return r.children.find(w=>w.name===A)?.pcb_component_id??void 0};for(let E of a){let A=E._parsedProps;if("left"in A&&"right"in A){let B=m(A.left),w=m(A.right);B&&w&&(f(B),f(w),x(B,w))}else if("top"in A&&"bottom"in A){let B=m(A.top),w=m(A.bottom);B&&w&&(f(B),f(w),x(B,w))}else if("for"in A&&Array.isArray(A.for)){let B=A.for.map(w=>m(w)).filter(w=>!!w);for(let w of B)f(w);for(let w=1;w<B.length;w++)x(B[0],B[w])}}for(let E of Object.keys(l)){let A=d(E);s.has(A)||s.set(A,{componentIds:[],constraints:[]}),s.get(A).componentIds.push(E)}for(let E of a){let A=E._parsedProps,B;if("left"in A?B=m(A.left):"top"in A?B=m(A.top):"for"in A&&(B=m(A.for[0])),!B)continue;let w=d(B);s.get(w)?.constraints.push(E)}let D={},b=Object.fromEntries(e.components.map(E=>[E.componentId,E]));for(let[E,A]of s.entries()){if(A.componentIds.length<=1)continue;let B=new ug,w={},P=(J,Q)=>{let de=`${J}_${Q}`;return w[de]||(w[de]=new rd(de)),w[de]},j=A.componentIds[0];B.addConstraint(new Vs(P(j,"x"),Ds.Eq,0,Oa.required)),B.addConstraint(new Vs(P(j,"y"),Ds.Eq,0,Oa.required));for(let J of A.constraints){let Q=J._parsedProps;if("xDist"in Q){let de=m(Q.left),oe=m(Q.right);de&&oe&&B.addConstraint(new Vs(new Xa(P(oe,"x"),[-1,P(de,"x")]),Ds.Eq,Q.xDist,Oa.required))}else if("yDist"in Q){let de=m(Q.top),oe=m(Q.bottom);de&&oe&&B.addConstraint(new Vs(new Xa(P(de,"y"),[-1,P(oe,"y")]),Ds.Eq,Q.yDist,Oa.required))}else if("sameX"in Q&&Array.isArray(Q.for)){let de=Q.for.map(oe=>m(oe)).filter(oe=>!!oe);if(de.length>1){let oe=P(de[0],"x");for(let Me=1;Me<de.length;Me++)B.addConstraint(new Vs(new Xa(P(de[Me],"x"),[-1,oe]),Ds.Eq,0,Oa.required))}}else if("sameY"in Q&&Array.isArray(Q.for)){let de=Q.for.map(oe=>m(oe)).filter(oe=>!!oe);if(de.length>1){let oe=P(de[0],"y");for(let Me=1;Me<de.length;Me++)B.addConstraint(new Vs(new Xa(P(de[Me],"y"),[-1,oe]),Ds.Eq,0,Oa.required))}}}B.updateVariables();let O={};for(let J of A.componentIds)O[J]={x:P(J,"x").value(),y:P(J,"y").value()};let q=1/0,ee=1/0,W=-1/0,re=-1/0;for(let J of A.componentIds){let Q=b[J],de=O[J];if(Q)for(let oe of Q.pads){let Me=de.x+oe.offset.x,Ne=de.y+oe.offset.y;q=Math.min(q,Me-oe.size.x/2),W=Math.max(W,Me+oe.size.x/2),ee=Math.min(ee,Ne-oe.size.y/2),re=Math.max(re,Ne+oe.size.y/2)}}let L={x:(q+W)/2,y:(ee+re)/2},K=[],U={};for(let J of A.componentIds){let Q=b[J],de=O[J];if(Q){U[J]={x:de.x-L.x,y:de.y-L.y};for(let oe of Q.pads)K.push({padId:oe.padId,networkId:oe.networkId,type:oe.type,size:oe.size,offset:{x:de.x+oe.offset.x-L.x,y:de.y+oe.offset.y-L.y}})}}e.components=e.components.filter(J=>!A.componentIds.includes(J.componentId)),e.components.push({componentId:A.componentIds[0],pads:K,availableRotationDegrees:[0]}),A.relativeCenters=U,D[A.componentIds[0]]=A}return D},VF=(r,e,a)=>{if(e===a)return!0;let s=r.source_group.get(e);return!s||!s.parent_source_group_id?!1:VF(r,s.parent_source_group_id,a)},oXt=(r,e,a)=>{let{db:s}=r.root;for(let l of e.components){let{center:d,componentId:x,ccwRotationOffset:f,ccwRotationDegrees:m}=l,D=a[x];if(D){let O=(m??f??0)*Math.PI/180;for(let q of D.componentIds){let ee=D.relativeCenters[q];if(!ee)continue;let W={x:ee.x*Math.cos(O)-ee.y*Math.sin(O),y:ee.x*Math.sin(O)+ee.y*Math.cos(O)},re=s.pcb_component.get(q);if(!re)continue;let L=re.center,K=js(r._computePcbGlobalTransformBeforeLayout(),Ma(d.x+W.x,d.y+W.y),Ip(O),Ma(-L.x,-L.y)),U=s.toArray().filter(J=>"pcb_component_id"in J&&J.pcb_component_id===q);pg(U,K)}continue}let b=s.pcb_component.get(x);if(b){let j=r.source_group_id,q=s.source_component.get(b.source_component_id)?.source_group_id;if(q!==void 0&&!VF(s,q,j))continue;let ee=b.center,W=m??f??0,re=js(r._computePcbGlobalTransformBeforeLayout(),Ma(d.x,d.y),Ip(W*Math.PI/180),Ma(-ee.x,-ee.y)),L=s.toArray().filter(K=>"pcb_component_id"in K&&K.pcb_component_id===x);pg(L,re);continue}let E=s.pcb_group.list().find(j=>j.source_group_id===x);if(!E)continue;let A=E.center,B=m??f??0,w=js(r._computePcbGlobalTransformBeforeLayout(),Ma(d.x,d.y),Ip(B*Math.PI/180),Ma(-A.x,-A.y)),P=s.toArray().filter(j=>{if("source_group_id"in j&&j.source_group_id&&(j.source_group_id===x||VF(s,j.source_group_id,x)))return!0;if("source_component_id"in j&&j.source_component_id){let O=s.source_component.get(j.source_component_id);if(O?.source_group_id&&(O.source_group_id===x||VF(s,O.source_group_id,x)))return!0}if("pcb_component_id"in j&&j.pcb_component_id){let O=s.pcb_component.get(j.pcb_component_id);if(O?.source_component_id){let q=s.source_component.get(O.source_component_id);if(q?.source_group_id&&(q.source_group_id===x||VF(s,q.source_group_id,x)))return!0}}return!1});pg(P,w),s.pcb_group.update(E.pcb_group_id,{center:d})}},uXt="1mm",NBe=(0,p9e.default)("Group_doInitialPcbLayoutPack"),cXt=r=>{let{db:e}=r.root,{_parsedProps:a}=r,{packOrderStrategy:s,packPlacementStrategy:l,gap:d,pcbGap:x,pcbPackGap:f}=a,m=f??x??d,D=pe.parse(m??uXt),b={},E=P=>{if(P?.pcb_component_id&&P?._parsedProps){let j=P._parsedProps,O=pe.parse(j.pcbMarginLeft??j.pcbMarginX??0),q=pe.parse(j.pcbMarginRight??j.pcbMarginX??0),ee=pe.parse(j.pcbMarginTop??j.pcbMarginY??0),W=pe.parse(j.pcbMarginBottom??j.pcbMarginY??0);(O||q||ee||W)&&(b[P.pcb_component_id]={left:O,right:q,top:ee,bottom:W})}P?.children&&P.children.forEach(E)};E(r);let A={...iSe(sSe(e.toArray(),{source_group_id:r.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:b})),orderStrategy:s??"largest_to_smallest",placementStrategy:l??"minimum_sum_squared_distance_to_network",minGap:D},B=iXt(r,A);NBe.enabled&&(r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${r.name}`,content:JSON.stringify(e.toArray())}),r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${r.name}`,content:A}));let w=ES(A);if(NBe.enabled){let P=yW(w);P.title=`packOutput-${r.name}`,global.debugGraphics?.push(P)}oXt(r,w,B)},lXt=r=>{let{db:e}=r.root,{_parsedProps:a}=r,s=r.children.filter(re=>re.pcb_component_id||re.pcb_group_id);if(s.some(re=>{let L=re._parsedProps;return L?.pcbX!==void 0||L?.pcbY!==void 0}))return;let d=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"}[d??"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: "${d}"`);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=pe.parse(f),A=pe.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=A5(s.map(re=>re._getMinimumFlexContainerSize()).filter(re=>re!==null),{alignItems:b,justifyContent:D,direction:m,rowGap:E,columnGap:A}),w=B.width,P=B.height);let O=new _S(w,P,{alignItems:b,justifyContent:D,direction:m,rowGap:E,columnGap:A});for(let re of s){let L=re._getMinimumFlexContainerSize();O.addChild({metadata:re,width:L?.width??0,height:L?.height??0,flexBasis:L?m==="row"?L.width:L.height:void 0})}O.build();let q={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let re of O.children)q.minX=Math.min(q.minX,re.position.x),q.minY=Math.min(q.minY,re.position.y),q.maxX=Math.max(q.maxX,re.position.x+re.size.width),q.maxY=Math.max(q.maxY,re.position.y+re.size.height);q.width=q.maxX-q.minX,q.height=q.maxY-q.minY;let ee=r._getGlobalPcbPositionBeforeLayout(),W={x:ee.x-(q.maxX+q.minX)/2,y:ee.y-(q.maxY+q.minY)/2};for(let re of O.children)re.metadata._repositionOnPcb({x:re.position.x+re.size.width/2+W.x,y:re.position.y+re.size.height/2+W.y});e.pcb_group.update(r.pcb_group_id,{width:q.width,height:q.height,center:ee})};function dXt(r){let{db:e}=r.root,a=new Map,s=new Map,l=new Set,x=r.selectAll("trace").filter(Q=>Q._parsedProps?.schDisplayLabel),f=r.selectAll("group"),m=[r.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,oe=[],Me=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 Ge of Ne){let tt=`${Me?.name??Q.schematic_component_id}.${Ge.pin_number}`;E.set(tt,Ge.schematic_port_id),A.set(Ge.schematic_port_id,tt)}for(let Ge of Ne){let tt=A.get(Ge.schematic_port_id);oe.push({pinId:tt,x:Ge.center.x,y:Ge.center.y})}b.push({chipId:de,center:Q.center,width:Q.size.width,height:Q.size.height,pins:oe})}let B=new Set,w=new Map,P=new Map,j=new Map;for(let Q of D){let de=e.schematic_port.list({schematic_component_id:Q.schematic_component_id});for(let oe of de)B.add(oe.schematic_port_id),oe.source_port_id&&(w.set(oe.schematic_port_id,oe.source_port_id),P.set(oe.source_port_id,oe.schematic_port_id))}let O=new Set;r.subcircuit_id&&O.add(r.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===r.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 W=[],re=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(oe=>P.get(oe)).filter(oe=>!!oe&&B.has(oe));if(de.length>=2){let[oe,Me]=de.slice(0,2),Ne=[oe,Me].sort().join("::");if(!re.has(Ne)){re.set(Ne,Q.source_trace_id);let Ge=Q.display_name??Q.source_trace_id;Q.subcircuit_connectivity_map_key&&(l.add(Q.subcircuit_connectivity_map_key),j.set(Ge,Q.subcircuit_connectivity_map_key),s.set(Q.subcircuit_connectivity_map_key,Ge)),W.push({pinIds:[oe,Me].map(tt=>A.get(tt)),netId:Ge})}}}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 oe=e.source_port.get(de);if(!oe?.subcircuit_connectivity_map_key)continue;let Me=oe.subcircuit_connectivity_map_key;l.add(Me),K.has(Me)||K.set(Me,[]),K.get(Me).push(Q)}for(let[Q,de]of K){let oe=a.get(Q);if(oe&&de.length>=2){let Me=String(oe.name||oe.source_net_id||Q);j.set(Me,Q),s.set(Q,Me);let Ge=.1*(.18/.18),tt=Number((String(Me).length*Ge).toFixed(2));L.push({netId:Me,pinIds:de.map(He=>A.get(He)),netLabelWidth:tt})}}let U=(()=>{let Q={},de=new Set(L.map(oe=>oe.netId));for(let oe of e.source_net.list().filter(Me=>!Me.subcircuit_id||O.has(Me.subcircuit_id)))oe.name&&de.has(oe.name)&&(oe.is_ground||oe.name.toLowerCase().startsWith("gnd")?Q[oe.name]=["y-"]:oe.is_power||oe.name.toLowerCase().startsWith("v")?Q[oe.name]=["y+"]:Q[oe.name]=["x-","x+"]);return Q})();return{inputProblem:{chips:b,directConnections:W,netConnections:L,availableNetLabelOrientations:U,maxMspPairDistance:r._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:E,pairKeyToSourceTraceId:re,sckToSourceNet:a,sckToUserNetId:s,userNetIdToSck:j,allSourceAndSchematicPortIdsInScope:B,schPortIdToSourcePortId:w,displayLabelTraces:x,allScks:l}}var Qi=1e-6;function MBe(r){let e=Math.abs(r.to.x-r.from.x),a=Math.abs(r.to.y-r.from.y);return e>=a}function WS(r,e){return Math.hypot(e.x-r.x,e.y-r.y)}function OBe(r,e,a){return{x:r.x+(e.x-r.x)*a,y:r.y+(e.y-r.y)*a}}function LBe(r,e,a){let s=WS(r,e);if(s<Qi)return 0;let l=((a.x-r.x)*(e.x-r.x)+(a.y-r.y)*(e.y-r.y))/((e.x-r.x)*(e.x-r.x)+(e.y-r.y)*(e.y-r.y));return Math.max(0,Math.min(1,l))*s}function $S(r,e,a,s){return r*s-e*a}function pXt(r,e,a,s){let l={x:e.x-r.x,y:e.y-r.y},d={x:s.x-a.x,y:s.y-a.y},x=$S(l.x,l.y,d.x,d.y),f={x:a.x-r.x,y:a.y-r.y},m=$S(f.x,f.y,l.x,l.y);if(Math.abs(x)<Qi&&Math.abs(m)<Qi||Math.abs(x)<Qi&&Math.abs(m)>=Qi)return null;let D=$S(f.x,f.y,d.x,d.y)/x,b=$S(f.x,f.y,l.x,l.y)/x;return D<-Qi||D>1+Qi||b<-Qi||b>1+Qi?null:{x:r.x+D*l.x,y:r.y+D*l.y}}function xXt(r,e=Qi){if(r.length===0)return r;r.sort((l,d)=>l.start-d.start);let a=[],s={...r[0]};for(let l=1;l<r.length;l++){let d=r[l];d.start<=s.end+e?s.end=Math.max(s.end,d.end):(a.push(s),s={...d})}return a.push(s),a}function fXt(r,e,a){let s=WS(r.from,r.to);if(s<Qi||e.length===0)return[r];let l=a/2,d=e.map(E=>({start:Math.max(0,E-l),end:Math.min(s,E+l)})).filter(E=>E.end-E.start>Qi),x=xXt(d),f=[],m=0,D={x:r.to.x-r.from.x,y:r.to.y-r.from.y},b=(E,A,B)=>{if(A-E<=Qi)return;let w=E/s,P=A/s;f.push({from:OBe(r.from,r.to,w),to:OBe(r.from,r.to,P),...B?{is_crossing:!0}:{}})};for(let E of x)E.start-m>Qi&&b(m,E.start,!1),b(E.start,E.end,!0),m=E.end;return s-m>Qi&&b(m,s,!1),f.length>0?f:[r]}function hXt(r,e={}){let a=e.crossSegmentLength??.075,s=e.tolerance??Qi,l=new Map,d=m=>`${m.traceIdx}:${m.edgeIdx}`,x=m=>r[m.traceIdx].edges[m.edgeIdx];for(let m=0;m<r.length;m++){let D=r[m];for(let b=0;b<D.edges.length;b++){let E=D.edges[b];for(let A=m;A<r.length;A++){let B=r[A];for(let w=A===m?b+1:0;w<B.edges.length;w++){let P=B.edges[w],j=pXt(E.from,E.to,P.from,P.to);if(!j)continue;let O=WS(E.from,E.to),q=WS(P.from,P.to);if(O<s||q<s)continue;let ee=LBe(E.from,E.to,j),W=LBe(P.from,P.to,j),re=ee<=s||Math.abs(O-ee)<=s||Number.isNaN(ee),L=W<=s||Math.abs(q-W)<=s||Number.isNaN(W);if(!re&&!L){let K=MBe(E),U=MBe(P),J;if(K!==U)J=K;else{let oe=Math.abs(E.to.x-E.from.x),Me=Math.abs(E.to.y-E.from.y),Ne=Math.abs(P.to.x-P.from.x),Ge=Math.abs(P.to.y-P.from.y),tt=oe-Me,He=Ne-Ge;J=tt===He?!0:tt>He}let Q=d({traceIdx:J?m:A,edgeIdx:J?b:w}),de=l.get(Q)??[];de.push(J?ee:W),l.set(Q,de)}}}}}let f=r.map(m=>({source_trace_id:m.source_trace_id,edges:[]}));for(let m=0;m<r.length;m++){let D=r[m];for(let b=0;b<D.edges.length;b++){let E=d({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,j)=>P-j),w=fXt(D.edges[b],B,a);f[m].edges.push(...w)}}return f}var al=1e-6;function KS(r,e,a=al){return Math.abs(r-e)<=a}function Hg(r,e,a=al){return KS(r.x,e.x,a)&&KS(r.y,e.y,a)}function $Be(r,e,a,s=al){let l=Math.min(e.x,a.x)-s,d=Math.max(e.x,a.x)+s,x=Math.min(e.y,a.y)-s,f=Math.max(e.y,a.y)+s;return r.x<l||r.x>d||r.y<x||r.y>f?!1:Math.abs((a.x-e.x)*(r.y-e.y)-(a.y-e.y)*(r.x-e.x))<=s}function zBe(r,e=al){let a=new Map;for(let s of r){let l=`${s.x.toFixed(6)},${s.y.toFixed(6)}`;a.has(l)||a.set(l,s)}return Array.from(a.values())}function qBe(r){return{x:r.to.x-r.from.x,y:r.to.y-r.from.y}}function HW(r,e,a=al){let s=qBe(r),l=qBe(e),d=Math.hypot(s.x,s.y),x=Math.hypot(l.x,l.y);if(d<a||x<a)return!0;let f=s.x*l.y-s.y*l.x;return Math.abs(f)<=a*d*x}function GF(r,e,a=al){return r.edges.filter(s=>Hg(s.from,e,a)||Hg(s.to,e,a))}function UBe(r,e,a=al){for(let s of r.edges){if(Hg(s.from,e,a))return s.from;if(Hg(s.to,e,a))return s.to}return null}function mXt(r,e,a=al){let s=Hg(r.from,e,a)||KS(r.from.x,e.x,a)&&KS(r.from.y,e.y,a)?r.to:r.from,l=s.x-e.x,d=s.y-e.y;return Math.abs(l)<a&&Math.abs(d)<a?null:Math.abs(l)>=Math.abs(d)?l>=0?"right":"left":d>=0?"up":"down"}function Vg(r,e,a=al){let s=GF(r,e,a);if(s.length<2)return null;let l=s.map(E=>mXt(E,e,a)),d=l.includes("up"),x=l.includes("down"),f=l.includes("left"),m=l.includes("right"),D=d?"up":x?"down":null,b=m?"right":f?"left":null;return D&&b?`${D}-${b}`:null}function gXt(r,e={}){let a=e.tolerance??al,s={};for(let d of r)s[d.source_trace_id]=[];let l=r.map(d=>{let x=[];for(let f of d.edges)x.push(f.from,f.to);return zBe(x,a)});for(let d=0;d<r.length;d++){let x=r[d],f=l[d];for(let m=d+1;m<r.length;m++){let D=r[m],b=l[m];for(let E of f)for(let A of b)if(Hg(E,A,a)){let B=GF(x,E,a),w=GF(D,A,a),P=B.some(ee=>w.some(W=>!HW(ee,W,a))),j=Vg(x,E,a),O=Vg(D,A,a);P&&!(j!==null&&O!==null&&j===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($Be(E,A.from,A.to,a)){let w=GF(x,E,a).some(ee=>!HW(ee,A,a)),P=Vg(x,E,a),j=UBe(D,E,a*1e3),O=j?Vg(D,j,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($Be(E,A.from,A.to,a)){let w=GF(D,E,a).some(ee=>!HW(A,ee,a)),P=Vg(D,E,a),j=UBe(x,E,a*1e3),O=j?Vg(x,j,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 d of Object.keys(s))s[d]=zBe(s[d],a);return s}var WW=(0,f9e.default)("Group_doInitialSchematicTraceRender");function DXt(r){let{group:e,solver:a,pinIdToSchematicPortId:s,userNetIdToSck:l}=r,{db:d}=e.root,x=a.traceOverlapShiftSolver?.correctedTraceMap,f=[];WW(`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){WW(`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),j=s.get(b.pins[1]?.pinId);if(P&&j){for(let O of[P,j])d.schematic_port.get(O)&&d.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})}WW(`Applying ${f.length} traces from SchematicTraceSolver output`);let m=hXt(f.map(b=>({source_trace_id:b.source_trace_id,edges:b.edges}))),D=gXt(m);for(let b of m)d.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 yXt=r=>{switch(r){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"}},bXt=r=>{for(let a of r){let s=a._getDirectlyConnectedTraces();for(let l of s){let d=l._parsedProps.schDisplayLabel;if(d)return{name:d,wasAssignedDisplayLabel:!0}}}return{name:r.map(a=>a._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},KW=(0,h9e.default)("Group_doInitialSchematicTraceRender");function FXt(r){let{group:e,solver:a,sckToSourceNet:s,allScks:l,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,userNetIdToSck:f,pinIdToSchematicPortId:m,schematicPortIdsWithPreExistingNetLabels:D,schematicPortIdsWithRoutedTraces:b}=r,{db:E}=e.root,A=a.netLabelPlacementSolver?.netLabelPlacements??[],B=a.mspConnectionPairSolver.globalConnMap;for(let w of A){KW(`processing placement: ${w.netId}`);let P=B.getIdsConnectedToNet(w.globalConnNetId).find(Q=>f.get(Q)),j=f.get(P),O=w.anchorPoint,q=w.orientation,ee=yXt(q),W=j?s.get(j):void 0,re=w.pinIds.map(Q=>m.get(Q));if(re.some(Q=>D.has(Q))){KW(`skipping net label placement for "${w.netId}" REASON:schematic port has pre-existing net label`);continue}if(W){let Q=W.name,de=sx({anchor_position:O,anchor_side:ee,text:Q});E.schematic_net_label.insert({text:Q,anchor_position:O,center:de,anchor_side:ee,...W?.source_net_id?{source_net_id:W.source_net_id}:{}});continue}let L=e.selectAll("port").filter(Q=>Q._getSubcircuitConnectivityKey()===j),{name:K,wasAssignedDisplayLabel:U}=bXt(L);if(!U&&re.some(Q=>b.has(Q))){KW(`skipping net label placement for "${w.netId}" REASON:schematic port has routed traces and no display label`);continue}let J=sx({anchor_position:O,anchor_side:ee,text:K});E.schematic_net_label.insert({text:K,anchor_position:O,center:J,anchor_side:ee})}}var EXt=({allSourceAndSchematicPortIdsInScope:r,group:e,schPortIdToSourcePortId:a,sckToSourceNet:s,pinIdToSchematicPortId:l,schematicPortIdsWithPreExistingNetLabels:d})=>{let{db:x}=e.root;for(let f of Array.from(r)){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=HF(m.facing_direction||"right")||"right",j=sx({anchor_position:m.center,anchor_side:P,text:w});x.schematic_net_label.insert({text:w,anchor_position:m.center,center:j,anchor_side:P,...A.source_net_id?{source_net_id:A.source_net_id}:{}})}},vXt=r=>{let e=new Set,a=r.selectAll("netlabel");for(let s of a){let l=s._getConnectedPorts();for(let d of l)d.schematic_port_id&&e.add(d.schematic_port_id)}return e},CXt=({solver:r,pinIdToSchematicPortId:e})=>{let a=r.schematicTraceLinesSolver.solvedTracePaths,s=new Set;for(let l of a)for(let d of l.pinIds){let x=e.get(d);x&&s.add(x)}return s},_Xt=(0,x9e.default)("Group_doInitialSchematicTraceRender"),AXt=r=>{if(!r.root?._featureMspSchematicTraceRouting||!r.isSubcircuit||r.root?.schematicDisabled)return;let{inputProblem:e,pinIdToSchematicPortId:a,pairKeyToSourceTraceId:s,sckToSourceNet:l,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,displayLabelTraces:f,allScks:m,userNetIdToSck:D}=dXt(r),b=vXt(r);_Xt.enabled&&r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(e,null,2)});let E=new wSe(e);E.solve();let A=CXt({solver:E,pinIdToSchematicPortId:a});DXt({group:r,solver:E,pinIdToSchematicPortId:a,userNetIdToSck:D}),FXt({group:r,solver:E,sckToSourceNet:l,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,pinIdToSchematicPortId:a,allScks:m,userNetIdToSck:D,schematicPortIdsWithPreExistingNetLabels:b,schematicPortIdsWithRoutedTraces:A}),EXt({group:r,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,sckToSourceNet:l,pinIdToSchematicPortId:a,schematicPortIdsWithPreExistingNetLabels:b})},Wg=class extends es{constructor(){super(...arguments);z(this,"pcb_group_id",null);z(this,"schematic_group_id",null);z(this,"subcircuit_id",null);z(this,"_hasStartedAsyncAutorouting",!1);z(this,"_asyncAutoroutingResult",null);z(this,"unnamedElementCounter",{})}get config(){return{zodProps:oAe,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=ZS(this.children);if(this.pcb_group_id){let l=s.width,d=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,d+=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??d),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,d=s("paddingX"),x=s("paddingY"),f=s("paddingLeft")??d??l,m=s("paddingRight")??d??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 d of l)this.add(new fK({for:d.pcb_port_selector,offsets:d.offsets}))}doInitialSourceAddConnectivityMapKey(){XGt(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,Gg.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,Gg.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),s=this._parsedProps,l=this._getAutorouterConfig(),d=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(`${d}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:nK({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(`${d}/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(`${d}/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(`${d}/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(`${d}/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 UF(`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,Gg.default)("tscircuit:core:_runLocalAutorouting");s(`[${this.getString()}] starting local autorouting`);let l=this._getAutorouterConfig(),{simpleRouteJson:d}=nK({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(s.enabled){let m=aH(d);m.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(m)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:d});let x;l.algorithmFn?x=await l.algorithmFn(d):x=new MGt(d,{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:d}),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,Gg.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(){AXt(this)}updatePcbTraceRender(){let e=(0,Gg.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 d=l._parsedProps;return d?.schX!==void 0||d?.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(){UGt(this)}_doInitialSchematicLayoutMatchpack(){GGt(this)}_doInitialSchematicLayoutGrid(){YGt(this)}_doInitialSchematicLayoutFlex(){HGt(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 d=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&&d>1?"pack":"none"}doInitialPcbLayout(){let e=this._getPcbLayoutMode();e==="grid"?this._doInitialPcbLayoutGrid():e==="pack"?this._doInitialPcbLayoutPack():e==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){WGt(this)}_doInitialPcbLayoutPack(){cXt(this)}_doInitialPcbLayoutFlex(){lXt(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,d=typeof a.schPadding=="number"?a.schPadding:0,x=typeof a.schPaddingLeft=="number"?a.schPaddingLeft:d,f=typeof a.schPaddingRight=="number"?a.schPaddingRight:d,m=typeof a.schPaddingTop=="number"?a.schPaddingTop:d,D=typeof a.schPaddingBottom=="number"?a.schPaddingBottom:d,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,d=-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),d=Math.max(d,f.centerY);let x=2;return{minX:a-x,maxX:s+x,minY:l-x,maxY:d+x}}_getAutorouterConfig(){let e=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return sXt(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(d=>d.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),d=s.text||l?.name||"";if(s.anchor_side==="top"&&/^gnd/i.test(d)){a.schematic_net_label.update(s.schematic_net_label_id,{symbol_name:"rail_down"});continue}s.anchor_side==="bottom"&&/^v/i.test(d)&&a.schematic_net_label.update(s.schematic_net_label_id,{symbol_name:"rail_up"})}}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(e){return super._repositionOnPcb(e)}},VBe=(r,e,a)=>{let s=Math.min(a,r/2,e/2),l=Math.max(1,Math.ceil(Math.PI/2*s)),d=Math.PI/2/l,x=r/2,f=e/2,m=[];m.push({x:-x+s,y:-f}),m.push({x:x-s,y:-f});for(let D=1;D<=l;D++){let b=-Math.PI/2+D*d;m.push({x:x-s+s*Math.cos(b),y:-f+s+s*Math.sin(b)})}m.push({x,y:f-s});for(let D=1;D<=l;D++){let b=0+D*d;m.push({x:x-s+s*Math.cos(b),y:f-s+s*Math.sin(b)})}m.push({x:-x+s,y:f});for(let D=1;D<=l;D++){let b=Math.PI/2+D*d;m.push({x:-x+s+s*Math.cos(b),y:f-s+s*Math.sin(b)})}m.push({x:-x,y:-f+s});for(let D=1;D<=l;D++){let b=Math.PI+D*d;m.push({x:-x+s+s*Math.cos(b),y:-f+s+s*Math.sin(b)})}return m},m9e=class extends Wg{constructor(){super(...arguments);z(this,"pcb_board_id",null);z(this,"_drcChecksComplete",!1);z(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:SY}}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,d=-1/0,x=-1/0,f=c9e(e,this.subcircuit_id),m=new Set([this.subcircuit_id,...f]),D=e.pcb_component.list().filter(re=>re.subcircuit_id&&m.has(re.subcircuit_id)),b=e.pcb_group.list().filter(re=>re.subcircuit_id&&m.has(re.subcircuit_id)),E=!1,A=(re,L,K)=>{L===0||K===0||(E=!0,s=Math.min(s,re.x-L/2),l=Math.min(l,re.y-K/2),d=Math.max(d,re.x+L/2),x=Math.max(x,re.y+K/2))};for(let re of D)A(re.center,re.width,re.height);for(let re of b)A(re.center,re.width,re.height);let B=2,w=E?d-s+B*2:0,P=E?x-l+B*2:0,j={x:E?(s+d)/2+(a.outlineOffsetX??0):a.outlineOffsetX??0,y:E?(l+x)/2+(a.outlineOffsetY??0):a.outlineOffsetY??0},O=a.width??w,q=a.height??P,ee=a.outline;!ee&&a.borderRadius!=null&&O>0&&q>0&&(ee=VBe(O,q,a.borderRadius));let W={width:O,height:q,center:j};ee&&(W.outline=ee.map(re=>({x:re.x+(a.outlineOffsetX??0),y:re.y+(a.outlineOffsetY??0)}))),e.pcb_board.update(this.pcb_board_id,W)}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(`
1038
- `),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,d={x:(a.pcbX??0)+(a.outlineOffsetX??0),y:(a.pcbY??0)+(a.outlineOffsetY??0)};if(a.outline){let m=a.outline.map(w=>w.x),D=a.outline.map(w=>w.y),b=Math.min(...m),E=Math.max(...m),A=Math.min(...D),B=Math.max(...D);s=E-b,l=B-A,d={x:(b+E)/2+(a.outlineOffsetX??0),y:(A+B)/2+(a.outlineOffsetY??0)}}let x=a.outline;!x&&a.borderRadius!=null&&s>0&&l>0&&(x=VBe(s,l,a.borderRadius));let f=e.pcb_board.insert({center:d,thickness:this.boardThickness,num_layers:this.allLayers.length,width:s,height:l,outline:x?.map(m=>({x:m.x+(a.outlineOffsetX??0),y:m.y+(a.outlineOffsetY??0)})),material:a.material});this.pcb_board_id=f.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 Si()}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=jSe(e.toArray());for(let d of a)e.pcb_trace_error.insert(d);let s=ISe(e.toArray());for(let d of s)e.pcb_port_not_connected_error.insert(d);let l=MSe(e.toArray());for(let d of l)e.pcb_component_outside_board_error.insert(d)}_emitRenderLifecycleEvent(e,a){super._emitRenderLifecycleEvent(e,a),a==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e})}},RXt=new Proxy({},{get:(r,e)=>e}),dd=RXt,g9e="rgba(132, 0, 0)",D9e=.12,y9e=class extends es{constructor(){super(...arguments);z(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:gAe,sourceFtype:dd.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:`${Ns(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${a}/${Ns(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 qc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new qc({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}},QS=class extends es{constructor(e){super(e);z(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:og,shouldRenderAsSchematicBox:!0}}initPorts(e={}){super.initPorts(e);let{_parsedProps:a}=this;if(a.externallyConnectedPins){let s=new Set;for(let[l,d]of a.externallyConnectedPins)s.add(l),s.add(d);for(let l of s)if(!this.children.find(x=>x instanceof Ni&&x.isMatchingAnyOf([l]))){let x=l.match(/^pin(\d+)$/);if(x){let f=parseInt(x[1]);this.add(new Ni({pinNumber:f,aliases:[l]}))}else this.add(new Ni({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 qc({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,d,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,d=B.providesVoltage),B.providesGround&&(l=E)}if(!s||!l||d===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:d})}},b9e=class extends QS{constructor(r){super(r)}get config(){return{...super.config,componentName:"Pinout",zodProps:uAe}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.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}},F9e=class extends es{constructor(){super(...arguments);z(this,"pos",this.portMap.pin1);z(this,"anode",this.portMap.pin1);z(this,"neg",this.portMap.pin2);z(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:IAe,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}},E9e=class extends es{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:lAe,sourceFtype:dd.simple_fuse}}_getSchematicSymbolDisplayValue(){let r=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,a=typeof r=="string"?parseFloat(r):r,s=typeof e=="string"?parseFloat(e):e;return`${Ns(a)}A / ${Ns(s)}V`}doInitialSourceRender(){let{db:r}=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=r.source_component.insert({name:this.name,ftype:dd.simple_fuse,current_rating_amps:a,voltage_rating_volts:s,display_current_rating:`${Ns(a)}A`,display_voltage_rating:`${Ns(s)}V`});this.source_component_id=l.source_component_id}},v9e=class extends es{constructor(){super(...arguments);z(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:BY,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}),d=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=d(f.start_pcb_port_id),f.end_pcb_port_id=d(f.end_pcb_port_id))}},C9e=class extends es{constructor(){super(...arguments);z(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 d=(e.bridgedPins??[]).flat().map(D=>this._getPinNumberFromBridgedPinName(D)).filter(D=>D!==null),x=d.length>0?Math.max(...d):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(d=>this._getPinNumberFromBridgedPinName(d)).filter(d=>d!==null))).sort((d,x)=>d-x):e.bridged&&a&&(l=Array.from({length:a},(d,x)=>x+1)),l.length>0&&(s+=`_bridged${l.join("")}`),{schematicSymbolName:e.symbolName??s,componentName:"SolderJumper",zodProps:cAe,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}),d=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=d(f.start_pcb_port_id),f.end_pcb_port_id=d(f.end_pcb_port_id))}},_9e=class extends es{constructor(){super(...arguments);z(this,"pos",this.portMap.pin1);z(this,"anode",this.portMap.pin1);z(this,"neg",this.portMap.pin2);z(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:kAe,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}},A9e=class extends es{constructor(){super(...arguments);z(this,"pos",this.portMap.pin1);z(this,"positive",this.portMap.pin1);z(this,"neg",this.portMap.pin2);z(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:YAe,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Ni({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Ni({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db: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}},SXt=gs.extend({voltage:Us.optional(),frequency:Oc.optional(),peakToPeakVoltage:Us.optional(),waveShape:v.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Gn.optional(),dutyCycle:v.number().optional()}),R9e=class extends es{constructor(){super(...arguments);z(this,"terminal1",this.portMap.terminal1);z(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:SXt,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})}},S9e=class extends es{constructor(){super(...arguments);z(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:pAe,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${Ns(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 qc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new qc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new qc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new qc({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}},BXt=["leftedge","rightedge","topedge","bottomedge","center"],B9e=class extends qn{get config(){return{componentName:"Constraint",zodProps:yAe}}constructor(r){if(super(r),("xdist"in r||"ydist"in r)&&!("edgeToEdge"in r)&&!("centerToCenter"in r))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in r&&r.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let r=[],e=this.getPrimitiveContainer();function a(s){let l=s.split(" ").pop(),d=BXt.includes(l)?l:void 0,x=d?s.replace(` ${d}`,""):s,f=e.selectOne(x,{pcbPrimitive:!0});f&&r.push({selector:s,component:f,componentSelector:x,edge:d})}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:r}}},w9e=class extends qn{constructor(){super(...arguments);z(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:LAe}}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 d=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=as(d,{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}},T9e=class extends qn{get config(){return{componentName:"FabricationNoteText",zodProps:OAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:r}=this.root,{_parsedProps:e}=this,a=this.getPrimitiveContainer(),s=this.getSubcircuit();r.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})}},P9e=class extends Wg{constructor(r){super({...r,subcircuit:!0})}},I9e=class extends Wg{constructor(r){super({...r,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:r}=this.root,e=this._parsedProps;if(!this.pcb_group_id)return;let a=r.pcb_group.get(this.pcb_group_id),s=e.paddingLeft??e.padding??0,l=e.paddingRight??e.padding??0,d=e.paddingTop??e.padding??0,x=e.paddingBottom??e.padding??0;r.pcb_group.update(this.pcb_group_id,{width:a.width+s+l,height:a.height+d+x,center:{x:a.center.x+(l-s)/2,y:a.center.y+(d-x)/2}})}},j9e=class extends qn{constructor(){super(...arguments);z(this,"pcb_breakout_point_id",null);z(this,"matchedPort",null);z(this,"matchedNet",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:qAe}}_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(),d=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:d?.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}}},k9e=class extends qn{constructor(){super(...arguments);z(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:SAe}}_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 d=l[0]._getGlobalSchematicPositionBeforeLayout(),x=d.x-s.x,f=d.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=as(this.parent?.computeSchematicGlobalTransform?.()??Si(),{x:0,y:0});return Ma(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()}`),d=a.anchorSide??"right",x=sx({anchor_position:s,anchor_side:d,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&&uK(this,[`net.${e.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let e=this._resolveConnectsTo();if(e)for(let a of e)this.add(new qc({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(q=>q.connected_source_net_ids?.includes(f.source_net_id)&&q.connected_source_port_ids?.includes(D.source_port_id??""));if(O&&(b=e.schematic_trace.list().some(q=>q.source_trace_id===O.source_trace_id)),b)continue}let E=D._getGlobalSchematicPositionAfterLayout(),A=eK(D.facingDirection??"right")??"x+",B=dg({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,j;if(f?.source_net_id&&D.source_port_id){let O=e.source_trace.list().find(q=>q.connected_source_net_ids?.includes(f.source_net_id)&&q.connected_source_port_ids?.includes(D.source_port_id));P=O?.source_trace_id,j=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:j}),e.schematic_port.update(D.schematic_port_id,{is_connected:!0})}}},N9e=class extends qn{constructor(){super(...arguments);z(this,"pcb_silkscreen_circle_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:s4e}}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 d=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}}},M9e=class extends qn{constructor(){super(...arguments);z(this,"pcb_silkscreen_rect_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:a4e}}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 d=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:d?.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}}},O9e=class extends qn{constructor(){super(...arguments);z(this,"pcb_silkscreen_line_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:n4e}}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 d=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:d?.subcircuit_id??void 0,pcb_group_id:d?.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}}},L9e=class extends qn{constructor(e){super(e);z(this,"pcb_via_id",null);z(this,"matchedPort",null);z(this,"isPcbPrimitive",!0);z(this,"source_manually_placed_via_id",null);let a=this._getLayers();this._parsedProps.layers=a,this.initPorts()}get config(){return{componentName:"Via",zodProps:$Ae}}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 Ni({name:s,layer:s});l.registerMatch(this),this.add(l)}let a=new Ni({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(),d=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=d.pcb_component_id}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getGroup(),l=this.getSubcircuit(),d=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=d.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(),d=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=d.pcb_via_id}},$9e=class extends qn{constructor(){super(...arguments);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:VAe}}getPcbSize(){return{width:0,height:0}}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit().selectOne(a.connectsTo);if(!s||!s.source_net_id){this.renderError(`Net "${a.connectsTo}" not found for copper pour`);return}let l=e.pcb_board.list()[0];if(!l){this.renderError("No board found for copper pour");return}let d;l.outline&&l.outline.length>0?d=new se.Polygon(l.outline.map(B=>se.point(B.x,B.y))):d=new se.Polygon(new se.Box(l.center.x-l.width/2,l.center.y-l.height/2,l.center.x+l.width/2,l.center.y+l.height/2).toPoints());let x=eu(e.toArray()),f=pK(e.toArray(),x).filter(B=>B.layers.includes(a.layer));for(let B of e.pcb_trace.list())if(B.route)for(let w=0;w<B.route.length-1;w++){let P=B.route[w],j=B.route[w+1];if(P.route_type!=="wire"||j.route_type!=="wire"||P.layer!==a.layer)continue;let O=P.width;if(O===0)continue;let q=Math.hypot(P.x-j.x,P.y-j.y);if(q===0)continue;let ee=(P.x+j.x)/2,W=(P.y+j.y)/2,re=Math.atan2(j.y-P.y,j.x-P.x)*180/Math.PI,K=s9e({center:{x:ee,y:W},width:q,height:O,rotation:re});for(let U of K)f.push({type:"rect",layers:[P.layer],center:U.center,width:U.width,height:U.height,connectedTo:B.source_trace_id?[B.source_trace_id]:[],obstacle_type:"trace"})}let m=[],D=[],b=a.traceMargin??.2,E=a.padMargin??.2;for(let B of f){if(B.connectedTo.some(O=>x.areIdsConnected(O,s.source_net_id)))continue;if(B.type==="oval"&&B.width===B.height){let O=B.width/2+E;D.push({center:B.center,radius:O});continue}if(B.type==="rect"&&B.width===B.height&&B.connectedTo.length===0){let O=B.width/2;D.push({center:B.center,radius:O});continue}let P=b,j=new se.Box(B.center.x-B.width/2-P,B.center.y-B.height/2-P,B.center.x+B.width/2+P,B.center.y+B.height/2+P);m.push(new se.Polygon(j.toPoints()))}let A=d;if(m.length>0){let B=m.reduce((w,P)=>se.BooleanOperations.unify(w,P));B&&!B.isEmpty()&&(A=se.BooleanOperations.subtract(d,B))}Array.isArray(A)||(A=[A]);for(let B of A){let w=B.splitToIslands();for(let P of w){if(P.isEmpty())continue;let j=[...P.faces],O=j.find(L=>L.orientation()===se.ORIENTATION.CCW),q=j.filter(L=>L.orientation()===se.ORIENTATION.CW);if(!O)continue;if(!e.pcb_copper_pour){this.renderError("db.pcb_copper_pour not found. The database schema may be outdated.");return}let ee=L=>L.edges.map(K=>{let U={x:K.start.x,y:K.start.y};if(K.isArc){let J=Math.tan(K.shape.sweep/4);Math.abs(J)>1e-9&&(U.bulge=J)}return U});O.reverse();let W=ee(O),re=q.map(L=>(L.reverse(),{vertices:ee(L)}));for(let L of D){let K=se.point(L.center.x,L.center.y);P.contains(K)&&re.push({vertices:[{x:L.center.x,y:L.center.y-L.radius,bulge:1},{x:L.center.x,y:L.center.y+L.radius,bulge:1}]})}e.pcb_copper_pour.insert({shape:"brep",layer:a.layer,brep_shape:{outer_ring:{vertices:W},inner_rings:re},source_net_id:s.source_net_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0})}}})}},z9e=class extends es{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:AAe,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.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}},q9e=class extends es{_getPcbRotationBeforeLayout(){let r=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+r}get config(){return{componentName:"PinHeader",zodProps:RAe,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let r=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(r>0){let d;if(s)!e&&!a?d=`pinrow${r}_p${s}`:d=`pinrow${r}_p${s}_id${e}_od${a}`;else if(!e&&!a)d=`pinrow${r}`;else return null;return l!==!0&&(d+="_nopinlabels"),d}return null}initPorts(){let r=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<=r;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 Ni({pinNumber:e,name:s,aliases:[`pin${e}`,...l]}))}else this.add(new Ni({pinNumber:e,name:`pin${e}`}))}}_getSchematicPortArrangement(){let r=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:r},(s,l)=>`pin${l+1}`)}}:{rightSide:{direction:a?.rightSide?.direction??"top-to-bottom",pins:a?.rightSide?.pins??Array.from({length:r},(s,l)=>`pin${l+1}`)}}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.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 wXt(r){switch(r){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var U9e=class extends es{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??wXt(this.props.pinVariant),zodProps:mAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=e.pinVariant||"no_ground",s=r.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 r=`${Ns(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${r} / ${Ns(this._parsedProps.loadCapacitance)}F`:r}},V9e=class extends es{constructor(){super(...arguments);z(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:PAe,sourceFtype:dd.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${Ns(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:dd.simple_inductor,inductance:a.inductance,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}};function TXt(r){switch(r){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var G9e=class extends es{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??TXt(this.props.pinVariant),zodProps:fAe,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${Ns(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=e.pinVariant||"two_pin",s=r.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}},X9e=class extends es{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:BAe,sourceFtype:dd.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let r=ks[this._getSchematicSymbolNameOrThrow()],e=r.ports.find(D=>D.labels.includes("1")),a=r.ports.find(D=>D.labels.includes("2")),s=this.selectAll("port"),l=s.find(D=>D.props.pinNumber===1),d=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)&&(d.schematicSymbolPortDef=a);for(let[D,b]of[[2,d],[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:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({name:this.name,ftype:dd.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}},Y9e=class extends es{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:hAe,sourceFtype:"simple_crystal"}}initPorts(){let r=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:r})}_getSchematicSymbolDisplayValue(){let r=`${Ns(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${r} / ${Ns(this._parsedProps.loadCapacitance)}F`:r}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.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}},H9e=class extends es{constructor(){super(...arguments);z(this,"emitter",this.portMap.pin1);z(this,"collector",this.portMap.pin2);z(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:wAe,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}},W9e=class extends es{get config(){let r=this.props.mosfetMode==="depletion"?"d":"e",a=`${this.props.channelType}_channel_${r}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??a,zodProps:TAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.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}},K9e=class extends es{_getSwitchType(){let{spst:r,spdt:e,dpst:a,dpdt:s,type:l}=this._parsedProps??{};return s?"dpdt":r?"spst":e?"spdt":a?"dpst":l??"spst"}get config(){let r=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"}[r]??"spst_switch";return{componentName:"Switch",schematicSymbolName:this.props.symbolName??s,zodProps:MAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.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}},JW={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},J9e=class extends es{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:zAe,sourceFtype:dd.simple_test_point}}_getPropsWithDefaults(){let{padShape:r,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:d}=this._parsedProps;return!a&&e&&(a="through_hole"),a??(a="through_hole"),r??(r="circle"),a==="pad"?r==="circle"?s??(s=JW.SMT_CIRCLE_DIAMETER):r==="rect"&&(l??(l=JW.SMT_RECT_SIZE),d??(d=l)):a==="through_hole"&&(e??(e=JW.HOLE_DIAMETER)),{padShape:r,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:d}}_getImpliedFootprintString(){let{padShape:r,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:d}=this._getPropsWithDefaults();if(a==="through_hole")return`platedhole_d${e}`;if(a==="pad"){if(r==="circle")return`smtpad_circle_d${s}`;if(r==="rect")return`smtpad_rect_w${l}_h${d}`}throw new Error(`Footprint variant "${a}" with pad shape "${r}" not implemented`)}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,{padShape:a,holeDiameter:s,footprintVariant:l,padDiameter:d,width:x,height:f}=this._getPropsWithDefaults(),m=r.source_component.insert({ftype:dd.simple_test_point,name:this.name,supplier_part_numbers:e.supplierPartNumbers,footprint_variant:l,pad_shape:a,pad_diameter:d,hole_diameter:s,width:x,height:f,are_pins_interchangeable:!0});this.source_component_id=m.source_component_id}},Z9e=class extends qn{constructor(){super(...arguments);z(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:JAe}}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})}},Q9e=class extends qn{constructor(){super(...arguments);z(this,"isSchematicPrimitive",!0);z(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:KAe}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalSchematicPositionBeforeLayout(),l=this.getPrimitiveContainer()?.parent?.schematic_component_id,d=e.schematic_line.insert({schematic_component_id:l,x1:a.x1+s.x,y1:a.y1+s.y,x2:a.x2+s.x,y2:a.y2+s.y,stroke_width:D9e,color:g9e,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=d.schematic_line_id}},ewe=class extends qn{constructor(){super(...arguments);z(this,"isSchematicPrimitive",!0);z(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:WAe}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalSchematicPositionBeforeLayout(),l=this.getPrimitiveContainer()?.parent?.schematic_component_id,d=e.schematic_rect.insert({center:{x:a.center.x+s.x,y:a.center.y+s.y},width:a.width,height:a.height,stroke_width:D9e,color:g9e,is_filled:a.isFilled,schematic_component_id:l,is_dashed:a.isDashed,rotation:a.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=d.schematic_rect_id}};function PXt({anchor:r,x:e,y:a,width:s,height:l,isInside:d}){switch(r){case"top_left":return{x:e,y:a+l,textAnchor:d?"top_left":"bottom_left"};case"top_center":return{x:e+s/2,y:a+l,textAnchor:d?"top_center":"bottom_center"};case"top_right":return{x:e+s,y:a+l,textAnchor:d?"top_right":"bottom_right"};case"center_left":return{x:e,y:a+l/2,textAnchor:d?"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:d?"center_right":"center_left"};case"bottom_left":return{x:e,y:a,textAnchor:d?"bottom_left":"top_left"};case"bottom_center":return{x:e+s/2,y:a,textAnchor:d?"bottom_center":"top_center"};case"bottom_right":return{x:e+s,y:a,textAnchor:d?"bottom_right":"top_right"};default:return{x:e+s/2,y:a+l,textAnchor:"center"}}}var twe=class extends qn{constructor(){super(...arguments);z(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:HAe,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,d=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,j;if(D){let q=a.overlay.map(ot=>({selector:ot,port:this.getSubcircuit().selectOne(ot,{type:"port"})})).filter(({port:ot})=>ot!=null).map(({port:ot})=>({position:ot._getGlobalSchematicPositionAfterLayout()}));if(q.length===0)return;let ee=q.map(ot=>ot.position.x),W=q.map(ot=>ot.position.y),re=Math.min(...ee),L=Math.max(...ee),K=Math.min(...W),U=Math.max(...W),J=L-re,Q=U-K,de=J===0?s:0,oe=Q===0?s:0,Me=f+de/2,Ne=m+de/2,Ge=d+oe/2,tt=x+oe/2,He=re-Me,$t=L+Ne,bt=K-tt,ct=U+Ge;E=$t-He,A=ct-bt,B=He+(a.schX??0),w=bt+(a.schY??0),P=B+E/2,j=w+A/2}else if(b){E=a.width,A=a.height;let O=this._getGlobalSchematicPositionBeforeLayout();P=O.x,j=O.y,B=P-E/2,w=j-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,q=.1,ee=a.titleAlignment,W=PXt({anchor:ee,x:B,y:w,width:E,height:A,isInside:O}),re,L,K=W.textAnchor;O?(re=ee.includes("top")?-q:ee.includes("bottom")?q:0,L=ee.includes("left")?q:ee.includes("right")?-q:0):(re=ee.includes("top")?q:ee.includes("bottom")?-q:0,L=ee.includes("center_left")?-q:ee.includes("center_right")?q:0);let U=W.x+L,J=W.y+re;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})}}},rwe=class extends qn{constructor(){super(...arguments);z(this,"isSchematicPrimitive",!0);z(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:ZAe}}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=[],d=0;for(let A of s){let B=A.children.filter(w=>w.componentName==="SchematicCell");d=Math.max(d,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(j=>j.componentName==="SchematicCell"),P=0;for(let j=0;j<w.length;j++){for(;l[A][P];)P++;let O=w[j],q=O._parsedProps.colSpan??1,ee=O._parsedProps.rowSpan??1;for(let W=0;W<ee;W++)for(let re=0;re<q;re++)l[A+W]||(l[A+W]=[]),l[A+W][P+re]=O;P+=q}}d=Math.max(0,...l.map(A=>A.length));let x=s.map((A,B)=>A._parsedProps.height??1),f=Array.from({length:d},(A,B)=>{let w=0;for(let P=0;P<s.length;P++){let j=l[P]?.[B];if(j){let O=j._parsedProps.text??j._parsedProps.children,q=j._parsedProps.width??(O?.length??2)*.5;q>w&&(w=q)}}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<d;w++){let P=l[A]?.[w];if(P&&!b.has(P)){b.add(P);let j=P._parsedProps,O=j.rowSpan??1,q=j.colSpan??1,ee=0;for(let re=0;re<q;re++)ee+=f[w+re];let W=0;for(let re=0;re<O;re++)W+=x[A+re];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+q-1,text:j.text??j.children,center:{x:m.x+B+ee/2,y:m.y-E-W/2},width:ee,height:W,horizontal_align:j.horizontalAlign,vertical_align:j.verticalAlign,font_size:j.fontSize??a.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}f[w]&&(B+=f[w])}E+=x[A]}}},nwe=class extends qn{constructor(){super(...arguments);z(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:QAe}}},awe=class extends qn{constructor(){super(...arguments);z(this,"isSchematicPrimitive",!0);z(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:e4e}}},swe=class extends qn{constructor(){super(...arguments);z(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:_Ae}}},IXt={name:"@tscircuit/core",type:"module",version:"0.0.736",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"'},devDependencies:{"@biomejs/biome":"^1.8.3","@tscircuit/capacity-autorouter":"^0.0.107","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.67","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.21","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.335","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.37","@tscircuit/simple-3d-svg":"^0.0.41","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.260","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-simple-3d":"^0.0.8","circuit-to-svg":"^0.0.196",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.201","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.37","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Kg=class{constructor({platform:r,projectUrl:e}={}){z(this,"firstChild",null);z(this,"children");z(this,"db");z(this,"root",null);z(this,"isRoot",!0);z(this,"schematicDisabled",!1);z(this,"pcbDisabled",!1);z(this,"pcbRoutingDisabled",!1);z(this,"_featureMspSchematicTraceRouting",!0);z(this,"name");z(this,"platform");z(this,"projectUrl");z(this,"_hasRenderedAtleastOnce",!1);z(this,"_eventListeners",{});this.children=[],this.db=ua([]),this.root=this,this.platform=r,this.projectUrl=e,this.pcbDisabled=r?.pcbDisabled??!1}add(r){let e;(0,iwe.isValidElement)(r)?e=KBe(r):e=r,this.children.push(e)}_getBoard(){return this.children.find(r=>r.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 r=new Wg({subcircuit:!0});r.parent=this,r.addAll(this.children),this.children=[r],this.firstChild=r}render(){this.firstChild||this._guessRootComponent();let{firstChild:r,db:e}=this;if(!r)throw new Error("RootCircuit has no root component");r.parent=this,r.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(r=>r._hasIncompleteAsyncEffects()?!0:r.children.some(e=>e._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(r){let e=await Promise.resolve().then(()=>(FBe(),bBe)).catch(a=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
1037
+ ${s.stack}`),a.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:r,componentDisplayName:this.getString(),phase:a.phase,error:s.toString()})})}_emitRenderLifecycleEvent(r,e){PVt(`${r}:${e} ${this.getString()}`);let a=`renderable:renderLifecycle:${r}:${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(r=>!r.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(r){for(let e of this._asyncEffects)if(!e.complete&&e.phase===r)return!0;for(let e of this.children)if(e._hasIncompleteAsyncEffectsInSubtreeForPhase(r))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(r=>r.getRenderGraph())}}runRenderCycle(){for(let r of ld)this.runRenderPhaseForChildren(r),this.runRenderPhase(r)}runRenderPhase(r){this._currentRenderPhase=r;let e=this.renderPhaseStates[r],a=e.initialized,s=e.dirty;if(!a&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&a){this._emitRenderLifecycleEvent(r,"start"),this?.[`remove${r}`]?.(),e.initialized=!1,e.dirty=!1,this._emitRenderLifecycleEvent(r,"end");return}let l=ld.indexOf(r)-1;if(l>=0){let x=ld[l];if(this._asyncEffects.filter(m=>m.phase===x).some(m=>!m.complete))return}let d=IVt[r]||[];for(let x of d)if(this._hasIncompleteAsyncEffectsInSubtreeForPhase(x))return;if(this._emitRenderLifecycleEvent(r,"start"),a){s&&(this?.[`update${r}`]?.(),e.dirty=!1),this._emitRenderLifecycleEvent(r,"end");return}e.dirty=!1,this?.[`doInitial${r}`]?.(),e.initialized=!0,this._emitRenderLifecycleEvent(r,"end")}runRenderPhaseForChildren(r){for(let e of this.children)e.runRenderPhaseForChildren(r),e.runRenderPhase(r)}renderError(r){throw typeof r=="string"?new Error(r):new Error(JSON.stringify(r,null,2))}},VS={},WBe=r=>{let e=Object.fromEntries(Object.entries(r).map(([a,s])=>[a.toLowerCase(),s]));Object.assign(VS,r),Object.assign(VS,e)},kVt=class extends Error{constructor(r,e,a){let s,l=Object.keys(a).filter(m=>m!=="_errors"),d=[],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(" "))&&d.push(`pinLabels.${m} ("${E}" has leading or trailing spaces)`)}let f=l.map(m=>m==="pinLabels"&&d.length>0?d.join(", "):a[m]._errors[0]?`${m} (${a[m]._errors[0]})`:`${m} (${JSON.stringify(a[m])})`).join(", ");"name"in e?s=`Invalid props for ${r} "${e.name}": ${f}`:"footprint"in e&&typeof e.footprint=="string"?s=`Invalid props for ${r} (unnamed ${e.footprint} component): ${f}`:s=`Invalid props for ${r} (unnamed): ${f}`,super(s),this.componentName=r,this.originalProps=e,this.formattedError=a}};function VW(r,e){let a=e.match(/^#(\w+)/);if(a)return r.props.id===a[1];let s=e.match(/^\.(\w+)/);if(s)return r.isMatchingNameOrAlias(s[1]);let[l,...d]=e.split(/(?=[#.[])/);return l==="pin"&&(l="port"),l&&l!=="*"&&r.lowercaseComponentName!==l.toLowerCase()?!1:d.every(x=>{if(x.startsWith("#"))return r.props.id===x.slice(1);if(x.startsWith("."))return r.isMatchingNameOrAlias(x.slice(1));let f=x.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!f)return!0;let[,m,D]=f;return r.props[m].toString()===D})}var iK={isTag:r=>!0,getParent:r=>r.parent,getChildren:r=>r.children,getName:r=>r.lowercaseComponentName,getAttributeValue:(r,e)=>{if(e==="class"&&"getNameAndAliases"in r)return r.getNameAndAliases().join(" ");if(e==="name"&&r._parsedProps?.name)return r._parsedProps.name;if(r._parsedProps&&e in r._parsedProps){let s=r._parsedProps[e];return typeof s=="string"?s:s!=null?String(s):null}if(e in r){let s=r[e];return typeof s=="string"?s:s!=null?String(s):null}let a=r._attributeLowerToCamelNameMap;if(a){let s=a[e];if(s&&s in r){let l=r[s];return typeof l=="string"?l:l!=null?String(l):null}}return null},hasAttrib:(r,e)=>{if(e==="class")return!!r._parsedProps?.name;if(r._parsedProps&&e in r._parsedProps||e in r)return!0;let a=r._attributeLowerToCamelNameMap;if(a){let s=a[e];if(s&&s in r)return!0}return!1},getSiblings:r=>r.parent?r.parent.children:[],prevElementSibling:r=>{if(!r.parent)return null;let e=r.parent.children,a=e.indexOf(r);return a>0?e[a-1]:null},getText:()=>"",removeSubsets:r=>r.filter((e,a)=>!r.some((s,l)=>a!==l&&s!==e&&s.getDescendants().includes(e))),existsOne:(r,e)=>e.some(r),findAll:(r,e)=>{let a=[],s=l=>{r(l)&&a.push(l);for(let d of l.children)s(d)};for(let l of e)s(l);return a},findOne:(r,e)=>{for(let a of e){if(r(a))return a;let s=a.children;if(s.length>0){let l=iK.findOne(r,s);if(l)return l}}return null},equals:(r,e)=>r._renderId===e._renderId,isHovered:r=>!1,isVisited:r=>!1,isActive:r=>!1},NVt={...iK,getChildren:r=>r.children.filter(e=>!e.isSubcircuit)},EBe={...iK,getChildren:r=>r.children.filter(e=>e.isSubcircuit)},vBe=r=>{if(/net\.[^\s>]*\./.test(r))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(r))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(r)){let e=r.match(/net\.([^ >]+)/),a=e?e[1]:"";throw new Error(`Net name "${a}" cannot start with a number, try using a prefix like "VBUS1"`)}return r.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 d=/^\d+$/.test(l)?`pin${l}`:l;return`${a}.${s} > .${d}`}).trim()},GW={adapter:NVt,cacheResults:!0},qn=class extends sK{constructor(e){super(e);z(this,"parent",null);z(this,"children");z(this,"childrenPendingRemoval");z(this,"props");z(this,"_parsedProps");z(this,"externallyAddedAliases");z(this,"isPrimitiveContainer",!1);z(this,"canHaveTextChildren",!1);z(this,"source_group_id",null);z(this,"source_component_id",null);z(this,"schematic_component_id",null);z(this,"pcb_component_id",null);z(this,"cad_component_id",null);z(this,"fallbackUnassignedName");z(this,"_cachedSelectAllQueries",new Map);z(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 kVt(this.lowercaseComponentName,this.props,s.error.format())}get config(){return{componentName:"",zodProps:v.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)}_getPcbRotationBeforeLayout(){let{pcbRotation:e}=this.props;return typeof e=="string"?parseFloat(e):e??null}computePcbPropsTransform(){let{_parsedProps:e}=this,a=this._getPcbRotationBeforeLayout()??0;return js(Ma(e.pcbX??0,e.pcbY??0),Ip(a*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let e=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(e&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let a=this._getPcbRotationBeforeLayout()??0;return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),js(Ma(e.x,e.y),Ip(a*Math.PI/180)))}if(this.isPcbPrimitive){let a=this.getPrimitiveContainer();if(a&&a._parsedProps.layer==="bottom")return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),P3e(),this.computePcbPropsTransform())}return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),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 js(Ma(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){let e=this._getSchematicGlobalManualPlacementTransform(this);return e||js(this.parent?.computeSchematicGlobalTransform?.()??Si(),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 d=`${a}_horz`,x=`${a}_vert`,f=`${a}_up`,m=`${a}_down`,D=`${a}_left`,b=`${a}_right`;if(b in ks&&l===0)return b;if(f in ks&&l===90)return f;if(D in ks&&l===180)return D;if(m in ks&&l===270)return m;if(d in ks&&(l===0||l===180))return d;if(x in ks&&(l===90||l===270))return x;if(a in ks)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?ks[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(VW(e,l.selector)||e.props.name===l.selector)return as(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(VW(e,l.selector)||e.props.name===l.selector)return as(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((VW(e,s.selector)||e.props.name===s.selector)&&s.relative_to==="group_center")return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),Ma(s.center.x,s.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return as(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return as(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],d=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(d)&&a.includes(d))}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 d of s)for(let x of l){let f=[`.${d} > .${x}`,`.${d} .${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=vBe(e),s=lY(a,this,GW);if(s.length>0)return this._cachedSelectAllQueries.set(e,s),s;let[l,...d]=a.split(" "),x=e5(l,this,{adapter:EBe});if(!x)return[];let f=x.selectAll(d.join(" "));return this._cachedSelectAllQueries.set(e,f),f}selectOne(e,a){if(this._cachedSelectOneQueries.has(e))return this._cachedSelectOneQueries.get(e);let s=vBe(e);a?.port&&(a.type="port");let l=null;if(a?.type&&(l=lY(s,this,GW).find(D=>D.lowercaseComponentName===a.type)),l??(l=e5(s,this,GW)),l)return this._cachedSelectOneQueries.set(e,l),l;let[d,...x]=s.split(" "),f=e5(d,this,{adapter:EBe});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()}},MVt=class extends qn{constructor(r,e){super(r),this._parsedProps={...r,error:e,type:r.type||"unknown",component_name:r.name,error_type:"source_failed_to_create_component_error",message:e instanceof Error?e.message:String(e),pcbX:r.pcbX,pcbY:r.pcbY,schX:r.schX,schY:r.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:v.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let r=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:r,schematic_center:e})}}};function OVt(r,e){return new MVt(r,e)}function LVt(r,e){let a=r;return a.__tsci={...e},r}var $Vt={supportsMutation:!0,createInstance(r,e){let a=VS[r];if(!a)throw Object.keys(VS).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 "${r}". 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 LVt(new a(e),{})}catch(s){return OVt({...e,componentType:r},s)}},createTextInstance(r){return{__text:r}},appendInitialChild(r,e){r.add(e)},appendChild(r,e){r.add(e)},appendChildToContainer(r,e){r.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(r){return r},preparePortalMount(r){throw new Error("Function not implemented.")},scheduleTimeout(r,e){throw new Error("Function not implemented.")},cancelTimeout(r){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(r){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(r,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:r=>{throw new Error("Function not implemented.")},detachDeletedInstance:r=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>zS.DefaultEventPriority,getCurrentUpdatePriority:()=>zS.DefaultEventPriority,resolveUpdatePriority:()=>zS.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},OS=(0,YBe.default)($Vt),KBe=r=>{let e={children:[],props:{name:"$root"},add(d){d.parent=this,this.children.push(d)},computePcbGlobalTransform(){return Si()}},a=[],s=OS.createContainer(e,0,null,!1,null,"tsci",d=>{console.log("Error in createContainer"),console.error(d),a.push(d)},null);if(OS.updateContainerSync(r,s,null,()=>{}),OS.flushSyncWork(),a.length>0)throw a[0];let l=OS.getPublicRootInstance(s);return l||e.children[0]},YF=(r,e)=>{if(typeof r=="number")return r;if(r.startsWith("pin"))return Number(r.slice(3));if(!e)throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`);for(let a in e)if((Array.isArray(e[a])?e[a]:[e[a]]).includes(r))return Number(a.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`)},zVt=(r,e)=>{if(!r)return;let a={},s={};for(let[l,d]of Object.entries(r)){let x=YF(l,e);s[x]={...s[x],...d}}for(let[l,d]of Object.entries(s)){let x=`pin${l}`;a[x]={bottom_margin:d.bottomMargin,left_margin:d.leftMargin,right_margin:d.rightMargin,top_margin:d.topMargin}}return a},qVt=r=>{if(r){if("leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r)return{left_side:r.leftSide,right_side:r.rightSide,top_side:r.topSide,bottom_side:r.bottomSide};if("leftPinCount"in r||"rightPinCount"in r||"topPinCount"in r||"bottomPinCount"in r)return{left_size:r.leftPinCount,right_size:r.rightPinCount,top_size:r.topPinCount,bottom_size:r.bottomPinCount};if("leftSize"in r||"rightSize"in r||"topSize"in r||"bottomSize"in r)return{left_size:r.leftSize,right_size:r.rightSize,top_size:r.topSize,bottom_size:r.bottomSize}}};function JBe(r){let e=[];for(let a=0;a<r.length-1;a++)e.push([r[a],r[a+1]]);return e}var UVt=v.object({name:v.string().refine(r=>!/[+-]/.test(r),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),oK=class extends qn{constructor(){super(...arguments);z(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:UVt}}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"),d=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=d.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 d of l)if(d._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 d=JBe(l);for(let[x,f]of d){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 q=m[O];for(let ee=0;ee<D.length;ee++){let W=D[ee],re=Math.sqrt((q.x-W.x)**2+(q.y-W.y)**2);re<b&&(b=re,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}=Z_e(w.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[A.source_port_id,B.source_port_id]}])),j=P[0];if(!j){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(j)}}renderError(e){if(typeof e=="string")return super.renderError(e);this.root?.db.pcb_trace_error.insert(e)}},uK=(r,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=r.getSubcircuit();if(!s.selectOne(a)){let l=new oK({name:a.split("net.")[1]});s.add(l)}}},GS=class extends qn{constructor(){super(...arguments);z(this,"pcb_smtpad_id",null);z(this,"matchedPort",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:FAe}}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),d=Math.min(...s),x=Math.max(...s),f=Math.min(...l),m=Math.max(...l);return{width:x-d,height:m-f}}if(e.shape==="pill")return{width:e.width,height:e.height};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let 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(),d=this._getGlobalPcbPositionBeforeLayout(),x=s?._getGlobalPcbPositionBeforeLayout(),f=i4(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()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,x:d.x,y:d.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()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,x:d.x,y:d.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:d.x,y:d.y,ccw_rotation:b,port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,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+d.x,y:B.y+d.y})),port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):a.shape==="pill"&&(E=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"pill",x:d.x,y:d.y,radius:a.radius,height:a.height,width:a.width,port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,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),d=Math.sin(s),x=a.width/2,f=a.height/2,m=Math.abs(x*l)+Math.abs(f*d),D=Math.abs(x*d)+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),d=s.map(b=>b.y),x=Math.min(...l),f=Math.max(...l),m=Math.min(...d),D=Math.max(...d);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}}if(a.shape==="pill"){let s=a.width/2,l=a.height/2;return{center:{x:a.x,y:a.y},bounds:{left:a.x-s,top:a.y-l,right:a.x+s,bottom:a.y+l},width:a.width,height:a.height}}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)}},cK=class extends qn{constructor(){super(...arguments);z(this,"pcb_silkscreen_path_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:r4e}}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 d=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=as(d,{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 d=0,x=0;for(let b of l.route)d+=b.x,x+=b.y;d/=l.route.length,x/=l.route.length;let f=e.x-d,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,d=-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),d=Math.max(d,x.y);return{width:s-a,height:d-l}}},VVt=v.object({route:v.array(UA),source_trace_id:v.string().optional()}),lK=class extends qn{constructor(){super(...arguments);z(this,"pcb_trace_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:VVt}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer(),l=this.getSubcircuit(),{maybeFlipLayer:d}=this._getPcbPrimitiveFlippedHelpers(),x=this._computePcbGlobalTransformBeforeLayout(),f=a.route.map(D=>{let{x:b,y:E,...A}=D,B=as(x,{x:b,y:E});return D.route_type==="wire"&&D.layer?{...B,...A,layer:d(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,d=-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),d=Math.max(d,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),d=Math.max(d,x.y+x.width/2));return a===1/0||s===-1/0||l===1/0||d===-1/0?{width:0,height:0}:{width:s-a,height:d-l}}},Yg=class extends qn{constructor(){super(...arguments);z(this,"pcb_plated_hole_id",null);z(this,"matchedPort",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:dAe}}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,d=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:d?.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:d?.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:d?.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:d?.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,hole_offset_x:a.holeOffsetX,hole_offset_y:a.holeOffsetY});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:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:a.pcbRotation??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:d?.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:d?.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:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:a.holeOffsetX,hole_offset_y:a.holeOffsetY,rect_border_radius:a.rectBorderRadius??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,hole_offset_x:a.holeOffsetX,hole_offset_y:a.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:d?.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})}},XS=class extends qn{constructor(){super(...arguments);z(this,"pcb_keepout_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:UAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let e=this.getSubcircuit(),{db:a}=this.root,{_parsedProps:s}=this,l=this._getGlobalPcbPositionBeforeLayout(),d=i4(this._computePcbGlobalTransformBeforeLayout()),x=Math.abs(d.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)}},dK=class extends qn{constructor(){super(...arguments);z(this,"pcb_hole_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:EAe}}getPcbSize(){let{_parsedProps:e}=this,a=e.shape==="pill";return{width:a?e.width:e.diameter,height:a?e.height:e.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=this._getGlobalPcbPositionBeforeLayout(),d=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=d.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})}},JS=class extends qn{constructor(){super(...arguments);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:t4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer(),l=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:d}=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:d(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,d=a;return{width:l*a,height:d*a}}},XF=class extends qn{constructor(){super(...arguments);z(this,"pcb_cutout_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:bAe}}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,d=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:d,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:d,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=>as(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,d=-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),d=Math.max(d,x.y);return{width:s-a,height:d-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,d=1/0,x=-1/0;for(let f of a.points)s=Math.min(s,f.x),l=Math.max(l,f.x),d=Math.min(d,f.y),x=Math.max(x,f.y);return{center:{x:(s+l)/2,y:(d+x)/2},bounds:{left:s,top:x,right:l,bottom:d},width:l-s,height:x-d}}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,d=e.x-l.x,x=e.y-l.y,f=s.points.map(m=>({x:m.x+d,y:m.y+x}));a.pcb_cutout.update(this.pcb_cutout_id,{...s,points:f})}}}},GVt=({elm:r,pinLabels:e,layer:a,readableRotation:s,anchorAlignment:l})=>{let d=r.text.replace(/[{}]/g,"").toLowerCase(),x=d;if(Array.isArray(e)){let f=parseInt(d.replace(/[^\d]/g,""),10)-1;x=String(e[f]??d)}else typeof e=="object"&&(x=String(e[d]??d));return new JS({anchorAlignment:l||"center",text:x??d,layer:a||"top",fontSize:r.font_size+.2,pcbX:isNaN(r.anchor_position.x)?0:r.anchor_position.x,pcbY:r.anchor_position.y,pcbRotation:s??0})},XVt=(r,e)=>((-parseInt(r||"0",10)+(e??0))%360+360)%360,qS=({componentName:r,componentRotation:e,footprint:a,pinLabels:s,pcbPinLabels:l},d)=>{let x=[];for(let f of d)if(f.type==="pcb_smtpad"&&f.shape==="rect")x.push(new GS({pcbX:f.x,pcbY:f.y,layer:f.layer,shape:"rect",height:f.height,width:f.width,portHints:f.port_hints,rectBorderRadius:f.rect_border_radius}));else if(f.type==="pcb_smtpad"&&f.shape==="circle")x.push(new GS({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 cK({layer:f.layer,route:f.route,strokeWidth:f.stroke_width}));else if(f.type==="pcb_plated_hole")f.shape==="circle"?x.push(new Yg({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 Yg({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,rectBorderRadius:f.rect_border_radius,holeOffsetX:f.hole_offset_x,holeOffsetY:f.hole_offset_y})):f.shape==="pill"||f.shape==="oval"?x.push(new Yg({pcbX:f.x,pcbY:f.y,shape:f.shape,holeWidth:f.hole_width,holeHeight:f.hole_height,outerWidth:f.outer_width,outerHeight:f.outer_height,portHints:f.port_hints})):f.shape==="pill_hole_with_rect_pad"&&x.push(new Yg({pcbX:f.x,pcbY:f.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:f.hole_width,holeHeight:f.hole_height,rectPadWidth:f.rect_pad_width,rectPadHeight:f.rect_pad_height,portHints:f.port_hints,holeOffsetX:f.hole_offset_x,holeOffsetY:f.hole_offset_y}));else if(f.type==="pcb_keepout"&&f.shape==="circle")x.push(new XS({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 XS({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 dK({pcbX:f.x,pcbY:f.y,diameter:f.hole_diameter}));else if(f.type==="pcb_cutout")f.shape==="rect"?x.push(new XF({pcbX:f.center.x,pcbY:f.center.y,shape:"rect",width:f.width,height:f.height})):f.shape==="circle"?x.push(new XF({pcbX:f.center.x,pcbY:f.center.y,shape:"circle",radius:f.radius})):f.shape==="polygon"&&x.push(new XF({shape:"polygon",points:f.points}));else if(f.type==="pcb_silkscreen_text"){let m=XVt(e,f.ccw_rotation);a.includes("pinrow")&&f.text.includes("PIN")?x.push(GVt({elm:f,pinLabels:l??s,layer:f.layer,readableRotation:m,anchorAlignment:f.anchor_alignment})):x.push(new JS({anchorAlignment:f.anchor_alignment||"center",text:r,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 lK({route:f.route}));return x};function ZS(r){let e=1/0,a=1/0,s=-1/0,l=-1/0,d=!1;for(let m of r)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),d=!0}else if(m.children.length>0){let D=ZS(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),d=!0)}if(!d)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 ZBe(r){let e=1/0,a=1/0,s=-1/0,l=-1/0;for(let d of r){let x,f,m,D;if(d.type==="schematic_component")x=d.center?.x,f=d.center?.y,m=d.size?.width,D=d.size?.height;else if(d.type==="schematic_box")x=d.x,f=d.y,m=d.width,D=d.height;else if(d.type==="schematic_port")x=d.center?.x,f=d.center?.y,m=.2,D=.2;else if(d.type==="schematic_text")x=d.position?.x,f=d.position?.y,m=(d.text?.length??0)*.1,D=.2;else if(d.type==="schematic_line"){let b=d.x1??0,E=d.y1??0,A=d.x2??0,B=d.y2??0;x=(b+A)/2,f=(E+B)/2,m=Math.abs(A-b),D=Math.abs(B-E)}else d.type==="schematic_rect"&&(x=d.center?.x,f=d.center?.y,m=d.width,D=d.height);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 YVt(r,e){let a=e.x-r.x,s=e.y-r.y;return Math.abs(a)>Math.abs(s)?a>=0?"right":"left":s>=0?"up":"down"}var CBe=r=>{if(r.length<=1)return!0;let e=r.map(d=>{let x=d._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 d=0;d<e.length;d++)for(let x=d+1;x<e.length;x++){let f=e[d],m=e[x];a[d][x]=a[x][d]=!(f.right<m.left||f.left>m.right||f.bottom>m.top||f.top<m.bottom)}let s=new Set,l=d=>{s.add(d);for(let x=0;x<e.length;x++)a[d][x]&&!s.has(x)&&l(x)};return l(0),s.size===e.length},_Be=r=>{if(r.length===0)throw new Error("Cannot get center of empty PCB primitives array");let e=r.map(l=>l._getPcbCircuitJsonBounds().center).filter(Boolean),a=e.reduce((l,d)=>l+d.x,0),s=e.reduce((l,d)=>l+d.y,0);return{x:a/e.length,y:s/e.length}},HVt=v.object({name:v.string().optional(),pinNumber:v.number().optional(),aliases:v.array(v.string()).optional(),layer:v.string().optional(),layers:v.array(v.string()).optional()}),Ni=class extends qn{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);z(this,"source_port_id",null);z(this,"pcb_port_id",null);z(this,"schematic_port_id",null);z(this,"schematicSymbolPortDef",null);z(this,"matchedComponents");z(this,"facingDirection",null);z(this,"originDescription",null);a.originDescription&&(this.originDescription=a.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:HVt}}_isBoardPinoutFromAttributes(){let e=this.parent;if(e?._parsedProps?.pinAttributes){let a=e._parsedProps.pinAttributes;for(let s of this.getNameAndAliases())if(a[s]?.includeInBoardPinout)return!0}}_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(d=>d.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=js(this.parent.computeSchematicGlobalTransform(),Ma(-e.center.x,-e.center.y));return as(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 as(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??[]]))}_getMatchingPinAttributes(){let e=this.parent?._parsedProps?.pinAttributes;if(!e)return[];let a=[];for(let s of this.getNameAndAliases()){let l=e[s];l&&a.push(l)}return a}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(e=>e.includeInBoardPinout===!0)}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(d=>d.isPcbPrimitive);if(s.length===0)return;let l=null;if(s.length===1&&(l=s[0]._getPcbCircuitJsonBounds().center),s.length>1){if(!CBe(s))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${s.map(d=>d.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=_Be(s)}if(l){let d=this.getSubcircuit(),x=this._shouldIncludeInBoardPinout(),f=e.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...x?{is_board_pinout:!0}:{},...l,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=f.pcb_port_id}else{let d=s[0];throw new Error(`${d.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(f=>f.isPcbPrimitive);if(a.length===0)return;let s=null;if(a.length===1&&(s=a[0]._getPcbCircuitJsonBounds().center),a.length>1)try{CBe(a)&&(s=_Be(a))}catch{}if(!s)return;let l=this.getSubcircuit(),d=this._shouldIncludeInBoardPinout(),x=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,...d?{is_board_pinout:!0}:{},...s,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=x.pcb_port_id}doInitialSchematicPortRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer();if(!s||!this._hasSchematicPort())return;let l=s._getGlobalSchematicPositionBeforeLayout(),d=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:d,size:{width:.1,height:.1},label:"obstacle"}),x?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[x.side]:this.facingDirection=YVt(l,d);let m=e.source_port.get(this.source_port_id),D=[];for(let w of m?.port_hints??[])w.match(/^(pin)?\d+$/)||w.match(/^(left|right)/)&&!m?.name.match(/^(left|right)/)||D.push(w);let b;this.parent?.props?.showPinAliases&&D.length>0?b=D.join("/"):D.length>0&&(b=D[0]);let A={type:"schematic_port",schematic_component_id:this.parent?.schematic_component_id,center:d,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};for(let w of this._getMatchingPinAttributes())w.requiresPower&&(A.has_input_arrow=!0),w.providesPower&&(A.has_output_arrow=!0);let B=e.schematic_port.insert(A);this.schematic_port_id=B.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}`}},QBe=r=>{let e=r.find(a=>/^(pin)?\d+$/.test(a));return e?Number.parseInt(e.replace(/^pin/,"")):null};function qF(r,e){let a=QBe(r);if(!a)return null;let l=[...r.filter(d=>d.toString()!==a.toString()&&d!==`pin${a}`),...e?.additionalAliases?.[`pin${a}`]??[]];return new Ni({pinNumber:a,aliases:l})}var WVt=r=>{for(let e of["leftSide","rightSide","topSide","bottomSide"])if(e in r&&typeof r[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r},KVt=r=>{if(WVt(r))return{leftSize:r.leftSide?.pins.length??0,rightSize:r.rightSide?.pins.length??0,topSize:r.topSide?.pins.length??0,bottomSize:r.bottomSide?.pins.length??0};let{leftSize:e=0,rightSize:a=0,topSize:s=0,bottomSize:l=0}=r;return{leftSize:e,rightSize:a,topSize:s,bottomSize:l}};function e9e(r){let e=r;return e.leftSide!==void 0||e.rightSide!==void 0||e.topSide!==void 0||e.bottomSide!==void 0}var JVt=r=>{let e=r.portDistanceFromEdge??.4,a=r.schPortArrangement?KVt(r.schPortArrangement):null,s={left:0,right:0,top:0,bottom:0},l=r.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 d=({side:w,sideIndex:P,truePinIndex:j})=>{if(!r.schPortArrangement||!e9e(r.schPortArrangement))return j+1;let O={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[w],q=r.schPortArrangement?.[`${w}Side`]?.direction??O,ee=r.schPortArrangement?.[`${w}Side`]?.pins,W=P;return q!==O&&(W=ee.length-P-1),YF(ee[W],r.pinLabels)},x=[],f=0,m=0;for(let w=0;w<a.leftSize;w++){let P=d({side:"left",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.topMargin&&(f+=j.topMargin),x.push({trueIndex:m,pinNumber:P,side:"left",distanceFromOrthogonalEdge:f}),j?.bottomMargin&&(f+=j.bottomMargin),w===a.leftSize-1?s.left=f:f+=r.schPinSpacing,m++}f=0;for(let w=0;w<a.bottomSize;w++){let P=d({side:"bottom",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.leftMargin&&(f+=j.leftMargin),x.push({trueIndex:m,pinNumber:P,side:"bottom",distanceFromOrthogonalEdge:f}),j?.rightMargin&&(f+=j.rightMargin),w===a.bottomSize-1?s.bottom=f:f+=r.schPinSpacing,m++}f=0;for(let w=0;w<a.rightSize;w++){let P=d({side:"right",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.bottomMargin&&(f+=j.bottomMargin),x.push({trueIndex:m,pinNumber:P,side:"right",distanceFromOrthogonalEdge:f}),j?.topMargin&&(f+=j.topMargin),w===a.rightSize-1?s.right=f:f+=r.schPinSpacing,m++}f=0;for(let w=0;w<a.topSize;w++){let P=d({side:"top",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.rightMargin&&(f+=j.rightMargin),x.push({trueIndex:m,pinNumber:P,side:"top",distanceFromOrthogonalEdge:f}),j?.leftMargin&&(f+=j.leftMargin),w===a.topSize-1?s.top=f:f+=r.schPinSpacing,m++}let D=r.schWidth;if(D===void 0){D=Math.max(s.top+r.schPinSpacing*2,s.bottom+r.schPinSpacing*2);let w=r.pinLabels?Math.max(...Object.values(r.pinLabels).map(j=>j.length*.1)):0,P=w>0?1.1:0;D=Math.max(D,w+P)}let b=r.schHeight;b||(b=Math.max(s.left+r.schPinSpacing*2,s.right+r.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:j}=w,O=E[j],q=A[j];return{x:O.x+P*q.x,y:O.y+P*q.y,...w}});return{getPortPositionByPinNumber(w){let P=B.find(j=>j.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}},ZVt=(0,t9e.default)("tscircuit:core:footprint"),r9e=class extends qn{get config(){return{componentName:"Footprint",zodProps:CAe}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let r=this.children.filter(E=>E.componentName==="Constraint");if(r.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=r.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 d=new ug,x={};function f(E){return E in x||(x[E]=new rd(E),d.addEditVariable(x[E],Oa.weak)),x[E]}for(let{selector:E,bounds:A}of s){let B=f(`${E}_x`),w=f(`${E}_y`);d.suggestValue(B,A.center.x),d.suggestValue(w,A.center.y)}for(let E of r){let A=E._parsedProps;if("xDist"in A){let{xDist:B,left:w,right:P,edgeToEdge:j,centerToCenter:O}=a(A),q=f(`${w}_x`),ee=f(`${P}_x`),W=l(w)?.bounds,re=l(P)?.bounds;if(O){let L=new Xa(ee,[-1,q]);d.addConstraint(new Vs(L,Ds.Eq,A.xDist,Oa.required))}else if(j){let L=new Xa(ee,-re.width/2,[-1,q],-W.width/2);d.addConstraint(new Vs(L,Ds.Eq,A.xDist,Oa.required))}}else if("yDist"in A){let{yDist:B,top:w,bottom:P,edgeToEdge:j,centerToCenter:O}=A,q=f(`${w}_y`),ee=f(`${P}_y`),W=l(w)?.bounds,re=l(P)?.bounds;if(O){let L=new Xa(q,[-1,ee]);d.addConstraint(new Vs(L,Ds.Eq,A.yDist,Oa.required))}else if(j){let L=new Xa(q,W.height/2,[-1,ee],-re.height/2);d.addConstraint(new Vs(L,Ds.Eq,A.yDist,Oa.required))}}else if("sameY"in A){let{for:B}=A;if(B.length<2)continue;let w=B.map(j=>f(`${j}_y`)),P=new Xa(...w.slice(1));d.addConstraint(new Vs(P,Ds.Eq,w[0],Oa.required))}else if("sameX"in A){let{for:B}=A;if(B.length<2)continue;let w=B.map(j=>f(`${j}_x`)),P=new Xa(...w.slice(1));d.addConstraint(new Vs(P,Ds.Eq,w[0],Oa.required))}}d.updateVariables(),ZVt.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`),j=w.value()-A/2,O=w.value()+A/2,q=P.value()+B/2,ee=P.value()-B/2;m.left=Math.min(m.left,j),m.right=Math.max(m.right,O),m.top=Math.max(m.top,q),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})}}},XW=v.union([v.number(),v.string()]),ABe=v.object({x:XW,y:XW,z:XW}),n9e=class extends qn{get config(){return{componentName:"CadModel",zodProps:XAe}}doInitialCadModelRender(){let r=this._findParentWithPcbComponent();if(!r||!r.pcb_component_id)return;let{db:e}=this.root,{boardThickness:a=0}=this.root?._getBoard()??{},s=r._getPcbCircuitJsonBounds(),l=e.pcb_component.get(r.pcb_component_id),d=this._parsedProps;if(!d||typeof d.modelUrl!="string")return;let x=ABe.parse({x:0,y:0,z:0});if(typeof d.rotationOffset=="number")x.z=Number(d.rotationOffset);else if(typeof d.rotationOffset=="object"){let A=ABe.parse(d.rotationOffset);x.x=Number(A.x),x.y=Number(A.y),x.z=Number(A.z)}let f=l5.parse({x:d.pcbX??0,y:d.pcbY??0,z:d.pcbZ??0,...typeof d.positionOffset=="object"?d.positionOffset:{}}),m=r.props.layer==="bottom"?"bottom":"top",D=new URL(d.modelUrl).pathname.split(".").pop()?.toLowerCase(),b={};D==="stl"?b.model_stl_url=this._addCachebustToModelUrl(d.modelUrl):D==="obj"?b.model_obj_url=this._addCachebustToModelUrl(d.modelUrl):D==="gltf"?b.model_gltf_url=this._addCachebustToModelUrl(d.modelUrl):D==="glb"?b.model_glb_url=this._addCachebustToModelUrl(d.modelUrl):D==="step"||D==="stp"?b.model_step_url=this._addCachebustToModelUrl(d.modelUrl):D==="wrl"||D==="vrml"?b.model_wrl_url=this._addCachebustToModelUrl(d.modelUrl):b.model_stl_url=this._addCachebustToModelUrl(d.modelUrl);let E=e.cad_component.insert({position:{x:s.center.x+Number(f.x),y:s.center.y+Number(f.y),z:(m==="bottom"?-a/2:a/2)+Number(f.z)},rotation:{x:Number(x.x),y:(m==="top"?0:180)+Number(x.y),z:m==="bottom"?-((l?.rotation??0)+Number(x.z))+180:(l?.rotation??0)+Number(x.z)},pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,model_unit_to_mm_scale_factor:typeof d.modelUnitToMmScale=="number"?d.modelUnitToMmScale:void 0,...b});this.cad_component_id=E.cad_component_id}_findParentWithPcbComponent(){let r=this.parent;for(;r&&!r.pcb_component_id;)r=r.parent;return r}_addCachebustToModelUrl(r){if(!r||!r.includes("modelcdn.tscircuit.com"))return r;let e=this.root?.getClientOrigin()??"";return`${r}${r.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(e)}`}},a9e=class extends qn{constructor(){super(...arguments);z(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:GAe}}},QVt=(r,e)=>{if(!r)return;let a={};for(let[s,l]of Object.entries(r)){let d=YF(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${d}`]={...a[`pin${d}`],...x}}return a},RBe=class{constructor({input:r}){z(this,"input");this.input=r}solveAndMapToTraces(){let r=[];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}]};r.push(l)}return r}},eGt=r=>{let e=Math.min(...r.map(d=>d.center.x)),a=Math.max(...r.map(d=>d.center.x)),s=Math.min(...r.map(d=>d.center.y)),l=Math.max(...r.map(d=>d.center.y));return{minX:e,maxX:a,minY:s,maxY:l}},SBe=["top","bottom","inner1","inner2"],US=(r,e=[])=>{let a=[];if(e.length===0){let f=r[0].layers;for(let m of f)a.push(...US(r.slice(1),[m]));return a}if(r.length===0)return[];let s=r[0],l=s.via||s.optional_via,d=e[e.length-1];if(r.length===1){let f=s;return f.layers&&l?f.layers.map(m=>({layer_path:[...e,m]})):f.layers?.includes(d)?[{layer_path:[...e,d]}]:[]}if(!l)return s.layers&&!s.layers.includes(d)?[]:US(r.slice(1),e.concat([d]));let x=(s.optional_via?SBe:SBe.filter(f=>f!==d)).filter(f=>!s.layers||s.layers?.includes(f));for(let f of x)a.push(...US(r.slice(1),e.concat(f)));return a};function BBe(r){let e={x:r.to.x-r.from.x,y:r.to.y-r.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 qg(r,e){return Math.hypot(r.x-e.x,r.y-e.y)}var tGt=r=>{if(r.length===1)return r[0];if(r.some(m=>m.length===0))throw new Error("Cannot merge routes with zero length");let e=[],a=r[0][0],s=r[0][r[0].length-1],l=r[1][0],d=r[1][r[1].length-1],x=Math.min(qg(a,l),qg(a,d)),f=Math.min(qg(s,l),qg(s,d));x<f?e.push(...r[0].reverse()):e.push(...r[0]);for(let m=1;m<r.length;m++){let D=e[e.length-1],b=r[m],E=b[0],A=b[b.length-1],B=qg(D,E),w=qg(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},rGt=(r,e)=>{let a="_getGlobalPcbPositionBeforeLayout"in r?r._getGlobalPcbPositionBeforeLayout():r,s="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((a.x-s.x)**2+(a.y-s.y)**2)};function nGt(r,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 d=rGt(r,l);d<s&&(a=l,s=d)}return a}var aGt=(r,e)=>{let a=0;a+=r.length??0,a+=e.filter(s=>s.is_crossing).length;for(let s=1;s<e.length;s++){let l=e[s-1],d=e[s],x=Math.abs(l.from.x-l.to.x)<.01,f=Math.abs(d.from.x-d.to.x)<.01;x!==f&&a++}return a},HF=r=>({up:"bottom",down:"top",left:"right",right:"left"})[r]??null,ZW=({firstEdge:r,firstEdgePort:e,firstDominantDirection:a,lastEdge:s,lastEdgePort:l,lastDominantDirection:d})=>{if(r&&e)return ZW({lastEdge:{from:r.to,to:r.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};d==="left"||d==="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=>wi(f.from,f.to)>.01),x};function sGt(r){try{return[r(),null]}catch(e){return[null,e]}}var iGt=(r,{db:e})=>{let a=r.map(s=>{let l=e.source_port.get(s.source_port_id);if(!l?.source_component_id)return null;let d=e.source_component.get(l.source_component_id);return d?.ftype==="simple_capacitor"?d.max_decoupling_trace_length:null}).filter(s=>s!==null);if(a.length!==0)return Math.min(...a)};function oGt({ports:r,nets:e}){if(r.length>=2)return`${r[0]?.selector} to ${r[1]?.selector}`;if(r.length===1&&e.length===1)return`${r[0]?.selector} to net.${e[0]._parsedProps.name}`}var uGt=(r,{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,j=E[B].y,O=E[w].x,q=E[w].y;j>b.y!=q>b.y&&b.x<(O-P)*(b.y-j)/(q-j)+P&&(A=!A)}return A};return r.some(b=>!D(b,m))}let s=a.width,l=a.height,d=a.center.x,x=a.center.y;return r.some(m=>m.x<d-s/2||m.y<x-l/2||m.x>d+s/2||m.y>x+l/2)},wBe=(r,e)=>Math.abs(r-e)<1e-4,cGt=(r,e,{viaDiameter:a=.5}={})=>{let s=[];for(let l=0;l<r.length-1;l++){let[d,x]=[r[l],r[l+1]],f=l-1>=0?r[l-1]:null,m=wBe(d.y,x.y),D=wBe(d.x,x.x);if(!m&&!D)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${d.x}, ${d.y}), end: (${x.x}, ${x.y})`);let b={type:"rect",layers:[d.layer],center:{x:(d.x+x.x)/2,y:(d.y+x.y)/2},width:m?Math.abs(d.x-x.x):.1,height:D?Math.abs(d.y-x.y):.1,connectedTo:[e]};if(s.push(b),f&&f.layer===d.layer&&d.layer!==x.layer){let E={type:"rect",layers:[d.layer,x.layer],center:{x:d.x,y:d.y},connectedTo:[e],width:a,height:a};s.push(E)}}return s};function s9e(r,e=4){let{center:a,width:s,height:l,rotation:d}=r,x=[],f=d*Math.PI/180,m=Math.cos(f),D=Math.sin(f),b=(d%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,j=-w*D,O=A*1.1,q=Math.abs(l*m)+Math.abs(A*D);x.push({center:{x:a.x+P,y:a.y+j},width:O,height:q})}}else{let A=l/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*D,j=w*m,O=Math.abs(s*m)+Math.abs(A*D),q=A*1.1;x.push({center:{x:a.x+P,y:a.y+j},width:O,height:q})}}return x}function lGt(r,e={}){if(r.length<3)return[];let{rectHeight:a=.1}=e,s=[],l=r.map(f=>f.y),d=Math.min(...l),x=Math.max(...l);for(let f=d;f<x;f+=a){let m=f+a/2,D=[];for(let b=0;b<r.length;b++){let E=r[b],A=r[(b+1)%r.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 dGt(r,e={}){let{center:a,radius:s}=r,{rectHeight:l=.1}=e,d=[],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&&d.push({center:{x:a.x,y:m},width:b*2,height:l})}return d}var nx=["top","inner1","inner2","bottom"],pK=(r,e)=>{let a=l=>e?l.concat(l.map(d=>e?.getNetConnectedToId(d)).filter(Boolean)):l,s=[];for(let l of r)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 d={center:{x:l.x,y:l.y},width:l.width,height:l.height,rotation:l.ccw_rotation},x=s9e(d);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:nx,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.shape==="circle"){let d=dGt({center:l.center,radius:l.radius},{rectHeight:.6});for(let x of d)s.push({type:"rect",layers:nx,center:x.center,width:x.width,height:x.height,connectedTo:[]})}else if(l.shape==="polygon"){let d=lGt(l.points,{rectHeight:.6});for(let x of d)s.push({type:"rect",layers:nx,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:nx,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:nx,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:nx,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:nx,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:nx,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 d=cGt(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(...d)}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},sx=({anchor_position:r,anchor_side:e,text:a,font_size:s=.18})=>{let l=.1*(s/.18),d=a.length*l,x=s,f={...r};switch(e){case"right":f.x-=d/2;break;case"left":f.x+=d/2;break;case"top":f.y-=x/2;break;case"bottom":f.y+=x/2;break}return f},xK=({db:r,source_trace_id:e,sameNetOnly:a,differentNetOnly:s})=>{!a&&!s&&(s=!0);let l=r.source_trace.get(e),d=[];for(let x of r.schematic_trace.list()){if(x.source_trace_id===e)continue;let m=r.source_trace.get(x.source_trace_id)?.subcircuit_connectivity_map_key===l.subcircuit_connectivity_map_key;s&&m||a&&!m||d.push(x)}return d},pGt=({edges:r,otherEdges:e})=>{let a=[...r];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],d=Math.abs(l.from.x-l.to.x)<.01?"vertical":l.from.y===l.to.y?"horizontal":"not-orthogonal";if(d==="not-orthogonal")continue;let x=[];for(let P of e){let j=P.from.x===P.to.x?"vertical":P.from.y===P.to.y?"horizontal":"not-orthogonal";if(j==="not-orthogonal"||d===j)continue;if(zp([l.from,l.to],[P.from,P.to],{lineThickness:.01})){let q=d==="vertical"?l.from.x:P.from.x,ee=d==="vertical"?P.from.y:l.from.y,W={x:q,y:ee};x.push({otherEdge:P,crossingPoint:W,distanceFromEdgeFrom:wi(l.from,W)})}}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=F5(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=wi(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},QW=.001,Ug=(r,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),d=Math.max(e.from.y,e.to.y);return r.x>=a&&r.x<=s&&r.y>=l&&r.y<=d},TBe=r=>{let e=Math.abs(r.from.x-r.to.x)<QW,a=Math.abs(r.from.y-r.to.y)<QW;return e?"vertical":a?"horizontal":"diagonal"},xGt=(r,e)=>{let a=TBe(r),s=TBe(e);if(a===s)return null;if(a==="vertical"&&s==="horizontal"||a==="horizontal"&&s==="vertical"){let E=a==="vertical"?r:e,A=a==="horizontal"?r:e,B=E.from.x,w=A.from.y,P={x:B,y:w};return Ug(P,r)&&Ug(P,e)?P:null}if(a==="vertical"||s==="vertical"){let E=a==="vertical"?r:e,A=a==="vertical"?e:r,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,j=w*B+P,O={x:B,y:j};return Ug(O,r)&&Ug(O,e)?O:null}let l=(r.to.y-r.from.y)/(r.to.x-r.from.x),d=r.from.y-l*r.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)<QW)return null;let m=(f-d)/(l-x),D=l*m+d,b={x:m,y:D};return Ug(b,r)&&Ug(b,e)?b:null},fGt=({edges:r,db:e,source_trace_id:a})=>{let s=xK({db:e,source_trace_id:a,sameNetOnly:!0}).flatMap(d=>d.edges),l=new Map;for(let d of r)for(let x of s){let f=xGt(d,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 hGt(r,e={}){let{minX:a,maxX:s,minY:l,maxY:d}=r,x=e.padding??1;if(!isFinite(a)||!isFinite(s)||!isFinite(l)||!isFinite(d))return[];let f=a-x,m=s+x,D=d+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 mGt=r=>{let e=r.root.db,a=r._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?E5(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 d=ZBe(e.toArray());return l.push(...hGt(d,{padding:1})),l},gGt=({edges:r,db:e,source_trace_id:a})=>{let s=e.source_trace.get(a),l=xK({db:e,source_trace_id:a,differentNetOnly:!0}).flatMap(x=>x.edges),d=x=>{let{from:f,to:m}=x;return f.x===m.x?"vertical":"horizontal"};for(let x of r){let f=d(x),m=()=>l.find(b=>d(b)===f&&zp([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()}},eK=r=>{switch(r){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},DGt=F4e.version??"unknown",UF=class extends Error{constructor(r){super(`${r} (capacity-autorouter@${DGt})`),this.name="AutorouterError"}},YS=class extends Error{constructor(r){super(r.message),this.errorData=r,this.name="TraceConnectionError"}},yGt=r=>{if(r.root?._featureMspSchematicTraceRouting||r._couldNotFindPort||r.root?.schematicDisabled)return;let{db:e}=r.root,{_parsedProps:a,parent:s}=r;if(!s)throw new Error("Trace has no parent");let l,d;try{let Ne=r._findConnectedPorts();l=Ne.allPortsFound,d=Ne.portsWithSelectors??[]}catch(Ne){if(Ne instanceof YS){e.source_trace_not_connected_error.insert({...Ne.errorData,error_type:"source_trace_not_connected_error"});return}throw Ne}let{netsWithSelectors:x}=r._findConnectedNets();if(!l)return;let m=d.map(Ne=>Ne.port.schematic_port_id).sort().join(","),D=r.root?._getBoard();if(D?._connectedSchematicPortPairs&&D._connectedSchematicPortPairs.has(m))return;let b={name:r.source_trace_id,pointsToConnect:[]},E=mGt(r),A=d.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:Ge,position:tt}=A[0],He=r.getSubcircuit().selectAll("netlabel").find(ct=>{let ot=ct._parsedProps.connection??ct._parsedProps.connectsTo;return ot?Array.isArray(ot)?ot.some(It=>r.getSubcircuit().selectOne(It,{port:!0})===Ge):r.getSubcircuit().selectOne(ot,{port:!0})===Ge:!1});if(!He){let ct=e.schematic_net_label.getWhere({source_trace_id:r.source_trace_id});ct&&(He=ct)}if(He){let ct="_getGlobalSchematicPositionBeforeLayout"in He?He._getGlobalSchematicPositionBeforeLayout():He.anchor_position,ot=[];tt.x===ct.x||tt.y===ct.y?ot.push({from:tt,to:ct}):(ot.push({from:tt,to:{x:ct.x,y:tt.y}}),ot.push({from:{x:ct.x,y:tt.y},to:ct}));let Ut=e.schematic_trace.insert({source_trace_id:r.source_trace_id,edges:ot,junctions:[],subcircuit_connectivity_map_key:r.subcircuit_connectivity_map_key??void 0});r.schematic_trace_id=Ut.schematic_trace_id;return}if(r.props.schDisplayLabel){let ct=HF(Ge.facingDirection)??"bottom";e.schematic_net_label.insert({text:r.props.schDisplayLabel,source_net_id:Ne.source_net_id,anchor_position:tt,center:sx({anchor_position:tt,anchor_side:ct,text:r.props.schDisplayLabel}),anchor_side:ct});return}let $t=HF(Ge.facingDirection)??"bottom",bt=e.schematic_net_label.insert({text:Ne._parsedProps.name,source_net_id:Ne.source_net_id,anchor_position:tt,center:sx({anchor_position:tt,anchor_side:$t,text:Ne._parsedProps.name}),anchor_side:$t});return}if(r.props.schDisplayLabel&&("from"in r.props&&"to"in r.props||"path"in r.props)){r._doInitialSchematicTraceRenderWithDisplayLabel();return}if(A.length<2)return;let P=(()=>{let Ne=[];for(let tt=0;tt<A.length-1;tt++){let He=A[tt],$t=A[tt+1],bt=dg({x:He.position.x,y:He.position.y,facingDirection:eK(He.facingDirection)},{x:$t.position.x,y:$t.position.y,facingDirection:eK($t.facingDirection)});for(let ct=0;ct<bt.length-1;ct++)Ne.push({from:bt[ct],to:bt[ct+1]})}let Ge=(tt,He)=>{let $t=He.width/2,bt=He.height/2,ct=He.center.x-$t,ot=He.center.x+$t,Ut=He.center.y-bt,It=He.center.y+bt,tr=vt=>vt.x>=ct&&vt.x<=ot&&vt.y>=Ut&&vt.y<=It;return tr(tt.from)||tr(tt.to)?!0:[[{x:ct,y:Ut},{x:ot,y:Ut}],[{x:ot,y:Ut},{x:ot,y:It}],[{x:ot,y:It},{x:ct,y:It}],[{x:ct,y:It},{x:ct,y:Ut}]].some(vt=>zp([tt.from,tt.to],vt,{lineThickness:0}))};for(let tt of Ne)for(let He of E)if(Ge(tt,He))return null;return Ne})();P&&P.length===0&&(P=null),b.pointsToConnect=A.map(({position:Ne})=>({...Ne,layer:"top"}));let j=eGt(E),O=2,q={minTraceWidth:.1,obstacles:E,connections:[b],bounds:{minX:j.minX-O,maxX:j.maxX+O,minY:j.minY-O,maxY:j.maxY+O},layerCount:1},ee=o5,W=!1;if(r.getSubcircuit().props._schDirectLineRoutingEnabled&&(ee=RBe,W=!0),!P){let Ge=new ee({input:q,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(Ge.length===0){if(r._isSymbolToChipConnection()||r._isSymbolToSymbolConnection()||r._isChipToChipConnection()){r._doInitialSchematicTraceRenderWithDisplayLabel();return}Ge=new RBe({input:q}).solveAndMapToTraces(),W=!0}let[{route:tt}]=Ge;P=[];for(let He=0;He<tt.length-1;He++)P.push({from:tt[He],to:tt[He+1]})}let re=r.source_trace_id,L=[];if(!W){gGt({edges:P,db:e,source_trace_id:re});let Ne=xK({db:e,source_trace_id:re,differentNetOnly:!0}).flatMap(Ge=>Ge.edges);P=pGt({edges:P,otherEdges:Ne}),L=fGt({edges:P,db:e,source_trace_id:r.source_trace_id})}if(!P||P.length===0)return;let K=P[P.length-1],U=A[A.length-1],J=BBe(K);P.push(...ZW({lastEdge:K,lastEdgePort:U,lastDominantDirection:J}));let Q=P[0],de=A[0],oe=BBe(Q);if(P.unshift(...ZW({firstEdge:Q,firstEdgePort:de,firstDominantDirection:oe})),!r.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(r.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&aGt(L,P)>=5&&(r._isSymbolToChipConnection()||r._isSymbolToSymbolConnection()||r._isChipToChipConnection())){r._doInitialSchematicTraceRenderWithDisplayLabel();return}let Me=e.schematic_trace.insert({source_trace_id:r.source_trace_id,edges:P,junctions:L,subcircuit_connectivity_map_key:r.subcircuit_connectivity_map_key??void 0});r.schematic_trace_id=Me.schematic_trace_id;for(let{port:Ne}of d)Ne.schematic_port_id&&e.schematic_port.update(Ne.schematic_port_id,{is_connected:!0});D?._connectedSchematicPortPairs&&D._connectedSchematicPortPairs.add(m)};function i9e(r){let e=0;for(let a=0;a<r.length;a++){let s=r[a];if(s.route_type==="wire"){let l=r[a+1];if(l){let d=l.x-s.x,x=l.y-s.y;e+=Math.sqrt(d*d+x*x)}}else s.route_type==="via"&&(e+=1.6)}return e}var LS=r=>({...r._getGlobalPcbPositionAfterLayout(),layers:r.getAvailablePcbLayers()}),bGt=!1;function FGt(r){if(r.root?.pcbDisabled)return;let{db:e}=r.root,{_parsedProps:a,parent:s}=r,l=r.getSubcircuit();if(!s)throw new Error("Trace has no parent");if(l._parsedProps.routingDisabled)return;let d=l._parsedProps.pcbRouteCache?.pcbTraces;if(d){let J=e.pcb_trace.insert({route:d.flatMap(Q=>Q.route),source_trace_id:r.source_trace_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0});r.pcb_trace_id=J.pcb_trace_id;return}if(a.pcbPath&&a.pcbPath.length>0||!l._shouldUseTraceByTraceRouting())return;let{allPortsFound:x,ports:f}=r._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:r.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, ${r} wasn't routed. Missing ports: ${D.map(J=>J.getString()).join(", ")}`,pcb_trace_id:r.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:D.map(J=>J.pcb_port_id).filter(Boolean)});return}let b=r._findConnectedNets().netsWithSelectors;if(f.length===0&&b.length===2){r.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(Me=>Me!==J);if(de.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let oe=nGt(J,de);m.push(oe),f.push(oe)}else if(f.length>1&&b.length>=1){r.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=(r._parsedProps.pcbRouteHints??[]).concat(E.flatMap(J=>J.getPcbRouteHints()));if(f.length>2){r.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(r.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=[LS(f[0]),LS(f[1])]:P=[LS(f[0]),...A,LS(f[1])];let j=US(P);if(bGt&&j.length===0){r.renderError(`Could not find a common layer (using hints) for trace ${r.getString()}`);return}let O=eu(r.root.db.toArray()),[q,ee]=sGt(()=>pK(r.root.db.toArray()));if(ee){r.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:r.pcb_trace_id,message:`Error getting obstacles for autorouting: ${ee.message}`,source_trace_id:r.source_trace_id,center:{x:0,y:0},pcb_port_ids:f.map(J=>J.pcb_port_id),pcb_trace_id:r.pcb_trace_id,pcb_component_ids:[]});return}for(let J of q)if(J.connectedTo.length>0){let de=O.getNetConnectedToId(J.connectedTo[0]);de&&J.connectedTo.push(de)}let W=[];if(j.length===0)W=P;else{let J=j[0].layer_path;W=P.map((Q,de)=>Q.via?{...Q,via_to_layer:J[de]}:{...Q,layers:[J[de]]})}W[0].pcb_port_id=f[0].pcb_port_id,W[W.length-1].pcb_port_id=f[1].pcb_port_id;let re=[];for(let[J,Q]of JBe(W)){let de="via_to_layer"in J?J.via_to_layer:null,oe=2,Me="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",Ge="pcb_port_id"in J?J.pcb_port_id:null,tt="pcb_port_id"in Q?Q.pcb_port_id:null,He=r.getSubcircuit()._parsedProps.minTraceWidth??.16,$t=new o5({OBSTACLE_MARGIN:He*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Ge&&tt),connMap:O,input:{obstacles:q,minTraceWidth:He,connections:[{name:r.source_trace_id,pointsToConnect:[{...J,layer:Me,pcb_port_id:Ge},{...Q,layer:Ne,pcb_port_id:tt}]}],layerCount:r.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(J.x,Q.x)-oe,maxX:Math.max(J.x,Q.x)+oe,minY:Math.min(J.y,Q.y)-oe,maxY:Math.max(J.y,Q.y)+oe}}}),bt=null;try{bt=$t.solveAndMapToTraces()}catch(Ut){r.renderError({type:"pcb_trace_error",pcb_trace_error_id:r.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${Ut.message}`,source_trace_id:r.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:r.pcb_trace_id,pcb_component_ids:f.map(It=>It.pcb_component_id)})}if(!bt)return;if(bt.length===0){r.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:r.pcb_trace_id,message:`Could not find a route for ${r}`,source_trace_id:r.source_trace_id,center:{x:(J.x+Q.x)/2,y:(J.y+Q.y)/2},pcb_port_ids:f.map(Ut=>Ut.pcb_port_id),pcb_trace_id:r.pcb_trace_id,pcb_component_ids:f.map(Ut=>Ut.pcb_component_id)});return}let[ct]=bt;de&&(ct.route=ct.route.map(Ut=>(Ut.route_type==="wire"&&!Ut.layer&&(Ut.layer=de),Ut))),Ge&&ct.route[0].route_type==="wire"&&(ct.route[0].start_pcb_port_id=Ge);let ot=ct.route[ct.route.length-1];tt&&ot.route_type==="wire"&&(ot.end_pcb_port_id=tt),re.push(ct.route)}let L=tGt(re),K=i9e(L),U=e.pcb_trace.insert({route:L,source_trace_id:r.source_trace_id,subcircuit_id:r.getSubcircuit()?.subcircuit_id,trace_length:K});r._portsRoutedOnPcb=f,r.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});r._insertErrorIfTraceIsOutsideBoard(L,f)}function EGt(r){if(r.root?.pcbDisabled)return;let{db:e}=r.root,{_parsedProps:a}=r,s=r.getSubcircuit();if(!a.pcbPath||a.pcbPath.length===0)return;let{allPortsFound:l,ports:d,portsWithSelectors:x}=r._findConnectedPorts();if(!l)return;let f=[];for(let q of d)q._hasMatchedPcbPrimitive()||f.push(q);if(f.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:r.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, ${r} wasn't routed. Missing ports: ${f.map(q=>q.getString()).join(", ")}`,pcb_trace_id:r.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:f.map(q=>q.pcb_port_id).filter(Boolean)});return}let m;a.pcbPathRelativeTo&&(m=x.find(q=>q.selector===a.pcbPathRelativeTo)?.port,m||(m=r.getSubcircuit().selectOne(a.pcbPathRelativeTo))),m||(m=d[0]);let D=d.find(q=>q!==m)??d[1],b=m.getAvailablePcbLayers()[0]||"top",E=a.thickness??r.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?.()||Si();for(let q of a.pcbPath){let ee=as(P,{x:q.x,y:q.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 j=i9e(w),O=e.pcb_trace.insert({route:w,source_trace_id:r.source_trace_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0,trace_length:j});r._portsRoutedOnPcb=d,r.pcb_trace_id=O.pcb_trace_id,r._insertErrorIfTraceIsOutsideBoard(w,d)}function vGt(r){if(r.root?.schematicDisabled)return;let{db:e}=r.root,{_parsedProps:a,parent:s}=r;if(!s)throw new Error("Trace has no parent");let{allPortsFound:l,portsWithSelectors:d}=r._findConnectedPorts();if(!l)return;let x=d.map(({port:W})=>({port:W,position:W._getGlobalSchematicPositionAfterLayout(),schematic_port_id:W.schematic_port_id,facingDirection:W.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 r.props){if(r.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[f,m]=r.props.path}else{if(!("from"in r.props&&"to"in r.props))throw new Error("Missing 'from' or 'to' properties in props.");f=r.props.from,m=r.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(W=>W.source_net_id===b.source_port_id),w=e.schematic_net_label.list().find(W=>W.source_net_id===A.source_port_id),[P,j]=d.map(({port:W})=>W),q=P.parent?.config.shouldRenderAsSchematicBox?`${P?.parent?.props.name}_${P?.props.name}`:`${j?.parent?.props.name}_${j?.props.name}`,ee=r.props.schDisplayLabel??q;if(B&&B.text!==ee&&(B.text=`${ee} / ${B.text}`),w&&w?.text!==ee&&(w.text=`${ee} / ${w.text}`),!w){let W=HF(A.facingDirection)??"bottom";e.schematic_net_label.insert({text:r.props.schDisplayLabel??q,source_net_id:A.source_port_id,anchor_position:E,center:sx({anchor_position:E,anchor_side:W,text:r.props.schDisplayLabel??q}),anchor_side:W})}if(!B){let W=HF(b.facingDirection)??"bottom";e.schematic_net_label.insert({text:r.props.schDisplayLabel??q,source_net_id:b.source_port_id,anchor_position:D,center:sx({anchor_position:D,anchor_side:W,text:r.props.schDisplayLabel??q}),anchor_side:W})}}function CGt(r){let{_parsedProps:e,parent:a}=r;if(!a)throw new Error("Trace has no parent");let l=r.getTracePortPathSelectors().map(d=>({selector:d,port:r.getSubcircuit().selectOne(d,{type:"port"})??null}));for(let{selector:d,port:x}of l)if(!x){let f,m,D=d.lastIndexOf(".");if(D!==-1&&D>d.lastIndexOf(" "))f=d.slice(0,D),m=d.slice(D+1);else{let W=d.match(/^(.*[ >])?([^ >]+)$/);f=W?.[1]?.trim()??"",m=W?.[2]??d}let b=f?r.getSubcircuit().selectOne(f):null;if(!b&&f&&!/[.#\[]/.test(f)&&(b=r.getSubcircuit().selectOne(`.${f}`)),!b){let W=f?`Could not find port for selector "${d}". Component "${f}" not found`:`Could not find port for selector "${d}"`,re=r.getSubcircuit(),L=re.getGroup();throw new YS({error_type:"source_trace_not_connected_error",message:W,subcircuit_id:re.subcircuit_id??void 0,source_group_id:L?.source_group_id??void 0,source_trace_id:r.source_trace_id??void 0,selectors_not_found:[d]})}let E=b.children.filter(W=>W.componentName==="Port"),A=m.includes(".")?m.split(".").pop()??"":m,B=E.flatMap(W=>W.getNameAndAliases()),w=B.some(W=>!/^(pin\d+|\d+)$/.test(W)),P=Array.from(new Set(B)).join(", "),j;E.length===0?j="It has no ports":w?j=`It has [${P}]`:j=`It has ${E.length} pins and no pinLabels (consider adding pinLabels)`;let O=`Could not find port for selector "${d}". Component "${b.props.name??f}" found, but does not have pin "${A}". ${j}`,q=r.getSubcircuit(),ee=q.getGroup();throw new YS({error_type:"source_trace_not_connected_error",message:O,subcircuit_id:q.subcircuit_id??void 0,source_group_id:ee?.source_group_id??void 0,source_trace_id:r.source_trace_id??void 0,selectors_not_found:[d]})}return l.some(d=>!d.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:l,ports:l.map(({port:d})=>d)}}var qc=class extends qn{constructor(e){super(e);z(this,"source_trace_id",null);z(this,"pcb_trace_id",null);z(this,"schematic_trace_id",null);z(this,"_portsRoutedOnPcb");z(this,"subcircuit_connectivity_map_key",null);z(this,"_traceConnectionHash",null);z(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}get config(){return{zodProps:vAe,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 CGt(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 d=l._findConnectedNets().nets,x=l._findConnectedPorts().ports??[];return d.some(f=>a.includes(f))||x.some(f=>s.includes(f))})}_isExplicitlyConnectedToPort(e){let{allPortsFound:a,portsWithSelectors:s}=this._findConnectedPorts();return a?s.map(d=>d.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){uK(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();return!e||!a?null:[...a].sort((d,x)=>(d.pcb_port_id||"").localeCompare(x.pcb_port_id||"")).map(d=>d.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,d;try{let E=this._findConnectedPorts();l=E.allPortsFound,d=E.portsWithSelectors??[]}catch(E){if(E instanceof YS){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=oGt({ports:d,nets:m}),b=e.source_trace.insert({connected_source_port_ids:d.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:iGt(d.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;uGt(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(d=>d.pcb_port_id)})}doInitialPcbManualTraceRender(){EGt(this)}doInitialPcbTraceRender(){FGt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){vGt(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 d=s.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return d&&!x||!d&&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 d=!s.parent.config.shouldRenderAsSchematicBox,x=!l.parent.config.shouldRenderAsSchematicBox;return d&&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 d=s.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return d&&x}doInitialSchematicTraceRender(){yGt(this)}},_Gt=r=>{let{db:e}=r.root;if(r.pcb_component_id){let a=e.pcb_component.get(r.pcb_component_id);return a?{width:a.width,height:a.height}:null}if(r.pcb_group_id){let a=e.pcb_group.get(r.pcb_group_id);return a?{width:a.width,height:a.height}:null}return null},AGt=(r,e)=>{let{db:a}=r.root,s=a.toArray();if(r.pcb_component_id){C5(s,r.pcb_component_id,e);return}if(r.source_group_id){_5(s,r.source_group_id,e);return}throw new Error(`Cannot reposition component ${r.getString()}: no pcb_component_id or source_group_id`)},RGt=r=>{let{db:e}=r.root;if(!r.source_component_id)return;let a=r.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 d=r._getInternallyConnectedPins();for(let x of d)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&&SGt(r,x)&&(l.has(x.source_port_id)||e.source_pin_missing_trace_warning.insert({message:`Port ${x.getNameAndAliases()[0]} on ${r.props.name} is missing a trace`,source_component_id:r.source_component_id,source_port_id:x.source_port_id,subcircuit_id:r.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},SGt=(r,e)=>{if(r.config.componentName==="Chip"){let a=r.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 BGt(r){let e=r.font_size,a=r.text.length*e*.6,s=e,l=r.anchor_alignment||"center",d=r.anchor_position.x,x=r.anchor_position.y;switch(l){case"top_left":d=r.anchor_position.x+a/2,x=r.anchor_position.y+s/2;break;case"top_center":d=r.anchor_position.x,x=r.anchor_position.y+s/2;break;case"top_right":d=r.anchor_position.x-a/2,x=r.anchor_position.y+s/2;break;case"center_left":d=r.anchor_position.x+a/2,x=r.anchor_position.y;break;case"center":d=r.anchor_position.x,x=r.anchor_position.y;break;case"center_right":d=r.anchor_position.x-a/2,x=r.anchor_position.y;break;case"bottom_left":d=r.anchor_position.x+a/2,x=r.anchor_position.y-s/2;break;case"bottom_center":d=r.anchor_position.x,x=r.anchor_position.y-s/2;break;case"bottom_right":d=r.anchor_position.x-a/2,x=r.anchor_position.y-s/2;break;default:d=r.anchor_position.x,x=r.anchor_position.y;break}return{x:d-a/2,y:x-s/2,width:a,height:s}}function wGt(r){if(!r._adjustSilkscreenTextAutomatically||r.root?.pcbDisabled||!r.pcb_component_id)return;let{db:e}=r.root,s=r._getPcbCircuitJsonBounds().center,l=e.pcb_silkscreen_text.list({pcb_component_id:r.pcb_component_id}).filter(m=>m.text===r.name);if(l.length===0)return;let f=r.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(m=>m!==r&&m.pcb_component_id).map(m=>{let D=m._getPcbCircuitJsonBounds(),b={center:D.center,width:D.width,height:D.height};return td(b)});for(let m of l){let D=m.anchor_position,b=BGt(m),E={center:{x:b.x+b.width/2,y:b.y+b.height/2},width:b.width,height:b.height},A=td(E);if(!f.some(ee=>Yb(A,ee)))continue;let w=2*s.x-D.x,P=2*s.y-D.y,j={center:{x:w,y:P},width:b.width,height:b.height},O=td(j);f.some(ee=>Yb(O,ee))||e.pcb_silkscreen_text.update(m.pcb_silkscreen_text_id,{anchor_position:{x:w,y:P}})}}function TGt(r){if(!r)return{validPinLabels:r,invalidPinLabelsMessages:[]};let e={},a=[];for(let[s,l]of Object.entries(r)){let d=Array.isArray(l)?l.slice():[l],x=[];for(let f of d)PGt(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 PGt(r,e){try{let a={name:"test",footprint:"test",pinLabels:{[r]:e}};return og.safeParse(a).success}catch{return!1}}var HS=r=>r.startsWith("http://")||r.startsWith("https://"),rK=r=>{if(HS(r))return null;let e=r.indexOf(":");if(e<=0)return null;let a=r.slice(0,e),s=r.slice(e+1);return!a||!s?null:{footprintLib:a,footprintName:s}};function IGt(r,e){let{footprint:a}=r.props;if(a??(a=r._getImpliedFootprintString?.()),!a)return;let{pcbRotation:s,pinLabels:l,pcbPinLabels:d}=r.props;if(typeof a=="string"&&HS(a)){if(r._hasStartedFootprintUrlLoad)return;r._hasStartedFootprintUrlLoad=!0;let x=a;e("load-footprint-url",async()=>{try{let f=await fetch(x);if(!f.ok)throw new Error(`Failed to fetch footprint: ${f.status}`);let m=await f.json(),D=qS({componentName:r.name,componentRotation:s,footprint:x,pinLabels:l,pcbPinLabels:d},m);r.addAll(D),r._markDirty("InitializePortsFromChildren")}catch(f){let m=r.root?.db;if(m&&r.source_component_id&&r.pcb_component_id){let D=r.getSubcircuit(),b=`${r.getString()} failed to load external footprint "${x}": `+(f instanceof Error?f.message:String(f)),E=yb.parse({type:"external_footprint_load_error",message:b,pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,subcircuit_id:D.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0,footprinter_string:x});m.external_footprint_load_error.insert(E)}throw f}});return}if(typeof a=="string"){let x=rK(a);if(!x||r._hasStartedFootprintUrlLoad)return;r._hasStartedFootprintUrlLoad=!0;let m=r.root?.platform?.footprintLibraryMap?.[x.footprintLib],D;if(typeof m=="function"&&(D=m),!D)return;e("load-lib-footprint",async()=>{try{let b=await D(x.footprintName),E=null;if(Array.isArray(b)?E=b:Array.isArray(b.footprintCircuitJson)&&(E=b.footprintCircuitJson),!E)return;let A=qS({componentName:r.name,componentRotation:s,footprint:a,pinLabels:l,pcbPinLabels:d},E);r.addAll(A),!Array.isArray(b)&&b.cadModel&&(r._asyncFootprintCadModel=b.cadModel);for(let B of r.children)B.componentName==="Port"&&B._markDirty?.("PcbPortRender");r._markDirty("InitializePortsFromChildren")}catch(b){let E=r.root?.db;if(E&&r.source_component_id&&r.pcb_component_id){let A=r.getSubcircuit(),B=`${r.getString()} failed to load external footprint "${a}": `+(b instanceof Error?b.message:String(b)),w=yb.parse({type:"external_footprint_load_error",message:B,pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,subcircuit_id:A.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0,footprinter_string:a});E.external_footprint_load_error.insert(w)}throw b}});return}if(!(0,tK.isValidElement)(a)&&a.componentName==="Footprint"&&r.add(a),Array.isArray(a)&&!(0,tK.isValidElement)(a)&&a.length>0){try{let x=qS({componentName:r.name,componentRotation:s,footprint:"",pinLabels:l,pcbPinLabels:d},a);r.addAll(x)}catch(x){let f=r.root?.db;if(f&&r.source_component_id&&r.pcb_component_id){let m=r.getSubcircuit(),D=`${r.getString()} failed to load json footprint: `+(x instanceof Error?x.message:String(x)),b=VA.parse({type:"circuit_json_footprint_load_error",message:D,pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,subcircuit_id:m.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0});f.circuit_json_footprint_load_error.insert(b)}throw x}return}}function jGt(r){if(r.root?.pcbDisabled||!r.pcb_component_id)return;let{pcbX:e,pcbY:a}=r._parsedProps,s=r.props?.pcbPositionAnchor;if(!s||e===void 0&&a===void 0)return;let l=ZS(r.children);if(l.width===0||l.height===0)return;let x={...{x:(l.minX+l.maxX)/2,y:(l.minY+l.maxY)/2}},f=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(s)){let b={left:l.minX,right:l.maxX,top:l.minY,bottom:l.maxY};switch(s){case"center":f=x;break;case"top_left":f={x:b.left,y:b.top};break;case"top_center":f={x:x.x,y:b.top};break;case"top_right":f={x:b.right,y:b.top};break;case"center_left":f={x:b.left,y:x.y};break;case"center_right":f={x:b.right,y:x.y};break;case"bottom_left":f={x:b.left,y:b.bottom};break;case"bottom_center":f={x:x.x,y:b.bottom};break;case"bottom_right":f={x:b.right,y:b.bottom};break}}else try{let b=r.portMap[s];b&&(f=b._getGlobalPcbPositionBeforeLayout())}catch{}if(!f)return;let D={...x};e!==void 0&&(D.x+=e-f.x),a!==void 0&&(D.y+=a-f.y),(Math.abs(D.x-x.x)>1e-6||Math.abs(D.y-x.y)>1e-6)&&r._repositionOnPcb(D)}var kGt=(0,XBe.default)("tscircuit:core"),NGt=v.object({x:Gn,y:Gn,z:Gn}),es=class extends qn{constructor(e){let a={...e},s=[];if(a.pinLabels&&!Array.isArray(a.pinLabels)){let{validPinLabels:l,invalidPinLabelsMessages:d}=TGt(a.pinLabels);a.pinLabels=l,s=d}super(a);z(this,"reactSubtrees",[]);z(this,"_impliedFootprint");z(this,"isPrimitiveContainer",!0);z(this,"_isNormalComponent",!0);z(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});z(this,"_asyncSupplierPartNumbers");z(this,"_asyncFootprintCadModel");z(this,"_isCadModelChild");z(this,"pcb_missing_footprint_error_id");z(this,"_hasStartedFootprintUrlLoad",!1);z(this,"_invalidPinLabelMessages",[]);z(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(),d=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:d}),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=YF(E,this._parsedProps.pinLabels);s.push(new Ni({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 Ni({pinNumber:m++,aliases:e.additionalAliases?.[`pin${m}`]??[]},{originDescription:`schPortArrangement:${D}`}))}}let d=this._parsedProps.pinLabels;if(d)for(let[f,m]of Object.entries(d)){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 Ni({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=ks[this._getSchematicSymbolNameOrThrow()];if(!f)return;for(let m of f.ports){let D=QBe(m.labels);if(!D)continue;let b=s.find(E=>E._parsedProps.pinNumber===Number(D));if(b)b.schematicSymbolPortDef=m;else{let E=qF(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 Ni({pinNumber:f,aliases:e.additionalAliases?.[`pin${f}`]??[]}));continue}let m=[...l.leftSide?.pins??[],...l.rightSide?.pins??[],...l.topSide?.pins??[],...l.bottomSide?.pins??[]].map(D=>YF(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 Ni({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(HS(l)||rK(l))return;let d=Vq.string(l).soup(),x=qS({componentName:this.name??this.componentName,componentRotation:e,footprint:l,pinLabels:a,pcbPinLabels:s},d);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 d of this._invalidPinLabelMessages){let x="pinLabels",f=d.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);f&&(x=`pinLabels['${f[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:x,message:d,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:a}=this.config,{_parsedProps:s}=this;s.symbol&&(0,ax.isValidElement)(s.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(s.symbol):a?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let l=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&l){if(!this.schematic_component_id)return;let d=qA.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(d)}}_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=ks[s],d=this._getGlobalSchematicPositionBeforeLayout();if(l){let x=e.schematic_component.insert({center:d,size:l.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name:s,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=x.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(e){if(this.root?.schematicDisabled)return;let{db:a}=this.root,s=this._getGlobalSchematicPositionBeforeLayout(),l=a.schematic_component.insert({center:s,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=l.schematic_component_id,this.add(e)}_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 d=this._getGlobalSchematicPositionBeforeLayout(),x=this._getSchematicPortArrangement(),f=e.schematic_component.insert({center:d,rotation:a.schRotation??0,size:s.getSize(),port_arrangement:qVt(x),pin_spacing:a.schPinSpacing??.2,pin_styles:zVt(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?d.x+(D??0)/2+.1:d.x-(D??0)/2,y:m?d.y+(b??0)/2+.35:d.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?d.x+(D??0)/2+.1:d.x-(D??0)/2,y:m?d.y+(b??0)/2+.55:d.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=GA.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=ZS(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()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db:e}=this.root;if(!e.schematic_component.get(this.schematic_component_id))return;let s=[],l=m=>{for(let D of m){if(D.isSchematicPrimitive&&D.componentName==="SchematicLine"){let b=e.schematic_line.get(D.schematic_line_id);b&&s.push(b)}if(D.isSchematicPrimitive&&D.componentName==="SchematicRect"){let b=e.schematic_rect.get(D.schematic_rect_id);b&&s.push(b)}if(D.isSchematicPrimitive&&D.componentName==="SchematicText"){let b=e.schematic_text.get(D.schematic_text_id);b&&s.push(b)}D.children&&D.children.length>0&&l(D.children)}};if(l(this.children),s.length===0)return;let d=ZBe(s),x=Math.abs(d.maxX-d.minX),f=Math.abs(d.maxY-d.minY);x===0&&f===0||e.schematic_component.update(this.schematic_component_id,{size:{width:x,height:f}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){jGt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(e){let a=KBe(e);return{element:e,component:a}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let e=this.props.footprint;(0,ax.isValidElement)(e)&&(this.children.some(l=>l.componentName==="Footprint")||this.add(e));let a=this.props.cadModel;if((0,ax.isValidElement)(a)){this._isCadModelChild=!0;let s=this.children.some(d=>d.componentName==="CadAssembly"),l=this.children.some(d=>d.componentName==="CadModel");!s&&!l&&this.add(a)}}doInitialPcbFootprintStringRender(){IGt(this,(e,a)=>this._queueAsyncEffect(e,a))}_hasExistingPortExactly(e){return this.children.filter(s=>s.componentName==="Port").some(s=>{let l=e.getNameAndAliases(),d=s.getNameAndAliases();return l.length===d.length&&l.every(x=>d.includes(x))})}add(e){let a;if((0,ax.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(d=>d.componentName==="Port").find(d=>d.isMatchingAnyOf(a.getNameAndAliases()));l&&kGt(`Similar ports added. Port 1: ${l}, Port 2: ${a}`)}super.add(a)}getPortsFromFootprint(e){let{footprint:a}=this.props;if((!a||(0,ax.isValidElement)(a))&&(a=this.children.find(l=>l.componentName==="Footprint")),typeof a=="string"){if(HS(a))return[];if(rK(a))return[];let l=Vq.string(a).soup(),d=[];for(let x of l)if("port_hints"in x&&x.port_hints){let f=qF(x.port_hints,e);if(!f)continue;f.originDescription=`footprint:string:${a}:port_hints[0]:${x.port_hints[0]}`,d.push(f)}return d}if(!(0,ax.isValidElement)(a)&&a&&a.componentName==="Footprint"){let l=a,d=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${d}`]),d++;let b=qF(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 d=qF(l.props.portHints);d&&s.push(d)}}return s}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:e}=this;if(!e.schematicSymbolName)return[];let a=ks[e.schematicSymbolName];if(!a)return[];let s=[];for(let l of a.ports){let d=qF(l.labels);d&&(d.schematicSymbolPortDef=l,s.push(d))}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 d=Array.isArray(l)?l:[l];for(let x of d)a.push(x)}return a}_createNetsFromProps(e){uK(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(!e9e(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:d,bottomSide:x}=e;return Math.max(...s?.pins??[],...l?.pins??[],...d?.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(d=>d.startsWith("pin")?parseInt(d.slice(3)):parseInt(d)).filter(d=>!Number.isNaN(d));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 JVt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:s,numericSchPinStyle:QVt(e.schPinStyle,e.pinLabels),pinCount:a,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:e.pinLabels})}doInitialCadModelRender(){if(this._isCadModelChild)return;let{db:e}=this.root,{boardThickness:a=0}=this.root?._getBoard()??{},s=this._parsedProps.cadModel,l=s===void 0?this._asyncFootprintCadModel:s,d=this.props.footprint??this._getImpliedFootprintString();if(!this.pcb_component_id||!l&&!d||l===null)return;let x=this._getPcbCircuitJsonBounds(),f=e.pcb_component.get(this.pcb_component_id);if(typeof l=="string")throw new Error("String cadModel not yet implemented");let m=NGt.parse({x:0,y:0,z:typeof l?.rotationOffset=="number"?l.rotationOffset:0,...typeof l?.rotationOffset=="object"?l.rotationOffset??{}:{}}),D=Gf.parse({x:0,y:0,z:0,...typeof l?.positionOffset=="object"?l.positionOffset:{}}),b=this.props.layer==="bottom"?"bottom":"top",E=e.cad_component.insert({position:{x:x.center.x+D.x,y:x.center.y+D.y,z:(b==="bottom"?-a/2:a/2)+D.z},rotation:{x:m.x,y:(b==="top"?0:180)+m.y,z:b==="bottom"?-((f?.rotation??0)+m.z)+180:(f?.rotation??0)+m.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(l??{})?this._addCachebustToModelUrl(l.stlUrl):void 0,model_obj_url:"objUrl"in(l??{})?this._addCachebustToModelUrl(l.objUrl):void 0,model_mtl_url:"mtlUrl"in(l??{})?this._addCachebustToModelUrl(l.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(l??{})?this._addCachebustToModelUrl(l.gltfUrl):void 0,model_glb_url:"glbUrl"in(l??{})?this._addCachebustToModelUrl(l.glbUrl):void 0,model_step_url:"stepUrl"in(l??{})?this._addCachebustToModelUrl(l.stepUrl):void 0,model_wrl_url:"wrlUrl"in(l??{})?this._addCachebustToModelUrl(l.wrlUrl):void 0,model_jscad:"jscad"in(l??{})?l.jscad:void 0,model_unit_to_mm_scale_factor:typeof l?.modelUnitToMmScale=="number"?l.modelUnitToMmScale:void 0,footprinter_string:typeof d=="string"&&!l?d:void 0});this.cad_component_id=E.cad_component_id}_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,d=this._getPartsEngineCacheKey(a,s);if(l){let m=await l.getItem(d);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(d,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 d=this._getSupplierPartNumbers(e,s,l);if(!(d instanceof Promise)){a.source_component.update(this.source_component_id,{supplier_part_numbers:d});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await d,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 d of l)this.add(new qc({from:`${this.getSubcircuitSelector()} > port.${a}`,to:d}))}}doInitialSourceDesignRuleChecks(){RGt(this)}_getMinimumFlexContainerSize(){return _Gt(this)}_repositionOnPcb(e){return AGt(this,e)}doInitialSilkscreenOverlapAdjustment(){return wGt(this)}},MGt=class{constructor(r,e={}){z(this,"input");z(this,"isRouting",!1);z(this,"solver");z(this,"eventHandlers",{complete:[],error:[],progress:[]});z(this,"cycleCount",0);z(this,"stepDelay");z(this,"timeoutId");this.input=r;let{capacityDepth:a,targetMinCapacity:s,stepDelay:l=0}=e;this.solver=new w6e(r,{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 UF(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let r=Date.now(),e=this.solver.iterations;for(;Date.now()-r<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let a=(this.solver.iterations-e)/(Date.now()-r)*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(r){this.emitEvent({type:"error",error:r instanceof Error?new UF(r.message):new UF(String(r))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(r,e){r==="complete"?this.eventHandlers.complete.push(e):r==="error"?this.eventHandlers.error.push(e):r==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(r){if(r.type==="complete")for(let e of this.eventHandlers.complete)e(r);else if(r.type==="error")for(let e of this.eventHandlers.error)e(r);else if(r.type==="progress")for(let e of this.eventHandlers.progress)e(r)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new UF(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},fK=class extends qn{constructor(){super(...arguments);z(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:i4e}}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=>({...as(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()})}},o9e=({circuitJson:r,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:d,new_center:x}=l,f=ua(r).pcb_component.get(d);if(!f)continue;let m=ua(r).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},u9e=({circuitJson:r,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:d,new_center:x}=l,f=ua(r).schematic_component.get(d);if(!f||!f.source_component_id)continue;let m=ua(r).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},OGt=({circuitJson:r,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"),d=a;return s.length>0&&(d=u9e({circuitJson:r,editEvents:s,manualEditsFile:d})),l.length>0&&(d=o9e({circuitJson:r,editEvents:l,manualEditsFile:d})),d},LGt=(r,e)=>{if(ua(r).pcb_trace_hint.get(e.pcb_trace_hint_id))r=r.map(s=>s.pcb_trace_hint_id===e.pcb_trace_hint_id?{...s,route:e.route}:s);else{let s=ua(r).pcb_port.get(e.pcb_port_id);r=r.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 r},$Gt=({circuitJson:r,editEvents:e})=>{r=JSON.parse(JSON.stringify(r));for(let a of e)if(a.edit_event_type==="edit_pcb_component_location"){let s=r.find(d=>d.type==="pcb_component"&&d.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 d=Ma(a.new_center.x-a.original_center.x,a.new_center.y-a.original_center.y);r=r.map(x=>x.pcb_component_id!==a.pcb_component_id?x:IY(x,d))}}else a.edit_event_type==="edit_schematic_component_location"?r=r.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"&&(r=LGt(r,a));return r},c9e=(r,e)=>{let a=r.source_group.list(),s=[],l=d=>{let x=a.filter(f=>f.parent_subcircuit_id===d);for(let f of x)f.subcircuit_id&&(s.push(f.subcircuit_id),l(f.subcircuit_id))};return l(e),s},nK=({db:r,circuitJson:e,subcircuit_id:a,minTraceWidth:s=.1})=>{if(!r&&e&&(r=ua(e)),!r)throw new Error("db or circuitJson is required");let l=r.pcb_trace_hint.list(),d=a?new Set([a]):null;if(a){let K=c9e(r,a);for(let U of K)d.add(U)}let x=(e??r.toArray()).filter(K=>!a||"subcircuit_id"in K&&d.has(K.subcircuit_id)),f=r.pcb_board.list()[0];r=ua(x);let m=eu(x),D=pK([...r.pcb_component.list(),...r.pcb_smtpad.list(),...r.pcb_plated_hole.list(),...r.pcb_hole.list(),...r.pcb_via.list(),...r.pcb_cutout.list()].filter(K=>!a||d?.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=r.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(r.pcb_trace.list().map(K=>K.source_trace_id).filter(K=>!!K)),B=r.source_trace.list().filter(K=>!A.has(K.source_trace_id)).map(K=>{let U=K.connected_source_port_ids.map(Ge=>{let tt=r.source_port.get(Ge),He=r.pcb_port.getWhere({source_port_id:Ge});return{...tt,...He}});if(U.length<2)return null;let[J,Q]=U,de=J.layers?.[0]??"top",oe=Q.layers?.[0]??"top",Me=l.filter(Ge=>Ge.pcb_port_id===J.pcb_port_id||Ge.pcb_port_id===Q.pcb_port_id),Ne=[];for(let Ge of Me){let He=r.pcb_port.get(Ge.pcb_port_id)?.layers?.[0]??"top";for(let $t of Ge.route)Ne.push({x:$t.x,y:$t.y,layer:He})}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:oe,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=r.source_net.list().filter(K=>!a||d?.has(K.subcircuit_id)),j=[];for(let K of P){let U=r.source_trace.list().filter(J=>J.connected_source_net_ids?.includes(K.source_net_id));j.push({name:K.source_net_id??m.getNetConnectedToId(K.source_net_id),pointsToConnect:U.flatMap(J=>r.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=r.pcb_breakout_point.list().filter(K=>!a||d?.has(K.subcircuit_id)),q=[],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]};q.push(Q),ee.set(K.source_trace_id,Q)}}else if(K.source_net_id){let J=j.find(Q=>Q.name===K.source_net_id);J?J.pointsToConnect.push(U):q.push({name:K.source_net_id,pointsToConnect:[U]})}else if(K.source_port_id){let J=r.pcb_port.getWhere({source_port_id:K.source_port_id});J&&q.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 W=[...B,...j,...q],re=new Map;for(let K of W)for(let U of K.pointsToConnect)U.pointId&&re.set(U.pointId,K);let L=r.pcb_trace.list().filter(K=>!a||d?.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=re.get(J);Q&&[...U].every(de=>re.get(de)===Q)&&(Q.externallyConnectedPointIds??(Q.externallyConnectedPointIds=[]),Q.externallyConnectedPointIds.push([...U]))}return{simpleRouteJson:{bounds:E,obstacles:D,connections:W,layerCount:f?.num_layers??2,minTraceWidth:s},connMap:m}},zGt=r=>{let e={};if(!r)return e;for(let s of ld)e[s]=0;let a=new Map;for(let s of r){let[,,l,d]=s.type.split(":");if(d==="start"){a.set(`${l}:${s.renderId}`,s);continue}if(d==="end"){let x=a.get(`${l}:${s.renderId}`);if(x){let f=s.createdAt-x.createdAt;e[l]=(e[l]||0)+f}}}return e},qGt=r=>{let e=r.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,d=new Set;for(let m=0;m<s.length;m++){let D=s[m];if(D===null||D<1)continue;if(!d.has(D)){d.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},PBe=(0,l9e.default)("Group_doInitialSchematicLayoutMatchAdapt");function UGt(r){let{db:e}=r.root,a=Hb(e.toArray(),{source_group_id:r.source_group_id}),s=uH(a);PBe.enabled&&global.debugGraphics?.push(Wp(s,{title:`floatingBpcGraph-${r.name}`}));let l=uH(a),d={boxes:l.boxes,pins:l.pins.map(m=>({...m,color:m.color.replace("not_connected","normal")}))},{result:x}=s5e([{variantName:"default",floatingGraph:l},{variantName:"noNotConnected",floatingGraph:d}],{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:{}});PBe.enabled&&global.debugGraphics?.push(Wp(x,{title:`laidOutBpcGraph-${r.name}`}));let f=r._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 an=(0,d9e.default)("Group_doInitialSchematicLayoutMatchpack");function IBe(r){switch(r){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function jBe(r,e){let a=["right","up","left","down"],s=a.indexOf(r);if(s===-1)return r;let l=Math.round(e/90),d=(s+l)%4;return a[d<0?d+4:d]}function VGt(r,e,a){let s={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};an(`[${a.name}] Processing ${r.childNodes.length} child nodes for input problem`),r.childNodes.forEach((d,x)=>{if(an(`[${a.name}] Processing child ${x}: nodeType=${d.nodeType}`),d.nodeType==="component"?an(`[${a.name}] - Component: ${d.sourceComponent?.name}`):d.nodeType==="group"&&an(`[${a.name}] - Group: ${d.sourceGroup?.name}`),d.nodeType==="component"&&d.sourceComponent){let f=d.sourceComponent.name||`chip_${x}`,m=e.schematic_component.getWhere({source_component_id:d.sourceComponent.source_component_id});if(!m)return;let D=a.children.find(q=>q.source_component_id===d.sourceComponent?.source_component_id),b=[0,90,180,270];D?._parsedProps?.schOrientation&&(b=[0]),D?._parsedProps?.schRotation!==void 0&&(b=[0]);let E=D?._parsedProps?.schMarginLeft??D?._parsedProps?.schMarginX??0,A=D?._parsedProps?.schMarginRight??D?._parsedProps?.schMarginX??0,B=D?._parsedProps?.schMarginTop??D?._parsedProps?.schMarginY??0,w=D?._parsedProps?.schMarginBottom??D?._parsedProps?.schMarginY??0;D?.config.shouldRenderAsSchematicBox&&(B+=.4,w+=.4);let P=(A-E)/2,j=(B-w)/2;s.chipMap[f]={chipId:f,pins:[],size:{x:(m.size?.width||1)+E+A,y:(m.size?.height||1)+B+w},availableRotations:b};let O=e.schematic_port.list({schematic_component_id:m.schematic_component_id});for(let q of O){let ee=e.source_port.get(q.source_port_id);if(!ee)continue;let W=`${f}.${ee.pin_number||ee.name||q.schematic_port_id}`;s.chipMap[f].pins.push(W);let re=IBe(q.facing_direction);s.chipPinMap[W]={pinId:W,offset:{x:(q.center?.x||0)-(m.center.x||0)+P,y:(q.center?.y||0)-(m.center.y||0)+j},side:re}}}else if(d.nodeType==="group"&&d.sourceGroup){let f=d.sourceGroup.name||`group_${x}`;an(`[${a.name}] Processing nested group: ${f}`);let m=e.schematic_group?.getWhere?.({source_group_id:d.sourceGroup.source_group_id}),D=a.children.find(b=>b.source_group_id===d.sourceGroup?.source_group_id);if(an(`[${a.name}] Found schematic_group for ${f}:`,m),m){an(`[${a.name}] Treating group ${f} as composite chip`);let b=e.schematic_component.list({schematic_group_id:m.schematic_group_id});an(`[${a.name}] Group ${f} has ${b.length} components:`,b.map(J=>J.source_component_id));let E=1/0,A=-1/0,B=1/0,w=-1/0,P=!1;for(let J of b)if(J.center&&J.size){P=!0;let Q=J.size.width/2,de=J.size.height/2;E=Math.min(E,J.center.x-Q),A=Math.max(A,J.center.x+Q),B=Math.min(B,J.center.y-de),w=Math.max(w,J.center.y+de)}let j=D?._parsedProps?.schMarginLeft??D?._parsedProps?.schMarginX??0,O=D?._parsedProps?.schMarginRight??D?._parsedProps?.schMarginX??0,q=D?._parsedProps?.schMarginTop??D?._parsedProps?.schMarginY??0,ee=D?._parsedProps?.schMarginBottom??D?._parsedProps?.schMarginY??0,W=(O-j)/2,re=(q-ee)/2,L=(P?A-E:2)+j+O,K=(P?w-B:2)+q+ee;an(`[${a.name}] Group ${f} computed size: ${L} x ${K}`);let U=[];for(let J of b){let Q=e.schematic_port.list({schematic_component_id:J.schematic_component_id});for(let de of Q){let oe=e.source_port.get(de.source_port_id);if(!oe)continue;let Me=`${f}.${oe.pin_number||oe.name||de.schematic_port_id}`;U.push(Me);let Ne=m.center||{x:0,y:0},Ge=IBe(de.facing_direction);s.chipPinMap[Me]={pinId:Me,offset:{x:(de.center?.x||0)-Ne.x+W,y:(de.center?.y||0)-Ne.y+re},side:Ge}}}an(`[${a.name}] Group ${f} has ${U.length} pins:`,U),s.chipMap[f]={chipId:f,pins:U,size:{x:L,y:K}},an(`[${a.name}] Added group ${f} to chipMap`)}else an(`[${a.name}] Warning: No schematic_group found for group ${f}`)}}),an(`[${a.name}] Creating connections using connectivity keys`);let l=new Map;for(let[d,x]of Object.entries(s.chipMap))for(let f of x.pins){let m=f.split(".").pop(),D=r.childNodes.find(b=>b.nodeType==="component"&&b.sourceComponent?b.sourceComponent.name===d:b.nodeType==="group"&&b.sourceGroup?`group_${r.childNodes.indexOf(b)}`===d:!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 j=w.subcircuit_connectivity_map_key;l.has(j)||l.set(j,[]),l.get(j).push(f),an(`[${a.name}] \u2713 Pin ${f} has connectivity key: ${j}`)}else an(`[${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),an(`[${a.name}] Pin ${f} has connectivity key: ${B}`)}}}}an(`[${a.name}] Found ${l.size} connectivity groups:`,Array.from(l.entries()).map(([d,x])=>({key:d,pins:x})));for(let[d,x]of l)if(x.length>=2){let f=e.source_trace.list().filter(b=>b.subcircuit_connectivity_map_key===d),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(an(`[${a.name}] Connectivity ${d}: 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 j=B.split(".")[0],O=r.childNodes.find(q=>q.nodeType==="component"&&q.sourceComponent?q.sourceComponent.name===j:q.nodeType==="group"&&q.sourceGroup?`group_${r.childNodes.indexOf(q)}`===j:!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,an(`[${a.name}] Created strong connection: ${w} <-> ${P}`)}}}if(m){let b=e.source_net.getWhere({subcircuit_connectivity_map_key:d}),E=b?.is_ground??!1,A=b?.is_power??!1;s.netMap[d]={netId:d,isGround:E,isPositiveVoltageSource:A};for(let B of x)s.netConnMap[`${B}-${d}`]=!0;an(`[${a.name}] Created net ${d} with ${x.length} pins:`,x)}}return s}function GGt(r){let{db:e}=r.root,a=xg(e.toArray(),{source_group_id:r.source_group_id});if(an(`[${r.name}] Starting matchpack layout with ${a.childNodes.length} children`),an(`[${r.name}] Tree structure:`,JSON.stringify(a,null,2)),a.childNodes.length<=1){an(`[${r.name}] Only ${a.childNodes.length} children, skipping layout`);return}an("Converting circuit tree to InputProblem...");let s=VGt(a,e,r);an.enabled&&r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${r.name}`,content:JSON.stringify(s,null,2)});let l=new uSe(s);if(an("Starting LayoutPipelineSolver..."),an.enabled&&global.debugGraphics){let m=l.visualize();global.debugGraphics.push({...m,title:`matchpack-initial-${r.name}`})}if(l.solve(),an(`Solver completed in ${l.iterations} iterations`),an(`Solved: ${l.solved}, Failed: ${l.failed}`),l.failed)throw an(`Solver failed with error: ${l.error}`),new Error(`Matchpack layout solver failed: ${l.error}`);let d=l.getOutputLayout();if(an("OutputLayout:",JSON.stringify(d,null,2)),an("Solver completed successfully:",!l.failed),an.enabled&&global.debugGraphics){let m=l.visualize();global.debugGraphics.push({...m,title:`matchpack-final-${r.name}`})}let x=l.checkForOverlaps(d);if(x.length>0){an(`Warning: Found ${x.length} overlapping components:`);for(let m of x)an(` ${m.chip1} overlaps ${m.chip2} (area: ${m.overlapArea})`)}let f=r._getGlobalSchematicPositionBeforeLayout();an(`Group offset: x=${f.x}, y=${f.y}`),an(`Applying layout results for ${Object.keys(d.chipPlacements).length} chip placements`);for(let[m,D]of Object.entries(d.chipPlacements)){an(`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 an(` 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 an(` Checking group ${B} (expected chipId: ${w}): matches=${P}`),P}return!1});if(!b){an(`Warning: No tree node found for chip: ${m}`),an("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){an(`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 j of B)j.center.x+=P.x,j.center.y+=P.y;for(let j of w)j.position.x+=P.x,j.position.y+=P.y;if(A.center=E,D.ccwRotationDegrees!==0){an(`Component ${m} has rotation: ${D.ccwRotationDegrees}\xB0`);let j=D.ccwRotationDegrees*Math.PI/180,O=Math.cos(j),q=Math.sin(j);for(let ee of B){let W=ee.center.x-E.x,re=ee.center.y-E.y,L=W*O-re*q,K=W*q+re*O;ee.center.x=E.x+L,ee.center.y=E.y+K;let U=ee.facing_direction||"right";ee.facing_direction=jBe(U,D.ccwRotationDegrees)}for(let ee of w){let W=ee.position.x-E.x,re=ee.position.y-E.y,L=W*O-re*q,K=W*q+re*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],`_${jBe(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){an(`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});an(`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};an(`Position delta for group ${m}: (${P.x}, ${P.y})`);for(let j of B)if(j.center){let O={...j.center};j.center.x+=P.x,j.center.y+=P.y,an(`Moved component ${j.source_component_id} from (${O.x}, ${O.y}) to (${j.center.x}, ${j.center.y})`);let q=e.schematic_port.list({schematic_component_id:j.schematic_component_id}),ee=e.schematic_text.list({schematic_component_id:j.schematic_component_id});for(let W of q)W.center&&(W.center.x+=P.x,W.center.y+=P.y);for(let W of ee)W.position&&(W.position.x+=P.x,W.position.y+=P.y)}A.center=E,an(`Updated group ${m} center to (${E.x}, ${E.y})`)}}}an("Matchpack layout completed successfully")}function XGt(r){if(!r.isSubcircuit)return;let{db:e}=r.root,a=r.selectAll("trace"),s=new $b({});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}=r._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${r._renderId}`}_${m}`,e.source_trace.update(f.source_trace_id,{subcircuit_connectivity_map_key:f.subcircuit_connectivity_map_key}))}let d=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)d.add(D)}for(let f of d){let m=s.getNetConnectedToId(f);if(!m)continue;let D=`${l??`unnamedsubcircuit${r._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${r._renderId}`}_${m}`;e.source_net.update(f,{subcircuit_connectivity_map_key:D})}}function YGt(r){let{db:e}=r.root,a=r._parsedProps,s=r.children.filter(re=>{let L=re._parsedProps?.schX!==void 0||re._parsedProps?.schY!==void 0;return re.schematic_component_id&&!L});if(s.length===0)return;let l=0,d=0;for(let re of s){let L=e.schematic_component.get(re.schematic_component_id);L?.size&&(l=Math.max(l,L.size.width),d=Math.max(d,L.size.height))}l===0&&s.length>0&&(l=1),d===0&&s.length>0&&(d=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=re=>{if(re!==void 0)return typeof re=="number"?re:pe.parse(re)};if(D!==void 0||b!==void 0){let re=typeof m=="object"&&m!==null?m.x:m,L=typeof m=="object"&&m!==null?m.y:m;B=P(b??re)??1,w=P(D??L)??1}else if(typeof m=="number")B=m,w=m;else if(typeof m=="string"){let re=pe.parse(m);B=re,w=re}else if(typeof m=="object"&&m!==null){let re=m.x,L=m.y;B=typeof re=="number"?re:pe.parse(re??"0mm"),w=typeof L=="number"?L:pe.parse(L??"0mm")}else B=1,w=1;let j=E*l+Math.max(0,E-1)*B,O=A*d+Math.max(0,A-1)*w,q=r._getGlobalSchematicPositionBeforeLayout(),ee=q.x-j/2+l/2,W=q.y+O/2-d/2;for(let re=0;re<s.length;re++){let L=s[re];if(!L.schematic_component_id)continue;let K=Math.floor(re/E),U=re%E;if(K>=A||U>=E){console.warn(`Schematic grid layout: Child ${L.getString()} at index ${re} (row ${K}, col ${U}) exceeds specified grid dimensions (${A}x${E}). Skipping placement.`);continue}let J=ee+U*(l+B),Q=W-K*(d+w),de=e.schematic_component.get(L.schematic_component_id);if(de){let oe=de.center,Me={x:J,y:Q};e.schematic_component.update(L.schematic_component_id,{center:Me});let Ne=Me.x-oe.x,Ge=Me.y-oe.y,tt=e.schematic_port.list({schematic_component_id:L.schematic_component_id});for(let $t of tt)e.schematic_port.update($t.schematic_port_id,{center:{x:$t.center.x+Ne,y:$t.center.y+Ge}});let He=e.schematic_text.list({schematic_component_id:L.schematic_component_id});for(let $t of He)e.schematic_text.update($t.schematic_text_id,{position:{x:$t.position.x+Ne,y:$t.position.y+Ge}})}}r.schematic_group_id&&e.schematic_group.update(r.schematic_group_id,{width:j,height:O,center:q})}var kBe=(r,e)=>{let{sourceComponent:a,sourceGroup:s}=e;if(e.nodeType==="component"){let l=r.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=r.schematic_group.getWhere({source_group_id:s?.source_group_id});if(l?.width&&l?.height)return{width:l.width,height:l.height};let d=r.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 d)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},HGt=r=>{let{db:e}=r.root,a=r._parsedProps,s=xg(e.toArray(),{source_group_id:r.source_group_id}),l=a.schJustifyContent??a.justifyContent,d=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"}[d??"center"];if(!m)throw new Error(`Invalid justifyContent value: "${l}"`);if(!D)throw new Error(`Invalid alignItems value: "${d}"`);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=pe.parse(x),E=pe.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=A5(s.childNodes.map(W=>kBe(e,W)).filter(W=>W!==null),{alignItems:D,justifyContent:m,direction:f,rowGap:b,columnGap:E}),B=A.width,w=A.height);let j=new _S(B,w,{alignItems:D,justifyContent:m,direction:f,rowGap:b,columnGap:E});for(let W of s.childNodes){let re=kBe(e,W);j.addChild({metadata:W,width:re?.width??0,height:re?.height??0,flexBasis:re?f==="row"?re.width:re.height:void 0})}j.build();let O={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let W of j.children)O.minX=Math.min(O.minX,W.position.x),O.minY=Math.min(O.minY,W.position.y),O.maxX=Math.max(O.maxX,W.position.x+W.size.width),O.maxY=Math.max(O.maxY,W.position.y+W.size.height);O.width=O.maxX-O.minX,O.height=O.maxY-O.minY;let q={x:-(O.maxX+O.minX)/2,y:-(O.maxY+O.minY)/2},ee=e.toArray();for(let W of j.children){let{sourceComponent:re,sourceGroup:L}=W.metadata;if(re){let K=e.schematic_component.getWhere({source_component_id:re.source_component_id});if(!K)continue;T4e(ee,K.schematic_component_id,{x:W.position.x+W.size.width/2+q.x,y:W.position.y+W.size.height/2+q.y})}if(L){if(!e.schematic_group.getWhere({source_group_id:L.source_group_id}))continue;I4e(ee,L.source_group_id,{x:W.position.x+W.size.width/2+q.x,y:W.position.y+W.size.height/2+q.y})}}r.schematic_group_id&&e.schematic_group.update(r.schematic_group_id,{width:O.width,height:O.height})},YW=1;function WGt(r){let{db:e}=r.root,a=r._parsedProps,s=KGt(r);if(s.length===0)return;let l=JGt({db:e,pcbChildren:s}),d=ZGt(a),x=QGt({props:a,pcbChildren:s,childDimensions:l,gridConfig:d}),f=rXt({pcbChildren:s,childDimensions:l,gridLayout:x,gridConfig:d}),{itemCoordinates:m}=f.layout();nXt({db:e,group:r,pcbChildren:s,itemCoordinates:m,gridLayout:x}),aXt({db:e,group:r,props:a,gridLayout:x})}function KGt(r){return r.children.filter(e=>e.pcb_component_id||e.pcb_group_id)}function JGt(r){let{db:e,pcbChildren:a}=r,s=0,l=0;for(let d of a){let x=0,f=0;if(d.pcb_group_id){let m=e.pcb_group.get(d.pcb_group_id);x=m?.width??0,f=m?.height??0}else if(d.pcb_component_id){let m=e.pcb_component.get(d.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 ZGt(r){let e=r.pcbGridCols??r.gridCols??r.pcbLayout?.grid?.cols,a=r.pcbGridRows??r.pcbLayout?.grid?.rows,s=r.pcbGridTemplateColumns,l=r.pcbGridTemplateRows,d=E=>E===void 0?YW:typeof E=="number"?E:pe.parse(E),x=r.pcbGridGap??r.gridGap??r.pcbLayout?.gridGap,f=r.pcbGridRowGap??r.gridRowGap??r.pcbLayout?.gridRowGap,m=r.pcbGridColumnGap??r.gridColumnGap??r.pcbLayout?.gridColumnGap,D=YW,b=YW;if(f!==void 0||m!==void 0){let E=typeof x=="object"?x?.x:x,A=typeof x=="object"?x?.y:x;D=d(m??E),b=d(f??A)}else if(typeof x=="object"&&x!==null)D=d(x.x),b=d(x.y);else{let E=d(x);D=E,b=E}return{cols:e,rows:a,gapX:D,gapY:b,templateColumns:s,templateRows:l}}function QGt(r){let{props:e,pcbChildren:a,childDimensions:s,gridConfig:l}=r;return e.pcbGridTemplateColumns||e.pcbGridTemplateRows?eXt({props:e,gridConfig:l,pcbChildren:a,childDimensions:s}):tXt({gridConfig:l,pcbChildren:a,childDimensions:s})}function eXt(r){let{props:e,gridConfig:a,pcbChildren:s,childDimensions:l}=r,d=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(d):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:d,gridTemplateRows:x,containerWidth:b,containerHeight:E}}function tXt(r){let{gridConfig:e,pcbChildren:a,childDimensions:s}=r,l,d;e.cols!==void 0&&e.rows!==void 0?(l=e.cols,d=e.rows):e.cols!==void 0?(l=e.cols,d=Math.ceil(a.length/l)):e.rows!==void 0?(d=e.rows,l=Math.ceil(a.length/d)):(l=Math.ceil(Math.sqrt(a.length)),d=Math.ceil(a.length/l)),l=Math.max(1,l),d=Math.max(1,d);let x=l*s.width+Math.max(0,l-1)*e.gapX,f=d*s.height+Math.max(0,d-1)*e.gapY,m=`repeat(${l}, ${s.width}px)`,D=`repeat(${d}, ${s.height}px)`;return{gridTemplateColumns:m,gridTemplateRows:D,containerWidth:x,containerHeight:f}}function rXt(r){let{pcbChildren:e,childDimensions:a,gridLayout:s,gridConfig:l}=r,d=e.map((x,f)=>({key:x.getString()||`child-${f}`,contentWidth:a.width,contentHeight:a.height}));return new gSe({containerWidth:s.containerWidth,containerHeight:s.containerHeight,gridTemplateColumns:s.gridTemplateColumns,gridTemplateRows:s.gridTemplateRows,gap:[l.gapY,l.gapX],children:d})}function nXt(r){let{db:e,group:a,pcbChildren:s,itemCoordinates:l,gridLayout:d}=r,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-d.containerWidth/2+E.x+E.width/2,B=x.y+d.containerHeight/2-E.y-E.height/2;if(D.pcb_component_id)C5(f,D.pcb_component_id,{x:A,y:B});else{let w=D;w.pcb_group_id&&w.source_group_id&&_5(f,w.source_group_id,{x:A,y:B})}}}function aXt(r){let{db:e,group:a,props:s,gridLayout:l}=r;if(a.pcb_group_id){let d=a._getGlobalPcbPositionBeforeLayout();e.pcb_group.update(a.pcb_group_id,{width:s.width??l.containerWidth,height:s.height??l.containerHeight,center:d})}}function sXt(r){let e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof r=="object"&&!r.preset)return{local:!(r.serverUrl||r.serverMode||r.serverCacheEnabled),...e,...r};let a=typeof r=="object"?r.preset:r,s=typeof r=="object"?r:{};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:d,groupMode:x,...f}=s;return{local:!1,groupMode:"subcircuit",...e,...f}}default:return{local:!0,groupMode:"subcircuit"}}}var iXt=(r,e)=>{let a=r.children.filter(E=>E.componentName==="Constraint"&&E._parsedProps.pcb),s=new Map,l={},d=E=>(l[E]!==E&&(l[E]=d(l[E])),l[E]),x=(E,A)=>{let B=d(E),w=d(A);B!==w&&(l[w]=B)},f=E=>{E in l||(l[E]=E)},m=E=>{let A=E.startsWith(".")?E.slice(1):E;return r.children.find(w=>w.name===A)?.pcb_component_id??void 0};for(let E of a){let A=E._parsedProps;if("left"in A&&"right"in A){let B=m(A.left),w=m(A.right);B&&w&&(f(B),f(w),x(B,w))}else if("top"in A&&"bottom"in A){let B=m(A.top),w=m(A.bottom);B&&w&&(f(B),f(w),x(B,w))}else if("for"in A&&Array.isArray(A.for)){let B=A.for.map(w=>m(w)).filter(w=>!!w);for(let w of B)f(w);for(let w=1;w<B.length;w++)x(B[0],B[w])}}for(let E of Object.keys(l)){let A=d(E);s.has(A)||s.set(A,{componentIds:[],constraints:[]}),s.get(A).componentIds.push(E)}for(let E of a){let A=E._parsedProps,B;if("left"in A?B=m(A.left):"top"in A?B=m(A.top):"for"in A&&(B=m(A.for[0])),!B)continue;let w=d(B);s.get(w)?.constraints.push(E)}let D={},b=Object.fromEntries(e.components.map(E=>[E.componentId,E]));for(let[E,A]of s.entries()){if(A.componentIds.length<=1)continue;let B=new ug,w={},P=(J,Q)=>{let de=`${J}_${Q}`;return w[de]||(w[de]=new rd(de)),w[de]},j=A.componentIds[0];B.addConstraint(new Vs(P(j,"x"),Ds.Eq,0,Oa.required)),B.addConstraint(new Vs(P(j,"y"),Ds.Eq,0,Oa.required));for(let J of A.constraints){let Q=J._parsedProps;if("xDist"in Q){let de=m(Q.left),oe=m(Q.right);de&&oe&&B.addConstraint(new Vs(new Xa(P(oe,"x"),[-1,P(de,"x")]),Ds.Eq,Q.xDist,Oa.required))}else if("yDist"in Q){let de=m(Q.top),oe=m(Q.bottom);de&&oe&&B.addConstraint(new Vs(new Xa(P(de,"y"),[-1,P(oe,"y")]),Ds.Eq,Q.yDist,Oa.required))}else if("sameX"in Q&&Array.isArray(Q.for)){let de=Q.for.map(oe=>m(oe)).filter(oe=>!!oe);if(de.length>1){let oe=P(de[0],"x");for(let Me=1;Me<de.length;Me++)B.addConstraint(new Vs(new Xa(P(de[Me],"x"),[-1,oe]),Ds.Eq,0,Oa.required))}}else if("sameY"in Q&&Array.isArray(Q.for)){let de=Q.for.map(oe=>m(oe)).filter(oe=>!!oe);if(de.length>1){let oe=P(de[0],"y");for(let Me=1;Me<de.length;Me++)B.addConstraint(new Vs(new Xa(P(de[Me],"y"),[-1,oe]),Ds.Eq,0,Oa.required))}}}B.updateVariables();let O={};for(let J of A.componentIds)O[J]={x:P(J,"x").value(),y:P(J,"y").value()};let q=1/0,ee=1/0,W=-1/0,re=-1/0;for(let J of A.componentIds){let Q=b[J],de=O[J];if(Q)for(let oe of Q.pads){let Me=de.x+oe.offset.x,Ne=de.y+oe.offset.y;q=Math.min(q,Me-oe.size.x/2),W=Math.max(W,Me+oe.size.x/2),ee=Math.min(ee,Ne-oe.size.y/2),re=Math.max(re,Ne+oe.size.y/2)}}let L={x:(q+W)/2,y:(ee+re)/2},K=[],U={};for(let J of A.componentIds){let Q=b[J],de=O[J];if(Q){U[J]={x:de.x-L.x,y:de.y-L.y};for(let oe of Q.pads)K.push({padId:oe.padId,networkId:oe.networkId,type:oe.type,size:oe.size,offset:{x:de.x+oe.offset.x-L.x,y:de.y+oe.offset.y-L.y}})}}e.components=e.components.filter(J=>!A.componentIds.includes(J.componentId)),e.components.push({componentId:A.componentIds[0],pads:K,availableRotationDegrees:[0]}),A.relativeCenters=U,D[A.componentIds[0]]=A}return D},VF=(r,e,a)=>{if(e===a)return!0;let s=r.source_group.get(e);return!s||!s.parent_source_group_id?!1:VF(r,s.parent_source_group_id,a)},oXt=(r,e,a)=>{let{db:s}=r.root;for(let l of e.components){let{center:d,componentId:x,ccwRotationOffset:f,ccwRotationDegrees:m}=l,D=a[x];if(D){let O=(m??f??0)*Math.PI/180;for(let q of D.componentIds){let ee=D.relativeCenters[q];if(!ee)continue;let W={x:ee.x*Math.cos(O)-ee.y*Math.sin(O),y:ee.x*Math.sin(O)+ee.y*Math.cos(O)},re=s.pcb_component.get(q);if(!re)continue;let L=re.center,K=js(r._computePcbGlobalTransformBeforeLayout(),Ma(d.x+W.x,d.y+W.y),Ip(O),Ma(-L.x,-L.y)),U=s.toArray().filter(J=>"pcb_component_id"in J&&J.pcb_component_id===q);pg(U,K)}continue}let b=s.pcb_component.get(x);if(b){let j=r.source_group_id,q=s.source_component.get(b.source_component_id)?.source_group_id;if(q!==void 0&&!VF(s,q,j))continue;let ee=b.center,W=m??f??0,re=js(r._computePcbGlobalTransformBeforeLayout(),Ma(d.x,d.y),Ip(W*Math.PI/180),Ma(-ee.x,-ee.y)),L=s.toArray().filter(K=>"pcb_component_id"in K&&K.pcb_component_id===x);pg(L,re);continue}let E=s.pcb_group.list().find(j=>j.source_group_id===x);if(!E)continue;let A=E.center,B=m??f??0,w=js(r._computePcbGlobalTransformBeforeLayout(),Ma(d.x,d.y),Ip(B*Math.PI/180),Ma(-A.x,-A.y)),P=s.toArray().filter(j=>{if("source_group_id"in j&&j.source_group_id&&(j.source_group_id===x||VF(s,j.source_group_id,x)))return!0;if("source_component_id"in j&&j.source_component_id){let O=s.source_component.get(j.source_component_id);if(O?.source_group_id&&(O.source_group_id===x||VF(s,O.source_group_id,x)))return!0}if("pcb_component_id"in j&&j.pcb_component_id){let O=s.pcb_component.get(j.pcb_component_id);if(O?.source_component_id){let q=s.source_component.get(O.source_component_id);if(q?.source_group_id&&(q.source_group_id===x||VF(s,q.source_group_id,x)))return!0}}return!1});pg(P,w),s.pcb_group.update(E.pcb_group_id,{center:d})}},uXt="1mm",NBe=(0,p9e.default)("Group_doInitialPcbLayoutPack"),cXt=r=>{let{db:e}=r.root,{_parsedProps:a}=r,{packOrderStrategy:s,packPlacementStrategy:l,gap:d,pcbGap:x,pcbPackGap:f}=a,m=f??x??d,D=pe.parse(m??uXt),b={},E=P=>{if(P?.pcb_component_id&&P?._parsedProps){let j=P._parsedProps,O=pe.parse(j.pcbMarginLeft??j.pcbMarginX??0),q=pe.parse(j.pcbMarginRight??j.pcbMarginX??0),ee=pe.parse(j.pcbMarginTop??j.pcbMarginY??0),W=pe.parse(j.pcbMarginBottom??j.pcbMarginY??0);(O||q||ee||W)&&(b[P.pcb_component_id]={left:O,right:q,top:ee,bottom:W})}P?.children&&P.children.forEach(E)};E(r);let A={...iSe(sSe(e.toArray(),{source_group_id:r.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:b})),orderStrategy:s??"largest_to_smallest",placementStrategy:l??"minimum_sum_squared_distance_to_network",minGap:D},B=iXt(r,A);NBe.enabled&&(r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${r.name}`,content:JSON.stringify(e.toArray())}),r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${r.name}`,content:A}));let w=ES(A);if(NBe.enabled){let P=yW(w);P.title=`packOutput-${r.name}`,global.debugGraphics?.push(P)}oXt(r,w,B)},lXt=r=>{let{db:e}=r.root,{_parsedProps:a}=r,s=r.children.filter(re=>re.pcb_component_id||re.pcb_group_id);if(s.some(re=>{let L=re._parsedProps;return L?.pcbX!==void 0||L?.pcbY!==void 0}))return;let d=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"}[d??"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: "${d}"`);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=pe.parse(f),A=pe.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=A5(s.map(re=>re._getMinimumFlexContainerSize()).filter(re=>re!==null),{alignItems:b,justifyContent:D,direction:m,rowGap:E,columnGap:A}),w=B.width,P=B.height);let O=new _S(w,P,{alignItems:b,justifyContent:D,direction:m,rowGap:E,columnGap:A});for(let re of s){let L=re._getMinimumFlexContainerSize();O.addChild({metadata:re,width:L?.width??0,height:L?.height??0,flexBasis:L?m==="row"?L.width:L.height:void 0})}O.build();let q={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let re of O.children)q.minX=Math.min(q.minX,re.position.x),q.minY=Math.min(q.minY,re.position.y),q.maxX=Math.max(q.maxX,re.position.x+re.size.width),q.maxY=Math.max(q.maxY,re.position.y+re.size.height);q.width=q.maxX-q.minX,q.height=q.maxY-q.minY;let ee=r._getGlobalPcbPositionBeforeLayout(),W={x:ee.x-(q.maxX+q.minX)/2,y:ee.y-(q.maxY+q.minY)/2};for(let re of O.children)re.metadata._repositionOnPcb({x:re.position.x+re.size.width/2+W.x,y:re.position.y+re.size.height/2+W.y});e.pcb_group.update(r.pcb_group_id,{width:q.width,height:q.height,center:ee})};function dXt(r){let{db:e}=r.root,a=new Map,s=new Map,l=new Set,x=r.selectAll("trace").filter(Q=>Q._parsedProps?.schDisplayLabel),f=r.selectAll("group"),m=[r.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,oe=[],Me=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 Ge of Ne){let tt=`${Me?.name??Q.schematic_component_id}.${Ge.pin_number}`;E.set(tt,Ge.schematic_port_id),A.set(Ge.schematic_port_id,tt)}for(let Ge of Ne){let tt=A.get(Ge.schematic_port_id);oe.push({pinId:tt,x:Ge.center.x,y:Ge.center.y})}b.push({chipId:de,center:Q.center,width:Q.size.width,height:Q.size.height,pins:oe})}let B=new Set,w=new Map,P=new Map,j=new Map;for(let Q of D){let de=e.schematic_port.list({schematic_component_id:Q.schematic_component_id});for(let oe of de)B.add(oe.schematic_port_id),oe.source_port_id&&(w.set(oe.schematic_port_id,oe.source_port_id),P.set(oe.source_port_id,oe.schematic_port_id))}let O=new Set;r.subcircuit_id&&O.add(r.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===r.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 W=[],re=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(oe=>P.get(oe)).filter(oe=>!!oe&&B.has(oe));if(de.length>=2){let[oe,Me]=de.slice(0,2),Ne=[oe,Me].sort().join("::");if(!re.has(Ne)){re.set(Ne,Q.source_trace_id);let Ge=Q.display_name??Q.source_trace_id;Q.subcircuit_connectivity_map_key&&(l.add(Q.subcircuit_connectivity_map_key),j.set(Ge,Q.subcircuit_connectivity_map_key),s.set(Q.subcircuit_connectivity_map_key,Ge)),W.push({pinIds:[oe,Me].map(tt=>A.get(tt)),netId:Ge})}}}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 oe=e.source_port.get(de);if(!oe?.subcircuit_connectivity_map_key)continue;let Me=oe.subcircuit_connectivity_map_key;l.add(Me),K.has(Me)||K.set(Me,[]),K.get(Me).push(Q)}for(let[Q,de]of K){let oe=a.get(Q);if(oe&&de.length>=2){let Me=String(oe.name||oe.source_net_id||Q);j.set(Me,Q),s.set(Q,Me);let Ge=.1*(.18/.18),tt=Number((String(Me).length*Ge).toFixed(2));L.push({netId:Me,pinIds:de.map(He=>A.get(He)),netLabelWidth:tt})}}let U=(()=>{let Q={},de=new Set(L.map(oe=>oe.netId));for(let oe of e.source_net.list().filter(Me=>!Me.subcircuit_id||O.has(Me.subcircuit_id)))oe.name&&de.has(oe.name)&&(oe.is_ground||oe.name.toLowerCase().startsWith("gnd")?Q[oe.name]=["y-"]:oe.is_power||oe.name.toLowerCase().startsWith("v")?Q[oe.name]=["y+"]:Q[oe.name]=["x-","x+"]);return Q})();return{inputProblem:{chips:b,directConnections:W,netConnections:L,availableNetLabelOrientations:U,maxMspPairDistance:r._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:E,pairKeyToSourceTraceId:re,sckToSourceNet:a,sckToUserNetId:s,userNetIdToSck:j,allSourceAndSchematicPortIdsInScope:B,schPortIdToSourcePortId:w,displayLabelTraces:x,allScks:l}}var Qi=1e-6;function MBe(r){let e=Math.abs(r.to.x-r.from.x),a=Math.abs(r.to.y-r.from.y);return e>=a}function WS(r,e){return Math.hypot(e.x-r.x,e.y-r.y)}function OBe(r,e,a){return{x:r.x+(e.x-r.x)*a,y:r.y+(e.y-r.y)*a}}function LBe(r,e,a){let s=WS(r,e);if(s<Qi)return 0;let l=((a.x-r.x)*(e.x-r.x)+(a.y-r.y)*(e.y-r.y))/((e.x-r.x)*(e.x-r.x)+(e.y-r.y)*(e.y-r.y));return Math.max(0,Math.min(1,l))*s}function $S(r,e,a,s){return r*s-e*a}function pXt(r,e,a,s){let l={x:e.x-r.x,y:e.y-r.y},d={x:s.x-a.x,y:s.y-a.y},x=$S(l.x,l.y,d.x,d.y),f={x:a.x-r.x,y:a.y-r.y},m=$S(f.x,f.y,l.x,l.y);if(Math.abs(x)<Qi&&Math.abs(m)<Qi||Math.abs(x)<Qi&&Math.abs(m)>=Qi)return null;let D=$S(f.x,f.y,d.x,d.y)/x,b=$S(f.x,f.y,l.x,l.y)/x;return D<-Qi||D>1+Qi||b<-Qi||b>1+Qi?null:{x:r.x+D*l.x,y:r.y+D*l.y}}function xXt(r,e=Qi){if(r.length===0)return r;r.sort((l,d)=>l.start-d.start);let a=[],s={...r[0]};for(let l=1;l<r.length;l++){let d=r[l];d.start<=s.end+e?s.end=Math.max(s.end,d.end):(a.push(s),s={...d})}return a.push(s),a}function fXt(r,e,a){let s=WS(r.from,r.to);if(s<Qi||e.length===0)return[r];let l=a/2,d=e.map(E=>({start:Math.max(0,E-l),end:Math.min(s,E+l)})).filter(E=>E.end-E.start>Qi),x=xXt(d),f=[],m=0,D={x:r.to.x-r.from.x,y:r.to.y-r.from.y},b=(E,A,B)=>{if(A-E<=Qi)return;let w=E/s,P=A/s;f.push({from:OBe(r.from,r.to,w),to:OBe(r.from,r.to,P),...B?{is_crossing:!0}:{}})};for(let E of x)E.start-m>Qi&&b(m,E.start,!1),b(E.start,E.end,!0),m=E.end;return s-m>Qi&&b(m,s,!1),f.length>0?f:[r]}function hXt(r,e={}){let a=e.crossSegmentLength??.075,s=e.tolerance??Qi,l=new Map,d=m=>`${m.traceIdx}:${m.edgeIdx}`,x=m=>r[m.traceIdx].edges[m.edgeIdx];for(let m=0;m<r.length;m++){let D=r[m];for(let b=0;b<D.edges.length;b++){let E=D.edges[b];for(let A=m;A<r.length;A++){let B=r[A];for(let w=A===m?b+1:0;w<B.edges.length;w++){let P=B.edges[w],j=pXt(E.from,E.to,P.from,P.to);if(!j)continue;let O=WS(E.from,E.to),q=WS(P.from,P.to);if(O<s||q<s)continue;let ee=LBe(E.from,E.to,j),W=LBe(P.from,P.to,j),re=ee<=s||Math.abs(O-ee)<=s||Number.isNaN(ee),L=W<=s||Math.abs(q-W)<=s||Number.isNaN(W);if(!re&&!L){let K=MBe(E),U=MBe(P),J;if(K!==U)J=K;else{let oe=Math.abs(E.to.x-E.from.x),Me=Math.abs(E.to.y-E.from.y),Ne=Math.abs(P.to.x-P.from.x),Ge=Math.abs(P.to.y-P.from.y),tt=oe-Me,He=Ne-Ge;J=tt===He?!0:tt>He}let Q=d({traceIdx:J?m:A,edgeIdx:J?b:w}),de=l.get(Q)??[];de.push(J?ee:W),l.set(Q,de)}}}}}let f=r.map(m=>({source_trace_id:m.source_trace_id,edges:[]}));for(let m=0;m<r.length;m++){let D=r[m];for(let b=0;b<D.edges.length;b++){let E=d({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,j)=>P-j),w=fXt(D.edges[b],B,a);f[m].edges.push(...w)}}return f}var al=1e-6;function KS(r,e,a=al){return Math.abs(r-e)<=a}function Hg(r,e,a=al){return KS(r.x,e.x,a)&&KS(r.y,e.y,a)}function $Be(r,e,a,s=al){let l=Math.min(e.x,a.x)-s,d=Math.max(e.x,a.x)+s,x=Math.min(e.y,a.y)-s,f=Math.max(e.y,a.y)+s;return r.x<l||r.x>d||r.y<x||r.y>f?!1:Math.abs((a.x-e.x)*(r.y-e.y)-(a.y-e.y)*(r.x-e.x))<=s}function zBe(r,e=al){let a=new Map;for(let s of r){let l=`${s.x.toFixed(6)},${s.y.toFixed(6)}`;a.has(l)||a.set(l,s)}return Array.from(a.values())}function qBe(r){return{x:r.to.x-r.from.x,y:r.to.y-r.from.y}}function HW(r,e,a=al){let s=qBe(r),l=qBe(e),d=Math.hypot(s.x,s.y),x=Math.hypot(l.x,l.y);if(d<a||x<a)return!0;let f=s.x*l.y-s.y*l.x;return Math.abs(f)<=a*d*x}function GF(r,e,a=al){return r.edges.filter(s=>Hg(s.from,e,a)||Hg(s.to,e,a))}function UBe(r,e,a=al){for(let s of r.edges){if(Hg(s.from,e,a))return s.from;if(Hg(s.to,e,a))return s.to}return null}function mXt(r,e,a=al){let s=Hg(r.from,e,a)||KS(r.from.x,e.x,a)&&KS(r.from.y,e.y,a)?r.to:r.from,l=s.x-e.x,d=s.y-e.y;return Math.abs(l)<a&&Math.abs(d)<a?null:Math.abs(l)>=Math.abs(d)?l>=0?"right":"left":d>=0?"up":"down"}function Vg(r,e,a=al){let s=GF(r,e,a);if(s.length<2)return null;let l=s.map(E=>mXt(E,e,a)),d=l.includes("up"),x=l.includes("down"),f=l.includes("left"),m=l.includes("right"),D=d?"up":x?"down":null,b=m?"right":f?"left":null;return D&&b?`${D}-${b}`:null}function gXt(r,e={}){let a=e.tolerance??al,s={};for(let d of r)s[d.source_trace_id]=[];let l=r.map(d=>{let x=[];for(let f of d.edges)x.push(f.from,f.to);return zBe(x,a)});for(let d=0;d<r.length;d++){let x=r[d],f=l[d];for(let m=d+1;m<r.length;m++){let D=r[m],b=l[m];for(let E of f)for(let A of b)if(Hg(E,A,a)){let B=GF(x,E,a),w=GF(D,A,a),P=B.some(ee=>w.some(W=>!HW(ee,W,a))),j=Vg(x,E,a),O=Vg(D,A,a);P&&!(j!==null&&O!==null&&j===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($Be(E,A.from,A.to,a)){let w=GF(x,E,a).some(ee=>!HW(ee,A,a)),P=Vg(x,E,a),j=UBe(D,E,a*1e3),O=j?Vg(D,j,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($Be(E,A.from,A.to,a)){let w=GF(D,E,a).some(ee=>!HW(A,ee,a)),P=Vg(D,E,a),j=UBe(x,E,a*1e3),O=j?Vg(x,j,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 d of Object.keys(s))s[d]=zBe(s[d],a);return s}var WW=(0,f9e.default)("Group_doInitialSchematicTraceRender");function DXt(r){let{group:e,solver:a,pinIdToSchematicPortId:s,userNetIdToSck:l}=r,{db:d}=e.root,x=a.traceOverlapShiftSolver?.correctedTraceMap,f=[];WW(`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){WW(`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),j=s.get(b.pins[1]?.pinId);if(P&&j){for(let O of[P,j])d.schematic_port.get(O)&&d.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})}WW(`Applying ${f.length} traces from SchematicTraceSolver output`);let m=hXt(f.map(b=>({source_trace_id:b.source_trace_id,edges:b.edges}))),D=gXt(m);for(let b of m)d.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 yXt=r=>{switch(r){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"}},bXt=r=>{for(let a of r){let s=a._getDirectlyConnectedTraces();for(let l of s){let d=l._parsedProps.schDisplayLabel;if(d)return{name:d,wasAssignedDisplayLabel:!0}}}return{name:r.map(a=>a._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},KW=(0,h9e.default)("Group_doInitialSchematicTraceRender");function FXt(r){let{group:e,solver:a,sckToSourceNet:s,allScks:l,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,userNetIdToSck:f,pinIdToSchematicPortId:m,schematicPortIdsWithPreExistingNetLabels:D,schematicPortIdsWithRoutedTraces:b}=r,{db:E}=e.root,A=a.netLabelPlacementSolver?.netLabelPlacements??[],B=a.mspConnectionPairSolver.globalConnMap;for(let w of A){KW(`processing placement: ${w.netId}`);let P=B.getIdsConnectedToNet(w.globalConnNetId).find(Q=>f.get(Q)),j=f.get(P),O=w.anchorPoint,q=w.orientation,ee=yXt(q),W=j?s.get(j):void 0,re=w.pinIds.map(Q=>m.get(Q));if(re.some(Q=>D.has(Q))){KW(`skipping net label placement for "${w.netId}" REASON:schematic port has pre-existing net label`);continue}if(W){let Q=W.name,de=sx({anchor_position:O,anchor_side:ee,text:Q});E.schematic_net_label.insert({text:Q,anchor_position:O,center:de,anchor_side:ee,...W?.source_net_id?{source_net_id:W.source_net_id}:{}});continue}let L=e.selectAll("port").filter(Q=>Q._getSubcircuitConnectivityKey()===j),{name:K,wasAssignedDisplayLabel:U}=bXt(L);if(!U&&re.some(Q=>b.has(Q))){KW(`skipping net label placement for "${w.netId}" REASON:schematic port has routed traces and no display label`);continue}let J=sx({anchor_position:O,anchor_side:ee,text:K});E.schematic_net_label.insert({text:K,anchor_position:O,center:J,anchor_side:ee})}}var EXt=({allSourceAndSchematicPortIdsInScope:r,group:e,schPortIdToSourcePortId:a,sckToSourceNet:s,pinIdToSchematicPortId:l,schematicPortIdsWithPreExistingNetLabels:d})=>{let{db:x}=e.root;for(let f of Array.from(r)){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=HF(m.facing_direction||"right")||"right",j=sx({anchor_position:m.center,anchor_side:P,text:w});x.schematic_net_label.insert({text:w,anchor_position:m.center,center:j,anchor_side:P,...A.source_net_id?{source_net_id:A.source_net_id}:{}})}},vXt=r=>{let e=new Set,a=r.selectAll("netlabel");for(let s of a){let l=s._getConnectedPorts();for(let d of l)d.schematic_port_id&&e.add(d.schematic_port_id)}return e},CXt=({solver:r,pinIdToSchematicPortId:e})=>{let a=r.schematicTraceLinesSolver.solvedTracePaths,s=new Set;for(let l of a)for(let d of l.pinIds){let x=e.get(d);x&&s.add(x)}return s},_Xt=(0,x9e.default)("Group_doInitialSchematicTraceRender"),AXt=r=>{if(!r.root?._featureMspSchematicTraceRouting||!r.isSubcircuit||r.root?.schematicDisabled)return;let{inputProblem:e,pinIdToSchematicPortId:a,pairKeyToSourceTraceId:s,sckToSourceNet:l,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,displayLabelTraces:f,allScks:m,userNetIdToSck:D}=dXt(r),b=vXt(r);_Xt.enabled&&r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(e,null,2)});let E=new wSe(e);E.solve();let A=CXt({solver:E,pinIdToSchematicPortId:a});DXt({group:r,solver:E,pinIdToSchematicPortId:a,userNetIdToSck:D}),FXt({group:r,solver:E,sckToSourceNet:l,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,pinIdToSchematicPortId:a,allScks:m,userNetIdToSck:D,schematicPortIdsWithPreExistingNetLabels:b,schematicPortIdsWithRoutedTraces:A}),EXt({group:r,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,sckToSourceNet:l,pinIdToSchematicPortId:a,schematicPortIdsWithPreExistingNetLabels:b})},Wg=class extends es{constructor(){super(...arguments);z(this,"pcb_group_id",null);z(this,"schematic_group_id",null);z(this,"subcircuit_id",null);z(this,"_hasStartedAsyncAutorouting",!1);z(this,"_asyncAutoroutingResult",null);z(this,"unnamedElementCounter",{})}get config(){return{zodProps:oAe,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=ZS(this.children);if(this.pcb_group_id){let l=s.width,d=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,d+=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??d),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,d=s("paddingX"),x=s("paddingY"),f=s("paddingLeft")??d??l,m=s("paddingRight")??d??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 d of l)this.add(new fK({for:d.pcb_port_selector,offsets:d.offsets}))}doInitialSourceAddConnectivityMapKey(){XGt(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,Gg.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,Gg.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),s=this._parsedProps,l=this._getAutorouterConfig(),d=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(`${d}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:nK({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(`${d}/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(`${d}/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(`${d}/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(`${d}/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 UF(`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,Gg.default)("tscircuit:core:_runLocalAutorouting");s(`[${this.getString()}] starting local autorouting`);let l=this._getAutorouterConfig(),{simpleRouteJson:d}=nK({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(s.enabled){let m=aH(d);m.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(m)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:d});let x;l.algorithmFn?x=await l.algorithmFn(d):x=new MGt(d,{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:d}),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,Gg.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(){AXt(this)}updatePcbTraceRender(){let e=(0,Gg.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 d=l._parsedProps;return d?.schX!==void 0||d?.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(){UGt(this)}_doInitialSchematicLayoutMatchpack(){GGt(this)}_doInitialSchematicLayoutGrid(){YGt(this)}_doInitialSchematicLayoutFlex(){HGt(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 d=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&&d>1?"pack":"none"}doInitialPcbLayout(){let e=this._getPcbLayoutMode();e==="grid"?this._doInitialPcbLayoutGrid():e==="pack"?this._doInitialPcbLayoutPack():e==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){WGt(this)}_doInitialPcbLayoutPack(){cXt(this)}_doInitialPcbLayoutFlex(){lXt(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,d=typeof a.schPadding=="number"?a.schPadding:0,x=typeof a.schPaddingLeft=="number"?a.schPaddingLeft:d,f=typeof a.schPaddingRight=="number"?a.schPaddingRight:d,m=typeof a.schPaddingTop=="number"?a.schPaddingTop:d,D=typeof a.schPaddingBottom=="number"?a.schPaddingBottom:d,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,d=-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),d=Math.max(d,f.centerY);let x=2;return{minX:a-x,maxX:s+x,minY:l-x,maxY:d+x}}_getAutorouterConfig(){let e=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return sXt(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(d=>d.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),d=s.text||l?.name||"";if(s.anchor_side==="top"&&/^gnd/i.test(d)){a.schematic_net_label.update(s.schematic_net_label_id,{symbol_name:"rail_down"});continue}s.anchor_side==="bottom"&&/^v/i.test(d)&&a.schematic_net_label.update(s.schematic_net_label_id,{symbol_name:"rail_up"})}}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(e){return super._repositionOnPcb(e)}},VBe=(r,e,a)=>{let s=Math.min(a,r/2,e/2),l=Math.max(1,Math.ceil(Math.PI/2*s)),d=Math.PI/2/l,x=r/2,f=e/2,m=[];m.push({x:-x+s,y:-f}),m.push({x:x-s,y:-f});for(let D=1;D<=l;D++){let b=-Math.PI/2+D*d;m.push({x:x-s+s*Math.cos(b),y:-f+s+s*Math.sin(b)})}m.push({x,y:f-s});for(let D=1;D<=l;D++){let b=0+D*d;m.push({x:x-s+s*Math.cos(b),y:f-s+s*Math.sin(b)})}m.push({x:-x+s,y:f});for(let D=1;D<=l;D++){let b=Math.PI/2+D*d;m.push({x:-x+s+s*Math.cos(b),y:f-s+s*Math.sin(b)})}m.push({x:-x,y:-f+s});for(let D=1;D<=l;D++){let b=Math.PI+D*d;m.push({x:-x+s+s*Math.cos(b),y:-f+s+s*Math.sin(b)})}return m},m9e=class extends Wg{constructor(){super(...arguments);z(this,"pcb_board_id",null);z(this,"_drcChecksComplete",!1);z(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:SY}}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,d=-1/0,x=-1/0,f=c9e(e,this.subcircuit_id),m=new Set([this.subcircuit_id,...f]),D=e.pcb_component.list().filter(re=>re.subcircuit_id&&m.has(re.subcircuit_id)),b=e.pcb_group.list().filter(re=>re.subcircuit_id&&m.has(re.subcircuit_id)),E=!1,A=(re,L,K)=>{L===0||K===0||(E=!0,s=Math.min(s,re.x-L/2),l=Math.min(l,re.y-K/2),d=Math.max(d,re.x+L/2),x=Math.max(x,re.y+K/2))};for(let re of D)A(re.center,re.width,re.height);for(let re of b)A(re.center,re.width,re.height);let B=2,w=E?d-s+B*2:0,P=E?x-l+B*2:0,j={x:E?(s+d)/2+(a.outlineOffsetX??0):a.outlineOffsetX??0,y:E?(l+x)/2+(a.outlineOffsetY??0):a.outlineOffsetY??0},O=a.width??w,q=a.height??P,ee=a.outline;!ee&&a.borderRadius!=null&&O>0&&q>0&&(ee=VBe(O,q,a.borderRadius));let W={width:O,height:q,center:j};ee&&(W.outline=ee.map(re=>({x:re.x+(a.outlineOffsetX??0),y:re.y+(a.outlineOffsetY??0)}))),e.pcb_board.update(this.pcb_board_id,W)}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(`
1038
+ `),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,d={x:(a.pcbX??0)+(a.outlineOffsetX??0),y:(a.pcbY??0)+(a.outlineOffsetY??0)};if(a.outline){let m=a.outline.map(w=>w.x),D=a.outline.map(w=>w.y),b=Math.min(...m),E=Math.max(...m),A=Math.min(...D),B=Math.max(...D);s=E-b,l=B-A,d={x:(b+E)/2+(a.outlineOffsetX??0),y:(A+B)/2+(a.outlineOffsetY??0)}}let x=a.outline;!x&&a.borderRadius!=null&&s>0&&l>0&&(x=VBe(s,l,a.borderRadius));let f=e.pcb_board.insert({center:d,thickness:this.boardThickness,num_layers:this.allLayers.length,width:s,height:l,outline:x?.map(m=>({x:m.x+(a.outlineOffsetX??0),y:m.y+(a.outlineOffsetY??0)})),material:a.material});this.pcb_board_id=f.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 Si()}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=jSe(e.toArray());for(let d of a)e.pcb_trace_error.insert(d);let s=ISe(e.toArray());for(let d of s)e.pcb_port_not_connected_error.insert(d);let l=MSe(e.toArray());for(let d of l)e.pcb_component_outside_board_error.insert(d)}_emitRenderLifecycleEvent(e,a){super._emitRenderLifecycleEvent(e,a),a==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e})}},RXt=new Proxy({},{get:(r,e)=>e}),dd=RXt,g9e="rgba(132, 0, 0)",D9e=.12,y9e=class extends es{constructor(){super(...arguments);z(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:gAe,sourceFtype:dd.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:`${Ns(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${a}/${Ns(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 qc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new qc({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}},QS=class extends es{constructor(e){super(e);z(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:og,shouldRenderAsSchematicBox:!0}}initPorts(e={}){super.initPorts(e);let{_parsedProps:a}=this;if(a.externallyConnectedPins){let s=new Set;for(let[l,d]of a.externallyConnectedPins)s.add(l),s.add(d);for(let l of s)if(!this.children.find(x=>x instanceof Ni&&x.isMatchingAnyOf([l]))){let x=l.match(/^pin(\d+)$/);if(x){let f=parseInt(x[1]);this.add(new Ni({pinNumber:f,aliases:[l]}))}else this.add(new Ni({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 qc({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,d,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,d=B.providesVoltage),B.providesGround&&(l=E)}if(!s||!l||d===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:d})}},b9e=class extends QS{constructor(r){super(r)}get config(){return{...super.config,componentName:"Pinout",zodProps:uAe}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.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}},F9e=class extends es{constructor(){super(...arguments);z(this,"pos",this.portMap.pin1);z(this,"anode",this.portMap.pin1);z(this,"neg",this.portMap.pin2);z(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:IAe,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}},E9e=class extends es{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:lAe,sourceFtype:dd.simple_fuse}}_getSchematicSymbolDisplayValue(){let r=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,a=typeof r=="string"?parseFloat(r):r,s=typeof e=="string"?parseFloat(e):e;return`${Ns(a)}A / ${Ns(s)}V`}doInitialSourceRender(){let{db:r}=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=r.source_component.insert({name:this.name,ftype:dd.simple_fuse,current_rating_amps:a,voltage_rating_volts:s,display_current_rating:`${Ns(a)}A`,display_voltage_rating:`${Ns(s)}V`});this.source_component_id=l.source_component_id}},v9e=class extends es{constructor(){super(...arguments);z(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:BY,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}),d=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=d(f.start_pcb_port_id),f.end_pcb_port_id=d(f.end_pcb_port_id))}},C9e=class extends es{constructor(){super(...arguments);z(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 d=(e.bridgedPins??[]).flat().map(D=>this._getPinNumberFromBridgedPinName(D)).filter(D=>D!==null),x=d.length>0?Math.max(...d):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(d=>this._getPinNumberFromBridgedPinName(d)).filter(d=>d!==null))).sort((d,x)=>d-x):e.bridged&&a&&(l=Array.from({length:a},(d,x)=>x+1)),l.length>0&&(s+=`_bridged${l.join("")}`),{schematicSymbolName:e.symbolName??s,componentName:"SolderJumper",zodProps:cAe,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}),d=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=d(f.start_pcb_port_id),f.end_pcb_port_id=d(f.end_pcb_port_id))}},_9e=class extends es{constructor(){super(...arguments);z(this,"pos",this.portMap.pin1);z(this,"anode",this.portMap.pin1);z(this,"neg",this.portMap.pin2);z(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:kAe,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}},A9e=class extends es{constructor(){super(...arguments);z(this,"pos",this.portMap.pin1);z(this,"positive",this.portMap.pin1);z(this,"neg",this.portMap.pin2);z(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:YAe,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Ni({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Ni({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db: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}},SXt=gs.extend({voltage:Us.optional(),frequency:Oc.optional(),peakToPeakVoltage:Us.optional(),waveShape:v.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Gn.optional(),dutyCycle:v.number().optional()}),R9e=class extends es{constructor(){super(...arguments);z(this,"terminal1",this.portMap.terminal1);z(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:SXt,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})}},S9e=class extends es{constructor(){super(...arguments);z(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:pAe,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${Ns(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 qc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new qc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new qc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new qc({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}},BXt=["leftedge","rightedge","topedge","bottomedge","center"],B9e=class extends qn{get config(){return{componentName:"Constraint",zodProps:yAe}}constructor(r){if(super(r),("xdist"in r||"ydist"in r)&&!("edgeToEdge"in r)&&!("centerToCenter"in r))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in r&&r.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let r=[],e=this.getPrimitiveContainer();function a(s){let l=s.split(" ").pop(),d=BXt.includes(l)?l:void 0,x=d?s.replace(` ${d}`,""):s,f=e.selectOne(x,{pcbPrimitive:!0});f&&r.push({selector:s,component:f,componentSelector:x,edge:d})}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:r}}},w9e=class extends qn{constructor(){super(...arguments);z(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:LAe}}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 d=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=as(d,{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}},T9e=class extends qn{get config(){return{componentName:"FabricationNoteText",zodProps:OAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:r}=this.root,{_parsedProps:e}=this,a=this.getPrimitiveContainer(),s=this.getSubcircuit();r.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})}},P9e=class extends Wg{constructor(r){super({...r,subcircuit:!0})}},I9e=class extends Wg{constructor(r){super({...r,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:r}=this.root,e=this._parsedProps;if(!this.pcb_group_id)return;let a=r.pcb_group.get(this.pcb_group_id),s=e.paddingLeft??e.padding??0,l=e.paddingRight??e.padding??0,d=e.paddingTop??e.padding??0,x=e.paddingBottom??e.padding??0;r.pcb_group.update(this.pcb_group_id,{width:a.width+s+l,height:a.height+d+x,center:{x:a.center.x+(l-s)/2,y:a.center.y+(d-x)/2}})}},j9e=class extends qn{constructor(){super(...arguments);z(this,"pcb_breakout_point_id",null);z(this,"matchedPort",null);z(this,"matchedNet",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:qAe}}_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(),d=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:d?.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}}},k9e=class extends qn{constructor(){super(...arguments);z(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:SAe}}_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 d=l[0]._getGlobalSchematicPositionBeforeLayout(),x=d.x-s.x,f=d.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=as(this.parent?.computeSchematicGlobalTransform?.()??Si(),{x:0,y:0});return Ma(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()}`),d=a.anchorSide??"right",x=sx({anchor_position:s,anchor_side:d,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&&uK(this,[`net.${e.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let e=this._resolveConnectsTo();if(e)for(let a of e)this.add(new qc({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(q=>q.connected_source_net_ids?.includes(f.source_net_id)&&q.connected_source_port_ids?.includes(D.source_port_id??""));if(O&&(b=e.schematic_trace.list().some(q=>q.source_trace_id===O.source_trace_id)),b)continue}let E=D._getGlobalSchematicPositionAfterLayout(),A=eK(D.facingDirection??"right")??"x+",B=dg({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,j;if(f?.source_net_id&&D.source_port_id){let O=e.source_trace.list().find(q=>q.connected_source_net_ids?.includes(f.source_net_id)&&q.connected_source_port_ids?.includes(D.source_port_id));P=O?.source_trace_id,j=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:j}),e.schematic_port.update(D.schematic_port_id,{is_connected:!0})}}},N9e=class extends qn{constructor(){super(...arguments);z(this,"pcb_silkscreen_circle_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:s4e}}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 d=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}}},M9e=class extends qn{constructor(){super(...arguments);z(this,"pcb_silkscreen_rect_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:a4e}}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 d=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:d?.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}}},O9e=class extends qn{constructor(){super(...arguments);z(this,"pcb_silkscreen_line_id",null);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:n4e}}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 d=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:d?.subcircuit_id??void 0,pcb_group_id:d?.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}}},L9e=class extends qn{constructor(e){super(e);z(this,"pcb_via_id",null);z(this,"matchedPort",null);z(this,"isPcbPrimitive",!0);z(this,"source_manually_placed_via_id",null);let a=this._getLayers();this._parsedProps.layers=a,this.initPorts()}get config(){return{componentName:"Via",zodProps:$Ae}}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 Ni({name:s,layer:s});l.registerMatch(this),this.add(l)}let a=new Ni({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(),d=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=d.pcb_component_id}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getGroup(),l=this.getSubcircuit(),d=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=d.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(),d=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=d.pcb_via_id}},$9e=class extends qn{constructor(){super(...arguments);z(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:VAe}}getPcbSize(){return{width:0,height:0}}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit().selectOne(a.connectsTo);if(!s||!s.source_net_id){this.renderError(`Net "${a.connectsTo}" not found for copper pour`);return}let l=e.pcb_board.list()[0];if(!l){this.renderError("No board found for copper pour");return}let d;l.outline&&l.outline.length>0?d=new se.Polygon(l.outline.map(B=>se.point(B.x,B.y))):d=new se.Polygon(new se.Box(l.center.x-l.width/2,l.center.y-l.height/2,l.center.x+l.width/2,l.center.y+l.height/2).toPoints());let x=eu(e.toArray()),f=pK(e.toArray(),x).filter(B=>B.layers.includes(a.layer));for(let B of e.pcb_trace.list())if(B.route)for(let w=0;w<B.route.length-1;w++){let P=B.route[w],j=B.route[w+1];if(P.route_type!=="wire"||j.route_type!=="wire"||P.layer!==a.layer)continue;let O=P.width;if(O===0)continue;let q=Math.hypot(P.x-j.x,P.y-j.y);if(q===0)continue;let ee=(P.x+j.x)/2,W=(P.y+j.y)/2,re=Math.atan2(j.y-P.y,j.x-P.x)*180/Math.PI,K=s9e({center:{x:ee,y:W},width:q,height:O,rotation:re});for(let U of K)f.push({type:"rect",layers:[P.layer],center:U.center,width:U.width,height:U.height,connectedTo:B.source_trace_id?[B.source_trace_id]:[],obstacle_type:"trace"})}let m=[],D=[],b=a.traceMargin??.2,E=a.padMargin??.2;for(let B of f){if(B.connectedTo.some(O=>x.areIdsConnected(O,s.source_net_id)))continue;if(B.type==="oval"&&B.width===B.height){let O=B.width/2+E;D.push({center:B.center,radius:O});continue}if(B.type==="rect"&&B.width===B.height&&B.connectedTo.length===0){let O=B.width/2;D.push({center:B.center,radius:O});continue}let P=b,j=new se.Box(B.center.x-B.width/2-P,B.center.y-B.height/2-P,B.center.x+B.width/2+P,B.center.y+B.height/2+P);m.push(new se.Polygon(j.toPoints()))}let A=d;if(m.length>0){let B=m.reduce((w,P)=>se.BooleanOperations.unify(w,P));B&&!B.isEmpty()&&(A=se.BooleanOperations.subtract(d,B))}Array.isArray(A)||(A=[A]);for(let B of A){let w=B.splitToIslands();for(let P of w){if(P.isEmpty())continue;let j=[...P.faces],O=j.find(L=>L.orientation()===se.ORIENTATION.CCW),q=j.filter(L=>L.orientation()===se.ORIENTATION.CW);if(!O)continue;if(!e.pcb_copper_pour){this.renderError("db.pcb_copper_pour not found. The database schema may be outdated.");return}let ee=L=>L.edges.map(K=>{let U={x:K.start.x,y:K.start.y};if(K.isArc){let J=Math.tan(K.shape.sweep/4);Math.abs(J)>1e-9&&(U.bulge=J)}return U});O.reverse();let W=ee(O),re=q.map(L=>(L.reverse(),{vertices:ee(L)}));for(let L of D){let K=se.point(L.center.x,L.center.y);P.contains(K)&&re.push({vertices:[{x:L.center.x,y:L.center.y-L.radius,bulge:1},{x:L.center.x,y:L.center.y+L.radius,bulge:1}]})}e.pcb_copper_pour.insert({shape:"brep",layer:a.layer,brep_shape:{outer_ring:{vertices:W},inner_rings:re},source_net_id:s.source_net_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0})}}})}},z9e=class extends es{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:AAe,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.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}},q9e=class extends es{_getPcbRotationBeforeLayout(){let r=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+r}get config(){return{componentName:"PinHeader",zodProps:RAe,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let r=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(r>0){let d;if(s)!e&&!a?d=`pinrow${r}_p${s}`:d=`pinrow${r}_p${s}_id${e}_od${a}`;else if(!e&&!a)d=`pinrow${r}`;else return null;return l!==!0&&(d+="_nopinlabels"),d}return null}initPorts(){let r=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<=r;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 Ni({pinNumber:e,name:s,aliases:[`pin${e}`,...l]}))}else this.add(new Ni({pinNumber:e,name:`pin${e}`}))}}_getSchematicPortArrangement(){let r=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:r},(s,l)=>`pin${l+1}`)}}:{rightSide:{direction:a?.rightSide?.direction??"top-to-bottom",pins:a?.rightSide?.pins??Array.from({length:r},(s,l)=>`pin${l+1}`)}}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.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 wXt(r){switch(r){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var U9e=class extends es{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??wXt(this.props.pinVariant),zodProps:mAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=e.pinVariant||"no_ground",s=r.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 r=`${Ns(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${r} / ${Ns(this._parsedProps.loadCapacitance)}F`:r}},V9e=class extends es{constructor(){super(...arguments);z(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:PAe,sourceFtype:dd.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${Ns(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:dd.simple_inductor,inductance:a.inductance,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}};function TXt(r){switch(r){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var G9e=class extends es{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??TXt(this.props.pinVariant),zodProps:fAe,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${Ns(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=e.pinVariant||"two_pin",s=r.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}},X9e=class extends es{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:BAe,sourceFtype:dd.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let r=ks[this._getSchematicSymbolNameOrThrow()],e=r.ports.find(D=>D.labels.includes("1")),a=r.ports.find(D=>D.labels.includes("2")),s=this.selectAll("port"),l=s.find(D=>D.props.pinNumber===1),d=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)&&(d.schematicSymbolPortDef=a);for(let[D,b]of[[2,d],[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:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({name:this.name,ftype:dd.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}},Y9e=class extends es{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:hAe,sourceFtype:"simple_crystal"}}initPorts(){let r=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:r})}_getSchematicSymbolDisplayValue(){let r=`${Ns(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${r} / ${Ns(this._parsedProps.loadCapacitance)}F`:r}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.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}},H9e=class extends es{constructor(){super(...arguments);z(this,"emitter",this.portMap.pin1);z(this,"collector",this.portMap.pin2);z(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:wAe,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}},W9e=class extends es{get config(){let r=this.props.mosfetMode==="depletion"?"d":"e",a=`${this.props.channelType}_channel_${r}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??a,zodProps:TAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.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}},K9e=class extends es{_getSwitchType(){let{spst:r,spdt:e,dpst:a,dpdt:s,type:l}=this._parsedProps??{};return s?"dpdt":r?"spst":e?"spdt":a?"dpst":l??"spst"}get config(){let r=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"}[r]??"spst_switch";return{componentName:"Switch",schematicSymbolName:this.props.symbolName??s,zodProps:MAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.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}},JW={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},J9e=class extends es{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:zAe,sourceFtype:dd.simple_test_point}}_getPropsWithDefaults(){let{padShape:r,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:d}=this._parsedProps;return!a&&e&&(a="through_hole"),a??(a="through_hole"),r??(r="circle"),a==="pad"?r==="circle"?s??(s=JW.SMT_CIRCLE_DIAMETER):r==="rect"&&(l??(l=JW.SMT_RECT_SIZE),d??(d=l)):a==="through_hole"&&(e??(e=JW.HOLE_DIAMETER)),{padShape:r,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:d}}_getImpliedFootprintString(){let{padShape:r,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:d}=this._getPropsWithDefaults();if(a==="through_hole")return`platedhole_d${e}`;if(a==="pad"){if(r==="circle")return`smtpad_circle_d${s}`;if(r==="rect")return`smtpad_rect_w${l}_h${d}`}throw new Error(`Footprint variant "${a}" with pad shape "${r}" not implemented`)}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,{padShape:a,holeDiameter:s,footprintVariant:l,padDiameter:d,width:x,height:f}=this._getPropsWithDefaults(),m=r.source_component.insert({ftype:dd.simple_test_point,name:this.name,supplier_part_numbers:e.supplierPartNumbers,footprint_variant:l,pad_shape:a,pad_diameter:d,hole_diameter:s,width:x,height:f,are_pins_interchangeable:!0});this.source_component_id=m.source_component_id}},Z9e=class extends qn{constructor(){super(...arguments);z(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:JAe}}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})}},Q9e=class extends qn{constructor(){super(...arguments);z(this,"isSchematicPrimitive",!0);z(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:KAe}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalSchematicPositionBeforeLayout(),l=this.getPrimitiveContainer()?.parent?.schematic_component_id,d=e.schematic_line.insert({schematic_component_id:l,x1:a.x1+s.x,y1:a.y1+s.y,x2:a.x2+s.x,y2:a.y2+s.y,stroke_width:D9e,color:g9e,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=d.schematic_line_id}},ewe=class extends qn{constructor(){super(...arguments);z(this,"isSchematicPrimitive",!0);z(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:WAe}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalSchematicPositionBeforeLayout(),l=this.getPrimitiveContainer()?.parent?.schematic_component_id,d=e.schematic_rect.insert({center:{x:a.center.x+s.x,y:a.center.y+s.y},width:a.width,height:a.height,stroke_width:D9e,color:g9e,is_filled:a.isFilled,schematic_component_id:l,is_dashed:a.isDashed,rotation:a.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=d.schematic_rect_id}};function PXt({anchor:r,x:e,y:a,width:s,height:l,isInside:d}){switch(r){case"top_left":return{x:e,y:a+l,textAnchor:d?"top_left":"bottom_left"};case"top_center":return{x:e+s/2,y:a+l,textAnchor:d?"top_center":"bottom_center"};case"top_right":return{x:e+s,y:a+l,textAnchor:d?"top_right":"bottom_right"};case"center_left":return{x:e,y:a+l/2,textAnchor:d?"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:d?"center_right":"center_left"};case"bottom_left":return{x:e,y:a,textAnchor:d?"bottom_left":"top_left"};case"bottom_center":return{x:e+s/2,y:a,textAnchor:d?"bottom_center":"top_center"};case"bottom_right":return{x:e+s,y:a,textAnchor:d?"bottom_right":"top_right"};default:return{x:e+s/2,y:a+l,textAnchor:"center"}}}var twe=class extends qn{constructor(){super(...arguments);z(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:HAe,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,d=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,j;if(D){let q=a.overlay.map(ot=>({selector:ot,port:this.getSubcircuit().selectOne(ot,{type:"port"})})).filter(({port:ot})=>ot!=null).map(({port:ot})=>({position:ot._getGlobalSchematicPositionAfterLayout()}));if(q.length===0)return;let ee=q.map(ot=>ot.position.x),W=q.map(ot=>ot.position.y),re=Math.min(...ee),L=Math.max(...ee),K=Math.min(...W),U=Math.max(...W),J=L-re,Q=U-K,de=J===0?s:0,oe=Q===0?s:0,Me=f+de/2,Ne=m+de/2,Ge=d+oe/2,tt=x+oe/2,He=re-Me,$t=L+Ne,bt=K-tt,ct=U+Ge;E=$t-He,A=ct-bt,B=He+(a.schX??0),w=bt+(a.schY??0),P=B+E/2,j=w+A/2}else if(b){E=a.width,A=a.height;let O=this._getGlobalSchematicPositionBeforeLayout();P=O.x,j=O.y,B=P-E/2,w=j-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,q=.1,ee=a.titleAlignment,W=PXt({anchor:ee,x:B,y:w,width:E,height:A,isInside:O}),re,L,K=W.textAnchor;O?(re=ee.includes("top")?-q:ee.includes("bottom")?q:0,L=ee.includes("left")?q:ee.includes("right")?-q:0):(re=ee.includes("top")?q:ee.includes("bottom")?-q:0,L=ee.includes("center_left")?-q:ee.includes("center_right")?q:0);let U=W.x+L,J=W.y+re;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})}}},rwe=class extends qn{constructor(){super(...arguments);z(this,"isSchematicPrimitive",!0);z(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:ZAe}}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=[],d=0;for(let A of s){let B=A.children.filter(w=>w.componentName==="SchematicCell");d=Math.max(d,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(j=>j.componentName==="SchematicCell"),P=0;for(let j=0;j<w.length;j++){for(;l[A][P];)P++;let O=w[j],q=O._parsedProps.colSpan??1,ee=O._parsedProps.rowSpan??1;for(let W=0;W<ee;W++)for(let re=0;re<q;re++)l[A+W]||(l[A+W]=[]),l[A+W][P+re]=O;P+=q}}d=Math.max(0,...l.map(A=>A.length));let x=s.map((A,B)=>A._parsedProps.height??1),f=Array.from({length:d},(A,B)=>{let w=0;for(let P=0;P<s.length;P++){let j=l[P]?.[B];if(j){let O=j._parsedProps.text??j._parsedProps.children,q=j._parsedProps.width??(O?.length??2)*.5;q>w&&(w=q)}}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<d;w++){let P=l[A]?.[w];if(P&&!b.has(P)){b.add(P);let j=P._parsedProps,O=j.rowSpan??1,q=j.colSpan??1,ee=0;for(let re=0;re<q;re++)ee+=f[w+re];let W=0;for(let re=0;re<O;re++)W+=x[A+re];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+q-1,text:j.text??j.children,center:{x:m.x+B+ee/2,y:m.y-E-W/2},width:ee,height:W,horizontal_align:j.horizontalAlign,vertical_align:j.verticalAlign,font_size:j.fontSize??a.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}f[w]&&(B+=f[w])}E+=x[A]}}},nwe=class extends qn{constructor(){super(...arguments);z(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:QAe}}},awe=class extends qn{constructor(){super(...arguments);z(this,"isSchematicPrimitive",!0);z(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:e4e}}},swe=class extends qn{constructor(){super(...arguments);z(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:_Ae}}},IXt={name:"@tscircuit/core",type:"module",version:"0.0.737",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"'},devDependencies:{"@biomejs/biome":"^1.8.3","@tscircuit/capacity-autorouter":"^0.0.107","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.67","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.21","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.335","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.37","@tscircuit/simple-3d-svg":"^0.0.41","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.261","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-simple-3d":"^0.0.8","circuit-to-svg":"^0.0.197",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.201","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.37","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Kg=class{constructor({platform:r,projectUrl:e}={}){z(this,"firstChild",null);z(this,"children");z(this,"db");z(this,"root",null);z(this,"isRoot",!0);z(this,"schematicDisabled",!1);z(this,"pcbDisabled",!1);z(this,"pcbRoutingDisabled",!1);z(this,"_featureMspSchematicTraceRouting",!0);z(this,"name");z(this,"platform");z(this,"projectUrl");z(this,"_hasRenderedAtleastOnce",!1);z(this,"_eventListeners",{});this.children=[],this.db=ua([]),this.root=this,this.platform=r,this.projectUrl=e,this.pcbDisabled=r?.pcbDisabled??!1}add(r){let e;(0,iwe.isValidElement)(r)?e=KBe(r):e=r,this.children.push(e)}_getBoard(){return this.children.find(r=>r.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 r=new Wg({subcircuit:!0});r.parent=this,r.addAll(this.children),this.children=[r],this.firstChild=r}render(){this.firstChild||this._guessRootComponent();let{firstChild:r,db:e}=this;if(!r)throw new Error("RootCircuit has no root component");r.parent=this,r.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(r=>r._hasIncompleteAsyncEffects()?!0:r.children.some(e=>e._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(r){let e=await Promise.resolve().then(()=>(FBe(),bBe)).catch(a=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
1039
1039
 
1040
1040
  "${a.message}"`)});if(r.view==="pcb")return e.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(r.view==="schematic")return e.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${r.view}`)}getCoreVersion(){let[r,e,a]=IXt.version.split(".").map(Number);return`${r}.${e}.${a+1}`}async preview(r){let e=typeof r=="object"?r:{previewName:r};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return Si()}_computePcbGlobalTransformBeforeLayout(){return Si()}selectAll(r){return this._guessRootComponent(),this.firstChild?.selectAll(r)??[]}selectOne(r,e){return this._guessRootComponent(),this.firstChild?.selectOne(r,e)??null}emit(r,...e){if(this._eventListeners[r])for(let a of this._eventListeners[r])a(...e)}on(r,e){this._eventListeners[r]||(this._eventListeners[r]=[]),this._eventListeners[r].push(e)}removeListener(r,e){this._eventListeners[r]&&(this._eventListeners[r]=this._eventListeners[r].filter(a=>a!==e))}enableDebug(r){typeof r=="string"?aK.default.enable(r):(r===null||r===!1)&&aK.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},jXt=Kg,kXt=Kg,NXt=r=>{let[e,a]=Xg.default.useState(!0),[s,l]=Xg.default.useState(null),[d,x]=Xg.default.useState(),[f,m]=Xg.default.useState();return Xg.default.useEffect(()=>{a(!0),l(null),r&&setTimeout(()=>{try{let D=new Kg;D.add(r),x(D),m(D.toJson())}catch(D){l(D)}a(!1)},1)},[r]),{isLoading:e,error:s,circuit:d,circuitJson:f}},Jg=(r,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 d=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,w1.jsxs)(w1.Fragment,{children:[(0,w1.jsx)(r,{...f}),m.map((D,b)=>(0,w1.jsx)("trace",{...D},b))]})};for(let x of l)d[x]=`.${a} > .${x}`;return d},MXt=Jg(r=>(0,owe.jsx)("capacitor",{...r}),DAe),OXt=r=>Jg(e=>(0,uwe.jsx)("chip",{pinLabels:r,...e}),r),LXt=Jg(r=>(0,cwe.jsx)("diode",{...r}),jAe),$Xt=Jg(r=>(0,lwe.jsx)("led",{...r}),NAe),zXt=Jg(r=>(0,dwe.jsx)("resistor",{...r}),xAe),qXt=new Proxy(r=>new Proxy({},{get:(e,a)=>`.${r} > .${a}`}),{get:(r,e)=>{let a=(...s)=>{let l=s[0];return new Proxy({},{get:(d,x)=>`.${e} > .${x}`})};return new Proxy(a,{get:(s,l)=>e==="net"?`net.${l}`:e==="subcircuit"?new Proxy({},{get:(d,x)=>new Proxy({},{get:(f,m)=>`subcircuit.${l} > .${x} > .${m}`})}):`.${e} > .${l}`,apply:(s,l,d)=>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}`})}})})}});WBe(GBe);WBe({Bug:QS});var hwe=Or(kc(),1);var hK=new Map,Co=async(r,e)=>{let a=new URLSearchParams({...e,json:"true"}).toString();if(hK.has(a))return hK.get(a);let l=await(await fetch(`https://jlcsearch.tscircuit.com/${r}/list?${a}`)).json();return hK.set(a,l),l},xwe={findPart:async({sourceComponent:r,footprinterString:e})=>{if(r.type==="source_component"&&r.ftype==="simple_resistor"){let{resistors:a}=await Co("resistors",{resistance:r.display_resistance??r.resistance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_capacitor"){e?.includes("cap")&&(e=e.replace("cap",""));let{capacitors:a}=await Co("capacitors",{capacitance:r.display_capacitance??r.capacitance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_pin_header"){let a;e?.includes("_p")&&(a=Number(e.split("_p")[1]));let{headers:s}=await Co("headers",a?{pitch:a,num_pins:r.pin_count,gender:r.gender}:{num_pins:r.pin_count,gender:r.gender});return{jlcpcb:(s??[]).map(l=>`C${l.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_potentiometer"){let{potentiometers:a}=await Co("potentiometers",{resistance:r.max_resistance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_diode"){let{diodes:a}=await Co("diodes",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_chip"){let{chips:a}=await Co("chips",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_transistor"){let{transistors:a}=await Co("transistors",{package:e,transistor_type:r.transistor_type});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_power_source"){let{power_sources:a}=await Co("power_sources",{voltage:r.voltage,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_inductor"){let{inductors:a}=await Co("inductors",{inductance:r.inductance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_crystal"){let{crystals:a}=await Co("crystals",{frequency:r.frequency,load_capacitance:r.load_capacitance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_mosfet"){let{mosfets:a}=await Co("mosfets",{package:e,mosfet_mode:r.mosfet_mode,channel_type:r.channel_type});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_resonator"){let{resonators:a}=await Co("resonators",{frequency:r.frequency,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_switch"){let{switches:a}=await Co("switches",{switch_type:r.type,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_led"){let{leds:a}=await Co("leds",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_fuse"){let{fuses:a}=await Co("fuses",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}return{}}};var UXt="https://kicad-mod-cache.tscircuit.com",fwe=()=>({partsEngine:xwe,footprintLibraryMap:{kicad:async r=>{let e=`${UXt}/${r}`,a=`${e}.circuit.json`,l=await(await fetch(a)).json(),d=Array.isArray(l)?l.filter(f=>f?.type==="pcb_silkscreen_text"?f?.text==="REF**":!0):l,x=`${e}.wrl`;return{footprintCircuitJson:d,cadModel:{wrlUrl:x,modelUnitToMmScale:2.54}}}}});var mK=Or(fs(),1),Pyr=(0,mK.default)("tsci:eval:execution-context");function tB(r,e={}){globalThis.React=hwe;let a=e.platform||fwe(),s=e.projectConfig?{...a,...e.projectConfig}:a,l=new Kg({platform:s});return e.name&&(l.name=e.name),e.debugNamespace&&l.enableDebug(e.debugNamespace),{fsMap:{},entrypoint:"",preSuppliedImports:{"@tscircuit/core":eB,tscircuit:eB,"@tscircuit/math-utils":TY,react:hwe,debug:mK.default,"@tscircuit/props":{}},circuit:l,...r}}function WF(r){let e=r;return e=e.replace(/\\/g,"/"),e=e.trim(),e.startsWith("./")&&(e=e.slice(2)),e.startsWith("/")&&(e=e.slice(1)),e}function mwe(r){let e={};for(let[a,s]of Object.entries(r))e[WF(a)]=s;return e}function Uc(r){if(!r)return".";let a=r.replace(/\\/g,"/").replace(/\/+$/,"");return a.indexOf("/")===-1?".":a.substring(0,a.lastIndexOf("/"))||"/"}function gK(r,e){if(r.startsWith("../")){let a=Uc(e);return gK(r.slice(3),a)}return r.startsWith("./")?gK(r.slice(2),e):r.startsWith("/")?r.slice(1):`${e}/${r}`}var KF=(r,e,a)=>{let s=a?gK(r,a):r,l=new Set(Array.isArray(e)?e:Object.keys(e));if(l.has(s))return s;let d=new Map;for(let m of l)d.set(WF(m),m);let x=WF(s);if(d.has(x))return d.get(x);let f=["tsx","ts","json","js","jsx","obj","gltf","glb"];for(let m of f){let D=`${x}.${m}`;if(d.has(D))return d.get(D)}if(!r.startsWith("./")&&!r.startsWith("../")){let m=WF(r);if(d.has(m))return d.get(m);for(let D of f){let b=`${m}.${D}`;if(d.has(b))return d.get(b)}}return null},rB=(r,e)=>{let a=KF(r,e);if(!a)throw new Error(`File not found "${r}", available paths:
1041
1041