@tscircuit/eval 0.0.461 → 0.0.463
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blob-url.js +1 -1
- package/dist/eval/index.d.ts +4 -2
- package/dist/lib/index.d.ts +4 -2
- package/dist/webworker/entrypoint.js +5 -5
- package/package.json +5 -5
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var mJ=Object.create;var u_=Object.defineProperty;var _J=Object.getOwnPropertyDescriptor;var yJ=Object.getOwnPropertyNames;var gJ=Object.getPrototypeOf,bJ=Object.prototype.hasOwnProperty;var xJ=(e,t,n)=>t in e?u_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Xd=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Ht=(e,t)=>()=>(e&&(t=e(e=0)),t);var oe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),il=(e,t)=>{for(var n in t)u_(e,n,{get:t[n],enumerable:!0})},vJ=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of yJ(t))!bJ.call(e,o)&&o!==n&&u_(e,o,{get:()=>t[o],enumerable:!(i=_J(t,o))||i.enumerable});return e};var Xt=(e,t,n)=>(n=e!=null?mJ(gJ(e)):{},vJ(t||!e||!e.__esModule?u_(n,"default",{value:e,enumerable:!0}):n,e));var P=(e,t,n)=>xJ(e,typeof t!="symbol"?t+"":t,n);var yA=oe(Se=>{"use strict";var sS=Symbol.for("react.transitional.element"),FJ=Symbol.for("react.portal"),zJ=Symbol.for("react.fragment"),DJ=Symbol.for("react.strict_mode"),$J=Symbol.for("react.profiler"),jJ=Symbol.for("react.consumer"),BJ=Symbol.for("react.context"),YJ=Symbol.for("react.forward_ref"),XJ=Symbol.for("react.suspense"),VJ=Symbol.for("react.memo"),pA=Symbol.for("react.lazy"),HJ=Symbol.for("react.activity"),aA=Symbol.iterator;function GJ(e){return e===null||typeof e!="object"?null:(e=aA&&e[aA]||e["@@iterator"],typeof e=="function"?e:null)}var hA={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},dA=Object.assign,fA={};function yp(e,t,n){this.props=e,this.context=t,this.refs=fA,this.updater=n||hA}yp.prototype.isReactComponent={};yp.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=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,e,t,"setState")};yp.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function mA(){}mA.prototype=yp.prototype;function aS(e,t,n){this.props=e,this.context=t,this.refs=fA,this.updater=n||hA}var cS=aS.prototype=new mA;cS.constructor=aS;dA(cS,yp.prototype);cS.isPureReactComponent=!0;var cA=Array.isArray;function rS(){}var Mn={H:null,A:null,T:null,S:null},_A=Object.prototype.hasOwnProperty;function lS(e,t,n){var i=n.ref;return{$$typeof:sS,type:e,key:t,ref:i!==void 0?i:null,props:n}}function UJ(e,t){return lS(e.type,t,e.props)}function uS(e){return typeof e=="object"&&e!==null&&e.$$typeof===sS}function qJ(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(n){return t[n]})}var lA=/\/+/g;function oS(e,t){return typeof e=="object"&&e!==null&&e.key!=null?qJ(""+e.key):t.toString(36)}function WJ(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status=="string"?e.then(rS,rS):(e.status="pending",e.then(function(t){e.status==="pending"&&(e.status="fulfilled",e.value=t)},function(t){e.status==="pending"&&(e.status="rejected",e.reason=t)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}function _p(e,t,n,i,o){var r=typeof e;(r==="undefined"||r==="boolean")&&(e=null);var s=!1;if(e===null)s=!0;else switch(r){case"bigint":case"string":case"number":s=!0;break;case"object":switch(e.$$typeof){case sS:case FJ:s=!0;break;case pA:return s=e._init,_p(s(e._payload),t,n,i,o)}}if(s)return o=o(e),s=i===""?"."+oS(e,0):i,cA(o)?(n="",s!=null&&(n=s.replace(lA,"$&/")+"/"),_p(o,t,n,"",function(l){return l})):o!=null&&(uS(o)&&(o=UJ(o,n+(o.key==null||e&&e.key===o.key?"":(""+o.key).replace(lA,"$&/")+"/")+s)),t.push(o)),1;s=0;var a=i===""?".":i+":";if(cA(e))for(var c=0;c<e.length;c++)i=e[c],r=a+oS(i,c),s+=_p(i,t,n,r,o);else if(c=GJ(e),typeof c=="function")for(e=c.call(e),c=0;!(i=e.next()).done;)i=i.value,r=a+oS(i,c++),s+=_p(i,t,n,r,o);else if(r==="object"){if(typeof e.then=="function")return _p(WJ(e),t,n,i,o);throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.")}return s}function y_(e,t,n){if(e==null)return e;var i=[],o=0;return _p(e,i,"","",function(r){return t.call(n,r,o++)}),i}function ZJ(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(n){(e._status===0||e._status===-1)&&(e._status=1,e._result=n)},function(n){(e._status===0||e._status===-1)&&(e._status=2,e._result=n)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var uA=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof e=="object"&&e!==null&&typeof e.message=="string"?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)},KJ={map:y_,forEach:function(e,t,n){y_(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return y_(e,function(){t++}),t},toArray:function(e){return y_(e,function(t){return t})||[]},only:function(e){if(!uS(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};Se.Activity=HJ;Se.Children=KJ;Se.Component=yp;Se.Fragment=zJ;Se.Profiler=$J;Se.PureComponent=aS;Se.StrictMode=DJ;Se.Suspense=XJ;Se.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Mn;Se.__COMPILER_RUNTIME={__proto__:null,c:function(e){return Mn.H.useMemoCache(e)}};Se.cache=function(e){return function(){return e.apply(null,arguments)}};Se.cacheSignal=function(){return null};Se.cloneElement=function(e,t,n){if(e==null)throw Error("The argument must be a React element, but you passed "+e+".");var i=dA({},e.props),o=e.key;if(t!=null)for(r in t.key!==void 0&&(o=""+t.key),t)!_A.call(t,r)||r==="key"||r==="__self"||r==="__source"||r==="ref"&&t.ref===void 0||(i[r]=t[r]);var r=arguments.length-2;if(r===1)i.children=n;else if(1<r){for(var s=Array(r),a=0;a<r;a++)s[a]=arguments[a+2];i.children=s}return lS(e.type,o,i)};Se.createContext=function(e){return e={$$typeof:BJ,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:jJ,_context:e},e};Se.createElement=function(e,t,n){var i,o={},r=null;if(t!=null)for(i in t.key!==void 0&&(r=""+t.key),t)_A.call(t,i)&&i!=="key"&&i!=="__self"&&i!=="__source"&&(o[i]=t[i]);var s=arguments.length-2;if(s===1)o.children=n;else if(1<s){for(var a=Array(s),c=0;c<s;c++)a[c]=arguments[c+2];o.children=a}if(e&&e.defaultProps)for(i in s=e.defaultProps,s)o[i]===void 0&&(o[i]=s[i]);return lS(e,r,o)};Se.createRef=function(){return{current:null}};Se.forwardRef=function(e){return{$$typeof:YJ,render:e}};Se.isValidElement=uS;Se.lazy=function(e){return{$$typeof:pA,_payload:{_status:-1,_result:e},_init:ZJ}};Se.memo=function(e,t){return{$$typeof:VJ,type:e,compare:t===void 0?null:t}};Se.startTransition=function(e){var t=Mn.T,n={};Mn.T=n;try{var i=e(),o=Mn.S;o!==null&&o(n,i),typeof i=="object"&&i!==null&&typeof i.then=="function"&&i.then(rS,uA)}catch(r){uA(r)}finally{t!==null&&n.types!==null&&(t.types=n.types),Mn.T=t}};Se.unstable_useCacheRefresh=function(){return Mn.H.useCacheRefresh()};Se.use=function(e){return Mn.H.use(e)};Se.useActionState=function(e,t,n){return Mn.H.useActionState(e,t,n)};Se.useCallback=function(e,t){return Mn.H.useCallback(e,t)};Se.useContext=function(e){return Mn.H.useContext(e)};Se.useDebugValue=function(){};Se.useDeferredValue=function(e,t){return Mn.H.useDeferredValue(e,t)};Se.useEffect=function(e,t){return Mn.H.useEffect(e,t)};Se.useEffectEvent=function(e){return Mn.H.useEffectEvent(e)};Se.useId=function(){return Mn.H.useId()};Se.useImperativeHandle=function(e,t,n){return Mn.H.useImperativeHandle(e,t,n)};Se.useInsertionEffect=function(e,t){return Mn.H.useInsertionEffect(e,t)};Se.useLayoutEffect=function(e,t){return Mn.H.useLayoutEffect(e,t)};Se.useMemo=function(e,t){return Mn.H.useMemo(e,t)};Se.useOptimistic=function(e,t){return Mn.H.useOptimistic(e,t)};Se.useReducer=function(e,t,n){return Mn.H.useReducer(e,t,n)};Se.useRef=function(e){return Mn.H.useRef(e)};Se.useState=function(e){return Mn.H.useState(e)};Se.useSyncExternalStore=function(e,t,n){return Mn.H.useSyncExternalStore(e,t,n)};Se.useTransition=function(){return Mn.H.useTransition()};Se.version="19.2.0"});var Mr=oe((RNt,gA)=>{"use strict";gA.exports=yA()});var $e,pS,Yt,Wr,Vd=Ht(()=>{"use strict";(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{let r={};for(let s of o)r[s]=s;return r},e.getValidEnumValues=o=>{let r=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),s={};for(let a of r)s[a]=o[a];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(r){return o[r]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let r=[];for(let s in o)Object.prototype.hasOwnProperty.call(o,s)&&r.push(s);return r},e.find=(o,r)=>{for(let s of o)if(r(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function i(o,r=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(r)}e.joinValues=i,e.jsonStringifyReplacer=(o,r)=>typeof r=="bigint"?r.toString():r})($e||($e={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(pS||(pS={}));Yt=$e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Wr=e=>{switch(typeof e){case"undefined":return Yt.undefined;case"string":return Yt.string;case"number":return Number.isNaN(e)?Yt.nan:Yt.number;case"boolean":return Yt.boolean;case"function":return Yt.function;case"bigint":return Yt.bigint;case"symbol":return Yt.symbol;case"object":return Array.isArray(e)?Yt.array:e===null?Yt.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Yt.promise:typeof Map<"u"&&e instanceof Map?Yt.map:typeof Set<"u"&&e instanceof Set?Yt.set:typeof Date<"u"&&e instanceof Date?Yt.date:Yt.object;default:return Yt.unknown}}});var Nt,JJ,bo,g_=Ht(()=>{"use strict";Vd();Nt=$e.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"]),JJ=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),bo=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(r){return r.message},i={_errors:[]},o=r=>{for(let s of r.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)i._errors.push(n(s));else{let a=i,c=0;for(;c<s.path.length;){let l=s.path[c];c===s.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(n(s))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),i}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$e.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},i=[];for(let o of this.issues)if(o.path.length>0){let r=o.path[0];n[r]=n[r]||[],n[r].push(t(o))}else i.push(t(o));return{formErrors:i,fieldErrors:n}}get formErrors(){return this.flatten()}};bo.create=e=>new bo(e)});var QJ,Rs,hS=Ht(()=>{"use strict";g_();Vd();QJ=(e,t)=>{let n;switch(e.code){case Nt.invalid_type:e.received===Yt.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case Nt.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,$e.jsonStringifyReplacer)}`;break;case Nt.unrecognized_keys:n=`Unrecognized key(s) in object: ${$e.joinValues(e.keys,", ")}`;break;case Nt.invalid_union:n="Invalid input";break;case Nt.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${$e.joinValues(e.options)}`;break;case Nt.invalid_enum_value:n=`Invalid enum value. Expected ${$e.joinValues(e.options)}, received '${e.received}'`;break;case Nt.invalid_arguments:n="Invalid function arguments";break;case Nt.invalid_return_type:n="Invalid function return type";break;case Nt.invalid_date:n="Invalid date";break;case Nt.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:$e.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case Nt.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case Nt.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case Nt.custom:n="Invalid input";break;case Nt.invalid_intersection_types:n="Intersection results could not be merged";break;case Nt.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Nt.not_finite:n="Number must be finite";break;default:n=t.defaultError,$e.assertNever(e)}return{message:n}},Rs=QJ});function tQ(e){bA=e}function gp(){return bA}var bA,b_=Ht(()=>{"use strict";hS();bA=Rs});function Dt(e,t){let n=gp(),i=Hd({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Rs?void 0:Rs].filter(o=>!!o)});e.common.issues.push(i)}var Hd,eQ,Li,pe,rl,Ui,x_,v_,Ba,bp,dS=Ht(()=>{"use strict";b_();hS();Hd=e=>{let{data:t,path:n,errorMaps:i,issueData:o}=e,r=[...n,...o.path||[]],s={...o,path:r};if(o.message!==void 0)return{...o,path:r,message:o.message};let a="",c=i.filter(l=>!!l).slice().reverse();for(let l of c)a=l(s,{data:t,defaultError:a}).message;return{...o,path:r,message:a}},eQ=[];Li=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let i=[];for(let o of n){if(o.status==="aborted")return pe;o.status==="dirty"&&t.dirty(),i.push(o.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,n){let i=[];for(let o of n){let r=await o.key,s=await o.value;i.push({key:r,value:s})}return e.mergeObjectSync(t,i)}static mergeObjectSync(t,n){let i={};for(let o of n){let{key:r,value:s}=o;if(r.status==="aborted"||s.status==="aborted")return pe;r.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),r.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(i[r.value]=s.value)}return{status:t.value,value:i}}},pe=Object.freeze({status:"aborted"}),rl=e=>({status:"dirty",value:e}),Ui=e=>({status:"valid",value:e}),x_=e=>e.status==="aborted",v_=e=>e.status==="dirty",Ba=e=>e.status==="valid",bp=e=>typeof Promise<"u"&&e instanceof Promise});var xA=Ht(()=>{"use strict"});var te,vA=Ht(()=>{"use strict";(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(te||(te={}))});function Pe(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:i,description:o}=e;if(t&&(n||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,a)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??i??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}function IA(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function gQ(e){return new RegExp(`^${IA(e)}$`)}function TA(e){let t=`${PA}T${IA(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function bQ(e,t){return!!((t==="v4"||!t)&&pQ.test(e)||(t==="v6"||!t)&&dQ.test(e))}function xQ(e,t){if(!aQ.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let i=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(i));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function vQ(e,t){return!!((t==="v4"||!t)&&hQ.test(e)||(t==="v6"||!t)&&fQ.test(e))}function SQ(e,t){let n=(e.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,o=n>i?n:i,r=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return r%s/10**o}function xp(e){if(e instanceof xo){let t={};for(let n in e.shape){let i=e.shape[n];t[n]=or.create(xp(i))}return new xo({...e._def,shape:()=>t})}else return e instanceof Fs?new Fs({...e._def,type:xp(e.element)}):e instanceof or?or.create(xp(e.unwrap())):e instanceof Kr?Kr.create(xp(e.unwrap())):e instanceof Zr?Zr.create(e.items.map(t=>xp(t))):e}function mS(e,t){let n=Wr(e),i=Wr(t);if(e===t)return{valid:!0,data:e};if(n===Yt.object&&i===Yt.object){let o=$e.objectKeys(t),r=$e.objectKeys(e).filter(a=>o.indexOf(a)!==-1),s={...e,...t};for(let a of r){let c=mS(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(n===Yt.array&&i===Yt.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let r=0;r<e.length;r++){let s=e[r],a=t[r],c=mS(s,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===Yt.date&&i===Yt.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function MA(e,t){return new _l({values:e,typeName:_e.ZodEnum,...Pe(t)})}function wA(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function CA(e,t={},n){return e?Xa.create().superRefine((i,o)=>{let r=e(i);if(r instanceof Promise)return r.then(s=>{if(!s){let a=wA(t,i),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!r){let s=wA(t,i),a=s.fatal??n??!0;o.addIssue({code:"custom",...s,fatal:a})}}):Xa.create()}var rr,SA,Ee,nQ,iQ,oQ,rQ,sQ,aQ,cQ,lQ,uQ,fS,pQ,hQ,dQ,fQ,mQ,_Q,PA,yQ,Ya,sl,al,cl,ll,vp,ul,pl,Xa,Ls,Cr,Sp,Fs,xo,hl,Os,S_,dl,Zr,w_,wp,Pp,P_,fl,ml,_l,yl,Va,sr,or,Kr,gl,bl,Ip,wQ,Gd,Ud,xl,PQ,_e,IQ,EA,NA,TQ,MQ,kA,CQ,EQ,NQ,kQ,AQ,RQ,OQ,LQ,FQ,zQ,DQ,$Q,jQ,BQ,YQ,XQ,VQ,HQ,GQ,UQ,qQ,WQ,ZQ,KQ,JQ,QQ,ttt,ett,ntt,itt,ott,rtt,stt,att,AA=Ht(()=>{"use strict";g_();b_();vA();dS();Vd();rr=class{constructor(t,n,i,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=i,this._key=o}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}},SA=(e,t)=>{if(Ba(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new bo(e.common.issues);return this._error=n,this._error}}};Ee=class{get description(){return this._def.description}_getType(t){return Wr(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Wr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Li,ctx:{common:t.parent.common,data:t.data,parsedType:Wr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(bp(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let i=this.safeParse(t,n);if(i.success)return i.data;throw i.error}safeParse(t,n){let i={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wr(t)},o=this._parseSync({data:t,path:i.path,parent:i});return SA(i,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wr(t)};if(!this["~standard"].async)try{let i=this._parseSync({data:t,path:[],parent:n});return Ba(i)?{value:i.value}:{issues:n.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(i=>Ba(i)?{value:i.value}:{issues:n.common.issues})}async parseAsync(t,n){let i=await this.safeParseAsync(t,n);if(i.success)return i.data;throw i.error}async safeParseAsync(t,n){let i={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wr(t)},o=this._parse({data:t,path:i.path,parent:i}),r=await(bp(o)?o:Promise.resolve(o));return SA(i,r)}refine(t,n){let i=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,r)=>{let s=t(o),a=()=>r.addIssue({code:Nt.custom,...i(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,n){return this._refinement((i,o)=>t(i)?!0:(o.addIssue(typeof n=="function"?n(i,o):n),!1))}_refinement(t){return new sr({schema:this,typeName:_e.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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:n=>this["~validate"](n)}}optional(){return or.create(this,this._def)}nullable(){return Kr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Fs.create(this)}promise(){return Va.create(this,this._def)}or(t){return hl.create([this,t],this._def)}and(t){return dl.create(this,t,this._def)}transform(t){return new sr({...Pe(this._def),schema:this,typeName:_e.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new gl({...Pe(this._def),innerType:this,defaultValue:n,typeName:_e.ZodDefault})}brand(){return new Gd({typeName:_e.ZodBranded,type:this,...Pe(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new bl({...Pe(this._def),innerType:this,catchValue:n,typeName:_e.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Ud.create(this,t)}readonly(){return xl.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},nQ=/^c[^\s-]{8,}$/i,iQ=/^[0-9a-z]+$/,oQ=/^[0-9A-HJKMNP-TV-Z]{26}$/i,rQ=/^[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,sQ=/^[a-z0-9_-]{21}$/i,aQ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,cQ=/^[-+]?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)?)??$/,lQ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,uQ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",pQ=/^(?:(?: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])$/,hQ=/^(?:(?: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])$/,dQ=/^(([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]))$/,fQ=/^(([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])$/,mQ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_Q=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,PA="((\\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])))",yQ=new RegExp(`^${PA}$`);Ya=class e extends Ee{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Yt.string){let r=this._getOrReturnCtx(t);return Dt(r,{code:Nt.invalid_type,expected:Yt.string,received:r.parsedType}),pe}let i=new Li,o;for(let r of this._def.checks)if(r.kind==="min")t.data.length<r.value&&(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="max")t.data.length>r.value&&(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="length"){let s=t.data.length>r.value,a=t.data.length<r.value;(s||a)&&(o=this._getOrReturnCtx(t,o),s?Dt(o,{code:Nt.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):a&&Dt(o,{code:Nt.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),i.dirty())}else if(r.kind==="email")lQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"email",code:Nt.invalid_string,message:r.message}),i.dirty());else if(r.kind==="emoji")fS||(fS=new RegExp(uQ,"u")),fS.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"emoji",code:Nt.invalid_string,message:r.message}),i.dirty());else if(r.kind==="uuid")rQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"uuid",code:Nt.invalid_string,message:r.message}),i.dirty());else if(r.kind==="nanoid")sQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"nanoid",code:Nt.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid")nQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"cuid",code:Nt.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid2")iQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"cuid2",code:Nt.invalid_string,message:r.message}),i.dirty());else if(r.kind==="ulid")oQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"ulid",code:Nt.invalid_string,message:r.message}),i.dirty());else if(r.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),Dt(o,{validation:"url",code:Nt.invalid_string,message:r.message}),i.dirty()}else r.kind==="regex"?(r.regex.lastIndex=0,r.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"regex",code:Nt.invalid_string,message:r.message}),i.dirty())):r.kind==="trim"?t.data=t.data.trim():r.kind==="includes"?t.data.includes(r.value,r.position)||(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),i.dirty()):r.kind==="toLowerCase"?t.data=t.data.toLowerCase():r.kind==="toUpperCase"?t.data=t.data.toUpperCase():r.kind==="startsWith"?t.data.startsWith(r.value)||(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.invalid_string,validation:{startsWith:r.value},message:r.message}),i.dirty()):r.kind==="endsWith"?t.data.endsWith(r.value)||(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.invalid_string,validation:{endsWith:r.value},message:r.message}),i.dirty()):r.kind==="datetime"?TA(r).test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.invalid_string,validation:"datetime",message:r.message}),i.dirty()):r.kind==="date"?yQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.invalid_string,validation:"date",message:r.message}),i.dirty()):r.kind==="time"?gQ(r).test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.invalid_string,validation:"time",message:r.message}),i.dirty()):r.kind==="duration"?cQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"duration",code:Nt.invalid_string,message:r.message}),i.dirty()):r.kind==="ip"?bQ(t.data,r.version)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"ip",code:Nt.invalid_string,message:r.message}),i.dirty()):r.kind==="jwt"?xQ(t.data,r.alg)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"jwt",code:Nt.invalid_string,message:r.message}),i.dirty()):r.kind==="cidr"?vQ(t.data,r.version)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"cidr",code:Nt.invalid_string,message:r.message}),i.dirty()):r.kind==="base64"?mQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"base64",code:Nt.invalid_string,message:r.message}),i.dirty()):r.kind==="base64url"?_Q.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"base64url",code:Nt.invalid_string,message:r.message}),i.dirty()):$e.assertNever(r);return{status:i.value,value:t.data}}_regex(t,n,i){return this.refinement(o=>t.test(o),{validation:n,code:Nt.invalid_string,...te.errToObj(i)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...te.errToObj(t)})}url(t){return this._addCheck({kind:"url",...te.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...te.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...te.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...te.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...te.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...te.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...te.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...te.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...te.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...te.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...te.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...te.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...te.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...te.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...te.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...te.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...te.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...te.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...te.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...te.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...te.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...te.errToObj(n)})}nonempty(t){return this.min(1,te.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Ya.create=e=>new Ya({checks:[],typeName:_e.ZodString,coerce:e?.coerce??!1,...Pe(e)});sl=class e extends Ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Yt.number){let r=this._getOrReturnCtx(t);return Dt(r,{code:Nt.invalid_type,expected:Yt.number,received:r.parsedType}),pe}let i,o=new Li;for(let r of this._def.checks)r.kind==="int"?$e.isInteger(t.data)||(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.invalid_type,expected:"integer",received:"float",message:r.message}),o.dirty()):r.kind==="min"?(r.inclusive?t.data<r.value:t.data<=r.value)&&(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),o.dirty()):r.kind==="max"?(r.inclusive?t.data>r.value:t.data>=r.value)&&(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),o.dirty()):r.kind==="multipleOf"?SQ(t.data,r.value)!==0&&(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.not_multiple_of,multipleOf:r.value,message:r.message}),o.dirty()):r.kind==="finite"?Number.isFinite(t.data)||(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.not_finite,message:r.message}),o.dirty()):$e.assertNever(r);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,te.toString(n))}gt(t,n){return this.setLimit("min",t,!1,te.toString(n))}lte(t,n){return this.setLimit("max",t,!0,te.toString(n))}lt(t,n){return this.setLimit("max",t,!1,te.toString(n))}setLimit(t,n,i,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:i,message:te.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:te.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:te.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:te.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:te.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:te.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:te.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:te.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:te.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:te.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&$e.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(n===null||i.value>n)&&(n=i.value):i.kind==="max"&&(t===null||i.value<t)&&(t=i.value)}return Number.isFinite(n)&&Number.isFinite(t)}};sl.create=e=>new sl({checks:[],typeName:_e.ZodNumber,coerce:e?.coerce||!1,...Pe(e)});al=class e extends Ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Yt.bigint)return this._getInvalidInput(t);let i,o=new Li;for(let r of this._def.checks)r.kind==="min"?(r.inclusive?t.data<r.value:t.data<=r.value)&&(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),o.dirty()):r.kind==="max"?(r.inclusive?t.data>r.value:t.data>=r.value)&&(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),o.dirty()):r.kind==="multipleOf"?t.data%r.value!==BigInt(0)&&(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.not_multiple_of,multipleOf:r.value,message:r.message}),o.dirty()):$e.assertNever(r);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return Dt(n,{code:Nt.invalid_type,expected:Yt.bigint,received:n.parsedType}),pe}gte(t,n){return this.setLimit("min",t,!0,te.toString(n))}gt(t,n){return this.setLimit("min",t,!1,te.toString(n))}lte(t,n){return this.setLimit("max",t,!0,te.toString(n))}lt(t,n){return this.setLimit("max",t,!1,te.toString(n))}setLimit(t,n,i,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:i,message:te.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:te.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:te.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:te.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:te.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:te.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};al.create=e=>new al({checks:[],typeName:_e.ZodBigInt,coerce:e?.coerce??!1,...Pe(e)});cl=class extends Ee{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Yt.boolean){let i=this._getOrReturnCtx(t);return Dt(i,{code:Nt.invalid_type,expected:Yt.boolean,received:i.parsedType}),pe}return Ui(t.data)}};cl.create=e=>new cl({typeName:_e.ZodBoolean,coerce:e?.coerce||!1,...Pe(e)});ll=class e extends Ee{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Yt.date){let r=this._getOrReturnCtx(t);return Dt(r,{code:Nt.invalid_type,expected:Yt.date,received:r.parsedType}),pe}if(Number.isNaN(t.data.getTime())){let r=this._getOrReturnCtx(t);return Dt(r,{code:Nt.invalid_date}),pe}let i=new Li,o;for(let r of this._def.checks)r.kind==="min"?t.data.getTime()<r.value&&(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),i.dirty()):r.kind==="max"?t.data.getTime()>r.value&&(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),i.dirty()):$e.assertNever(r);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:te.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:te.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};ll.create=e=>new ll({checks:[],coerce:e?.coerce||!1,typeName:_e.ZodDate,...Pe(e)});vp=class extends Ee{_parse(t){if(this._getType(t)!==Yt.symbol){let i=this._getOrReturnCtx(t);return Dt(i,{code:Nt.invalid_type,expected:Yt.symbol,received:i.parsedType}),pe}return Ui(t.data)}};vp.create=e=>new vp({typeName:_e.ZodSymbol,...Pe(e)});ul=class extends Ee{_parse(t){if(this._getType(t)!==Yt.undefined){let i=this._getOrReturnCtx(t);return Dt(i,{code:Nt.invalid_type,expected:Yt.undefined,received:i.parsedType}),pe}return Ui(t.data)}};ul.create=e=>new ul({typeName:_e.ZodUndefined,...Pe(e)});pl=class extends Ee{_parse(t){if(this._getType(t)!==Yt.null){let i=this._getOrReturnCtx(t);return Dt(i,{code:Nt.invalid_type,expected:Yt.null,received:i.parsedType}),pe}return Ui(t.data)}};pl.create=e=>new pl({typeName:_e.ZodNull,...Pe(e)});Xa=class extends Ee{constructor(){super(...arguments),this._any=!0}_parse(t){return Ui(t.data)}};Xa.create=e=>new Xa({typeName:_e.ZodAny,...Pe(e)});Ls=class extends Ee{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ui(t.data)}};Ls.create=e=>new Ls({typeName:_e.ZodUnknown,...Pe(e)});Cr=class extends Ee{_parse(t){let n=this._getOrReturnCtx(t);return Dt(n,{code:Nt.invalid_type,expected:Yt.never,received:n.parsedType}),pe}};Cr.create=e=>new Cr({typeName:_e.ZodNever,...Pe(e)});Sp=class extends Ee{_parse(t){if(this._getType(t)!==Yt.undefined){let i=this._getOrReturnCtx(t);return Dt(i,{code:Nt.invalid_type,expected:Yt.void,received:i.parsedType}),pe}return Ui(t.data)}};Sp.create=e=>new Sp({typeName:_e.ZodVoid,...Pe(e)});Fs=class e extends Ee{_parse(t){let{ctx:n,status:i}=this._processInputParams(t),o=this._def;if(n.parsedType!==Yt.array)return Dt(n,{code:Nt.invalid_type,expected:Yt.array,received:n.parsedType}),pe;if(o.exactLength!==null){let s=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(s||a)&&(Dt(n,{code:s?Nt.too_big:Nt.too_small,minimum:a?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),i.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(Dt(n,{code:Nt.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),i.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(Dt(n,{code:Nt.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),i.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>o.type._parseAsync(new rr(n,s,n.path,a)))).then(s=>Li.mergeArray(i,s));let r=[...n.data].map((s,a)=>o.type._parseSync(new rr(n,s,n.path,a)));return Li.mergeArray(i,r)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:te.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:te.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:te.toString(n)}})}nonempty(t){return this.min(1,t)}};Fs.create=(e,t)=>new Fs({type:e,minLength:null,maxLength:null,exactLength:null,typeName:_e.ZodArray,...Pe(t)});xo=class e extends Ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=$e.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==Yt.object){let l=this._getOrReturnCtx(t);return Dt(l,{code:Nt.invalid_type,expected:Yt.object,received:l.parsedType}),pe}let{status:i,ctx:o}=this._processInputParams(t),{shape:r,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Cr&&this._def.unknownKeys==="strip"))for(let l in o.data)s.includes(l)||a.push(l);let c=[];for(let l of s){let u=r[l],h=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new rr(o,h,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Cr){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(Dt(o,{code:Nt.unrecognized_keys,keys:a}),i.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let h=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new rr(o,h,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let h=await u.key,d=await u.value;l.push({key:h,value:d,alwaysSet:u.alwaysSet})}return l}).then(l=>Li.mergeObjectSync(i,l)):Li.mergeObjectSync(i,c)}get shape(){return this._def.shape()}strict(t){return te.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,i)=>{let o=this._def.errorMap?.(n,i).message??i.defaultError;return n.code==="unrecognized_keys"?{message:te.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:_e.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let i of $e.objectKeys(t))t[i]&&this.shape[i]&&(n[i]=this.shape[i]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let i of $e.objectKeys(this.shape))t[i]||(n[i]=this.shape[i]);return new e({...this._def,shape:()=>n})}deepPartial(){return xp(this)}partial(t){let n={};for(let i of $e.objectKeys(this.shape)){let o=this.shape[i];t&&!t[i]?n[i]=o:n[i]=o.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let i of $e.objectKeys(this.shape))if(t&&!t[i])n[i]=this.shape[i];else{let r=this.shape[i];for(;r instanceof or;)r=r._def.innerType;n[i]=r}return new e({...this._def,shape:()=>n})}keyof(){return MA($e.objectKeys(this.shape))}};xo.create=(e,t)=>new xo({shape:()=>e,unknownKeys:"strip",catchall:Cr.create(),typeName:_e.ZodObject,...Pe(t)});xo.strictCreate=(e,t)=>new xo({shape:()=>e,unknownKeys:"strict",catchall:Cr.create(),typeName:_e.ZodObject,...Pe(t)});xo.lazycreate=(e,t)=>new xo({shape:e,unknownKeys:"strip",catchall:Cr.create(),typeName:_e.ZodObject,...Pe(t)});hl=class extends Ee{_parse(t){let{ctx:n}=this._processInputParams(t),i=this._def.options;function o(r){for(let a of r)if(a.result.status==="valid")return a.result;for(let a of r)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let s=r.map(a=>new bo(a.ctx.common.issues));return Dt(n,{code:Nt.invalid_union,unionErrors:s}),pe}if(n.common.async)return Promise.all(i.map(async r=>{let s={...n,common:{...n.common,issues:[]},parent:null};return{result:await r._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let r,s=[];for(let c of i){let l={...n,common:{...n.common,issues:[]},parent:null},u=c._parseSync({data:n.data,path:n.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!r&&(r={result:u,ctx:l}),l.common.issues.length&&s.push(l.common.issues)}if(r)return n.common.issues.push(...r.ctx.common.issues),r.result;let a=s.map(c=>new bo(c));return Dt(n,{code:Nt.invalid_union,unionErrors:a}),pe}}get options(){return this._def.options}};hl.create=(e,t)=>new hl({options:e,typeName:_e.ZodUnion,...Pe(t)});Os=e=>e instanceof fl?Os(e.schema):e instanceof sr?Os(e.innerType()):e instanceof ml?[e.value]:e instanceof _l?e.options:e instanceof yl?$e.objectValues(e.enum):e instanceof gl?Os(e._def.innerType):e instanceof ul?[void 0]:e instanceof pl?[null]:e instanceof or?[void 0,...Os(e.unwrap())]:e instanceof Kr?[null,...Os(e.unwrap())]:e instanceof Gd||e instanceof xl?Os(e.unwrap()):e instanceof bl?Os(e._def.innerType):[],S_=class e extends Ee{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==Yt.object)return Dt(n,{code:Nt.invalid_type,expected:Yt.object,received:n.parsedType}),pe;let i=this.discriminator,o=n.data[i],r=this.optionsMap.get(o);return r?n.common.async?r._parseAsync({data:n.data,path:n.path,parent:n}):r._parseSync({data:n.data,path:n.path,parent:n}):(Dt(n,{code:Nt.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),pe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,i){let o=new Map;for(let r of n){let s=Os(r.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,r)}}return new e({typeName:_e.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Pe(i)})}};dl=class extends Ee{_parse(t){let{status:n,ctx:i}=this._processInputParams(t),o=(r,s)=>{if(x_(r)||x_(s))return pe;let a=mS(r.value,s.value);return a.valid?((v_(r)||v_(s))&&n.dirty(),{status:n.value,value:a.data}):(Dt(i,{code:Nt.invalid_intersection_types}),pe)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([r,s])=>o(r,s)):o(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}};dl.create=(e,t,n)=>new dl({left:e,right:t,typeName:_e.ZodIntersection,...Pe(n)});Zr=class e extends Ee{_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.parsedType!==Yt.array)return Dt(i,{code:Nt.invalid_type,expected:Yt.array,received:i.parsedType}),pe;if(i.data.length<this._def.items.length)return Dt(i,{code:Nt.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),pe;!this._def.rest&&i.data.length>this._def.items.length&&(Dt(i,{code:Nt.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let r=[...i.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new rr(i,s,i.path,a)):null}).filter(s=>!!s);return i.common.async?Promise.all(r).then(s=>Li.mergeArray(n,s)):Li.mergeArray(n,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Zr.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Zr({items:e,typeName:_e.ZodTuple,rest:null,...Pe(t)})};w_=class e extends Ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.parsedType!==Yt.object)return Dt(i,{code:Nt.invalid_type,expected:Yt.object,received:i.parsedType}),pe;let o=[],r=this._def.keyType,s=this._def.valueType;for(let a in i.data)o.push({key:r._parse(new rr(i,a,i.path,a)),value:s._parse(new rr(i,i.data[a],i.path,a)),alwaysSet:a in i.data});return i.common.async?Li.mergeObjectAsync(n,o):Li.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,i){return n instanceof Ee?new e({keyType:t,valueType:n,typeName:_e.ZodRecord,...Pe(i)}):new e({keyType:Ya.create(),valueType:t,typeName:_e.ZodRecord,...Pe(n)})}},wp=class extends Ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.parsedType!==Yt.map)return Dt(i,{code:Nt.invalid_type,expected:Yt.map,received:i.parsedType}),pe;let o=this._def.keyType,r=this._def.valueType,s=[...i.data.entries()].map(([a,c],l)=>({key:o._parse(new rr(i,a,i.path,[l,"key"])),value:r._parse(new rr(i,c,i.path,[l,"value"]))}));if(i.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return pe;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of s){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return pe;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};wp.create=(e,t,n)=>new wp({valueType:t,keyType:e,typeName:_e.ZodMap,...Pe(n)});Pp=class e extends Ee{_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.parsedType!==Yt.set)return Dt(i,{code:Nt.invalid_type,expected:Yt.set,received:i.parsedType}),pe;let o=this._def;o.minSize!==null&&i.data.size<o.minSize.value&&(Dt(i,{code:Nt.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&i.data.size>o.maxSize.value&&(Dt(i,{code:Nt.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let r=this._def.valueType;function s(c){let l=new Set;for(let u of c){if(u.status==="aborted")return pe;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...i.data.values()].map((c,l)=>r._parse(new rr(i,c,i.path,l)));return i.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:te.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:te.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Pp.create=(e,t)=>new Pp({valueType:e,minSize:null,maxSize:null,typeName:_e.ZodSet,...Pe(t)});P_=class e extends Ee{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==Yt.function)return Dt(n,{code:Nt.invalid_type,expected:Yt.function,received:n.parsedType}),pe;function i(a,c){return Hd({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,gp(),Rs].filter(l=>!!l),issueData:{code:Nt.invalid_arguments,argumentsError:c}})}function o(a,c){return Hd({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,gp(),Rs].filter(l=>!!l),issueData:{code:Nt.invalid_return_type,returnTypeError:c}})}let r={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof Va){let a=this;return Ui(async function(...c){let l=new bo([]),u=await a._def.args.parseAsync(c,r).catch(_=>{throw l.addIssue(i(c,_)),l}),h=await Reflect.apply(s,this,u);return await a._def.returns._def.type.parseAsync(h,r).catch(_=>{throw l.addIssue(o(h,_)),l})})}else{let a=this;return Ui(function(...c){let l=a._def.args.safeParse(c,r);if(!l.success)throw new bo([i(c,l.error)]);let u=Reflect.apply(s,this,l.data),h=a._def.returns.safeParse(u,r);if(!h.success)throw new bo([o(u,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Zr.create(t).rest(Ls.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,i){return new e({args:t||Zr.create([]).rest(Ls.create()),returns:n||Ls.create(),typeName:_e.ZodFunction,...Pe(i)})}},fl=class extends Ee{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};fl.create=(e,t)=>new fl({getter:e,typeName:_e.ZodLazy,...Pe(t)});ml=class extends Ee{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return Dt(n,{received:n.data,code:Nt.invalid_literal,expected:this._def.value}),pe}return{status:"valid",value:t.data}}get value(){return this._def.value}};ml.create=(e,t)=>new ml({value:e,typeName:_e.ZodLiteral,...Pe(t)});_l=class e extends Ee{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),i=this._def.values;return Dt(n,{expected:$e.joinValues(i),received:n.parsedType,code:Nt.invalid_type}),pe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),i=this._def.values;return Dt(n,{received:n.data,code:Nt.invalid_enum_value,options:i}),pe}return Ui(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(i=>!t.includes(i)),{...this._def,...n})}};_l.create=MA;yl=class extends Ee{_parse(t){let n=$e.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==Yt.string&&i.parsedType!==Yt.number){let o=$e.objectValues(n);return Dt(i,{expected:$e.joinValues(o),received:i.parsedType,code:Nt.invalid_type}),pe}if(this._cache||(this._cache=new Set($e.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=$e.objectValues(n);return Dt(i,{received:i.data,code:Nt.invalid_enum_value,options:o}),pe}return Ui(t.data)}get enum(){return this._def.values}};yl.create=(e,t)=>new yl({values:e,typeName:_e.ZodNativeEnum,...Pe(t)});Va=class extends Ee{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==Yt.promise&&n.common.async===!1)return Dt(n,{code:Nt.invalid_type,expected:Yt.promise,received:n.parsedType}),pe;let i=n.parsedType===Yt.promise?n.data:Promise.resolve(n.data);return Ui(i.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Va.create=(e,t)=>new Va({type:e,typeName:_e.ZodPromise,...Pe(t)});sr=class extends Ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_e.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:i}=this._processInputParams(t),o=this._def.effect||null,r={addIssue:s=>{Dt(i,s),s.fatal?n.abort():n.dirty()},get path(){return i.path}};if(r.addIssue=r.addIssue.bind(r),o.type==="preprocess"){let s=o.transform(i.data,r);if(i.common.async)return Promise.resolve(s).then(async a=>{if(n.value==="aborted")return pe;let c=await this._def.schema._parseAsync({data:a,path:i.path,parent:i});return c.status==="aborted"?pe:c.status==="dirty"?rl(c.value):n.value==="dirty"?rl(c.value):c});{if(n.value==="aborted")return pe;let a=this._def.schema._parseSync({data:s,path:i.path,parent:i});return a.status==="aborted"?pe:a.status==="dirty"?rl(a.value):n.value==="dirty"?rl(a.value):a}}if(o.type==="refinement"){let s=a=>{let c=o.refinement(a,r);if(i.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(i.common.async===!1){let a=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return a.status==="aborted"?pe:(a.status==="dirty"&&n.dirty(),s(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(a=>a.status==="aborted"?pe:(a.status==="dirty"&&n.dirty(),s(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(i.common.async===!1){let s=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!Ba(s))return pe;let a=o.transform(s.value,r);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(s=>Ba(s)?Promise.resolve(o.transform(s.value,r)).then(a=>({status:n.value,value:a})):pe);$e.assertNever(o)}};sr.create=(e,t,n)=>new sr({schema:e,typeName:_e.ZodEffects,effect:t,...Pe(n)});sr.createWithPreprocess=(e,t,n)=>new sr({schema:t,effect:{type:"preprocess",transform:e},typeName:_e.ZodEffects,...Pe(n)});or=class extends Ee{_parse(t){return this._getType(t)===Yt.undefined?Ui(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};or.create=(e,t)=>new or({innerType:e,typeName:_e.ZodOptional,...Pe(t)});Kr=class extends Ee{_parse(t){return this._getType(t)===Yt.null?Ui(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Kr.create=(e,t)=>new Kr({innerType:e,typeName:_e.ZodNullable,...Pe(t)});gl=class extends Ee{_parse(t){let{ctx:n}=this._processInputParams(t),i=n.data;return n.parsedType===Yt.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};gl.create=(e,t)=>new gl({innerType:e,typeName:_e.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Pe(t)});bl=class extends Ee{_parse(t){let{ctx:n}=this._processInputParams(t),i={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return bp(o)?o.then(r=>({status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new bo(i.common.issues)},input:i.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new bo(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}};bl.create=(e,t)=>new bl({innerType:e,typeName:_e.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Pe(t)});Ip=class extends Ee{_parse(t){if(this._getType(t)!==Yt.nan){let i=this._getOrReturnCtx(t);return Dt(i,{code:Nt.invalid_type,expected:Yt.nan,received:i.parsedType}),pe}return{status:"valid",value:t.data}}};Ip.create=e=>new Ip({typeName:_e.ZodNaN,...Pe(e)});wQ=Symbol("zod_brand"),Gd=class extends Ee{_parse(t){let{ctx:n}=this._processInputParams(t),i=n.data;return this._def.type._parse({data:i,path:n.path,parent:n})}unwrap(){return this._def.type}},Ud=class e extends Ee{_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{let r=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return r.status==="aborted"?pe:r.status==="dirty"?(n.dirty(),rl(r.value)):this._def.out._parseAsync({data:r.value,path:i.path,parent:i})})();{let o=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?pe:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:i.path,parent:i})}}static create(t,n){return new e({in:t,out:n,typeName:_e.ZodPipeline})}},xl=class extends Ee{_parse(t){let n=this._def.innerType._parse(t),i=o=>(Ba(o)&&(o.value=Object.freeze(o.value)),o);return bp(n)?n.then(o=>i(o)):i(n)}unwrap(){return this._def.innerType}};xl.create=(e,t)=>new xl({innerType:e,typeName:_e.ZodReadonly,...Pe(t)});PQ={object:xo.lazycreate};(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(_e||(_e={}));IQ=(e,t={message:`Input not instance of ${e.name}`})=>CA(n=>n instanceof e,t),EA=Ya.create,NA=sl.create,TQ=Ip.create,MQ=al.create,kA=cl.create,CQ=ll.create,EQ=vp.create,NQ=ul.create,kQ=pl.create,AQ=Xa.create,RQ=Ls.create,OQ=Cr.create,LQ=Sp.create,FQ=Fs.create,zQ=xo.create,DQ=xo.strictCreate,$Q=hl.create,jQ=S_.create,BQ=dl.create,YQ=Zr.create,XQ=w_.create,VQ=wp.create,HQ=Pp.create,GQ=P_.create,UQ=fl.create,qQ=ml.create,WQ=_l.create,ZQ=yl.create,KQ=Va.create,JQ=sr.create,QQ=or.create,ttt=Kr.create,ett=sr.createWithPreprocess,ntt=Ud.create,itt=()=>EA().optional(),ott=()=>NA().optional(),rtt=()=>kA().optional(),stt={string:(e=>Ya.create({...e,coerce:!0})),number:(e=>sl.create({...e,coerce:!0})),boolean:(e=>cl.create({...e,coerce:!0})),bigint:(e=>al.create({...e,coerce:!0})),date:(e=>ll.create({...e,coerce:!0}))},att=pe});var p={};il(p,{BRAND:()=>wQ,DIRTY:()=>rl,EMPTY_PATH:()=>eQ,INVALID:()=>pe,NEVER:()=>att,OK:()=>Ui,ParseStatus:()=>Li,Schema:()=>Ee,ZodAny:()=>Xa,ZodArray:()=>Fs,ZodBigInt:()=>al,ZodBoolean:()=>cl,ZodBranded:()=>Gd,ZodCatch:()=>bl,ZodDate:()=>ll,ZodDefault:()=>gl,ZodDiscriminatedUnion:()=>S_,ZodEffects:()=>sr,ZodEnum:()=>_l,ZodError:()=>bo,ZodFirstPartyTypeKind:()=>_e,ZodFunction:()=>P_,ZodIntersection:()=>dl,ZodIssueCode:()=>Nt,ZodLazy:()=>fl,ZodLiteral:()=>ml,ZodMap:()=>wp,ZodNaN:()=>Ip,ZodNativeEnum:()=>yl,ZodNever:()=>Cr,ZodNull:()=>pl,ZodNullable:()=>Kr,ZodNumber:()=>sl,ZodObject:()=>xo,ZodOptional:()=>or,ZodParsedType:()=>Yt,ZodPipeline:()=>Ud,ZodPromise:()=>Va,ZodReadonly:()=>xl,ZodRecord:()=>w_,ZodSchema:()=>Ee,ZodSet:()=>Pp,ZodString:()=>Ya,ZodSymbol:()=>vp,ZodTransformer:()=>sr,ZodTuple:()=>Zr,ZodType:()=>Ee,ZodUndefined:()=>ul,ZodUnion:()=>hl,ZodUnknown:()=>Ls,ZodVoid:()=>Sp,addIssueToContext:()=>Dt,any:()=>AQ,array:()=>FQ,bigint:()=>MQ,boolean:()=>kA,coerce:()=>stt,custom:()=>CA,date:()=>CQ,datetimeRegex:()=>TA,defaultErrorMap:()=>Rs,discriminatedUnion:()=>jQ,effect:()=>JQ,enum:()=>WQ,function:()=>GQ,getErrorMap:()=>gp,getParsedType:()=>Wr,instanceof:()=>IQ,intersection:()=>BQ,isAborted:()=>x_,isAsync:()=>bp,isDirty:()=>v_,isValid:()=>Ba,late:()=>PQ,lazy:()=>UQ,literal:()=>qQ,makeIssue:()=>Hd,map:()=>VQ,nan:()=>TQ,nativeEnum:()=>ZQ,never:()=>OQ,null:()=>kQ,nullable:()=>ttt,number:()=>NA,object:()=>zQ,objectUtil:()=>pS,oboolean:()=>rtt,onumber:()=>ott,optional:()=>QQ,ostring:()=>itt,pipeline:()=>ntt,preprocess:()=>ett,promise:()=>KQ,quotelessJson:()=>JJ,record:()=>XQ,set:()=>HQ,setErrorMap:()=>tQ,strictObject:()=>DQ,string:()=>EA,symbol:()=>EQ,transformer:()=>JQ,tuple:()=>YQ,undefined:()=>NQ,union:()=>$Q,unknown:()=>RQ,util:()=>$e,void:()=>LQ});var _S=Ht(()=>{"use strict";b_();dS();xA();Vd();AA();g_()});var K=Ht(()=>{"use strict";_S();_S()});var Pl={};il(Pl,{all_layers:()=>Cp,any_circuit_element:()=>q6,any_soup_element:()=>wl,any_source_component:()=>XA,battery_capacity:()=>zA,brep_shape:()=>P9,cad_component:()=>z6,capacitance:()=>zs,circuit_json_footprint_load_error:()=>k_,current:()=>ltt,distance:()=>Y,duration_ms:()=>qd,experiment_type:()=>Y6,external_footprint_load_error:()=>Ep,frequency:()=>Wi,getZodPrefixedIdWithDefault:()=>kt,inductance:()=>I_,layer_ref:()=>se,layer_string:()=>gS,length:()=>D,ms:()=>qi,ninePointAnchor:()=>Wd,pcb_autorouting_error:()=>w6,pcb_board:()=>W9,pcb_breakout_point:()=>P6,pcb_component:()=>T9,pcb_component_invalid_layer_error:()=>Np,pcb_component_outside_board_error:()=>A6,pcb_copper_pour:()=>k6,pcb_copper_pour_brep:()=>E6,pcb_copper_pour_polygon:()=>N6,pcb_copper_pour_rect:()=>C6,pcb_copper_text:()=>n6,pcb_courtyard_outline:()=>L6,pcb_courtyard_polygon:()=>F6,pcb_courtyard_rect:()=>O6,pcb_cutout:()=>x6,pcb_cutout_circle:()=>g6,pcb_cutout_polygon:()=>b6,pcb_cutout_rect:()=>y6,pcb_fabrication_note_dimension:()=>l6,pcb_fabrication_note_path:()=>a6,pcb_fabrication_note_rect:()=>c6,pcb_fabrication_note_text:()=>s6,pcb_footprint_overlap_error:()=>m6,pcb_ground_plane:()=>I6,pcb_ground_plane_region:()=>T6,pcb_group:()=>S6,pcb_hole:()=>R9,pcb_hole_circle_or_square_shape:()=>btt,pcb_hole_circle_shape:()=>ytt,pcb_hole_oval_shape:()=>xtt,pcb_hole_pill_shape:()=>vtt,pcb_hole_rect_shape:()=>gtt,pcb_hole_rotated_pill_shape:()=>Stt,pcb_keepout:()=>_6,pcb_manual_edit_conflict_warning:()=>A_,pcb_missing_footprint_error:()=>v6,pcb_net:()=>U9,pcb_note_dimension:()=>f6,pcb_note_line:()=>d6,pcb_note_path:()=>h6,pcb_note_rect:()=>p6,pcb_note_text:()=>u6,pcb_panel:()=>Z9,pcb_placement_error:()=>K9,pcb_plated_hole:()=>O9,pcb_port:()=>L9,pcb_port_not_connected_error:()=>G9,pcb_port_not_matched_error:()=>H9,pcb_route_hint:()=>I9,pcb_route_hints:()=>_tt,pcb_silkscreen_circle:()=>o6,pcb_silkscreen_line:()=>Q9,pcb_silkscreen_oval:()=>r6,pcb_silkscreen_path:()=>t6,pcb_silkscreen_rect:()=>i6,pcb_silkscreen_text:()=>e6,pcb_smtpad:()=>z9,pcb_smtpad_pill:()=>F9,pcb_solder_paste:()=>D9,pcb_text:()=>$9,pcb_thermal_spoke:()=>M6,pcb_trace:()=>Y9,pcb_trace_error:()=>X9,pcb_trace_hint:()=>J9,pcb_trace_missing_error:()=>V9,pcb_trace_route_point:()=>N_,pcb_trace_route_point_via:()=>B9,pcb_trace_route_point_wire:()=>j9,pcb_via:()=>q9,pcb_via_clearance_error:()=>R6,point:()=>qt,point3:()=>vl,point_with_bulge:()=>w9,port_arrangement:()=>n9,position:()=>ptt,position3:()=>htt,resistance:()=>Ha,ring:()=>bS,rotation:()=>Be,route_hint_point:()=>Fi,schematic_arc:()=>a9,schematic_box:()=>KA,schematic_circle:()=>s9,schematic_component:()=>i9,schematic_component_port_arrangement_by_sides:()=>e9,schematic_component_port_arrangement_by_size:()=>t9,schematic_debug_line:()=>m9,schematic_debug_object:()=>y9,schematic_debug_object_base:()=>C_,schematic_debug_point:()=>_9,schematic_debug_rect:()=>f9,schematic_error:()=>h9,schematic_group:()=>b9,schematic_layout_error:()=>d9,schematic_line:()=>o9,schematic_manual_edit_conflict_warning:()=>E_,schematic_net_label:()=>p9,schematic_path:()=>JA,schematic_pin_styles:()=>QA,schematic_port:()=>u9,schematic_rect:()=>r9,schematic_sheet:()=>S9,schematic_table:()=>x9,schematic_table_cell:()=>v9,schematic_text:()=>l9,schematic_trace:()=>c9,schematic_voltage_probe:()=>g9,simulation_ac_voltage_source:()=>j6,simulation_dc_voltage_source:()=>$6,simulation_experiment:()=>X6,simulation_switch:()=>H6,simulation_transient_voltage_graph:()=>V6,simulation_unknown_experiment_error:()=>U6,simulation_voltage_probe:()=>G6,simulation_voltage_source:()=>B6,size:()=>xS,source_board:()=>qA,source_component_base:()=>Jn,source_failed_to_create_component_error:()=>BA,source_group:()=>GA,source_manually_placed_via:()=>ZA,source_missing_property_error:()=>jA,source_net:()=>UA,source_pcb_ground_plane:()=>WA,source_pin_missing_trace_warning:()=>$S,source_port:()=>VA,source_project_metadata:()=>zS,source_property_ignored_warning:()=>YA,source_simple_battery:()=>TS,source_simple_capacitor:()=>vS,source_simple_chip:()=>PS,source_simple_crystal:()=>$A,source_simple_diode:()=>T_,source_simple_ground:()=>DA,source_simple_inductor:()=>MS,source_simple_led:()=>wS,source_simple_mosfet:()=>LS,source_simple_pin_header:()=>NS,source_simple_pinout:()=>kS,source_simple_potentiometer:()=>ES,source_simple_power_source:()=>IS,source_simple_push_button:()=>CS,source_simple_resistor:()=>SS,source_simple_resonator:()=>AS,source_simple_switch:()=>FS,source_simple_test_point:()=>OS,source_simple_transistor:()=>RS,source_trace:()=>HA,source_trace_not_connected_error:()=>DS,supplier_name:()=>Mp,time:()=>utt,timestamp:()=>FA,unknown_error_finding_part:()=>M_,visible_layer:()=>Nr,voltage:()=>ai,wave_shape:()=>D6});function ctt(e){for(let[t,n]of Object.entries(LA))if(e in n.variants)return{baseUnit:n.baseUnit,conversionFactor:n.variants[e]};return{baseUnit:e,conversionFactor:1}}function Er(e){if(e==null)return{parsedUnit:null,unitOfValue:null,value:null};if(typeof e=="string"&&e.match(/^-?[\d\.]+$/))return{value:Number.parseFloat(e),parsedUnit:null,unitOfValue:null};if(typeof e=="number")return{value:e,parsedUnit:null,unitOfValue:null};if(typeof e=="object"&&"x"in e&&"y"in e){let{parsedUnit:a,unitOfValue:c}=Er(e.x),l=Er(e.x),u=Er(e.y);return l.value===null||u.value===null?{parsedUnit:null,unitOfValue:null,value:null}:{parsedUnit:a,unitOfValue:c,value:{x:l.value,y:u.value}}}let n=e.toString().split("").reverse().join("").match(/[^\d\s]+/)?.[0];if(!n)throw new Error(`Could not determine unit: "${e}"`);let i=n.split("").reverse().join(""),o=e.slice(0,-i.length);if(i in OA&&!yS.has(i)){let a=OA[i];return{parsedUnit:null,unitOfValue:null,value:Number.parseFloat(o)*a}}let{baseUnit:r,conversionFactor:s}=ctt(i);return{parsedUnit:i,unitOfValue:r,value:s*Number.parseFloat(o)}}var LA,yS,OA,Ha,zs,I_,ai,D,Wi,Y,ltt,qd,utt,qi,FA,Be,zA,mt,Sl,qt,ptt,vl,htt,xS,dtt,kt,Wd,Mp,Jn,vS,SS,T_,wS,DA,PS,IS,ftt,TS,MS,CS,ES,$A,NS,kS,AS,RS,OS,LS,FS,zS,jA,BA,DS,YA,$S,XA,VA,HA,GA,UA,qA,WA,Cp,gS,se,Nr,ZA,M_,KA,JA,QA,t9,e9,n9,i9,o9,r9,s9,a9,c9,mtt,l9,u9,p9,h9,d9,C_,f9,m9,_9,y9,g9,E_,b9,x9,v9,S9,w9,bS,P9,I9,_tt,Fi,T9,M9,ytt,C9,gtt,E9,btt,N9,xtt,k9,vtt,A9,Stt,R9,wtt,Ptt,Itt,Ttt,Mtt,O9,L9,Ctt,Ett,Ntt,F9,ktt,Att,z9,Rtt,Ott,Ltt,Ftt,ztt,D9,$9,j9,B9,N_,Y9,X9,V9,H9,G9,U9,q9,W9,Z9,K9,J9,Q9,t6,e6,n6,i6,o6,r6,s6,a6,c6,l6,u6,p6,h6,d6,f6,m6,_6,jS,y6,g6,b6,x6,v6,Ep,k_,S6,w6,A_,P6,I6,T6,M6,BS,C6,E6,N6,k6,A6,Np,R6,O6,L6,F6,z6,D6,Dtt,$6,j6,B6,Y6,X6,V6,H6,G6,U6,q6,wl,vt=Ht(()=>{"use strict";K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();LA={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:{fs:1e-12,ps:1e-9,ns:1e-6,us:.001,\u00B5s:.001,ms:1,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}}},yS=new Set;for(let[e,t]of Object.entries(LA)){yS.add(e);for(let n of Object.keys(t.variants))yS.add(n)}OA={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};Ha=p.string().or(p.number()).transform(e=>Er(e).value),zs=p.string().or(p.number()).transform(e=>Er(e).value).transform(e=>Number.parseFloat(e.toPrecision(12))),I_=p.string().or(p.number()).transform(e=>Er(e).value),ai=p.string().or(p.number()).transform(e=>Er(e).value),D=p.string().or(p.number()).transform(e=>Er(e).value),Wi=p.string().or(p.number()).transform(e=>Er(e).value),Y=D,ltt=p.string().or(p.number()).transform(e=>Er(e).value),qd=p.string().or(p.number()).transform(e=>Er(e).value),utt=qd,qi=qd,FA=p.string().datetime(),Be=p.string().or(p.number()).transform(e=>typeof e=="number"?e:e.endsWith("deg")?Number.parseFloat(e.split("deg")[0]):e.endsWith("rad")?Number.parseFloat(e.split("rad")[0])*180/Math.PI:Number.parseFloat(e)),zA=p.number().or(p.string().endsWith("mAh")).transform(e=>{if(typeof e=="string"){let t=e.replace("mAh",""),n=Number.parseFloat(t);if(Number.isNaN(n))throw new Error("Invalid capacity");return n}return e}).describe("Battery capacity in mAh"),mt=e=>{};mt("extra props b");mt("missing props b");mt(!0);mt("mismatched prop types: a");Sl=e=>{};Sl(!0);Sl('T1 has extra: "c", T2 has extra: "d"');Sl('T1 has extra: "c"');Sl('T2 has extra: "c"');Sl('T1 has extra: "d", T2 has extra: "c"');Sl(!0);qt=p.object({x:Y,y:Y}),ptt=qt;mt(!0);mt(!0);vl=p.object({x:Y,y:Y,z:Y}),htt=vl;mt(!0);xS=p.object({width:p.number(),height:p.number()});mt(!0);dtt=e=>{let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";return Array.from({length:e},()=>t[Math.floor(Math.random()*t.length)]).join("")},kt=e=>p.string().optional().default(()=>`${e}_${dtt(10)}`),Wd=p.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]);mt(!0);Mp=p.enum(["jlcpcb","macrofab","pcbway","digikey","mouser","lcsc"]);mt(!0);Jn=p.object({type:p.literal("source_component"),ftype:p.string().optional(),source_component_id:p.string(),name:p.string(),manufacturer_part_number:p.string().optional(),supplier_part_numbers:p.record(Mp,p.array(p.string())).optional(),display_value:p.string().optional(),are_pins_interchangeable:p.boolean().optional(),internally_connected_source_port_ids:p.array(p.array(p.string())).optional(),source_group_id:p.string().optional(),subcircuit_id:p.string().optional()});mt(!0);vS=Jn.extend({ftype:p.literal("simple_capacitor"),capacitance:zs,max_voltage_rating:ai.optional(),display_capacitance:p.string().optional(),max_decoupling_trace_length:Y.optional()});mt(!0);SS=Jn.extend({ftype:p.literal("simple_resistor"),resistance:Ha,display_resistance:p.string().optional()});mt(!0);T_=Jn.extend({ftype:p.literal("simple_diode")});mt(!0);wS=T_.extend({ftype:p.literal("simple_led"),color:p.string().optional(),wavelength:p.string().optional()});mt(!0);DA=Jn.extend({ftype:p.literal("simple_ground")});mt(!0);PS=Jn.extend({ftype:p.literal("simple_chip")});mt(!0);IS=Jn.extend({ftype:p.literal("simple_power_source"),voltage:ai});mt(!0);ftt=Jn.extend({ftype:p.literal("simple_fuse"),current_rating_amps:p.number().describe("Nominal current in amps the fuse is rated for"),voltage_rating_volts:p.number().describe("Voltage rating in volts, e.g. \xB15V would be 5")});mt(!0);TS=Jn.extend({ftype:p.literal("simple_battery"),capacity:zA});mt(!0);MS=Jn.extend({ftype:p.literal("simple_inductor"),inductance:I_,max_current_rating:p.number().optional()});mt(!0);CS=Jn.extend({ftype:p.literal("simple_push_button")});mt(!0);ES=Jn.extend({ftype:p.literal("simple_potentiometer"),max_resistance:Ha});mt(!0);$A=Jn.extend({ftype:p.literal("simple_crystal"),frequency:p.number().describe("Frequency in Hz"),load_capacitance:p.number().optional().describe("Load capacitance in pF")});mt(!0);NS=Jn.extend({ftype:p.literal("simple_pin_header"),pin_count:p.number(),gender:p.enum(["male","female"]).optional().default("male")});mt(!0);kS=Jn.extend({ftype:p.literal("simple_pinout")});mt(!0);AS=Jn.extend({ftype:p.literal("simple_resonator"),load_capacitance:zs,equivalent_series_resistance:Ha.optional(),frequency:Wi});mt(!0);RS=Jn.extend({ftype:p.literal("simple_transistor"),transistor_type:p.enum(["npn","pnp"])});mt(!0);OS=Jn.extend({ftype:p.literal("simple_test_point"),footprint_variant:p.enum(["pad","through_hole"]).optional(),pad_shape:p.enum(["rect","circle"]).optional(),pad_diameter:p.union([p.number(),p.string()]).optional(),hole_diameter:p.union([p.number(),p.string()]).optional(),width:p.union([p.number(),p.string()]).optional(),height:p.union([p.number(),p.string()]).optional()});mt(!0);LS=Jn.extend({ftype:p.literal("simple_mosfet"),channel_type:p.enum(["n","p"]),mosfet_mode:p.enum(["enhancement","depletion"])});mt(!0);FS=Jn.extend({ftype:p.literal("simple_switch")});mt(!0);zS=p.object({type:p.literal("source_project_metadata"),name:p.string().optional(),software_used_string:p.string().optional(),project_url:p.string().optional(),created_at:FA.optional()});mt(!0);jA=p.object({type:p.literal("source_missing_property_error"),source_missing_property_error_id:kt("source_missing_property_error"),source_component_id:p.string(),property_name:p.string(),subcircuit_id:p.string().optional(),error_type:p.literal("source_missing_property_error").default("source_missing_property_error"),message:p.string()}).describe("The source code is missing a property");mt(!0);BA=p.object({type:p.literal("source_failed_to_create_component_error"),source_failed_to_create_component_error_id:kt("source_failed_to_create_component_error"),error_type:p.literal("source_failed_to_create_component_error").default("source_failed_to_create_component_error"),component_name:p.string().optional(),subcircuit_id:p.string().optional(),parent_source_component_id:p.string().optional(),message:p.string(),pcb_center:p.object({x:p.number().optional(),y:p.number().optional()}).optional(),schematic_center:p.object({x:p.number().optional(),y:p.number().optional()}).optional()}).describe("Error emitted when a component fails to be constructed");mt(!0);DS=p.object({type:p.literal("source_trace_not_connected_error"),source_trace_not_connected_error_id:kt("source_trace_not_connected_error"),error_type:p.literal("source_trace_not_connected_error").default("source_trace_not_connected_error"),message:p.string(),subcircuit_id:p.string().optional(),source_group_id:p.string().optional(),source_trace_id:p.string().optional(),connected_source_port_ids:p.array(p.string()).optional(),selectors_not_found:p.array(p.string()).optional()}).describe("Occurs when a source trace selector does not match any ports");mt(!0);YA=p.object({type:p.literal("source_property_ignored_warning"),source_property_ignored_warning_id:kt("source_property_ignored_warning"),source_component_id:p.string(),property_name:p.string(),subcircuit_id:p.string().optional(),error_type:p.literal("source_property_ignored_warning").default("source_property_ignored_warning"),message:p.string()}).describe("The source property was ignored");mt(!0);$S=p.object({type:p.literal("source_pin_missing_trace_warning"),source_pin_missing_trace_warning_id:kt("source_pin_missing_trace_warning"),warning_type:p.literal("source_pin_missing_trace_warning").default("source_pin_missing_trace_warning"),message:p.string(),source_component_id:p.string(),source_port_id:p.string(),subcircuit_id:p.string().optional()}).describe("Warning emitted when a source component pin is missing a trace connection");mt(!0);XA=p.union([SS,vS,T_,wS,DA,PS,IS,TS,MS,CS,ES,$A,NS,kS,AS,FS,RS,OS,LS,ftt,zS,jA,BA,DS,YA,$S]);mt(!0);VA=p.object({type:p.literal("source_port"),pin_number:p.number().optional(),port_hints:p.array(p.string()).optional(),name:p.string(),source_port_id:p.string(),source_component_id:p.string().optional(),source_group_id:p.string().optional(),subcircuit_id:p.string().optional(),subcircuit_connectivity_map_key:p.string().optional()});mt(!0);HA=p.object({type:p.literal("source_trace"),source_trace_id:p.string(),connected_source_port_ids:p.array(p.string()),connected_source_net_ids:p.array(p.string()),subcircuit_id:p.string().optional(),subcircuit_connectivity_map_key:p.string().optional(),max_length:p.number().optional(),min_trace_thickness:p.number().optional(),display_name:p.string().optional()});mt(!0);GA=p.object({type:p.literal("source_group"),source_group_id:p.string(),subcircuit_id:p.string().optional(),parent_subcircuit_id:p.string().optional(),parent_source_group_id:p.string().optional(),is_subcircuit:p.boolean().optional(),show_as_schematic_box:p.boolean().optional(),name:p.string().optional(),was_automatically_named:p.boolean().optional()});mt(!0);UA=p.object({type:p.literal("source_net"),source_net_id:p.string(),name:p.string(),member_source_group_ids:p.array(p.string()),is_power:p.boolean().optional(),is_ground:p.boolean().optional(),is_digital_signal:p.boolean().optional(),is_analog_signal:p.boolean().optional(),is_positive_voltage_source:p.boolean().optional(),trace_width:p.number().optional(),subcircuit_id:p.string().optional(),subcircuit_connectivity_map_key:p.string().optional()});mt(!0);qA=p.object({type:p.literal("source_board"),source_board_id:p.string(),source_group_id:p.string(),title:p.string().optional()}).describe("Defines a board in the source domain");mt(!0);WA=p.object({type:p.literal("source_pcb_ground_plane"),source_pcb_ground_plane_id:p.string(),source_group_id:p.string(),source_net_id:p.string(),subcircuit_id:p.string().optional()}).describe("Defines a ground plane in the source domain");mt(!0);Cp=["top","bottom","inner1","inner2","inner3","inner4","inner5","inner6"],gS=p.enum(Cp),se=gS.or(p.object({name:gS})).transform(e=>typeof e=="string"?e:e.name);mt(!0);Nr=p.enum(["top","bottom"]),ZA=p.object({type:p.literal("source_manually_placed_via"),source_manually_placed_via_id:p.string(),source_group_id:p.string(),source_net_id:p.string(),subcircuit_id:p.string().optional(),source_trace_id:p.string().optional()}).describe("Defines a via that is manually placed in the source domain");mt(!0);M_=p.object({type:p.literal("unknown_error_finding_part"),unknown_error_finding_part_id:kt("unknown_error_finding_part"),error_type:p.literal("unknown_error_finding_part").default("unknown_error_finding_part"),message:p.string(),source_component_id:p.string().optional(),subcircuit_id:p.string().optional()}).describe("Error emitted when an unexpected error occurs while finding a part");mt(!0);KA=p.object({type:p.literal("schematic_box"),schematic_component_id:p.string().optional(),width:Y,height:Y,is_dashed:p.boolean().default(!1),x:Y,y:Y,subcircuit_id:p.string().optional()}).describe("Draws a box on the schematic");mt(!0);JA=p.object({type:p.literal("schematic_path"),schematic_component_id:p.string(),fill_color:p.enum(["red","blue"]).optional(),is_filled:p.boolean().optional(),points:p.array(qt),subcircuit_id:p.string().optional()});mt(!0);QA=p.record(p.object({left_margin:D.optional(),right_margin:D.optional(),top_margin:D.optional(),bottom_margin:D.optional()})),t9=p.object({left_size:p.number(),right_size:p.number(),top_size:p.number().optional(),bottom_size:p.number().optional()});mt(!0);e9=p.object({left_side:p.object({pins:p.array(p.number()),direction:p.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),right_side:p.object({pins:p.array(p.number()),direction:p.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),top_side:p.object({pins:p.array(p.number()),direction:p.enum(["left-to-right","right-to-left"]).optional()}).optional(),bottom_side:p.object({pins:p.array(p.number()),direction:p.enum(["left-to-right","right-to-left"]).optional()}).optional()});mt(!0);n9=p.union([t9,e9]),i9=p.object({type:p.literal("schematic_component"),size:xS,center:qt,source_component_id:p.string().optional(),schematic_component_id:p.string(),pin_spacing:D.optional(),pin_styles:QA.optional(),box_width:D.optional(),symbol_name:p.string().optional(),port_arrangement:n9.optional(),port_labels:p.record(p.string()).optional(),symbol_display_value:p.string().optional(),subcircuit_id:p.string().optional(),schematic_group_id:p.string().optional(),is_schematic_group:p.boolean().optional(),source_group_id:p.string().optional(),is_box_with_pins:p.boolean().optional().default(!0)});mt(!0);o9=p.object({type:p.literal("schematic_line"),schematic_line_id:kt("schematic_line"),schematic_component_id:p.string(),x1:Y,y1:Y,x2:Y,y2:Y,stroke_width:Y.nullable().optional(),color:p.string().default("#000000"),is_dashed:p.boolean().default(!1),subcircuit_id:p.string().optional()}).describe("Draws a styled line on the schematic");mt(!0);r9=p.object({type:p.literal("schematic_rect"),schematic_rect_id:kt("schematic_rect"),schematic_component_id:p.string(),center:qt,width:Y,height:Y,rotation:Be.default(0),stroke_width:Y.nullable().optional(),color:p.string().default("#000000"),is_filled:p.boolean().default(!1),fill_color:p.string().optional(),is_dashed:p.boolean().default(!1),subcircuit_id:p.string().optional()}).describe("Draws a styled rectangle on the schematic");mt(!0);s9=p.object({type:p.literal("schematic_circle"),schematic_circle_id:kt("schematic_circle"),schematic_component_id:p.string(),center:qt,radius:Y,stroke_width:Y.nullable().optional(),color:p.string().default("#000000"),is_filled:p.boolean().default(!1),fill_color:p.string().optional(),is_dashed:p.boolean().default(!1),subcircuit_id:p.string().optional()}).describe("Draws a styled circle on the schematic");mt(!0);a9=p.object({type:p.literal("schematic_arc"),schematic_arc_id:kt("schematic_arc"),schematic_component_id:p.string(),center:qt,radius:Y,start_angle_degrees:Be,end_angle_degrees:Be,direction:p.enum(["clockwise","counterclockwise"]).default("counterclockwise"),stroke_width:Y.nullable().optional(),color:p.string().default("#000000"),is_dashed:p.boolean().default(!1),subcircuit_id:p.string().optional()}).describe("Draws a styled arc on the schematic");mt(!0);c9=p.object({type:p.literal("schematic_trace"),schematic_trace_id:p.string(),source_trace_id:p.string().optional(),junctions:p.array(p.object({x:p.number(),y:p.number()})),edges:p.array(p.object({from:p.object({x:p.number(),y:p.number()}),to:p.object({x:p.number(),y:p.number()}),is_crossing:p.boolean().optional(),from_schematic_port_id:p.string().optional(),to_schematic_port_id:p.string().optional()})),subcircuit_id:p.string().optional(),subcircuit_connectivity_map_key:p.string().optional()});mt(!0);mtt=p.enum(["center","left","right","top","bottom"]);mt(!0);l9=p.object({type:p.literal("schematic_text"),schematic_component_id:p.string().optional(),schematic_text_id:p.string(),text:p.string(),font_size:p.number().default(.18),position:p.object({x:Y,y:Y}),rotation:p.number().default(0),anchor:p.union([mtt.describe("legacy"),Wd]).default("center"),color:p.string().default("#000000"),subcircuit_id:p.string().optional()});mt(!0);u9=p.object({type:p.literal("schematic_port"),schematic_port_id:p.string(),source_port_id:p.string(),schematic_component_id:p.string().optional(),center:qt,facing_direction:p.enum(["up","down","left","right"]).optional(),distance_from_component_edge:p.number().optional(),side_of_component:p.enum(["top","bottom","left","right"]).optional(),true_ccw_index:p.number().optional(),pin_number:p.number().optional(),display_pin_label:p.string().optional(),subcircuit_id:p.string().optional(),is_connected:p.boolean().optional(),has_input_arrow:p.boolean().optional(),has_output_arrow:p.boolean().optional()}).describe("Defines a port on a schematic component");mt(!0);p9=p.object({type:p.literal("schematic_net_label"),schematic_net_label_id:kt("schematic_net_label"),schematic_trace_id:p.string().optional(),source_trace_id:p.string().optional(),source_net_id:p.string(),center:qt,anchor_position:qt.optional(),anchor_side:p.enum(["top","bottom","left","right"]),text:p.string(),symbol_name:p.string().optional(),is_movable:p.boolean().optional(),subcircuit_id:p.string().optional()});mt(!0);h9=p.object({type:p.literal("schematic_error"),schematic_error_id:p.string(),error_type:p.literal("schematic_port_not_found").default("schematic_port_not_found"),message:p.string(),subcircuit_id:p.string().optional()}).describe("Defines a schematic error on the schematic");mt(!0);d9=p.object({type:p.literal("schematic_layout_error"),schematic_layout_error_id:kt("schematic_layout_error"),error_type:p.literal("schematic_layout_error").default("schematic_layout_error"),message:p.string(),source_group_id:p.string(),schematic_group_id:p.string(),subcircuit_id:p.string().optional()}).describe("Error emitted when schematic layout fails for a group");mt(!0);C_=p.object({type:p.literal("schematic_debug_object"),label:p.string().optional(),subcircuit_id:p.string().optional()}),f9=C_.extend({shape:p.literal("rect"),center:qt,size:xS}),m9=C_.extend({shape:p.literal("line"),start:qt,end:qt}),_9=C_.extend({shape:p.literal("point"),center:qt}),y9=p.discriminatedUnion("shape",[f9,m9,_9]);mt(!0);g9=p.object({type:p.literal("schematic_voltage_probe"),schematic_voltage_probe_id:p.string(),position:qt,schematic_trace_id:p.string(),voltage:ai.optional(),subcircuit_id:p.string().optional()}).describe("Defines a voltage probe measurement point on a schematic trace");mt(!0);E_=p.object({type:p.literal("schematic_manual_edit_conflict_warning"),schematic_manual_edit_conflict_warning_id:kt("schematic_manual_edit_conflict_warning"),warning_type:p.literal("schematic_manual_edit_conflict_warning").default("schematic_manual_edit_conflict_warning"),message:p.string(),schematic_component_id:p.string(),schematic_group_id:p.string().optional(),subcircuit_id:p.string().optional(),source_component_id:p.string()}).describe("Warning emitted when a component has both manual placement and explicit schX/schY coordinates");mt(!0);b9=p.object({type:p.literal("schematic_group"),schematic_group_id:kt("schematic_group"),source_group_id:p.string(),is_subcircuit:p.boolean().optional(),subcircuit_id:p.string().optional(),width:D,height:D,center:qt,schematic_component_ids:p.array(p.string()),show_as_schematic_box:p.boolean().optional(),name:p.string().optional(),description:p.string().optional()}).describe("Defines a group of components on the schematic");mt(!0);x9=p.object({type:p.literal("schematic_table"),schematic_table_id:kt("schematic_table"),anchor_position:qt,column_widths:p.array(Y),row_heights:p.array(Y),cell_padding:Y.optional(),border_width:Y.optional(),subcircuit_id:p.string().optional(),schematic_component_id:p.string().optional(),anchor:Wd.optional()}).describe("Defines a table on the schematic");mt(!0);v9=p.object({type:p.literal("schematic_table_cell"),schematic_table_cell_id:kt("schematic_table_cell"),schematic_table_id:p.string(),start_row_index:p.number(),end_row_index:p.number(),start_column_index:p.number(),end_column_index:p.number(),text:p.string().optional(),center:qt,width:Y,height:Y,horizontal_align:p.enum(["left","center","right"]).optional(),vertical_align:p.enum(["top","middle","bottom"]).optional(),font_size:Y.optional(),subcircuit_id:p.string().optional()}).describe("Defines a cell within a schematic_table");mt(!0);S9=p.object({type:p.literal("schematic_sheet"),schematic_sheet_id:kt("schematic_sheet"),name:p.string().optional(),subcircuit_id:p.string().optional()}).describe("Defines a schematic sheet or page that components can be placed on");mt(!0);w9=p.object({x:Y,y:Y,bulge:p.number().optional()});mt(!0);bS=p.object({vertices:p.array(w9)});mt(!0);P9=p.object({outer_ring:bS,inner_rings:p.array(bS).default([])});mt(!0);I9=p.object({x:Y,y:Y,via:p.boolean().optional(),via_to_layer:se.optional()}),_tt=p.array(I9);mt(!0);mt(!0);Fi=p.object({x:Y,y:Y,via:p.boolean().optional(),to_layer:se.optional(),trace_width:Y.optional()});mt(!0);T9=p.object({type:p.literal("pcb_component"),pcb_component_id:kt("pcb_component"),source_component_id:p.string(),center:qt,layer:se,rotation:Be,width:D,height:D,do_not_place:p.boolean().optional(),subcircuit_id:p.string().optional(),pcb_group_id:p.string().optional(),position_mode:p.enum(["packed","relative_to_group_anchor","none"]).optional(),positioned_relative_to_pcb_group_id:p.string().optional(),obstructs_within_bounds:p.boolean().default(!0).describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath")}).describe("Defines a component on the PCB");mt(!0);M9=p.object({type:p.literal("pcb_hole"),pcb_hole_id:kt("pcb_hole"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("circle"),hole_diameter:p.number(),x:Y,y:Y}),ytt=M9.describe("Defines a circular hole on the PCB");mt(!0);C9=p.object({type:p.literal("pcb_hole"),pcb_hole_id:kt("pcb_hole"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("rect"),hole_width:p.number(),hole_height:p.number(),x:Y,y:Y}),gtt=C9.describe("Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.");mt(!0);E9=p.object({type:p.literal("pcb_hole"),pcb_hole_id:kt("pcb_hole"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.enum(["circle","square"]),hole_diameter:p.number(),x:Y,y:Y}),btt=E9.describe("Defines a circular or square hole on the PCB");mt(!0);N9=p.object({type:p.literal("pcb_hole"),pcb_hole_id:kt("pcb_hole"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("oval"),hole_width:p.number(),hole_height:p.number(),x:Y,y:Y}),xtt=N9.describe("Defines an oval hole on the PCB");mt(!0);k9=p.object({type:p.literal("pcb_hole"),pcb_hole_id:kt("pcb_hole"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("pill"),hole_width:p.number(),hole_height:p.number(),x:Y,y:Y}),vtt=k9.describe("Defines a pill-shaped hole on the PCB");mt(!0);A9=p.object({type:p.literal("pcb_hole"),pcb_hole_id:kt("pcb_hole"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("rotated_pill"),hole_width:p.number(),hole_height:p.number(),x:Y,y:Y,ccw_rotation:Be}),Stt=A9.describe("Defines a rotated pill-shaped hole on the PCB");mt(!0);R9=E9.or(N9).or(k9).or(A9).or(M9).or(C9),wtt=p.object({type:p.literal("pcb_plated_hole"),shape:p.literal("circle"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),outer_diameter:p.number(),hole_diameter:p.number(),x:Y,y:Y,layers:p.array(se),port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),pcb_plated_hole_id:kt("pcb_plated_hole")}),Ptt=p.object({type:p.literal("pcb_plated_hole"),shape:p.enum(["oval","pill"]),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),outer_width:p.number(),outer_height:p.number(),hole_width:p.number(),hole_height:p.number(),x:Y,y:Y,ccw_rotation:Be,layers:p.array(se),port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),pcb_plated_hole_id:kt("pcb_plated_hole")}),Itt=p.object({type:p.literal("pcb_plated_hole"),shape:p.literal("circular_hole_with_rect_pad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("circle"),pad_shape:p.literal("rect"),hole_diameter:p.number(),rect_pad_width:p.number(),rect_pad_height:p.number(),rect_border_radius:p.number().optional(),hole_offset_x:Y.default(0),hole_offset_y:Y.default(0),x:Y,y:Y,layers:p.array(se),port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),pcb_plated_hole_id:kt("pcb_plated_hole")}),Ttt=p.object({type:p.literal("pcb_plated_hole"),shape:p.literal("pill_hole_with_rect_pad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("pill"),pad_shape:p.literal("rect"),hole_width:p.number(),hole_height:p.number(),rect_pad_width:p.number(),rect_pad_height:p.number(),rect_border_radius:p.number().optional(),hole_offset_x:Y.default(0),hole_offset_y:Y.default(0),x:Y,y:Y,layers:p.array(se),port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),pcb_plated_hole_id:kt("pcb_plated_hole")}),Mtt=p.object({type:p.literal("pcb_plated_hole"),shape:p.literal("rotated_pill_hole_with_rect_pad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("rotated_pill"),pad_shape:p.literal("rect"),hole_width:p.number(),hole_height:p.number(),hole_ccw_rotation:Be,rect_pad_width:p.number(),rect_pad_height:p.number(),rect_border_radius:p.number().optional(),rect_ccw_rotation:Be,hole_offset_x:Y.default(0),hole_offset_y:Y.default(0),x:Y,y:Y,layers:p.array(se),port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),pcb_plated_hole_id:kt("pcb_plated_hole")}),O9=p.union([wtt,Ptt,Itt,Ttt,Mtt]);mt(!0);mt(!0);mt(!0);mt(!0);mt(!0);L9=p.object({type:p.literal("pcb_port"),pcb_port_id:kt("pcb_port"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),source_port_id:p.string(),pcb_component_id:p.string().optional(),x:Y,y:Y,layers:p.array(se),is_board_pinout:p.boolean().optional()}).describe("Defines a port on the PCB");mt(!0);Ctt=p.object({type:p.literal("pcb_smtpad"),shape:p.literal("circle"),pcb_smtpad_id:kt("pcb_smtpad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,radius:p.number(),layer:se,port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),is_covered_with_solder_mask:p.boolean().optional()}),Ett=p.object({type:p.literal("pcb_smtpad"),shape:p.literal("rect"),pcb_smtpad_id:kt("pcb_smtpad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),rect_border_radius:p.number().optional(),corner_radius:p.number().optional(),layer:se,port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),is_covered_with_solder_mask:p.boolean().optional()}),Ntt=p.object({type:p.literal("pcb_smtpad"),shape:p.literal("rotated_rect"),pcb_smtpad_id:kt("pcb_smtpad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),rect_border_radius:p.number().optional(),corner_radius:p.number().optional(),ccw_rotation:Be,layer:se,port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),is_covered_with_solder_mask:p.boolean().optional()}),F9=p.object({type:p.literal("pcb_smtpad"),shape:p.literal("pill"),pcb_smtpad_id:kt("pcb_smtpad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),radius:p.number(),layer:se,port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),is_covered_with_solder_mask:p.boolean().optional()}),ktt=p.object({type:p.literal("pcb_smtpad"),shape:p.literal("rotated_pill"),pcb_smtpad_id:kt("pcb_smtpad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),radius:p.number(),ccw_rotation:Be,layer:se,port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),is_covered_with_solder_mask:p.boolean().optional()}),Att=p.object({type:p.literal("pcb_smtpad"),shape:p.literal("polygon"),pcb_smtpad_id:kt("pcb_smtpad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),points:p.array(qt),layer:se,port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),is_covered_with_solder_mask:p.boolean().optional()}),z9=p.discriminatedUnion("shape",[Ctt,Ett,Ntt,ktt,F9,Att]).describe("Defines an SMT pad on the PCB");mt(!0);mt(!0);mt(!0);mt(!0);mt(!0);mt(!0);Rtt=p.object({type:p.literal("pcb_solder_paste"),shape:p.literal("circle"),pcb_solder_paste_id:kt("pcb_solder_paste"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,radius:p.number(),layer:se,pcb_component_id:p.string().optional(),pcb_smtpad_id:p.string().optional()}),Ott=p.object({type:p.literal("pcb_solder_paste"),shape:p.literal("rect"),pcb_solder_paste_id:kt("pcb_solder_paste"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),layer:se,pcb_component_id:p.string().optional(),pcb_smtpad_id:p.string().optional()}),Ltt=p.object({type:p.literal("pcb_solder_paste"),shape:p.literal("pill"),pcb_solder_paste_id:kt("pcb_solder_paste"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),radius:p.number(),layer:se,pcb_component_id:p.string().optional(),pcb_smtpad_id:p.string().optional()}),Ftt=p.object({type:p.literal("pcb_solder_paste"),shape:p.literal("rotated_rect"),pcb_solder_paste_id:kt("pcb_solder_paste"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),ccw_rotation:Y,layer:se,pcb_component_id:p.string().optional(),pcb_smtpad_id:p.string().optional()}),ztt=p.object({type:p.literal("pcb_solder_paste"),shape:p.literal("oval"),pcb_solder_paste_id:kt("pcb_solder_paste"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),layer:se,pcb_component_id:p.string().optional(),pcb_smtpad_id:p.string().optional()}),D9=p.union([Rtt,Ott,Ltt,Ftt,ztt]).describe("Defines solderpaste on the PCB");mt(!0);mt(!0);mt(!0);mt(!0);mt(!0);$9=p.object({type:p.literal("pcb_text"),pcb_text_id:kt("pcb_text"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),text:p.string(),center:qt,layer:se,width:D,height:D,lines:p.number(),align:p.enum(["bottom-left"])}).describe("Defines text on the PCB");mt(!0);j9=p.object({route_type:p.literal("wire"),x:Y,y:Y,width:Y,start_pcb_port_id:p.string().optional(),end_pcb_port_id:p.string().optional(),layer:se}),B9=p.object({route_type:p.literal("via"),x:Y,y:Y,hole_diameter:Y.optional(),outer_diameter:Y.optional(),from_layer:p.string(),to_layer:p.string()}),N_=p.union([j9,B9]),Y9=p.object({type:p.literal("pcb_trace"),source_trace_id:p.string().optional(),pcb_component_id:p.string().optional(),pcb_trace_id:kt("pcb_trace"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),route_thickness_mode:p.enum(["constant","interpolated"]).default("constant").optional(),route_order_index:p.number().optional(),should_round_corners:p.boolean().optional(),trace_length:p.number().optional(),highlight_color:p.string().optional(),route:p.array(N_)}).describe("Defines a trace on the PCB");mt(!0);mt(!0);X9=p.object({type:p.literal("pcb_trace_error"),pcb_trace_error_id:kt("pcb_trace_error"),error_type:p.literal("pcb_trace_error").default("pcb_trace_error"),message:p.string(),center:qt.optional(),pcb_trace_id:p.string(),source_trace_id:p.string(),pcb_component_ids:p.array(p.string()),pcb_port_ids:p.array(p.string()),subcircuit_id:p.string().optional()}).describe("Defines a trace error on the PCB");mt(!0);V9=p.object({type:p.literal("pcb_trace_missing_error"),pcb_trace_missing_error_id:kt("pcb_trace_missing_error"),error_type:p.literal("pcb_trace_missing_error").default("pcb_trace_missing_error"),message:p.string(),center:qt.optional(),source_trace_id:p.string(),pcb_component_ids:p.array(p.string()),pcb_port_ids:p.array(p.string()),subcircuit_id:p.string().optional()}).describe("Defines an error when a source trace has no corresponding PCB trace");mt(!0);H9=p.object({type:p.literal("pcb_port_not_matched_error"),pcb_error_id:kt("pcb_error"),error_type:p.literal("pcb_port_not_matched_error").default("pcb_port_not_matched_error"),message:p.string(),pcb_component_ids:p.array(p.string()),subcircuit_id:p.string().optional()}).describe("Defines a trace error on the PCB where a port is not matched");mt(!0);G9=p.object({type:p.literal("pcb_port_not_connected_error"),pcb_port_not_connected_error_id:kt("pcb_port_not_connected_error"),error_type:p.literal("pcb_port_not_connected_error").default("pcb_port_not_connected_error"),message:p.string(),pcb_port_ids:p.array(p.string()),pcb_component_ids:p.array(p.string()),subcircuit_id:p.string().optional()}).describe("Defines an error when a pcb port is not connected to any trace");mt(!0);U9=p.object({type:p.literal("pcb_net"),pcb_net_id:kt("pcb_net"),source_net_id:p.string().optional(),highlight_color:p.string().optional()}).describe("Defines a net on the PCB");mt(!0);q9=p.object({type:p.literal("pcb_via"),pcb_via_id:kt("pcb_via"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,outer_diameter:Y.default("0.6mm"),hole_diameter:Y.default("0.25mm"),from_layer:se.optional(),to_layer:se.optional(),layers:p.array(se),pcb_trace_id:p.string().optional(),net_is_assignable:p.boolean().optional(),net_assigned:p.boolean().optional()}).describe("Defines a via on the PCB");mt(!0);W9=p.object({type:p.literal("pcb_board"),pcb_board_id:kt("pcb_board"),pcb_panel_id:p.string().optional(),is_subcircuit:p.boolean().optional(),subcircuit_id:p.string().optional(),width:D.optional(),height:D.optional(),center:qt,thickness:D.optional().default(1.4),num_layers:p.number().optional().default(4),outline:p.array(qt).optional(),shape:p.enum(["rect","polygon"]).optional(),material:p.enum(["fr4","fr1"]).default("fr4")}).describe("Defines the board outline of the PCB");mt(!0);Z9=p.object({type:p.literal("pcb_panel"),pcb_panel_id:kt("pcb_panel"),width:D,height:D,covered_with_solder_mask:p.boolean().optional().default(!0)}).describe("Defines a PCB panel that can contain multiple boards");mt(!0);K9=p.object({type:p.literal("pcb_placement_error"),pcb_placement_error_id:kt("pcb_placement_error"),error_type:p.literal("pcb_placement_error").default("pcb_placement_error"),message:p.string(),subcircuit_id:p.string().optional()}).describe("Defines a placement error on the PCB");mt(!0);J9=p.object({type:p.literal("pcb_trace_hint"),pcb_trace_hint_id:kt("pcb_trace_hint"),pcb_port_id:p.string(),pcb_component_id:p.string(),route:p.array(Fi),subcircuit_id:p.string().optional()}).describe("A hint that can be used during generation of a PCB trace");mt(!0);Q9=p.object({type:p.literal("pcb_silkscreen_line"),pcb_silkscreen_line_id:kt("pcb_silkscreen_line"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),stroke_width:Y.default("0.1mm"),x1:Y,y1:Y,x2:Y,y2:Y,layer:Nr}).describe("Defines a silkscreen line on the PCB");mt(!0);t6=p.object({type:p.literal("pcb_silkscreen_path"),pcb_silkscreen_path_id:kt("pcb_silkscreen_path"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),layer:Nr,route:p.array(qt),stroke_width:D}).describe("Defines a silkscreen path on the PCB");mt(!0);e6=p.object({type:p.literal("pcb_silkscreen_text"),pcb_silkscreen_text_id:kt("pcb_silkscreen_text"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),font:p.literal("tscircuit2024").default("tscircuit2024"),font_size:Y.default("0.2mm"),pcb_component_id:p.string(),text:p.string(),is_knockout:p.boolean().default(!1).optional(),knockout_padding:p.object({left:D,top:D,bottom:D,right:D}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:p.number().optional(),layer:se,is_mirrored:p.boolean().default(!1).optional(),anchor_position:qt.default({x:0,y:0}),anchor_alignment:Wd.default("center")}).describe("Defines silkscreen text on the PCB");mt(!0);n6=p.object({type:p.literal("pcb_copper_text"),pcb_copper_text_id:kt("pcb_copper_text"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),font:p.literal("tscircuit2024").default("tscircuit2024"),font_size:Y.default("0.2mm"),pcb_component_id:p.string(),text:p.string(),is_knockout:p.boolean().default(!1).optional(),knockout_padding:p.object({left:D,top:D,bottom:D,right:D}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:p.number().optional(),layer:se,is_mirrored:p.boolean().default(!1).optional(),anchor_position:qt.default({x:0,y:0}),anchor_alignment:Wd.default("center")}).describe("Defines copper text on the PCB");mt(!0);i6=p.object({type:p.literal("pcb_silkscreen_rect"),pcb_silkscreen_rect_id:kt("pcb_silkscreen_rect"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),center:qt,width:D,height:D,layer:se,stroke_width:D.default("1mm"),corner_radius:D.optional(),is_filled:p.boolean().default(!0).optional(),has_stroke:p.boolean().optional(),is_stroke_dashed:p.boolean().optional()}).describe("Defines a silkscreen rect on the PCB");mt(!0);o6=p.object({type:p.literal("pcb_silkscreen_circle"),pcb_silkscreen_circle_id:kt("pcb_silkscreen_circle"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),center:qt,radius:D,layer:Nr,stroke_width:D.default("1mm")}).describe("Defines a silkscreen circle on the PCB");mt(!0);r6=p.object({type:p.literal("pcb_silkscreen_oval"),pcb_silkscreen_oval_id:kt("pcb_silkscreen_oval"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),center:qt,radius_x:Y,radius_y:Y,layer:Nr}).describe("Defines a silkscreen oval on the PCB");mt(!0);s6=p.object({type:p.literal("pcb_fabrication_note_text"),pcb_fabrication_note_text_id:kt("pcb_fabrication_note_text"),subcircuit_id:p.string().optional(),pcb_group_id:p.string().optional(),font:p.literal("tscircuit2024").default("tscircuit2024"),font_size:Y.default("1mm"),pcb_component_id:p.string(),text:p.string(),layer:Nr,anchor_position:qt.default({x:0,y:0}),anchor_alignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),color:p.string().optional()}).describe("Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators");mt(!0);a6=p.object({type:p.literal("pcb_fabrication_note_path"),pcb_fabrication_note_path_id:kt("pcb_fabrication_note_path"),pcb_component_id:p.string(),subcircuit_id:p.string().optional(),layer:se,route:p.array(qt),stroke_width:D,color:p.string().optional()}).describe("Defines a fabrication path on the PCB for fabricators or assemblers");mt(!0);c6=p.object({type:p.literal("pcb_fabrication_note_rect"),pcb_fabrication_note_rect_id:kt("pcb_fabrication_note_rect"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),center:qt,width:D,height:D,layer:Nr,stroke_width:D.default("0.1mm"),corner_radius:D.optional(),is_filled:p.boolean().optional(),has_stroke:p.boolean().optional(),is_stroke_dashed:p.boolean().optional(),color:p.string().optional()}).describe("Defines a fabrication note rectangle on the PCB");mt(!0);l6=p.object({type:p.literal("pcb_fabrication_note_dimension"),pcb_fabrication_note_dimension_id:kt("pcb_fabrication_note_dimension"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),layer:Nr,from:qt,to:qt,text:p.string().optional(),text_ccw_rotation:p.number().optional(),offset:D.optional(),offset_distance:D.optional(),offset_direction:p.object({x:p.number(),y:p.number()}).optional(),font:p.literal("tscircuit2024").default("tscircuit2024"),font_size:D.default("1mm"),color:p.string().optional(),arrow_size:D.default("1mm")}).describe("Defines a measurement annotation within PCB fabrication notes");mt(!0);u6=p.object({type:p.literal("pcb_note_text"),pcb_note_text_id:kt("pcb_note_text"),pcb_component_id:p.string().optional(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),name:p.string().optional(),font:p.literal("tscircuit2024").default("tscircuit2024"),font_size:Y.default("1mm"),text:p.string().optional(),anchor_position:qt.default({x:0,y:0}),anchor_alignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),color:p.string().optional()}).describe("Defines a documentation note in text on the PCB");mt(!0);p6=p.object({type:p.literal("pcb_note_rect"),pcb_note_rect_id:kt("pcb_note_rect"),pcb_component_id:p.string().optional(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),name:p.string().optional(),text:p.string().optional(),center:qt,width:D,height:D,stroke_width:D.default("0.1mm"),corner_radius:D.optional(),is_filled:p.boolean().optional(),has_stroke:p.boolean().optional(),is_stroke_dashed:p.boolean().optional(),color:p.string().optional()}).describe("Defines a rectangular documentation note on the PCB");mt(!0);h6=p.object({type:p.literal("pcb_note_path"),pcb_note_path_id:kt("pcb_note_path"),pcb_component_id:p.string().optional(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),name:p.string().optional(),text:p.string().optional(),route:p.array(qt),stroke_width:D.default("0.1mm"),color:p.string().optional()}).describe("Defines a polyline documentation note on the PCB");mt(!0);d6=p.object({type:p.literal("pcb_note_line"),pcb_note_line_id:kt("pcb_note_line"),pcb_component_id:p.string().optional(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),name:p.string().optional(),text:p.string().optional(),x1:Y,y1:Y,x2:Y,y2:Y,stroke_width:Y.default("0.1mm"),color:p.string().optional(),is_dashed:p.boolean().optional()}).describe("Defines a straight documentation note line on the PCB");mt(!0);f6=p.object({type:p.literal("pcb_note_dimension"),pcb_note_dimension_id:kt("pcb_note_dimension"),pcb_component_id:p.string().optional(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),name:p.string().optional(),from:qt,to:qt,text:p.string().optional(),text_ccw_rotation:p.number().optional(),offset_distance:D.optional(),offset_direction:p.object({x:p.number(),y:p.number()}).optional(),font:p.literal("tscircuit2024").default("tscircuit2024"),font_size:D.default("1mm"),color:p.string().optional(),arrow_size:D.default("1mm")}).describe("Defines a measurement annotation within PCB documentation notes");mt(!0);m6=p.object({type:p.literal("pcb_footprint_overlap_error"),pcb_error_id:kt("pcb_error"),error_type:p.literal("pcb_footprint_overlap_error").default("pcb_footprint_overlap_error"),message:p.string(),pcb_smtpad_ids:p.array(p.string()).optional(),pcb_plated_hole_ids:p.array(p.string()).optional(),pcb_hole_ids:p.array(p.string()).optional(),pcb_keepout_ids:p.array(p.string()).optional()}).describe("Error emitted when a pcb footprint overlaps with another element");mt(!0);_6=p.object({type:p.literal("pcb_keepout"),shape:p.literal("rect"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),center:qt,width:Y,height:Y,pcb_keepout_id:p.string(),layers:p.array(p.string()),description:p.string().optional()}).or(p.object({type:p.literal("pcb_keepout"),shape:p.literal("circle"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),center:qt,radius:Y,pcb_keepout_id:p.string(),layers:p.array(p.string()),description:p.string().optional()}));mt(!0);jS=p.object({type:p.literal("pcb_cutout"),pcb_cutout_id:kt("pcb_cutout"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional()}),y6=jS.extend({shape:p.literal("rect"),center:qt,width:D,height:D,rotation:Be.optional()});mt(!0);g6=jS.extend({shape:p.literal("circle"),center:qt,radius:D});mt(!0);b6=jS.extend({shape:p.literal("polygon"),points:p.array(qt)});mt(!0);x6=p.discriminatedUnion("shape",[y6,g6,b6]).describe("Defines a cutout on the PCB, removing board material.");mt(!0);v6=p.object({type:p.literal("pcb_missing_footprint_error"),pcb_missing_footprint_error_id:kt("pcb_missing_footprint_error"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),error_type:p.literal("pcb_missing_footprint_error").default("pcb_missing_footprint_error"),source_component_id:p.string(),message:p.string()}).describe("Defines a missing footprint error on the PCB");mt(!0);Ep=p.object({type:p.literal("external_footprint_load_error"),external_footprint_load_error_id:kt("external_footprint_load_error"),pcb_component_id:p.string(),source_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),footprinter_string:p.string().optional(),error_type:p.literal("external_footprint_load_error").default("external_footprint_load_error"),message:p.string()}).describe("Defines an error when an external footprint fails to load");mt(!0);k_=p.object({type:p.literal("circuit_json_footprint_load_error"),circuit_json_footprint_load_error_id:kt("circuit_json_footprint_load_error"),pcb_component_id:p.string(),source_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),error_type:p.literal("circuit_json_footprint_load_error").default("circuit_json_footprint_load_error"),message:p.string(),circuit_json:p.array(p.any()).optional()}).describe("Defines an error when a circuit JSON footprint fails to load");mt(!0);S6=p.object({type:p.literal("pcb_group"),pcb_group_id:kt("pcb_group"),source_group_id:p.string(),is_subcircuit:p.boolean().optional(),subcircuit_id:p.string().optional(),width:D.optional(),height:D.optional(),center:qt,outline:p.array(qt).optional(),anchor_position:qt.optional(),anchor_alignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).optional(),pcb_component_ids:p.array(p.string()),child_layout_mode:p.enum(["packed","none"]).optional(),name:p.string().optional(),description:p.string().optional(),layout_mode:p.string().optional(),autorouter_configuration:p.object({trace_clearance:D}).optional(),autorouter_used_string:p.string().optional()}).describe("Defines a group of components on the PCB");mt(!0);w6=p.object({type:p.literal("pcb_autorouting_error"),pcb_error_id:kt("pcb_autorouting_error"),error_type:p.literal("pcb_autorouting_error").default("pcb_autorouting_error"),message:p.string(),subcircuit_id:p.string().optional()}).describe("The autorouting has failed to route a portion of the board");mt(!0);A_=p.object({type:p.literal("pcb_manual_edit_conflict_warning"),pcb_manual_edit_conflict_warning_id:kt("pcb_manual_edit_conflict_warning"),warning_type:p.literal("pcb_manual_edit_conflict_warning").default("pcb_manual_edit_conflict_warning"),message:p.string(),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),source_component_id:p.string()}).describe("Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates");mt(!0);P6=p.object({type:p.literal("pcb_breakout_point"),pcb_breakout_point_id:kt("pcb_breakout_point"),pcb_group_id:p.string(),subcircuit_id:p.string().optional(),source_trace_id:p.string().optional(),source_port_id:p.string().optional(),source_net_id:p.string().optional(),x:Y,y:Y}).describe("Defines a routing target within a pcb_group for a source_trace or source_net");mt(!0);I6=p.object({type:p.literal("pcb_ground_plane"),pcb_ground_plane_id:kt("pcb_ground_plane"),source_pcb_ground_plane_id:p.string(),source_net_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional()}).describe("Defines a ground plane on the PCB");mt(!0);T6=p.object({type:p.literal("pcb_ground_plane_region"),pcb_ground_plane_region_id:kt("pcb_ground_plane_region"),pcb_ground_plane_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),layer:se,points:p.array(qt)}).describe("Defines a polygon region of a ground plane");mt(!0);M6=p.object({type:p.literal("pcb_thermal_spoke"),pcb_thermal_spoke_id:kt("pcb_thermal_spoke"),pcb_ground_plane_id:p.string(),shape:p.string(),spoke_count:p.number(),spoke_thickness:Y,spoke_inner_diameter:Y,spoke_outer_diameter:Y,pcb_plated_hole_id:p.string().optional(),subcircuit_id:p.string().optional()}).describe("Pattern for connecting a ground plane to a plated hole");mt(!0);BS=p.object({type:p.literal("pcb_copper_pour"),pcb_copper_pour_id:kt("pcb_copper_pour"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),layer:se,source_net_id:p.string().optional(),covered_with_solder_mask:p.boolean().optional().default(!0)}),C6=BS.extend({shape:p.literal("rect"),center:qt,width:D,height:D,rotation:Be.optional()});mt(!0);E6=BS.extend({shape:p.literal("brep"),brep_shape:P9});mt(!0);N6=BS.extend({shape:p.literal("polygon"),points:p.array(qt)});mt(!0);k6=p.discriminatedUnion("shape",[C6,E6,N6]).describe("Defines a copper pour on the PCB.");mt(!0);A6=p.object({type:p.literal("pcb_component_outside_board_error"),pcb_component_outside_board_error_id:kt("pcb_component_outside_board_error"),error_type:p.literal("pcb_component_outside_board_error").default("pcb_component_outside_board_error"),message:p.string(),pcb_component_id:p.string(),pcb_board_id:p.string(),component_center:qt,component_bounds:p.object({min_x:p.number(),max_x:p.number(),min_y:p.number(),max_y:p.number()}),subcircuit_id:p.string().optional(),source_component_id:p.string().optional()}).describe("Error emitted when a PCB component is placed outside the board boundaries");mt(!0);Np=p.object({type:p.literal("pcb_component_invalid_layer_error"),pcb_component_invalid_layer_error_id:kt("pcb_component_invalid_layer_error"),error_type:p.literal("pcb_component_invalid_layer_error").default("pcb_component_invalid_layer_error"),message:p.string(),pcb_component_id:p.string().optional(),source_component_id:p.string(),layer:se,subcircuit_id:p.string().optional()}).describe("Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)");mt(!0);R6=p.object({type:p.literal("pcb_via_clearance_error"),pcb_error_id:kt("pcb_error"),error_type:p.literal("pcb_via_clearance_error").default("pcb_via_clearance_error"),message:p.string(),pcb_via_ids:p.array(p.string()).min(2),minimum_clearance:Y.optional(),actual_clearance:Y.optional(),pcb_center:p.object({x:p.number().optional(),y:p.number().optional()}).optional(),subcircuit_id:p.string().optional()}).describe("Error emitted when vias are closer than the allowed clearance");mt(!0);O6=p.object({type:p.literal("pcb_courtyard_rect"),pcb_courtyard_rect_id:kt("pcb_courtyard_rect"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),center:qt,width:D,height:D,layer:Nr,color:p.string().optional()}).describe("Defines a courtyard rectangle on the PCB");mt(!0);L6=p.object({type:p.literal("pcb_courtyard_outline"),pcb_courtyard_outline_id:kt("pcb_courtyard_outline"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),layer:Nr,outline:p.array(qt).min(2),stroke_width:D.default("0.1mm"),is_closed:p.boolean().optional(),is_stroke_dashed:p.boolean().optional(),color:p.string().optional()}).describe("Defines a courtyard outline on the PCB");mt(!0);F6=p.object({type:p.literal("pcb_courtyard_polygon"),pcb_courtyard_polygon_id:kt("pcb_courtyard_polygon"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),layer:Nr,points:p.array(qt).min(3),color:p.string().optional()}).describe("Defines a courtyard polygon on the PCB");mt(!0);z6=p.object({type:p.literal("cad_component"),cad_component_id:p.string(),pcb_component_id:p.string(),source_component_id:p.string(),position:vl,rotation:vl.optional(),size:vl.optional(),layer:se.optional(),subcircuit_id:p.string().optional(),footprinter_string:p.string().optional(),model_obj_url:p.string().optional(),model_stl_url:p.string().optional(),model_3mf_url:p.string().optional(),model_gltf_url:p.string().optional(),model_glb_url:p.string().optional(),model_step_url:p.string().optional(),model_wrl_url:p.string().optional(),model_unit_to_mm_scale_factor:p.number().optional(),model_jscad:p.any().optional()}).describe("Defines a component on the PCB");mt(!0);D6=p.enum(["sinewave","square","triangle","sawtooth"]),Dtt=p.union([p.string(),p.number()]).transform(e=>typeof e=="string"?e.endsWith("%")?parseFloat(e.slice(0,-1))/100:parseFloat(e):e).pipe(p.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),$6=p.object({type:p.literal("simulation_voltage_source"),simulation_voltage_source_id:kt("simulation_voltage_source"),is_dc_source:p.literal(!0).optional().default(!0),positive_source_port_id:p.string().optional(),negative_source_port_id:p.string().optional(),positive_source_net_id:p.string().optional(),negative_source_net_id:p.string().optional(),voltage:ai}).describe("Defines a DC voltage source for simulation"),j6=p.object({type:p.literal("simulation_voltage_source"),simulation_voltage_source_id:kt("simulation_voltage_source"),is_dc_source:p.literal(!1),terminal1_source_port_id:p.string().optional(),terminal2_source_port_id:p.string().optional(),terminal1_source_net_id:p.string().optional(),terminal2_source_net_id:p.string().optional(),voltage:ai.optional(),frequency:Wi.optional(),peak_to_peak_voltage:ai.optional(),wave_shape:D6.optional(),phase:Be.optional(),duty_cycle:Dtt.optional()}).describe("Defines an AC voltage source for simulation"),B6=p.union([$6,j6]).describe("Defines a voltage source for simulation");mt(!0);mt(!0);mt(!0);Y6=p.union([p.literal("spice_dc_sweep"),p.literal("spice_dc_operating_point"),p.literal("spice_transient_analysis"),p.literal("spice_ac_analysis")]),X6=p.object({type:p.literal("simulation_experiment"),simulation_experiment_id:kt("simulation_experiment"),name:p.string(),experiment_type:Y6,time_per_step:qd.optional(),start_time_ms:qi.optional(),end_time_ms:qi.optional()}).describe("Defines a simulation experiment configuration");mt(!0);V6=p.object({type:p.literal("simulation_transient_voltage_graph"),simulation_transient_voltage_graph_id:kt("simulation_transient_voltage_graph"),simulation_experiment_id:p.string(),timestamps_ms:p.array(p.number()).optional(),voltage_levels:p.array(p.number()),schematic_voltage_probe_id:p.string().optional(),simulation_voltage_probe_id:p.string().optional(),subcircuit_connectivity_map_key:p.string().optional(),time_per_step:qd,start_time_ms:qi,end_time_ms:qi,name:p.string().optional()}).describe("Stores voltage measurements over time for a simulation");mt(!0);H6=p.object({type:p.literal("simulation_switch"),simulation_switch_id:kt("simulation_switch"),source_component_id:p.string().optional(),closes_at:qi.optional(),opens_at:qi.optional(),starts_closed:p.boolean().optional(),switching_frequency:Wi.optional()}).describe("Defines a switch for simulation timing control");mt(!0);G6=p.object({type:p.literal("simulation_voltage_probe"),simulation_voltage_probe_id:kt("simulation_voltage_probe"),source_port_id:p.string().optional(),source_net_id:p.string().optional(),name:p.string().optional(),subcircuit_id:p.string().optional()}).describe("Defines a voltage probe for simulation, connected to a port or a net").refine(e=>!!e.source_port_id!=!!e.source_net_id,{message:"Exactly one of source_port_id or source_net_id must be provided to simulation_voltage_probe"});mt(!0);U6=p.object({type:p.literal("simulation_unknown_experiment_error"),simulation_unknown_experiment_error_id:kt("simulation_unknown_experiment_error"),error_type:p.literal("simulation_unknown_experiment_error").default("simulation_unknown_experiment_error"),message:p.string(),simulation_experiment_id:p.string().optional(),subcircuit_id:p.string().optional()}).describe("An unknown error occurred during the simulation experiment.");mt(!0);q6=p.union([HA,VA,XA,UA,GA,PS,vS,T_,wS,SS,IS,TS,MS,NS,kS,AS,FS,RS,OS,LS,ES,CS,WA,ZA,qA,zS,DS,$S,M_,T9,R9,v6,Ep,k_,A_,O9,_6,L9,U9,$9,Y9,q9,z9,D9,W9,Z9,S6,J9,Q9,t6,e6,n6,i6,o6,r6,X9,V9,K9,H9,G9,R6,a6,s6,c6,l6,u6,p6,h6,d6,f6,w6,m6,P6,x6,I6,T6,M6,k6,A6,Np,O6,L6,F6,KA,l9,o9,r9,s9,a9,i9,u9,c9,JA,h9,d9,p9,y9,g9,E_,b9,S9,x9,v9,z6,B6,X6,V6,H6,G6,U6]),wl=q6;mt(!0);Sl(!0)});var b8=oe((uOt,g8)=>{"use strict";var Ap=1e3,Rp=Ap*60,Op=Rp*60,Ml=Op*24,rrt=Ml*7,srt=Ml*365.25;g8.exports=function(e,t){t=t||{};var n=typeof e;if(n==="string"&&e.length>0)return art(e);if(n==="number"&&isFinite(e))return t.long?lrt(e):crt(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function art(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),i=(t[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return n*srt;case"weeks":case"week":case"w":return n*rrt;case"days":case"day":case"d":return n*Ml;case"hours":case"hour":case"hrs":case"hr":case"h":return n*Op;case"minutes":case"minute":case"mins":case"min":case"m":return n*Rp;case"seconds":case"second":case"secs":case"sec":case"s":return n*Ap;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function crt(e){var t=Math.abs(e);return t>=Ml?Math.round(e/Ml)+"d":t>=Op?Math.round(e/Op)+"h":t>=Rp?Math.round(e/Rp)+"m":t>=Ap?Math.round(e/Ap)+"s":e+"ms"}function lrt(e){var t=Math.abs(e);return t>=Ml?Y_(e,t,Ml,"day"):t>=Op?Y_(e,t,Op,"hour"):t>=Rp?Y_(e,t,Rp,"minute"):t>=Ap?Y_(e,t,Ap,"second"):e+" ms"}function Y_(e,t,n,i){var o=t>=n*1.5;return Math.round(e/n)+" "+i+(o?"s":"")}});var v8=oe((pOt,x8)=>{"use strict";function urt(e){n.debug=n,n.default=n,n.coerce=c,n.disable=s,n.enable=o,n.enabled=a,n.humanize=b8(),n.destroy=l,Object.keys(e).forEach(u=>{n[u]=e[u]}),n.names=[],n.skips=[],n.formatters={};function t(u){let h=0;for(let d=0;d<u.length;d++)h=(h<<5)-h+u.charCodeAt(d),h|=0;return n.colors[Math.abs(h)%n.colors.length]}n.selectColor=t;function n(u){let h,d=null,_,y;function g(...x){if(!g.enabled)return;let w=g,S=Number(new Date),T=S-(h||S);w.diff=T,w.prev=h,w.curr=S,h=S,x[0]=n.coerce(x[0]),typeof x[0]!="string"&&x.unshift("%O");let I=0;x[0]=x[0].replace(/%([a-zA-Z%])/g,(M,k)=>{if(M==="%%")return"%";I++;let N=n.formatters[k];if(typeof N=="function"){let A=x[I];M=N.call(w,A),x.splice(I,1),I--}return M}),n.formatArgs.call(w,x),(w.log||n.log).apply(w,x)}return g.namespace=u,g.useColors=n.useColors(),g.color=n.selectColor(u),g.extend=i,g.destroy=n.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(_!==n.namespaces&&(_=n.namespaces,y=n.enabled(u)),y),set:x=>{d=x}}),typeof n.init=="function"&&n.init(g),g}function i(u,h){let d=n(this.namespace+(typeof h>"u"?":":h)+u);return d.log=this.log,d}function o(u){n.save(u),n.namespaces=u,n.names=[],n.skips=[];let h=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let d of h)d[0]==="-"?n.skips.push(d.slice(1)):n.names.push(d)}function r(u,h){let d=0,_=0,y=-1,g=0;for(;d<u.length;)if(_<h.length&&(h[_]===u[d]||h[_]==="*"))h[_]==="*"?(y=_,g=d,_++):(d++,_++);else if(y!==-1)_=y+1,g++,d=g;else return!1;for(;_<h.length&&h[_]==="*";)_++;return _===h.length}function s(){let u=[...n.names,...n.skips.map(h=>"-"+h)].join(",");return n.enable(""),u}function a(u){for(let h of n.skips)if(r(u,h))return!1;for(let h of n.names)if(r(u,h))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){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 n.enable(n.load()),n}x8.exports=urt});var Sn=oe((vo,X_)=>{"use strict";vo.formatArgs=hrt;vo.save=drt;vo.load=frt;vo.useColors=prt;vo.storage=mrt();vo.destroy=(()=>{let e=!1;return()=>{e||(e=!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`."))}})();vo.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 prt(){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 e;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&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function hrt(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+X_.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;e.splice(1,0,t,"color: inherit");let n=0,i=0;e[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(i=n))}),e.splice(i,0,t)}vo.log=console.debug||console.log||(()=>{});function drt(e){try{e?vo.storage.setItem("debug",e):vo.storage.removeItem("debug")}catch{}}function frt(){let e;try{e=vo.storage.getItem("debug")||vo.storage.getItem("DEBUG")}catch{}return!e&&typeof process<"u"&&"env"in process&&(e=process.env.DEBUG),e}function mrt(){try{return localStorage}catch{}}X_.exports=v8()(vo);var{formatters:_rt}=X_.exports;_rt.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var k8=oe(An=>{"use strict";function KS(e,t){var n=e.length;e.push(t);t:for(;0<n;){var i=n-1>>>1,o=e[i];if(0<V_(o,t))e[i]=t,e[n]=o,n=i;else break t}}function Jr(e){return e.length===0?null:e[0]}function G_(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;t:for(var i=0,o=e.length,r=o>>>1;i<r;){var s=2*(i+1)-1,a=e[s],c=s+1,l=e[c];if(0>V_(a,n))c<o&&0>V_(l,a)?(e[i]=l,e[c]=n,i=c):(e[i]=a,e[s]=n,i=s);else if(c<o&&0>V_(l,n))e[i]=l,e[c]=n,i=c;else break t}}return t}function V_(e,t){var n=e.sortIndex-t.sortIndex;return n!==0?n:e.id-t.id}An.unstable_now=void 0;typeof performance=="object"&&typeof performance.now=="function"?(S8=performance,An.unstable_now=function(){return S8.now()}):(qS=Date,w8=qS.now(),An.unstable_now=function(){return qS.now()-w8});var S8,qS,w8,Bs=[],qa=[],yrt=1,ar=null,Zi=3,JS=!1,Kd=!1,Jd=!1,QS=!1,T8=typeof setTimeout=="function"?setTimeout:null,M8=typeof clearTimeout=="function"?clearTimeout:null,P8=typeof setImmediate<"u"?setImmediate:null;function H_(e){for(var t=Jr(qa);t!==null;){if(t.callback===null)G_(qa);else if(t.startTime<=e)G_(qa),t.sortIndex=t.expirationTime,KS(Bs,t);else break;t=Jr(qa)}}function tw(e){if(Jd=!1,H_(e),!Kd)if(Jr(Bs)!==null)Kd=!0,Fp||(Fp=!0,Lp());else{var t=Jr(qa);t!==null&&ew(tw,t.startTime-e)}}var Fp=!1,Qd=-1,C8=5,E8=-1;function N8(){return QS?!0:!(An.unstable_now()-E8<C8)}function WS(){if(QS=!1,Fp){var e=An.unstable_now();E8=e;var t=!0;try{t:{Kd=!1,Jd&&(Jd=!1,M8(Qd),Qd=-1),JS=!0;var n=Zi;try{e:{for(H_(e),ar=Jr(Bs);ar!==null&&!(ar.expirationTime>e&&N8());){var i=ar.callback;if(typeof i=="function"){ar.callback=null,Zi=ar.priorityLevel;var o=i(ar.expirationTime<=e);if(e=An.unstable_now(),typeof o=="function"){ar.callback=o,H_(e),t=!0;break e}ar===Jr(Bs)&&G_(Bs),H_(e)}else G_(Bs);ar=Jr(Bs)}if(ar!==null)t=!0;else{var r=Jr(qa);r!==null&&ew(tw,r.startTime-e),t=!1}}break t}finally{ar=null,Zi=n,JS=!1}t=void 0}}finally{t?Lp():Fp=!1}}}var Lp;typeof P8=="function"?Lp=function(){P8(WS)}:typeof MessageChannel<"u"?(ZS=new MessageChannel,I8=ZS.port2,ZS.port1.onmessage=WS,Lp=function(){I8.postMessage(null)}):Lp=function(){T8(WS,0)};var ZS,I8;function ew(e,t){Qd=T8(function(){e(An.unstable_now())},t)}An.unstable_IdlePriority=5;An.unstable_ImmediatePriority=1;An.unstable_LowPriority=4;An.unstable_NormalPriority=3;An.unstable_Profiling=null;An.unstable_UserBlockingPriority=2;An.unstable_cancelCallback=function(e){e.callback=null};An.unstable_forceFrameRate=function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):C8=0<e?Math.floor(1e3/e):5};An.unstable_getCurrentPriorityLevel=function(){return Zi};An.unstable_next=function(e){switch(Zi){case 1:case 2:case 3:var t=3;break;default:t=Zi}var n=Zi;Zi=t;try{return e()}finally{Zi=n}};An.unstable_requestPaint=function(){QS=!0};An.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=Zi;Zi=e;try{return t()}finally{Zi=n}};An.unstable_scheduleCallback=function(e,t,n){var i=An.unstable_now();switch(typeof n=="object"&&n!==null?(n=n.delay,n=typeof n=="number"&&0<n?i+n:i):n=i,e){case 1:var o=-1;break;case 2:o=250;break;case 5:o=1073741823;break;case 4:o=1e4;break;default:o=5e3}return o=n+o,e={id:yrt++,callback:t,priorityLevel:e,startTime:n,expirationTime:o,sortIndex:-1},n>i?(e.sortIndex=n,KS(qa,e),Jr(Bs)===null&&e===Jr(qa)&&(Jd?(M8(Qd),Qd=-1):Jd=!0,ew(tw,n-i))):(e.sortIndex=o,KS(Bs,e),Kd||JS||(Kd=!0,Fp||(Fp=!0,Lp()))),e};An.unstable_shouldYield=N8;An.unstable_wrapCallback=function(e){var t=Zi;return function(){var n=Zi;Zi=t;try{return e.apply(this,arguments)}finally{Zi=n}}}});var R8=oe((dOt,A8)=>{"use strict";A8.exports=k8()});var O8=oe((fOt,tf)=>{"use strict";tf.exports=function(e){function t(f,m,v,C){return new EZ(f,m,v,C)}function n(){}function i(f){var m="https://react.dev/errors/"+f;if(1<arguments.length){m+="?args[]="+encodeURIComponent(arguments[1]);for(var v=2;v<arguments.length;v++)m+="&args[]="+encodeURIComponent(arguments[v])}return"Minified React error #"+f+"; visit "+m+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function o(f){var m=f,v=f;if(f.alternate)for(;m.return;)m=m.return;else{f=m;do m=f,(m.flags&4098)!==0&&(v=m.return),f=m.return;while(f)}return m.tag===3?v:null}function r(f){if(o(f)!==f)throw Error(i(188))}function s(f){var m=f.alternate;if(!m){if(m=o(f),m===null)throw Error(i(188));return m!==f?null:f}for(var v=f,C=m;;){var O=v.return;if(O===null)break;var z=O.alternate;if(z===null){if(C=O.return,C!==null){v=C;continue}break}if(O.child===z.child){for(z=O.child;z;){if(z===v)return r(O),f;if(z===C)return r(O),m;z=z.sibling}throw Error(i(188))}if(v.return!==C.return)v=O,C=z;else{for(var Z=!1,st=O.child;st;){if(st===v){Z=!0,v=O,C=z;break}if(st===C){Z=!0,C=O,v=z;break}st=st.sibling}if(!Z){for(st=z.child;st;){if(st===v){Z=!0,v=z,C=O;break}if(st===C){Z=!0,C=z,v=O;break}st=st.sibling}if(!Z)throw Error(i(189))}}if(v.alternate!==C)throw Error(i(190))}if(v.tag!==3)throw Error(i(188));return v.stateNode.current===v?f:m}function a(f){var m=f.tag;if(m===5||m===26||m===27||m===6)return f;for(f=f.child;f!==null;){if(m=a(f),m!==null)return m;f=f.sibling}return null}function c(f){var m=f.tag;if(m===5||m===26||m===27||m===6)return f;for(f=f.child;f!==null;){if(f.tag!==4&&(m=c(f),m!==null))return m;f=f.sibling}return null}function l(f){return f===null||typeof f!="object"?null:(f=bk&&f[bk]||f["@@iterator"],typeof f=="function"?f:null)}function u(f){if(f==null)return null;if(typeof f=="function")return f.$$typeof===LZ?null:f.displayName||f.name||null;if(typeof f=="string")return f;switch(f){case Gu:return"Fragment";case Pv:return"Profiler";case yk:return"StrictMode";case Tv:return"Suspense";case Mv:return"SuspenseList";case Ev:return"Activity"}if(typeof f=="object")switch(f.$$typeof){case Hu:return"Portal";case Na:return(f.displayName||"Context")+".Provider";case gk:return(f._context.displayName||"Context")+".Consumer";case Iv:var m=f.render;return f=f.displayName,f||(f=m.displayName||m.name||"",f=f!==""?"ForwardRef("+f+")":"ForwardRef"),f;case Cv:return m=f.displayName||null,m!==null?m:u(f.type)||"Memo";case ka:m=f._payload,f=f._init;try{return u(f(m))}catch{}}return null}function h(f){return{current:f}}function d(f){0>Wu||(f.current=Ov[Wu],Ov[Wu]=null,Wu--)}function _(f,m){Wu++,Ov[Wu]=f.current,f.current=m}function y(f){return f>>>=0,f===0?32:31-(JK(f)/QK|0)|0}function g(f){var m=f&42;if(m!==0)return m;switch(f&-f){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 f&4194048;case 4194304:case 8388608:case 16777216:case 33554432:return f&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return f}}function x(f,m,v){var C=f.pendingLanes;if(C===0)return 0;var O=0,z=f.suspendedLanes,Z=f.pingedLanes;f=f.warmLanes;var st=C&134217727;return st!==0?(C=st&~z,C!==0?O=g(C):(Z&=st,Z!==0?O=g(Z):v||(v=st&~f,v!==0&&(O=g(v))))):(st=C&~z,st!==0?O=g(st):Z!==0?O=g(Z):v||(v=C&~f,v!==0&&(O=g(v)))),O===0?0:m!==0&&m!==O&&(m&z)===0&&(z=O&-O,v=m&-m,z>=v||z===32&&(v&4194048)!==0)?m:O}function w(f,m){return(f.pendingLanes&~(f.suspendedLanes&~f.pingedLanes)&m)===0}function S(f,m){switch(f){case 1:case 2:case 4:case 8:case 64:return m+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 m+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 T(){var f=X1;return X1<<=1,(X1&4194048)===0&&(X1=256),f}function I(){var f=V1;return V1<<=1,(V1&62914560)===0&&(V1=4194304),f}function E(f){for(var m=[],v=0;31>v;v++)m.push(f);return m}function M(f,m){f.pendingLanes|=m,m!==268435456&&(f.suspendedLanes=0,f.pingedLanes=0,f.warmLanes=0)}function k(f,m,v,C,O,z){var Z=f.pendingLanes;f.pendingLanes=v,f.suspendedLanes=0,f.pingedLanes=0,f.warmLanes=0,f.expiredLanes&=v,f.entangledLanes&=v,f.errorRecoveryDisabledLanes&=v,f.shellSuspendCounter=0;var st=f.entanglements,gt=f.expirationTimes,Et=f.hiddenUpdates;for(v=Z&~v;0<v;){var zt=31-Fo(v),jt=1<<zt;st[zt]=0,gt[zt]=-1;var Vt=Et[zt];if(Vt!==null)for(Et[zt]=null,zt=0;zt<Vt.length;zt++){var Me=Vt[zt];Me!==null&&(Me.lane&=-536870913)}v&=~jt}C!==0&&N(f,C,0),z!==0&&O===0&&f.tag!==0&&(f.suspendedLanes|=z&~(Z&~m))}function N(f,m,v){f.pendingLanes|=m,f.suspendedLanes&=~m;var C=31-Fo(m);f.entangledLanes|=m,f.entanglements[C]=f.entanglements[C]|1073741824|v&4194090}function A(f,m){var v=f.entangledLanes|=m;for(f=f.entanglements;v;){var C=31-Fo(v),O=1<<C;O&m|f[C]&m&&(f[C]|=m),v&=~O}}function R(f){switch(f){case 2:f=1;break;case 8:f=4;break;case 32:f=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:f=128;break;case 268435456:f=134217728;break;default:f=0}return f}function $(f){return f&=-f,2<f?8<f?(f&134217727)!==0?32:268435456:8:2}function j(f){if(typeof oJ=="function"&&rJ(f),zo&&typeof zo.setStrictMode=="function")try{zo.setStrictMode(Ad,f)}catch{}}function H(f){if(zv===void 0)try{throw Error()}catch(v){var m=v.stack.trim().match(/\n( *(at )?)/);zv=m&&m[1]||"",Vk=-1<v.stack.indexOf(`
|
|
1
|
+
var mJ=Object.create;var u_=Object.defineProperty;var _J=Object.getOwnPropertyDescriptor;var yJ=Object.getOwnPropertyNames;var gJ=Object.getPrototypeOf,bJ=Object.prototype.hasOwnProperty;var xJ=(e,t,n)=>t in e?u_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Xd=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Ht=(e,t)=>()=>(e&&(t=e(e=0)),t);var oe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),il=(e,t)=>{for(var n in t)u_(e,n,{get:t[n],enumerable:!0})},vJ=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of yJ(t))!bJ.call(e,o)&&o!==n&&u_(e,o,{get:()=>t[o],enumerable:!(i=_J(t,o))||i.enumerable});return e};var Xt=(e,t,n)=>(n=e!=null?mJ(gJ(e)):{},vJ(t||!e||!e.__esModule?u_(n,"default",{value:e,enumerable:!0}):n,e));var P=(e,t,n)=>xJ(e,typeof t!="symbol"?t+"":t,n);var yA=oe(Se=>{"use strict";var sS=Symbol.for("react.transitional.element"),FJ=Symbol.for("react.portal"),zJ=Symbol.for("react.fragment"),DJ=Symbol.for("react.strict_mode"),$J=Symbol.for("react.profiler"),jJ=Symbol.for("react.consumer"),BJ=Symbol.for("react.context"),YJ=Symbol.for("react.forward_ref"),XJ=Symbol.for("react.suspense"),VJ=Symbol.for("react.memo"),pA=Symbol.for("react.lazy"),HJ=Symbol.for("react.activity"),aA=Symbol.iterator;function GJ(e){return e===null||typeof e!="object"?null:(e=aA&&e[aA]||e["@@iterator"],typeof e=="function"?e:null)}var hA={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},dA=Object.assign,fA={};function yp(e,t,n){this.props=e,this.context=t,this.refs=fA,this.updater=n||hA}yp.prototype.isReactComponent={};yp.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=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,e,t,"setState")};yp.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function mA(){}mA.prototype=yp.prototype;function aS(e,t,n){this.props=e,this.context=t,this.refs=fA,this.updater=n||hA}var cS=aS.prototype=new mA;cS.constructor=aS;dA(cS,yp.prototype);cS.isPureReactComponent=!0;var cA=Array.isArray;function rS(){}var Mn={H:null,A:null,T:null,S:null},_A=Object.prototype.hasOwnProperty;function lS(e,t,n){var i=n.ref;return{$$typeof:sS,type:e,key:t,ref:i!==void 0?i:null,props:n}}function UJ(e,t){return lS(e.type,t,e.props)}function uS(e){return typeof e=="object"&&e!==null&&e.$$typeof===sS}function qJ(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(n){return t[n]})}var lA=/\/+/g;function oS(e,t){return typeof e=="object"&&e!==null&&e.key!=null?qJ(""+e.key):t.toString(36)}function WJ(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status=="string"?e.then(rS,rS):(e.status="pending",e.then(function(t){e.status==="pending"&&(e.status="fulfilled",e.value=t)},function(t){e.status==="pending"&&(e.status="rejected",e.reason=t)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}function _p(e,t,n,i,o){var r=typeof e;(r==="undefined"||r==="boolean")&&(e=null);var s=!1;if(e===null)s=!0;else switch(r){case"bigint":case"string":case"number":s=!0;break;case"object":switch(e.$$typeof){case sS:case FJ:s=!0;break;case pA:return s=e._init,_p(s(e._payload),t,n,i,o)}}if(s)return o=o(e),s=i===""?"."+oS(e,0):i,cA(o)?(n="",s!=null&&(n=s.replace(lA,"$&/")+"/"),_p(o,t,n,"",function(l){return l})):o!=null&&(uS(o)&&(o=UJ(o,n+(o.key==null||e&&e.key===o.key?"":(""+o.key).replace(lA,"$&/")+"/")+s)),t.push(o)),1;s=0;var a=i===""?".":i+":";if(cA(e))for(var c=0;c<e.length;c++)i=e[c],r=a+oS(i,c),s+=_p(i,t,n,r,o);else if(c=GJ(e),typeof c=="function")for(e=c.call(e),c=0;!(i=e.next()).done;)i=i.value,r=a+oS(i,c++),s+=_p(i,t,n,r,o);else if(r==="object"){if(typeof e.then=="function")return _p(WJ(e),t,n,i,o);throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.")}return s}function y_(e,t,n){if(e==null)return e;var i=[],o=0;return _p(e,i,"","",function(r){return t.call(n,r,o++)}),i}function ZJ(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(n){(e._status===0||e._status===-1)&&(e._status=1,e._result=n)},function(n){(e._status===0||e._status===-1)&&(e._status=2,e._result=n)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var uA=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof e=="object"&&e!==null&&typeof e.message=="string"?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)},KJ={map:y_,forEach:function(e,t,n){y_(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return y_(e,function(){t++}),t},toArray:function(e){return y_(e,function(t){return t})||[]},only:function(e){if(!uS(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};Se.Activity=HJ;Se.Children=KJ;Se.Component=yp;Se.Fragment=zJ;Se.Profiler=$J;Se.PureComponent=aS;Se.StrictMode=DJ;Se.Suspense=XJ;Se.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Mn;Se.__COMPILER_RUNTIME={__proto__:null,c:function(e){return Mn.H.useMemoCache(e)}};Se.cache=function(e){return function(){return e.apply(null,arguments)}};Se.cacheSignal=function(){return null};Se.cloneElement=function(e,t,n){if(e==null)throw Error("The argument must be a React element, but you passed "+e+".");var i=dA({},e.props),o=e.key;if(t!=null)for(r in t.key!==void 0&&(o=""+t.key),t)!_A.call(t,r)||r==="key"||r==="__self"||r==="__source"||r==="ref"&&t.ref===void 0||(i[r]=t[r]);var r=arguments.length-2;if(r===1)i.children=n;else if(1<r){for(var s=Array(r),a=0;a<r;a++)s[a]=arguments[a+2];i.children=s}return lS(e.type,o,i)};Se.createContext=function(e){return e={$$typeof:BJ,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:jJ,_context:e},e};Se.createElement=function(e,t,n){var i,o={},r=null;if(t!=null)for(i in t.key!==void 0&&(r=""+t.key),t)_A.call(t,i)&&i!=="key"&&i!=="__self"&&i!=="__source"&&(o[i]=t[i]);var s=arguments.length-2;if(s===1)o.children=n;else if(1<s){for(var a=Array(s),c=0;c<s;c++)a[c]=arguments[c+2];o.children=a}if(e&&e.defaultProps)for(i in s=e.defaultProps,s)o[i]===void 0&&(o[i]=s[i]);return lS(e,r,o)};Se.createRef=function(){return{current:null}};Se.forwardRef=function(e){return{$$typeof:YJ,render:e}};Se.isValidElement=uS;Se.lazy=function(e){return{$$typeof:pA,_payload:{_status:-1,_result:e},_init:ZJ}};Se.memo=function(e,t){return{$$typeof:VJ,type:e,compare:t===void 0?null:t}};Se.startTransition=function(e){var t=Mn.T,n={};Mn.T=n;try{var i=e(),o=Mn.S;o!==null&&o(n,i),typeof i=="object"&&i!==null&&typeof i.then=="function"&&i.then(rS,uA)}catch(r){uA(r)}finally{t!==null&&n.types!==null&&(t.types=n.types),Mn.T=t}};Se.unstable_useCacheRefresh=function(){return Mn.H.useCacheRefresh()};Se.use=function(e){return Mn.H.use(e)};Se.useActionState=function(e,t,n){return Mn.H.useActionState(e,t,n)};Se.useCallback=function(e,t){return Mn.H.useCallback(e,t)};Se.useContext=function(e){return Mn.H.useContext(e)};Se.useDebugValue=function(){};Se.useDeferredValue=function(e,t){return Mn.H.useDeferredValue(e,t)};Se.useEffect=function(e,t){return Mn.H.useEffect(e,t)};Se.useEffectEvent=function(e){return Mn.H.useEffectEvent(e)};Se.useId=function(){return Mn.H.useId()};Se.useImperativeHandle=function(e,t,n){return Mn.H.useImperativeHandle(e,t,n)};Se.useInsertionEffect=function(e,t){return Mn.H.useInsertionEffect(e,t)};Se.useLayoutEffect=function(e,t){return Mn.H.useLayoutEffect(e,t)};Se.useMemo=function(e,t){return Mn.H.useMemo(e,t)};Se.useOptimistic=function(e,t){return Mn.H.useOptimistic(e,t)};Se.useReducer=function(e,t,n){return Mn.H.useReducer(e,t,n)};Se.useRef=function(e){return Mn.H.useRef(e)};Se.useState=function(e){return Mn.H.useState(e)};Se.useSyncExternalStore=function(e,t,n){return Mn.H.useSyncExternalStore(e,t,n)};Se.useTransition=function(){return Mn.H.useTransition()};Se.version="19.2.0"});var Mr=oe((RNt,gA)=>{"use strict";gA.exports=yA()});var $e,pS,Yt,Wr,Vd=Ht(()=>{"use strict";(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{let r={};for(let s of o)r[s]=s;return r},e.getValidEnumValues=o=>{let r=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),s={};for(let a of r)s[a]=o[a];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(r){return o[r]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let r=[];for(let s in o)Object.prototype.hasOwnProperty.call(o,s)&&r.push(s);return r},e.find=(o,r)=>{for(let s of o)if(r(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function i(o,r=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(r)}e.joinValues=i,e.jsonStringifyReplacer=(o,r)=>typeof r=="bigint"?r.toString():r})($e||($e={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(pS||(pS={}));Yt=$e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Wr=e=>{switch(typeof e){case"undefined":return Yt.undefined;case"string":return Yt.string;case"number":return Number.isNaN(e)?Yt.nan:Yt.number;case"boolean":return Yt.boolean;case"function":return Yt.function;case"bigint":return Yt.bigint;case"symbol":return Yt.symbol;case"object":return Array.isArray(e)?Yt.array:e===null?Yt.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Yt.promise:typeof Map<"u"&&e instanceof Map?Yt.map:typeof Set<"u"&&e instanceof Set?Yt.set:typeof Date<"u"&&e instanceof Date?Yt.date:Yt.object;default:return Yt.unknown}}});var Nt,JJ,bo,g_=Ht(()=>{"use strict";Vd();Nt=$e.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"]),JJ=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),bo=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(r){return r.message},i={_errors:[]},o=r=>{for(let s of r.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)i._errors.push(n(s));else{let a=i,c=0;for(;c<s.path.length;){let l=s.path[c];c===s.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(n(s))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),i}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$e.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},i=[];for(let o of this.issues)if(o.path.length>0){let r=o.path[0];n[r]=n[r]||[],n[r].push(t(o))}else i.push(t(o));return{formErrors:i,fieldErrors:n}}get formErrors(){return this.flatten()}};bo.create=e=>new bo(e)});var QJ,Rs,hS=Ht(()=>{"use strict";g_();Vd();QJ=(e,t)=>{let n;switch(e.code){case Nt.invalid_type:e.received===Yt.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case Nt.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,$e.jsonStringifyReplacer)}`;break;case Nt.unrecognized_keys:n=`Unrecognized key(s) in object: ${$e.joinValues(e.keys,", ")}`;break;case Nt.invalid_union:n="Invalid input";break;case Nt.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${$e.joinValues(e.options)}`;break;case Nt.invalid_enum_value:n=`Invalid enum value. Expected ${$e.joinValues(e.options)}, received '${e.received}'`;break;case Nt.invalid_arguments:n="Invalid function arguments";break;case Nt.invalid_return_type:n="Invalid function return type";break;case Nt.invalid_date:n="Invalid date";break;case Nt.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:$e.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case Nt.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case Nt.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case Nt.custom:n="Invalid input";break;case Nt.invalid_intersection_types:n="Intersection results could not be merged";break;case Nt.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Nt.not_finite:n="Number must be finite";break;default:n=t.defaultError,$e.assertNever(e)}return{message:n}},Rs=QJ});function tQ(e){bA=e}function gp(){return bA}var bA,b_=Ht(()=>{"use strict";hS();bA=Rs});function Dt(e,t){let n=gp(),i=Hd({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Rs?void 0:Rs].filter(o=>!!o)});e.common.issues.push(i)}var Hd,eQ,Li,pe,rl,Ui,x_,v_,Ba,bp,dS=Ht(()=>{"use strict";b_();hS();Hd=e=>{let{data:t,path:n,errorMaps:i,issueData:o}=e,r=[...n,...o.path||[]],s={...o,path:r};if(o.message!==void 0)return{...o,path:r,message:o.message};let a="",c=i.filter(l=>!!l).slice().reverse();for(let l of c)a=l(s,{data:t,defaultError:a}).message;return{...o,path:r,message:a}},eQ=[];Li=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let i=[];for(let o of n){if(o.status==="aborted")return pe;o.status==="dirty"&&t.dirty(),i.push(o.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,n){let i=[];for(let o of n){let r=await o.key,s=await o.value;i.push({key:r,value:s})}return e.mergeObjectSync(t,i)}static mergeObjectSync(t,n){let i={};for(let o of n){let{key:r,value:s}=o;if(r.status==="aborted"||s.status==="aborted")return pe;r.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),r.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(i[r.value]=s.value)}return{status:t.value,value:i}}},pe=Object.freeze({status:"aborted"}),rl=e=>({status:"dirty",value:e}),Ui=e=>({status:"valid",value:e}),x_=e=>e.status==="aborted",v_=e=>e.status==="dirty",Ba=e=>e.status==="valid",bp=e=>typeof Promise<"u"&&e instanceof Promise});var xA=Ht(()=>{"use strict"});var te,vA=Ht(()=>{"use strict";(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(te||(te={}))});function Pe(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:i,description:o}=e;if(t&&(n||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,a)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??i??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}function IA(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function gQ(e){return new RegExp(`^${IA(e)}$`)}function TA(e){let t=`${PA}T${IA(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function bQ(e,t){return!!((t==="v4"||!t)&&pQ.test(e)||(t==="v6"||!t)&&dQ.test(e))}function xQ(e,t){if(!aQ.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let i=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(i));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function vQ(e,t){return!!((t==="v4"||!t)&&hQ.test(e)||(t==="v6"||!t)&&fQ.test(e))}function SQ(e,t){let n=(e.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,o=n>i?n:i,r=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return r%s/10**o}function xp(e){if(e instanceof xo){let t={};for(let n in e.shape){let i=e.shape[n];t[n]=or.create(xp(i))}return new xo({...e._def,shape:()=>t})}else return e instanceof Fs?new Fs({...e._def,type:xp(e.element)}):e instanceof or?or.create(xp(e.unwrap())):e instanceof Kr?Kr.create(xp(e.unwrap())):e instanceof Zr?Zr.create(e.items.map(t=>xp(t))):e}function mS(e,t){let n=Wr(e),i=Wr(t);if(e===t)return{valid:!0,data:e};if(n===Yt.object&&i===Yt.object){let o=$e.objectKeys(t),r=$e.objectKeys(e).filter(a=>o.indexOf(a)!==-1),s={...e,...t};for(let a of r){let c=mS(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(n===Yt.array&&i===Yt.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let r=0;r<e.length;r++){let s=e[r],a=t[r],c=mS(s,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===Yt.date&&i===Yt.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function MA(e,t){return new _l({values:e,typeName:_e.ZodEnum,...Pe(t)})}function wA(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function CA(e,t={},n){return e?Xa.create().superRefine((i,o)=>{let r=e(i);if(r instanceof Promise)return r.then(s=>{if(!s){let a=wA(t,i),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!r){let s=wA(t,i),a=s.fatal??n??!0;o.addIssue({code:"custom",...s,fatal:a})}}):Xa.create()}var rr,SA,Ee,nQ,iQ,oQ,rQ,sQ,aQ,cQ,lQ,uQ,fS,pQ,hQ,dQ,fQ,mQ,_Q,PA,yQ,Ya,sl,al,cl,ll,vp,ul,pl,Xa,Ls,Cr,Sp,Fs,xo,hl,Os,S_,dl,Zr,w_,wp,Pp,P_,fl,ml,_l,yl,Va,sr,or,Kr,gl,bl,Ip,wQ,Gd,Ud,xl,PQ,_e,IQ,EA,NA,TQ,MQ,kA,CQ,EQ,NQ,kQ,AQ,RQ,OQ,LQ,FQ,zQ,DQ,$Q,jQ,BQ,YQ,XQ,VQ,HQ,GQ,UQ,qQ,WQ,ZQ,KQ,JQ,QQ,ttt,ett,ntt,itt,ott,rtt,stt,att,AA=Ht(()=>{"use strict";g_();b_();vA();dS();Vd();rr=class{constructor(t,n,i,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=i,this._key=o}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}},SA=(e,t)=>{if(Ba(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new bo(e.common.issues);return this._error=n,this._error}}};Ee=class{get description(){return this._def.description}_getType(t){return Wr(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Wr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Li,ctx:{common:t.parent.common,data:t.data,parsedType:Wr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(bp(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let i=this.safeParse(t,n);if(i.success)return i.data;throw i.error}safeParse(t,n){let i={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wr(t)},o=this._parseSync({data:t,path:i.path,parent:i});return SA(i,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wr(t)};if(!this["~standard"].async)try{let i=this._parseSync({data:t,path:[],parent:n});return Ba(i)?{value:i.value}:{issues:n.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(i=>Ba(i)?{value:i.value}:{issues:n.common.issues})}async parseAsync(t,n){let i=await this.safeParseAsync(t,n);if(i.success)return i.data;throw i.error}async safeParseAsync(t,n){let i={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wr(t)},o=this._parse({data:t,path:i.path,parent:i}),r=await(bp(o)?o:Promise.resolve(o));return SA(i,r)}refine(t,n){let i=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,r)=>{let s=t(o),a=()=>r.addIssue({code:Nt.custom,...i(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,n){return this._refinement((i,o)=>t(i)?!0:(o.addIssue(typeof n=="function"?n(i,o):n),!1))}_refinement(t){return new sr({schema:this,typeName:_e.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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:n=>this["~validate"](n)}}optional(){return or.create(this,this._def)}nullable(){return Kr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Fs.create(this)}promise(){return Va.create(this,this._def)}or(t){return hl.create([this,t],this._def)}and(t){return dl.create(this,t,this._def)}transform(t){return new sr({...Pe(this._def),schema:this,typeName:_e.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new gl({...Pe(this._def),innerType:this,defaultValue:n,typeName:_e.ZodDefault})}brand(){return new Gd({typeName:_e.ZodBranded,type:this,...Pe(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new bl({...Pe(this._def),innerType:this,catchValue:n,typeName:_e.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Ud.create(this,t)}readonly(){return xl.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},nQ=/^c[^\s-]{8,}$/i,iQ=/^[0-9a-z]+$/,oQ=/^[0-9A-HJKMNP-TV-Z]{26}$/i,rQ=/^[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,sQ=/^[a-z0-9_-]{21}$/i,aQ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,cQ=/^[-+]?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)?)??$/,lQ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,uQ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",pQ=/^(?:(?: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])$/,hQ=/^(?:(?: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])$/,dQ=/^(([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]))$/,fQ=/^(([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])$/,mQ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_Q=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,PA="((\\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])))",yQ=new RegExp(`^${PA}$`);Ya=class e extends Ee{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Yt.string){let r=this._getOrReturnCtx(t);return Dt(r,{code:Nt.invalid_type,expected:Yt.string,received:r.parsedType}),pe}let i=new Li,o;for(let r of this._def.checks)if(r.kind==="min")t.data.length<r.value&&(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="max")t.data.length>r.value&&(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="length"){let s=t.data.length>r.value,a=t.data.length<r.value;(s||a)&&(o=this._getOrReturnCtx(t,o),s?Dt(o,{code:Nt.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):a&&Dt(o,{code:Nt.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),i.dirty())}else if(r.kind==="email")lQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"email",code:Nt.invalid_string,message:r.message}),i.dirty());else if(r.kind==="emoji")fS||(fS=new RegExp(uQ,"u")),fS.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"emoji",code:Nt.invalid_string,message:r.message}),i.dirty());else if(r.kind==="uuid")rQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"uuid",code:Nt.invalid_string,message:r.message}),i.dirty());else if(r.kind==="nanoid")sQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"nanoid",code:Nt.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid")nQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"cuid",code:Nt.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid2")iQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"cuid2",code:Nt.invalid_string,message:r.message}),i.dirty());else if(r.kind==="ulid")oQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"ulid",code:Nt.invalid_string,message:r.message}),i.dirty());else if(r.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),Dt(o,{validation:"url",code:Nt.invalid_string,message:r.message}),i.dirty()}else r.kind==="regex"?(r.regex.lastIndex=0,r.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"regex",code:Nt.invalid_string,message:r.message}),i.dirty())):r.kind==="trim"?t.data=t.data.trim():r.kind==="includes"?t.data.includes(r.value,r.position)||(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),i.dirty()):r.kind==="toLowerCase"?t.data=t.data.toLowerCase():r.kind==="toUpperCase"?t.data=t.data.toUpperCase():r.kind==="startsWith"?t.data.startsWith(r.value)||(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.invalid_string,validation:{startsWith:r.value},message:r.message}),i.dirty()):r.kind==="endsWith"?t.data.endsWith(r.value)||(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.invalid_string,validation:{endsWith:r.value},message:r.message}),i.dirty()):r.kind==="datetime"?TA(r).test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.invalid_string,validation:"datetime",message:r.message}),i.dirty()):r.kind==="date"?yQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.invalid_string,validation:"date",message:r.message}),i.dirty()):r.kind==="time"?gQ(r).test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.invalid_string,validation:"time",message:r.message}),i.dirty()):r.kind==="duration"?cQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"duration",code:Nt.invalid_string,message:r.message}),i.dirty()):r.kind==="ip"?bQ(t.data,r.version)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"ip",code:Nt.invalid_string,message:r.message}),i.dirty()):r.kind==="jwt"?xQ(t.data,r.alg)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"jwt",code:Nt.invalid_string,message:r.message}),i.dirty()):r.kind==="cidr"?vQ(t.data,r.version)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"cidr",code:Nt.invalid_string,message:r.message}),i.dirty()):r.kind==="base64"?mQ.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"base64",code:Nt.invalid_string,message:r.message}),i.dirty()):r.kind==="base64url"?_Q.test(t.data)||(o=this._getOrReturnCtx(t,o),Dt(o,{validation:"base64url",code:Nt.invalid_string,message:r.message}),i.dirty()):$e.assertNever(r);return{status:i.value,value:t.data}}_regex(t,n,i){return this.refinement(o=>t.test(o),{validation:n,code:Nt.invalid_string,...te.errToObj(i)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...te.errToObj(t)})}url(t){return this._addCheck({kind:"url",...te.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...te.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...te.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...te.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...te.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...te.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...te.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...te.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...te.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...te.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...te.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...te.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...te.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...te.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...te.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...te.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...te.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...te.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...te.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...te.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...te.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...te.errToObj(n)})}nonempty(t){return this.min(1,te.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Ya.create=e=>new Ya({checks:[],typeName:_e.ZodString,coerce:e?.coerce??!1,...Pe(e)});sl=class e extends Ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Yt.number){let r=this._getOrReturnCtx(t);return Dt(r,{code:Nt.invalid_type,expected:Yt.number,received:r.parsedType}),pe}let i,o=new Li;for(let r of this._def.checks)r.kind==="int"?$e.isInteger(t.data)||(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.invalid_type,expected:"integer",received:"float",message:r.message}),o.dirty()):r.kind==="min"?(r.inclusive?t.data<r.value:t.data<=r.value)&&(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),o.dirty()):r.kind==="max"?(r.inclusive?t.data>r.value:t.data>=r.value)&&(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),o.dirty()):r.kind==="multipleOf"?SQ(t.data,r.value)!==0&&(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.not_multiple_of,multipleOf:r.value,message:r.message}),o.dirty()):r.kind==="finite"?Number.isFinite(t.data)||(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.not_finite,message:r.message}),o.dirty()):$e.assertNever(r);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,te.toString(n))}gt(t,n){return this.setLimit("min",t,!1,te.toString(n))}lte(t,n){return this.setLimit("max",t,!0,te.toString(n))}lt(t,n){return this.setLimit("max",t,!1,te.toString(n))}setLimit(t,n,i,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:i,message:te.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:te.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:te.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:te.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:te.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:te.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:te.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:te.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:te.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:te.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&$e.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(n===null||i.value>n)&&(n=i.value):i.kind==="max"&&(t===null||i.value<t)&&(t=i.value)}return Number.isFinite(n)&&Number.isFinite(t)}};sl.create=e=>new sl({checks:[],typeName:_e.ZodNumber,coerce:e?.coerce||!1,...Pe(e)});al=class e extends Ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Yt.bigint)return this._getInvalidInput(t);let i,o=new Li;for(let r of this._def.checks)r.kind==="min"?(r.inclusive?t.data<r.value:t.data<=r.value)&&(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),o.dirty()):r.kind==="max"?(r.inclusive?t.data>r.value:t.data>=r.value)&&(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),o.dirty()):r.kind==="multipleOf"?t.data%r.value!==BigInt(0)&&(i=this._getOrReturnCtx(t,i),Dt(i,{code:Nt.not_multiple_of,multipleOf:r.value,message:r.message}),o.dirty()):$e.assertNever(r);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return Dt(n,{code:Nt.invalid_type,expected:Yt.bigint,received:n.parsedType}),pe}gte(t,n){return this.setLimit("min",t,!0,te.toString(n))}gt(t,n){return this.setLimit("min",t,!1,te.toString(n))}lte(t,n){return this.setLimit("max",t,!0,te.toString(n))}lt(t,n){return this.setLimit("max",t,!1,te.toString(n))}setLimit(t,n,i,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:i,message:te.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:te.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:te.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:te.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:te.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:te.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};al.create=e=>new al({checks:[],typeName:_e.ZodBigInt,coerce:e?.coerce??!1,...Pe(e)});cl=class extends Ee{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Yt.boolean){let i=this._getOrReturnCtx(t);return Dt(i,{code:Nt.invalid_type,expected:Yt.boolean,received:i.parsedType}),pe}return Ui(t.data)}};cl.create=e=>new cl({typeName:_e.ZodBoolean,coerce:e?.coerce||!1,...Pe(e)});ll=class e extends Ee{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Yt.date){let r=this._getOrReturnCtx(t);return Dt(r,{code:Nt.invalid_type,expected:Yt.date,received:r.parsedType}),pe}if(Number.isNaN(t.data.getTime())){let r=this._getOrReturnCtx(t);return Dt(r,{code:Nt.invalid_date}),pe}let i=new Li,o;for(let r of this._def.checks)r.kind==="min"?t.data.getTime()<r.value&&(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),i.dirty()):r.kind==="max"?t.data.getTime()>r.value&&(o=this._getOrReturnCtx(t,o),Dt(o,{code:Nt.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),i.dirty()):$e.assertNever(r);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:te.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:te.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};ll.create=e=>new ll({checks:[],coerce:e?.coerce||!1,typeName:_e.ZodDate,...Pe(e)});vp=class extends Ee{_parse(t){if(this._getType(t)!==Yt.symbol){let i=this._getOrReturnCtx(t);return Dt(i,{code:Nt.invalid_type,expected:Yt.symbol,received:i.parsedType}),pe}return Ui(t.data)}};vp.create=e=>new vp({typeName:_e.ZodSymbol,...Pe(e)});ul=class extends Ee{_parse(t){if(this._getType(t)!==Yt.undefined){let i=this._getOrReturnCtx(t);return Dt(i,{code:Nt.invalid_type,expected:Yt.undefined,received:i.parsedType}),pe}return Ui(t.data)}};ul.create=e=>new ul({typeName:_e.ZodUndefined,...Pe(e)});pl=class extends Ee{_parse(t){if(this._getType(t)!==Yt.null){let i=this._getOrReturnCtx(t);return Dt(i,{code:Nt.invalid_type,expected:Yt.null,received:i.parsedType}),pe}return Ui(t.data)}};pl.create=e=>new pl({typeName:_e.ZodNull,...Pe(e)});Xa=class extends Ee{constructor(){super(...arguments),this._any=!0}_parse(t){return Ui(t.data)}};Xa.create=e=>new Xa({typeName:_e.ZodAny,...Pe(e)});Ls=class extends Ee{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ui(t.data)}};Ls.create=e=>new Ls({typeName:_e.ZodUnknown,...Pe(e)});Cr=class extends Ee{_parse(t){let n=this._getOrReturnCtx(t);return Dt(n,{code:Nt.invalid_type,expected:Yt.never,received:n.parsedType}),pe}};Cr.create=e=>new Cr({typeName:_e.ZodNever,...Pe(e)});Sp=class extends Ee{_parse(t){if(this._getType(t)!==Yt.undefined){let i=this._getOrReturnCtx(t);return Dt(i,{code:Nt.invalid_type,expected:Yt.void,received:i.parsedType}),pe}return Ui(t.data)}};Sp.create=e=>new Sp({typeName:_e.ZodVoid,...Pe(e)});Fs=class e extends Ee{_parse(t){let{ctx:n,status:i}=this._processInputParams(t),o=this._def;if(n.parsedType!==Yt.array)return Dt(n,{code:Nt.invalid_type,expected:Yt.array,received:n.parsedType}),pe;if(o.exactLength!==null){let s=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(s||a)&&(Dt(n,{code:s?Nt.too_big:Nt.too_small,minimum:a?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),i.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(Dt(n,{code:Nt.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),i.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(Dt(n,{code:Nt.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),i.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>o.type._parseAsync(new rr(n,s,n.path,a)))).then(s=>Li.mergeArray(i,s));let r=[...n.data].map((s,a)=>o.type._parseSync(new rr(n,s,n.path,a)));return Li.mergeArray(i,r)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:te.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:te.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:te.toString(n)}})}nonempty(t){return this.min(1,t)}};Fs.create=(e,t)=>new Fs({type:e,minLength:null,maxLength:null,exactLength:null,typeName:_e.ZodArray,...Pe(t)});xo=class e extends Ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=$e.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==Yt.object){let l=this._getOrReturnCtx(t);return Dt(l,{code:Nt.invalid_type,expected:Yt.object,received:l.parsedType}),pe}let{status:i,ctx:o}=this._processInputParams(t),{shape:r,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Cr&&this._def.unknownKeys==="strip"))for(let l in o.data)s.includes(l)||a.push(l);let c=[];for(let l of s){let u=r[l],h=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new rr(o,h,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Cr){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(Dt(o,{code:Nt.unrecognized_keys,keys:a}),i.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let h=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new rr(o,h,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let h=await u.key,d=await u.value;l.push({key:h,value:d,alwaysSet:u.alwaysSet})}return l}).then(l=>Li.mergeObjectSync(i,l)):Li.mergeObjectSync(i,c)}get shape(){return this._def.shape()}strict(t){return te.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,i)=>{let o=this._def.errorMap?.(n,i).message??i.defaultError;return n.code==="unrecognized_keys"?{message:te.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:_e.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let i of $e.objectKeys(t))t[i]&&this.shape[i]&&(n[i]=this.shape[i]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let i of $e.objectKeys(this.shape))t[i]||(n[i]=this.shape[i]);return new e({...this._def,shape:()=>n})}deepPartial(){return xp(this)}partial(t){let n={};for(let i of $e.objectKeys(this.shape)){let o=this.shape[i];t&&!t[i]?n[i]=o:n[i]=o.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let i of $e.objectKeys(this.shape))if(t&&!t[i])n[i]=this.shape[i];else{let r=this.shape[i];for(;r instanceof or;)r=r._def.innerType;n[i]=r}return new e({...this._def,shape:()=>n})}keyof(){return MA($e.objectKeys(this.shape))}};xo.create=(e,t)=>new xo({shape:()=>e,unknownKeys:"strip",catchall:Cr.create(),typeName:_e.ZodObject,...Pe(t)});xo.strictCreate=(e,t)=>new xo({shape:()=>e,unknownKeys:"strict",catchall:Cr.create(),typeName:_e.ZodObject,...Pe(t)});xo.lazycreate=(e,t)=>new xo({shape:e,unknownKeys:"strip",catchall:Cr.create(),typeName:_e.ZodObject,...Pe(t)});hl=class extends Ee{_parse(t){let{ctx:n}=this._processInputParams(t),i=this._def.options;function o(r){for(let a of r)if(a.result.status==="valid")return a.result;for(let a of r)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let s=r.map(a=>new bo(a.ctx.common.issues));return Dt(n,{code:Nt.invalid_union,unionErrors:s}),pe}if(n.common.async)return Promise.all(i.map(async r=>{let s={...n,common:{...n.common,issues:[]},parent:null};return{result:await r._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let r,s=[];for(let c of i){let l={...n,common:{...n.common,issues:[]},parent:null},u=c._parseSync({data:n.data,path:n.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!r&&(r={result:u,ctx:l}),l.common.issues.length&&s.push(l.common.issues)}if(r)return n.common.issues.push(...r.ctx.common.issues),r.result;let a=s.map(c=>new bo(c));return Dt(n,{code:Nt.invalid_union,unionErrors:a}),pe}}get options(){return this._def.options}};hl.create=(e,t)=>new hl({options:e,typeName:_e.ZodUnion,...Pe(t)});Os=e=>e instanceof fl?Os(e.schema):e instanceof sr?Os(e.innerType()):e instanceof ml?[e.value]:e instanceof _l?e.options:e instanceof yl?$e.objectValues(e.enum):e instanceof gl?Os(e._def.innerType):e instanceof ul?[void 0]:e instanceof pl?[null]:e instanceof or?[void 0,...Os(e.unwrap())]:e instanceof Kr?[null,...Os(e.unwrap())]:e instanceof Gd||e instanceof xl?Os(e.unwrap()):e instanceof bl?Os(e._def.innerType):[],S_=class e extends Ee{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==Yt.object)return Dt(n,{code:Nt.invalid_type,expected:Yt.object,received:n.parsedType}),pe;let i=this.discriminator,o=n.data[i],r=this.optionsMap.get(o);return r?n.common.async?r._parseAsync({data:n.data,path:n.path,parent:n}):r._parseSync({data:n.data,path:n.path,parent:n}):(Dt(n,{code:Nt.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),pe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,i){let o=new Map;for(let r of n){let s=Os(r.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,r)}}return new e({typeName:_e.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Pe(i)})}};dl=class extends Ee{_parse(t){let{status:n,ctx:i}=this._processInputParams(t),o=(r,s)=>{if(x_(r)||x_(s))return pe;let a=mS(r.value,s.value);return a.valid?((v_(r)||v_(s))&&n.dirty(),{status:n.value,value:a.data}):(Dt(i,{code:Nt.invalid_intersection_types}),pe)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([r,s])=>o(r,s)):o(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}};dl.create=(e,t,n)=>new dl({left:e,right:t,typeName:_e.ZodIntersection,...Pe(n)});Zr=class e extends Ee{_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.parsedType!==Yt.array)return Dt(i,{code:Nt.invalid_type,expected:Yt.array,received:i.parsedType}),pe;if(i.data.length<this._def.items.length)return Dt(i,{code:Nt.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),pe;!this._def.rest&&i.data.length>this._def.items.length&&(Dt(i,{code:Nt.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let r=[...i.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new rr(i,s,i.path,a)):null}).filter(s=>!!s);return i.common.async?Promise.all(r).then(s=>Li.mergeArray(n,s)):Li.mergeArray(n,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Zr.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Zr({items:e,typeName:_e.ZodTuple,rest:null,...Pe(t)})};w_=class e extends Ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.parsedType!==Yt.object)return Dt(i,{code:Nt.invalid_type,expected:Yt.object,received:i.parsedType}),pe;let o=[],r=this._def.keyType,s=this._def.valueType;for(let a in i.data)o.push({key:r._parse(new rr(i,a,i.path,a)),value:s._parse(new rr(i,i.data[a],i.path,a)),alwaysSet:a in i.data});return i.common.async?Li.mergeObjectAsync(n,o):Li.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,i){return n instanceof Ee?new e({keyType:t,valueType:n,typeName:_e.ZodRecord,...Pe(i)}):new e({keyType:Ya.create(),valueType:t,typeName:_e.ZodRecord,...Pe(n)})}},wp=class extends Ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.parsedType!==Yt.map)return Dt(i,{code:Nt.invalid_type,expected:Yt.map,received:i.parsedType}),pe;let o=this._def.keyType,r=this._def.valueType,s=[...i.data.entries()].map(([a,c],l)=>({key:o._parse(new rr(i,a,i.path,[l,"key"])),value:r._parse(new rr(i,c,i.path,[l,"value"]))}));if(i.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return pe;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of s){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return pe;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};wp.create=(e,t,n)=>new wp({valueType:t,keyType:e,typeName:_e.ZodMap,...Pe(n)});Pp=class e extends Ee{_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.parsedType!==Yt.set)return Dt(i,{code:Nt.invalid_type,expected:Yt.set,received:i.parsedType}),pe;let o=this._def;o.minSize!==null&&i.data.size<o.minSize.value&&(Dt(i,{code:Nt.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&i.data.size>o.maxSize.value&&(Dt(i,{code:Nt.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let r=this._def.valueType;function s(c){let l=new Set;for(let u of c){if(u.status==="aborted")return pe;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...i.data.values()].map((c,l)=>r._parse(new rr(i,c,i.path,l)));return i.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:te.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:te.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Pp.create=(e,t)=>new Pp({valueType:e,minSize:null,maxSize:null,typeName:_e.ZodSet,...Pe(t)});P_=class e extends Ee{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==Yt.function)return Dt(n,{code:Nt.invalid_type,expected:Yt.function,received:n.parsedType}),pe;function i(a,c){return Hd({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,gp(),Rs].filter(l=>!!l),issueData:{code:Nt.invalid_arguments,argumentsError:c}})}function o(a,c){return Hd({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,gp(),Rs].filter(l=>!!l),issueData:{code:Nt.invalid_return_type,returnTypeError:c}})}let r={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof Va){let a=this;return Ui(async function(...c){let l=new bo([]),u=await a._def.args.parseAsync(c,r).catch(_=>{throw l.addIssue(i(c,_)),l}),h=await Reflect.apply(s,this,u);return await a._def.returns._def.type.parseAsync(h,r).catch(_=>{throw l.addIssue(o(h,_)),l})})}else{let a=this;return Ui(function(...c){let l=a._def.args.safeParse(c,r);if(!l.success)throw new bo([i(c,l.error)]);let u=Reflect.apply(s,this,l.data),h=a._def.returns.safeParse(u,r);if(!h.success)throw new bo([o(u,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Zr.create(t).rest(Ls.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,i){return new e({args:t||Zr.create([]).rest(Ls.create()),returns:n||Ls.create(),typeName:_e.ZodFunction,...Pe(i)})}},fl=class extends Ee{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};fl.create=(e,t)=>new fl({getter:e,typeName:_e.ZodLazy,...Pe(t)});ml=class extends Ee{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return Dt(n,{received:n.data,code:Nt.invalid_literal,expected:this._def.value}),pe}return{status:"valid",value:t.data}}get value(){return this._def.value}};ml.create=(e,t)=>new ml({value:e,typeName:_e.ZodLiteral,...Pe(t)});_l=class e extends Ee{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),i=this._def.values;return Dt(n,{expected:$e.joinValues(i),received:n.parsedType,code:Nt.invalid_type}),pe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),i=this._def.values;return Dt(n,{received:n.data,code:Nt.invalid_enum_value,options:i}),pe}return Ui(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(i=>!t.includes(i)),{...this._def,...n})}};_l.create=MA;yl=class extends Ee{_parse(t){let n=$e.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==Yt.string&&i.parsedType!==Yt.number){let o=$e.objectValues(n);return Dt(i,{expected:$e.joinValues(o),received:i.parsedType,code:Nt.invalid_type}),pe}if(this._cache||(this._cache=new Set($e.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=$e.objectValues(n);return Dt(i,{received:i.data,code:Nt.invalid_enum_value,options:o}),pe}return Ui(t.data)}get enum(){return this._def.values}};yl.create=(e,t)=>new yl({values:e,typeName:_e.ZodNativeEnum,...Pe(t)});Va=class extends Ee{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==Yt.promise&&n.common.async===!1)return Dt(n,{code:Nt.invalid_type,expected:Yt.promise,received:n.parsedType}),pe;let i=n.parsedType===Yt.promise?n.data:Promise.resolve(n.data);return Ui(i.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Va.create=(e,t)=>new Va({type:e,typeName:_e.ZodPromise,...Pe(t)});sr=class extends Ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_e.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:i}=this._processInputParams(t),o=this._def.effect||null,r={addIssue:s=>{Dt(i,s),s.fatal?n.abort():n.dirty()},get path(){return i.path}};if(r.addIssue=r.addIssue.bind(r),o.type==="preprocess"){let s=o.transform(i.data,r);if(i.common.async)return Promise.resolve(s).then(async a=>{if(n.value==="aborted")return pe;let c=await this._def.schema._parseAsync({data:a,path:i.path,parent:i});return c.status==="aborted"?pe:c.status==="dirty"?rl(c.value):n.value==="dirty"?rl(c.value):c});{if(n.value==="aborted")return pe;let a=this._def.schema._parseSync({data:s,path:i.path,parent:i});return a.status==="aborted"?pe:a.status==="dirty"?rl(a.value):n.value==="dirty"?rl(a.value):a}}if(o.type==="refinement"){let s=a=>{let c=o.refinement(a,r);if(i.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(i.common.async===!1){let a=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return a.status==="aborted"?pe:(a.status==="dirty"&&n.dirty(),s(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(a=>a.status==="aborted"?pe:(a.status==="dirty"&&n.dirty(),s(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(i.common.async===!1){let s=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!Ba(s))return pe;let a=o.transform(s.value,r);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(s=>Ba(s)?Promise.resolve(o.transform(s.value,r)).then(a=>({status:n.value,value:a})):pe);$e.assertNever(o)}};sr.create=(e,t,n)=>new sr({schema:e,typeName:_e.ZodEffects,effect:t,...Pe(n)});sr.createWithPreprocess=(e,t,n)=>new sr({schema:t,effect:{type:"preprocess",transform:e},typeName:_e.ZodEffects,...Pe(n)});or=class extends Ee{_parse(t){return this._getType(t)===Yt.undefined?Ui(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};or.create=(e,t)=>new or({innerType:e,typeName:_e.ZodOptional,...Pe(t)});Kr=class extends Ee{_parse(t){return this._getType(t)===Yt.null?Ui(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Kr.create=(e,t)=>new Kr({innerType:e,typeName:_e.ZodNullable,...Pe(t)});gl=class extends Ee{_parse(t){let{ctx:n}=this._processInputParams(t),i=n.data;return n.parsedType===Yt.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};gl.create=(e,t)=>new gl({innerType:e,typeName:_e.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Pe(t)});bl=class extends Ee{_parse(t){let{ctx:n}=this._processInputParams(t),i={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return bp(o)?o.then(r=>({status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new bo(i.common.issues)},input:i.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new bo(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}};bl.create=(e,t)=>new bl({innerType:e,typeName:_e.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Pe(t)});Ip=class extends Ee{_parse(t){if(this._getType(t)!==Yt.nan){let i=this._getOrReturnCtx(t);return Dt(i,{code:Nt.invalid_type,expected:Yt.nan,received:i.parsedType}),pe}return{status:"valid",value:t.data}}};Ip.create=e=>new Ip({typeName:_e.ZodNaN,...Pe(e)});wQ=Symbol("zod_brand"),Gd=class extends Ee{_parse(t){let{ctx:n}=this._processInputParams(t),i=n.data;return this._def.type._parse({data:i,path:n.path,parent:n})}unwrap(){return this._def.type}},Ud=class e extends Ee{_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{let r=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return r.status==="aborted"?pe:r.status==="dirty"?(n.dirty(),rl(r.value)):this._def.out._parseAsync({data:r.value,path:i.path,parent:i})})();{let o=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?pe:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:i.path,parent:i})}}static create(t,n){return new e({in:t,out:n,typeName:_e.ZodPipeline})}},xl=class extends Ee{_parse(t){let n=this._def.innerType._parse(t),i=o=>(Ba(o)&&(o.value=Object.freeze(o.value)),o);return bp(n)?n.then(o=>i(o)):i(n)}unwrap(){return this._def.innerType}};xl.create=(e,t)=>new xl({innerType:e,typeName:_e.ZodReadonly,...Pe(t)});PQ={object:xo.lazycreate};(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(_e||(_e={}));IQ=(e,t={message:`Input not instance of ${e.name}`})=>CA(n=>n instanceof e,t),EA=Ya.create,NA=sl.create,TQ=Ip.create,MQ=al.create,kA=cl.create,CQ=ll.create,EQ=vp.create,NQ=ul.create,kQ=pl.create,AQ=Xa.create,RQ=Ls.create,OQ=Cr.create,LQ=Sp.create,FQ=Fs.create,zQ=xo.create,DQ=xo.strictCreate,$Q=hl.create,jQ=S_.create,BQ=dl.create,YQ=Zr.create,XQ=w_.create,VQ=wp.create,HQ=Pp.create,GQ=P_.create,UQ=fl.create,qQ=ml.create,WQ=_l.create,ZQ=yl.create,KQ=Va.create,JQ=sr.create,QQ=or.create,ttt=Kr.create,ett=sr.createWithPreprocess,ntt=Ud.create,itt=()=>EA().optional(),ott=()=>NA().optional(),rtt=()=>kA().optional(),stt={string:(e=>Ya.create({...e,coerce:!0})),number:(e=>sl.create({...e,coerce:!0})),boolean:(e=>cl.create({...e,coerce:!0})),bigint:(e=>al.create({...e,coerce:!0})),date:(e=>ll.create({...e,coerce:!0}))},att=pe});var p={};il(p,{BRAND:()=>wQ,DIRTY:()=>rl,EMPTY_PATH:()=>eQ,INVALID:()=>pe,NEVER:()=>att,OK:()=>Ui,ParseStatus:()=>Li,Schema:()=>Ee,ZodAny:()=>Xa,ZodArray:()=>Fs,ZodBigInt:()=>al,ZodBoolean:()=>cl,ZodBranded:()=>Gd,ZodCatch:()=>bl,ZodDate:()=>ll,ZodDefault:()=>gl,ZodDiscriminatedUnion:()=>S_,ZodEffects:()=>sr,ZodEnum:()=>_l,ZodError:()=>bo,ZodFirstPartyTypeKind:()=>_e,ZodFunction:()=>P_,ZodIntersection:()=>dl,ZodIssueCode:()=>Nt,ZodLazy:()=>fl,ZodLiteral:()=>ml,ZodMap:()=>wp,ZodNaN:()=>Ip,ZodNativeEnum:()=>yl,ZodNever:()=>Cr,ZodNull:()=>pl,ZodNullable:()=>Kr,ZodNumber:()=>sl,ZodObject:()=>xo,ZodOptional:()=>or,ZodParsedType:()=>Yt,ZodPipeline:()=>Ud,ZodPromise:()=>Va,ZodReadonly:()=>xl,ZodRecord:()=>w_,ZodSchema:()=>Ee,ZodSet:()=>Pp,ZodString:()=>Ya,ZodSymbol:()=>vp,ZodTransformer:()=>sr,ZodTuple:()=>Zr,ZodType:()=>Ee,ZodUndefined:()=>ul,ZodUnion:()=>hl,ZodUnknown:()=>Ls,ZodVoid:()=>Sp,addIssueToContext:()=>Dt,any:()=>AQ,array:()=>FQ,bigint:()=>MQ,boolean:()=>kA,coerce:()=>stt,custom:()=>CA,date:()=>CQ,datetimeRegex:()=>TA,defaultErrorMap:()=>Rs,discriminatedUnion:()=>jQ,effect:()=>JQ,enum:()=>WQ,function:()=>GQ,getErrorMap:()=>gp,getParsedType:()=>Wr,instanceof:()=>IQ,intersection:()=>BQ,isAborted:()=>x_,isAsync:()=>bp,isDirty:()=>v_,isValid:()=>Ba,late:()=>PQ,lazy:()=>UQ,literal:()=>qQ,makeIssue:()=>Hd,map:()=>VQ,nan:()=>TQ,nativeEnum:()=>ZQ,never:()=>OQ,null:()=>kQ,nullable:()=>ttt,number:()=>NA,object:()=>zQ,objectUtil:()=>pS,oboolean:()=>rtt,onumber:()=>ott,optional:()=>QQ,ostring:()=>itt,pipeline:()=>ntt,preprocess:()=>ett,promise:()=>KQ,quotelessJson:()=>JJ,record:()=>XQ,set:()=>HQ,setErrorMap:()=>tQ,strictObject:()=>DQ,string:()=>EA,symbol:()=>EQ,transformer:()=>JQ,tuple:()=>YQ,undefined:()=>NQ,union:()=>$Q,unknown:()=>RQ,util:()=>$e,void:()=>LQ});var _S=Ht(()=>{"use strict";b_();dS();xA();Vd();AA();g_()});var K=Ht(()=>{"use strict";_S();_S()});var Pl={};il(Pl,{all_layers:()=>Cp,any_circuit_element:()=>q6,any_soup_element:()=>wl,any_source_component:()=>XA,battery_capacity:()=>zA,brep_shape:()=>P9,cad_component:()=>z6,capacitance:()=>zs,circuit_json_footprint_load_error:()=>k_,current:()=>ltt,distance:()=>Y,duration_ms:()=>qd,experiment_type:()=>Y6,external_footprint_load_error:()=>Ep,frequency:()=>Wi,getZodPrefixedIdWithDefault:()=>kt,inductance:()=>I_,layer_ref:()=>se,layer_string:()=>gS,length:()=>D,ms:()=>qi,ninePointAnchor:()=>Wd,pcb_autorouting_error:()=>w6,pcb_board:()=>W9,pcb_breakout_point:()=>P6,pcb_component:()=>T9,pcb_component_invalid_layer_error:()=>Np,pcb_component_outside_board_error:()=>A6,pcb_copper_pour:()=>k6,pcb_copper_pour_brep:()=>E6,pcb_copper_pour_polygon:()=>N6,pcb_copper_pour_rect:()=>C6,pcb_copper_text:()=>n6,pcb_courtyard_outline:()=>L6,pcb_courtyard_polygon:()=>F6,pcb_courtyard_rect:()=>O6,pcb_cutout:()=>x6,pcb_cutout_circle:()=>g6,pcb_cutout_polygon:()=>b6,pcb_cutout_rect:()=>y6,pcb_fabrication_note_dimension:()=>l6,pcb_fabrication_note_path:()=>a6,pcb_fabrication_note_rect:()=>c6,pcb_fabrication_note_text:()=>s6,pcb_footprint_overlap_error:()=>m6,pcb_ground_plane:()=>I6,pcb_ground_plane_region:()=>T6,pcb_group:()=>S6,pcb_hole:()=>R9,pcb_hole_circle_or_square_shape:()=>btt,pcb_hole_circle_shape:()=>ytt,pcb_hole_oval_shape:()=>xtt,pcb_hole_pill_shape:()=>vtt,pcb_hole_rect_shape:()=>gtt,pcb_hole_rotated_pill_shape:()=>Stt,pcb_keepout:()=>_6,pcb_manual_edit_conflict_warning:()=>A_,pcb_missing_footprint_error:()=>v6,pcb_net:()=>U9,pcb_note_dimension:()=>f6,pcb_note_line:()=>d6,pcb_note_path:()=>h6,pcb_note_rect:()=>p6,pcb_note_text:()=>u6,pcb_panel:()=>Z9,pcb_placement_error:()=>K9,pcb_plated_hole:()=>O9,pcb_port:()=>L9,pcb_port_not_connected_error:()=>G9,pcb_port_not_matched_error:()=>H9,pcb_route_hint:()=>I9,pcb_route_hints:()=>_tt,pcb_silkscreen_circle:()=>o6,pcb_silkscreen_line:()=>Q9,pcb_silkscreen_oval:()=>r6,pcb_silkscreen_path:()=>t6,pcb_silkscreen_rect:()=>i6,pcb_silkscreen_text:()=>e6,pcb_smtpad:()=>z9,pcb_smtpad_pill:()=>F9,pcb_solder_paste:()=>D9,pcb_text:()=>$9,pcb_thermal_spoke:()=>M6,pcb_trace:()=>Y9,pcb_trace_error:()=>X9,pcb_trace_hint:()=>J9,pcb_trace_missing_error:()=>V9,pcb_trace_route_point:()=>N_,pcb_trace_route_point_via:()=>B9,pcb_trace_route_point_wire:()=>j9,pcb_via:()=>q9,pcb_via_clearance_error:()=>R6,point:()=>qt,point3:()=>vl,point_with_bulge:()=>w9,port_arrangement:()=>n9,position:()=>ptt,position3:()=>htt,resistance:()=>Ha,ring:()=>bS,rotation:()=>Be,route_hint_point:()=>Fi,schematic_arc:()=>a9,schematic_box:()=>KA,schematic_circle:()=>s9,schematic_component:()=>i9,schematic_component_port_arrangement_by_sides:()=>e9,schematic_component_port_arrangement_by_size:()=>t9,schematic_debug_line:()=>m9,schematic_debug_object:()=>y9,schematic_debug_object_base:()=>C_,schematic_debug_point:()=>_9,schematic_debug_rect:()=>f9,schematic_error:()=>h9,schematic_group:()=>b9,schematic_layout_error:()=>d9,schematic_line:()=>o9,schematic_manual_edit_conflict_warning:()=>E_,schematic_net_label:()=>p9,schematic_path:()=>JA,schematic_pin_styles:()=>QA,schematic_port:()=>u9,schematic_rect:()=>r9,schematic_sheet:()=>S9,schematic_table:()=>x9,schematic_table_cell:()=>v9,schematic_text:()=>l9,schematic_trace:()=>c9,schematic_voltage_probe:()=>g9,simulation_ac_voltage_source:()=>j6,simulation_dc_voltage_source:()=>$6,simulation_experiment:()=>X6,simulation_switch:()=>H6,simulation_transient_voltage_graph:()=>V6,simulation_unknown_experiment_error:()=>U6,simulation_voltage_probe:()=>G6,simulation_voltage_source:()=>B6,size:()=>xS,source_board:()=>qA,source_component_base:()=>Jn,source_failed_to_create_component_error:()=>BA,source_group:()=>GA,source_manually_placed_via:()=>ZA,source_missing_property_error:()=>jA,source_net:()=>UA,source_pcb_ground_plane:()=>WA,source_pin_missing_trace_warning:()=>$S,source_port:()=>VA,source_project_metadata:()=>zS,source_property_ignored_warning:()=>YA,source_simple_battery:()=>TS,source_simple_capacitor:()=>vS,source_simple_chip:()=>PS,source_simple_crystal:()=>$A,source_simple_diode:()=>T_,source_simple_ground:()=>DA,source_simple_inductor:()=>MS,source_simple_led:()=>wS,source_simple_mosfet:()=>LS,source_simple_pin_header:()=>NS,source_simple_pinout:()=>kS,source_simple_potentiometer:()=>ES,source_simple_power_source:()=>IS,source_simple_push_button:()=>CS,source_simple_resistor:()=>SS,source_simple_resonator:()=>AS,source_simple_switch:()=>FS,source_simple_test_point:()=>OS,source_simple_transistor:()=>RS,source_trace:()=>HA,source_trace_not_connected_error:()=>DS,supplier_name:()=>Mp,time:()=>utt,timestamp:()=>FA,unknown_error_finding_part:()=>M_,visible_layer:()=>Nr,voltage:()=>ai,wave_shape:()=>D6});function ctt(e){for(let[t,n]of Object.entries(LA))if(e in n.variants)return{baseUnit:n.baseUnit,conversionFactor:n.variants[e]};return{baseUnit:e,conversionFactor:1}}function Er(e){if(e==null)return{parsedUnit:null,unitOfValue:null,value:null};if(typeof e=="string"&&e.match(/^-?[\d\.]+$/))return{value:Number.parseFloat(e),parsedUnit:null,unitOfValue:null};if(typeof e=="number")return{value:e,parsedUnit:null,unitOfValue:null};if(typeof e=="object"&&"x"in e&&"y"in e){let{parsedUnit:a,unitOfValue:c}=Er(e.x),l=Er(e.x),u=Er(e.y);return l.value===null||u.value===null?{parsedUnit:null,unitOfValue:null,value:null}:{parsedUnit:a,unitOfValue:c,value:{x:l.value,y:u.value}}}let n=e.toString().split("").reverse().join("").match(/[^\d\s]+/)?.[0];if(!n)throw new Error(`Could not determine unit: "${e}"`);let i=n.split("").reverse().join(""),o=e.slice(0,-i.length);if(i in OA&&!yS.has(i)){let a=OA[i];return{parsedUnit:null,unitOfValue:null,value:Number.parseFloat(o)*a}}let{baseUnit:r,conversionFactor:s}=ctt(i);return{parsedUnit:i,unitOfValue:r,value:s*Number.parseFloat(o)}}var LA,yS,OA,Ha,zs,I_,ai,D,Wi,Y,ltt,qd,utt,qi,FA,Be,zA,mt,Sl,qt,ptt,vl,htt,xS,dtt,kt,Wd,Mp,Jn,vS,SS,T_,wS,DA,PS,IS,ftt,TS,MS,CS,ES,$A,NS,kS,AS,RS,OS,LS,FS,zS,jA,BA,DS,YA,$S,XA,VA,HA,GA,UA,qA,WA,Cp,gS,se,Nr,ZA,M_,KA,JA,QA,t9,e9,n9,i9,o9,r9,s9,a9,c9,mtt,l9,u9,p9,h9,d9,C_,f9,m9,_9,y9,g9,E_,b9,x9,v9,S9,w9,bS,P9,I9,_tt,Fi,T9,M9,ytt,C9,gtt,E9,btt,N9,xtt,k9,vtt,A9,Stt,R9,wtt,Ptt,Itt,Ttt,Mtt,O9,L9,Ctt,Ett,Ntt,F9,ktt,Att,z9,Rtt,Ott,Ltt,Ftt,ztt,D9,$9,j9,B9,N_,Y9,X9,V9,H9,G9,U9,q9,W9,Z9,K9,J9,Q9,t6,e6,n6,i6,o6,r6,s6,a6,c6,l6,u6,p6,h6,d6,f6,m6,_6,jS,y6,g6,b6,x6,v6,Ep,k_,S6,w6,A_,P6,I6,T6,M6,BS,C6,E6,N6,k6,A6,Np,R6,O6,L6,F6,z6,D6,Dtt,$6,j6,B6,Y6,X6,V6,H6,G6,U6,q6,wl,vt=Ht(()=>{"use strict";K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();K();LA={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:{fs:1e-12,ps:1e-9,ns:1e-6,us:.001,\u00B5s:.001,ms:1,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}}},yS=new Set;for(let[e,t]of Object.entries(LA)){yS.add(e);for(let n of Object.keys(t.variants))yS.add(n)}OA={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};Ha=p.string().or(p.number()).transform(e=>Er(e).value),zs=p.string().or(p.number()).transform(e=>Er(e).value).transform(e=>Number.parseFloat(e.toPrecision(12))),I_=p.string().or(p.number()).transform(e=>Er(e).value),ai=p.string().or(p.number()).transform(e=>Er(e).value),D=p.string().or(p.number()).transform(e=>Er(e).value),Wi=p.string().or(p.number()).transform(e=>Er(e).value),Y=D,ltt=p.string().or(p.number()).transform(e=>Er(e).value),qd=p.string().or(p.number()).transform(e=>Er(e).value),utt=qd,qi=qd,FA=p.string().datetime(),Be=p.string().or(p.number()).transform(e=>typeof e=="number"?e:e.endsWith("deg")?Number.parseFloat(e.split("deg")[0]):e.endsWith("rad")?Number.parseFloat(e.split("rad")[0])*180/Math.PI:Number.parseFloat(e)),zA=p.number().or(p.string().endsWith("mAh")).transform(e=>{if(typeof e=="string"){let t=e.replace("mAh",""),n=Number.parseFloat(t);if(Number.isNaN(n))throw new Error("Invalid capacity");return n}return e}).describe("Battery capacity in mAh"),mt=e=>{};mt("extra props b");mt("missing props b");mt(!0);mt("mismatched prop types: a");Sl=e=>{};Sl(!0);Sl('T1 has extra: "c", T2 has extra: "d"');Sl('T1 has extra: "c"');Sl('T2 has extra: "c"');Sl('T1 has extra: "d", T2 has extra: "c"');Sl(!0);qt=p.object({x:Y,y:Y}),ptt=qt;mt(!0);mt(!0);vl=p.object({x:Y,y:Y,z:Y}),htt=vl;mt(!0);xS=p.object({width:p.number(),height:p.number()});mt(!0);dtt=e=>{let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";return Array.from({length:e},()=>t[Math.floor(Math.random()*t.length)]).join("")},kt=e=>p.string().optional().default(()=>`${e}_${dtt(10)}`),Wd=p.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]);mt(!0);Mp=p.enum(["jlcpcb","macrofab","pcbway","digikey","mouser","lcsc"]);mt(!0);Jn=p.object({type:p.literal("source_component"),ftype:p.string().optional(),source_component_id:p.string(),name:p.string(),manufacturer_part_number:p.string().optional(),supplier_part_numbers:p.record(Mp,p.array(p.string())).optional(),display_value:p.string().optional(),are_pins_interchangeable:p.boolean().optional(),internally_connected_source_port_ids:p.array(p.array(p.string())).optional(),source_group_id:p.string().optional(),subcircuit_id:p.string().optional()});mt(!0);vS=Jn.extend({ftype:p.literal("simple_capacitor"),capacitance:zs,max_voltage_rating:ai.optional(),display_capacitance:p.string().optional(),max_decoupling_trace_length:Y.optional()});mt(!0);SS=Jn.extend({ftype:p.literal("simple_resistor"),resistance:Ha,display_resistance:p.string().optional()});mt(!0);T_=Jn.extend({ftype:p.literal("simple_diode")});mt(!0);wS=T_.extend({ftype:p.literal("simple_led"),color:p.string().optional(),wavelength:p.string().optional()});mt(!0);DA=Jn.extend({ftype:p.literal("simple_ground")});mt(!0);PS=Jn.extend({ftype:p.literal("simple_chip")});mt(!0);IS=Jn.extend({ftype:p.literal("simple_power_source"),voltage:ai});mt(!0);ftt=Jn.extend({ftype:p.literal("simple_fuse"),current_rating_amps:p.number().describe("Nominal current in amps the fuse is rated for"),voltage_rating_volts:p.number().describe("Voltage rating in volts, e.g. \xB15V would be 5")});mt(!0);TS=Jn.extend({ftype:p.literal("simple_battery"),capacity:zA});mt(!0);MS=Jn.extend({ftype:p.literal("simple_inductor"),inductance:I_,max_current_rating:p.number().optional()});mt(!0);CS=Jn.extend({ftype:p.literal("simple_push_button")});mt(!0);ES=Jn.extend({ftype:p.literal("simple_potentiometer"),max_resistance:Ha});mt(!0);$A=Jn.extend({ftype:p.literal("simple_crystal"),frequency:p.number().describe("Frequency in Hz"),load_capacitance:p.number().optional().describe("Load capacitance in pF")});mt(!0);NS=Jn.extend({ftype:p.literal("simple_pin_header"),pin_count:p.number(),gender:p.enum(["male","female"]).optional().default("male")});mt(!0);kS=Jn.extend({ftype:p.literal("simple_pinout")});mt(!0);AS=Jn.extend({ftype:p.literal("simple_resonator"),load_capacitance:zs,equivalent_series_resistance:Ha.optional(),frequency:Wi});mt(!0);RS=Jn.extend({ftype:p.literal("simple_transistor"),transistor_type:p.enum(["npn","pnp"])});mt(!0);OS=Jn.extend({ftype:p.literal("simple_test_point"),footprint_variant:p.enum(["pad","through_hole"]).optional(),pad_shape:p.enum(["rect","circle"]).optional(),pad_diameter:p.union([p.number(),p.string()]).optional(),hole_diameter:p.union([p.number(),p.string()]).optional(),width:p.union([p.number(),p.string()]).optional(),height:p.union([p.number(),p.string()]).optional()});mt(!0);LS=Jn.extend({ftype:p.literal("simple_mosfet"),channel_type:p.enum(["n","p"]),mosfet_mode:p.enum(["enhancement","depletion"])});mt(!0);FS=Jn.extend({ftype:p.literal("simple_switch")});mt(!0);zS=p.object({type:p.literal("source_project_metadata"),name:p.string().optional(),software_used_string:p.string().optional(),project_url:p.string().optional(),created_at:FA.optional()});mt(!0);jA=p.object({type:p.literal("source_missing_property_error"),source_missing_property_error_id:kt("source_missing_property_error"),source_component_id:p.string(),property_name:p.string(),subcircuit_id:p.string().optional(),error_type:p.literal("source_missing_property_error").default("source_missing_property_error"),message:p.string()}).describe("The source code is missing a property");mt(!0);BA=p.object({type:p.literal("source_failed_to_create_component_error"),source_failed_to_create_component_error_id:kt("source_failed_to_create_component_error"),error_type:p.literal("source_failed_to_create_component_error").default("source_failed_to_create_component_error"),component_name:p.string().optional(),subcircuit_id:p.string().optional(),parent_source_component_id:p.string().optional(),message:p.string(),pcb_center:p.object({x:p.number().optional(),y:p.number().optional()}).optional(),schematic_center:p.object({x:p.number().optional(),y:p.number().optional()}).optional()}).describe("Error emitted when a component fails to be constructed");mt(!0);DS=p.object({type:p.literal("source_trace_not_connected_error"),source_trace_not_connected_error_id:kt("source_trace_not_connected_error"),error_type:p.literal("source_trace_not_connected_error").default("source_trace_not_connected_error"),message:p.string(),subcircuit_id:p.string().optional(),source_group_id:p.string().optional(),source_trace_id:p.string().optional(),connected_source_port_ids:p.array(p.string()).optional(),selectors_not_found:p.array(p.string()).optional()}).describe("Occurs when a source trace selector does not match any ports");mt(!0);YA=p.object({type:p.literal("source_property_ignored_warning"),source_property_ignored_warning_id:kt("source_property_ignored_warning"),source_component_id:p.string(),property_name:p.string(),subcircuit_id:p.string().optional(),error_type:p.literal("source_property_ignored_warning").default("source_property_ignored_warning"),message:p.string()}).describe("The source property was ignored");mt(!0);$S=p.object({type:p.literal("source_pin_missing_trace_warning"),source_pin_missing_trace_warning_id:kt("source_pin_missing_trace_warning"),warning_type:p.literal("source_pin_missing_trace_warning").default("source_pin_missing_trace_warning"),message:p.string(),source_component_id:p.string(),source_port_id:p.string(),subcircuit_id:p.string().optional()}).describe("Warning emitted when a source component pin is missing a trace connection");mt(!0);XA=p.union([SS,vS,T_,wS,DA,PS,IS,TS,MS,CS,ES,$A,NS,kS,AS,FS,RS,OS,LS,ftt,zS,jA,BA,DS,YA,$S]);mt(!0);VA=p.object({type:p.literal("source_port"),pin_number:p.number().optional(),port_hints:p.array(p.string()).optional(),name:p.string(),source_port_id:p.string(),source_component_id:p.string().optional(),source_group_id:p.string().optional(),subcircuit_id:p.string().optional(),subcircuit_connectivity_map_key:p.string().optional()});mt(!0);HA=p.object({type:p.literal("source_trace"),source_trace_id:p.string(),connected_source_port_ids:p.array(p.string()),connected_source_net_ids:p.array(p.string()),subcircuit_id:p.string().optional(),subcircuit_connectivity_map_key:p.string().optional(),max_length:p.number().optional(),min_trace_thickness:p.number().optional(),display_name:p.string().optional()});mt(!0);GA=p.object({type:p.literal("source_group"),source_group_id:p.string(),subcircuit_id:p.string().optional(),parent_subcircuit_id:p.string().optional(),parent_source_group_id:p.string().optional(),is_subcircuit:p.boolean().optional(),show_as_schematic_box:p.boolean().optional(),name:p.string().optional(),was_automatically_named:p.boolean().optional()});mt(!0);UA=p.object({type:p.literal("source_net"),source_net_id:p.string(),name:p.string(),member_source_group_ids:p.array(p.string()),is_power:p.boolean().optional(),is_ground:p.boolean().optional(),is_digital_signal:p.boolean().optional(),is_analog_signal:p.boolean().optional(),is_positive_voltage_source:p.boolean().optional(),trace_width:p.number().optional(),subcircuit_id:p.string().optional(),subcircuit_connectivity_map_key:p.string().optional()});mt(!0);qA=p.object({type:p.literal("source_board"),source_board_id:p.string(),source_group_id:p.string(),title:p.string().optional()}).describe("Defines a board in the source domain");mt(!0);WA=p.object({type:p.literal("source_pcb_ground_plane"),source_pcb_ground_plane_id:p.string(),source_group_id:p.string(),source_net_id:p.string(),subcircuit_id:p.string().optional()}).describe("Defines a ground plane in the source domain");mt(!0);Cp=["top","bottom","inner1","inner2","inner3","inner4","inner5","inner6"],gS=p.enum(Cp),se=gS.or(p.object({name:gS})).transform(e=>typeof e=="string"?e:e.name);mt(!0);Nr=p.enum(["top","bottom"]),ZA=p.object({type:p.literal("source_manually_placed_via"),source_manually_placed_via_id:p.string(),source_group_id:p.string(),source_net_id:p.string(),subcircuit_id:p.string().optional(),source_trace_id:p.string().optional()}).describe("Defines a via that is manually placed in the source domain");mt(!0);M_=p.object({type:p.literal("unknown_error_finding_part"),unknown_error_finding_part_id:kt("unknown_error_finding_part"),error_type:p.literal("unknown_error_finding_part").default("unknown_error_finding_part"),message:p.string(),source_component_id:p.string().optional(),subcircuit_id:p.string().optional()}).describe("Error emitted when an unexpected error occurs while finding a part");mt(!0);KA=p.object({type:p.literal("schematic_box"),schematic_component_id:p.string().optional(),width:Y,height:Y,is_dashed:p.boolean().default(!1),x:Y,y:Y,subcircuit_id:p.string().optional()}).describe("Draws a box on the schematic");mt(!0);JA=p.object({type:p.literal("schematic_path"),schematic_component_id:p.string(),fill_color:p.enum(["red","blue"]).optional(),is_filled:p.boolean().optional(),points:p.array(qt),subcircuit_id:p.string().optional()});mt(!0);QA=p.record(p.object({left_margin:D.optional(),right_margin:D.optional(),top_margin:D.optional(),bottom_margin:D.optional()})),t9=p.object({left_size:p.number(),right_size:p.number(),top_size:p.number().optional(),bottom_size:p.number().optional()});mt(!0);e9=p.object({left_side:p.object({pins:p.array(p.number()),direction:p.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),right_side:p.object({pins:p.array(p.number()),direction:p.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),top_side:p.object({pins:p.array(p.number()),direction:p.enum(["left-to-right","right-to-left"]).optional()}).optional(),bottom_side:p.object({pins:p.array(p.number()),direction:p.enum(["left-to-right","right-to-left"]).optional()}).optional()});mt(!0);n9=p.union([t9,e9]),i9=p.object({type:p.literal("schematic_component"),size:xS,center:qt,source_component_id:p.string().optional(),schematic_component_id:p.string(),pin_spacing:D.optional(),pin_styles:QA.optional(),box_width:D.optional(),symbol_name:p.string().optional(),port_arrangement:n9.optional(),port_labels:p.record(p.string()).optional(),symbol_display_value:p.string().optional(),subcircuit_id:p.string().optional(),schematic_group_id:p.string().optional(),is_schematic_group:p.boolean().optional(),source_group_id:p.string().optional(),is_box_with_pins:p.boolean().optional().default(!0)});mt(!0);o9=p.object({type:p.literal("schematic_line"),schematic_line_id:kt("schematic_line"),schematic_component_id:p.string(),x1:Y,y1:Y,x2:Y,y2:Y,stroke_width:Y.nullable().optional(),color:p.string().default("#000000"),is_dashed:p.boolean().default(!1),subcircuit_id:p.string().optional()}).describe("Draws a styled line on the schematic");mt(!0);r9=p.object({type:p.literal("schematic_rect"),schematic_rect_id:kt("schematic_rect"),schematic_component_id:p.string(),center:qt,width:Y,height:Y,rotation:Be.default(0),stroke_width:Y.nullable().optional(),color:p.string().default("#000000"),is_filled:p.boolean().default(!1),fill_color:p.string().optional(),is_dashed:p.boolean().default(!1),subcircuit_id:p.string().optional()}).describe("Draws a styled rectangle on the schematic");mt(!0);s9=p.object({type:p.literal("schematic_circle"),schematic_circle_id:kt("schematic_circle"),schematic_component_id:p.string(),center:qt,radius:Y,stroke_width:Y.nullable().optional(),color:p.string().default("#000000"),is_filled:p.boolean().default(!1),fill_color:p.string().optional(),is_dashed:p.boolean().default(!1),subcircuit_id:p.string().optional()}).describe("Draws a styled circle on the schematic");mt(!0);a9=p.object({type:p.literal("schematic_arc"),schematic_arc_id:kt("schematic_arc"),schematic_component_id:p.string(),center:qt,radius:Y,start_angle_degrees:Be,end_angle_degrees:Be,direction:p.enum(["clockwise","counterclockwise"]).default("counterclockwise"),stroke_width:Y.nullable().optional(),color:p.string().default("#000000"),is_dashed:p.boolean().default(!1),subcircuit_id:p.string().optional()}).describe("Draws a styled arc on the schematic");mt(!0);c9=p.object({type:p.literal("schematic_trace"),schematic_trace_id:p.string(),source_trace_id:p.string().optional(),junctions:p.array(p.object({x:p.number(),y:p.number()})),edges:p.array(p.object({from:p.object({x:p.number(),y:p.number()}),to:p.object({x:p.number(),y:p.number()}),is_crossing:p.boolean().optional(),from_schematic_port_id:p.string().optional(),to_schematic_port_id:p.string().optional()})),subcircuit_id:p.string().optional(),subcircuit_connectivity_map_key:p.string().optional()});mt(!0);mtt=p.enum(["center","left","right","top","bottom"]);mt(!0);l9=p.object({type:p.literal("schematic_text"),schematic_component_id:p.string().optional(),schematic_text_id:p.string(),text:p.string(),font_size:p.number().default(.18),position:p.object({x:Y,y:Y}),rotation:p.number().default(0),anchor:p.union([mtt.describe("legacy"),Wd]).default("center"),color:p.string().default("#000000"),subcircuit_id:p.string().optional()});mt(!0);u9=p.object({type:p.literal("schematic_port"),schematic_port_id:p.string(),source_port_id:p.string(),schematic_component_id:p.string().optional(),center:qt,facing_direction:p.enum(["up","down","left","right"]).optional(),distance_from_component_edge:p.number().optional(),side_of_component:p.enum(["top","bottom","left","right"]).optional(),true_ccw_index:p.number().optional(),pin_number:p.number().optional(),display_pin_label:p.string().optional(),subcircuit_id:p.string().optional(),is_connected:p.boolean().optional(),has_input_arrow:p.boolean().optional(),has_output_arrow:p.boolean().optional()}).describe("Defines a port on a schematic component");mt(!0);p9=p.object({type:p.literal("schematic_net_label"),schematic_net_label_id:kt("schematic_net_label"),schematic_trace_id:p.string().optional(),source_trace_id:p.string().optional(),source_net_id:p.string(),center:qt,anchor_position:qt.optional(),anchor_side:p.enum(["top","bottom","left","right"]),text:p.string(),symbol_name:p.string().optional(),is_movable:p.boolean().optional(),subcircuit_id:p.string().optional()});mt(!0);h9=p.object({type:p.literal("schematic_error"),schematic_error_id:p.string(),error_type:p.literal("schematic_port_not_found").default("schematic_port_not_found"),message:p.string(),subcircuit_id:p.string().optional()}).describe("Defines a schematic error on the schematic");mt(!0);d9=p.object({type:p.literal("schematic_layout_error"),schematic_layout_error_id:kt("schematic_layout_error"),error_type:p.literal("schematic_layout_error").default("schematic_layout_error"),message:p.string(),source_group_id:p.string(),schematic_group_id:p.string(),subcircuit_id:p.string().optional()}).describe("Error emitted when schematic layout fails for a group");mt(!0);C_=p.object({type:p.literal("schematic_debug_object"),label:p.string().optional(),subcircuit_id:p.string().optional()}),f9=C_.extend({shape:p.literal("rect"),center:qt,size:xS}),m9=C_.extend({shape:p.literal("line"),start:qt,end:qt}),_9=C_.extend({shape:p.literal("point"),center:qt}),y9=p.discriminatedUnion("shape",[f9,m9,_9]);mt(!0);g9=p.object({type:p.literal("schematic_voltage_probe"),schematic_voltage_probe_id:p.string(),position:qt,schematic_trace_id:p.string(),voltage:ai.optional(),subcircuit_id:p.string().optional()}).describe("Defines a voltage probe measurement point on a schematic trace");mt(!0);E_=p.object({type:p.literal("schematic_manual_edit_conflict_warning"),schematic_manual_edit_conflict_warning_id:kt("schematic_manual_edit_conflict_warning"),warning_type:p.literal("schematic_manual_edit_conflict_warning").default("schematic_manual_edit_conflict_warning"),message:p.string(),schematic_component_id:p.string(),schematic_group_id:p.string().optional(),subcircuit_id:p.string().optional(),source_component_id:p.string()}).describe("Warning emitted when a component has both manual placement and explicit schX/schY coordinates");mt(!0);b9=p.object({type:p.literal("schematic_group"),schematic_group_id:kt("schematic_group"),source_group_id:p.string(),is_subcircuit:p.boolean().optional(),subcircuit_id:p.string().optional(),width:D,height:D,center:qt,schematic_component_ids:p.array(p.string()),show_as_schematic_box:p.boolean().optional(),name:p.string().optional(),description:p.string().optional()}).describe("Defines a group of components on the schematic");mt(!0);x9=p.object({type:p.literal("schematic_table"),schematic_table_id:kt("schematic_table"),anchor_position:qt,column_widths:p.array(Y),row_heights:p.array(Y),cell_padding:Y.optional(),border_width:Y.optional(),subcircuit_id:p.string().optional(),schematic_component_id:p.string().optional(),anchor:Wd.optional()}).describe("Defines a table on the schematic");mt(!0);v9=p.object({type:p.literal("schematic_table_cell"),schematic_table_cell_id:kt("schematic_table_cell"),schematic_table_id:p.string(),start_row_index:p.number(),end_row_index:p.number(),start_column_index:p.number(),end_column_index:p.number(),text:p.string().optional(),center:qt,width:Y,height:Y,horizontal_align:p.enum(["left","center","right"]).optional(),vertical_align:p.enum(["top","middle","bottom"]).optional(),font_size:Y.optional(),subcircuit_id:p.string().optional()}).describe("Defines a cell within a schematic_table");mt(!0);S9=p.object({type:p.literal("schematic_sheet"),schematic_sheet_id:kt("schematic_sheet"),name:p.string().optional(),subcircuit_id:p.string().optional()}).describe("Defines a schematic sheet or page that components can be placed on");mt(!0);w9=p.object({x:Y,y:Y,bulge:p.number().optional()});mt(!0);bS=p.object({vertices:p.array(w9)});mt(!0);P9=p.object({outer_ring:bS,inner_rings:p.array(bS).default([])});mt(!0);I9=p.object({x:Y,y:Y,via:p.boolean().optional(),via_to_layer:se.optional()}),_tt=p.array(I9);mt(!0);mt(!0);Fi=p.object({x:Y,y:Y,via:p.boolean().optional(),to_layer:se.optional(),trace_width:Y.optional()});mt(!0);T9=p.object({type:p.literal("pcb_component"),pcb_component_id:kt("pcb_component"),source_component_id:p.string(),center:qt,layer:se,rotation:Be,width:D,height:D,do_not_place:p.boolean().optional(),subcircuit_id:p.string().optional(),pcb_group_id:p.string().optional(),position_mode:p.enum(["packed","relative_to_group_anchor","none"]).optional(),positioned_relative_to_pcb_group_id:p.string().optional(),obstructs_within_bounds:p.boolean().default(!0).describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath")}).describe("Defines a component on the PCB");mt(!0);M9=p.object({type:p.literal("pcb_hole"),pcb_hole_id:kt("pcb_hole"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("circle"),hole_diameter:p.number(),x:Y,y:Y}),ytt=M9.describe("Defines a circular hole on the PCB");mt(!0);C9=p.object({type:p.literal("pcb_hole"),pcb_hole_id:kt("pcb_hole"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("rect"),hole_width:p.number(),hole_height:p.number(),x:Y,y:Y}),gtt=C9.describe("Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.");mt(!0);E9=p.object({type:p.literal("pcb_hole"),pcb_hole_id:kt("pcb_hole"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.enum(["circle","square"]),hole_diameter:p.number(),x:Y,y:Y}),btt=E9.describe("Defines a circular or square hole on the PCB");mt(!0);N9=p.object({type:p.literal("pcb_hole"),pcb_hole_id:kt("pcb_hole"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("oval"),hole_width:p.number(),hole_height:p.number(),x:Y,y:Y}),xtt=N9.describe("Defines an oval hole on the PCB");mt(!0);k9=p.object({type:p.literal("pcb_hole"),pcb_hole_id:kt("pcb_hole"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("pill"),hole_width:p.number(),hole_height:p.number(),x:Y,y:Y}),vtt=k9.describe("Defines a pill-shaped hole on the PCB");mt(!0);A9=p.object({type:p.literal("pcb_hole"),pcb_hole_id:kt("pcb_hole"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("rotated_pill"),hole_width:p.number(),hole_height:p.number(),x:Y,y:Y,ccw_rotation:Be}),Stt=A9.describe("Defines a rotated pill-shaped hole on the PCB");mt(!0);R9=E9.or(N9).or(k9).or(A9).or(M9).or(C9),wtt=p.object({type:p.literal("pcb_plated_hole"),shape:p.literal("circle"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),outer_diameter:p.number(),hole_diameter:p.number(),x:Y,y:Y,layers:p.array(se),port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),pcb_plated_hole_id:kt("pcb_plated_hole")}),Ptt=p.object({type:p.literal("pcb_plated_hole"),shape:p.enum(["oval","pill"]),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),outer_width:p.number(),outer_height:p.number(),hole_width:p.number(),hole_height:p.number(),x:Y,y:Y,ccw_rotation:Be,layers:p.array(se),port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),pcb_plated_hole_id:kt("pcb_plated_hole")}),Itt=p.object({type:p.literal("pcb_plated_hole"),shape:p.literal("circular_hole_with_rect_pad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("circle"),pad_shape:p.literal("rect"),hole_diameter:p.number(),rect_pad_width:p.number(),rect_pad_height:p.number(),rect_border_radius:p.number().optional(),hole_offset_x:Y.default(0),hole_offset_y:Y.default(0),x:Y,y:Y,layers:p.array(se),port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),pcb_plated_hole_id:kt("pcb_plated_hole")}),Ttt=p.object({type:p.literal("pcb_plated_hole"),shape:p.literal("pill_hole_with_rect_pad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("pill"),pad_shape:p.literal("rect"),hole_width:p.number(),hole_height:p.number(),rect_pad_width:p.number(),rect_pad_height:p.number(),rect_border_radius:p.number().optional(),hole_offset_x:Y.default(0),hole_offset_y:Y.default(0),x:Y,y:Y,layers:p.array(se),port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),pcb_plated_hole_id:kt("pcb_plated_hole")}),Mtt=p.object({type:p.literal("pcb_plated_hole"),shape:p.literal("rotated_pill_hole_with_rect_pad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),hole_shape:p.literal("rotated_pill"),pad_shape:p.literal("rect"),hole_width:p.number(),hole_height:p.number(),hole_ccw_rotation:Be,rect_pad_width:p.number(),rect_pad_height:p.number(),rect_border_radius:p.number().optional(),rect_ccw_rotation:Be,hole_offset_x:Y.default(0),hole_offset_y:Y.default(0),x:Y,y:Y,layers:p.array(se),port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),pcb_plated_hole_id:kt("pcb_plated_hole")}),O9=p.union([wtt,Ptt,Itt,Ttt,Mtt]);mt(!0);mt(!0);mt(!0);mt(!0);mt(!0);L9=p.object({type:p.literal("pcb_port"),pcb_port_id:kt("pcb_port"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),source_port_id:p.string(),pcb_component_id:p.string().optional(),x:Y,y:Y,layers:p.array(se),is_board_pinout:p.boolean().optional()}).describe("Defines a port on the PCB");mt(!0);Ctt=p.object({type:p.literal("pcb_smtpad"),shape:p.literal("circle"),pcb_smtpad_id:kt("pcb_smtpad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,radius:p.number(),layer:se,port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),is_covered_with_solder_mask:p.boolean().optional()}),Ett=p.object({type:p.literal("pcb_smtpad"),shape:p.literal("rect"),pcb_smtpad_id:kt("pcb_smtpad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),rect_border_radius:p.number().optional(),corner_radius:p.number().optional(),layer:se,port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),is_covered_with_solder_mask:p.boolean().optional()}),Ntt=p.object({type:p.literal("pcb_smtpad"),shape:p.literal("rotated_rect"),pcb_smtpad_id:kt("pcb_smtpad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),rect_border_radius:p.number().optional(),corner_radius:p.number().optional(),ccw_rotation:Be,layer:se,port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),is_covered_with_solder_mask:p.boolean().optional()}),F9=p.object({type:p.literal("pcb_smtpad"),shape:p.literal("pill"),pcb_smtpad_id:kt("pcb_smtpad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),radius:p.number(),layer:se,port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),is_covered_with_solder_mask:p.boolean().optional()}),ktt=p.object({type:p.literal("pcb_smtpad"),shape:p.literal("rotated_pill"),pcb_smtpad_id:kt("pcb_smtpad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),radius:p.number(),ccw_rotation:Be,layer:se,port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),is_covered_with_solder_mask:p.boolean().optional()}),Att=p.object({type:p.literal("pcb_smtpad"),shape:p.literal("polygon"),pcb_smtpad_id:kt("pcb_smtpad"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),points:p.array(qt),layer:se,port_hints:p.array(p.string()).optional(),pcb_component_id:p.string().optional(),pcb_port_id:p.string().optional(),is_covered_with_solder_mask:p.boolean().optional()}),z9=p.discriminatedUnion("shape",[Ctt,Ett,Ntt,ktt,F9,Att]).describe("Defines an SMT pad on the PCB");mt(!0);mt(!0);mt(!0);mt(!0);mt(!0);mt(!0);Rtt=p.object({type:p.literal("pcb_solder_paste"),shape:p.literal("circle"),pcb_solder_paste_id:kt("pcb_solder_paste"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,radius:p.number(),layer:se,pcb_component_id:p.string().optional(),pcb_smtpad_id:p.string().optional()}),Ott=p.object({type:p.literal("pcb_solder_paste"),shape:p.literal("rect"),pcb_solder_paste_id:kt("pcb_solder_paste"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),layer:se,pcb_component_id:p.string().optional(),pcb_smtpad_id:p.string().optional()}),Ltt=p.object({type:p.literal("pcb_solder_paste"),shape:p.literal("pill"),pcb_solder_paste_id:kt("pcb_solder_paste"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),radius:p.number(),layer:se,pcb_component_id:p.string().optional(),pcb_smtpad_id:p.string().optional()}),Ftt=p.object({type:p.literal("pcb_solder_paste"),shape:p.literal("rotated_rect"),pcb_solder_paste_id:kt("pcb_solder_paste"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),ccw_rotation:Y,layer:se,pcb_component_id:p.string().optional(),pcb_smtpad_id:p.string().optional()}),ztt=p.object({type:p.literal("pcb_solder_paste"),shape:p.literal("oval"),pcb_solder_paste_id:kt("pcb_solder_paste"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),x:Y,y:Y,width:p.number(),height:p.number(),layer:se,pcb_component_id:p.string().optional(),pcb_smtpad_id:p.string().optional()}),D9=p.union([Rtt,Ott,Ltt,Ftt,ztt]).describe("Defines solderpaste on the PCB");mt(!0);mt(!0);mt(!0);mt(!0);mt(!0);$9=p.object({type:p.literal("pcb_text"),pcb_text_id:kt("pcb_text"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),text:p.string(),center:qt,layer:se,width:D,height:D,lines:p.number(),align:p.enum(["bottom-left"])}).describe("Defines text on the PCB");mt(!0);j9=p.object({route_type:p.literal("wire"),x:Y,y:Y,width:Y,start_pcb_port_id:p.string().optional(),end_pcb_port_id:p.string().optional(),layer:se}),B9=p.object({route_type:p.literal("via"),x:Y,y:Y,hole_diameter:Y.optional(),outer_diameter:Y.optional(),from_layer:p.string(),to_layer:p.string()}),N_=p.union([j9,B9]),Y9=p.object({type:p.literal("pcb_trace"),source_trace_id:p.string().optional(),pcb_component_id:p.string().optional(),pcb_trace_id:kt("pcb_trace"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),route_thickness_mode:p.enum(["constant","interpolated"]).default("constant").optional(),route_order_index:p.number().optional(),should_round_corners:p.boolean().optional(),trace_length:p.number().optional(),highlight_color:p.string().optional(),route:p.array(N_)}).describe("Defines a trace on the PCB");mt(!0);mt(!0);X9=p.object({type:p.literal("pcb_trace_error"),pcb_trace_error_id:kt("pcb_trace_error"),error_type:p.literal("pcb_trace_error").default("pcb_trace_error"),message:p.string(),center:qt.optional(),pcb_trace_id:p.string(),source_trace_id:p.string(),pcb_component_ids:p.array(p.string()),pcb_port_ids:p.array(p.string()),subcircuit_id:p.string().optional()}).describe("Defines a trace error on the PCB");mt(!0);V9=p.object({type:p.literal("pcb_trace_missing_error"),pcb_trace_missing_error_id:kt("pcb_trace_missing_error"),error_type:p.literal("pcb_trace_missing_error").default("pcb_trace_missing_error"),message:p.string(),center:qt.optional(),source_trace_id:p.string(),pcb_component_ids:p.array(p.string()),pcb_port_ids:p.array(p.string()),subcircuit_id:p.string().optional()}).describe("Defines an error when a source trace has no corresponding PCB trace");mt(!0);H9=p.object({type:p.literal("pcb_port_not_matched_error"),pcb_error_id:kt("pcb_error"),error_type:p.literal("pcb_port_not_matched_error").default("pcb_port_not_matched_error"),message:p.string(),pcb_component_ids:p.array(p.string()),subcircuit_id:p.string().optional()}).describe("Defines a trace error on the PCB where a port is not matched");mt(!0);G9=p.object({type:p.literal("pcb_port_not_connected_error"),pcb_port_not_connected_error_id:kt("pcb_port_not_connected_error"),error_type:p.literal("pcb_port_not_connected_error").default("pcb_port_not_connected_error"),message:p.string(),pcb_port_ids:p.array(p.string()),pcb_component_ids:p.array(p.string()),subcircuit_id:p.string().optional()}).describe("Defines an error when a pcb port is not connected to any trace");mt(!0);U9=p.object({type:p.literal("pcb_net"),pcb_net_id:kt("pcb_net"),source_net_id:p.string().optional(),highlight_color:p.string().optional()}).describe("Defines a net on the PCB");mt(!0);q9=p.object({type:p.literal("pcb_via"),pcb_via_id:kt("pcb_via"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),subcircuit_connectivity_map_key:p.string().optional(),x:Y,y:Y,outer_diameter:Y.default("0.6mm"),hole_diameter:Y.default("0.25mm"),from_layer:se.optional(),to_layer:se.optional(),layers:p.array(se),pcb_trace_id:p.string().optional(),net_is_assignable:p.boolean().optional(),net_assigned:p.boolean().optional()}).describe("Defines a via on the PCB");mt(!0);W9=p.object({type:p.literal("pcb_board"),pcb_board_id:kt("pcb_board"),pcb_panel_id:p.string().optional(),is_subcircuit:p.boolean().optional(),subcircuit_id:p.string().optional(),width:D.optional(),height:D.optional(),center:qt,thickness:D.optional().default(1.4),num_layers:p.number().optional().default(4),outline:p.array(qt).optional(),shape:p.enum(["rect","polygon"]).optional(),material:p.enum(["fr4","fr1"]).default("fr4")}).describe("Defines the board outline of the PCB");mt(!0);Z9=p.object({type:p.literal("pcb_panel"),pcb_panel_id:kt("pcb_panel"),width:D,height:D,covered_with_solder_mask:p.boolean().optional().default(!0)}).describe("Defines a PCB panel that can contain multiple boards");mt(!0);K9=p.object({type:p.literal("pcb_placement_error"),pcb_placement_error_id:kt("pcb_placement_error"),error_type:p.literal("pcb_placement_error").default("pcb_placement_error"),message:p.string(),subcircuit_id:p.string().optional()}).describe("Defines a placement error on the PCB");mt(!0);J9=p.object({type:p.literal("pcb_trace_hint"),pcb_trace_hint_id:kt("pcb_trace_hint"),pcb_port_id:p.string(),pcb_component_id:p.string(),route:p.array(Fi),subcircuit_id:p.string().optional()}).describe("A hint that can be used during generation of a PCB trace");mt(!0);Q9=p.object({type:p.literal("pcb_silkscreen_line"),pcb_silkscreen_line_id:kt("pcb_silkscreen_line"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),stroke_width:Y.default("0.1mm"),x1:Y,y1:Y,x2:Y,y2:Y,layer:Nr}).describe("Defines a silkscreen line on the PCB");mt(!0);t6=p.object({type:p.literal("pcb_silkscreen_path"),pcb_silkscreen_path_id:kt("pcb_silkscreen_path"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),layer:Nr,route:p.array(qt),stroke_width:D}).describe("Defines a silkscreen path on the PCB");mt(!0);e6=p.object({type:p.literal("pcb_silkscreen_text"),pcb_silkscreen_text_id:kt("pcb_silkscreen_text"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),font:p.literal("tscircuit2024").default("tscircuit2024"),font_size:Y.default("0.2mm"),pcb_component_id:p.string(),text:p.string(),is_knockout:p.boolean().default(!1).optional(),knockout_padding:p.object({left:D,top:D,bottom:D,right:D}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:p.number().optional(),layer:se,is_mirrored:p.boolean().default(!1).optional(),anchor_position:qt.default({x:0,y:0}),anchor_alignment:Wd.default("center")}).describe("Defines silkscreen text on the PCB");mt(!0);n6=p.object({type:p.literal("pcb_copper_text"),pcb_copper_text_id:kt("pcb_copper_text"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),font:p.literal("tscircuit2024").default("tscircuit2024"),font_size:Y.default("0.2mm"),pcb_component_id:p.string(),text:p.string(),is_knockout:p.boolean().default(!1).optional(),knockout_padding:p.object({left:D,top:D,bottom:D,right:D}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:p.number().optional(),layer:se,is_mirrored:p.boolean().default(!1).optional(),anchor_position:qt.default({x:0,y:0}),anchor_alignment:Wd.default("center")}).describe("Defines copper text on the PCB");mt(!0);i6=p.object({type:p.literal("pcb_silkscreen_rect"),pcb_silkscreen_rect_id:kt("pcb_silkscreen_rect"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),center:qt,width:D,height:D,layer:se,stroke_width:D.default("1mm"),corner_radius:D.optional(),is_filled:p.boolean().default(!0).optional(),has_stroke:p.boolean().optional(),is_stroke_dashed:p.boolean().optional()}).describe("Defines a silkscreen rect on the PCB");mt(!0);o6=p.object({type:p.literal("pcb_silkscreen_circle"),pcb_silkscreen_circle_id:kt("pcb_silkscreen_circle"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),center:qt,radius:D,layer:Nr,stroke_width:D.default("1mm")}).describe("Defines a silkscreen circle on the PCB");mt(!0);r6=p.object({type:p.literal("pcb_silkscreen_oval"),pcb_silkscreen_oval_id:kt("pcb_silkscreen_oval"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),center:qt,radius_x:Y,radius_y:Y,layer:Nr}).describe("Defines a silkscreen oval on the PCB");mt(!0);s6=p.object({type:p.literal("pcb_fabrication_note_text"),pcb_fabrication_note_text_id:kt("pcb_fabrication_note_text"),subcircuit_id:p.string().optional(),pcb_group_id:p.string().optional(),font:p.literal("tscircuit2024").default("tscircuit2024"),font_size:Y.default("1mm"),pcb_component_id:p.string(),text:p.string(),layer:Nr,anchor_position:qt.default({x:0,y:0}),anchor_alignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),color:p.string().optional()}).describe("Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators");mt(!0);a6=p.object({type:p.literal("pcb_fabrication_note_path"),pcb_fabrication_note_path_id:kt("pcb_fabrication_note_path"),pcb_component_id:p.string(),subcircuit_id:p.string().optional(),layer:se,route:p.array(qt),stroke_width:D,color:p.string().optional()}).describe("Defines a fabrication path on the PCB for fabricators or assemblers");mt(!0);c6=p.object({type:p.literal("pcb_fabrication_note_rect"),pcb_fabrication_note_rect_id:kt("pcb_fabrication_note_rect"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),center:qt,width:D,height:D,layer:Nr,stroke_width:D.default("0.1mm"),corner_radius:D.optional(),is_filled:p.boolean().optional(),has_stroke:p.boolean().optional(),is_stroke_dashed:p.boolean().optional(),color:p.string().optional()}).describe("Defines a fabrication note rectangle on the PCB");mt(!0);l6=p.object({type:p.literal("pcb_fabrication_note_dimension"),pcb_fabrication_note_dimension_id:kt("pcb_fabrication_note_dimension"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),layer:Nr,from:qt,to:qt,text:p.string().optional(),text_ccw_rotation:p.number().optional(),offset:D.optional(),offset_distance:D.optional(),offset_direction:p.object({x:p.number(),y:p.number()}).optional(),font:p.literal("tscircuit2024").default("tscircuit2024"),font_size:D.default("1mm"),color:p.string().optional(),arrow_size:D.default("1mm")}).describe("Defines a measurement annotation within PCB fabrication notes");mt(!0);u6=p.object({type:p.literal("pcb_note_text"),pcb_note_text_id:kt("pcb_note_text"),pcb_component_id:p.string().optional(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),name:p.string().optional(),font:p.literal("tscircuit2024").default("tscircuit2024"),font_size:Y.default("1mm"),text:p.string().optional(),anchor_position:qt.default({x:0,y:0}),anchor_alignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),color:p.string().optional()}).describe("Defines a documentation note in text on the PCB");mt(!0);p6=p.object({type:p.literal("pcb_note_rect"),pcb_note_rect_id:kt("pcb_note_rect"),pcb_component_id:p.string().optional(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),name:p.string().optional(),text:p.string().optional(),center:qt,width:D,height:D,stroke_width:D.default("0.1mm"),corner_radius:D.optional(),is_filled:p.boolean().optional(),has_stroke:p.boolean().optional(),is_stroke_dashed:p.boolean().optional(),color:p.string().optional()}).describe("Defines a rectangular documentation note on the PCB");mt(!0);h6=p.object({type:p.literal("pcb_note_path"),pcb_note_path_id:kt("pcb_note_path"),pcb_component_id:p.string().optional(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),name:p.string().optional(),text:p.string().optional(),route:p.array(qt),stroke_width:D.default("0.1mm"),color:p.string().optional()}).describe("Defines a polyline documentation note on the PCB");mt(!0);d6=p.object({type:p.literal("pcb_note_line"),pcb_note_line_id:kt("pcb_note_line"),pcb_component_id:p.string().optional(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),name:p.string().optional(),text:p.string().optional(),x1:Y,y1:Y,x2:Y,y2:Y,stroke_width:Y.default("0.1mm"),color:p.string().optional(),is_dashed:p.boolean().optional()}).describe("Defines a straight documentation note line on the PCB");mt(!0);f6=p.object({type:p.literal("pcb_note_dimension"),pcb_note_dimension_id:kt("pcb_note_dimension"),pcb_component_id:p.string().optional(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),name:p.string().optional(),from:qt,to:qt,text:p.string().optional(),text_ccw_rotation:p.number().optional(),offset_distance:D.optional(),offset_direction:p.object({x:p.number(),y:p.number()}).optional(),font:p.literal("tscircuit2024").default("tscircuit2024"),font_size:D.default("1mm"),color:p.string().optional(),arrow_size:D.default("1mm")}).describe("Defines a measurement annotation within PCB documentation notes");mt(!0);m6=p.object({type:p.literal("pcb_footprint_overlap_error"),pcb_error_id:kt("pcb_error"),error_type:p.literal("pcb_footprint_overlap_error").default("pcb_footprint_overlap_error"),message:p.string(),pcb_smtpad_ids:p.array(p.string()).optional(),pcb_plated_hole_ids:p.array(p.string()).optional(),pcb_hole_ids:p.array(p.string()).optional(),pcb_keepout_ids:p.array(p.string()).optional()}).describe("Error emitted when a pcb footprint overlaps with another element");mt(!0);_6=p.object({type:p.literal("pcb_keepout"),shape:p.literal("rect"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),center:qt,width:Y,height:Y,pcb_keepout_id:p.string(),layers:p.array(p.string()),description:p.string().optional()}).or(p.object({type:p.literal("pcb_keepout"),shape:p.literal("circle"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),center:qt,radius:Y,pcb_keepout_id:p.string(),layers:p.array(p.string()),description:p.string().optional()}));mt(!0);jS=p.object({type:p.literal("pcb_cutout"),pcb_cutout_id:kt("pcb_cutout"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional()}),y6=jS.extend({shape:p.literal("rect"),center:qt,width:D,height:D,rotation:Be.optional()});mt(!0);g6=jS.extend({shape:p.literal("circle"),center:qt,radius:D});mt(!0);b6=jS.extend({shape:p.literal("polygon"),points:p.array(qt)});mt(!0);x6=p.discriminatedUnion("shape",[y6,g6,b6]).describe("Defines a cutout on the PCB, removing board material.");mt(!0);v6=p.object({type:p.literal("pcb_missing_footprint_error"),pcb_missing_footprint_error_id:kt("pcb_missing_footprint_error"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),error_type:p.literal("pcb_missing_footprint_error").default("pcb_missing_footprint_error"),source_component_id:p.string(),message:p.string()}).describe("Defines a missing footprint error on the PCB");mt(!0);Ep=p.object({type:p.literal("external_footprint_load_error"),external_footprint_load_error_id:kt("external_footprint_load_error"),pcb_component_id:p.string(),source_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),footprinter_string:p.string().optional(),error_type:p.literal("external_footprint_load_error").default("external_footprint_load_error"),message:p.string()}).describe("Defines an error when an external footprint fails to load");mt(!0);k_=p.object({type:p.literal("circuit_json_footprint_load_error"),circuit_json_footprint_load_error_id:kt("circuit_json_footprint_load_error"),pcb_component_id:p.string(),source_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),error_type:p.literal("circuit_json_footprint_load_error").default("circuit_json_footprint_load_error"),message:p.string(),circuit_json:p.array(p.any()).optional()}).describe("Defines an error when a circuit JSON footprint fails to load");mt(!0);S6=p.object({type:p.literal("pcb_group"),pcb_group_id:kt("pcb_group"),source_group_id:p.string(),is_subcircuit:p.boolean().optional(),subcircuit_id:p.string().optional(),width:D.optional(),height:D.optional(),center:qt,outline:p.array(qt).optional(),anchor_position:qt.optional(),anchor_alignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).optional(),pcb_component_ids:p.array(p.string()),child_layout_mode:p.enum(["packed","none"]).optional(),name:p.string().optional(),description:p.string().optional(),layout_mode:p.string().optional(),autorouter_configuration:p.object({trace_clearance:D}).optional(),autorouter_used_string:p.string().optional()}).describe("Defines a group of components on the PCB");mt(!0);w6=p.object({type:p.literal("pcb_autorouting_error"),pcb_error_id:kt("pcb_autorouting_error"),error_type:p.literal("pcb_autorouting_error").default("pcb_autorouting_error"),message:p.string(),subcircuit_id:p.string().optional()}).describe("The autorouting has failed to route a portion of the board");mt(!0);A_=p.object({type:p.literal("pcb_manual_edit_conflict_warning"),pcb_manual_edit_conflict_warning_id:kt("pcb_manual_edit_conflict_warning"),warning_type:p.literal("pcb_manual_edit_conflict_warning").default("pcb_manual_edit_conflict_warning"),message:p.string(),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),source_component_id:p.string()}).describe("Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates");mt(!0);P6=p.object({type:p.literal("pcb_breakout_point"),pcb_breakout_point_id:kt("pcb_breakout_point"),pcb_group_id:p.string(),subcircuit_id:p.string().optional(),source_trace_id:p.string().optional(),source_port_id:p.string().optional(),source_net_id:p.string().optional(),x:Y,y:Y}).describe("Defines a routing target within a pcb_group for a source_trace or source_net");mt(!0);I6=p.object({type:p.literal("pcb_ground_plane"),pcb_ground_plane_id:kt("pcb_ground_plane"),source_pcb_ground_plane_id:p.string(),source_net_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional()}).describe("Defines a ground plane on the PCB");mt(!0);T6=p.object({type:p.literal("pcb_ground_plane_region"),pcb_ground_plane_region_id:kt("pcb_ground_plane_region"),pcb_ground_plane_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),layer:se,points:p.array(qt)}).describe("Defines a polygon region of a ground plane");mt(!0);M6=p.object({type:p.literal("pcb_thermal_spoke"),pcb_thermal_spoke_id:kt("pcb_thermal_spoke"),pcb_ground_plane_id:p.string(),shape:p.string(),spoke_count:p.number(),spoke_thickness:Y,spoke_inner_diameter:Y,spoke_outer_diameter:Y,pcb_plated_hole_id:p.string().optional(),subcircuit_id:p.string().optional()}).describe("Pattern for connecting a ground plane to a plated hole");mt(!0);BS=p.object({type:p.literal("pcb_copper_pour"),pcb_copper_pour_id:kt("pcb_copper_pour"),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),layer:se,source_net_id:p.string().optional(),covered_with_solder_mask:p.boolean().optional().default(!0)}),C6=BS.extend({shape:p.literal("rect"),center:qt,width:D,height:D,rotation:Be.optional()});mt(!0);E6=BS.extend({shape:p.literal("brep"),brep_shape:P9});mt(!0);N6=BS.extend({shape:p.literal("polygon"),points:p.array(qt)});mt(!0);k6=p.discriminatedUnion("shape",[C6,E6,N6]).describe("Defines a copper pour on the PCB.");mt(!0);A6=p.object({type:p.literal("pcb_component_outside_board_error"),pcb_component_outside_board_error_id:kt("pcb_component_outside_board_error"),error_type:p.literal("pcb_component_outside_board_error").default("pcb_component_outside_board_error"),message:p.string(),pcb_component_id:p.string(),pcb_board_id:p.string(),component_center:qt,component_bounds:p.object({min_x:p.number(),max_x:p.number(),min_y:p.number(),max_y:p.number()}),subcircuit_id:p.string().optional(),source_component_id:p.string().optional()}).describe("Error emitted when a PCB component is placed outside the board boundaries");mt(!0);Np=p.object({type:p.literal("pcb_component_invalid_layer_error"),pcb_component_invalid_layer_error_id:kt("pcb_component_invalid_layer_error"),error_type:p.literal("pcb_component_invalid_layer_error").default("pcb_component_invalid_layer_error"),message:p.string(),pcb_component_id:p.string().optional(),source_component_id:p.string(),layer:se,subcircuit_id:p.string().optional()}).describe("Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)");mt(!0);R6=p.object({type:p.literal("pcb_via_clearance_error"),pcb_error_id:kt("pcb_error"),error_type:p.literal("pcb_via_clearance_error").default("pcb_via_clearance_error"),message:p.string(),pcb_via_ids:p.array(p.string()).min(2),minimum_clearance:Y.optional(),actual_clearance:Y.optional(),pcb_center:p.object({x:p.number().optional(),y:p.number().optional()}).optional(),subcircuit_id:p.string().optional()}).describe("Error emitted when vias are closer than the allowed clearance");mt(!0);O6=p.object({type:p.literal("pcb_courtyard_rect"),pcb_courtyard_rect_id:kt("pcb_courtyard_rect"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),center:qt,width:D,height:D,layer:Nr,color:p.string().optional()}).describe("Defines a courtyard rectangle on the PCB");mt(!0);L6=p.object({type:p.literal("pcb_courtyard_outline"),pcb_courtyard_outline_id:kt("pcb_courtyard_outline"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),layer:Nr,outline:p.array(qt).min(2),stroke_width:D.default("0.1mm"),is_closed:p.boolean().optional(),is_stroke_dashed:p.boolean().optional(),color:p.string().optional()}).describe("Defines a courtyard outline on the PCB");mt(!0);F6=p.object({type:p.literal("pcb_courtyard_polygon"),pcb_courtyard_polygon_id:kt("pcb_courtyard_polygon"),pcb_component_id:p.string(),pcb_group_id:p.string().optional(),subcircuit_id:p.string().optional(),layer:Nr,points:p.array(qt).min(3),color:p.string().optional()}).describe("Defines a courtyard polygon on the PCB");mt(!0);z6=p.object({type:p.literal("cad_component"),cad_component_id:p.string(),pcb_component_id:p.string(),source_component_id:p.string(),position:vl,rotation:vl.optional(),size:vl.optional(),layer:se.optional(),subcircuit_id:p.string().optional(),footprinter_string:p.string().optional(),model_obj_url:p.string().optional(),model_stl_url:p.string().optional(),model_3mf_url:p.string().optional(),model_gltf_url:p.string().optional(),model_glb_url:p.string().optional(),model_step_url:p.string().optional(),model_wrl_url:p.string().optional(),model_unit_to_mm_scale_factor:p.number().optional(),model_jscad:p.any().optional()}).describe("Defines a component on the PCB");mt(!0);D6=p.enum(["sinewave","square","triangle","sawtooth"]),Dtt=p.union([p.string(),p.number()]).transform(e=>typeof e=="string"?e.endsWith("%")?parseFloat(e.slice(0,-1))/100:parseFloat(e):e).pipe(p.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),$6=p.object({type:p.literal("simulation_voltage_source"),simulation_voltage_source_id:kt("simulation_voltage_source"),is_dc_source:p.literal(!0).optional().default(!0),positive_source_port_id:p.string().optional(),negative_source_port_id:p.string().optional(),positive_source_net_id:p.string().optional(),negative_source_net_id:p.string().optional(),voltage:ai}).describe("Defines a DC voltage source for simulation"),j6=p.object({type:p.literal("simulation_voltage_source"),simulation_voltage_source_id:kt("simulation_voltage_source"),is_dc_source:p.literal(!1),terminal1_source_port_id:p.string().optional(),terminal2_source_port_id:p.string().optional(),terminal1_source_net_id:p.string().optional(),terminal2_source_net_id:p.string().optional(),voltage:ai.optional(),frequency:Wi.optional(),peak_to_peak_voltage:ai.optional(),wave_shape:D6.optional(),phase:Be.optional(),duty_cycle:Dtt.optional()}).describe("Defines an AC voltage source for simulation"),B6=p.union([$6,j6]).describe("Defines a voltage source for simulation");mt(!0);mt(!0);mt(!0);Y6=p.union([p.literal("spice_dc_sweep"),p.literal("spice_dc_operating_point"),p.literal("spice_transient_analysis"),p.literal("spice_ac_analysis")]),X6=p.object({type:p.literal("simulation_experiment"),simulation_experiment_id:kt("simulation_experiment"),name:p.string(),experiment_type:Y6,time_per_step:qd.optional(),start_time_ms:qi.optional(),end_time_ms:qi.optional()}).describe("Defines a simulation experiment configuration");mt(!0);V6=p.object({type:p.literal("simulation_transient_voltage_graph"),simulation_transient_voltage_graph_id:kt("simulation_transient_voltage_graph"),simulation_experiment_id:p.string(),timestamps_ms:p.array(p.number()).optional(),voltage_levels:p.array(p.number()),schematic_voltage_probe_id:p.string().optional(),simulation_voltage_probe_id:p.string().optional(),subcircuit_connectivity_map_key:p.string().optional(),time_per_step:qd,start_time_ms:qi,end_time_ms:qi,name:p.string().optional()}).describe("Stores voltage measurements over time for a simulation");mt(!0);H6=p.object({type:p.literal("simulation_switch"),simulation_switch_id:kt("simulation_switch"),source_component_id:p.string().optional(),closes_at:qi.optional(),opens_at:qi.optional(),starts_closed:p.boolean().optional(),switching_frequency:Wi.optional()}).describe("Defines a switch for simulation timing control");mt(!0);G6=p.object({type:p.literal("simulation_voltage_probe"),simulation_voltage_probe_id:kt("simulation_voltage_probe"),source_port_id:p.string().optional(),source_net_id:p.string().optional(),name:p.string().optional(),subcircuit_id:p.string().optional()}).describe("Defines a voltage probe for simulation, connected to a port or a net").refine(e=>!!e.source_port_id!=!!e.source_net_id,{message:"Exactly one of source_port_id or source_net_id must be provided to simulation_voltage_probe"});mt(!0);U6=p.object({type:p.literal("simulation_unknown_experiment_error"),simulation_unknown_experiment_error_id:kt("simulation_unknown_experiment_error"),error_type:p.literal("simulation_unknown_experiment_error").default("simulation_unknown_experiment_error"),message:p.string(),simulation_experiment_id:p.string().optional(),subcircuit_id:p.string().optional()}).describe("An unknown error occurred during the simulation experiment.");mt(!0);q6=p.union([HA,VA,XA,UA,GA,PS,vS,T_,wS,SS,IS,TS,MS,NS,kS,AS,FS,RS,OS,LS,ES,CS,WA,ZA,qA,zS,DS,$S,M_,T9,R9,v6,Ep,k_,A_,O9,_6,L9,U9,$9,Y9,q9,z9,D9,W9,Z9,S6,J9,Q9,t6,e6,n6,i6,o6,r6,X9,V9,K9,H9,G9,R6,a6,s6,c6,l6,u6,p6,h6,d6,f6,w6,m6,P6,x6,I6,T6,M6,k6,A6,Np,O6,L6,F6,KA,l9,o9,r9,s9,a9,i9,u9,c9,JA,h9,d9,p9,y9,g9,E_,b9,S9,x9,v9,z6,B6,X6,V6,H6,G6,U6]),wl=q6;mt(!0);Sl(!0)});var b8=oe((uOt,g8)=>{"use strict";var Ap=1e3,Rp=Ap*60,Op=Rp*60,Ml=Op*24,rrt=Ml*7,srt=Ml*365.25;g8.exports=function(e,t){t=t||{};var n=typeof e;if(n==="string"&&e.length>0)return art(e);if(n==="number"&&isFinite(e))return t.long?lrt(e):crt(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function art(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),i=(t[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return n*srt;case"weeks":case"week":case"w":return n*rrt;case"days":case"day":case"d":return n*Ml;case"hours":case"hour":case"hrs":case"hr":case"h":return n*Op;case"minutes":case"minute":case"mins":case"min":case"m":return n*Rp;case"seconds":case"second":case"secs":case"sec":case"s":return n*Ap;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function crt(e){var t=Math.abs(e);return t>=Ml?Math.round(e/Ml)+"d":t>=Op?Math.round(e/Op)+"h":t>=Rp?Math.round(e/Rp)+"m":t>=Ap?Math.round(e/Ap)+"s":e+"ms"}function lrt(e){var t=Math.abs(e);return t>=Ml?Y_(e,t,Ml,"day"):t>=Op?Y_(e,t,Op,"hour"):t>=Rp?Y_(e,t,Rp,"minute"):t>=Ap?Y_(e,t,Ap,"second"):e+" ms"}function Y_(e,t,n,i){var o=t>=n*1.5;return Math.round(e/n)+" "+i+(o?"s":"")}});var v8=oe((pOt,x8)=>{"use strict";function urt(e){n.debug=n,n.default=n,n.coerce=c,n.disable=s,n.enable=o,n.enabled=a,n.humanize=b8(),n.destroy=l,Object.keys(e).forEach(u=>{n[u]=e[u]}),n.names=[],n.skips=[],n.formatters={};function t(u){let h=0;for(let d=0;d<u.length;d++)h=(h<<5)-h+u.charCodeAt(d),h|=0;return n.colors[Math.abs(h)%n.colors.length]}n.selectColor=t;function n(u){let h,d=null,_,y;function g(...x){if(!g.enabled)return;let w=g,S=Number(new Date),T=S-(h||S);w.diff=T,w.prev=h,w.curr=S,h=S,x[0]=n.coerce(x[0]),typeof x[0]!="string"&&x.unshift("%O");let I=0;x[0]=x[0].replace(/%([a-zA-Z%])/g,(M,k)=>{if(M==="%%")return"%";I++;let N=n.formatters[k];if(typeof N=="function"){let A=x[I];M=N.call(w,A),x.splice(I,1),I--}return M}),n.formatArgs.call(w,x),(w.log||n.log).apply(w,x)}return g.namespace=u,g.useColors=n.useColors(),g.color=n.selectColor(u),g.extend=i,g.destroy=n.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(_!==n.namespaces&&(_=n.namespaces,y=n.enabled(u)),y),set:x=>{d=x}}),typeof n.init=="function"&&n.init(g),g}function i(u,h){let d=n(this.namespace+(typeof h>"u"?":":h)+u);return d.log=this.log,d}function o(u){n.save(u),n.namespaces=u,n.names=[],n.skips=[];let h=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let d of h)d[0]==="-"?n.skips.push(d.slice(1)):n.names.push(d)}function r(u,h){let d=0,_=0,y=-1,g=0;for(;d<u.length;)if(_<h.length&&(h[_]===u[d]||h[_]==="*"))h[_]==="*"?(y=_,g=d,_++):(d++,_++);else if(y!==-1)_=y+1,g++,d=g;else return!1;for(;_<h.length&&h[_]==="*";)_++;return _===h.length}function s(){let u=[...n.names,...n.skips.map(h=>"-"+h)].join(",");return n.enable(""),u}function a(u){for(let h of n.skips)if(r(u,h))return!1;for(let h of n.names)if(r(u,h))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){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 n.enable(n.load()),n}x8.exports=urt});var Sn=oe((vo,X_)=>{"use strict";vo.formatArgs=hrt;vo.save=drt;vo.load=frt;vo.useColors=prt;vo.storage=mrt();vo.destroy=(()=>{let e=!1;return()=>{e||(e=!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`."))}})();vo.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 prt(){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 e;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&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function hrt(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+X_.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;e.splice(1,0,t,"color: inherit");let n=0,i=0;e[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(i=n))}),e.splice(i,0,t)}vo.log=console.debug||console.log||(()=>{});function drt(e){try{e?vo.storage.setItem("debug",e):vo.storage.removeItem("debug")}catch{}}function frt(){let e;try{e=vo.storage.getItem("debug")||vo.storage.getItem("DEBUG")}catch{}return!e&&typeof process<"u"&&"env"in process&&(e=process.env.DEBUG),e}function mrt(){try{return localStorage}catch{}}X_.exports=v8()(vo);var{formatters:_rt}=X_.exports;_rt.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var k8=oe(An=>{"use strict";function KS(e,t){var n=e.length;e.push(t);t:for(;0<n;){var i=n-1>>>1,o=e[i];if(0<V_(o,t))e[i]=t,e[n]=o,n=i;else break t}}function Jr(e){return e.length===0?null:e[0]}function G_(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;t:for(var i=0,o=e.length,r=o>>>1;i<r;){var s=2*(i+1)-1,a=e[s],c=s+1,l=e[c];if(0>V_(a,n))c<o&&0>V_(l,a)?(e[i]=l,e[c]=n,i=c):(e[i]=a,e[s]=n,i=s);else if(c<o&&0>V_(l,n))e[i]=l,e[c]=n,i=c;else break t}}return t}function V_(e,t){var n=e.sortIndex-t.sortIndex;return n!==0?n:e.id-t.id}An.unstable_now=void 0;typeof performance=="object"&&typeof performance.now=="function"?(S8=performance,An.unstable_now=function(){return S8.now()}):(qS=Date,w8=qS.now(),An.unstable_now=function(){return qS.now()-w8});var S8,qS,w8,Bs=[],qa=[],yrt=1,ar=null,Zi=3,JS=!1,Kd=!1,Jd=!1,QS=!1,T8=typeof setTimeout=="function"?setTimeout:null,M8=typeof clearTimeout=="function"?clearTimeout:null,P8=typeof setImmediate<"u"?setImmediate:null;function H_(e){for(var t=Jr(qa);t!==null;){if(t.callback===null)G_(qa);else if(t.startTime<=e)G_(qa),t.sortIndex=t.expirationTime,KS(Bs,t);else break;t=Jr(qa)}}function tw(e){if(Jd=!1,H_(e),!Kd)if(Jr(Bs)!==null)Kd=!0,Fp||(Fp=!0,Lp());else{var t=Jr(qa);t!==null&&ew(tw,t.startTime-e)}}var Fp=!1,Qd=-1,C8=5,E8=-1;function N8(){return QS?!0:!(An.unstable_now()-E8<C8)}function WS(){if(QS=!1,Fp){var e=An.unstable_now();E8=e;var t=!0;try{t:{Kd=!1,Jd&&(Jd=!1,M8(Qd),Qd=-1),JS=!0;var n=Zi;try{e:{for(H_(e),ar=Jr(Bs);ar!==null&&!(ar.expirationTime>e&&N8());){var i=ar.callback;if(typeof i=="function"){ar.callback=null,Zi=ar.priorityLevel;var o=i(ar.expirationTime<=e);if(e=An.unstable_now(),typeof o=="function"){ar.callback=o,H_(e),t=!0;break e}ar===Jr(Bs)&&G_(Bs),H_(e)}else G_(Bs);ar=Jr(Bs)}if(ar!==null)t=!0;else{var r=Jr(qa);r!==null&&ew(tw,r.startTime-e),t=!1}}break t}finally{ar=null,Zi=n,JS=!1}t=void 0}}finally{t?Lp():Fp=!1}}}var Lp;typeof P8=="function"?Lp=function(){P8(WS)}:typeof MessageChannel<"u"?(ZS=new MessageChannel,I8=ZS.port2,ZS.port1.onmessage=WS,Lp=function(){I8.postMessage(null)}):Lp=function(){T8(WS,0)};var ZS,I8;function ew(e,t){Qd=T8(function(){e(An.unstable_now())},t)}An.unstable_IdlePriority=5;An.unstable_ImmediatePriority=1;An.unstable_LowPriority=4;An.unstable_NormalPriority=3;An.unstable_Profiling=null;An.unstable_UserBlockingPriority=2;An.unstable_cancelCallback=function(e){e.callback=null};An.unstable_forceFrameRate=function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):C8=0<e?Math.floor(1e3/e):5};An.unstable_getCurrentPriorityLevel=function(){return Zi};An.unstable_next=function(e){switch(Zi){case 1:case 2:case 3:var t=3;break;default:t=Zi}var n=Zi;Zi=t;try{return e()}finally{Zi=n}};An.unstable_requestPaint=function(){QS=!0};An.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=Zi;Zi=e;try{return t()}finally{Zi=n}};An.unstable_scheduleCallback=function(e,t,n){var i=An.unstable_now();switch(typeof n=="object"&&n!==null?(n=n.delay,n=typeof n=="number"&&0<n?i+n:i):n=i,e){case 1:var o=-1;break;case 2:o=250;break;case 5:o=1073741823;break;case 4:o=1e4;break;default:o=5e3}return o=n+o,e={id:yrt++,callback:t,priorityLevel:e,startTime:n,expirationTime:o,sortIndex:-1},n>i?(e.sortIndex=n,KS(qa,e),Jr(Bs)===null&&e===Jr(qa)&&(Jd?(M8(Qd),Qd=-1):Jd=!0,ew(tw,n-i))):(e.sortIndex=o,KS(Bs,e),Kd||JS||(Kd=!0,Fp||(Fp=!0,Lp()))),e};An.unstable_shouldYield=N8;An.unstable_wrapCallback=function(e){var t=Zi;return function(){var n=Zi;Zi=t;try{return e.apply(this,arguments)}finally{Zi=n}}}});var R8=oe((dOt,A8)=>{"use strict";A8.exports=k8()});var O8=oe((fOt,tf)=>{"use strict";tf.exports=function(e){function t(f,m,v,C){return new EZ(f,m,v,C)}function n(){}function i(f){var m="https://react.dev/errors/"+f;if(1<arguments.length){m+="?args[]="+encodeURIComponent(arguments[1]);for(var v=2;v<arguments.length;v++)m+="&args[]="+encodeURIComponent(arguments[v])}return"Minified React error #"+f+"; visit "+m+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function o(f){var m=f,v=f;if(f.alternate)for(;m.return;)m=m.return;else{f=m;do m=f,(m.flags&4098)!==0&&(v=m.return),f=m.return;while(f)}return m.tag===3?v:null}function r(f){if(o(f)!==f)throw Error(i(188))}function s(f){var m=f.alternate;if(!m){if(m=o(f),m===null)throw Error(i(188));return m!==f?null:f}for(var v=f,C=m;;){var O=v.return;if(O===null)break;var z=O.alternate;if(z===null){if(C=O.return,C!==null){v=C;continue}break}if(O.child===z.child){for(z=O.child;z;){if(z===v)return r(O),f;if(z===C)return r(O),m;z=z.sibling}throw Error(i(188))}if(v.return!==C.return)v=O,C=z;else{for(var Z=!1,st=O.child;st;){if(st===v){Z=!0,v=O,C=z;break}if(st===C){Z=!0,C=O,v=z;break}st=st.sibling}if(!Z){for(st=z.child;st;){if(st===v){Z=!0,v=z,C=O;break}if(st===C){Z=!0,C=z,v=O;break}st=st.sibling}if(!Z)throw Error(i(189))}}if(v.alternate!==C)throw Error(i(190))}if(v.tag!==3)throw Error(i(188));return v.stateNode.current===v?f:m}function a(f){var m=f.tag;if(m===5||m===26||m===27||m===6)return f;for(f=f.child;f!==null;){if(m=a(f),m!==null)return m;f=f.sibling}return null}function c(f){var m=f.tag;if(m===5||m===26||m===27||m===6)return f;for(f=f.child;f!==null;){if(f.tag!==4&&(m=c(f),m!==null))return m;f=f.sibling}return null}function l(f){return f===null||typeof f!="object"?null:(f=bk&&f[bk]||f["@@iterator"],typeof f=="function"?f:null)}function u(f){if(f==null)return null;if(typeof f=="function")return f.$$typeof===LZ?null:f.displayName||f.name||null;if(typeof f=="string")return f;switch(f){case Gu:return"Fragment";case Pv:return"Profiler";case yk:return"StrictMode";case Tv:return"Suspense";case Mv:return"SuspenseList";case Ev:return"Activity"}if(typeof f=="object")switch(f.$$typeof){case Hu:return"Portal";case Na:return(f.displayName||"Context")+".Provider";case gk:return(f._context.displayName||"Context")+".Consumer";case Iv:var m=f.render;return f=f.displayName,f||(f=m.displayName||m.name||"",f=f!==""?"ForwardRef("+f+")":"ForwardRef"),f;case Cv:return m=f.displayName||null,m!==null?m:u(f.type)||"Memo";case ka:m=f._payload,f=f._init;try{return u(f(m))}catch{}}return null}function h(f){return{current:f}}function d(f){0>Wu||(f.current=Ov[Wu],Ov[Wu]=null,Wu--)}function _(f,m){Wu++,Ov[Wu]=f.current,f.current=m}function y(f){return f>>>=0,f===0?32:31-(JK(f)/QK|0)|0}function g(f){var m=f&42;if(m!==0)return m;switch(f&-f){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 f&4194048;case 4194304:case 8388608:case 16777216:case 33554432:return f&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return f}}function x(f,m,v){var C=f.pendingLanes;if(C===0)return 0;var O=0,z=f.suspendedLanes,Z=f.pingedLanes;f=f.warmLanes;var st=C&134217727;return st!==0?(C=st&~z,C!==0?O=g(C):(Z&=st,Z!==0?O=g(Z):v||(v=st&~f,v!==0&&(O=g(v))))):(st=C&~z,st!==0?O=g(st):Z!==0?O=g(Z):v||(v=C&~f,v!==0&&(O=g(v)))),O===0?0:m!==0&&m!==O&&(m&z)===0&&(z=O&-O,v=m&-m,z>=v||z===32&&(v&4194048)!==0)?m:O}function w(f,m){return(f.pendingLanes&~(f.suspendedLanes&~f.pingedLanes)&m)===0}function S(f,m){switch(f){case 1:case 2:case 4:case 8:case 64:return m+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 m+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 T(){var f=X1;return X1<<=1,(X1&4194048)===0&&(X1=256),f}function I(){var f=V1;return V1<<=1,(V1&62914560)===0&&(V1=4194304),f}function E(f){for(var m=[],v=0;31>v;v++)m.push(f);return m}function M(f,m){f.pendingLanes|=m,m!==268435456&&(f.suspendedLanes=0,f.pingedLanes=0,f.warmLanes=0)}function k(f,m,v,C,O,z){var Z=f.pendingLanes;f.pendingLanes=v,f.suspendedLanes=0,f.pingedLanes=0,f.warmLanes=0,f.expiredLanes&=v,f.entangledLanes&=v,f.errorRecoveryDisabledLanes&=v,f.shellSuspendCounter=0;var st=f.entanglements,gt=f.expirationTimes,Et=f.hiddenUpdates;for(v=Z&~v;0<v;){var zt=31-Fo(v),jt=1<<zt;st[zt]=0,gt[zt]=-1;var Vt=Et[zt];if(Vt!==null)for(Et[zt]=null,zt=0;zt<Vt.length;zt++){var Me=Vt[zt];Me!==null&&(Me.lane&=-536870913)}v&=~jt}C!==0&&N(f,C,0),z!==0&&O===0&&f.tag!==0&&(f.suspendedLanes|=z&~(Z&~m))}function N(f,m,v){f.pendingLanes|=m,f.suspendedLanes&=~m;var C=31-Fo(m);f.entangledLanes|=m,f.entanglements[C]=f.entanglements[C]|1073741824|v&4194090}function A(f,m){var v=f.entangledLanes|=m;for(f=f.entanglements;v;){var C=31-Fo(v),O=1<<C;O&m|f[C]&m&&(f[C]|=m),v&=~O}}function R(f){switch(f){case 2:f=1;break;case 8:f=4;break;case 32:f=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:f=128;break;case 268435456:f=134217728;break;default:f=0}return f}function $(f){return f&=-f,2<f?8<f?(f&134217727)!==0?32:268435456:8:2}function j(f){if(typeof oJ=="function"&&rJ(f),zo&&typeof zo.setStrictMode=="function")try{zo.setStrictMode(Ad,f)}catch{}}function H(f){if(zv===void 0)try{throw Error()}catch(v){var m=v.stack.trim().match(/\n( *(at )?)/);zv=m&&m[1]||"",Vk=-1<v.stack.indexOf(`
|
|
2
2
|
at`)?" (<anonymous>)":-1<v.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
3
3
|
`+zv+f+Vk}function X(f,m){if(!f||Dv)return"";Dv=!0;var v=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var C={DetermineComponentFrameRoot:function(){try{if(m){var jt=function(){throw Error()};if(Object.defineProperty(jt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(jt,[])}catch(Me){var Vt=Me}Reflect.construct(f,[],jt)}else{try{jt.call()}catch(Me){Vt=Me}f.call(jt.prototype)}}else{try{throw Error()}catch(Me){Vt=Me}(jt=f())&&typeof jt.catch=="function"&&jt.catch(function(){})}}catch(Me){if(Me&&Vt&&typeof Me.stack=="string")return[Me.stack,Vt.stack]}return[null,null]}};C.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var O=Object.getOwnPropertyDescriptor(C.DetermineComponentFrameRoot,"name");O&&O.configurable&&Object.defineProperty(C.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var z=C.DetermineComponentFrameRoot(),Z=z[0],st=z[1];if(Z&&st){var gt=Z.split(`
|
|
4
4
|
`),Et=st.split(`
|
|
@@ -158,7 +158,7 @@ svg { font-family: 'Inter', 'Helvetica Neue', Arial, sans-serif; }
|
|
|
158
158
|
fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *)
|
|
159
159
|
)`,enabled:":not(:disabled)",checked:":is(:is(input[type=radio], input[type=checkbox])[checked], option:selected)",required:":is(input, select, textarea)[required]",optional:":is(input, select, textarea):not([required])",selected:"option:is([selected], select:not([multiple]):not(:has(> option[selected])) > :first-of-type)",checkbox:"[type=checkbox]",file:"[type=file]",password:"[type=password]",radio:"[type=radio]",reset:"[type=reset]",image:"[type=image]",submit:"[type=submit]",parent:":not(:empty)",header:":is(h1, h2, h3, h4, h5, h6)",button:":is(button, input[type=button])",input:":is(input, textarea, select, button)",text:"input:is(:not([type!='']), [type=text])"};var lr=Xt(kl(),1);var sI={};function aI(e,t){return e===lr.default.falseFunc?lr.default.falseFunc:n=>t.isTag(n)&&e(n)}function cI(e,t){let n=t.getSiblings(e);if(n.length<=1)return[];let i=n.indexOf(e);return i<0||i===n.length-1?[]:n.slice(i+1).filter(t.isTag)}function rI(e){return{xmlMode:!!e.xmlMode,lowerCaseAttributeNames:!!e.lowerCaseAttributeNames,lowerCaseTags:!!e.lowerCaseTags,quirksMode:!!e.quirksMode,cacheResults:!!e.cacheResults,pseudos:e.pseudos,adapter:e.adapter,equals:e.equals}}var oI=(e,t,n,i,o)=>{let r=o(t,rI(n),i);return r===lr.default.trueFunc?e:r===lr.default.falseFunc?lr.default.falseFunc:s=>r(s)&&e(s)},zg={is:oI,matches:oI,where:oI,not(e,t,n,i,o){let r=o(t,rI(n),i);return r===lr.default.falseFunc?e:r===lr.default.trueFunc?lr.default.falseFunc:s=>!r(s)&&e(s)},has(e,t,n,i,o){let{adapter:r}=n,s=rI(n);s.relativeSelector=!0;let a=t.some(u=>u.some(uf))?[sI]:void 0,c=o(t,s,a);if(c===lr.default.falseFunc)return lr.default.falseFunc;let l=aI(c,r);if(a&&c!==lr.default.trueFunc){let{shouldTestNextSiblings:u=!1}=c;return h=>{if(!e(h))return!1;a[0]=h;let d=r.getChildren(h),_=u?[...d,...cI(h,r)]:d;return r.existsOne(l,_)}}return u=>e(u)&&r.existsOne(l,r.getChildren(u))}};function hF(e,t,n,i,o){var r;let{name:s,data:a}=t;if(Array.isArray(a)){if(!(s in zg))throw new Error(`Unknown pseudo-class :${s}(${a})`);return zg[s](e,a,n,i,o)}let c=(r=n.pseudos)===null||r===void 0?void 0:r[s],l=typeof c=="string"?c:iI[s];if(typeof l=="string"){if(a!=null)throw new Error(`Pseudo ${s} doesn't have any arguments`);let u=lf(l);return zg.is(e,u,n,i,o)}if(typeof c=="function")return nI(c,s,a,1),u=>c(u,a)&&e(u);if(s in hf)return hf[s](e,a,n,i);if(s in Fg){let u=Fg[s];return nI(u,s,a,2),h=>u(h,n,a)&&e(h)}throw new Error(`Unknown pseudo-class :${s}`)}function lI(e,t){let n=t.getParent(e);return n&&t.isTag(n)?n:null}function dF(e,t,n,i,o){let{adapter:r,equals:s}=n;switch(t.type){case ae.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case ae.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case ae.Attribute:{if(t.namespace!=null)throw new Error("Namespaced attributes are not yet supported by css-select");return(!n.xmlMode||n.lowerCaseAttributeNames)&&(t.name=t.name.toLowerCase()),cF[t.action](e,t,n)}case ae.Pseudo:return hF(e,t,n,i,o);case ae.Tag:{if(t.namespace!=null)throw new Error("Namespaced tag names are not yet supported by css-select");let{name:a}=t;return(!n.xmlMode||n.lowerCaseTags)&&(a=a.toLowerCase()),function(l){return r.getName(l)===a&&e(l)}}case ae.Descendant:{if(n.cacheResults===!1||typeof WeakSet>"u")return function(l){let u=l;for(;u=lI(u,r);)if(e(u))return!0;return!1};let a=new WeakSet;return function(l){let u=l;for(;u=lI(u,r);)if(!a.has(u)){if(r.isTag(u)&&e(u))return!0;a.add(u)}return!1}}case"_flexibleDescendant":return function(c){let l=c;do if(e(l))return!0;while(l=lI(l,r));return!1};case ae.Parent:return function(c){return r.getChildren(c).some(l=>r.isTag(l)&&e(l))};case ae.Child:return function(c){let l=r.getParent(c);return l!=null&&r.isTag(l)&&e(l)};case ae.Sibling:return function(c){let l=r.getSiblings(c);for(let u=0;u<l.length;u++){let h=l[u];if(s(c,h))break;if(r.isTag(h)&&e(h))return!0}return!1};case ae.Adjacent:return r.prevElementSibling?function(c){let l=r.prevElementSibling(c);return l!=null&&e(l)}:function(c){let l=r.getSiblings(c),u;for(let h=0;h<l.length;h++){let d=l[h];if(s(c,d))break;r.isTag(d)&&(u=d)}return!!u&&e(u)};case ae.Universal:{if(t.namespace!=null&&t.namespace!=="*")throw new Error("Namespaced universal selectors are not yet supported by css-select");return e}}}function fF(e,t,n){let i=Dg(e,t,n);return aI(i,t.adapter)}function Dg(e,t,n){let i=typeof e=="string"?lf(e):e;return $g(i,t,n)}function mF(e){return e.type===ae.Pseudo&&(e.name==="scope"||Array.isArray(e.data)&&e.data.some(t=>t.some(mF)))}var L1t={type:ae.Descendant},F1t={type:"_flexibleDescendant"},z1t={type:ae.Pseudo,name:"scope",data:null};function D1t(e,{adapter:t},n){let i=!!n?.every(o=>{let r=t.isTag(o)&&t.getParent(o);return o===sI||r&&t.isTag(r)});for(let o of e){if(!(o.length>0&&uf(o[0])&&o[0].type!==ae.Descendant))if(i&&!o.some(mF))o.unshift(L1t);else continue;o.unshift(z1t)}}function $g(e,t,n){var i;e.forEach(Q5),n=(i=t.context)!==null&&i!==void 0?i:n;let o=Array.isArray(n),r=n&&(Array.isArray(n)?n:[n]);if(t.relativeSelector!==!1)D1t(e,t,r);else if(e.some(c=>c.length>0&&uf(c[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let s=!1,a=e.map(c=>{if(c.length>=2){let[l,u]=c;l.type!==ae.Pseudo||l.name!=="scope"||(o&&u.type===ae.Descendant?c[1]=F1t:(u.type===ae.Adjacent||u.type===ae.Sibling)&&(s=!0))}return $1t(c,t,r)}).reduce(j1t,Hs.default.falseFunc);return a.shouldTestNextSiblings=s,a}function $1t(e,t,n){var i;return e.reduce((o,r)=>o===Hs.default.falseFunc?Hs.default.falseFunc:dF(o,r,t,n,$g),(i=t.rootFunc)!==null&&i!==void 0?i:Hs.default.trueFunc)}function j1t(e,t){return t===Hs.default.falseFunc||e===Hs.default.trueFunc?e:e===Hs.default.falseFunc||t===Hs.default.trueFunc?t:function(i){return e(i)||t(i)}}var _F=(e,t)=>e===t,B1t={adapter:Og,equals:_F};function yF(e){var t,n,i,o;let r=e??B1t;return(t=r.adapter)!==null&&t!==void 0||(r.adapter=Og),(n=r.equals)!==null&&n!==void 0||(r.equals=(o=(i=r.adapter)===null||i===void 0?void 0:i.equals)!==null&&o!==void 0?o:_F),r}function pI(e){return function(n,i,o){let r=yF(i);return e(n,r,o)}}var Tzt=pI(fF),Mzt=pI(Dg),Czt=pI($g);function gF(e){return function(n,i,o){let r=yF(o);typeof n!="function"&&(n=Dg(n,r,i));let s=Y1t(i,r.adapter,n.shouldTestNextSiblings);return e(n,s,r)}}function Y1t(e,t,n=!1){return n&&(e=X1t(e,t)),Array.isArray(e)?t.removeSubsets(e):t.getChildren(e)}function X1t(e,t){let n=Array.isArray(e)?e.slice(0):[e],i=n.length;for(let o=0;o<i;o++){let r=cI(n[o],t);n.push(...r)}return n}var hI=gF((e,t,n)=>e===uI.default.falseFunc||!t||t.length===0?[]:n.adapter.findAll(e,t)),jg=gF((e,t,n)=>e===uI.default.falseFunc||!t||t.length===0?null:n.adapter.findOne(e,t));K();vt();K();var WF=Xt(Sn(),1);vt();var JF=Xt(Sn(),1),tz=Xt(Sn(),1);vt();Qr();bI();var xI=(e,t={})=>{let n=e._internal_store;if(!n){n={counts:{}},e._internal_store=n;for(let o of e){let r=o.type,s=o[`${r}_id`];if(!s)continue;let a=Number.parseInt(s.split("_").pop());Number.isNaN(a)||(n.counts[r]=Math.max(n.counts[r]??0,a))}}return new Proxy({},{get:(o,r)=>r==="toArray"?()=>e:{get:s=>e.find(a=>a.type===r&&a[`${r}_id`]===s),getUsing:s=>{let a=Object.keys(s);if(a.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");let c=a[0],l=c.replace("_id",""),u=e.find(h=>h.type===l&&h[c]===s[c]);return u?e.find(h=>h.type===r&&h[`${r}_id`]===u[`${r}_id`]):null},getWhere:s=>{let a=Object.keys(s);return e.find(c=>c.type===r&&a.every(l=>c[l]===s[l]))},list:s=>{let a=s?Object.keys(s):[];return e.filter(c=>c.type===r&&a.every(l=>c[l]===s[l]))},insert:s=>{var l;(l=n.counts)[r]??(l[r]=-1),n.counts[r]++;let a=n.counts[r],c={type:r,[`${r}_id`]:`${r}_${a}`,...s};return t.validateInserts&&(Pl[r]??wl).parse(c),e.push(c),c},delete:s=>{let a=e.find(c=>c[`${r}_id`]===s);a&&e.splice(e.indexOf(a),1)},update:(s,a)=>{let c=e.find(l=>l.type===r&&l[`${r}_id`]===s);if(c)return Object.assign(c,a),c},select:s=>{if(r==="source_component")return e.find(a=>a.type==="source_component"&&a.name===s.replace(/\./g,""));if(r==="pcb_port"||r==="source_port"||r==="schematic_port"){let[a,c]=s.replace(/\./g,"").split(/[\s\>]+/),l=e.find(h=>h.type==="source_component"&&h.name===a);if(!l)return null;let u=e.find(h=>h.type==="source_port"&&h.source_component_id===l.source_component_id&&(h.name===c||(h.port_hints??[]).includes(c)));if(!u)return null;if(r==="source_port")return u;if(r==="pcb_port")return e.find(h=>h.type==="pcb_port"&&h.source_port_id===u.source_port_id);if(r==="schematic_port")return e.find(h=>h.type==="schematic_port"&&h.source_port_id===u.source_port_id)}}}})};xI.unparsed=xI;var Rr=xI;var k$t=Xt(RF(),1);ji();function Or(e){let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,maxX:e.center.x+t,minY:e.center.y-n,maxY:e.center.y+n}}function yf(e,t){let n=Or(e),i=Or(t),o=Math.max(n.minX-i.maxX,i.minX-n.maxX,0),r=Math.max(n.minY-i.maxY,i.minY-n.maxY,0),s={x:0,y:0},a={x:0,y:0};return o===0&&r===0?{distance:0,pointA:e.center,pointB:t.center}:(s.x=Rn(e.center.x,i.minX,i.maxX),s.y=Rn(e.center.y,i.minY,i.maxY),a.x=Rn(t.center.x,n.minX,n.maxX),a.y=Rn(t.center.y,n.minY,n.maxY),{distance:Math.hypot(s.x-a.x,s.y-a.y),pointA:s,pointB:a})}function ts(e,t){return yf(e,t)}function II(e,t){let n=Or(e),i=Or(t),o=Math.max(n.minX-i.maxX,i.minX-n.maxX,0),r=Math.max(n.minY-i.maxY,i.minY-n.maxY,0);return Math.hypot(o,r)}function Rn(e,t,n){return Math.max(t,Math.min(n,e))}function gf(e,t){let n=Number.POSITIVE_INFINITY,i={x:0,y:0},o={x:0,y:0};for(let r of e)for(let s of t){let{distance:a,pointA:c,pointB:l}=yf(r,s);a<n&&(n=a,i=c,o=l)}return{pointA:i,pointB:o,distance:n}}ji();ji();var jF="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var BF=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=jF[n[e]&63];return t};ji();var $l=(e,t)=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y),YF=(e,t)=>{let n=t.x-e.x,i=t.y-e.y;return Math.abs(n)>Math.abs(i)?{dx:Math.sign(n),dy:0}:{dx:0,dy:Math.sign(i)}},UF=(e,t,n)=>Math.abs(e.x-t.x)*Math.abs(n.dx)+Math.abs(e.y-t.y)*Math.abs(n.dy),qF=(e,t=.1)=>`${Math.round(e.x/t)},${Math.round(e.y/t)}`,XF=(e,t)=>Math.abs(e-t)<1e-4,ZF=(e,t,{viaDiameter:n=.5}={})=>{let i=[];for(let o=0;o<e.length-1;o++){let[r,s]=[e[o],e[o+1]],a=o-1>=0?e[o-1]:null,c=XF(r.y,s.y),l=XF(r.x,s.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${t}, start: (${r.x}, ${r.y}), end: (${s.x}, ${s.y})`);let u={type:"rect",layers:[r.layer],center:{x:(r.x+s.x)/2,y:(r.y+s.y)/2},width:c?Math.abs(r.x-s.x):.1,height:l?Math.abs(r.y-s.y):.1,connectedTo:[t]};if(i.push(u),a&&a.layer===r.layer&&r.layer!==s.layer){let h={type:"rect",layers:[r.layer,s.layer],center:{x:r.x,y:r.y},connectedTo:[t],width:n,height:n};i.push(h)}}return i},KF=class{constructor(e){P(this,"obstacles");P(this,"GRID_STEP",.1);this.obstacles=e.map(t=>({...t,left:t.center.x-t.width/2,right:t.center.x+t.width/2,top:t.center.y+t.height/2,bottom:t.center.y-t.height/2}))}getObstacleAt(e,t,n){n??(n=this.GRID_STEP);for(let i of this.obstacles){let o=i.width/2+n,r=i.height/2+n;if(e>=i.center.x-o&&e<=i.center.x+o&&t>=i.center.y-r&&t<=i.center.y+r)return i}return null}isObstacleAt(e,t,n){return this.getObstacleAt(e,t,n)!==null}getDirectionDistancesToNearestObstacle(e,t){let{GRID_STEP:n}=this,i={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let o of this.obstacles)if(o.type==="rect"){let r=o.center.x-o.width/2-n,s=o.center.x+o.width/2+n,a=o.center.y+o.height/2+n,c=o.center.y-o.height/2-n;t>=c&&t<=a&&e>r&&(i.left=Math.min(i.left,e-s)),t>=c&&t<=a&&e<s&&(i.right=Math.min(i.right,r-e)),e>=r&&e<=s&&t<a&&(i.top=Math.min(i.top,c-t)),e>=r&&e<=s&&t>c&&(i.bottom=Math.min(i.bottom,t-a))}return i}getOrthoDirectionCollisionInfo(e,t,{margin:n=0}={}){let{x:i,y:o}=e,{dx:r,dy:s}=t,a=1/0,c=null;for(let l of this.obstacles){let u=l.left-n,h=l.right+n,d=l.top+n,_=l.bottom-n,y=null;r===1&&s===0?o>_&&o<d&&i<l.left&&(y=l.left-i):r===-1&&s===0?o>_&&o<d&&i>l.right&&(y=i-l.right):r===0&&s===1?i>u&&i<h&&o<l.bottom&&(y=l.bottom-o):r===0&&s===-1&&i>u&&i<h&&o>l.top&&(y=o-l.top),y!==null&&y<a&&(a=y,c=l)}return{dx:r,dy:s,wallDistance:a,obstacle:c}}getObstaclesOverlappingRegion(e){let t=[];for(let n of this.obstacles){let{left:i,right:o,top:r,bottom:s}=n;i<=e.maxX&&o>=e.minX&&r<=e.maxY&&s>=e.minY&&t.push(n)}return t}};function W1t(e){if(e.length<4)return e;let t=[{...e[0]}],n=e[0].layer;for(let i=1;i<e.length;i++){let o={start:e[i-1],end:e[i]},r=e[i].route_type==="via"||e[i-1].route_type==="via";if(e[i].layer!==n||r){t.push({...e[i]}),n=e[i].layer;continue}let s=!1,a=null,c=-1;for(let u=0;u<t.length-1;u++){let h={start:t[u],end:t[u+1]};if(h.start.layer===o.start.layer&&h.start.layer===o.start.layer){let d=Z1t(h,o);if(d){s=!0,a={...d,layer:n},c=u;break}}}s&&a&&(t.splice(c+1),t.push(a));let l=t[t.length-1];(l.x!==e[i].x||l.y!==e[i].y)&&t.push(e[i])}return t}function Z1t(e,t){if(e.start.x===e.end.x&&t.start.x===t.end.x||e.start.y===e.end.y&&t.start.y===t.end.y)return null;let n;if(e.start.x===e.end.x){let i=e.start.x,o=t.start.y;n={...e.start,x:i,y:o}}else{let i=t.start.x,o=e.start.y;n={...e.start,x:i,y:o}}return VF(n,e)&&VF(n,t)?n:null}function VF(e,t){return e.x>=Math.min(t.start.x,t.end.x)&&e.x<=Math.max(t.start.x,t.end.x)&&e.y>=Math.min(t.start.y,t.end.y)&&e.y<=Math.max(t.start.y,t.end.y)}function K1t(e){let t=[e[0]];for(let n=1;n<e.length-1;n++){let[i,o,r]=[e[n-1],e[n],e[n+1]];t.push(o),!(o.route_type!=="wire"||i.route_type!=="wire"||r.route_type!=="wire")&&i.layer===o.layer&&o.layer!==r.layer&&t.push({route_type:"via",from_layer:o.layer,to_layer:r.layer,x:o.x,y:o.y})}return t.push(e[e.length-1]),t}var E$t=(0,JF.default)("autorouter:shortenPathWithShortcuts");function J1t(e,t){if(e.length<=2)return e;let n=[e[0]];for(let i=1;i<e.length;i++){let o={start:n[n.length-1],end:e[i]},r=-1,s=o.start.x===o.end.x,a=o.start.y===o.end.y;for(let c=i+1;c<e.length;c++){if(c<=r)continue;let l={start:e[c],end:e[c+1]};if(!l.end)continue;let u=l.start.x===l.end.x,h=l.start.y===l.end.y,d=s&&u,_=a&&h;if(_&&d||!(d||_))continue;let g=!1,x=Math.min(o.start.x,o.end.x),w=Math.max(o.start.x,o.end.x),S=Math.min(l.start.x,l.end.x),T=Math.max(l.start.x,l.end.x),I=Math.min(o.start.y,o.end.y),E=Math.max(o.start.y,o.end.y),M=Math.min(l.start.y,l.end.y),k=Math.max(l.start.y,l.end.y);if(_?g=x<=T&&w>=S:d&&(g=I<=k&&E>=M),!g)continue;let N=[],A=n[n.length-1],R=e[c+2];if(!R)continue;_&&S<w&&R.x===S&&N.push({x:S,y:o.start.y,layer:o.start.layer}),_&&T>x&&R.x===T&&N.push({x:T,y:o.start.y,layer:o.start.layer}),d&&M<E&&R.y===M&&N.push({x:o.start.x,y:M,layer:o.start.layer}),d&&k>I&&R.y===k&&N.push({x:o.start.x,y:k,layer:o.start.layer});let $=null;for(let j of N)if(!(t(A,j)||t(R,j))){$=j;break}if($){n.push($),i=c+1,r=c+1;break}}r===-1&&n.push(e[i])}return n[n.length-1]!==e[e.length-1]&&n.push(e[e.length-1]),n}var Dl=(0,WF.default)("autorouting-dataset:astar"),QF=class{constructor(e){P(this,"openSet",[]);P(this,"closedSet",new Set);P(this,"debug",!1);P(this,"debugSolutions");P(this,"debugMessage",null);P(this,"debugTraceCount",0);P(this,"input");P(this,"obstacles");P(this,"allObstacles");P(this,"startNode");P(this,"goalPoint");P(this,"GRID_STEP");P(this,"OBSTACLE_MARGIN");P(this,"MAX_ITERATIONS");P(this,"isRemovePathLoopsEnabled");P(this,"isShortenPathWithShortcutsEnabled");P(this,"GREEDY_MULTIPLIER",1.1);P(this,"iterations",-1);this.input=e.input,this.allObstacles=e.input.obstacles,this.startNode=e.startNode,this.goalPoint=e.goalPoint?{l:0,...e.goalPoint}:void 0,this.GRID_STEP=e.GRID_STEP??.1,this.OBSTACLE_MARGIN=e.OBSTACLE_MARGIN??.15,this.MAX_ITERATIONS=e.MAX_ITERATIONS??100,this.debug=e.debug??Dl.enabled,this.isRemovePathLoopsEnabled=e.isRemovePathLoopsEnabled??!1,this.isShortenPathWithShortcutsEnabled=e.isShortenPathWithShortcutsEnabled??!1,this.debug&&(Dl.enabled=!0),Dl.enabled&&(this.debugSolutions={},this.debugMessage="")}getNeighbors(e){return[]}isSameNode(e,t){return $l(e,t)<this.GRID_STEP}computeG(e,t){return e.g+$l(e,t)}computeH(e){return $l(e,this.goalPoint)}getNodeName(e){return qF(e,this.GRID_STEP)}solveOneStep(){this.iterations+=1;let{openSet:e,closedSet:t,GRID_STEP:n,goalPoint:i}=this;e.sort((a,c)=>a.f-c.f);let o=e.shift();if(this.computeH(o)<=n*2)return{solved:!0,current:o,newNeighbors:[]};this.closedSet.add(this.getNodeName(o));let s=[];for(let a of this.getNeighbors(o)){if(t.has(this.getNodeName(a)))continue;let c=this.computeG(o,a),l=this.openSet.find(u=>this.isSameNode(u,a));if(!l||c<l.g){let u=this.computeH(a),h=c+u*this.GREEDY_MULTIPLIER,d={...a,g:c,h:u,f:h,obstacleHit:a.obstacleHit??void 0,manDistFromParent:$l(o,a),nodesInPath:o.nodesInPath+1,parent:o,enterMarginCost:a.enterMarginCost,travelMarginCostFactor:a.travelMarginCostFactor};e.push(d),s.push(d)}}return Dl.enabled&&(e.sort((a,c)=>a.f-c.f),this.drawDebugSolution({current:o,newNeighbors:s})),{solved:!1,current:o,newNeighbors:s}}getStartNode(e){return{x:e.pointsToConnect[0].x,y:e.pointsToConnect[0].y,manDistFromParent:0,f:0,g:0,h:0,nodesInPath:0,parent:null}}layerToIndex(e){return 0}indexToLayer(e){return"top"}preprocessConnectionBeforeSolving(e){return e}solveConnection(e){if(e.pointsToConnect.length>2)throw new Error("GeneralizedAstarAutorouter doesn't currently support 2+ points in a connection");e=this.preprocessConnectionBeforeSolving(e);let{pointsToConnect:t}=e;for(this.iterations=0,this.closedSet=new Set,this.startNode=this.getStartNode(e),this.goalPoint={...t[t.length-1],l:this.layerToIndex(t[t.length-1].layer)},this.openSet=[this.startNode];this.iterations<this.MAX_ITERATIONS;){let{solved:n,current:i}=this.solveOneStep();if(n){let o=[],r=i;for(;r;){let s=r.l;o.unshift({x:r.x,y:r.y,layer:s!==void 0?this.indexToLayer(s):t[0].layer}),r=r.parent}return Dl.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations
|
|
160
160
|
`),this.isRemovePathLoopsEnabled&&(o=W1t(o)),this.isShortenPathWithShortcutsEnabled&&(o=J1t(o,(s,a)=>{if(s.x===a.x&&s.y===a.y)return!1;let c=this.obstacles.getOrthoDirectionCollisionInfo({x:s.x,y:s.y,l:this.layerToIndex(s.layer)??0},{dx:Math.sign(a.x-s.x),dy:Math.sign(a.y-s.y),dl:0},{margin:.05}),l=Math.sqrt((s.x-a.x)**2+(s.y-a.y)**2);return c.wallDistance<l})),{solved:!0,route:o,connectionName:e.name}}if(this.openSet.length===0)break}return Dl.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations (failed)
|
|
161
|
-
`),{solved:!1,connectionName:e.name}}createObstacleList({dominantLayer:e,connection:t,obstaclesFromTraces:n}){return new KF(this.allObstacles.filter(i=>!i.connectedTo.includes(t.name)).filter(i=>i.layers.includes(e)).concat(n??[]))}postprocessConnectionSolveResult(e,t){return t}solve(){let e=[],t=[];this.debugTraceCount=0;for(let n of this.input.connections){let i=n.pointsToConnect[0].layer??"top";this.debugTraceCount+=1,this.obstacles=this.createObstacleList({dominantLayer:i,connection:n,obstaclesFromTraces:t});let o=this.solveConnection(n);o=this.postprocessConnectionSolveResult(n,o),e.push(o),Dl.enabled&&this.drawDebugTraceObstacles(t),o.solved&&t.push(...ZF(o.route.map(r=>({x:r.x,y:r.y,layer:r.layer??i})),n.name))}return e}solveAndMapToTraces(){return this.solve().flatMap(t=>t.solved?[{type:"pcb_trace",pcb_trace_id:`pcb_trace_for_${t.connectionName}`,route:K1t(t.route.map(n=>({route_type:"wire",x:n.x,y:n.y,width:this.input.minTraceWidth,layer:n.layer})))}]:[])}getDebugGroup(){let e=`t${this.debugTraceCount}_iter[${this.iterations-1}]`;return this.iterations<30||this.iterations<100&&this.iterations%10===0||this.iterations<1e3&&this.iterations%100===0||!this.debugSolutions?e:null}drawDebugTraceObstacles(e){let{debugTraceCount:t,debugSolutions:n}=this;for(let i in n)i.startsWith(`t${t}_`)&&n[i].push(...e.map((o,r)=>({type:"pcb_smtpad",pcb_component_id:"",layer:o.layers[0],width:o.width,shape:"rect",x:o.center.x,y:o.center.y,pcb_smtpad_id:`trace_obstacle_${r}`,height:o.height})))}drawDebugSolution({current:e,newNeighbors:t}){let n=this.getDebugGroup();if(!n)return;let{openSet:i,debugTraceCount:o,debugSolutions:r}=this;r[n]??(r[n]=[]);let s=r[n];s.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${e.x}_${e.y}`,font:"tscircuit2024",font_size:.25,text:"X"+(e.l!==void 0?e.l:""),pcb_component_id:"",layer:"top",anchor_position:{x:e.x,y:e.y},anchor_alignment:"center"});for(let a=0;a<i.length;a++){let c=i[a];s.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${c.x}_${c.y}`,layer:"top",route:[[0,.05],[.05,0],[0,-.05],[-.05,0],[0,.05]].map(([l,u])=>({x:c.x+l,y:c.y+u})),stroke_width:.01}),s.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${c.x}_${c.y}`,font:"tscircuit2024",font_size:.03,text:a.toString(),pcb_component_id:"",layer:"top",anchor_position:{x:c.x,y:c.y},anchor_alignment:"center"})}if(e.parent){let a=[],c=e;for(;c;)a.unshift(c),c=c.parent;s.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${e.x}_${e.y}`,layer:"top",route:a,stroke_width:.01})}}},Q1t=(0,tz.default)("autorouting-dataset:infinite-grid-ijump-astar:get-distance-to-overcome-obstacle");function TI({node:e,travelDir:t,wallDir:n,obstacle:i,obstacles:o,obstaclesInRow:r=0,OBSTACLE_MARGIN:s=.15,SHOULD_DETECT_CONJOINED_OBSTACLES:a=!1,MAX_CONJOINED_OBSTACLES:c=20}){let l;if(t.dx===0?t.dy>0?l=i.center.y+i.height/2-e.y:l=e.y-(i.center.y-i.height/2):t.dx>0?l=i.center.x+i.width/2-e.x:l=e.x-(i.center.x-i.width/2),l+=s,a&&r<c){let u=o.getObstacleAt(e.x+t.dx*l+n.dx*(n.wallDistance+.001),e.y+t.dy*l+n.dy*(n.wallDistance+.001));if(u===i)return l;if(u&&u.type==="rect"){let h=t.dy===0,d=h?i.height:i.width;if((h?u.height:u.width)>d)return Q1t("next obstacle on path is bigger, not trying to overcome it"),l;let y=TI({node:{x:e.x+t.dx*l,y:e.y+t.dy*l},travelDir:t,wallDir:n,obstacle:u,obstacles:o,obstaclesInRow:r+1,SHOULD_DETECT_CONJOINED_OBSTACLES:a,MAX_CONJOINED_OBSTACLES:c,OBSTACLE_MARGIN:s});l+=y}}return l}var t_t=class extends QF{constructor(){super(...arguments);P(this,"MAX_ITERATIONS",200)}getNeighbors(t){let n=this.obstacles,i=this.goalPoint,o;t.parent?o=YF(t.parent,t):o=YF(t,i);let r=[{dx:0,dy:1},{dx:1,dy:0},{dx:0,dy:-1},{dx:-1,dy:0}].filter(a=>a.dx===o.dx*-1&&a.dy===o.dy*-1?!1:!(a.dx===o.dx&&a.dy===o.dy&&t.parent?.obstacleHit)).map(a=>n.getOrthoDirectionCollisionInfo(t,a,{margin:this.OBSTACLE_MARGIN})).filter(a=>a.wallDistance>=this.OBSTACLE_MARGIN),s=[];for(let a of r){let c=null;t?.obstacleHit&&(c=TI({node:t,travelDir:a,wallDir:{...o,wallDistance:this.OBSTACLE_MARGIN},obstacle:t.obstacleHit,obstacles:n,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let l=UF(t,i,a),u=(a.dx===0||Math.sign(i.x-t.x)===a.dx)&&(a.dy===0||Math.sign(i.y-t.y)===a.dy);l<a.wallDistance&&l>0&&u?s.push({...a,travelDistance:l}):c!==null&&c<a.wallDistance?s.push({...a,travelDistance:c}):a.wallDistance!==1/0&&s.push({...a,travelDistance:a.wallDistance-this.OBSTACLE_MARGIN})}return s.filter(a=>!n.isObstacleAt(t.x+a.dx*a.travelDistance,t.y+a.dy*a.travelDistance)).map(a=>({x:t.x+a.dx*a.travelDistance,y:t.y+a.dy*a.travelDistance,obstacleHit:a.obstacle}))}};function e_t(e,t=4){let{center:n,width:i,height:o,rotation:r}=e,s=[],a=r*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(r%360+360)%360;if(o<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*c,x=-y*l,w=d*1.1,S=Math.abs(o*c)+Math.abs(d*l);s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}else{let d=o/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*l,x=y*c,w=Math.abs(i*c)+Math.abs(d*l),S=d*1.1;s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}return s}var Gg=["top","inner1","inner2","bottom"],ez=(e,t)=>{let n=o=>t?o.concat(o.map(r=>t?.getNetConnectedToId(r)).filter(Boolean)):o,i=[];for(let o of e)if(o.type==="pcb_smtpad"){if(o.shape==="circle")i.push({type:"oval",layers:[o.layer],center:{x:o.x,y:o.y},width:o.radius*2,height:o.radius*2,connectedTo:n([o.pcb_smtpad_id])});else if(o.shape==="rect")i.push({type:"rect",layers:[o.layer],center:{x:o.x,y:o.y},width:o.width,height:o.height,connectedTo:n([o.pcb_smtpad_id])});else if(o.shape==="rotated_rect"){let r={center:{x:o.x,y:o.y},width:o.width,height:o.height,rotation:o.ccw_rotation},s=e_t(r);for(let a of s)i.push({type:"rect",layers:[o.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([o.pcb_smtpad_id])})}}else if(o.type==="pcb_keepout")o.shape==="circle"?i.push({type:"oval",layers:o.layers,center:{x:o.center.x,y:o.center.y},width:o.radius*2,height:o.radius*2,connectedTo:[]}):o.shape==="rect"&&i.push({type:"rect",layers:o.layers,center:{x:o.center.x,y:o.center.y},width:o.width,height:o.height,connectedTo:[]});else if(o.type==="pcb_hole")o.hole_shape==="oval"?i.push({type:"oval",center:{x:o.x,y:o.y},width:o.hole_width,height:o.hole_height,connectedTo:[]}):o.hole_shape==="square"?i.push({type:"rect",layers:Gg,center:{x:o.x,y:o.y},width:o.hole_diameter,height:o.hole_diameter,connectedTo:[]}):(o.hole_shape==="round"||o.hole_shape==="circle")&&i.push({type:"rect",layers:Gg,center:{x:o.x,y:o.y},width:o.hole_diameter,height:o.hole_diameter,connectedTo:[]});else if(o.type==="pcb_plated_hole")o.shape==="circle"?i.push({type:"oval",layers:Gg,center:{x:o.x,y:o.y},width:o.outer_diameter,height:o.outer_diameter,connectedTo:n([o.pcb_plated_hole_id])}):(o.shape==="oval"||o.shape==="pill")&&i.push({type:"oval",layers:Gg,center:{x:o.x,y:o.y},width:o.outer_width,height:o.outer_height,connectedTo:n([o.pcb_plated_hole_id])});else if(o.type==="pcb_trace"){let r=ZF(o.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),o.source_trace_id);i.push(...r)}else o.type==="pcb_via"&&i.push({type:"rect",layers:o.layers,center:{x:o.x,y:o.y},connectedTo:[],width:o.outer_diameter,height:o.outer_diameter});return i};function HF(e){let{pcbConnMap:t,goalElementId:n}=e;if(!n.startsWith("pcb_port_"))throw new Error(`Currently alternative goal boxes must have a goal id with prefix "pcb_port_" (got ${n})`);let i=t.getAllTracesConnectedToPort(n);return ez(i).map(o=>({...o,connectedTo:[n]}))}var nz=e=>{let{connection:t,pcbConnMap:n}=e;if(t.pointsToConnect.length!==2)throw new Error(`Connection must have exactly 2 points for alternative goal boxes (got ${t.pointsToConnect.length})`);let[i,o]=t.pointsToConnect;if(!i.pcb_port_id||!o.pcb_port_id)throw new Error(`Connection points must have pcb_port_id for alternative goal box calculation (got ${i.pcb_port_id} and ${o.pcb_port_id})`);let r=HF({goalElementId:i.pcb_port_id,pcbConnMap:n}).concat([{center:i,width:.01,height:.01,connectedTo:[i.pcb_port_id],layers:[i.layer],type:"rect"}]),s=HF({goalElementId:o.pcb_port_id,pcbConnMap:n}).concat([{center:o,width:.01,height:.01,connectedTo:[o.pcb_port_id],layers:[o.layer],type:"rect"}]);if(r.length<=1&&s.length<=1)return{...t,startPoint:i,endPoint:o,goalBoxes:[]};let a=gf(r,s),c,l,u;return r.length>=s.length?(c={...o,...a.pointB},l={...i,...a.pointA},u=r):(c={...i,...a.pointA},l={...o,...a.pointB},u=s),{startPoint:c,endPoint:l,goalBoxes:u,name:t.name,pointsToConnect:[c,l]}},n_t=(e,t={})=>{let n={minTraceWidth:.1};n.layerCount=t.layerCount??1,n.obstacles=ez(e,t.connMap),n.connections=[];for(let o of e)if(o.type==="source_trace"){let r={name:o.source_trace_id,pointsToConnect:o.connected_source_port_ids.map(s=>{let a=Rr(e).pcb_port.getWhere({source_port_id:s});if(!a)throw new Error(`Could not find pcb_port for source_port_id "${s}"`);return{x:a.x,y:a.y,layer:a.layers?.[0]??"top",pcb_port_id:a.pcb_port_id}})};if(t.optimizeWithGoalBoxes){let s=new Hg(e);r=nz({connection:r,pcbConnMap:s})}n.connections.push(r),i_t(n.obstacles,r.pointsToConnect,r.name)}let i={minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0};for(let o of n.obstacles)i.minX=Math.min(i.minX,o.center.x-o.width/2),i.maxX=Math.max(i.maxX,o.center.x+o.width/2),i.minY=Math.min(i.minY,o.center.y-o.height/2),i.maxY=Math.max(i.maxY,o.center.y+o.height/2);for(let o of n.connections)for(let r of o.pointsToConnect)i.minX=Math.min(i.minX,r.x),i.maxX=Math.max(i.maxX,r.x),i.minY=Math.min(i.minY,r.y),i.maxY=Math.max(i.maxY,r.y);return n.bounds=i,n},i_t=(e,t,n)=>{for(let i of t)for(let o of e)o_t(i,o)&&o.connectedTo.push(n)};function o_t(e,t){let n=t.width/2,i=t.height/2;if(t.type==="rect")return e.x>=t.center.x-n&&e.x<=t.center.x+n&&e.y>=t.center.y-i&&e.y<=t.center.y+i;if(t.type==="oval"){let o=(e.x-t.center.x)/n,r=(e.y-t.center.y)/i;return o*o+r*r<=1}return!1}function GF(e,t){let n=t.x>e.x?1:t.x<e.x?-1:0,i=t.y>e.y?1:t.y<e.y?-1:0,o=t.l>e.l?1:t.l<e.l?-1:0;return{dx:n,dy:i,dl:o}}var MI={1:["top"],2:["top","bottom"],4:["top","inner1","inner2","bottom"]},r_t=e=>MI[e];function iz(e,t){let i=MI[e].indexOf(t);if(i===-1)throw new Error(`Invalid layer for getLayerIndex (for layerCount === ${e}): "${t}"`);return i}function s_t(e,t){let i=MI[e][t];if(!i)throw new Error(`Invalid index for indexToLayer (for layerCount === ${e}): "${t}"`);return i}var a_t=class extends KF{constructor(t,n){super([]);P(this,"obstacles");P(this,"GRID_STEP",.1);P(this,"layerCount");this.layerCount=t;let i=r_t(t);this.obstacles=n.flatMap(o=>o.layers.filter(r=>i.includes(r)).map(r=>({...o,left:o.center.x-o.width/2,right:o.center.x+o.width/2,top:o.center.y+o.height/2,bottom:o.center.y-o.height/2,l:iz(t,r)})))}getObstacleAt(t,n,i,o){o??(o=this.GRID_STEP);for(let r of this.obstacles){if(r.l!==i)continue;let s=r.width/2+o,a=r.height/2+o;if(t>=r.center.x-s&&t<=r.center.x+s&&n>=r.center.y-a&&n<=r.center.y+a)return r}return null}isObstacleAt(t,n,i,o){return this.getObstacleAt(t,n,i,o)!==null}getDirectionDistancesToNearestObstacle3d(t,n,i){let{GRID_STEP:o}=this,r={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let s of this.obstacles)if(s.l===i&&s.type==="rect"){let a=s.center.x-s.width/2-o,c=s.center.x+s.width/2+o,l=s.center.y+s.height/2+o,u=s.center.y-s.height/2-o;n>=u&&n<=l&&t>a&&(r.left=Math.min(r.left,t-c)),n>=u&&n<=l&&t<c&&(r.right=Math.min(r.right,a-t)),t>=a&&t<=c&&n<l&&(r.top=Math.min(r.top,u-n)),t>=a&&t<=c&&n>u&&(r.bottom=Math.min(r.bottom,n-l))}return r}getOrthoDirectionCollisionInfo(t,n,{margin:i=0}={}){let{x:o,y:r,l:s}=t,{dx:a,dy:c,dl:l}=n,u=1/0,h=null;if(l!==0){let d=s+l;return this.isObstacleAt(o,r,d,i)?(u=1,h=this.getObstacleAt(o,r,d,i)):u=1,{dx:a,dy:c,dl:l,wallDistance:u,obstacle:h}}else{for(let d of this.obstacles){if(d.l!==s)continue;let _=d.left-i,y=d.right+i,g=d.top+i,x=d.bottom-i,w=null;a===1&&c===0?r>x&&r<g&&o<d.left&&(w=d.left-o):a===-1&&c===0?r>x&&r<g&&o>d.right&&(w=o-d.right):a===0&&c===1?o>_&&o<y&&r<d.bottom&&(w=d.bottom-r):a===0&&c===-1&&o>_&&o<y&&r>d.top&&(w=r-d.top),w!==null&&w<u&&(u=w,h=d)}return{dx:a,dy:c,dl:0,wallDistance:u,obstacle:h}}}getObstaclesOverlappingRegion(t){let n=[];for(let i of this.obstacles){if(i.l!==t.l)continue;let{left:o,right:r,top:s,bottom:a}=i;o<=t.maxX&&r>=t.minX&&s>=t.minY&&a<=t.maxY&&n.push(i)}return n}},Ug=class extends QF{constructor(t){super(t);P(this,"MAX_ITERATIONS",500);P(this,"VIA_COST",4);P(this,"VIA_DIAMETER",.5);P(this,"allowLayerChange",!0);P(this,"layerCount");P(this,"obstacles");P(this,"optimizeWithGoalBoxes");P(this,"connMap");P(this,"pcbConnMap");P(this,"GOAL_RUSH_FACTOR",1.1);P(this,"defaultGoalViaMargin",.5);P(this,"marginsWithCosts");this.layerCount=t.input.layerCount??2,this.MAX_ITERATIONS=t.MAX_ITERATIONS??this.MAX_ITERATIONS,this.VIA_COST=t.VIA_COST??this.VIA_COST,this.connMap=t.connMap,this.pcbConnMap=t.pcbConnMap??new Hg,this.optimizeWithGoalBoxes=t.optimizeWithGoalBoxes??!1,this.obstacles=null,this.marginsWithCosts=t.marginsWithCosts??[{margin:1,enterCost:0,travelCostFactor:1},{margin:this.OBSTACLE_MARGIN,enterCost:10,travelCostFactor:2}]}get largestMargin(){return this.marginsWithCosts[0].margin}preprocessConnectionBeforeSolving(t){return this.optimizeWithGoalBoxes?nz({connection:t,pcbConnMap:this.pcbConnMap}):t}postprocessConnectionSolveResult(t,n){if(!n.solved)return n;if(this.optimizeWithGoalBoxes){let i=n.route.map(o=>({x:o.x,y:o.y,route_type:"wire",layer:o.layer,width:this.input.minTraceWidth}));i[0].start_pcb_port_id=t.pointsToConnect[0].pcb_port_id,i[i.length-1].end_pcb_port_id=t.pointsToConnect[1].pcb_port_id,this.pcbConnMap.addTrace({type:"pcb_trace",pcb_trace_id:`postprocess_trace_${BF(8)}`,route:i})}return n}createObstacleList({dominantLayer:t,connection:n,obstaclesFromTraces:i}){let o=this.connMap?this.connMap.getNetConnectedToId(n.name):n.name;if(!o)throw new Error(`The connection.name "${n.name}" wasn't present in the full connectivity map`);return new a_t(this.layerCount,this.allObstacles.filter(r=>!r.connectedTo.includes(o)).concat(i??[]))}computeG(t,n){let i=t.g+$l(t,n)*(t.travelMarginCostFactor??1)+(n.enterMarginCost??0);return(n.l??t.l!==-1??-1)&&(i+=this.VIA_COST),i}computeH(t){let n=Math.abs(t.x-this.goalPoint.x),i=Math.abs(t.y-this.goalPoint.y),o=Math.abs(t.l-this.goalPoint.l);return(n+i)**this.GOAL_RUSH_FACTOR+o*this.VIA_COST}getStartNode(t){return{...super.getStartNode(t),l:this.layerToIndex(t.pointsToConnect[0].layer)}}layerToIndex(t){return iz(this.layerCount,t)}indexToLayer(t){return s_t(this.layerCount,t)}getNodeName(t){return`${qF(t,this.GRID_STEP)}-${t.l??0}`}hasSpaceForVia(t,n){return t.every(i=>this.obstacles.getObstaclesOverlappingRegion({minX:n.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:n.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:n.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:n.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:i}).length===0)}getNeighborsSurroundingGoal(t){let n=this.obstacles,i=this.goalPoint,o=[],r=[{dx:1,dy:0,dl:0},{dx:-1,dy:0,dl:0},{dx:0,dy:1,dl:0},{dx:0,dy:-1,dl:0}],s=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin;for(let a of r){let c={x:t.x+a.dx*s,y:t.y+a.dy*s,l:t.l+a.dl,obstacleHit:null};this.hasSpaceForVia([t.l,i.l],c)&&o.push(c)}return o}getNeighbors(t){let n=this.obstacles,i=this.goalPoint,o=$l(t,i);if(o<=this.OBSTACLE_MARGIN)return this.getNeighborsSurroundingGoal(t);let r;t.parent?r=GF(t.parent,t):r=GF(t,i);let s=[{dx:0,dy:1,dl:0},{dx:1,dy:0,dl:0},{dx:0,dy:-1,dl:0},{dx:-1,dy:0,dl:0}],a=o>this.VIA_DIAMETER+this.OBSTACLE_MARGIN,c=$l(t,this.startNode)>this.VIA_DIAMETER+this.OBSTACLE_MARGIN;this.allowLayerChange&&a&&c&&(t.l<this.layerCount-1&&s.push({dx:0,dy:0,dl:1}),t.l>0&&s.push({dx:0,dy:0,dl:-1}));let l=s.filter(h=>h.dx===r.dx*-1&&h.dy===r.dy*-1&&h.dl===r.dl*-1?!1:!(h.dx===r.dx&&h.dy===r.dy&&h.dl===r.dl&&t.parent?.obstacleHit)).map(h=>n.getOrthoDirectionCollisionInfo(t,h,{margin:this.OBSTACLE_MARGIN})).filter(h=>!(h.wallDistance<this.OBSTACLE_MARGIN)),u=[];for(let h of l){let d=h.dx===0&&h.dy===0&&h.dl===1,_=h.dx===0&&h.dy===0&&h.dl===-1;if((d||_)&&![t.l,t.l+h.dl].every(S=>n.getObstaclesOverlappingRegion({minX:t.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:t.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:t.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:t.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:S}).length===0))continue;if(d){t.l<this.layerCount-1&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}if(_){t.l>0&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}let y=null;t?.obstacleHit&&(y=TI({node:t,travelDir:h,wallDir:{...r,wallDistance:this.OBSTACLE_MARGIN},obstacle:t.obstacleHit,obstacles:n,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let g=UF(t,i,h),x=(h.dx===0||Math.sign(i.x-t.x)===h.dx)&&(h.dy===0||Math.sign(i.y-t.y)===h.dy);if(g<h.wallDistance&&g>0&&x){let w=t.l===i.l,S=0;!w&&Math.abs(g-o)<this.GRID_STEP&&(S=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin),u.push({...h,travelDistance:g-S,enterMarginCost:0,travelMarginCostFactor:1})}else if(y!==null&&y<h.wallDistance){for(let{margin:w,enterCost:S,travelCostFactor:T}of this.marginsWithCosts)y-this.OBSTACLE_MARGIN+w*2<h.wallDistance&&u.push({...h,travelDistance:y-this.OBSTACLE_MARGIN+w,enterMarginCost:S,travelMarginCostFactor:T});if(h.wallDistance===1/0)u.push({...h,travelDistance:g,enterMarginCost:0,travelMarginCostFactor:1});else if(h.wallDistance>this.largestMargin)for(let{margin:w,enterCost:S,travelCostFactor:T}of this.marginsWithCosts)h.wallDistance>this.largestMargin+w&&u.push({...h,travelDistance:h.wallDistance-w,enterMarginCost:S,travelMarginCostFactor:T})}else if(h.wallDistance!==1/0)for(let{margin:w,enterCost:S,travelCostFactor:T}of this.marginsWithCosts)h.wallDistance>w&&u.push({...h,travelDistance:h.wallDistance-w,enterMarginCost:S,travelMarginCostFactor:T})}return u.map(h=>({x:t.x+h.dx*h.travelDistance,y:t.y+h.dy*h.travelDistance,l:t.l+h.dl,obstacleHit:h.obstacle,travelMarginCostFactor:h.travelMarginCostFactor,enterMarginCost:h.enterMarginCost}))}};function oz(e){let t=n_t(e),n=new t_t({input:t});return{solution:n.solveAndMapToTraces(),debugSolutions:n.debugSolutions,debugMessage:n.debugMessage}}K();K();vt();K();K();vt();vt();K();K();vt();K();K();K();K();vt();K();K();K();vt();K();K();vt();K();K();K();K();K();K();K();K();K();K();vt();K();vt();K();vt();K();K();vt();vt();K();vt();K();K();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();K();K();K();K();K();K();vt();K();vt();K();K();vt();K();vt();K();K();K();vt();K();vt();vt();K();K();K();vt();K();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();vt();K();vt();K();vt();K();K();vt();vt();K();K();vt();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();vt();K();vt();K();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();var Ct=e=>{};Ct("extra props b");Ct("missing props b");Ct(!0);Ct("property a has mismatched types");var c_t=p.enum(["up","down","left","right"]),U$t=p.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);Ct(!0);Ct(!0);var es=p.array(p.string().or(p.number()));Ct(!0);var Zg=p.object({x:Y,y:Y,z:Y}),l_t=p.object({x:p.union([p.number(),p.string()]),y:p.union([p.number(),p.string()]),z:p.union([p.number(),p.string()])}),Qa=p.object({rotationOffset:p.number().or(l_t).optional(),positionOffset:Zg.optional(),size:Zg.optional(),modelUnitToMmScale:Y.optional(),zOffsetFromSurface:Y.optional()});Ct(!0);var u_t=Qa.extend({stlUrl:p.string()}),p_t=Qa.extend({objUrl:p.string(),mtlUrl:p.string().optional()}),h_t=Qa.extend({gltfUrl:p.string()}),d_t=Qa.extend({glbUrl:p.string()}),f_t=Qa.extend({stepUrl:p.string()}),m_t=Qa.extend({wrlUrl:p.string()}),__t=Qa.extend({jscad:p.record(p.any())}),hz=p.union([p.null(),p.string(),p.custom(e=>e&&typeof e=="object"&&"type"in e&&"props"in e),u_t,p_t,h_t,d_t,f_t,m_t,__t]);Ct(!0);var y_t=p.custom(e=>!0),NI=p.object({silkscreenFontSize:Y.optional(),silkscreenTextPosition:p.union([p.enum(["centered","outside","none"]),p.object({offsetX:p.number(),offsetY:p.number()})]).optional(),silkscreenTextVisibility:p.enum(["hidden","visible","inherit"]).optional()});Ct(!0);var g_t=p.custom(e=>!0),Oe=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbRotation:Be.optional(),pcbPositionAnchor:p.string().optional(),pcbPositionMode:p.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),layer:se.optional(),pcbMarginTop:Y.optional(),pcbMarginRight:Y.optional(),pcbMarginBottom:Y.optional(),pcbMarginLeft:Y.optional(),pcbMarginX:Y.optional(),pcbMarginY:Y.optional(),pcbStyle:NI.optional(),pcbRelative:p.boolean().optional(),relative:p.boolean().optional()});Ct(!0);var Kg=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbRotation:Be.optional(),pcbPositionAnchor:p.string().optional(),pcbPositionMode:p.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),pcbMarginTop:Y.optional(),pcbMarginRight:Y.optional(),pcbMarginBottom:Y.optional(),pcbMarginLeft:Y.optional(),pcbMarginX:Y.optional(),pcbMarginY:Y.optional(),pcbStyle:NI.optional(),schMarginTop:Y.optional(),schMarginRight:Y.optional(),schMarginBottom:Y.optional(),schMarginLeft:Y.optional(),schMarginX:Y.optional(),schMarginY:Y.optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Be.optional(),layer:se.optional(),footprint:y_t.optional(),symbol:g_t.optional(),relative:p.boolean().optional(),schRelative:p.boolean().optional(),pcbRelative:p.boolean().optional()});Ct(!0);var b_t=p.object({supplierPartNumbers:p.record(Mp,p.array(p.string())).optional()});Ct(!0);var x_t=p.object({providesPower:p.boolean().optional(),requiresPower:p.boolean().optional(),providesGround:p.boolean().optional(),requiresGround:p.boolean().optional(),providesVoltage:p.union([p.string(),p.number()]).optional(),requiresVoltage:p.union([p.string(),p.number()]).optional(),doNotConnect:p.boolean().optional(),includeInBoardPinout:p.boolean().optional(),highlightColor:p.string().optional()});Ct(!0);var Dn=Kg.merge(b_t).extend({key:p.any().optional(),name:p.string(),cadModel:hz.optional(),children:p.any().optional(),symbolName:p.string().optional(),doNotPlace:p.boolean().optional(),obstructsWithinBounds:p.boolean().optional().describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath"),pinAttributes:p.record(p.string(),x_t).optional()});Ct(!0);var kI=["pin1","left","pin2","right"],Jg=["pin1","left","anode","pos","pin2","right","cathode","neg"],sjt=Y.or(p.enum(["2x","3x","4x"])),tc=p.enum(["vertical","horizontal","pos_top","pos_bottom","pos_left","pos_right","neg_top","neg_bottom","neg_left","neg_right"]).describe("horizontal means pins go 1->2 rightward and vertical means pins go 1->2 downward (generally, positive on top)");Ct(!0);var qg=p.object({pins:p.array(p.union([p.number(),p.string()])),direction:p.union([p.literal("top-to-bottom"),p.literal("left-to-right"),p.literal("bottom-to-top"),p.literal("right-to-left")])}),xf=p.object({leftSize:p.number().optional().describe("@deprecated, use leftPinCount"),topSize:p.number().optional().describe("@deprecated, use topPinCount"),rightSize:p.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:p.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftSide:qg.optional(),rightSide:qg.optional(),topSide:qg.optional(),bottomSide:qg.optional()}),AI=xf;Ct(!0);var vf=p.record(p.object({marginLeft:Y.optional(),marginRight:Y.optional(),marginTop:Y.optional(),marginBottom:Y.optional(),leftMargin:Y.optional(),rightMargin:Y.optional(),topMargin:Y.optional(),bottomMargin:Y.optional()}));Ct(!0);var ur=p.string().regex(/^[A-Za-z0-9_]+$/),Zp=p.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),Gs=p.object({x:Y,y:Y}),Sf=p.object({edit_event_id:p.string(),in_progress:p.boolean().optional(),created_at:p.number()});Ct(!0);var v_t=Sf.extend({pcb_edit_event_type:p.literal("edit_component_location").describe("deprecated"),edit_event_type:p.literal("edit_pcb_component_location"),pcb_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var S_t=Sf.extend({pcb_edit_event_type:p.literal("edit_trace_hint").describe("deprecated"),edit_event_type:p.literal("edit_pcb_trace_hint").optional(),pcb_port_id:p.string(),pcb_trace_hint_id:p.string().optional(),route:p.array(p.object({x:p.number(),y:p.number(),via:p.boolean().optional()}))});Ct(!0);var w_t=Sf.extend({edit_event_type:p.literal("edit_schematic_component_location"),schematic_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var wjt=Sf.extend({edit_event_type:p.literal("edit_pcb_group_location"),pcb_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var Ijt=Sf.extend({edit_event_type:p.literal("edit_schematic_group_location"),schematic_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var Mjt=p.union([v_t,S_t,w_t]);Ct(!0);var P_t=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:qt});Ct(!0);var I_t=p.object({pcb_port_selector:p.string(),offsets:p.array(Fi)});Ct(!0);var T_t=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:qt});Ct(!0);var M_t=p.object({pcb_placements:p.array(P_t).optional(),manual_trace_hints:p.array(I_t).optional(),schematic_placements:p.array(T_t).optional()});Ct(!0);var Kp=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),jl=e=>p.record(p.enum(e),Kp),bf=p.object({layoutMode:p.enum(["grid","flex","match-adapt","relative","none"]).optional(),position:p.enum(["absolute","relative"]).optional(),grid:p.boolean().optional(),gridCols:p.number().or(p.string()).optional(),gridRows:p.number().or(p.string()).optional(),gridTemplateRows:p.string().optional(),gridTemplateColumns:p.string().optional(),gridTemplate:p.string().optional(),gridGap:p.number().or(p.string()).optional(),gridRowGap:p.number().or(p.string()).optional(),gridColumnGap:p.number().or(p.string()).optional(),flex:p.boolean().or(p.string()).optional(),flexDirection:p.enum(["row","column"]).optional(),alignItems:p.enum(["start","center","end","stretch"]).optional(),justifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),flexRow:p.boolean().optional(),flexColumn:p.boolean().optional(),gap:p.number().or(p.string()).optional(),pack:p.boolean().optional().describe("Pack the contents of this group using a packing strategy"),packOrderStrategy:p.enum(["largest_to_smallest","first_to_last","highest_to_lowest_pin_count"]).optional(),packPlacementStrategy:p.enum(["shortest_connection_along_outline"]).optional(),padding:D.optional(),paddingLeft:D.optional(),paddingRight:D.optional(),paddingTop:D.optional(),paddingBottom:D.optional(),paddingX:D.optional(),paddingY:D.optional(),width:D.optional(),height:D.optional(),matchAdapt:p.boolean().optional(),matchAdaptTemplate:p.any().optional()});Ct(!0);var rz=p.object({strokeWidth:D.optional(),dashed:p.boolean().optional(),solid:p.boolean().optional()}),C_t=p.custom(e=>typeof e=="string"),E_t=p.object({serverUrl:p.string().optional(),inputFormat:p.enum(["simplified","circuit-json"]).optional(),serverMode:p.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:p.boolean().optional(),cache:p.custom(e=>!0).optional(),traceClearance:D.optional(),groupMode:p.enum(["sequential_trace","subcircuit","sequential-trace"]).optional(),algorithmFn:p.custom(e=>typeof e=="function"||e===void 0).optional(),preset:p.enum(["sequential_trace","subcircuit","auto","auto_local","auto_cloud","freerouting","laser_prefab","sequential-trace","auto-local","auto-cloud"]).optional(),local:p.boolean().optional()}),N_t=p.union([p.literal("sequential_trace"),p.literal("subcircuit"),p.literal("auto"),p.literal("auto_local"),p.literal("auto_cloud"),p.literal("freerouting"),p.literal("laser_prefab"),p.literal("sequential-trace"),p.literal("auto-local"),p.literal("auto-cloud")]),k_t=p.string(),dz=p.union([E_t,N_t,k_t]),RI=Kg.extend({name:p.string().optional(),children:p.any().optional(),schTitle:p.string().optional(),key:p.any().optional(),showAsSchematicBox:p.boolean().optional(),connections:p.record(p.string(),Kp.optional()).optional(),schPinArrangement:AI.optional(),schPinSpacing:D.optional(),schPinStyle:vf.optional(),...bf.shape,grid:bf.shape.grid.describe("@deprecated use pcbGrid"),flex:bf.shape.flex.describe("@deprecated use pcbFlex"),pcbGrid:p.boolean().optional(),pcbGridCols:p.number().or(p.string()).optional(),pcbGridRows:p.number().or(p.string()).optional(),pcbGridTemplateRows:p.string().optional(),pcbGridTemplateColumns:p.string().optional(),pcbGridTemplate:p.string().optional(),pcbGridGap:p.number().or(p.string()).optional(),pcbGridRowGap:p.number().or(p.string()).optional(),pcbGridColumnGap:p.number().or(p.string()).optional(),pcbFlex:p.boolean().or(p.string()).optional(),pcbFlexGap:p.number().or(p.string()).optional(),pcbFlexDirection:p.enum(["row","column"]).optional(),pcbAlignItems:p.enum(["start","center","end","stretch"]).optional(),pcbJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),pcbFlexRow:p.boolean().optional(),pcbFlexColumn:p.boolean().optional(),pcbGap:p.number().or(p.string()).optional(),pcbPack:p.boolean().optional(),pcbPackGap:p.number().or(p.string()).optional(),schGrid:p.boolean().optional(),schGridCols:p.number().or(p.string()).optional(),schGridRows:p.number().or(p.string()).optional(),schGridTemplateRows:p.string().optional(),schGridTemplateColumns:p.string().optional(),schGridTemplate:p.string().optional(),schGridGap:p.number().or(p.string()).optional(),schGridRowGap:p.number().or(p.string()).optional(),schGridColumnGap:p.number().or(p.string()).optional(),schFlex:p.boolean().or(p.string()).optional(),schFlexGap:p.number().or(p.string()).optional(),schFlexDirection:p.enum(["row","column"]).optional(),schAlignItems:p.enum(["start","center","end","stretch"]).optional(),schJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),schFlexRow:p.boolean().optional(),schFlexColumn:p.boolean().optional(),schGap:p.number().or(p.string()).optional(),schPack:p.boolean().optional(),schMatchAdapt:p.boolean().optional(),pcbWidth:D.optional(),pcbHeight:D.optional(),minTraceWidth:D.optional(),schWidth:D.optional(),schHeight:D.optional(),pcbLayout:bf.optional(),schLayout:bf.optional(),cellBorder:rz.nullable().optional(),border:rz.nullable().optional(),schPadding:D.optional(),schPaddingLeft:D.optional(),schPaddingRight:D.optional(),schPaddingTop:D.optional(),schPaddingBottom:D.optional(),pcbPadding:D.optional(),pcbPaddingLeft:D.optional(),pcbPaddingRight:D.optional(),pcbPaddingTop:D.optional(),pcbPaddingBottom:D.optional(),pcbPositionAnchor:C_t.optional()}),fz=p.custom(e=>"findPart"in e),OI=RI.extend({manualEdits:M_t.optional(),schAutoLayoutEnabled:p.boolean().optional(),schTraceAutoLabelEnabled:p.boolean().optional(),schMaxTraceDistance:Y.optional(),routingDisabled:p.boolean().optional(),defaultTraceWidth:D.optional(),minTraceWidth:D.optional(),partsEngine:fz.optional(),pcbRouteCache:p.custom(e=>!0).optional(),autorouter:dz.optional(),square:p.boolean().optional(),emptyArea:p.string().optional(),filledArea:p.string().optional(),width:Y.optional(),height:Y.optional(),outline:p.array(Gs).optional(),outlineOffsetX:Y.optional(),outlineOffsetY:Y.optional(),circuitJson:p.array(p.any()).optional()}),A_t=OI.extend({subcircuit:p.literal(!0)}),mz=p.discriminatedUnion("subcircuit",[RI.extend({subcircuit:p.literal(!1).optional()}),A_t]);Ct(!0);Ct(!0);Ct(!0);Ct(!0);var Wp=p.custom(e=>typeof e=="string"),LI=OI.omit({connections:!0}).extend({material:p.enum(["fr4","fr1"]).default("fr4"),layers:p.union([p.literal(2),p.literal(4)]).default(2),borderRadius:Y.optional(),thickness:Y.optional(),boardAnchorPosition:Gs.optional(),boardAnchorAlignment:Zp.optional(),title:p.string().optional(),solderMaskColor:Wp.optional(),topSolderMaskColor:Wp.optional(),bottomSolderMaskColor:Wp.optional(),silkscreenColor:Wp.optional(),topSilkscreenColor:Wp.optional(),bottomSilkscreenColor:Wp.optional(),doubleSidedAssembly:p.boolean().optional().default(!1)});Ct(!0);var _z=RI.omit({width:!0,height:!0,children:!0}).extend({width:Y,height:Y,children:p.any().optional(),noSolderMask:p.boolean().optional()});Ct(!0);var Djt=OI.extend({padding:Y.optional(),paddingLeft:Y.optional(),paddingRight:Y.optional(),paddingTop:Y.optional(),paddingBottom:Y.optional()});Ct(!0);var R_t=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),O_t=p.custom().pipe(p.record(p.string(),R_t)),L_t=p.record(ur,ur.or(p.array(ur).readonly()).or(p.array(ur)));Ct(!0);var F_t=p.object({manufacturerPartNumber:p.string().optional(),supplierPartNumber:p.record(Mp,p.array(p.string())).optional()}),Jp=Dn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:L_t.optional(),showPinAliases:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),externallyConnectedPins:p.array(p.array(p.string())).optional(),schPinArrangement:xf.optional(),schPortArrangement:xf.optional(),pinCompatibleVariants:p.array(F_t).optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),noSchematicRepresentation:p.boolean().optional(),connections:O_t.optional()});Ct(!0);var yz=Jp;Ct(!0);var FI=Dn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(ur),ur.or(p.array(ur))).optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),schDirection:p.enum(["left","right"]).optional(),schPinArrangement:AI.optional(),schPortArrangement:xf.optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),pinCount:p.union([p.literal(2),p.literal(3)]).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),connections:p.custom().pipe(p.record(p.string(),Kp)).optional()});Ct(!0);var gz=FI.extend({bridgedPins:p.array(p.array(p.string())).optional(),bridged:p.boolean().optional()});Ct(!0);var Gjt=Dn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(ur),ur.or(p.array(ur))).optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),schDirection:p.enum(["left","right"]).optional(),schPortArrangement:xf.optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),standard:p.enum(["usb_c","m2"]).optional()});Ct(!0);var bz=Dn.extend({currentRating:p.union([p.number(),p.string()]),voltageRating:p.union([p.number(),p.string()]).optional(),schShowRatings:p.boolean().optional(),schOrientation:tc.optional(),connections:p.record(p.string(),p.union([p.string(),p.array(p.string()).readonly(),p.array(p.string())])).optional()}),Wg=p.custom().transform(e=>{if(e!==void 0)return Y.parse(e)}),xz=p.discriminatedUnion("shape",[Oe.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circle"),holeDiameter:Y,outerDiameter:Y,portHints:es.optional()}),Oe.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("oval"),outerWidth:Y,outerHeight:Y,holeWidth:Wg,holeHeight:Wg,innerWidth:Y.optional().describe("DEPRECATED use holeWidth"),innerHeight:Y.optional().describe("DEPRECATED use holeHeight"),portHints:es.optional()}),Oe.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill"),rectPad:p.boolean().optional(),outerWidth:Y,outerHeight:Y,holeWidth:Wg,holeHeight:Wg,innerWidth:Y.optional().describe("DEPRECATED use holeWidth"),innerHeight:Y.optional().describe("DEPRECATED use holeHeight"),portHints:es.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional()}),Oe.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circular_hole_with_rect_pad"),holeDiameter:Y,rectPadWidth:Y,rectPadHeight:Y,rectBorderRadius:Y.optional(),holeShape:p.literal("circle").optional(),padShape:p.literal("rect").optional(),portHints:es.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional()}),Oe.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill_hole_with_rect_pad"),holeShape:p.literal("pill"),padShape:p.literal("rect"),holeWidth:Y,holeHeight:Y,rectPadWidth:Y,rectPadHeight:Y,portHints:es.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional()})]).refine(e=>("innerWidth"in e&&e.innerWidth!==void 0&&(e.holeWidth??(e.holeWidth=e.innerWidth)),"innerHeight"in e&&e.innerHeight!==void 0&&(e.holeHeight??(e.holeHeight=e.innerHeight)),e));Ct(!0);var z_t=["pin1","pin2","pos","neg"],vz=Dn.extend({resistance:Ha,pullupFor:p.string().optional(),pullupTo:p.string().optional(),pulldownFor:p.string().optional(),pulldownTo:p.string().optional(),schOrientation:tc.optional(),connections:jl(z_t).optional()}),Sz=kI;Ct(!0);var wz=Dn.extend({maxResistance:Ha,pinVariant:p.enum(["two_pin","three_pin"]).optional()});Ct(!0);var D_t=kI,Pz=Dn.extend({frequency:Wi,loadCapacitance:zs,manufacturerPartNumber:p.string().optional(),mpn:p.string().optional(),pinVariant:p.enum(["two_pin","four_pin"]).optional(),schOrientation:tc.optional(),connections:jl(D_t).optional()});Ct(!0);var Iz=Dn.extend({frequency:Wi,loadCapacitance:zs,pinVariant:p.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});Ct(!0);var sBt=LI.extend({leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftPins:p.array(p.string()).optional(),rightPins:p.array(p.string()).optional(),topPins:p.array(p.string()).optional(),bottomPins:p.array(p.string()).optional(),pinPitch:Y.optional(),innerHoles:p.boolean().optional()});Ct(!0);var $_t=["pin1","pin2","pos","neg","anode","cathode"],Tz=Dn.extend({capacitance:zs,maxVoltageRating:ai.optional(),schShowRatings:p.boolean().optional().default(!1),polarized:p.boolean().optional().default(!1),decouplingFor:p.string().optional(),decouplingTo:p.string().optional(),bypassFor:p.string().optional(),bypassTo:p.string().optional(),maxDecouplingTraceLength:p.number().optional(),schOrientation:tc.optional(),connections:jl($_t).optional()}),Mz=Jg;Ct(!0);var uBt=p.object({name:p.string(),connectsTo:p.string().or(p.array(p.string())).optional(),highlightColor:p.string().optional(),isPowerNet:p.boolean().optional(),isGroundNet:p.boolean().optional()});Ct(!0);var hBt=p.object({name:p.string().optional(),pcbOnly:p.boolean().optional(),schOnly:p.boolean().optional()});Ct(!0);var j_t=p.object({pcb:p.literal(!0).optional(),xDist:Y,left:p.string(),right:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});Ct(!0);var B_t=p.object({pcb:p.literal(!0).optional(),yDist:Y,top:p.string(),bottom:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});Ct(!0);var Y_t=p.object({pcb:p.literal(!0).optional(),sameY:p.literal(!0).optional(),for:p.array(p.string())});Ct(!0);var X_t=p.object({pcb:p.literal(!0).optional(),sameX:p.literal(!0).optional(),for:p.array(p.string())});Ct(!0);var Cz=p.union([j_t,B_t,Y_t,X_t]);Ct(!0);var V_t=Oe.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y});Ct(!0);var H_t=Oe.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:Y});Ct(!0);var G_t=Oe.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Gs)});Ct(!0);var Ez=p.discriminatedUnion("shape",[V_t,H_t,G_t]),U_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y,rectBorderRadius:Y.optional(),cornerRadius:Y.optional(),portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var q_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rotated_rect"),width:Y,height:Y,ccwRotation:p.number(),cornerRadius:Y.optional(),portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var W_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:Y,portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var Z_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("pill"),width:Y,height:Y,radius:Y,portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var K_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Gs),portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var Nz=p.discriminatedUnion("shape",[W_t,U_t,q_t,Z_t,K_t]);Ct(!0);var J_t=Oe.omit({pcbRotation:!0}).extend({shape:p.literal("rect"),width:Y,height:Y});Ct(!0);var Q_t=Oe.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:Y});Ct(!0);var yBt=p.union([Q_t,J_t]);Ct(!0);var tyt=Oe.extend({name:p.string().optional(),shape:p.literal("circle").optional(),diameter:Y.optional(),radius:Y.optional()}).transform(e=>({...e,diameter:e.diameter??2*e.radius,radius:e.radius??e.diameter/2})),eyt=Oe.extend({name:p.string().optional(),shape:p.literal("pill"),width:Y,height:Y}),nyt=Oe.extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y}),kz=p.union([tyt,eyt,nyt]);Ct(!0);var CI=p.union([p.string(),p.custom(e=>!!e.getPortSelector)]),sz=p.object({key:p.string().optional(),thickness:Y.optional(),width:Y.optional().describe("Alias for trace thickness"),schematicRouteHints:p.array(Gs).optional(),pcbRouteHints:p.array(Fi).optional(),pcbPathRelativeTo:p.string().optional(),pcbPath:p.array(p.union([Gs,p.string()])).optional(),schDisplayLabel:p.string().optional(),schStroke:p.string().optional(),highlightColor:p.string().optional(),maxLength:Y.optional()}),Az=p.union([sz.extend({path:p.array(CI)}),sz.extend({from:CI,to:CI})]),Rz=p.object({originalLayer:se.default("top").optional()});Ct(!0);var Oz=p.object({originalFacingDirection:p.enum(["up","down","left","right"]).default("right").optional()});Ct(!0);var iyt=p.number().or(p.string().endsWith("mAh")).transform(e=>{if(typeof e=="string"){let t=e.replace("mAh",""),n=Number.parseFloat(t);if(Number.isNaN(n))throw new Error("Invalid capacity");return n}return e}).describe("Battery capacity in mAh"),Lz=Dn.extend({capacity:iyt.optional(),voltage:ai.optional(),standard:p.enum(["AA","AAA","9V","CR2032","18650","C"]).optional(),schOrientation:tc.optional()});Ct(!0);var oyt=p.enum(["vertical","horizontal"]).describe("vertical means pins go 1->2 downward and horizontal means pins go 1->2 rightward");Ct(!0);var Fz=Dn.extend({pinCount:p.number(),pitch:Y.optional(),schFacingDirection:p.enum(["up","down","left","right"]).optional(),gender:p.enum(["male","female","unpopulated"]).optional().default("male"),showSilkscreenPinLabels:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),doubleRow:p.boolean().optional(),rightAngle:p.boolean().optional(),pcbOrientation:oyt.optional(),holeDiameter:Y.optional(),platedDiameter:Y.optional(),pinLabels:p.record(p.string(),ur).or(p.array(ur)).optional(),connections:p.custom().pipe(p.record(p.string(),Kp)).optional(),facingDirection:p.enum(["left","right"]).optional(),schPinArrangement:AI.optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional()});Ct(!0);var kBt=p.object({net:p.string().optional(),connection:p.string().optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Be.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});Ct(!0);var zz=p.object({net:p.string().optional(),connection:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Be.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});Ct(!0);var Dz=Jp.extend({});Ct(!0);Ct(!0);var ryt=p.custom(e=>typeof e=="string"),$z=p.object({simulationType:p.literal("spice_transient_analysis").default("spice_transient_analysis"),duration:qi.optional(),timePerStep:qi.optional(),spiceEngine:ryt.optional()});Ct(!0);var syt=["pin1","pin2","pin3","emitter","collector","base","gate","source","drain"],jz=Dn.extend({type:p.enum(["npn","pnp","bjt","jfet","mosfet","igbt"]),connections:jl(syt).optional()});Ct(!0);var Bz=Dn.extend({channelType:p.enum(["n","p"]),mosfetMode:p.enum(["enhancement","depletion"])});Ct(!0);var ayt=kI,Yz=Dn.extend({inductance:I_,maxCurrentRating:p.union([p.string(),p.number()]).optional(),schOrientation:tc.optional(),connections:jl(ayt).optional()});Ct(!0);var cyt=p.enum(["anode","cathode","pin1","pin2","pos","neg"]),lyt=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),uyt=p.record(cyt,lyt),pyt=p.enum(["standard","schottky","zener","avalanche","photo","tvs"]),Xz=Dn.extend({connections:uyt.optional(),variant:pyt.optional().default("standard"),standard:p.boolean().optional(),schottky:p.boolean().optional(),zener:p.boolean().optional(),avalanche:p.boolean().optional(),photo:p.boolean().optional(),tvs:p.boolean().optional(),schOrientation:tc.optional()}).superRefine((e,t)=>{if([e.standard,e.schottky,e.zener,e.avalanche,e.photo,e.tvs].filter(Boolean).length>1)return t.addIssue({code:p.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),p.INVALID}).transform(e=>{let t={...e,standard:!1,schottky:!1,zener:!1,avalanche:!1,photo:!1,tvs:!1};if(e.standard)t.standard=!0;else if(e.schottky)t.schottky=!0;else if(e.zener)t.zener=!0;else if(e.photo)t.photo=!0;else if(e.tvs)t.tvs=!0;else switch(e.variant){case"standard":t.standard=!0;break;case"schottky":t.schottky=!0;break;case"zener":t.zener=!0;break;case"avalanche":t.avalanche=!0;break;case"photo":t.photo=!0;break;case"tvs":t.tvs=!0;break;default:t.standard=!0}return t}),Vz=Jg;Ct(!0);var Hz=Dn.extend({color:p.string().optional(),wavelength:p.string().optional(),schDisplayValue:p.string().optional(),schOrientation:tc.optional(),connections:jl(Jg).optional(),laser:p.boolean().optional()}),Gz=Jg,Uz=Dn.extend({type:p.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:p.boolean().optional().default(!1),spst:p.boolean().optional(),spdt:p.boolean().optional(),dpst:p.boolean().optional(),dpdt:p.boolean().optional(),simSwitchFrequency:Wi.optional(),simCloseAt:qi.optional(),simOpenAt:qi.optional(),simStartClosed:p.boolean().optional(),simStartOpen:p.boolean().optional(),connections:p.custom().pipe(p.record(p.string(),Kp)).optional()}).transform(e=>{let t={...e};switch(t.dpdt?t.type="dpdt":t.spst?t.type="spst":t.spdt?t.type="spdt":t.dpst&&(t.type="dpst"),t.type){case"spdt":t.spdt=!0;break;case"spst":t.spst=!0;break;case"dpst":t.dpst=!0;break;case"dpdt":t.dpdt=!0;break}return t});Ct(!0);var qz=Oe.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional()});Ct(!0);var Wz=Oe.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional(),cornerRadius:Y.optional()}),Zz=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Fi),strokeWidth:D.optional(),color:p.string().optional()}),az=p.union([p.string(),Gs]),Kz=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:az,to:az,text:p.string().optional(),offset:Y.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional(),arrowSize:Y.optional(),units:p.enum(["in","mm"]).optional(),outerEdgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional(),innerEdgeToEdge:p.literal(!0).optional()});Ct(!0);var tYt=p.object({layer:p.string().optional(),thickness:Y.optional(),route:p.array(Fi)}),Jz=Kg.extend({name:p.string().optional(),fromLayer:se,toLayer:se,holeDiameter:Y,outerDiameter:Y,connectsTo:p.string().or(p.array(p.string())).optional(),netIsAssignable:p.boolean().optional()});Ct(!0);var hyt=p.object({pin1:Kp}).strict(),Qz=Dn.extend({connections:hyt.optional(),footprintVariant:p.enum(["pad","through_hole"]).optional(),padShape:p.enum(["rect","circle"]).optional().default("circle"),padDiameter:Y.optional(),holeDiameter:Y.optional(),width:Y.optional(),height:Y.optional()}).refine(e=>e.footprintVariant!=="through_hole"||e.holeDiameter!==void 0,{message:"holeDiameter is required for through_hole testpoints"});Ct(!0);var tD=Oe.omit({pcbRotation:!0,layer:!0}).extend({connection:p.string()});Ct(!0);var eD=p.union([Oe.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:Y}),Oe.extend({shape:p.literal("rect"),width:Y,height:Y})]),uYt=Oe.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),dYt=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({outline:p.array(Gs),strokeWidth:D.optional(),isClosed:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),nD=p.object({name:p.string().optional(),layer:se,connectsTo:p.string(),padMargin:Y.optional(),traceMargin:Y.optional(),clearance:Y.optional(),boardEdgeMargin:Y.optional(),cutoutMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional().default(!0)});Ct(!0);var iD=p.object({originalLayer:se.default("top").optional(),children:p.any().optional()});Ct(!0);var dyt=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbZ:Y.optional()}),fyt=Qa.extend({modelUrl:p.string(),stepUrl:p.string().optional()}),myt=fyt.merge(dyt);Ct(!0);var oD=p.union([p.null(),p.string(),myt]),rD=Dn.extend({voltage:ai}),_yt=["pin1","pin2","pos","neg"],yyt=p.union([p.string(),p.number()]).transform(e=>typeof e=="string"?e.endsWith("%")?parseFloat(e.slice(0,-1))/100:parseFloat(e):e).pipe(p.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),SYt=Dn.extend({voltage:ai.optional(),frequency:Wi.optional(),peakToPeakVoltage:ai.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Be.optional(),dutyCycle:yyt.optional(),connections:jl(_yt).optional()});Ct(!0);var sD=Dn.omit({name:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string()))});Ct(!0);var aD=p.object({center:qt,radius:Y,startAngleDegrees:Be,endAngleDegrees:Be,direction:p.enum(["clockwise","counterclockwise"]).default("counterclockwise"),strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),cD=p.object({schX:Y.optional(),schY:Y.optional(),width:Y.optional(),height:Y.optional(),overlay:p.array(p.string()).optional(),padding:Y.optional(),paddingLeft:Y.optional(),paddingRight:Y.optional(),paddingTop:Y.optional(),paddingBottom:Y.optional(),title:p.string().optional(),titleAlignment:Zp.default("top_left"),titleColor:p.string().optional(),titleFontSize:Y.optional(),titleInside:p.boolean().default(!1),strokeStyle:p.enum(["solid","dashed"]).default("solid")}).refine(e=>e.width!==void 0&&e.height!==void 0||Array.isArray(e.overlay)&&e.overlay.length>0,{message:"Must provide either both `width` and `height`, or a non-empty `overlay` array."}).refine(e=>!(e.width!==void 0&&e.height!==void 0&&Array.isArray(e.overlay)&&e.overlay.length>0),{message:"Cannot provide both `width`/`height` and `overlay` at the same time."}),lD=p.object({center:qt,radius:Y,strokeWidth:Y.optional(),color:p.string().optional(),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),uD=p.object({schX:Y.optional(),schY:Y.optional(),width:Y,height:Y,rotation:Be.default(0),strokeWidth:Y.optional(),color:p.string().optional(),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1),cornerRadius:Y.optional()}),pD=p.object({x1:Y,y1:Y,x2:Y,y2:Y,strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),gyt=p.enum(["center","left","right","top","bottom"]),hD=p.object({schX:Y.optional(),schY:Y.optional(),text:p.string(),fontSize:p.number().default(1),anchor:p.union([gyt.describe("legacy"),Zp]).default("center"),color:p.string().default("#000000"),schRotation:Be.default(0)}),$Yt=p.object({points:p.array(qt),isFilled:p.boolean().optional().default(!1),fillColor:p.enum(["red","blue"]).optional()}),dD=p.object({schX:Y.optional(),schY:Y.optional(),children:p.any().optional(),cellPadding:Y.optional(),borderWidth:Y.optional(),anchor:Zp.optional(),fontSize:Y.optional()});Ct(!0);var fD=p.object({children:p.any().optional(),height:Y.optional()});Ct(!0);var mD=p.object({children:p.string().optional(),horizontalAlign:p.enum(["left","center","right"]).optional(),verticalAlign:p.enum(["top","middle","bottom"]).optional(),fontSize:Y.optional(),rowSpan:p.number().optional(),colSpan:p.number().optional(),width:Y.optional(),text:p.string().optional()});Ct(!0);var qYt=Oe.extend({text:p.string(),anchorAlignment:Zp.default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),layers:p.array(se).optional()}),_D=Oe.extend({text:p.string(),anchorAlignment:Zp.default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),isKnockout:p.boolean().optional(),knockoutPadding:D.optional(),knockoutPaddingLeft:D.optional(),knockoutPaddingRight:D.optional(),knockoutPaddingTop:D.optional(),knockoutPaddingBottom:D.optional(),layers:p.array(se).optional()}),yD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Fi),strokeWidth:D.optional()}),gD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({strokeWidth:Y,x1:Y,y1:Y,x2:Y,y2:Y}),bD=Oe.omit({pcbRotation:!0}).extend({filled:p.boolean().default(!0).optional(),stroke:p.enum(["dashed","solid","none"]).optional(),strokeWidth:Y.optional(),width:Y,height:Y,cornerRadius:Y.optional()}),xD=Oe.omit({pcbRotation:!0}).extend({isFilled:p.boolean().optional(),isOutline:p.boolean().optional(),strokeWidth:Y.optional(),radius:Y}),cz=p.object({x:Y,y:Y,via:p.boolean().optional(),toLayer:se.optional()}),vD=p.object({for:p.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:p.number().optional(),offset:Fi.or(cz).optional(),offsets:p.array(Fi).or(p.array(cz)).optional(),traceWidth:p.number().optional()}),aXt=Kg.extend({name:p.string(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),direction:c_t,connectsTo:p.string().or(p.array(p.string())).optional()}),SD=Oe.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional()});Ct(!0);var wD=Oe.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional(),cornerRadius:Y.optional()});Ct(!0);var PD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Fi),strokeWidth:D.optional(),color:p.string().optional()});Ct(!0);var ID=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({x1:Y,y1:Y,x2:Y,y2:Y,strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional()});Ct(!0);var lz=p.union([p.string(),Gs]),TD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:lz,to:lz,text:p.string().optional(),offset:Y.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional(),arrowSize:Y.optional(),units:p.enum(["in","mm"]).optional(),outerEdgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional(),innerEdgeToEdge:p.literal(!0).optional()});Ct(!0);var MD=p.array(p.any()).describe("Circuit JSON"),EI=p.object({footprintCircuitJson:p.array(p.any()),cadModel:hz.optional()}),uz=p.function().args(p.string()).returns(p.promise(EI)).or(p.function().args(p.string(),p.object({resolvedPcbStyle:NI.optional()}).optional()).returns(p.promise(EI))).describe("A function that takes a path and returns Circuit JSON"),byt=p.object({loadFromUrl:p.function().args(p.string()).returns(p.promise(EI)).describe("A function that takes a footprint file URL and returns Circuit JSON")}),xyt=p.object({engineVersionString:p.string().optional(),simulationResultCircuitJson:MD}),vyt=p.object({simulate:p.function().args(p.string()).returns(p.promise(xyt)).describe("A function that takes a SPICE string and returns a simulation result")}),Syt=p.custom(e=>typeof e=="string"),pz=p.object({run:p.function().args().returns(p.promise(p.unknown())).describe("Run the autorouter"),getOutputSimpleRouteJson:p.function().args().returns(p.promise(p.any())).describe("Get the resulting SimpleRouteJson")}),wyt=p.object({createAutorouter:p.function().args(p.any(),p.any().optional()).returns(p.union([pz,p.promise(pz)])).describe("Create an autorouter instance")}),Pyt=p.object({partsEngine:fz.optional(),autorouter:dz.optional(),autorouterMap:p.record(p.string(),wyt).optional(),registryApiUrl:p.string().optional(),cloudAutorouterUrl:p.string().optional(),projectName:p.string().optional(),projectBaseUrl:p.string().optional(),version:p.string().optional(),url:p.string().optional(),printBoardInformationToSilkscreen:p.boolean().optional(),includeBoardFiles:p.array(p.string()).describe('The board files to automatically build with "tsci build", defaults to ["**/*.circuit.tsx"]. Can be an array of files or globs').optional(),snapshotsDir:p.string().describe('The directory where snapshots are stored for "tsci snapshot", defaults to "tests/__snapshots__"').optional(),defaultSpiceEngine:Syt.optional(),localCacheEngine:p.any().optional(),pcbDisabled:p.boolean().optional(),schematicDisabled:p.boolean().optional(),partsEngineDisabled:p.boolean().optional(),spiceEngineMap:p.record(p.string(),vyt).optional(),footprintLibraryMap:p.record(p.string(),p.union([uz,p.record(p.string(),p.union([MD,uz]))])).optional(),footprintFileParserMap:p.record(p.string(),byt).optional(),resolveProjectStaticFileImportUrl:p.function().args(p.string()).returns(p.promise(p.string())).describe("A function that returns a string URL for static files for the project").optional()});Ct(!0);var Iyt=Pyt,bXt=Iyt.pick({projectName:!0,projectBaseUrl:!0,version:!0,url:!0,printBoardInformationToSilkscreen:!0,includeBoardFiles:!0,snapshotsDir:!0,defaultSpiceEngine:!0});Ct(!0);vt();K();vt();Ys();K();var ca=Xt(Mr(),1);Ys();K();function ec(){return new zI}var zI=class e{constructor(){P(this,"index",{});P(this,"array",[])}size(){return this.array.length}empty(){return this.array.length===0}itemAt(t){return this.array[t]}contains(t){return this.index[t.id()]!==void 0}find(t){let n=this.index[t.id()];return n===void 0?void 0:this.array[n]}setDefault(t,n){let i=this.index[t.id()];if(i===void 0){let o=new Qg(t,n());return this.index[t.id()]=this.array.length,this.array.push(o),o}else return this.array[i]}insert(t,n){let i=new Qg(t,n),o=this.index[t.id()];return o===void 0?(this.index[t.id()]=this.array.length,this.array.push(i)):this.array[o]=i,i}erase(t){let n=this.index[t.id()];if(n===void 0)return;this.index[t.id()]=void 0;let i=this.array[n],o=this.array.pop();return i!==o&&(this.array[n]=o,this.index[o.first.id()]=n),i}copy(){let t=new e;for(let n=0;n<this.array.length;n++){let i=this.array[n].copy();t.array[n]=i,t.index[i.first.id()]=n}return t}},Qg=class e{constructor(t,n){P(this,"first");P(this,"second");this.first=t,this.second=n}copy(){return new e(this.first,this.second)}};var Us=class{constructor(t=""){P(this,"_name");P(this,"_value",0);P(this,"_context",null);P(this,"_id",Tyt++);this._name=t}id(){return this._id}name(){return this._name}setName(t){this._name=t}context(){return this._context}setContext(t){this._context=t}value(){return this._value}setValue(t){this._value=t}plus(t){return new Cn(this,t)}minus(t){return new Cn(this,typeof t=="number"?-t:[-1,t])}multiply(t){return new Cn([t,this])}divide(t){return new Cn([1/t,this])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},Tyt=0;var Cn=class e{constructor(){P(this,"_terms");P(this,"_constant");let t=Myt(arguments);this._terms=t.terms,this._constant=t.constant}terms(){return this._terms}constant(){return this._constant}value(){let t=this._constant;for(let n=0,i=this._terms.size();n<i;n++){let o=this._terms.itemAt(n);t+=o.first.value()*o.second}return t}plus(t){return new e(this,t)}minus(t){return new e(this,typeof t=="number"?-t:[-1,t])}multiply(t){return new e([t,this])}divide(t){return new e([1/t,this])}isConstant(){return this._terms.size()==0}toString(){let t=this._terms.array.map(function(n){return n.second+"*"+n.first.toString()}).join(" + ");return!this.isConstant()&&this._constant!==0&&(t+=" + "),t+=this._constant,t}};function Myt(e){let t=0,n=()=>0,i=ec();for(let o=0,r=e.length;o<r;++o){let s=e[o];if(typeof s=="number")t+=s;else if(s instanceof Us)i.setDefault(s,n).second+=1;else if(s instanceof Cn){t+=s.constant();let a=s.terms();for(let c=0,l=a.size();c<l;c++){let u=a.itemAt(c);i.setDefault(u.first,n).second+=u.second}}else if(s instanceof Array){if(s.length!==2)throw new Error("array must have length 2");let a=s[0],c=s[1];if(typeof a!="number")throw new Error("array item 0 must be a number");if(c instanceof Us)i.setDefault(c,n).second+=a;else if(c instanceof Cn){t+=c.constant()*a;let l=c.terms();for(let u=0,h=l.size();u<h;u++){let d=l.itemAt(u);i.setDefault(d.first,n).second+=d.second*a}}else throw new Error("array item 1 must be a variable or expression")}else throw new Error("invalid Expression argument: "+s)}return{terms:i,constant:t}}var Lr=class Lr{static create(t,n,i,o=1){let r=0;return r+=Math.max(0,Math.min(1e3,t*o))*1e6,r+=Math.max(0,Math.min(1e3,n*o))*1e3,r+=Math.max(0,Math.min(1e3,i*o)),r}static clip(t){return Math.max(0,Math.min(Lr.required,t))}};P(Lr,"required",Lr.create(1e3,1e3,1e3)),P(Lr,"strong",Lr.create(1,0,0)),P(Lr,"medium",Lr.create(0,1,0)),P(Lr,"weak",Lr.create(0,0,1));var wn=Lr;var Vn;(function(e){e[e.Le=0]="Le",e[e.Ge=1]="Ge",e[e.Eq=2]="Eq"})(Vn||(Vn={}));var ci=class{constructor(t,n,i,o=wn.required){P(this,"_expression");P(this,"_operator");P(this,"_strength");P(this,"_id",Cyt++);this._operator=n,this._strength=wn.clip(o),i===void 0&&t instanceof Cn?this._expression=t:this._expression=t.minus(i)}id(){return this._id}expression(){return this._expression}op(){return this._operator}strength(){return this._strength}toString(){return this._expression.toString()+" "+["<=",">=","="][this._operator]+" 0 ("+this._strength.toString()+")"}},Cyt=0;var Qp=class{constructor(){P(this,"maxIterations",1e3);P(this,"_cnMap",Eyt());P(this,"_rowMap",Nyt());P(this,"_varMap",kyt());P(this,"_editMap",Ayt());P(this,"_infeasibleRows",[]);P(this,"_objective",new nb);P(this,"_artificial",null);P(this,"_idTick",0)}createConstraint(t,n,i,o=wn.required){let r=new ci(t,n,i,o);return this.addConstraint(r),r}addConstraint(t){if(this._cnMap.find(t)!==void 0)throw new Error("duplicate constraint");let i=this._createRow(t),o=i.row,r=i.tag,s=this._chooseSubject(o,r);if(s.type()===Ue.Invalid&&o.allDummies())if(tb(o.constant()))s=r.marker;else throw new Error("unsatisfiable constraint");if(s.type()===Ue.Invalid){if(!this._addWithArtificialVariable(o))throw new Error("unsatisfiable constraint")}else o.solveFor(s),this._substitute(s,o),this._rowMap.insert(s,o);this._cnMap.insert(t,r),this._optimize(this._objective)}removeConstraint(t){let n=this._cnMap.erase(t);if(n===void 0)throw new Error("unknown constraint");this._removeConstraintEffects(t,n.second);let i=n.second.marker,o=this._rowMap.erase(i);if(o===void 0){let r=this._getMarkerLeavingSymbol(i);if(r.type()===Ue.Invalid)throw new Error("failed to find leaving row");o=this._rowMap.erase(r),o.second.solveForEx(r,i),this._substitute(i,o.second)}this._optimize(this._objective)}hasConstraint(t){return this._cnMap.contains(t)}getConstraints(){return this._cnMap.array.map(({first:t})=>t)}addEditVariable(t,n){if(this._editMap.find(t)!==void 0)throw new Error("duplicate edit variable");if(n=wn.clip(n),n===wn.required)throw new Error("bad required strength");let o=new Cn(t),r=new ci(o,Vn.Eq,void 0,n);this.addConstraint(r);let a={tag:this._cnMap.find(r).second,constraint:r,constant:0};this._editMap.insert(t,a)}removeEditVariable(t){let n=this._editMap.erase(t);if(n===void 0)throw new Error("unknown edit variable");this.removeConstraint(n.second.constraint)}hasEditVariable(t){return this._editMap.contains(t)}suggestValue(t,n){let i=this._editMap.find(t);if(i===void 0)throw new Error("unknown edit variable");let o=this._rowMap,r=i.second,s=n-r.constant;r.constant=n;let a=r.tag.marker,c=o.find(a);if(c!==void 0){c.second.add(-s)<0&&this._infeasibleRows.push(a),this._dualOptimize();return}let l=r.tag.other;if(c=o.find(l),c!==void 0){c.second.add(s)<0&&this._infeasibleRows.push(l),this._dualOptimize();return}for(let u=0,h=o.size();u<h;++u){let d=o.itemAt(u),_=d.second,y=_.coefficientFor(a);y!==0&&_.add(s*y)<0&&d.first.type()!==Ue.External&&this._infeasibleRows.push(d.first)}this._dualOptimize()}updateVariables(){let t=this._varMap,n=this._rowMap;for(let i=0,o=t.size();i<o;++i){let r=t.itemAt(i),s=n.find(r.second);s!==void 0?r.first.setValue(s.second.constant()):r.first.setValue(0)}}_getVarSymbol(t){let n=()=>this._makeSymbol(Ue.External);return this._varMap.setDefault(t,n).second}_createRow(t){let n=t.expression(),i=new nb(n.constant()),o=n.terms();for(let c=0,l=o.size();c<l;++c){let u=o.itemAt(c);if(!tb(u.second)){let h=this._getVarSymbol(u.first),d=this._rowMap.find(h);d!==void 0?i.insertRow(d.second,u.second):i.insertSymbol(h,u.second)}}let r=this._objective,s=t.strength(),a={marker:nc,other:nc};switch(t.op()){case Vn.Le:case Vn.Ge:{let c=t.op()===Vn.Le?1:-1,l=this._makeSymbol(Ue.Slack);if(a.marker=l,i.insertSymbol(l,c),s<wn.required){let u=this._makeSymbol(Ue.Error);a.other=u,i.insertSymbol(u,-c),r.insertSymbol(u,s)}break}case Vn.Eq:{if(s<wn.required){let c=this._makeSymbol(Ue.Error),l=this._makeSymbol(Ue.Error);a.marker=c,a.other=l,i.insertSymbol(c,-1),i.insertSymbol(l,1),r.insertSymbol(c,s),r.insertSymbol(l,s)}else{let c=this._makeSymbol(Ue.Dummy);a.marker=c,i.insertSymbol(c)}break}}return i.constant()<0&&i.reverseSign(),{row:i,tag:a}}_chooseSubject(t,n){let i=t.cells();for(let r=0,s=i.size();r<s;++r){let a=i.itemAt(r);if(a.first.type()===Ue.External)return a.first}let o=n.marker.type();return(o===Ue.Slack||o===Ue.Error)&&t.coefficientFor(n.marker)<0?n.marker:(o=n.other.type(),(o===Ue.Slack||o===Ue.Error)&&t.coefficientFor(n.other)<0?n.other:nc)}_addWithArtificialVariable(t){let n=this._makeSymbol(Ue.Slack);this._rowMap.insert(n,t.copy()),this._artificial=t.copy(),this._optimize(this._artificial);let i=tb(this._artificial.constant());this._artificial=null;let o=this._rowMap.erase(n);if(o!==void 0){let s=o.second;if(s.isConstant())return i;let a=this._anyPivotableSymbol(s);if(a.type()===Ue.Invalid)return!1;s.solveForEx(n,a),this._substitute(a,s),this._rowMap.insert(a,s)}let r=this._rowMap;for(let s=0,a=r.size();s<a;++s)r.itemAt(s).second.removeSymbol(n);return this._objective.removeSymbol(n),i}_substitute(t,n){let i=this._rowMap;for(let o=0,r=i.size();o<r;++o){let s=i.itemAt(o);s.second.substitute(t,n),s.second.constant()<0&&s.first.type()!==Ue.External&&this._infeasibleRows.push(s.first)}this._objective.substitute(t,n),this._artificial&&this._artificial.substitute(t,n)}_optimize(t){let n=0;for(;n<this.maxIterations;){let i=this._getEnteringSymbol(t);if(i.type()===Ue.Invalid)return;let o=this._getLeavingSymbol(i);if(o.type()===Ue.Invalid)throw new Error("the objective is unbounded");let r=this._rowMap.erase(o).second;r.solveForEx(o,i),this._substitute(i,r),this._rowMap.insert(i,r),n++}throw new Error("solver iterations exceeded")}_dualOptimize(){let t=this._rowMap,n=this._infeasibleRows;for(;n.length!==0;){let i=n.pop(),o=t.find(i);if(o!==void 0&&o.second.constant()<0){let r=this._getDualEnteringSymbol(o.second);if(r.type()===Ue.Invalid)throw new Error("dual optimize failed");let s=o.second;t.erase(i),s.solveForEx(i,r),this._substitute(r,s),t.insert(r,s)}}}_getEnteringSymbol(t){let n=t.cells();for(let i=0,o=n.size();i<o;++i){let r=n.itemAt(i),s=r.first;if(r.second<0&&s.type()!==Ue.Dummy)return s}return nc}_getDualEnteringSymbol(t){let n=Number.MAX_VALUE,i=nc,o=t.cells();for(let r=0,s=o.size();r<s;++r){let a=o.itemAt(r),c=a.first,l=a.second;if(l>0&&c.type()!==Ue.Dummy){let h=this._objective.coefficientFor(c)/l;h<n&&(n=h,i=c)}}return i}_getLeavingSymbol(t){let n=Number.MAX_VALUE,i=nc,o=this._rowMap;for(let r=0,s=o.size();r<s;++r){let a=o.itemAt(r),c=a.first;if(c.type()!==Ue.External){let l=a.second,u=l.coefficientFor(t);if(u<0){let h=-l.constant()/u;h<n&&(n=h,i=c)}}}return i}_getMarkerLeavingSymbol(t){let n=Number.MAX_VALUE,i=n,o=n,r=nc,s=r,a=r,c=r,l=this._rowMap;for(let u=0,h=l.size();u<h;++u){let d=l.itemAt(u),_=d.second,y=_.coefficientFor(t);if(y===0)continue;let g=d.first;if(g.type()===Ue.External)c=g;else if(y<0){let x=-_.constant()/y;x<i&&(i=x,s=g)}else{let x=_.constant()/y;x<o&&(o=x,a=g)}}return s!==r?s:a!==r?a:c}_removeConstraintEffects(t,n){n.marker.type()===Ue.Error&&this._removeMarkerEffects(n.marker,t.strength()),n.other.type()===Ue.Error&&this._removeMarkerEffects(n.other,t.strength())}_removeMarkerEffects(t,n){let i=this._rowMap.find(t);i!==void 0?this._objective.insertRow(i.second,-n):this._objective.insertSymbol(t,-n)}_anyPivotableSymbol(t){let n=t.cells();for(let i=0,o=n.size();i<o;++i){let r=n.itemAt(i),s=r.first.type();if(s===Ue.Slack||s===Ue.Error)return r.first}return nc}_makeSymbol(t){return new eb(t,this._idTick++)}};function tb(e){let t=1e-8;return e<0?-e<t:e<t}function Eyt(){return ec()}function Nyt(){return ec()}function kyt(){return ec()}function Ayt(){return ec()}var Ue;(function(e){e[e.Invalid=0]="Invalid",e[e.External=1]="External",e[e.Slack=2]="Slack",e[e.Error=3]="Error",e[e.Dummy=4]="Dummy"})(Ue||(Ue={}));var eb=class{constructor(t,n){P(this,"_id");P(this,"_type");this._id=n,this._type=t}id(){return this._id}type(){return this._type}},nc=new eb(Ue.Invalid,-1),nb=class e{constructor(t=0){P(this,"_cellMap",ec());P(this,"_constant");this._constant=t}cells(){return this._cellMap}constant(){return this._constant}isConstant(){return this._cellMap.empty()}allDummies(){let t=this._cellMap;for(let n=0,i=t.size();n<i;++n)if(t.itemAt(n).first.type()!==Ue.Dummy)return!1;return!0}copy(){let t=new e(this._constant);return t._cellMap=this._cellMap.copy(),t}add(t){return this._constant+=t}insertSymbol(t,n=1){let i=this._cellMap.setDefault(t,()=>0);tb(i.second+=n)&&this._cellMap.erase(t)}insertRow(t,n=1){this._constant+=t._constant*n;let i=t._cellMap;for(let o=0,r=i.size();o<r;++o){let s=i.itemAt(o);this.insertSymbol(s.first,s.second*n)}}removeSymbol(t){this._cellMap.erase(t)}reverseSign(){this._constant=-this._constant;let t=this._cellMap;for(let n=0,i=t.size();n<i;++n){let o=t.itemAt(n);o.second=-o.second}}solveFor(t){let n=this._cellMap,o=-1/n.erase(t).second;this._constant*=o;for(let r=0,s=n.size();r<s;++r)n.itemAt(r).second*=o}solveForEx(t,n){this.insertSymbol(t,-1),this.solveFor(n)}coefficientFor(t){let n=this._cellMap.find(t);return n!==void 0?n.second:0}substitute(t,n){let i=this._cellMap.erase(t);i!==void 0&&this.insertRow(n,i.second)}};var RH=Xt(Sn(),1);K();vt();vt();ji();var YI={};il(YI,{areBoundsCompletelyInsidePolygon:()=>BI,areBoundsOverlappingPolygon:()=>jI,boundsAreaOverlap:()=>jD,boundsDistance:()=>BD,boundsIntersection:()=>YD,clamp:()=>Rn,computeDistanceBetweenBoxes:()=>ts,computeGapBetweenBoxes:()=>II,computeManhattanDistanceBetweenBoxes:()=>yf,distSq:()=>RD,distance:()=>vi,doBoundsOverlap:()=>ic,doSegmentsIntersect:()=>li,doesLineIntersectLine:()=>qs,doesSegmentIntersectRect:()=>DI,findNearestPointsBetweenBoxSets:()=>gf,getBoundingBox:()=>Or,getBoundsFromPoints:()=>ns,getSegmentIntersection:()=>Xl,getUnitVectorFromDirection:()=>ab,getUnitVectorFromPointAToB:()=>sb,grid:()=>XD,isPointInsidePolygon:()=>rb,isRectCompletelyInsidePolygon:()=>DD,isRectOverlappingPolygon:()=>zD,midpoint:()=>AD,normalizeDegrees:()=>Vl,onSegment:()=>Yl,orientation:()=>Bl,pointToBoundsDistance:()=>kD,pointToBoxDistance:()=>ND,pointToSegmentClosestPoint:()=>ED,pointToSegmentDistance:()=>ei,range:()=>$D,segmentToBoundsMinDistance:()=>wf,segmentToBoxMinDistance:()=>ib,segmentToCircleMinDistance:()=>ob,segmentToSegmentMinDistance:()=>th});function qs([e,t],[n,i],{lineThickness:o=0}={}){return o===0?li(e,t,n,i):Ryt(e,t,n,i)<=o}function li(e,t,n,i){let o=Bl(e,t,n),r=Bl(e,t,i),s=Bl(n,i,e),a=Bl(n,i,t);return!!(o!==r&&s!==a||o===0&&Yl(e,n,t)||r===0&&Yl(e,i,t)||s===0&&Yl(n,e,i)||a===0&&Yl(n,t,i))}function Bl(e,t,n){let i=(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y);return i===0?0:i>0?1:2}function Yl(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function Ryt(e,t,n,i){if(e.x===t.x&&e.y===t.y)return ei(e,n,i);if(n.x===i.x&&n.y===i.y)return ei(n,e,t);if(li(e,t,n,i))return 0;let o=[ei(e,n,i),ei(t,n,i),ei(n,e,t),ei(i,e,t)];return Math.min(...o)}function ei(e,t,n){let i=(n.x-t.x)**2+(n.y-t.y)**2;if(i===0)return vi(e,t);let o=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/i;o=Math.max(0,Math.min(1,o));let r={x:t.x+o*(n.x-t.x),y:t.y+o*(n.y-t.y)};return vi(e,r)}function vi(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}function Xl(e,t,n,i){let o=t.x-e.x,r=t.y-e.y,s=i.x-n.x,a=i.y-n.y,c=e.x-n.x,l=e.y-n.y,u=o*a-r*s;if(Math.abs(u)<1e-10)return null;let h=(l*s-c*a)/u,d=(o*l-r*c)/u,_=1e-9;if(h>=-_&&h<=1+_&&d>=-_&&d<=1+_){let y=e.x+h*o,g=e.y+h*r;return{x:y,y:g}}return null}function DI(e,t,n){let i=c=>c.x>=n.minX&&c.x<=n.maxX&&c.y>=n.minY&&c.y<=n.maxY;if(i(e)||i(t))return!0;let o={x:n.minX,y:n.minY},r={x:n.maxX,y:n.minY},s={x:n.minX,y:n.maxY},a={x:n.maxX,y:n.maxY};return li(e,t,o,r)||li(e,t,r,a)||li(e,t,a,s)||li(e,t,s,o)}function th(e,t,n,i){if(e.x===t.x&&e.y===t.y)return ei(e,n,i);if(n.x===i.x&&n.y===i.y)return ei(n,e,t);if(li(e,t,n,i))return 0;let o=[ei(e,n,i),ei(t,n,i),ei(n,e,t),ei(i,e,t)];return Math.min(...o)}function wf(e,t,n){let i={x:n.minX,y:n.minY},o={x:n.maxX,y:n.minY},r={x:n.minX,y:n.maxY},s={x:n.maxX,y:n.maxY};if(li(e,t,i,o)||li(e,t,o,s)||li(e,t,s,r)||li(e,t,r,i)||e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY&&t.x>=n.minX&&t.x<=n.maxX&&t.y>=n.minY&&t.y<=n.maxY)return 0;let a=[ei(i,e,t),ei(o,e,t),ei(r,e,t),ei(s,e,t)];if(e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY||t.x>=n.minX&&t.x<=n.maxX&&t.y>=n.minY&&t.y<=n.maxY)return 0;if(e.x<n.minX||e.x>n.maxX||e.y<n.minY||e.y>n.maxY){let c=Rn(e.x,n.minX,n.maxX),l=Rn(e.y,n.minY,n.maxY);a.push(vi(e,{x:c,y:l}))}if(t.x<n.minX||t.x>n.maxX||t.y<n.minY||t.y>n.maxY){let c=Rn(t.x,n.minX,n.maxX),l=Rn(t.y,n.minY,n.maxY);a.push(vi(t,{x:c,y:l}))}return Math.min(...a)}function ib(e,t,n){let i=n.width/2,o=n.height/2,r={minX:n.center.x-i,maxX:n.center.x+i,minY:n.center.y-o,maxY:n.center.y+o};return wf(e,t,r)}function ob(e,t,n){let i={x:n.x,y:n.y};if(e.x===t.x&&e.y===t.y)return Math.max(0,vi(e,i)-n.radius);let o={x:t.x-e.x,y:t.y-e.y},r={x:i.x-e.x,y:i.y-e.y},s=o.x*o.x+o.y*o.y,a=Math.max(0,Math.min(1,(o.x*r.x+o.y*r.y)/s)),c={x:e.x+a*o.x,y:e.y+a*o.y},l=vi(c,i);return Math.max(0,l-n.radius)}function ED(e,t,n){let i=n.x-t.x,o=n.y-t.y,r=i*i+o*o;if(r===0)return{x:t.x,y:t.y};let s=((e.x-t.x)*i+(e.y-t.y)*o)/r;return s=Math.max(0,Math.min(1,s)),{x:t.x+s*i,y:t.y+s*o}}function Vl(e){return(e%360+360)%360}function ND(e,t){let n=t.width/2,i=t.height/2,o=t.center.x-n,r=t.center.x+n,s=t.center.y-i,a=t.center.y+i;if(e.x>=o&&e.x<=r&&e.y>=s&&e.y<=a)return 0;let c=Rn(e.x,o,r),l=Rn(e.y,s,a);return vi(e,{x:c,y:l})}function kD(e,t){if(e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)return 0;let n=Rn(e.x,t.minX,t.maxX),i=Rn(e.y,t.minY,t.maxY);return vi(e,{x:n,y:i})}function AD(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function RD(e,t){let n=e.x-t.x,i=e.y-t.y;return n*n+i*i}var OD=e=>{if("minX"in e)return e;let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,minY:e.center.y-n,maxX:e.center.x+t,maxY:e.center.y+n}},$I=e=>[{x:e.minX,y:e.minY},{x:e.maxX,y:e.minY},{x:e.maxX,y:e.maxY},{x:e.minX,y:e.maxY}],LD=e=>{let t=[];for(let n=0;n<e.length;n++){let i=e[n],o=e[(n+1)%e.length];t.push([i,o])}return t},Oyt=(e,t,n)=>{let i=(e.y-t.y)*(n.x-t.x)-(e.x-t.x)*(n.y-t.y);if(Math.abs(i)>1e-9)return!1;let o=(e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y);if(o<0)return!1;let r=(n.x-t.x)**2+(n.y-t.y)**2;return!(o>r)},Lyt=(e,t)=>e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY,rb=(e,t)=>{if(t.length<3)return!1;let n=LD(t);for(let[o,r]of n)if(Oyt(e,o,r))return!0;let i=!1;for(let o=0,r=t.length-1;o<t.length;r=o++){let s=t[o].x,a=t[o].y,c=t[r].x,l=t[r].y;a>e.y!=l>e.y&&e.x<(c-s)*(e.y-a)/(l-a)+s&&(i=!i)}return i},FD=(e,t)=>{let n=$I(e),i=[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]],o=LD(t);for(let[r,s]of o)for(let[a,c]of i)if(li(r,s,a,c))return!0;return!1},jI=(e,t)=>t.length<3?!1:t.some(i=>Lyt(i,e))||$I(e).some(i=>rb(i,t))?!0:FD(e,t),BI=(e,t)=>t.length<3||!$I(e).every(i=>rb(i,t))?!1:!FD(e,t),zD=(e,t)=>jI(OD(e),t),DD=(e,t)=>BI(OD(e),t);function $D(e,t,n=1){if(n===0)throw new Error("step cannot be 0");let i,o;t===void 0?(i=0,o=e):(i=e,o=t);let r=[];if(n>0)for(let s=i;s<o;s+=n)r.push(s);else for(let s=i;s>o;s+=n)r.push(s);return r}var jD=(e,t)=>{let n=Math.max(0,Math.min(e.maxX,t.maxX)-Math.max(e.minX,t.minX)),i=Math.max(0,Math.min(e.maxY,t.maxY)-Math.max(e.minY,t.minY));return n*i};var BD=(e,t)=>{let n=e.maxX<t.minX?t.minX-e.maxX:t.maxX<e.minX?e.minX-t.maxX:0,i=e.maxY<t.minY?t.minY-e.maxY:t.maxY<e.minY?e.minY-t.maxY:0;return Math.sqrt(n*n+i*i)};var YD=(e,t)=>{let n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),o=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return n>o||i>r?null:{minX:n,minY:i,maxX:o,maxY:r}};var ic=(e,t)=>!(e.maxX<t.minX||t.maxX<e.minX||e.maxY<t.minY||t.maxY<e.minY);var ns=e=>{if(e.length===0)return null;let t=e[0].x,n=e[0].y,i=e[0].x,o=e[0].y;for(let r=1;r<e.length;r++){let s=e[r];s.x<t&&(t=s.x),s.y<n&&(n=s.y),s.x>i&&(i=s.x),s.y>o&&(o=s.y)}return{minX:t,minY:n,maxX:i,maxY:o}};var sb=(e,t)=>{let n={x:t.x-e.x,y:t.y-e.y},i=Math.sqrt(n.x**2+n.y**2);return{x:n.x/i,y:n.y/i}},ab=e=>{switch(e){case"up":return{x:0,y:1};case"down":return{x:0,y:-1};case"left":return{x:-1,y:0};case"right":return{x:1,y:0}}};function XD({rows:e,cols:t,xSpacing:n,ySpacing:i,width:o,height:r,offsetX:s=0,offsetY:a=0,yDirection:c="cartesian",centered:l=!0}){let u=n??1,h=i??1,d=o??t*u,_=r??e*h,y=l?-d/2:0,g=l?-_/2:0,x=o?o/t:u,w=r?r/e:h,S=[];for(let T=0;T<e;T++)for(let I=0;I<t;I++){let E=T*t+I,M=s+y+I*x+x/2,k=a+T*w+w/2,N=c==="cartesian"?a+g+(e-1-T)*w+w/2:a+g+T*w+w/2;S.push({index:E,center:{x:M,y:N},topLeft:{x:M-x/2,y:N+w/2},bottomRight:{x:M+x/2,y:N-w/2},row:T,col:I})}return S}vt();Pf();var VD={name:"@tscircuit/capacity-autorouter",main:"./dist/index.js",version:"0.0.140",type:"module",files:["dist"],scripts:{start:"cosmos",build:"tsup ./lib/index.ts --minify terser --external @tscircuit/core --external circuit-to-svg --format esm --dts --sourcemap",bench:"bun test tests/spatial-index-bench.test.ts",format:"biome format --write .","format:check":"biome format .","vercel-build":"cosmos-export","repomix:lib":"repomix --ignore 'testing/**,**/TwoRouteHighDensitySolver/**,**/RouteStitchingSolver/**,solvers/CapacitySegmentPointOptimizer/CapacitySegmentPointOptimizer.ts' lib","bug-report":"bun run scripts/download-bug-report.ts","bug-report-with-test":"bun run scripts/create-bug-report-test.ts"},devDependencies:{"@biomejs/biome":"^1.9.4","@radix-ui/react-icons":"^1.3.2","@radix-ui/react-menubar":"^1.1.14","@react-hook/resize-observer":"^2.0.2","@resvg/resvg-js":"^2.6.2","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.46","@tscircuit/core":"^0.0.337","@tscircuit/math-utils":"^0.0.27","@types/bun":"^1.2.23","@types/fast-json-stable-stringify":"^2.1.2","@types/object-hash":"^3.0.6","@types/rbush":"^4.0.0","@types/react":"^19.0.8","@types/react-dom":"^19.0.3","@vercel/node":"^5.1.7","@vitejs/plugin-react":"^4.3.4","circuit-json-to-connectivity-map":"^0.0.19","circuit-to-svg":"^0.0.220",clsx:"^2.1.1",flatbush:"^4.4.0","graphics-debug":"^0.0.44","looks-same":"9",rbush:"^4.0.1",react:"18","react-cosmos":"^6.2.3","react-cosmos-plugin-vite":"^6.2.0","react-dom":"18","react-konva":"18",recharts:"^2.15.1","tailwind-merge":"^3.2.0",terser:"^5.43.1",tsup:"^8.3.6",typescript:"^5.9.3","use-mouse-matrix-transform":"^1.3.0",vite:"^6.0.11","vite-tsconfig-paths":"^5.1.4"},dependencies:{"fast-json-stable-stringify":"^2.1.0","object-hash":"^3.0.0"}};vt();ji();ke();var N4=Xt(Mr(),1);vt();var BH=Xt(Sn(),1);var bT={};il(bT,{AssignableViaAutoroutingPipelineSolver:()=>Tgt,AutoroutingPipelineSolver:()=>dj,CapacityMeshSolver:()=>xgt,InMemoryCache:()=>W$,LocalStorageCache:()=>Z$,calculateOptimalCapacityDepth:()=>mT,convertSrjToGraphicsObject:()=>zf,getGlobalInMemoryCache:()=>hh,getGlobalLocalStorageCache:()=>K$,getTunedTotalCapacity1:()=>zr,setupGlobalCaches:()=>Ff});var q$=Xt(pb(),1),aj=Xt(pb(),1),uj=Xt(pb(),1);var Wl=(...e)=>{let t={points:[],lines:[],circles:[],rects:[]};return e.forEach((n,i)=>{n&&(n.lines&&(t.lines=[...t.lines||[],...n.lines.map(o=>({...o,step:i}))]),n.points&&(t.points=[...t.points||[],...n.points.map(o=>({...o,step:i}))]),n.circles&&(t.circles=[...t.circles||[],...n.circles.map(o=>({...o,step:i}))]),n.rects&&(t.rects=[...t.rects||[],...n.rects.map(o=>({...o,step:i}))]))}),t},Ke=class{constructor(){P(this,"MAX_ITERATIONS",1e3);P(this,"solved",!1);P(this,"failed",!1);P(this,"iterations",0);P(this,"progress",0);P(this,"error",null);P(this,"activeSubSolver");P(this,"failedSubSolvers");P(this,"timeToSolve");P(this,"stats",{});P(this,"cacheHit");P(this,"cacheKey");P(this,"cacheToSolveSpaceTransform")}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.constructor.name} error: ${e}`,console.error(this.error),this.failed=!0,e}!this.solved&&this.iterations>this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,console.error(this.error),this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){let e=Date.now();for(;!this.solved&&!this.failed;)this.step();let t=Date.now();this.timeToSolve=t-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function o$(e){let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,maxX:e.center.x+t,minY:e.center.y-n,maxY:e.center.y+n}}function sc(e,t,n){return Math.max(t,Math.min(n,e))}function Si(e,t,n,i){let o=hb(e,t,n),r=hb(e,t,i),s=hb(n,i,e),a=hb(n,i,t);return o!==r&&s!==a||!(o!==0||!db(e,n,t))||!(r!==0||!db(e,i,t))||!(s!==0||!db(n,e,i))||!(a!==0||!db(n,t,i))}function hb(e,t,n){let i=(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y);return i===0?0:i>0?1:2}function db(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function Qi(e,t,n){let i=(n.x-t.x)**2+(n.y-t.y)**2;if(i===0)return Wt(e,t);let o=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/i;return o=Math.max(0,Math.min(1,o)),Wt(e,{x:t.x+o*(n.x-t.x),y:t.y+o*(n.y-t.y)})}function Wt(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}function k$(e,t,n,i){let o=t.x-e.x,r=t.y-e.y,s=i.x-n.x,a=i.y-n.y,c=e.x-n.x,l=e.y-n.y,u=o*a-r*s;if(Math.abs(u)<1e-10)return null;let h=(l*s-c*a)/u,d=(o*l-r*c)/u,_=1e-9;return h>=-1e-9&&h<=1+_&&d>=-1e-9&&d<=1+_?{x:e.x+h*o,y:e.y+h*r}:null}function r$(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}var A$=e=>{if("minX"in e)return e;let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,minY:e.center.y-n,maxX:e.center.x+t,maxY:e.center.y+n}},fT=e=>[{x:e.minX,y:e.minY},{x:e.maxX,y:e.minY},{x:e.maxX,y:e.maxY},{x:e.minX,y:e.maxY}],R$=e=>{let t=[];for(let n=0;n<e.length;n++){let i=e[n],o=e[(n+1)%e.length];t.push([i,o])}return t},qyt=(e,t,n)=>{let i=(e.y-t.y)*(n.x-t.x)-(e.x-t.x)*(n.y-t.y);if(Math.abs(i)>1e-9)return!1;let o=(e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y);return o<0?!1:!(o>(n.x-t.x)**2+(n.y-t.y)**2)},O$=(e,t)=>{if(t.length<3)return!1;let n=R$(t);for(let[o,r]of n)if(qyt(e,o,r))return!0;let i=!1;for(let o=0,r=t.length-1;o<t.length;r=o++){let s=t[o].x,a=t[o].y,c=t[r].x,l=t[r].y;a>e.y!=l>e.y&&e.x<(c-s)*(e.y-a)/(l-a)+s&&(i=!i)}return i},L$=(e,t)=>{let n=fT(e),i=[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]],o=R$(t);for(let[r,s]of o)for(let[a,c]of i)if(Si(r,s,a,c))return!0;return!1},iT=(e,t)=>((n,i)=>!(i.length<3)&&(!!i.some(o=>((r,s)=>r.x>=s.minX&&r.x<=s.maxX&&r.y>=s.minY&&r.y<=s.maxY)(o,n))||!!fT(n).some(o=>O$(o,i))||L$(n,i)))(A$(e),t),F$=(e,t)=>((n,i)=>!(i.length<3)&&!!fT(n).every(o=>O$(o,i))&&!L$(n,i))(A$(e),t);function oT(e,t,n,i){if(e.x===t.x&&e.y===t.y)return Qi(e,n,i);if(n.x===i.x&&n.y===i.y)return Qi(n,e,t);if(Si(e,t,n,i))return 0;let o=[Qi(e,n,i),Qi(t,n,i),Qi(n,e,t),Qi(i,e,t)];return Math.min(...o)}function z$(e,t,n){let i=n.width/2,o=n.height/2;return(function(r,s,a){let c={x:a.minX,y:a.minY},l={x:a.maxX,y:a.minY},u={x:a.minX,y:a.maxY},h={x:a.maxX,y:a.maxY};if(Si(r,s,c,l)||Si(r,s,l,h)||Si(r,s,h,u)||Si(r,s,u,c)||r.x>=a.minX&&r.x<=a.maxX&&r.y>=a.minY&&r.y<=a.maxY&&s.x>=a.minX&&s.x<=a.maxX&&s.y>=a.minY&&s.y<=a.maxY)return 0;let d=[Qi(c,r,s),Qi(l,r,s),Qi(u,r,s),Qi(h,r,s)];if(r.x>=a.minX&&r.x<=a.maxX&&r.y>=a.minY&&r.y<=a.maxY||s.x>=a.minX&&s.x<=a.maxX&&s.y>=a.minY&&s.y<=a.maxY)return 0;if(r.x<a.minX||r.x>a.maxX||r.y<a.minY||r.y>a.maxY){let _=sc(r.x,a.minX,a.maxX),y=sc(r.y,a.minY,a.maxY);d.push(Wt(r,{x:_,y}))}if(s.x<a.minX||s.x>a.maxX||s.y<a.minY||s.y>a.maxY){let _=sc(s.x,a.minX,a.maxX),y=sc(s.y,a.minY,a.maxY);d.push(Wt(s,{x:_,y}))}return Math.min(...d)})(e,t,{minX:n.center.x-i,maxX:n.center.x+i,minY:n.center.y-o,maxY:n.center.y+o})}function ah(e,t,n){let i=n.x-t.x,o=n.y-t.y,r=i*i+o*o;if(r===0)return{x:t.x,y:t.y};let s=((e.x-t.x)*i+(e.y-t.y)*o)/r;return s=Math.max(0,Math.min(1,s)),{x:t.x+s*i,y:t.y+s*o}}function Io(){return Io=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},Io.apply(null,arguments)}function Cb(e,t){return(Cb=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n})(e,t)}function D$(e){return(D$=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(e)}function $$(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return($$=function(){return!!e})()}function rT(e){var t=typeof Map=="function"?new Map:void 0;return rT=function(n){if(n===null||!(function(o){try{return Function.toString.call(o).indexOf("[native code]")!==-1}catch{return typeof o=="function"}})(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(t!==void 0){if(t.has(n))return t.get(n);t.set(n,i)}function i(){return(function(o,r,s){if($$())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,r);var c=new(o.bind.apply(o,a));return s&&Cb(c,s.prototype),c})(n,arguments,D$(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Cb(i,n)},rT(e)}var Po=(function(e){var t,n;function i(o){var r;if(1)r=e.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+o+" for more information.")||this;else for(var s,a,c;c<s;c++);return(function(l){if(l===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return l})(r)}return n=e,(t=i).prototype=Object.create(n.prototype),t.prototype.constructor=t,Cb(t,n),i})(rT(Error));function s$(e,t){return e.substr(-t.length)===t}var Wyt=/^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;function a$(e){return typeof e!="string"?e:e.match(Wyt)?parseFloat(e):e}var c$=function(e){return function(t,n){n===void 0&&(n="16px");var i=t,o=n;if(typeof t=="string"){if(!s$(t,"px"))throw new Po(69,e,t);i=a$(t)}if(typeof n=="string"){if(!s$(n,"px"))throw new Po(70,e,n);o=a$(n)}if(typeof i=="string")throw new Po(71,t,e);if(typeof o=="string")throw new Po(72,n,e);return""+i/o+e}};c$("em"),c$("rem");function GI(e){return Math.round(255*e)}function Zyt(e,t,n){return GI(e)+","+GI(t)+","+GI(n)}function Rf(e,t,n,i){if(i===void 0&&(i=Zyt),t===0)return i(n,n,n);var o=(e%360+360)%360/60,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o%2-1)),a=0,c=0,l=0;o>=0&&o<1?(a=r,c=s):o>=1&&o<2?(a=s,c=r):o>=2&&o<3?(c=r,l=s):o>=3&&o<4?(c=s,l=r):o>=4&&o<5?(a=s,l=r):o>=5&&o<6&&(a=r,l=s);var u=n-r/2;return i(a+u,c+u,l+u)}var l$={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},Kyt=/^#[a-fA-F0-9]{6}$/,Jyt=/^#[a-fA-F0-9]{8}$/,Qyt=/^#[a-fA-F0-9]{3}$/,t0t=/^#[a-fA-F0-9]{4}$/,UI=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,e0t=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,n0t=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,i0t=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function ch(e){if(typeof e!="string")throw new Po(3);var t=(function(d){if(typeof d!="string")return d;var _=d.toLowerCase();return l$[_]?"#"+l$[_]:d})(e);if(t.match(Kyt))return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16)};if(t.match(Jyt)){var n=parseFloat((parseInt(""+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16),alpha:n}}if(t.match(Qyt))return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16)};if(t.match(t0t)){var i=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:i}}var o=UI.exec(t);if(o)return{red:parseInt(""+o[1],10),green:parseInt(""+o[2],10),blue:parseInt(""+o[3],10)};var r=e0t.exec(t.substring(0,50));if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10),alpha:parseFloat(""+r[4])>1?parseFloat(""+r[4])/100:parseFloat(""+r[4])};var s=n0t.exec(t);if(s){var a="rgb("+Rf(parseInt(""+s[1],10),parseInt(""+s[2],10)/100,parseInt(""+s[3],10)/100)+")",c=UI.exec(a);if(!c)throw new Po(4,t,a);return{red:parseInt(""+c[1],10),green:parseInt(""+c[2],10),blue:parseInt(""+c[3],10)}}var l=i0t.exec(t.substring(0,50));if(l){var u="rgb("+Rf(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",h=UI.exec(u);if(!h)throw new Po(4,t,u);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+l[4])>1?parseFloat(""+l[4])/100:parseFloat(""+l[4])}}throw new Po(5)}function ac(e){return(function(t){var n,i=t.red/255,o=t.green/255,r=t.blue/255,s=Math.max(i,o,r),a=Math.min(i,o,r),c=(s+a)/2;if(s===a)return t.alpha!==void 0?{hue:0,saturation:0,lightness:c,alpha:t.alpha}:{hue:0,saturation:0,lightness:c};var l=s-a,u=c>.5?l/(2-s-a):l/(s+a);switch(s){case i:n=(o-r)/l+(o<r?6:0);break;case o:n=(r-i)/l+2;break;default:n=(i-o)/l+4}return n*=60,t.alpha!==void 0?{hue:n,saturation:u,lightness:c,alpha:t.alpha}:{hue:n,saturation:u,lightness:c}})(ch(e))}var sT=function(e){return e.length===7&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?"#"+e[1]+e[3]+e[5]:e};function Ul(e){var t=e.toString(16);return t.length===1?"0"+t:t}function qI(e){return Ul(Math.round(255*e))}function o0t(e,t,n){return sT("#"+qI(e)+qI(t)+qI(n))}function fb(e,t,n){return Rf(e,t,n,o0t)}function aT(e,t,n){if(typeof e=="number"&&typeof t=="number"&&typeof n=="number")return sT("#"+Ul(e)+Ul(t)+Ul(n));if(typeof e=="object"&&t===void 0&&n===void 0)return sT("#"+Ul(e.red)+Ul(e.green)+Ul(e.blue));throw new Po(6)}function Fb(e,t,n,i){if(typeof e=="string"&&typeof t=="number"){var o=ch(e);return"rgba("+o.red+","+o.green+","+o.blue+","+t+")"}if(typeof e=="number"&&typeof t=="number"&&typeof n=="number"&&typeof i=="number")return i>=1?aT(e,t,n):"rgba("+e+","+t+","+n+","+i+")";if(typeof e=="object"&&t===void 0&&n===void 0&&i===void 0)return e.alpha>=1?aT(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new Po(7)}function cc(e){if(typeof e!="object")throw new Po(8);if((function(t){return typeof t.red=="number"&&typeof t.green=="number"&&typeof t.blue=="number"&&typeof t.alpha=="number"})(e))return Fb(e);if((function(t){return typeof t.red=="number"&&typeof t.green=="number"&&typeof t.blue=="number"&&(typeof t.alpha!="number"||t.alpha===void 0)})(e))return aT(e);if((function(t){return typeof t.hue=="number"&&typeof t.saturation=="number"&&typeof t.lightness=="number"&&typeof t.alpha=="number"})(e))return(function(t,n,i,o){if(typeof t=="number"&&typeof n=="number"&&typeof i=="number"&&typeof o=="number")return o>=1?fb(t,n,i):"rgba("+Rf(t,n,i)+","+o+")";if(typeof t=="object"&&n===void 0&&i===void 0&&o===void 0)return t.alpha>=1?fb(t.hue,t.saturation,t.lightness):"rgba("+Rf(t.hue,t.saturation,t.lightness)+","+t.alpha+")";throw new Po(2)})(e);if((function(t){return typeof t.hue=="number"&&typeof t.saturation=="number"&&typeof t.lightness=="number"&&(typeof t.alpha!="number"||t.alpha===void 0)})(e))return(function(t,n,i){if(typeof t=="number"&&typeof n=="number"&&typeof i=="number")return fb(t,n,i);if(typeof t=="object"&&n===void 0&&i===void 0)return fb(t.hue,t.saturation,t.lightness);throw new Po(1)})(e);throw new Po(8)}function j$(e,t,n){return function(){var i=n.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):j$(e,t,i)}}function Bo(e){return j$(e,e.length,[])}Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{hue:n.hue+parseFloat(e)}))});function ph(e,t,n){return Math.max(e,Math.min(t,n))}Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{lightness:ph(0,1,n.lightness-parseFloat(e))}))});Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{saturation:ph(0,1,n.saturation-parseFloat(e))}))});Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{lightness:ph(0,1,n.lightness+parseFloat(e))}))});var B$=Bo(function(e,t,n){if(t==="transparent")return n;if(n==="transparent")return t;if(e===0)return n;var i=ch(t),o=Io({},i,{alpha:typeof i.alpha=="number"?i.alpha:1}),r=ch(n),s=Io({},r,{alpha:typeof r.alpha=="number"?r.alpha:1}),a=o.alpha-s.alpha,c=2*parseFloat(e)-1,l=((c*a===-1?c:c+a)/(1+c*a)+1)/2,u=1-l;return Fb({red:Math.floor(o.red*l+s.red*u),green:Math.floor(o.green*l+s.green*u),blue:Math.floor(o.blue*l+s.blue*u),alpha:o.alpha*parseFloat(e)+s.alpha*(1-parseFloat(e))})});Bo(function(e,t){if(t==="transparent")return t;var n=ch(t);return Fb(Io({},n,{alpha:ph(0,1,(100*(typeof n.alpha=="number"?n.alpha:1)+100*parseFloat(e))/100)}))});Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{saturation:ph(0,1,n.saturation+parseFloat(e))}))});Bo(function(e,t){return t==="transparent"?t:cc(Io({},ac(t),{hue:parseFloat(e)}))});Bo(function(e,t){return t==="transparent"?t:cc(Io({},ac(t),{lightness:parseFloat(e)}))});Bo(function(e,t){return t==="transparent"?t:cc(Io({},ac(t),{saturation:parseFloat(e)}))});Bo(function(e,t){return t==="transparent"?t:B$(parseFloat(e),"rgb(0, 0, 0)",t)});Bo(function(e,t){return t==="transparent"?t:B$(parseFloat(e),"rgb(255, 255, 255)",t)});var r0t=Bo(function(e,t){if(t==="transparent")return t;var n=ch(t);return Fb(Io({},n,{alpha:ph(0,1,+(100*(typeof n.alpha=="number"?n.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))}),u$=["blue","orange","purple","cyan","magenta","yellowgreen","darkgoldenrod","deeppink"],Of=(e,t)=>{let n={};for(let i=0;i<e.connections.length;i++){let o=e.connections[i],r=t?.getNetConnectedToId(o.name);r&&!n[r]&&(n[r]=`hsl(${300*i/e.connections.length}, 100%, 50%)`),n[o.name]=(r?n[r]:null)??`hsl(${340*i/e.connections.length}, 100%, 50%)`}return n},$n=(e,t)=>{try{return r0t(t,e)}catch(n){return console.error(n),e}},Zl=(e,t)=>e==="top"?0:e==="bottom"?t-1:parseInt(e.slice(5)),zr=(e,t=1)=>{let n=(("width"in e?e.width:e)/.5/2)**1.1*t;return e.availableZ?.length===1&&n>1?1:n},mT=(e,t=.5,n=16)=>{let i=0,o=e;for(;i<n&&!(zr({width:o})<=t);)o/=2,i++;return Math.max(1,i)};function Y$(e,t,n=0,i=e.length-1,o=s0t){for(;i>n;){if(i-n>600){let c=i-n+1,l=t-n+1,u=Math.log(c),h=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*h*(c-h)/c)*(l-c/2<0?-1:1);Y$(e,t,Math.max(n,Math.floor(t-l*h/c+d)),Math.min(i,Math.floor(t+(c-l)*h/c+d)),o)}let r=e[t],s=n,a=i;for(Tf(e,n,t),o(e[i],r)>0&&Tf(e,n,i);s<a;){for(Tf(e,s,a),s++,a--;o(e[s],r)<0;)s++;for(;o(e[a],r)>0;)a--}o(e[n],r)===0?Tf(e,n,a):(a++,Tf(e,a,i)),a<=t&&(n=a+1),t<=a&&(i=a-1)}}function Tf(e,t,n){let i=e[t];e[t]=e[n],e[n]=i}function s0t(e,t){return e<t?-1:e>t?1:0}var a0t=class{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data,n=[];if(!_b(e,t))return n;let i=this.toBBox,o=[];for(;t;){for(let r=0;r<t.children.length;r++){let s=t.children[r],a=t.leaf?i(s):s;_b(e,a)&&(t.leaf?n.push(s):ZI(e,a)?this._all(s,n):o.push(s))}t=o.pop()}return n}collides(e){let t=this.data;if(!_b(e,t))return!1;let n=[];for(;t;){for(let i=0;i<t.children.length;i++){let o=t.children[i],r=t.leaf?this.toBBox(o):o;if(_b(e,r)){if(t.leaf||ZI(e,r))return!0;n.push(o)}}t=n.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let n=0;n<e.length;n++)this.insert(e[n]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){let n=this.data;this.data=t,t=n}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=rh([]),this}remove(e,t){if(!e)return this;let n=this.data,i=this.toBBox(e),o=[],r=[],s,a,c;for(;n||o.length;){if(n||(n=o.pop(),a=o[o.length-1],s=r.pop(),c=!0),n.leaf){let l=c0t(e,n.children,t);if(l!==-1)return n.children.splice(l,1),o.push(n),this._condense(o),this}c||n.leaf||!ZI(n,i)?a?(s++,n=a.children[s],c=!1):n=null:(o.push(n),r.push(s),s=0,a=n,n=n.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){let n=[];for(;e;)e.leaf?t.push(...e.children):n.push(...e.children),e=n.pop();return t}_build(e,t,n,i){let o=n-t+1,r,s=this._maxEntries;if(o<=s)return r=rh(e.slice(t,n+1)),oh(r,this.toBBox),r;i||(i=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/Math.pow(s,i-1))),r=rh([]),r.leaf=!1,r.height=i;let a=Math.ceil(o/s),c=a*Math.ceil(Math.sqrt(s));p$(e,t,n,c,this.compareMinX);for(let l=t;l<=n;l+=c){let u=Math.min(l+c-1,n);p$(e,l,u,a,this.compareMinY);for(let h=l;h<=u;h+=a){let d=Math.min(h+a-1,u);r.children.push(this._build(e,h,d,i-1))}}return oh(r,this.toBBox),r}_chooseSubtree(e,t,n,i){for(;i.push(t),!t.leaf&&i.length-1!==n;){let o,r=1/0,s=1/0;for(let a=0;a<t.children.length;a++){let c=t.children[a],l=WI(c),u=p0t(e,c)-l;u<s?(s=u,r=l<r?l:r,o=c):u===s&&l<r&&(r=l,o=c)}t=o||t.children[0]}return t}_insert(e,t,n){let i=n?e:this.toBBox(e),o=[],r=this._chooseSubtree(i,this.data,t,o);for(r.children.push(e),Cf(r,i);t>=0&&o[t].children.length>this._maxEntries;)this._split(o,t),t--;this._adjustParentBBoxes(i,o,t)}_split(e,t){let n=e[t],i=n.children.length,o=this._minEntries;this._chooseSplitAxis(n,o,i);let r=this._chooseSplitIndex(n,o,i),s=rh(n.children.splice(r,n.children.length-r));s.height=n.height,s.leaf=n.leaf,oh(n,this.toBBox),oh(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)}_splitRoot(e,t){this.data=rh([e,t]),this.data.height=e.height+1,this.data.leaf=!1,oh(this.data,this.toBBox)}_chooseSplitIndex(e,t,n){let i,o=1/0,r=1/0;for(let s=t;s<=n-t;s++){let a=Mf(e,0,s,this.toBBox),c=Mf(e,s,n,this.toBBox),l=h0t(a,c),u=WI(a)+WI(c);l<o?(o=l,i=s,r=u<r?u:r):l===o&&u<r&&(r=u,i=s)}return i||n-t}_chooseSplitAxis(e,t,n){let i=e.leaf?this.compareMinX:l0t,o=e.leaf?this.compareMinY:u0t;this._allDistMargin(e,t,n,i)<this._allDistMargin(e,t,n,o)&&e.children.sort(i)}_allDistMargin(e,t,n,i){e.children.sort(i);let o=this.toBBox,r=Mf(e,0,t,o),s=Mf(e,n-t,n,o),a=mb(r)+mb(s);for(let c=t;c<n-t;c++){let l=e.children[c];Cf(r,e.leaf?o(l):l),a+=mb(r)}for(let c=n-t-1;c>=t;c--){let l=e.children[c];Cf(s,e.leaf?o(l):l),a+=mb(s)}return a}_adjustParentBBoxes(e,t,n){for(let i=n;i>=0;i--)Cf(t[i],e)}_condense(e){for(let t,n=e.length-1;n>=0;n--)e[n].children.length===0?n>0?(t=e[n-1].children,t.splice(t.indexOf(e[n]),1)):this.clear():oh(e[n],this.toBBox)}};function c0t(e,t,n){if(!n)return t.indexOf(e);for(let i=0;i<t.length;i++)if(n(e,t[i]))return i;return-1}function oh(e,t){Mf(e,0,e.children.length,t,e)}function Mf(e,t,n,i,o){o||(o=rh(null)),o.minX=1/0,o.minY=1/0,o.maxX=-1/0,o.maxY=-1/0;for(let r=t;r<n;r++){let s=e.children[r];Cf(o,e.leaf?i(s):s)}return o}function Cf(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function l0t(e,t){return e.minX-t.minX}function u0t(e,t){return e.minY-t.minY}function WI(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function mb(e){return e.maxX-e.minX+(e.maxY-e.minY)}function p0t(e,t){return(Math.max(t.maxX,e.maxX)-Math.min(t.minX,e.minX))*(Math.max(t.maxY,e.maxY)-Math.min(t.minY,e.minY))}function h0t(e,t){let n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),o=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return Math.max(0,o-n)*Math.max(0,r-i)}function ZI(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function _b(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function rh(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function p$(e,t,n,i,o){let r=[t,n];for(;r.length;){if((n=r.pop())-(t=r.pop())<=i)continue;let s=t+Math.ceil((n-t)/i/2)*i;Y$(e,s,t,n,o),r.push(t,s,s,n)}}var h$=class{constructor(e=9){P(this,"tree");this.tree=new a0t(e)}insert(e,t,n,i,o){this.tree.insert({minX:t,minY:n,maxX:i,maxY:o,data:e})}bulkLoad(e){let t=e.map(({item:n,minX:i,minY:o,maxX:r,maxY:s})=>({minX:i,minY:o,maxX:r,maxY:s,data:n}));this.tree.load(t)}search(e,t,n,i){return this.tree.search({minX:e,minY:t,maxX:n,maxY:i}).map(o=>o.data)}clear(){this.tree.clear()}},d0t=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(e,t){let n=this.length++;for(;n>0;){let i=n-1>>1,o=this.values[i];if(t>=o)break;this.ids[n]=this.ids[i],this.values[n]=o,n=i}this.ids[n]=e,this.values[n]=t}pop(){if(this.length===0)return;let e=this.ids,t=this.values,n=e[0],i=--this.length;if(i>0){let o=e[i],r=t[i],s=0,a=i>>1;for(;s<a;){let c=1+(s<<1),l=c+1,u=c+(+(l<i)&+(t[l]<t[c]));if(t[u]>=r)break;e[s]=e[u],t[s]=t[u],s=u}e[s]=o,t[s]=r}return n}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){this.ids.length=this.values.length=this.length}},d$=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],f$=class X${static from(t,n=0){if(n%8!=0)throw new Error("byteOffset must be 8-byte aligned.");if(!t||t.byteLength===void 0||t.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[i,o]=new Uint8Array(t,n+0,2);if(i!==251)throw new Error("Data does not appear to be in a Flatbush format.");let r=o>>4;if(r!==3)throw new Error(`Got v${r} data when expected v3.`);let s=d$[15&o];if(!s)throw new Error("Unrecognized array type.");let[a]=new Uint16Array(t,n+2,1),[c]=new Uint32Array(t,n+4,1);return new X$(c,a,s,void 0,t,n)}constructor(t,n=16,i=Float64Array,o=ArrayBuffer,r,s=0){if(t===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(t)||t<=0)throw new Error(`Unexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+n,2),65535),this.byteOffset=s;let a=t,c=a;this._levelBounds=[4*a];do a=Math.ceil(a/this.nodeSize),c+=a,this._levelBounds.push(4*c);while(a!==1);this.ArrayType=i,this.IndexArrayType=c<16384?Uint16Array:Uint32Array;let l=d$.indexOf(i),u=4*c*i.BYTES_PER_ELEMENT;if(l<0)throw new Error(`Unexpected typed array class: ${i}.`);if(r)this.data=r,this._boxes=new i(r,s+8,4*c),this._indices=new this.IndexArrayType(r,s+8+u,c),this._pos=4*c,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1];else{let h=this.data=new o(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(h,8,4*c),this._indices=new this.IndexArrayType(h,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(h,0,2).set([251,48+l]),new Uint16Array(h,2,1)[0]=n,new Uint32Array(h,4,1)[0]=t}this._queue=new d0t}add(t,n,i=t,o=n){let r=this._pos>>2,s=this._boxes;return this._indices[r]=r,s[this._pos++]=t,s[this._pos++]=n,s[this._pos++]=i,s[this._pos++]=o,t<this.minX&&(this.minX=t),n<this.minY&&(this.minY=n),i>this.maxX&&(this.maxX=i),o>this.maxY&&(this.maxY=o),r}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let t=this._boxes;if(this.numItems<=this.nodeSize)return t[this._pos++]=this.minX,t[this._pos++]=this.minY,t[this._pos++]=this.maxX,void(t[this._pos++]=this.maxY);let n=this.maxX-this.minX||1,i=this.maxY-this.minY||1,o=new Uint32Array(this.numItems);for(let r=0,s=0;r<this.numItems;r++){let a=t[s++],c=t[s++],l=t[s++],u=t[s++],h=Math.floor(65535*((a+l)/2-this.minX)/n),d=Math.floor(65535*((c+u)/2-this.minY)/i);o[r]=m0t(h,d)}cT(o,t,this._indices,0,this.numItems-1,this.nodeSize);for(let r=0,s=0;r<this._levelBounds.length-1;r++){let a=this._levelBounds[r];for(;s<a;){let c=s,l=t[s++],u=t[s++],h=t[s++],d=t[s++];for(let _=1;_<this.nodeSize&&s<a;_++)l=Math.min(l,t[s++]),u=Math.min(u,t[s++]),h=Math.max(h,t[s++]),d=Math.max(d,t[s++]);this._indices[this._pos>>2]=c,t[this._pos++]=l,t[this._pos++]=u,t[this._pos++]=h,t[this._pos++]=d}}}search(t,n,i,o,r){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=[],c=[];for(;s!==void 0;){let l=Math.min(s+4*this.nodeSize,m$(s,this._levelBounds));for(let u=s;u<l;u+=4){let h=this._boxes[u];if(i<h)continue;let d=this._boxes[u+1];if(o<d)continue;let _=this._boxes[u+2];if(t>_)continue;let y=this._boxes[u+3];if(n>y)continue;let g=0|this._indices[u>>2];s>=4*this.numItems?a.push(g):(r===void 0||r(g,h,d,_,y))&&c.push(g)}s=a.pop()}return c}neighbors(t,n,i=1/0,o=1/0,r){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=this._queue,c=[],l=o*o;t:for(;s!==void 0;){let u=Math.min(s+4*this.nodeSize,m$(s,this._levelBounds));for(let h=s;h<u;h+=4){let d=0|this._indices[h>>2],_=this._boxes[h],y=this._boxes[h+1],g=this._boxes[h+2],x=this._boxes[h+3],w=t<_?_-t:t>g?t-g:0,S=n<y?y-n:n>x?n-x:0,T=w*w+S*S;T>l||(s>=4*this.numItems?a.push(d<<1,T):(r===void 0||r(d))&&a.push(1+(d<<1),T))}for(;a.length&&1&a.peek();)if(a.peekValue()>l||(c.push(a.pop()>>1),c.length===i))break t;s=a.length?a.pop()>>1:void 0}return a.clear(),c}};function m$(e,t){let n=0,i=t.length-1;for(;n<i;){let o=n+i>>1;t[o]>e?i=o:n=o+1}return t[n]}function cT(e,t,n,i,o,r){if(Math.floor(i/r)>=Math.floor(o/r))return;let s=e[i],a=e[i+o>>1],c=e[o],l=c,u=Math.max(s,a);c>u?l=u:u===s?l=Math.max(a,c):u===a&&(l=Math.max(s,c));let h=i-1,d=o+1;for(;;){do h++;while(e[h]<l);do d--;while(e[d]>l);if(h>=d)break;f0t(e,t,n,h,d)}cT(e,t,n,i,d,r),cT(e,t,n,d+1,o,r)}function f0t(e,t,n,i,o){let r=e[i];e[i]=e[o],e[o]=r;let s=4*i,a=4*o,c=t[s],l=t[s+1],u=t[s+2],h=t[s+3];t[s]=t[a],t[s+1]=t[a+1],t[s+2]=t[a+2],t[s+3]=t[a+3],t[a]=c,t[a+1]=l,t[a+2]=u,t[a+3]=h;let d=n[i];n[i]=n[o],n[o]=d}function m0t(e,t){let n=e^t,i=65535^n,o=65535^(e|t),r=e&(65535^t),s=n|i>>1,a=n>>1^n,c=o>>1^i&r>>1^o,l=n&o>>1^r>>1^r;n=s,i=a,o=c,r=l,s=n&n>>2^i&i>>2,a=n&i>>2^i&(n^i)>>2,c^=n&o>>2^i&r>>2,l^=i&o>>2^(n^i)&r>>2,n=s,i=a,o=c,r=l,s=n&n>>4^i&i>>4,a=n&i>>4^i&(n^i)>>4,c^=n&o>>4^i&r>>4,l^=i&o>>4^(n^i)&r>>4,n=s,i=a,o=c,r=l,c^=n&o>>8^i&r>>8,l^=i&o>>8^(n^i)&r>>8,n=c^c>>1,i=l^l>>1;let u=e^t,h=i|65535^(u|n);return u=16711935&(u|u<<8),u=252645135&(u|u<<4),u=858993459&(u|u<<2),u=1431655765&(u|u<<1),h=16711935&(h|h<<8),h=252645135&(h|h<<4),h=858993459&(h|h<<2),h=1431655765&(h|h<<1),(h<<1|u)>>>0}var _0t=class{constructor(e){P(this,"index");P(this,"items",[]);P(this,"currentIndex",0);P(this,"capacity");this.capacity=Math.max(1,e),this.index=new f$(this.capacity)}insert(e,t,n,i,o){if(this.currentIndex>=this.index.numItems)throw new Error("Exceeded initial capacity");this.items[this.currentIndex]=e,this.index.add(t,n,i,o),this.currentIndex++}finish(){this.index.finish()}search(e,t,n,i){return this.index.search(e,t,n,i).map(o=>this.items[o]||null).filter(Boolean)}clear(){this.items=[],this.currentIndex=0,this.index=new f$(this.capacity)}},V$=class{constructor(e="native",t=[]){P(this,"idx");P(this,"storage",[]);e==="flatbush"?t.length===0?(this.idx=new h$,e="rbush"):this.idx=new _0t(t.length):this.idx=e==="rbush"?new h$:new class{constructor(){P(this,"shi",new y0t(t))}insert(n){}search(n,i,o,r){let s=(n+o)/2,a=(i+r)/2,c=o-n,l=r-i;return this.shi.getNodesInArea(s,a,c,l)}clear(){}},t.forEach(n=>this.insert(n)),e==="flatbush"&&t.length>0&&this.idx.finish?.()}insert(e){this.storage.push(e),this.idx.insert(e,e.center.x-e.width/2,e.center.y-e.height/2,e.center.x+e.width/2,e.center.y+e.height/2)}search(e){return this.idx.search(e.minX,e.minY,e.maxX,e.maxY)}searchArea(e,t,n,i){return this.search({minX:e-n/2,minY:t-i/2,maxX:e+n/2,maxY:t+i/2})}},y0t=class{constructor(e){P(this,"buckets");P(this,"CELL_SIZE",.4);this.obstacles=e,this.buckets=new Map;for(let t=0;t<e.length;t++){let n=e[t],i=n.center.x-n.width/2,o=n.center.y-n.height/2,r=n.center.x+n.width/2,s=n.center.y+n.height/2;for(let a=i;a<=r;a+=this.CELL_SIZE)for(let c=o;c<=s;c+=this.CELL_SIZE){let l=this.getBucketKey(a,c),u=this.buckets.get(l);u?u.push([n,t]):this.buckets.set(l,[[n,t]])}}}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getNodesInArea(e,t,n,i){let o=[],r=new Set,s=t-i/2,a=e+n/2,c=t+i/2;for(let l=e-n/2;l<=a;l+=this.CELL_SIZE)for(let u=s;u<=c;u+=this.CELL_SIZE){let h=this.getBucketKey(l,u),d=this.buckets.get(h)||[];for(let _ of d)r.has(_[1])||(r.add(_[1]),o.push(_[0]))}return o}},g0t=class{constructor(e){P(this,"buckets");P(this,"CELL_SIZE",5);this.targets=e,this.buckets=new Map;for(let t=0;t<e.length;t++){let n=e[t],i=Math.floor(n.bounds.minX/this.CELL_SIZE)*this.CELL_SIZE,o=Math.floor(n.bounds.minY/this.CELL_SIZE)*this.CELL_SIZE,r=n.bounds.maxX,s=n.bounds.maxY;for(let a=i;a<=r;a+=this.CELL_SIZE)for(let c=o;c<=s;c+=this.CELL_SIZE){let l=this.getBucketKey(a,c),u=this.buckets.get(l);u?u.push([n,t]):this.buckets.set(l,[[n,t]])}}}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getTargetsInArea(e,t,n,i){let o=[],r=new Set,s=Math.floor((e-n/2)/this.CELL_SIZE)*this.CELL_SIZE,a=Math.floor((t-i/2)/this.CELL_SIZE)*this.CELL_SIZE,c=e+n/2,l=t+i/2;for(let u=s;u<=c;u+=this.CELL_SIZE)for(let h=a;h<=l;h+=this.CELL_SIZE){let d=this.getBucketKey(u,h),_=this.buckets.get(d)||[];for(let y of _)r.has(y[1])||(r.add(y[1]),o.push(y[0]))}return o}},b0t=class extends Ke{constructor(t,n={}){super();P(this,"unfinishedNodes");P(this,"finishedNodes");P(this,"nodeToXYOverlappingObstaclesMap");P(this,"layerCount");P(this,"outlinePolygon");P(this,"MAX_DEPTH",4);P(this,"targets");P(this,"targetTree");P(this,"obstacleTree");P(this,"_nextNodeCounter",0);this.srj=t,this.opts=n,this.MAX_DEPTH=n?.capacityDepth??this.MAX_DEPTH,this.MAX_ITERATIONS=1e5,this.layerCount=t.layerCount??2,this.outlinePolygon=t.outline&&t.outline.length>=3?t.outline:void 0;for(let s of t.obstacles)if(!s.zLayers){let a=[];for(let c of s.layers)a.push(Zl(c,t.layerCount));s.zLayers=a}let i={x:(t.bounds.minX+t.bounds.maxX)/2,y:(t.bounds.minY+t.bounds.maxY)/2},o={width:t.bounds.maxX-t.bounds.minX,height:t.bounds.maxY-t.bounds.minY},r=Math.max(o.width,o.height);this.unfinishedNodes=[{capacityMeshNodeId:this.getNextNodeId(),center:i,width:r,height:r,layer:"top",availableZ:Array.from({length:this.layerCount},(s,a)=>a),_depth:0,_containsTarget:!0,_containsObstacle:!0,_completelyInsideObstacle:!1}],this.finishedNodes=[],this.nodeToXYOverlappingObstaclesMap=new Map,this.obstacleTree=new V$("flatbush",this.srj.obstacles),this.targets=this.computeTargets(),this.targetTree=new g0t(this.targets)}computeTargets(){let t=[];for(let n of this.srj.connections)for(let i of n.pointsToConnect){let o=this.obstacleTree.searchArea(i.x,i.y,.01,.01).filter(a=>a.zLayers.some(c=>c===Zl(i.layer,this.layerCount))),r={minX:i.x-.005,minY:i.y-.005,maxX:i.x+.005,maxY:i.y+.005};o.length>0&&(r={minX:Math.min(...o.map(a=>a.center.x-a.width/2)),minY:Math.min(...o.map(a=>a.center.y-a.height/2)),maxX:Math.max(...o.map(a=>a.center.x+a.width/2)),maxY:Math.max(...o.map(a=>a.center.y+a.height/2))});let s={...i,connectionName:n.name,availableZ:[Zl(i.layer,this.layerCount)],bounds:r};t.push(s)}return t}getNodeBounds(t){let n=t.width/2,i=t.height/2;return{minX:t.center.x-n,maxX:t.center.x+n,minY:t.center.y-i,maxY:t.center.y+i}}getNodeRect(t){return{center:{x:t.center.x,y:t.center.y},width:t.width,height:t.height}}getNextNodeId(){return"cn"+this._nextNodeCounter++}getCapacityFromDepth(t){return(this.MAX_DEPTH-t+1)**2}getTargetIfNodeContainsTarget(t){let n=t.width>4*this.targetTree.CELL_SIZE?this.targets:this.targetTree.getTargetsInArea(t.center.x,t.center.y,t.width,t.height);for(let i of n)if(i.bounds.minX<=t.center.x+t.width/2&&i.bounds.maxX>=t.center.x-t.width/2&&i.bounds.minY<=t.center.y+t.height/2&&i.bounds.maxY>=t.center.y-t.height/2&&i.availableZ.some(o=>t.availableZ.includes(o)))return i;return null}getXYOverlappingObstacles(t){let n=this.nodeToXYOverlappingObstaclesMap.get(t.capacityMeshNodeId);if(n)return n;let i=[],o=this.getNodeBounds(t),r=o.minX,s=o.maxX,a=o.minY,c=o.maxY,l=t._parent?this.getXYOverlappingObstacles(t._parent):this.srj.obstacles;for(let u of l){let h=u.center.x-u.width/2,d=u.center.x+u.width/2,_=u.center.y-u.height/2,y=u.center.y+u.height/2;(s>=h&&r<=d&&c>=_&&a<=y||r>=h&&s<=d&&a>=_&&c<=y||h>=r&&d<=s&&_>=a&&y<=c)&&i.push(u)}return this.nodeToXYOverlappingObstaclesMap.set(t.capacityMeshNodeId,i),i}getXYZOverlappingObstacles(t){let n=this.getXYOverlappingObstacles(t),i=[];for(let o of n)t.availableZ.some(r=>o.zLayers.includes(r))&&i.push(o);return i}doesNodeOverlapObstacle(t){if(this.getXYZOverlappingObstacles(t).length>0)return!0;let n=this.getNodeBounds(t);if(this.outlinePolygon){let i=this.getNodeRect(t);if(!F$(i,this.outlinePolygon))return!0}return n.minX<this.srj.bounds.minX||n.maxX>this.srj.bounds.maxX||n.minY<this.srj.bounds.minY||n.maxY>this.srj.bounds.maxY}isNodeCompletelyInsideObstacle(t){let n=this.getXYZOverlappingObstacles(t),i=this.getNodeBounds(t);if(this.outlinePolygon){let o=this.getNodeRect(t);if(!iT(o,this.outlinePolygon))return!0}for(let o of n){let r=o.center.x-o.width/2,s=o.center.x+o.width/2,a=o.center.y-o.height/2,c=o.center.y+o.height/2;if(i.minX>=r&&i.maxX<=s&&i.minY>=a&&i.maxY<=c)return!0}return!1}getChildNodes(t){if(t._depth===this.MAX_DEPTH)return[];let n=[],i={width:t.width/2,height:t.height/2},o=[{x:t.center.x-i.width/2,y:t.center.y-i.height/2},{x:t.center.x+i.width/2,y:t.center.y-i.height/2},{x:t.center.x-i.width/2,y:t.center.y+i.height/2},{x:t.center.x+i.width/2,y:t.center.y+i.height/2}];for(let r of o){let s={capacityMeshNodeId:this.getNextNodeId(),center:r,width:i.width,height:i.height,layer:t.layer,availableZ:t.availableZ,_depth:(t._depth??0)+1,_parent:t};s._containsObstacle=this.doesNodeOverlapObstacle(s);let a=this.getTargetIfNodeContainsTarget(s);a&&(s._targetConnectionName=a.connectionName,s.availableZ=a.availableZ,s._containsTarget=!0),s._containsObstacle&&(s._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(s)),s._completelyInsideObstacle&&!s._containsTarget||n.push(s)}return n}shouldNodeBeXYSubdivided(t){return!(t._depth>=this.MAX_DEPTH)&&(!!t._containsTarget||!(!t._containsObstacle||t._completelyInsideObstacle))}_step(){let t=this.unfinishedNodes.pop();if(!t)return void(this.solved=!0);let n=this.getChildNodes(t),i=[],o=[];for(let r of n){let s=this.shouldNodeBeXYSubdivided(r);s?o.push(r):s||r._containsObstacle?!s&&r._containsTarget&&i.push(r):i.push(r)}this.unfinishedNodes.push(...o),this.finishedNodes.push(...i)}visualize(){let t={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Capacity Mesh Visualization"};if(this.outlinePolygon&&this.outlinePolygon.length>=2){let i=this.outlinePolygon.map(o=>({x:o.x,y:o.y}));i.push({...i[0]}),t.lines.push({points:i,strokeColor:"rgba(0, 136, 255, 0.95)",label:"outline"});for(let o of this.outlinePolygon)t.points.push({x:o.x,y:o.y,color:"rgba(0, 136, 255, 0.95)"})}for(let i of this.srj.obstacles)t.rects.push({center:i.center,width:i.width,height:i.height,fill:i.zLayers?.length===1&&i.zLayers?.includes(1)?"rgba(0,0,255,0.3)":"rgba(255,0,0,0.3)",stroke:"red",label:["obstacle",`z: ${i.zLayers.join(",")}`].join(`
|
|
161
|
+
`),{solved:!1,connectionName:e.name}}createObstacleList({dominantLayer:e,connection:t,obstaclesFromTraces:n}){return new KF(this.allObstacles.filter(i=>!i.connectedTo.includes(t.name)).filter(i=>i.layers.includes(e)).concat(n??[]))}postprocessConnectionSolveResult(e,t){return t}solve(){let e=[],t=[];this.debugTraceCount=0;for(let n of this.input.connections){let i=n.pointsToConnect[0].layer??"top";this.debugTraceCount+=1,this.obstacles=this.createObstacleList({dominantLayer:i,connection:n,obstaclesFromTraces:t});let o=this.solveConnection(n);o=this.postprocessConnectionSolveResult(n,o),e.push(o),Dl.enabled&&this.drawDebugTraceObstacles(t),o.solved&&t.push(...ZF(o.route.map(r=>({x:r.x,y:r.y,layer:r.layer??i})),n.name))}return e}solveAndMapToTraces(){return this.solve().flatMap(t=>t.solved?[{type:"pcb_trace",pcb_trace_id:`pcb_trace_for_${t.connectionName}`,route:K1t(t.route.map(n=>({route_type:"wire",x:n.x,y:n.y,width:this.input.minTraceWidth,layer:n.layer})))}]:[])}getDebugGroup(){let e=`t${this.debugTraceCount}_iter[${this.iterations-1}]`;return this.iterations<30||this.iterations<100&&this.iterations%10===0||this.iterations<1e3&&this.iterations%100===0||!this.debugSolutions?e:null}drawDebugTraceObstacles(e){let{debugTraceCount:t,debugSolutions:n}=this;for(let i in n)i.startsWith(`t${t}_`)&&n[i].push(...e.map((o,r)=>({type:"pcb_smtpad",pcb_component_id:"",layer:o.layers[0],width:o.width,shape:"rect",x:o.center.x,y:o.center.y,pcb_smtpad_id:`trace_obstacle_${r}`,height:o.height})))}drawDebugSolution({current:e,newNeighbors:t}){let n=this.getDebugGroup();if(!n)return;let{openSet:i,debugTraceCount:o,debugSolutions:r}=this;r[n]??(r[n]=[]);let s=r[n];s.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${e.x}_${e.y}`,font:"tscircuit2024",font_size:.25,text:"X"+(e.l!==void 0?e.l:""),pcb_component_id:"",layer:"top",anchor_position:{x:e.x,y:e.y},anchor_alignment:"center"});for(let a=0;a<i.length;a++){let c=i[a];s.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${c.x}_${c.y}`,layer:"top",route:[[0,.05],[.05,0],[0,-.05],[-.05,0],[0,.05]].map(([l,u])=>({x:c.x+l,y:c.y+u})),stroke_width:.01}),s.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${c.x}_${c.y}`,font:"tscircuit2024",font_size:.03,text:a.toString(),pcb_component_id:"",layer:"top",anchor_position:{x:c.x,y:c.y},anchor_alignment:"center"})}if(e.parent){let a=[],c=e;for(;c;)a.unshift(c),c=c.parent;s.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${e.x}_${e.y}`,layer:"top",route:a,stroke_width:.01})}}},Q1t=(0,tz.default)("autorouting-dataset:infinite-grid-ijump-astar:get-distance-to-overcome-obstacle");function TI({node:e,travelDir:t,wallDir:n,obstacle:i,obstacles:o,obstaclesInRow:r=0,OBSTACLE_MARGIN:s=.15,SHOULD_DETECT_CONJOINED_OBSTACLES:a=!1,MAX_CONJOINED_OBSTACLES:c=20}){let l;if(t.dx===0?t.dy>0?l=i.center.y+i.height/2-e.y:l=e.y-(i.center.y-i.height/2):t.dx>0?l=i.center.x+i.width/2-e.x:l=e.x-(i.center.x-i.width/2),l+=s,a&&r<c){let u=o.getObstacleAt(e.x+t.dx*l+n.dx*(n.wallDistance+.001),e.y+t.dy*l+n.dy*(n.wallDistance+.001));if(u===i)return l;if(u&&u.type==="rect"){let h=t.dy===0,d=h?i.height:i.width;if((h?u.height:u.width)>d)return Q1t("next obstacle on path is bigger, not trying to overcome it"),l;let y=TI({node:{x:e.x+t.dx*l,y:e.y+t.dy*l},travelDir:t,wallDir:n,obstacle:u,obstacles:o,obstaclesInRow:r+1,SHOULD_DETECT_CONJOINED_OBSTACLES:a,MAX_CONJOINED_OBSTACLES:c,OBSTACLE_MARGIN:s});l+=y}}return l}var t_t=class extends QF{constructor(){super(...arguments);P(this,"MAX_ITERATIONS",200)}getNeighbors(t){let n=this.obstacles,i=this.goalPoint,o;t.parent?o=YF(t.parent,t):o=YF(t,i);let r=[{dx:0,dy:1},{dx:1,dy:0},{dx:0,dy:-1},{dx:-1,dy:0}].filter(a=>a.dx===o.dx*-1&&a.dy===o.dy*-1?!1:!(a.dx===o.dx&&a.dy===o.dy&&t.parent?.obstacleHit)).map(a=>n.getOrthoDirectionCollisionInfo(t,a,{margin:this.OBSTACLE_MARGIN})).filter(a=>a.wallDistance>=this.OBSTACLE_MARGIN),s=[];for(let a of r){let c=null;t?.obstacleHit&&(c=TI({node:t,travelDir:a,wallDir:{...o,wallDistance:this.OBSTACLE_MARGIN},obstacle:t.obstacleHit,obstacles:n,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let l=UF(t,i,a),u=(a.dx===0||Math.sign(i.x-t.x)===a.dx)&&(a.dy===0||Math.sign(i.y-t.y)===a.dy);l<a.wallDistance&&l>0&&u?s.push({...a,travelDistance:l}):c!==null&&c<a.wallDistance?s.push({...a,travelDistance:c}):a.wallDistance!==1/0&&s.push({...a,travelDistance:a.wallDistance-this.OBSTACLE_MARGIN})}return s.filter(a=>!n.isObstacleAt(t.x+a.dx*a.travelDistance,t.y+a.dy*a.travelDistance)).map(a=>({x:t.x+a.dx*a.travelDistance,y:t.y+a.dy*a.travelDistance,obstacleHit:a.obstacle}))}};function e_t(e,t=4){let{center:n,width:i,height:o,rotation:r}=e,s=[],a=r*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(r%360+360)%360;if(o<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*c,x=-y*l,w=d*1.1,S=Math.abs(o*c)+Math.abs(d*l);s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}else{let d=o/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*l,x=y*c,w=Math.abs(i*c)+Math.abs(d*l),S=d*1.1;s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}return s}var Gg=["top","inner1","inner2","bottom"],ez=(e,t)=>{let n=o=>t?o.concat(o.map(r=>t?.getNetConnectedToId(r)).filter(Boolean)):o,i=[];for(let o of e)if(o.type==="pcb_smtpad"){if(o.shape==="circle")i.push({type:"oval",layers:[o.layer],center:{x:o.x,y:o.y},width:o.radius*2,height:o.radius*2,connectedTo:n([o.pcb_smtpad_id])});else if(o.shape==="rect")i.push({type:"rect",layers:[o.layer],center:{x:o.x,y:o.y},width:o.width,height:o.height,connectedTo:n([o.pcb_smtpad_id])});else if(o.shape==="rotated_rect"){let r={center:{x:o.x,y:o.y},width:o.width,height:o.height,rotation:o.ccw_rotation},s=e_t(r);for(let a of s)i.push({type:"rect",layers:[o.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([o.pcb_smtpad_id])})}}else if(o.type==="pcb_keepout")o.shape==="circle"?i.push({type:"oval",layers:o.layers,center:{x:o.center.x,y:o.center.y},width:o.radius*2,height:o.radius*2,connectedTo:[]}):o.shape==="rect"&&i.push({type:"rect",layers:o.layers,center:{x:o.center.x,y:o.center.y},width:o.width,height:o.height,connectedTo:[]});else if(o.type==="pcb_hole")o.hole_shape==="oval"?i.push({type:"oval",center:{x:o.x,y:o.y},width:o.hole_width,height:o.hole_height,connectedTo:[]}):o.hole_shape==="square"?i.push({type:"rect",layers:Gg,center:{x:o.x,y:o.y},width:o.hole_diameter,height:o.hole_diameter,connectedTo:[]}):(o.hole_shape==="round"||o.hole_shape==="circle")&&i.push({type:"rect",layers:Gg,center:{x:o.x,y:o.y},width:o.hole_diameter,height:o.hole_diameter,connectedTo:[]});else if(o.type==="pcb_plated_hole")o.shape==="circle"?i.push({type:"oval",layers:Gg,center:{x:o.x,y:o.y},width:o.outer_diameter,height:o.outer_diameter,connectedTo:n([o.pcb_plated_hole_id])}):(o.shape==="oval"||o.shape==="pill")&&i.push({type:"oval",layers:Gg,center:{x:o.x,y:o.y},width:o.outer_width,height:o.outer_height,connectedTo:n([o.pcb_plated_hole_id])});else if(o.type==="pcb_trace"){let r=ZF(o.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),o.source_trace_id);i.push(...r)}else o.type==="pcb_via"&&i.push({type:"rect",layers:o.layers,center:{x:o.x,y:o.y},connectedTo:[],width:o.outer_diameter,height:o.outer_diameter});return i};function HF(e){let{pcbConnMap:t,goalElementId:n}=e;if(!n.startsWith("pcb_port_"))throw new Error(`Currently alternative goal boxes must have a goal id with prefix "pcb_port_" (got ${n})`);let i=t.getAllTracesConnectedToPort(n);return ez(i).map(o=>({...o,connectedTo:[n]}))}var nz=e=>{let{connection:t,pcbConnMap:n}=e;if(t.pointsToConnect.length!==2)throw new Error(`Connection must have exactly 2 points for alternative goal boxes (got ${t.pointsToConnect.length})`);let[i,o]=t.pointsToConnect;if(!i.pcb_port_id||!o.pcb_port_id)throw new Error(`Connection points must have pcb_port_id for alternative goal box calculation (got ${i.pcb_port_id} and ${o.pcb_port_id})`);let r=HF({goalElementId:i.pcb_port_id,pcbConnMap:n}).concat([{center:i,width:.01,height:.01,connectedTo:[i.pcb_port_id],layers:[i.layer],type:"rect"}]),s=HF({goalElementId:o.pcb_port_id,pcbConnMap:n}).concat([{center:o,width:.01,height:.01,connectedTo:[o.pcb_port_id],layers:[o.layer],type:"rect"}]);if(r.length<=1&&s.length<=1)return{...t,startPoint:i,endPoint:o,goalBoxes:[]};let a=gf(r,s),c,l,u;return r.length>=s.length?(c={...o,...a.pointB},l={...i,...a.pointA},u=r):(c={...i,...a.pointA},l={...o,...a.pointB},u=s),{startPoint:c,endPoint:l,goalBoxes:u,name:t.name,pointsToConnect:[c,l]}},n_t=(e,t={})=>{let n={minTraceWidth:.1};n.layerCount=t.layerCount??1,n.obstacles=ez(e,t.connMap),n.connections=[];for(let o of e)if(o.type==="source_trace"){let r={name:o.source_trace_id,pointsToConnect:o.connected_source_port_ids.map(s=>{let a=Rr(e).pcb_port.getWhere({source_port_id:s});if(!a)throw new Error(`Could not find pcb_port for source_port_id "${s}"`);return{x:a.x,y:a.y,layer:a.layers?.[0]??"top",pcb_port_id:a.pcb_port_id}})};if(t.optimizeWithGoalBoxes){let s=new Hg(e);r=nz({connection:r,pcbConnMap:s})}n.connections.push(r),i_t(n.obstacles,r.pointsToConnect,r.name)}let i={minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0};for(let o of n.obstacles)i.minX=Math.min(i.minX,o.center.x-o.width/2),i.maxX=Math.max(i.maxX,o.center.x+o.width/2),i.minY=Math.min(i.minY,o.center.y-o.height/2),i.maxY=Math.max(i.maxY,o.center.y+o.height/2);for(let o of n.connections)for(let r of o.pointsToConnect)i.minX=Math.min(i.minX,r.x),i.maxX=Math.max(i.maxX,r.x),i.minY=Math.min(i.minY,r.y),i.maxY=Math.max(i.maxY,r.y);return n.bounds=i,n},i_t=(e,t,n)=>{for(let i of t)for(let o of e)o_t(i,o)&&o.connectedTo.push(n)};function o_t(e,t){let n=t.width/2,i=t.height/2;if(t.type==="rect")return e.x>=t.center.x-n&&e.x<=t.center.x+n&&e.y>=t.center.y-i&&e.y<=t.center.y+i;if(t.type==="oval"){let o=(e.x-t.center.x)/n,r=(e.y-t.center.y)/i;return o*o+r*r<=1}return!1}function GF(e,t){let n=t.x>e.x?1:t.x<e.x?-1:0,i=t.y>e.y?1:t.y<e.y?-1:0,o=t.l>e.l?1:t.l<e.l?-1:0;return{dx:n,dy:i,dl:o}}var MI={1:["top"],2:["top","bottom"],4:["top","inner1","inner2","bottom"]},r_t=e=>MI[e];function iz(e,t){let i=MI[e].indexOf(t);if(i===-1)throw new Error(`Invalid layer for getLayerIndex (for layerCount === ${e}): "${t}"`);return i}function s_t(e,t){let i=MI[e][t];if(!i)throw new Error(`Invalid index for indexToLayer (for layerCount === ${e}): "${t}"`);return i}var a_t=class extends KF{constructor(t,n){super([]);P(this,"obstacles");P(this,"GRID_STEP",.1);P(this,"layerCount");this.layerCount=t;let i=r_t(t);this.obstacles=n.flatMap(o=>o.layers.filter(r=>i.includes(r)).map(r=>({...o,left:o.center.x-o.width/2,right:o.center.x+o.width/2,top:o.center.y+o.height/2,bottom:o.center.y-o.height/2,l:iz(t,r)})))}getObstacleAt(t,n,i,o){o??(o=this.GRID_STEP);for(let r of this.obstacles){if(r.l!==i)continue;let s=r.width/2+o,a=r.height/2+o;if(t>=r.center.x-s&&t<=r.center.x+s&&n>=r.center.y-a&&n<=r.center.y+a)return r}return null}isObstacleAt(t,n,i,o){return this.getObstacleAt(t,n,i,o)!==null}getDirectionDistancesToNearestObstacle3d(t,n,i){let{GRID_STEP:o}=this,r={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let s of this.obstacles)if(s.l===i&&s.type==="rect"){let a=s.center.x-s.width/2-o,c=s.center.x+s.width/2+o,l=s.center.y+s.height/2+o,u=s.center.y-s.height/2-o;n>=u&&n<=l&&t>a&&(r.left=Math.min(r.left,t-c)),n>=u&&n<=l&&t<c&&(r.right=Math.min(r.right,a-t)),t>=a&&t<=c&&n<l&&(r.top=Math.min(r.top,u-n)),t>=a&&t<=c&&n>u&&(r.bottom=Math.min(r.bottom,n-l))}return r}getOrthoDirectionCollisionInfo(t,n,{margin:i=0}={}){let{x:o,y:r,l:s}=t,{dx:a,dy:c,dl:l}=n,u=1/0,h=null;if(l!==0){let d=s+l;return this.isObstacleAt(o,r,d,i)?(u=1,h=this.getObstacleAt(o,r,d,i)):u=1,{dx:a,dy:c,dl:l,wallDistance:u,obstacle:h}}else{for(let d of this.obstacles){if(d.l!==s)continue;let _=d.left-i,y=d.right+i,g=d.top+i,x=d.bottom-i,w=null;a===1&&c===0?r>x&&r<g&&o<d.left&&(w=d.left-o):a===-1&&c===0?r>x&&r<g&&o>d.right&&(w=o-d.right):a===0&&c===1?o>_&&o<y&&r<d.bottom&&(w=d.bottom-r):a===0&&c===-1&&o>_&&o<y&&r>d.top&&(w=r-d.top),w!==null&&w<u&&(u=w,h=d)}return{dx:a,dy:c,dl:0,wallDistance:u,obstacle:h}}}getObstaclesOverlappingRegion(t){let n=[];for(let i of this.obstacles){if(i.l!==t.l)continue;let{left:o,right:r,top:s,bottom:a}=i;o<=t.maxX&&r>=t.minX&&s>=t.minY&&a<=t.maxY&&n.push(i)}return n}},Ug=class extends QF{constructor(t){super(t);P(this,"MAX_ITERATIONS",500);P(this,"VIA_COST",4);P(this,"VIA_DIAMETER",.5);P(this,"allowLayerChange",!0);P(this,"layerCount");P(this,"obstacles");P(this,"optimizeWithGoalBoxes");P(this,"connMap");P(this,"pcbConnMap");P(this,"GOAL_RUSH_FACTOR",1.1);P(this,"defaultGoalViaMargin",.5);P(this,"marginsWithCosts");this.layerCount=t.input.layerCount??2,this.MAX_ITERATIONS=t.MAX_ITERATIONS??this.MAX_ITERATIONS,this.VIA_COST=t.VIA_COST??this.VIA_COST,this.connMap=t.connMap,this.pcbConnMap=t.pcbConnMap??new Hg,this.optimizeWithGoalBoxes=t.optimizeWithGoalBoxes??!1,this.obstacles=null,this.marginsWithCosts=t.marginsWithCosts??[{margin:1,enterCost:0,travelCostFactor:1},{margin:this.OBSTACLE_MARGIN,enterCost:10,travelCostFactor:2}]}get largestMargin(){return this.marginsWithCosts[0].margin}preprocessConnectionBeforeSolving(t){return this.optimizeWithGoalBoxes?nz({connection:t,pcbConnMap:this.pcbConnMap}):t}postprocessConnectionSolveResult(t,n){if(!n.solved)return n;if(this.optimizeWithGoalBoxes){let i=n.route.map(o=>({x:o.x,y:o.y,route_type:"wire",layer:o.layer,width:this.input.minTraceWidth}));i[0].start_pcb_port_id=t.pointsToConnect[0].pcb_port_id,i[i.length-1].end_pcb_port_id=t.pointsToConnect[1].pcb_port_id,this.pcbConnMap.addTrace({type:"pcb_trace",pcb_trace_id:`postprocess_trace_${BF(8)}`,route:i})}return n}createObstacleList({dominantLayer:t,connection:n,obstaclesFromTraces:i}){let o=this.connMap?this.connMap.getNetConnectedToId(n.name):n.name;if(!o)throw new Error(`The connection.name "${n.name}" wasn't present in the full connectivity map`);return new a_t(this.layerCount,this.allObstacles.filter(r=>!r.connectedTo.includes(o)).concat(i??[]))}computeG(t,n){let i=t.g+$l(t,n)*(t.travelMarginCostFactor??1)+(n.enterMarginCost??0);return(n.l??t.l!==-1??-1)&&(i+=this.VIA_COST),i}computeH(t){let n=Math.abs(t.x-this.goalPoint.x),i=Math.abs(t.y-this.goalPoint.y),o=Math.abs(t.l-this.goalPoint.l);return(n+i)**this.GOAL_RUSH_FACTOR+o*this.VIA_COST}getStartNode(t){return{...super.getStartNode(t),l:this.layerToIndex(t.pointsToConnect[0].layer)}}layerToIndex(t){return iz(this.layerCount,t)}indexToLayer(t){return s_t(this.layerCount,t)}getNodeName(t){return`${qF(t,this.GRID_STEP)}-${t.l??0}`}hasSpaceForVia(t,n){return t.every(i=>this.obstacles.getObstaclesOverlappingRegion({minX:n.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:n.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:n.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:n.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:i}).length===0)}getNeighborsSurroundingGoal(t){let n=this.obstacles,i=this.goalPoint,o=[],r=[{dx:1,dy:0,dl:0},{dx:-1,dy:0,dl:0},{dx:0,dy:1,dl:0},{dx:0,dy:-1,dl:0}],s=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin;for(let a of r){let c={x:t.x+a.dx*s,y:t.y+a.dy*s,l:t.l+a.dl,obstacleHit:null};this.hasSpaceForVia([t.l,i.l],c)&&o.push(c)}return o}getNeighbors(t){let n=this.obstacles,i=this.goalPoint,o=$l(t,i);if(o<=this.OBSTACLE_MARGIN)return this.getNeighborsSurroundingGoal(t);let r;t.parent?r=GF(t.parent,t):r=GF(t,i);let s=[{dx:0,dy:1,dl:0},{dx:1,dy:0,dl:0},{dx:0,dy:-1,dl:0},{dx:-1,dy:0,dl:0}],a=o>this.VIA_DIAMETER+this.OBSTACLE_MARGIN,c=$l(t,this.startNode)>this.VIA_DIAMETER+this.OBSTACLE_MARGIN;this.allowLayerChange&&a&&c&&(t.l<this.layerCount-1&&s.push({dx:0,dy:0,dl:1}),t.l>0&&s.push({dx:0,dy:0,dl:-1}));let l=s.filter(h=>h.dx===r.dx*-1&&h.dy===r.dy*-1&&h.dl===r.dl*-1?!1:!(h.dx===r.dx&&h.dy===r.dy&&h.dl===r.dl&&t.parent?.obstacleHit)).map(h=>n.getOrthoDirectionCollisionInfo(t,h,{margin:this.OBSTACLE_MARGIN})).filter(h=>!(h.wallDistance<this.OBSTACLE_MARGIN)),u=[];for(let h of l){let d=h.dx===0&&h.dy===0&&h.dl===1,_=h.dx===0&&h.dy===0&&h.dl===-1;if((d||_)&&![t.l,t.l+h.dl].every(S=>n.getObstaclesOverlappingRegion({minX:t.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:t.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:t.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:t.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:S}).length===0))continue;if(d){t.l<this.layerCount-1&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}if(_){t.l>0&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}let y=null;t?.obstacleHit&&(y=TI({node:t,travelDir:h,wallDir:{...r,wallDistance:this.OBSTACLE_MARGIN},obstacle:t.obstacleHit,obstacles:n,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let g=UF(t,i,h),x=(h.dx===0||Math.sign(i.x-t.x)===h.dx)&&(h.dy===0||Math.sign(i.y-t.y)===h.dy);if(g<h.wallDistance&&g>0&&x){let w=t.l===i.l,S=0;!w&&Math.abs(g-o)<this.GRID_STEP&&(S=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin),u.push({...h,travelDistance:g-S,enterMarginCost:0,travelMarginCostFactor:1})}else if(y!==null&&y<h.wallDistance){for(let{margin:w,enterCost:S,travelCostFactor:T}of this.marginsWithCosts)y-this.OBSTACLE_MARGIN+w*2<h.wallDistance&&u.push({...h,travelDistance:y-this.OBSTACLE_MARGIN+w,enterMarginCost:S,travelMarginCostFactor:T});if(h.wallDistance===1/0)u.push({...h,travelDistance:g,enterMarginCost:0,travelMarginCostFactor:1});else if(h.wallDistance>this.largestMargin)for(let{margin:w,enterCost:S,travelCostFactor:T}of this.marginsWithCosts)h.wallDistance>this.largestMargin+w&&u.push({...h,travelDistance:h.wallDistance-w,enterMarginCost:S,travelMarginCostFactor:T})}else if(h.wallDistance!==1/0)for(let{margin:w,enterCost:S,travelCostFactor:T}of this.marginsWithCosts)h.wallDistance>w&&u.push({...h,travelDistance:h.wallDistance-w,enterMarginCost:S,travelMarginCostFactor:T})}return u.map(h=>({x:t.x+h.dx*h.travelDistance,y:t.y+h.dy*h.travelDistance,l:t.l+h.dl,obstacleHit:h.obstacle,travelMarginCostFactor:h.travelMarginCostFactor,enterMarginCost:h.enterMarginCost}))}};function oz(e){let t=n_t(e),n=new t_t({input:t});return{solution:n.solveAndMapToTraces(),debugSolutions:n.debugSolutions,debugMessage:n.debugMessage}}K();K();vt();K();K();vt();vt();K();K();vt();K();K();K();K();vt();K();K();K();vt();K();K();vt();K();K();K();K();K();K();K();K();K();K();vt();K();vt();K();vt();K();K();vt();vt();K();vt();K();K();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();K();K();K();K();K();K();vt();K();vt();K();K();vt();K();vt();K();K();K();vt();K();vt();vt();K();K();K();vt();K();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();vt();K();vt();K();vt();K();K();vt();vt();K();K();vt();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();K();vt();vt();K();vt();K();vt();K();K();vt();K();vt();K();vt();K();vt();K();vt();K();K();var Ct=e=>{};Ct("extra props b");Ct("missing props b");Ct(!0);Ct("property a has mismatched types");var c_t=p.enum(["up","down","left","right"]),U$t=p.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);Ct(!0);Ct(!0);var es=p.array(p.string().or(p.number()));Ct(!0);var Zg=p.object({x:Y,y:Y,z:Y}),l_t=p.object({x:p.union([p.number(),p.string()]),y:p.union([p.number(),p.string()]),z:p.union([p.number(),p.string()])}),Qa=p.object({rotationOffset:p.number().or(l_t).optional(),positionOffset:Zg.optional(),size:Zg.optional(),modelUnitToMmScale:Y.optional(),zOffsetFromSurface:Y.optional()});Ct(!0);var u_t=Qa.extend({stlUrl:p.string()}),p_t=Qa.extend({objUrl:p.string(),mtlUrl:p.string().optional()}),h_t=Qa.extend({gltfUrl:p.string()}),d_t=Qa.extend({glbUrl:p.string()}),f_t=Qa.extend({stepUrl:p.string()}),m_t=Qa.extend({wrlUrl:p.string()}),__t=Qa.extend({jscad:p.record(p.any())}),hz=p.union([p.null(),p.string(),p.custom(e=>e&&typeof e=="object"&&"type"in e&&"props"in e),u_t,p_t,h_t,d_t,f_t,m_t,__t]);Ct(!0);var y_t=p.custom(e=>!0),NI=p.object({silkscreenFontSize:Y.optional(),silkscreenTextPosition:p.union([p.enum(["centered","outside","none"]),p.object({offsetX:p.number(),offsetY:p.number()})]).optional(),silkscreenTextVisibility:p.enum(["hidden","visible","inherit"]).optional()});Ct(!0);var g_t=p.custom(e=>!0),Oe=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbRotation:Be.optional(),pcbPositionAnchor:p.string().optional(),pcbPositionMode:p.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),layer:se.optional(),pcbMarginTop:Y.optional(),pcbMarginRight:Y.optional(),pcbMarginBottom:Y.optional(),pcbMarginLeft:Y.optional(),pcbMarginX:Y.optional(),pcbMarginY:Y.optional(),pcbStyle:NI.optional(),pcbRelative:p.boolean().optional(),relative:p.boolean().optional()});Ct(!0);var Kg=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbRotation:Be.optional(),pcbPositionAnchor:p.string().optional(),pcbPositionMode:p.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),pcbMarginTop:Y.optional(),pcbMarginRight:Y.optional(),pcbMarginBottom:Y.optional(),pcbMarginLeft:Y.optional(),pcbMarginX:Y.optional(),pcbMarginY:Y.optional(),pcbStyle:NI.optional(),schMarginTop:Y.optional(),schMarginRight:Y.optional(),schMarginBottom:Y.optional(),schMarginLeft:Y.optional(),schMarginX:Y.optional(),schMarginY:Y.optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Be.optional(),layer:se.optional(),footprint:y_t.optional(),symbol:g_t.optional(),relative:p.boolean().optional(),schRelative:p.boolean().optional(),pcbRelative:p.boolean().optional()});Ct(!0);var b_t=p.object({supplierPartNumbers:p.record(Mp,p.array(p.string())).optional()});Ct(!0);var x_t=p.object({providesPower:p.boolean().optional(),requiresPower:p.boolean().optional(),providesGround:p.boolean().optional(),requiresGround:p.boolean().optional(),providesVoltage:p.union([p.string(),p.number()]).optional(),requiresVoltage:p.union([p.string(),p.number()]).optional(),doNotConnect:p.boolean().optional(),includeInBoardPinout:p.boolean().optional(),highlightColor:p.string().optional()});Ct(!0);var Dn=Kg.merge(b_t).extend({key:p.any().optional(),name:p.string(),cadModel:hz.optional(),children:p.any().optional(),symbolName:p.string().optional(),doNotPlace:p.boolean().optional(),obstructsWithinBounds:p.boolean().optional().describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath"),pinAttributes:p.record(p.string(),x_t).optional()});Ct(!0);var kI=["pin1","left","pin2","right"],Jg=["pin1","left","anode","pos","pin2","right","cathode","neg"],sjt=Y.or(p.enum(["2x","3x","4x"])),tc=p.enum(["vertical","horizontal","pos_top","pos_bottom","pos_left","pos_right","neg_top","neg_bottom","neg_left","neg_right"]).describe("horizontal means pins go 1->2 rightward and vertical means pins go 1->2 downward (generally, positive on top)");Ct(!0);var qg=p.object({pins:p.array(p.union([p.number(),p.string()])),direction:p.union([p.literal("top-to-bottom"),p.literal("left-to-right"),p.literal("bottom-to-top"),p.literal("right-to-left")])}),xf=p.object({leftSize:p.number().optional().describe("@deprecated, use leftPinCount"),topSize:p.number().optional().describe("@deprecated, use topPinCount"),rightSize:p.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:p.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftSide:qg.optional(),rightSide:qg.optional(),topSide:qg.optional(),bottomSide:qg.optional()}),AI=xf;Ct(!0);var vf=p.record(p.object({marginLeft:Y.optional(),marginRight:Y.optional(),marginTop:Y.optional(),marginBottom:Y.optional(),leftMargin:Y.optional(),rightMargin:Y.optional(),topMargin:Y.optional(),bottomMargin:Y.optional()}));Ct(!0);var ur=p.string().regex(/^[A-Za-z0-9_]+$/),Zp=p.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),Gs=p.object({x:Y,y:Y}),Sf=p.object({edit_event_id:p.string(),in_progress:p.boolean().optional(),created_at:p.number()});Ct(!0);var v_t=Sf.extend({pcb_edit_event_type:p.literal("edit_component_location").describe("deprecated"),edit_event_type:p.literal("edit_pcb_component_location"),pcb_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var S_t=Sf.extend({pcb_edit_event_type:p.literal("edit_trace_hint").describe("deprecated"),edit_event_type:p.literal("edit_pcb_trace_hint").optional(),pcb_port_id:p.string(),pcb_trace_hint_id:p.string().optional(),route:p.array(p.object({x:p.number(),y:p.number(),via:p.boolean().optional()}))});Ct(!0);var w_t=Sf.extend({edit_event_type:p.literal("edit_schematic_component_location"),schematic_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var wjt=Sf.extend({edit_event_type:p.literal("edit_pcb_group_location"),pcb_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var Ijt=Sf.extend({edit_event_type:p.literal("edit_schematic_group_location"),schematic_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var Mjt=p.union([v_t,S_t,w_t]);Ct(!0);var P_t=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:qt});Ct(!0);var I_t=p.object({pcb_port_selector:p.string(),offsets:p.array(Fi)});Ct(!0);var T_t=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:qt});Ct(!0);var M_t=p.object({pcb_placements:p.array(P_t).optional(),manual_trace_hints:p.array(I_t).optional(),schematic_placements:p.array(T_t).optional()});Ct(!0);var Kp=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),jl=e=>p.record(p.enum(e),Kp),bf=p.object({layoutMode:p.enum(["grid","flex","match-adapt","relative","none"]).optional(),position:p.enum(["absolute","relative"]).optional(),grid:p.boolean().optional(),gridCols:p.number().or(p.string()).optional(),gridRows:p.number().or(p.string()).optional(),gridTemplateRows:p.string().optional(),gridTemplateColumns:p.string().optional(),gridTemplate:p.string().optional(),gridGap:p.number().or(p.string()).optional(),gridRowGap:p.number().or(p.string()).optional(),gridColumnGap:p.number().or(p.string()).optional(),flex:p.boolean().or(p.string()).optional(),flexDirection:p.enum(["row","column"]).optional(),alignItems:p.enum(["start","center","end","stretch"]).optional(),justifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),flexRow:p.boolean().optional(),flexColumn:p.boolean().optional(),gap:p.number().or(p.string()).optional(),pack:p.boolean().optional().describe("Pack the contents of this group using a packing strategy"),packOrderStrategy:p.enum(["largest_to_smallest","first_to_last","highest_to_lowest_pin_count"]).optional(),packPlacementStrategy:p.enum(["shortest_connection_along_outline"]).optional(),padding:D.optional(),paddingLeft:D.optional(),paddingRight:D.optional(),paddingTop:D.optional(),paddingBottom:D.optional(),paddingX:D.optional(),paddingY:D.optional(),width:D.optional(),height:D.optional(),matchAdapt:p.boolean().optional(),matchAdaptTemplate:p.any().optional()});Ct(!0);var rz=p.object({strokeWidth:D.optional(),dashed:p.boolean().optional(),solid:p.boolean().optional()}),C_t=p.custom(e=>typeof e=="string"),E_t=p.object({serverUrl:p.string().optional(),inputFormat:p.enum(["simplified","circuit-json"]).optional(),serverMode:p.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:p.boolean().optional(),cache:p.custom(e=>!0).optional(),traceClearance:D.optional(),groupMode:p.enum(["sequential_trace","subcircuit","sequential-trace"]).optional(),algorithmFn:p.custom(e=>typeof e=="function"||e===void 0).optional(),preset:p.enum(["sequential_trace","subcircuit","auto","auto_local","auto_cloud","freerouting","laser_prefab","sequential-trace","auto-local","auto-cloud"]).optional(),local:p.boolean().optional()}),N_t=p.union([p.literal("sequential_trace"),p.literal("subcircuit"),p.literal("auto"),p.literal("auto_local"),p.literal("auto_cloud"),p.literal("freerouting"),p.literal("laser_prefab"),p.literal("sequential-trace"),p.literal("auto-local"),p.literal("auto-cloud")]),k_t=p.string(),dz=p.union([E_t,N_t,k_t]),RI=Kg.extend({name:p.string().optional(),children:p.any().optional(),schTitle:p.string().optional(),key:p.any().optional(),showAsSchematicBox:p.boolean().optional(),connections:p.record(p.string(),Kp.optional()).optional(),schPinArrangement:AI.optional(),schPinSpacing:D.optional(),schPinStyle:vf.optional(),...bf.shape,grid:bf.shape.grid.describe("@deprecated use pcbGrid"),flex:bf.shape.flex.describe("@deprecated use pcbFlex"),pcbGrid:p.boolean().optional(),pcbGridCols:p.number().or(p.string()).optional(),pcbGridRows:p.number().or(p.string()).optional(),pcbGridTemplateRows:p.string().optional(),pcbGridTemplateColumns:p.string().optional(),pcbGridTemplate:p.string().optional(),pcbGridGap:p.number().or(p.string()).optional(),pcbGridRowGap:p.number().or(p.string()).optional(),pcbGridColumnGap:p.number().or(p.string()).optional(),pcbFlex:p.boolean().or(p.string()).optional(),pcbFlexGap:p.number().or(p.string()).optional(),pcbFlexDirection:p.enum(["row","column"]).optional(),pcbAlignItems:p.enum(["start","center","end","stretch"]).optional(),pcbJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),pcbFlexRow:p.boolean().optional(),pcbFlexColumn:p.boolean().optional(),pcbGap:p.number().or(p.string()).optional(),pcbPack:p.boolean().optional(),pcbPackGap:p.number().or(p.string()).optional(),schGrid:p.boolean().optional(),schGridCols:p.number().or(p.string()).optional(),schGridRows:p.number().or(p.string()).optional(),schGridTemplateRows:p.string().optional(),schGridTemplateColumns:p.string().optional(),schGridTemplate:p.string().optional(),schGridGap:p.number().or(p.string()).optional(),schGridRowGap:p.number().or(p.string()).optional(),schGridColumnGap:p.number().or(p.string()).optional(),schFlex:p.boolean().or(p.string()).optional(),schFlexGap:p.number().or(p.string()).optional(),schFlexDirection:p.enum(["row","column"]).optional(),schAlignItems:p.enum(["start","center","end","stretch"]).optional(),schJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),schFlexRow:p.boolean().optional(),schFlexColumn:p.boolean().optional(),schGap:p.number().or(p.string()).optional(),schPack:p.boolean().optional(),schMatchAdapt:p.boolean().optional(),pcbWidth:D.optional(),pcbHeight:D.optional(),minTraceWidth:D.optional(),schWidth:D.optional(),schHeight:D.optional(),pcbLayout:bf.optional(),schLayout:bf.optional(),cellBorder:rz.nullable().optional(),border:rz.nullable().optional(),schPadding:D.optional(),schPaddingLeft:D.optional(),schPaddingRight:D.optional(),schPaddingTop:D.optional(),schPaddingBottom:D.optional(),pcbPadding:D.optional(),pcbPaddingLeft:D.optional(),pcbPaddingRight:D.optional(),pcbPaddingTop:D.optional(),pcbPaddingBottom:D.optional(),pcbPositionAnchor:C_t.optional()}),fz=p.custom(e=>"findPart"in e),OI=RI.extend({manualEdits:M_t.optional(),schAutoLayoutEnabled:p.boolean().optional(),schTraceAutoLabelEnabled:p.boolean().optional(),schMaxTraceDistance:Y.optional(),routingDisabled:p.boolean().optional(),defaultTraceWidth:D.optional(),minTraceWidth:D.optional(),partsEngine:fz.optional(),pcbRouteCache:p.custom(e=>!0).optional(),autorouter:dz.optional(),square:p.boolean().optional(),emptyArea:p.string().optional(),filledArea:p.string().optional(),width:Y.optional(),height:Y.optional(),outline:p.array(Gs).optional(),outlineOffsetX:Y.optional(),outlineOffsetY:Y.optional(),circuitJson:p.array(p.any()).optional()}),A_t=OI.extend({subcircuit:p.literal(!0)}),mz=p.discriminatedUnion("subcircuit",[RI.extend({subcircuit:p.literal(!1).optional()}),A_t]);Ct(!0);Ct(!0);Ct(!0);Ct(!0);var Wp=p.custom(e=>typeof e=="string"),LI=OI.omit({connections:!0}).extend({material:p.enum(["fr4","fr1"]).default("fr4"),layers:p.union([p.literal(2),p.literal(4)]).default(2),borderRadius:Y.optional(),thickness:Y.optional(),boardAnchorPosition:Gs.optional(),boardAnchorAlignment:Zp.optional(),title:p.string().optional(),solderMaskColor:Wp.optional(),topSolderMaskColor:Wp.optional(),bottomSolderMaskColor:Wp.optional(),silkscreenColor:Wp.optional(),topSilkscreenColor:Wp.optional(),bottomSilkscreenColor:Wp.optional(),doubleSidedAssembly:p.boolean().optional().default(!1),schematicDisabled:p.boolean().optional()});Ct(!0);var _z=RI.omit({width:!0,height:!0,children:!0}).extend({width:Y,height:Y,children:p.any().optional(),noSolderMask:p.boolean().optional()});Ct(!0);var Djt=OI.extend({padding:Y.optional(),paddingLeft:Y.optional(),paddingRight:Y.optional(),paddingTop:Y.optional(),paddingBottom:Y.optional()});Ct(!0);var R_t=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),O_t=p.custom().pipe(p.record(p.string(),R_t)),L_t=p.record(ur,ur.or(p.array(ur).readonly()).or(p.array(ur)));Ct(!0);var F_t=p.object({manufacturerPartNumber:p.string().optional(),supplierPartNumber:p.record(Mp,p.array(p.string())).optional()}),Jp=Dn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:L_t.optional(),showPinAliases:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),externallyConnectedPins:p.array(p.array(p.string())).optional(),schPinArrangement:xf.optional(),schPortArrangement:xf.optional(),pinCompatibleVariants:p.array(F_t).optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),noSchematicRepresentation:p.boolean().optional(),connections:O_t.optional()});Ct(!0);var yz=Jp;Ct(!0);var FI=Dn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(ur),ur.or(p.array(ur))).optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),schDirection:p.enum(["left","right"]).optional(),schPinArrangement:AI.optional(),schPortArrangement:xf.optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),pinCount:p.union([p.literal(2),p.literal(3)]).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),connections:p.custom().pipe(p.record(p.string(),Kp)).optional()});Ct(!0);var gz=FI.extend({bridgedPins:p.array(p.array(p.string())).optional(),bridged:p.boolean().optional()});Ct(!0);var Gjt=Dn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(ur),ur.or(p.array(ur))).optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),schDirection:p.enum(["left","right"]).optional(),schPortArrangement:xf.optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),standard:p.enum(["usb_c","m2"]).optional()});Ct(!0);var bz=Dn.extend({currentRating:p.union([p.number(),p.string()]),voltageRating:p.union([p.number(),p.string()]).optional(),schShowRatings:p.boolean().optional(),schOrientation:tc.optional(),connections:p.record(p.string(),p.union([p.string(),p.array(p.string()).readonly(),p.array(p.string())])).optional()}),Wg=p.custom().transform(e=>{if(e!==void 0)return Y.parse(e)}),xz=p.discriminatedUnion("shape",[Oe.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circle"),holeDiameter:Y,outerDiameter:Y,portHints:es.optional()}),Oe.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("oval"),outerWidth:Y,outerHeight:Y,holeWidth:Wg,holeHeight:Wg,innerWidth:Y.optional().describe("DEPRECATED use holeWidth"),innerHeight:Y.optional().describe("DEPRECATED use holeHeight"),portHints:es.optional()}),Oe.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill"),rectPad:p.boolean().optional(),outerWidth:Y,outerHeight:Y,holeWidth:Wg,holeHeight:Wg,innerWidth:Y.optional().describe("DEPRECATED use holeWidth"),innerHeight:Y.optional().describe("DEPRECATED use holeHeight"),portHints:es.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional()}),Oe.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circular_hole_with_rect_pad"),holeDiameter:Y,rectPadWidth:Y,rectPadHeight:Y,rectBorderRadius:Y.optional(),holeShape:p.literal("circle").optional(),padShape:p.literal("rect").optional(),portHints:es.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional()}),Oe.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill_hole_with_rect_pad"),holeShape:p.literal("pill"),padShape:p.literal("rect"),holeWidth:Y,holeHeight:Y,rectPadWidth:Y,rectPadHeight:Y,portHints:es.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional()})]).refine(e=>("innerWidth"in e&&e.innerWidth!==void 0&&(e.holeWidth??(e.holeWidth=e.innerWidth)),"innerHeight"in e&&e.innerHeight!==void 0&&(e.holeHeight??(e.holeHeight=e.innerHeight)),e));Ct(!0);var z_t=["pin1","pin2","pos","neg"],vz=Dn.extend({resistance:Ha,pullupFor:p.string().optional(),pullupTo:p.string().optional(),pulldownFor:p.string().optional(),pulldownTo:p.string().optional(),schOrientation:tc.optional(),connections:jl(z_t).optional()}),Sz=kI;Ct(!0);var wz=Dn.extend({maxResistance:Ha,pinVariant:p.enum(["two_pin","three_pin"]).optional()});Ct(!0);var D_t=kI,Pz=Dn.extend({frequency:Wi,loadCapacitance:zs,manufacturerPartNumber:p.string().optional(),mpn:p.string().optional(),pinVariant:p.enum(["two_pin","four_pin"]).optional(),schOrientation:tc.optional(),connections:jl(D_t).optional()});Ct(!0);var Iz=Dn.extend({frequency:Wi,loadCapacitance:zs,pinVariant:p.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});Ct(!0);var sBt=LI.extend({leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftPins:p.array(p.string()).optional(),rightPins:p.array(p.string()).optional(),topPins:p.array(p.string()).optional(),bottomPins:p.array(p.string()).optional(),pinPitch:Y.optional(),innerHoles:p.boolean().optional()});Ct(!0);var $_t=["pin1","pin2","pos","neg","anode","cathode"],Tz=Dn.extend({capacitance:zs,maxVoltageRating:ai.optional(),schShowRatings:p.boolean().optional().default(!1),polarized:p.boolean().optional().default(!1),decouplingFor:p.string().optional(),decouplingTo:p.string().optional(),bypassFor:p.string().optional(),bypassTo:p.string().optional(),maxDecouplingTraceLength:p.number().optional(),schOrientation:tc.optional(),connections:jl($_t).optional()}),Mz=Jg;Ct(!0);var uBt=p.object({name:p.string(),connectsTo:p.string().or(p.array(p.string())).optional(),highlightColor:p.string().optional(),isPowerNet:p.boolean().optional(),isGroundNet:p.boolean().optional()});Ct(!0);var hBt=p.object({name:p.string().optional(),pcbOnly:p.boolean().optional(),schOnly:p.boolean().optional()});Ct(!0);var j_t=p.object({pcb:p.literal(!0).optional(),xDist:Y,left:p.string(),right:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});Ct(!0);var B_t=p.object({pcb:p.literal(!0).optional(),yDist:Y,top:p.string(),bottom:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});Ct(!0);var Y_t=p.object({pcb:p.literal(!0).optional(),sameY:p.literal(!0).optional(),for:p.array(p.string())});Ct(!0);var X_t=p.object({pcb:p.literal(!0).optional(),sameX:p.literal(!0).optional(),for:p.array(p.string())});Ct(!0);var Cz=p.union([j_t,B_t,Y_t,X_t]);Ct(!0);var V_t=Oe.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y});Ct(!0);var H_t=Oe.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:Y});Ct(!0);var G_t=Oe.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Gs)});Ct(!0);var Ez=p.discriminatedUnion("shape",[V_t,H_t,G_t]),U_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y,rectBorderRadius:Y.optional(),cornerRadius:Y.optional(),portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var q_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rotated_rect"),width:Y,height:Y,ccwRotation:p.number(),cornerRadius:Y.optional(),portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var W_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:Y,portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var Z_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("pill"),width:Y,height:Y,radius:Y,portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var K_t=Oe.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Gs),portHints:es.optional(),coveredWithSolderMask:p.boolean().optional()});Ct(!0);var Nz=p.discriminatedUnion("shape",[W_t,U_t,q_t,Z_t,K_t]);Ct(!0);var J_t=Oe.omit({pcbRotation:!0}).extend({shape:p.literal("rect"),width:Y,height:Y});Ct(!0);var Q_t=Oe.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:Y});Ct(!0);var yBt=p.union([Q_t,J_t]);Ct(!0);var tyt=Oe.extend({name:p.string().optional(),shape:p.literal("circle").optional(),diameter:Y.optional(),radius:Y.optional()}).transform(e=>({...e,diameter:e.diameter??2*e.radius,radius:e.radius??e.diameter/2})),eyt=Oe.extend({name:p.string().optional(),shape:p.literal("pill"),width:Y,height:Y}),nyt=Oe.extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y}),kz=p.union([tyt,eyt,nyt]);Ct(!0);var CI=p.union([p.string(),p.custom(e=>!!e.getPortSelector)]),sz=p.object({key:p.string().optional(),thickness:Y.optional(),width:Y.optional().describe("Alias for trace thickness"),schematicRouteHints:p.array(Gs).optional(),pcbRouteHints:p.array(Fi).optional(),pcbPathRelativeTo:p.string().optional(),pcbPath:p.array(p.union([Gs,p.string()])).optional(),schDisplayLabel:p.string().optional(),schStroke:p.string().optional(),highlightColor:p.string().optional(),maxLength:Y.optional()}),Az=p.union([sz.extend({path:p.array(CI)}),sz.extend({from:CI,to:CI})]),Rz=p.object({originalLayer:se.default("top").optional()});Ct(!0);var Oz=p.object({originalFacingDirection:p.enum(["up","down","left","right"]).default("right").optional()});Ct(!0);var iyt=p.number().or(p.string().endsWith("mAh")).transform(e=>{if(typeof e=="string"){let t=e.replace("mAh",""),n=Number.parseFloat(t);if(Number.isNaN(n))throw new Error("Invalid capacity");return n}return e}).describe("Battery capacity in mAh"),Lz=Dn.extend({capacity:iyt.optional(),voltage:ai.optional(),standard:p.enum(["AA","AAA","9V","CR2032","18650","C"]).optional(),schOrientation:tc.optional()});Ct(!0);var oyt=p.enum(["vertical","horizontal"]).describe("vertical means pins go 1->2 downward and horizontal means pins go 1->2 rightward");Ct(!0);var Fz=Dn.extend({pinCount:p.number(),pitch:Y.optional(),schFacingDirection:p.enum(["up","down","left","right"]).optional(),gender:p.enum(["male","female","unpopulated"]).optional().default("male"),showSilkscreenPinLabels:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),doubleRow:p.boolean().optional(),rightAngle:p.boolean().optional(),pcbOrientation:oyt.optional(),holeDiameter:Y.optional(),platedDiameter:Y.optional(),pinLabels:p.record(p.string(),ur).or(p.array(ur)).optional(),connections:p.custom().pipe(p.record(p.string(),Kp)).optional(),facingDirection:p.enum(["left","right"]).optional(),schPinArrangement:AI.optional(),schPinStyle:vf.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional()});Ct(!0);var kBt=p.object({net:p.string().optional(),connection:p.string().optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Be.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});Ct(!0);var zz=p.object({net:p.string().optional(),connection:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Be.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});Ct(!0);var Dz=Jp.extend({});Ct(!0);Ct(!0);var ryt=p.custom(e=>typeof e=="string"),$z=p.object({simulationType:p.literal("spice_transient_analysis").default("spice_transient_analysis"),duration:qi.optional(),timePerStep:qi.optional(),spiceEngine:ryt.optional()});Ct(!0);var syt=["pin1","pin2","pin3","emitter","collector","base","gate","source","drain"],jz=Dn.extend({type:p.enum(["npn","pnp","bjt","jfet","mosfet","igbt"]),connections:jl(syt).optional()});Ct(!0);var Bz=Dn.extend({channelType:p.enum(["n","p"]),mosfetMode:p.enum(["enhancement","depletion"])});Ct(!0);var ayt=kI,Yz=Dn.extend({inductance:I_,maxCurrentRating:p.union([p.string(),p.number()]).optional(),schOrientation:tc.optional(),connections:jl(ayt).optional()});Ct(!0);var cyt=p.enum(["anode","cathode","pin1","pin2","pos","neg"]),lyt=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),uyt=p.record(cyt,lyt),pyt=p.enum(["standard","schottky","zener","avalanche","photo","tvs"]),Xz=Dn.extend({connections:uyt.optional(),variant:pyt.optional().default("standard"),standard:p.boolean().optional(),schottky:p.boolean().optional(),zener:p.boolean().optional(),avalanche:p.boolean().optional(),photo:p.boolean().optional(),tvs:p.boolean().optional(),schOrientation:tc.optional()}).superRefine((e,t)=>{if([e.standard,e.schottky,e.zener,e.avalanche,e.photo,e.tvs].filter(Boolean).length>1)return t.addIssue({code:p.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),p.INVALID}).transform(e=>{let t={...e,standard:!1,schottky:!1,zener:!1,avalanche:!1,photo:!1,tvs:!1};if(e.standard)t.standard=!0;else if(e.schottky)t.schottky=!0;else if(e.zener)t.zener=!0;else if(e.photo)t.photo=!0;else if(e.tvs)t.tvs=!0;else switch(e.variant){case"standard":t.standard=!0;break;case"schottky":t.schottky=!0;break;case"zener":t.zener=!0;break;case"avalanche":t.avalanche=!0;break;case"photo":t.photo=!0;break;case"tvs":t.tvs=!0;break;default:t.standard=!0}return t}),Vz=Jg;Ct(!0);var Hz=Dn.extend({color:p.string().optional(),wavelength:p.string().optional(),schDisplayValue:p.string().optional(),schOrientation:tc.optional(),connections:jl(Jg).optional(),laser:p.boolean().optional()}),Gz=Jg,Uz=Dn.extend({type:p.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:p.boolean().optional().default(!1),spst:p.boolean().optional(),spdt:p.boolean().optional(),dpst:p.boolean().optional(),dpdt:p.boolean().optional(),simSwitchFrequency:Wi.optional(),simCloseAt:qi.optional(),simOpenAt:qi.optional(),simStartClosed:p.boolean().optional(),simStartOpen:p.boolean().optional(),connections:p.custom().pipe(p.record(p.string(),Kp)).optional()}).transform(e=>{let t={...e};switch(t.dpdt?t.type="dpdt":t.spst?t.type="spst":t.spdt?t.type="spdt":t.dpst&&(t.type="dpst"),t.type){case"spdt":t.spdt=!0;break;case"spst":t.spst=!0;break;case"dpst":t.dpst=!0;break;case"dpdt":t.dpdt=!0;break}return t});Ct(!0);var qz=Oe.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional()});Ct(!0);var Wz=Oe.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional(),cornerRadius:Y.optional()}),Zz=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Fi),strokeWidth:D.optional(),color:p.string().optional()}),az=p.union([p.string(),Gs]),Kz=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:az,to:az,text:p.string().optional(),offset:Y.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional(),arrowSize:Y.optional(),units:p.enum(["in","mm"]).optional(),outerEdgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional(),innerEdgeToEdge:p.literal(!0).optional()});Ct(!0);var tYt=p.object({layer:p.string().optional(),thickness:Y.optional(),route:p.array(Fi)}),Jz=Kg.extend({name:p.string().optional(),fromLayer:se,toLayer:se,holeDiameter:Y,outerDiameter:Y,connectsTo:p.string().or(p.array(p.string())).optional(),netIsAssignable:p.boolean().optional()});Ct(!0);var hyt=p.object({pin1:Kp}).strict(),Qz=Dn.extend({connections:hyt.optional(),footprintVariant:p.enum(["pad","through_hole"]).optional(),padShape:p.enum(["rect","circle"]).optional().default("circle"),padDiameter:Y.optional(),holeDiameter:Y.optional(),width:Y.optional(),height:Y.optional()}).refine(e=>e.footprintVariant!=="through_hole"||e.holeDiameter!==void 0,{message:"holeDiameter is required for through_hole testpoints"});Ct(!0);var tD=Oe.omit({pcbRotation:!0,layer:!0}).extend({connection:p.string()});Ct(!0);var eD=p.union([Oe.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:Y}),Oe.extend({shape:p.literal("rect"),width:Y,height:Y})]),uYt=Oe.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),dYt=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({outline:p.array(Gs),strokeWidth:D.optional(),isClosed:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),nD=p.object({name:p.string().optional(),layer:se,connectsTo:p.string(),padMargin:Y.optional(),traceMargin:Y.optional(),clearance:Y.optional(),boardEdgeMargin:Y.optional(),cutoutMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional().default(!0)});Ct(!0);var iD=p.object({originalLayer:se.default("top").optional(),children:p.any().optional()});Ct(!0);var dyt=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbZ:Y.optional()}),fyt=Qa.extend({modelUrl:p.string(),stepUrl:p.string().optional()}),myt=fyt.merge(dyt);Ct(!0);var oD=p.union([p.null(),p.string(),myt]),rD=Dn.extend({voltage:ai}),_yt=["pin1","pin2","pos","neg"],yyt=p.union([p.string(),p.number()]).transform(e=>typeof e=="string"?e.endsWith("%")?parseFloat(e.slice(0,-1))/100:parseFloat(e):e).pipe(p.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),SYt=Dn.extend({voltage:ai.optional(),frequency:Wi.optional(),peakToPeakVoltage:ai.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Be.optional(),dutyCycle:yyt.optional(),connections:jl(_yt).optional()});Ct(!0);var sD=Dn.omit({name:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string()))});Ct(!0);var aD=p.object({center:qt,radius:Y,startAngleDegrees:Be,endAngleDegrees:Be,direction:p.enum(["clockwise","counterclockwise"]).default("counterclockwise"),strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),cD=p.object({schX:Y.optional(),schY:Y.optional(),width:Y.optional(),height:Y.optional(),overlay:p.array(p.string()).optional(),padding:Y.optional(),paddingLeft:Y.optional(),paddingRight:Y.optional(),paddingTop:Y.optional(),paddingBottom:Y.optional(),title:p.string().optional(),titleAlignment:Zp.default("top_left"),titleColor:p.string().optional(),titleFontSize:Y.optional(),titleInside:p.boolean().default(!1),strokeStyle:p.enum(["solid","dashed"]).default("solid")}).refine(e=>e.width!==void 0&&e.height!==void 0||Array.isArray(e.overlay)&&e.overlay.length>0,{message:"Must provide either both `width` and `height`, or a non-empty `overlay` array."}).refine(e=>!(e.width!==void 0&&e.height!==void 0&&Array.isArray(e.overlay)&&e.overlay.length>0),{message:"Cannot provide both `width`/`height` and `overlay` at the same time."}),lD=p.object({center:qt,radius:Y,strokeWidth:Y.optional(),color:p.string().optional(),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),uD=p.object({schX:Y.optional(),schY:Y.optional(),width:Y,height:Y,rotation:Be.default(0),strokeWidth:Y.optional(),color:p.string().optional(),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1),cornerRadius:Y.optional()}),pD=p.object({x1:Y,y1:Y,x2:Y,y2:Y,strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),gyt=p.enum(["center","left","right","top","bottom"]),hD=p.object({schX:Y.optional(),schY:Y.optional(),text:p.string(),fontSize:p.number().default(1),anchor:p.union([gyt.describe("legacy"),Zp]).default("center"),color:p.string().default("#000000"),schRotation:Be.default(0)}),$Yt=p.object({points:p.array(qt),isFilled:p.boolean().optional().default(!1),fillColor:p.enum(["red","blue"]).optional()}),dD=p.object({schX:Y.optional(),schY:Y.optional(),children:p.any().optional(),cellPadding:Y.optional(),borderWidth:Y.optional(),anchor:Zp.optional(),fontSize:Y.optional()});Ct(!0);var fD=p.object({children:p.any().optional(),height:Y.optional()});Ct(!0);var mD=p.object({children:p.string().optional(),horizontalAlign:p.enum(["left","center","right"]).optional(),verticalAlign:p.enum(["top","middle","bottom"]).optional(),fontSize:Y.optional(),rowSpan:p.number().optional(),colSpan:p.number().optional(),width:Y.optional(),text:p.string().optional()});Ct(!0);var qYt=Oe.extend({text:p.string(),anchorAlignment:Zp.default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),layers:p.array(se).optional()}),_D=Oe.extend({text:p.string(),anchorAlignment:Zp.default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),isKnockout:p.boolean().optional(),knockoutPadding:D.optional(),knockoutPaddingLeft:D.optional(),knockoutPaddingRight:D.optional(),knockoutPaddingTop:D.optional(),knockoutPaddingBottom:D.optional(),layers:p.array(se).optional()}),yD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Fi),strokeWidth:D.optional()}),gD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({strokeWidth:Y,x1:Y,y1:Y,x2:Y,y2:Y}),bD=Oe.omit({pcbRotation:!0}).extend({filled:p.boolean().default(!0).optional(),stroke:p.enum(["dashed","solid","none"]).optional(),strokeWidth:Y.optional(),width:Y,height:Y,cornerRadius:Y.optional()}),xD=Oe.omit({pcbRotation:!0}).extend({isFilled:p.boolean().optional(),isOutline:p.boolean().optional(),strokeWidth:Y.optional(),radius:Y}),cz=p.object({x:Y,y:Y,via:p.boolean().optional(),toLayer:se.optional()}),vD=p.object({for:p.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:p.number().optional(),offset:Fi.or(cz).optional(),offsets:p.array(Fi).or(p.array(cz)).optional(),traceWidth:p.number().optional()}),aXt=Kg.extend({name:p.string(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),direction:c_t,connectsTo:p.string().or(p.array(p.string())).optional()}),SD=Oe.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional()});Ct(!0);var wD=Oe.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional(),cornerRadius:Y.optional()});Ct(!0);var PD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Fi),strokeWidth:D.optional(),color:p.string().optional()});Ct(!0);var ID=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({x1:Y,y1:Y,x2:Y,y2:Y,strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional()});Ct(!0);var lz=p.union([p.string(),Gs]),TD=Oe.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:lz,to:lz,text:p.string().optional(),offset:Y.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional(),arrowSize:Y.optional(),units:p.enum(["in","mm"]).optional(),outerEdgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional(),innerEdgeToEdge:p.literal(!0).optional()});Ct(!0);var MD=p.array(p.any()).describe("Circuit JSON"),EI=p.object({footprintCircuitJson:p.array(p.any()),cadModel:hz.optional()}),uz=p.function().args(p.string()).returns(p.promise(EI)).or(p.function().args(p.string(),p.object({resolvedPcbStyle:NI.optional()}).optional()).returns(p.promise(EI))).describe("A function that takes a path and returns Circuit JSON"),byt=p.object({loadFromUrl:p.function().args(p.string()).returns(p.promise(EI)).describe("A function that takes a footprint file URL and returns Circuit JSON")}),xyt=p.object({engineVersionString:p.string().optional(),simulationResultCircuitJson:MD}),vyt=p.object({simulate:p.function().args(p.string()).returns(p.promise(xyt)).describe("A function that takes a SPICE string and returns a simulation result")}),Syt=p.custom(e=>typeof e=="string"),pz=p.object({run:p.function().args().returns(p.promise(p.unknown())).describe("Run the autorouter"),getOutputSimpleRouteJson:p.function().args().returns(p.promise(p.any())).describe("Get the resulting SimpleRouteJson")}),wyt=p.object({createAutorouter:p.function().args(p.any(),p.any().optional()).returns(p.union([pz,p.promise(pz)])).describe("Create an autorouter instance")}),Pyt=p.object({partsEngine:fz.optional(),autorouter:dz.optional(),autorouterMap:p.record(p.string(),wyt).optional(),registryApiUrl:p.string().optional(),cloudAutorouterUrl:p.string().optional(),projectName:p.string().optional(),projectBaseUrl:p.string().optional(),version:p.string().optional(),url:p.string().optional(),printBoardInformationToSilkscreen:p.boolean().optional(),includeBoardFiles:p.array(p.string()).describe('The board files to automatically build with "tsci build", defaults to ["**/*.circuit.tsx"]. Can be an array of files or globs').optional(),snapshotsDir:p.string().describe('The directory where snapshots are stored for "tsci snapshot", defaults to "tests/__snapshots__"').optional(),defaultSpiceEngine:Syt.optional(),localCacheEngine:p.any().optional(),pcbDisabled:p.boolean().optional(),schematicDisabled:p.boolean().optional(),partsEngineDisabled:p.boolean().optional(),spiceEngineMap:p.record(p.string(),vyt).optional(),footprintLibraryMap:p.record(p.string(),p.union([uz,p.record(p.string(),p.union([MD,uz]))])).optional(),footprintFileParserMap:p.record(p.string(),byt).optional(),resolveProjectStaticFileImportUrl:p.function().args(p.string()).returns(p.promise(p.string())).describe("A function that returns a string URL for static files for the project").optional()});Ct(!0);var Iyt=Pyt,bXt=Iyt.pick({projectName:!0,projectBaseUrl:!0,version:!0,url:!0,printBoardInformationToSilkscreen:!0,includeBoardFiles:!0,snapshotsDir:!0,defaultSpiceEngine:!0});Ct(!0);vt();K();vt();Ys();K();var ca=Xt(Mr(),1);Ys();K();function ec(){return new zI}var zI=class e{constructor(){P(this,"index",{});P(this,"array",[])}size(){return this.array.length}empty(){return this.array.length===0}itemAt(t){return this.array[t]}contains(t){return this.index[t.id()]!==void 0}find(t){let n=this.index[t.id()];return n===void 0?void 0:this.array[n]}setDefault(t,n){let i=this.index[t.id()];if(i===void 0){let o=new Qg(t,n());return this.index[t.id()]=this.array.length,this.array.push(o),o}else return this.array[i]}insert(t,n){let i=new Qg(t,n),o=this.index[t.id()];return o===void 0?(this.index[t.id()]=this.array.length,this.array.push(i)):this.array[o]=i,i}erase(t){let n=this.index[t.id()];if(n===void 0)return;this.index[t.id()]=void 0;let i=this.array[n],o=this.array.pop();return i!==o&&(this.array[n]=o,this.index[o.first.id()]=n),i}copy(){let t=new e;for(let n=0;n<this.array.length;n++){let i=this.array[n].copy();t.array[n]=i,t.index[i.first.id()]=n}return t}},Qg=class e{constructor(t,n){P(this,"first");P(this,"second");this.first=t,this.second=n}copy(){return new e(this.first,this.second)}};var Us=class{constructor(t=""){P(this,"_name");P(this,"_value",0);P(this,"_context",null);P(this,"_id",Tyt++);this._name=t}id(){return this._id}name(){return this._name}setName(t){this._name=t}context(){return this._context}setContext(t){this._context=t}value(){return this._value}setValue(t){this._value=t}plus(t){return new Cn(this,t)}minus(t){return new Cn(this,typeof t=="number"?-t:[-1,t])}multiply(t){return new Cn([t,this])}divide(t){return new Cn([1/t,this])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},Tyt=0;var Cn=class e{constructor(){P(this,"_terms");P(this,"_constant");let t=Myt(arguments);this._terms=t.terms,this._constant=t.constant}terms(){return this._terms}constant(){return this._constant}value(){let t=this._constant;for(let n=0,i=this._terms.size();n<i;n++){let o=this._terms.itemAt(n);t+=o.first.value()*o.second}return t}plus(t){return new e(this,t)}minus(t){return new e(this,typeof t=="number"?-t:[-1,t])}multiply(t){return new e([t,this])}divide(t){return new e([1/t,this])}isConstant(){return this._terms.size()==0}toString(){let t=this._terms.array.map(function(n){return n.second+"*"+n.first.toString()}).join(" + ");return!this.isConstant()&&this._constant!==0&&(t+=" + "),t+=this._constant,t}};function Myt(e){let t=0,n=()=>0,i=ec();for(let o=0,r=e.length;o<r;++o){let s=e[o];if(typeof s=="number")t+=s;else if(s instanceof Us)i.setDefault(s,n).second+=1;else if(s instanceof Cn){t+=s.constant();let a=s.terms();for(let c=0,l=a.size();c<l;c++){let u=a.itemAt(c);i.setDefault(u.first,n).second+=u.second}}else if(s instanceof Array){if(s.length!==2)throw new Error("array must have length 2");let a=s[0],c=s[1];if(typeof a!="number")throw new Error("array item 0 must be a number");if(c instanceof Us)i.setDefault(c,n).second+=a;else if(c instanceof Cn){t+=c.constant()*a;let l=c.terms();for(let u=0,h=l.size();u<h;u++){let d=l.itemAt(u);i.setDefault(d.first,n).second+=d.second*a}}else throw new Error("array item 1 must be a variable or expression")}else throw new Error("invalid Expression argument: "+s)}return{terms:i,constant:t}}var Lr=class Lr{static create(t,n,i,o=1){let r=0;return r+=Math.max(0,Math.min(1e3,t*o))*1e6,r+=Math.max(0,Math.min(1e3,n*o))*1e3,r+=Math.max(0,Math.min(1e3,i*o)),r}static clip(t){return Math.max(0,Math.min(Lr.required,t))}};P(Lr,"required",Lr.create(1e3,1e3,1e3)),P(Lr,"strong",Lr.create(1,0,0)),P(Lr,"medium",Lr.create(0,1,0)),P(Lr,"weak",Lr.create(0,0,1));var wn=Lr;var Vn;(function(e){e[e.Le=0]="Le",e[e.Ge=1]="Ge",e[e.Eq=2]="Eq"})(Vn||(Vn={}));var ci=class{constructor(t,n,i,o=wn.required){P(this,"_expression");P(this,"_operator");P(this,"_strength");P(this,"_id",Cyt++);this._operator=n,this._strength=wn.clip(o),i===void 0&&t instanceof Cn?this._expression=t:this._expression=t.minus(i)}id(){return this._id}expression(){return this._expression}op(){return this._operator}strength(){return this._strength}toString(){return this._expression.toString()+" "+["<=",">=","="][this._operator]+" 0 ("+this._strength.toString()+")"}},Cyt=0;var Qp=class{constructor(){P(this,"maxIterations",1e3);P(this,"_cnMap",Eyt());P(this,"_rowMap",Nyt());P(this,"_varMap",kyt());P(this,"_editMap",Ayt());P(this,"_infeasibleRows",[]);P(this,"_objective",new nb);P(this,"_artificial",null);P(this,"_idTick",0)}createConstraint(t,n,i,o=wn.required){let r=new ci(t,n,i,o);return this.addConstraint(r),r}addConstraint(t){if(this._cnMap.find(t)!==void 0)throw new Error("duplicate constraint");let i=this._createRow(t),o=i.row,r=i.tag,s=this._chooseSubject(o,r);if(s.type()===Ue.Invalid&&o.allDummies())if(tb(o.constant()))s=r.marker;else throw new Error("unsatisfiable constraint");if(s.type()===Ue.Invalid){if(!this._addWithArtificialVariable(o))throw new Error("unsatisfiable constraint")}else o.solveFor(s),this._substitute(s,o),this._rowMap.insert(s,o);this._cnMap.insert(t,r),this._optimize(this._objective)}removeConstraint(t){let n=this._cnMap.erase(t);if(n===void 0)throw new Error("unknown constraint");this._removeConstraintEffects(t,n.second);let i=n.second.marker,o=this._rowMap.erase(i);if(o===void 0){let r=this._getMarkerLeavingSymbol(i);if(r.type()===Ue.Invalid)throw new Error("failed to find leaving row");o=this._rowMap.erase(r),o.second.solveForEx(r,i),this._substitute(i,o.second)}this._optimize(this._objective)}hasConstraint(t){return this._cnMap.contains(t)}getConstraints(){return this._cnMap.array.map(({first:t})=>t)}addEditVariable(t,n){if(this._editMap.find(t)!==void 0)throw new Error("duplicate edit variable");if(n=wn.clip(n),n===wn.required)throw new Error("bad required strength");let o=new Cn(t),r=new ci(o,Vn.Eq,void 0,n);this.addConstraint(r);let a={tag:this._cnMap.find(r).second,constraint:r,constant:0};this._editMap.insert(t,a)}removeEditVariable(t){let n=this._editMap.erase(t);if(n===void 0)throw new Error("unknown edit variable");this.removeConstraint(n.second.constraint)}hasEditVariable(t){return this._editMap.contains(t)}suggestValue(t,n){let i=this._editMap.find(t);if(i===void 0)throw new Error("unknown edit variable");let o=this._rowMap,r=i.second,s=n-r.constant;r.constant=n;let a=r.tag.marker,c=o.find(a);if(c!==void 0){c.second.add(-s)<0&&this._infeasibleRows.push(a),this._dualOptimize();return}let l=r.tag.other;if(c=o.find(l),c!==void 0){c.second.add(s)<0&&this._infeasibleRows.push(l),this._dualOptimize();return}for(let u=0,h=o.size();u<h;++u){let d=o.itemAt(u),_=d.second,y=_.coefficientFor(a);y!==0&&_.add(s*y)<0&&d.first.type()!==Ue.External&&this._infeasibleRows.push(d.first)}this._dualOptimize()}updateVariables(){let t=this._varMap,n=this._rowMap;for(let i=0,o=t.size();i<o;++i){let r=t.itemAt(i),s=n.find(r.second);s!==void 0?r.first.setValue(s.second.constant()):r.first.setValue(0)}}_getVarSymbol(t){let n=()=>this._makeSymbol(Ue.External);return this._varMap.setDefault(t,n).second}_createRow(t){let n=t.expression(),i=new nb(n.constant()),o=n.terms();for(let c=0,l=o.size();c<l;++c){let u=o.itemAt(c);if(!tb(u.second)){let h=this._getVarSymbol(u.first),d=this._rowMap.find(h);d!==void 0?i.insertRow(d.second,u.second):i.insertSymbol(h,u.second)}}let r=this._objective,s=t.strength(),a={marker:nc,other:nc};switch(t.op()){case Vn.Le:case Vn.Ge:{let c=t.op()===Vn.Le?1:-1,l=this._makeSymbol(Ue.Slack);if(a.marker=l,i.insertSymbol(l,c),s<wn.required){let u=this._makeSymbol(Ue.Error);a.other=u,i.insertSymbol(u,-c),r.insertSymbol(u,s)}break}case Vn.Eq:{if(s<wn.required){let c=this._makeSymbol(Ue.Error),l=this._makeSymbol(Ue.Error);a.marker=c,a.other=l,i.insertSymbol(c,-1),i.insertSymbol(l,1),r.insertSymbol(c,s),r.insertSymbol(l,s)}else{let c=this._makeSymbol(Ue.Dummy);a.marker=c,i.insertSymbol(c)}break}}return i.constant()<0&&i.reverseSign(),{row:i,tag:a}}_chooseSubject(t,n){let i=t.cells();for(let r=0,s=i.size();r<s;++r){let a=i.itemAt(r);if(a.first.type()===Ue.External)return a.first}let o=n.marker.type();return(o===Ue.Slack||o===Ue.Error)&&t.coefficientFor(n.marker)<0?n.marker:(o=n.other.type(),(o===Ue.Slack||o===Ue.Error)&&t.coefficientFor(n.other)<0?n.other:nc)}_addWithArtificialVariable(t){let n=this._makeSymbol(Ue.Slack);this._rowMap.insert(n,t.copy()),this._artificial=t.copy(),this._optimize(this._artificial);let i=tb(this._artificial.constant());this._artificial=null;let o=this._rowMap.erase(n);if(o!==void 0){let s=o.second;if(s.isConstant())return i;let a=this._anyPivotableSymbol(s);if(a.type()===Ue.Invalid)return!1;s.solveForEx(n,a),this._substitute(a,s),this._rowMap.insert(a,s)}let r=this._rowMap;for(let s=0,a=r.size();s<a;++s)r.itemAt(s).second.removeSymbol(n);return this._objective.removeSymbol(n),i}_substitute(t,n){let i=this._rowMap;for(let o=0,r=i.size();o<r;++o){let s=i.itemAt(o);s.second.substitute(t,n),s.second.constant()<0&&s.first.type()!==Ue.External&&this._infeasibleRows.push(s.first)}this._objective.substitute(t,n),this._artificial&&this._artificial.substitute(t,n)}_optimize(t){let n=0;for(;n<this.maxIterations;){let i=this._getEnteringSymbol(t);if(i.type()===Ue.Invalid)return;let o=this._getLeavingSymbol(i);if(o.type()===Ue.Invalid)throw new Error("the objective is unbounded");let r=this._rowMap.erase(o).second;r.solveForEx(o,i),this._substitute(i,r),this._rowMap.insert(i,r),n++}throw new Error("solver iterations exceeded")}_dualOptimize(){let t=this._rowMap,n=this._infeasibleRows;for(;n.length!==0;){let i=n.pop(),o=t.find(i);if(o!==void 0&&o.second.constant()<0){let r=this._getDualEnteringSymbol(o.second);if(r.type()===Ue.Invalid)throw new Error("dual optimize failed");let s=o.second;t.erase(i),s.solveForEx(i,r),this._substitute(r,s),t.insert(r,s)}}}_getEnteringSymbol(t){let n=t.cells();for(let i=0,o=n.size();i<o;++i){let r=n.itemAt(i),s=r.first;if(r.second<0&&s.type()!==Ue.Dummy)return s}return nc}_getDualEnteringSymbol(t){let n=Number.MAX_VALUE,i=nc,o=t.cells();for(let r=0,s=o.size();r<s;++r){let a=o.itemAt(r),c=a.first,l=a.second;if(l>0&&c.type()!==Ue.Dummy){let h=this._objective.coefficientFor(c)/l;h<n&&(n=h,i=c)}}return i}_getLeavingSymbol(t){let n=Number.MAX_VALUE,i=nc,o=this._rowMap;for(let r=0,s=o.size();r<s;++r){let a=o.itemAt(r),c=a.first;if(c.type()!==Ue.External){let l=a.second,u=l.coefficientFor(t);if(u<0){let h=-l.constant()/u;h<n&&(n=h,i=c)}}}return i}_getMarkerLeavingSymbol(t){let n=Number.MAX_VALUE,i=n,o=n,r=nc,s=r,a=r,c=r,l=this._rowMap;for(let u=0,h=l.size();u<h;++u){let d=l.itemAt(u),_=d.second,y=_.coefficientFor(t);if(y===0)continue;let g=d.first;if(g.type()===Ue.External)c=g;else if(y<0){let x=-_.constant()/y;x<i&&(i=x,s=g)}else{let x=_.constant()/y;x<o&&(o=x,a=g)}}return s!==r?s:a!==r?a:c}_removeConstraintEffects(t,n){n.marker.type()===Ue.Error&&this._removeMarkerEffects(n.marker,t.strength()),n.other.type()===Ue.Error&&this._removeMarkerEffects(n.other,t.strength())}_removeMarkerEffects(t,n){let i=this._rowMap.find(t);i!==void 0?this._objective.insertRow(i.second,-n):this._objective.insertSymbol(t,-n)}_anyPivotableSymbol(t){let n=t.cells();for(let i=0,o=n.size();i<o;++i){let r=n.itemAt(i),s=r.first.type();if(s===Ue.Slack||s===Ue.Error)return r.first}return nc}_makeSymbol(t){return new eb(t,this._idTick++)}};function tb(e){let t=1e-8;return e<0?-e<t:e<t}function Eyt(){return ec()}function Nyt(){return ec()}function kyt(){return ec()}function Ayt(){return ec()}var Ue;(function(e){e[e.Invalid=0]="Invalid",e[e.External=1]="External",e[e.Slack=2]="Slack",e[e.Error=3]="Error",e[e.Dummy=4]="Dummy"})(Ue||(Ue={}));var eb=class{constructor(t,n){P(this,"_id");P(this,"_type");this._id=n,this._type=t}id(){return this._id}type(){return this._type}},nc=new eb(Ue.Invalid,-1),nb=class e{constructor(t=0){P(this,"_cellMap",ec());P(this,"_constant");this._constant=t}cells(){return this._cellMap}constant(){return this._constant}isConstant(){return this._cellMap.empty()}allDummies(){let t=this._cellMap;for(let n=0,i=t.size();n<i;++n)if(t.itemAt(n).first.type()!==Ue.Dummy)return!1;return!0}copy(){let t=new e(this._constant);return t._cellMap=this._cellMap.copy(),t}add(t){return this._constant+=t}insertSymbol(t,n=1){let i=this._cellMap.setDefault(t,()=>0);tb(i.second+=n)&&this._cellMap.erase(t)}insertRow(t,n=1){this._constant+=t._constant*n;let i=t._cellMap;for(let o=0,r=i.size();o<r;++o){let s=i.itemAt(o);this.insertSymbol(s.first,s.second*n)}}removeSymbol(t){this._cellMap.erase(t)}reverseSign(){this._constant=-this._constant;let t=this._cellMap;for(let n=0,i=t.size();n<i;++n){let o=t.itemAt(n);o.second=-o.second}}solveFor(t){let n=this._cellMap,o=-1/n.erase(t).second;this._constant*=o;for(let r=0,s=n.size();r<s;++r)n.itemAt(r).second*=o}solveForEx(t,n){this.insertSymbol(t,-1),this.solveFor(n)}coefficientFor(t){let n=this._cellMap.find(t);return n!==void 0?n.second:0}substitute(t,n){let i=this._cellMap.erase(t);i!==void 0&&this.insertRow(n,i.second)}};var RH=Xt(Sn(),1);K();vt();vt();ji();var YI={};il(YI,{areBoundsCompletelyInsidePolygon:()=>BI,areBoundsOverlappingPolygon:()=>jI,boundsAreaOverlap:()=>jD,boundsDistance:()=>BD,boundsIntersection:()=>YD,clamp:()=>Rn,computeDistanceBetweenBoxes:()=>ts,computeGapBetweenBoxes:()=>II,computeManhattanDistanceBetweenBoxes:()=>yf,distSq:()=>RD,distance:()=>vi,doBoundsOverlap:()=>ic,doSegmentsIntersect:()=>li,doesLineIntersectLine:()=>qs,doesSegmentIntersectRect:()=>DI,findNearestPointsBetweenBoxSets:()=>gf,getBoundingBox:()=>Or,getBoundsFromPoints:()=>ns,getSegmentIntersection:()=>Xl,getUnitVectorFromDirection:()=>ab,getUnitVectorFromPointAToB:()=>sb,grid:()=>XD,isPointInsidePolygon:()=>rb,isRectCompletelyInsidePolygon:()=>DD,isRectOverlappingPolygon:()=>zD,midpoint:()=>AD,normalizeDegrees:()=>Vl,onSegment:()=>Yl,orientation:()=>Bl,pointToBoundsDistance:()=>kD,pointToBoxDistance:()=>ND,pointToSegmentClosestPoint:()=>ED,pointToSegmentDistance:()=>ei,range:()=>$D,segmentToBoundsMinDistance:()=>wf,segmentToBoxMinDistance:()=>ib,segmentToCircleMinDistance:()=>ob,segmentToSegmentMinDistance:()=>th});function qs([e,t],[n,i],{lineThickness:o=0}={}){return o===0?li(e,t,n,i):Ryt(e,t,n,i)<=o}function li(e,t,n,i){let o=Bl(e,t,n),r=Bl(e,t,i),s=Bl(n,i,e),a=Bl(n,i,t);return!!(o!==r&&s!==a||o===0&&Yl(e,n,t)||r===0&&Yl(e,i,t)||s===0&&Yl(n,e,i)||a===0&&Yl(n,t,i))}function Bl(e,t,n){let i=(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y);return i===0?0:i>0?1:2}function Yl(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function Ryt(e,t,n,i){if(e.x===t.x&&e.y===t.y)return ei(e,n,i);if(n.x===i.x&&n.y===i.y)return ei(n,e,t);if(li(e,t,n,i))return 0;let o=[ei(e,n,i),ei(t,n,i),ei(n,e,t),ei(i,e,t)];return Math.min(...o)}function ei(e,t,n){let i=(n.x-t.x)**2+(n.y-t.y)**2;if(i===0)return vi(e,t);let o=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/i;o=Math.max(0,Math.min(1,o));let r={x:t.x+o*(n.x-t.x),y:t.y+o*(n.y-t.y)};return vi(e,r)}function vi(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}function Xl(e,t,n,i){let o=t.x-e.x,r=t.y-e.y,s=i.x-n.x,a=i.y-n.y,c=e.x-n.x,l=e.y-n.y,u=o*a-r*s;if(Math.abs(u)<1e-10)return null;let h=(l*s-c*a)/u,d=(o*l-r*c)/u,_=1e-9;if(h>=-_&&h<=1+_&&d>=-_&&d<=1+_){let y=e.x+h*o,g=e.y+h*r;return{x:y,y:g}}return null}function DI(e,t,n){let i=c=>c.x>=n.minX&&c.x<=n.maxX&&c.y>=n.minY&&c.y<=n.maxY;if(i(e)||i(t))return!0;let o={x:n.minX,y:n.minY},r={x:n.maxX,y:n.minY},s={x:n.minX,y:n.maxY},a={x:n.maxX,y:n.maxY};return li(e,t,o,r)||li(e,t,r,a)||li(e,t,a,s)||li(e,t,s,o)}function th(e,t,n,i){if(e.x===t.x&&e.y===t.y)return ei(e,n,i);if(n.x===i.x&&n.y===i.y)return ei(n,e,t);if(li(e,t,n,i))return 0;let o=[ei(e,n,i),ei(t,n,i),ei(n,e,t),ei(i,e,t)];return Math.min(...o)}function wf(e,t,n){let i={x:n.minX,y:n.minY},o={x:n.maxX,y:n.minY},r={x:n.minX,y:n.maxY},s={x:n.maxX,y:n.maxY};if(li(e,t,i,o)||li(e,t,o,s)||li(e,t,s,r)||li(e,t,r,i)||e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY&&t.x>=n.minX&&t.x<=n.maxX&&t.y>=n.minY&&t.y<=n.maxY)return 0;let a=[ei(i,e,t),ei(o,e,t),ei(r,e,t),ei(s,e,t)];if(e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY||t.x>=n.minX&&t.x<=n.maxX&&t.y>=n.minY&&t.y<=n.maxY)return 0;if(e.x<n.minX||e.x>n.maxX||e.y<n.minY||e.y>n.maxY){let c=Rn(e.x,n.minX,n.maxX),l=Rn(e.y,n.minY,n.maxY);a.push(vi(e,{x:c,y:l}))}if(t.x<n.minX||t.x>n.maxX||t.y<n.minY||t.y>n.maxY){let c=Rn(t.x,n.minX,n.maxX),l=Rn(t.y,n.minY,n.maxY);a.push(vi(t,{x:c,y:l}))}return Math.min(...a)}function ib(e,t,n){let i=n.width/2,o=n.height/2,r={minX:n.center.x-i,maxX:n.center.x+i,minY:n.center.y-o,maxY:n.center.y+o};return wf(e,t,r)}function ob(e,t,n){let i={x:n.x,y:n.y};if(e.x===t.x&&e.y===t.y)return Math.max(0,vi(e,i)-n.radius);let o={x:t.x-e.x,y:t.y-e.y},r={x:i.x-e.x,y:i.y-e.y},s=o.x*o.x+o.y*o.y,a=Math.max(0,Math.min(1,(o.x*r.x+o.y*r.y)/s)),c={x:e.x+a*o.x,y:e.y+a*o.y},l=vi(c,i);return Math.max(0,l-n.radius)}function ED(e,t,n){let i=n.x-t.x,o=n.y-t.y,r=i*i+o*o;if(r===0)return{x:t.x,y:t.y};let s=((e.x-t.x)*i+(e.y-t.y)*o)/r;return s=Math.max(0,Math.min(1,s)),{x:t.x+s*i,y:t.y+s*o}}function Vl(e){return(e%360+360)%360}function ND(e,t){let n=t.width/2,i=t.height/2,o=t.center.x-n,r=t.center.x+n,s=t.center.y-i,a=t.center.y+i;if(e.x>=o&&e.x<=r&&e.y>=s&&e.y<=a)return 0;let c=Rn(e.x,o,r),l=Rn(e.y,s,a);return vi(e,{x:c,y:l})}function kD(e,t){if(e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)return 0;let n=Rn(e.x,t.minX,t.maxX),i=Rn(e.y,t.minY,t.maxY);return vi(e,{x:n,y:i})}function AD(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function RD(e,t){let n=e.x-t.x,i=e.y-t.y;return n*n+i*i}var OD=e=>{if("minX"in e)return e;let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,minY:e.center.y-n,maxX:e.center.x+t,maxY:e.center.y+n}},$I=e=>[{x:e.minX,y:e.minY},{x:e.maxX,y:e.minY},{x:e.maxX,y:e.maxY},{x:e.minX,y:e.maxY}],LD=e=>{let t=[];for(let n=0;n<e.length;n++){let i=e[n],o=e[(n+1)%e.length];t.push([i,o])}return t},Oyt=(e,t,n)=>{let i=(e.y-t.y)*(n.x-t.x)-(e.x-t.x)*(n.y-t.y);if(Math.abs(i)>1e-9)return!1;let o=(e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y);if(o<0)return!1;let r=(n.x-t.x)**2+(n.y-t.y)**2;return!(o>r)},Lyt=(e,t)=>e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY,rb=(e,t)=>{if(t.length<3)return!1;let n=LD(t);for(let[o,r]of n)if(Oyt(e,o,r))return!0;let i=!1;for(let o=0,r=t.length-1;o<t.length;r=o++){let s=t[o].x,a=t[o].y,c=t[r].x,l=t[r].y;a>e.y!=l>e.y&&e.x<(c-s)*(e.y-a)/(l-a)+s&&(i=!i)}return i},FD=(e,t)=>{let n=$I(e),i=[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]],o=LD(t);for(let[r,s]of o)for(let[a,c]of i)if(li(r,s,a,c))return!0;return!1},jI=(e,t)=>t.length<3?!1:t.some(i=>Lyt(i,e))||$I(e).some(i=>rb(i,t))?!0:FD(e,t),BI=(e,t)=>t.length<3||!$I(e).every(i=>rb(i,t))?!1:!FD(e,t),zD=(e,t)=>jI(OD(e),t),DD=(e,t)=>BI(OD(e),t);function $D(e,t,n=1){if(n===0)throw new Error("step cannot be 0");let i,o;t===void 0?(i=0,o=e):(i=e,o=t);let r=[];if(n>0)for(let s=i;s<o;s+=n)r.push(s);else for(let s=i;s>o;s+=n)r.push(s);return r}var jD=(e,t)=>{let n=Math.max(0,Math.min(e.maxX,t.maxX)-Math.max(e.minX,t.minX)),i=Math.max(0,Math.min(e.maxY,t.maxY)-Math.max(e.minY,t.minY));return n*i};var BD=(e,t)=>{let n=e.maxX<t.minX?t.minX-e.maxX:t.maxX<e.minX?e.minX-t.maxX:0,i=e.maxY<t.minY?t.minY-e.maxY:t.maxY<e.minY?e.minY-t.maxY:0;return Math.sqrt(n*n+i*i)};var YD=(e,t)=>{let n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),o=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return n>o||i>r?null:{minX:n,minY:i,maxX:o,maxY:r}};var ic=(e,t)=>!(e.maxX<t.minX||t.maxX<e.minX||e.maxY<t.minY||t.maxY<e.minY);var ns=e=>{if(e.length===0)return null;let t=e[0].x,n=e[0].y,i=e[0].x,o=e[0].y;for(let r=1;r<e.length;r++){let s=e[r];s.x<t&&(t=s.x),s.y<n&&(n=s.y),s.x>i&&(i=s.x),s.y>o&&(o=s.y)}return{minX:t,minY:n,maxX:i,maxY:o}};var sb=(e,t)=>{let n={x:t.x-e.x,y:t.y-e.y},i=Math.sqrt(n.x**2+n.y**2);return{x:n.x/i,y:n.y/i}},ab=e=>{switch(e){case"up":return{x:0,y:1};case"down":return{x:0,y:-1};case"left":return{x:-1,y:0};case"right":return{x:1,y:0}}};function XD({rows:e,cols:t,xSpacing:n,ySpacing:i,width:o,height:r,offsetX:s=0,offsetY:a=0,yDirection:c="cartesian",centered:l=!0}){let u=n??1,h=i??1,d=o??t*u,_=r??e*h,y=l?-d/2:0,g=l?-_/2:0,x=o?o/t:u,w=r?r/e:h,S=[];for(let T=0;T<e;T++)for(let I=0;I<t;I++){let E=T*t+I,M=s+y+I*x+x/2,k=a+T*w+w/2,N=c==="cartesian"?a+g+(e-1-T)*w+w/2:a+g+T*w+w/2;S.push({index:E,center:{x:M,y:N},topLeft:{x:M-x/2,y:N+w/2},bottomRight:{x:M+x/2,y:N-w/2},row:T,col:I})}return S}vt();Pf();var VD={name:"@tscircuit/capacity-autorouter",main:"./dist/index.js",version:"0.0.140",type:"module",files:["dist"],scripts:{start:"cosmos",build:"tsup ./lib/index.ts --minify terser --external @tscircuit/core --external circuit-to-svg --format esm --dts --sourcemap",bench:"bun test tests/spatial-index-bench.test.ts",format:"biome format --write .","format:check":"biome format .","vercel-build":"cosmos-export","repomix:lib":"repomix --ignore 'testing/**,**/TwoRouteHighDensitySolver/**,**/RouteStitchingSolver/**,solvers/CapacitySegmentPointOptimizer/CapacitySegmentPointOptimizer.ts' lib","bug-report":"bun run scripts/download-bug-report.ts","bug-report-with-test":"bun run scripts/create-bug-report-test.ts"},devDependencies:{"@biomejs/biome":"^1.9.4","@radix-ui/react-icons":"^1.3.2","@radix-ui/react-menubar":"^1.1.14","@react-hook/resize-observer":"^2.0.2","@resvg/resvg-js":"^2.6.2","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.46","@tscircuit/core":"^0.0.337","@tscircuit/math-utils":"^0.0.27","@types/bun":"^1.2.23","@types/fast-json-stable-stringify":"^2.1.2","@types/object-hash":"^3.0.6","@types/rbush":"^4.0.0","@types/react":"^19.0.8","@types/react-dom":"^19.0.3","@vercel/node":"^5.1.7","@vitejs/plugin-react":"^4.3.4","circuit-json-to-connectivity-map":"^0.0.19","circuit-to-svg":"^0.0.220",clsx:"^2.1.1",flatbush:"^4.4.0","graphics-debug":"^0.0.44","looks-same":"9",rbush:"^4.0.1",react:"18","react-cosmos":"^6.2.3","react-cosmos-plugin-vite":"^6.2.0","react-dom":"18","react-konva":"18",recharts:"^2.15.1","tailwind-merge":"^3.2.0",terser:"^5.43.1",tsup:"^8.3.6",typescript:"^5.9.3","use-mouse-matrix-transform":"^1.3.0",vite:"^6.0.11","vite-tsconfig-paths":"^5.1.4"},dependencies:{"fast-json-stable-stringify":"^2.1.0","object-hash":"^3.0.0"}};vt();ji();ke();var N4=Xt(Mr(),1);vt();var BH=Xt(Sn(),1);var bT={};il(bT,{AssignableViaAutoroutingPipelineSolver:()=>Tgt,AutoroutingPipelineSolver:()=>dj,CapacityMeshSolver:()=>xgt,InMemoryCache:()=>W$,LocalStorageCache:()=>Z$,calculateOptimalCapacityDepth:()=>mT,convertSrjToGraphicsObject:()=>zf,getGlobalInMemoryCache:()=>hh,getGlobalLocalStorageCache:()=>K$,getTunedTotalCapacity1:()=>zr,setupGlobalCaches:()=>Ff});var q$=Xt(pb(),1),aj=Xt(pb(),1),uj=Xt(pb(),1);var Wl=(...e)=>{let t={points:[],lines:[],circles:[],rects:[]};return e.forEach((n,i)=>{n&&(n.lines&&(t.lines=[...t.lines||[],...n.lines.map(o=>({...o,step:i}))]),n.points&&(t.points=[...t.points||[],...n.points.map(o=>({...o,step:i}))]),n.circles&&(t.circles=[...t.circles||[],...n.circles.map(o=>({...o,step:i}))]),n.rects&&(t.rects=[...t.rects||[],...n.rects.map(o=>({...o,step:i}))]))}),t},Ke=class{constructor(){P(this,"MAX_ITERATIONS",1e3);P(this,"solved",!1);P(this,"failed",!1);P(this,"iterations",0);P(this,"progress",0);P(this,"error",null);P(this,"activeSubSolver");P(this,"failedSubSolvers");P(this,"timeToSolve");P(this,"stats",{});P(this,"cacheHit");P(this,"cacheKey");P(this,"cacheToSolveSpaceTransform")}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.constructor.name} error: ${e}`,console.error(this.error),this.failed=!0,e}!this.solved&&this.iterations>this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,console.error(this.error),this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){let e=Date.now();for(;!this.solved&&!this.failed;)this.step();let t=Date.now();this.timeToSolve=t-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function o$(e){let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,maxX:e.center.x+t,minY:e.center.y-n,maxY:e.center.y+n}}function sc(e,t,n){return Math.max(t,Math.min(n,e))}function Si(e,t,n,i){let o=hb(e,t,n),r=hb(e,t,i),s=hb(n,i,e),a=hb(n,i,t);return o!==r&&s!==a||!(o!==0||!db(e,n,t))||!(r!==0||!db(e,i,t))||!(s!==0||!db(n,e,i))||!(a!==0||!db(n,t,i))}function hb(e,t,n){let i=(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y);return i===0?0:i>0?1:2}function db(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function Qi(e,t,n){let i=(n.x-t.x)**2+(n.y-t.y)**2;if(i===0)return Wt(e,t);let o=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/i;return o=Math.max(0,Math.min(1,o)),Wt(e,{x:t.x+o*(n.x-t.x),y:t.y+o*(n.y-t.y)})}function Wt(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}function k$(e,t,n,i){let o=t.x-e.x,r=t.y-e.y,s=i.x-n.x,a=i.y-n.y,c=e.x-n.x,l=e.y-n.y,u=o*a-r*s;if(Math.abs(u)<1e-10)return null;let h=(l*s-c*a)/u,d=(o*l-r*c)/u,_=1e-9;return h>=-1e-9&&h<=1+_&&d>=-1e-9&&d<=1+_?{x:e.x+h*o,y:e.y+h*r}:null}function r$(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}var A$=e=>{if("minX"in e)return e;let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,minY:e.center.y-n,maxX:e.center.x+t,maxY:e.center.y+n}},fT=e=>[{x:e.minX,y:e.minY},{x:e.maxX,y:e.minY},{x:e.maxX,y:e.maxY},{x:e.minX,y:e.maxY}],R$=e=>{let t=[];for(let n=0;n<e.length;n++){let i=e[n],o=e[(n+1)%e.length];t.push([i,o])}return t},qyt=(e,t,n)=>{let i=(e.y-t.y)*(n.x-t.x)-(e.x-t.x)*(n.y-t.y);if(Math.abs(i)>1e-9)return!1;let o=(e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y);return o<0?!1:!(o>(n.x-t.x)**2+(n.y-t.y)**2)},O$=(e,t)=>{if(t.length<3)return!1;let n=R$(t);for(let[o,r]of n)if(qyt(e,o,r))return!0;let i=!1;for(let o=0,r=t.length-1;o<t.length;r=o++){let s=t[o].x,a=t[o].y,c=t[r].x,l=t[r].y;a>e.y!=l>e.y&&e.x<(c-s)*(e.y-a)/(l-a)+s&&(i=!i)}return i},L$=(e,t)=>{let n=fT(e),i=[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]],o=R$(t);for(let[r,s]of o)for(let[a,c]of i)if(Si(r,s,a,c))return!0;return!1},iT=(e,t)=>((n,i)=>!(i.length<3)&&(!!i.some(o=>((r,s)=>r.x>=s.minX&&r.x<=s.maxX&&r.y>=s.minY&&r.y<=s.maxY)(o,n))||!!fT(n).some(o=>O$(o,i))||L$(n,i)))(A$(e),t),F$=(e,t)=>((n,i)=>!(i.length<3)&&!!fT(n).every(o=>O$(o,i))&&!L$(n,i))(A$(e),t);function oT(e,t,n,i){if(e.x===t.x&&e.y===t.y)return Qi(e,n,i);if(n.x===i.x&&n.y===i.y)return Qi(n,e,t);if(Si(e,t,n,i))return 0;let o=[Qi(e,n,i),Qi(t,n,i),Qi(n,e,t),Qi(i,e,t)];return Math.min(...o)}function z$(e,t,n){let i=n.width/2,o=n.height/2;return(function(r,s,a){let c={x:a.minX,y:a.minY},l={x:a.maxX,y:a.minY},u={x:a.minX,y:a.maxY},h={x:a.maxX,y:a.maxY};if(Si(r,s,c,l)||Si(r,s,l,h)||Si(r,s,h,u)||Si(r,s,u,c)||r.x>=a.minX&&r.x<=a.maxX&&r.y>=a.minY&&r.y<=a.maxY&&s.x>=a.minX&&s.x<=a.maxX&&s.y>=a.minY&&s.y<=a.maxY)return 0;let d=[Qi(c,r,s),Qi(l,r,s),Qi(u,r,s),Qi(h,r,s)];if(r.x>=a.minX&&r.x<=a.maxX&&r.y>=a.minY&&r.y<=a.maxY||s.x>=a.minX&&s.x<=a.maxX&&s.y>=a.minY&&s.y<=a.maxY)return 0;if(r.x<a.minX||r.x>a.maxX||r.y<a.minY||r.y>a.maxY){let _=sc(r.x,a.minX,a.maxX),y=sc(r.y,a.minY,a.maxY);d.push(Wt(r,{x:_,y}))}if(s.x<a.minX||s.x>a.maxX||s.y<a.minY||s.y>a.maxY){let _=sc(s.x,a.minX,a.maxX),y=sc(s.y,a.minY,a.maxY);d.push(Wt(s,{x:_,y}))}return Math.min(...d)})(e,t,{minX:n.center.x-i,maxX:n.center.x+i,minY:n.center.y-o,maxY:n.center.y+o})}function ah(e,t,n){let i=n.x-t.x,o=n.y-t.y,r=i*i+o*o;if(r===0)return{x:t.x,y:t.y};let s=((e.x-t.x)*i+(e.y-t.y)*o)/r;return s=Math.max(0,Math.min(1,s)),{x:t.x+s*i,y:t.y+s*o}}function Io(){return Io=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},Io.apply(null,arguments)}function Cb(e,t){return(Cb=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n})(e,t)}function D$(e){return(D$=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(e)}function $$(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return($$=function(){return!!e})()}function rT(e){var t=typeof Map=="function"?new Map:void 0;return rT=function(n){if(n===null||!(function(o){try{return Function.toString.call(o).indexOf("[native code]")!==-1}catch{return typeof o=="function"}})(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(t!==void 0){if(t.has(n))return t.get(n);t.set(n,i)}function i(){return(function(o,r,s){if($$())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,r);var c=new(o.bind.apply(o,a));return s&&Cb(c,s.prototype),c})(n,arguments,D$(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Cb(i,n)},rT(e)}var Po=(function(e){var t,n;function i(o){var r;if(1)r=e.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+o+" for more information.")||this;else for(var s,a,c;c<s;c++);return(function(l){if(l===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return l})(r)}return n=e,(t=i).prototype=Object.create(n.prototype),t.prototype.constructor=t,Cb(t,n),i})(rT(Error));function s$(e,t){return e.substr(-t.length)===t}var Wyt=/^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;function a$(e){return typeof e!="string"?e:e.match(Wyt)?parseFloat(e):e}var c$=function(e){return function(t,n){n===void 0&&(n="16px");var i=t,o=n;if(typeof t=="string"){if(!s$(t,"px"))throw new Po(69,e,t);i=a$(t)}if(typeof n=="string"){if(!s$(n,"px"))throw new Po(70,e,n);o=a$(n)}if(typeof i=="string")throw new Po(71,t,e);if(typeof o=="string")throw new Po(72,n,e);return""+i/o+e}};c$("em"),c$("rem");function GI(e){return Math.round(255*e)}function Zyt(e,t,n){return GI(e)+","+GI(t)+","+GI(n)}function Rf(e,t,n,i){if(i===void 0&&(i=Zyt),t===0)return i(n,n,n);var o=(e%360+360)%360/60,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o%2-1)),a=0,c=0,l=0;o>=0&&o<1?(a=r,c=s):o>=1&&o<2?(a=s,c=r):o>=2&&o<3?(c=r,l=s):o>=3&&o<4?(c=s,l=r):o>=4&&o<5?(a=s,l=r):o>=5&&o<6&&(a=r,l=s);var u=n-r/2;return i(a+u,c+u,l+u)}var l$={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},Kyt=/^#[a-fA-F0-9]{6}$/,Jyt=/^#[a-fA-F0-9]{8}$/,Qyt=/^#[a-fA-F0-9]{3}$/,t0t=/^#[a-fA-F0-9]{4}$/,UI=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,e0t=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,n0t=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,i0t=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function ch(e){if(typeof e!="string")throw new Po(3);var t=(function(d){if(typeof d!="string")return d;var _=d.toLowerCase();return l$[_]?"#"+l$[_]:d})(e);if(t.match(Kyt))return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16)};if(t.match(Jyt)){var n=parseFloat((parseInt(""+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16),alpha:n}}if(t.match(Qyt))return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16)};if(t.match(t0t)){var i=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:i}}var o=UI.exec(t);if(o)return{red:parseInt(""+o[1],10),green:parseInt(""+o[2],10),blue:parseInt(""+o[3],10)};var r=e0t.exec(t.substring(0,50));if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10),alpha:parseFloat(""+r[4])>1?parseFloat(""+r[4])/100:parseFloat(""+r[4])};var s=n0t.exec(t);if(s){var a="rgb("+Rf(parseInt(""+s[1],10),parseInt(""+s[2],10)/100,parseInt(""+s[3],10)/100)+")",c=UI.exec(a);if(!c)throw new Po(4,t,a);return{red:parseInt(""+c[1],10),green:parseInt(""+c[2],10),blue:parseInt(""+c[3],10)}}var l=i0t.exec(t.substring(0,50));if(l){var u="rgb("+Rf(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",h=UI.exec(u);if(!h)throw new Po(4,t,u);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+l[4])>1?parseFloat(""+l[4])/100:parseFloat(""+l[4])}}throw new Po(5)}function ac(e){return(function(t){var n,i=t.red/255,o=t.green/255,r=t.blue/255,s=Math.max(i,o,r),a=Math.min(i,o,r),c=(s+a)/2;if(s===a)return t.alpha!==void 0?{hue:0,saturation:0,lightness:c,alpha:t.alpha}:{hue:0,saturation:0,lightness:c};var l=s-a,u=c>.5?l/(2-s-a):l/(s+a);switch(s){case i:n=(o-r)/l+(o<r?6:0);break;case o:n=(r-i)/l+2;break;default:n=(i-o)/l+4}return n*=60,t.alpha!==void 0?{hue:n,saturation:u,lightness:c,alpha:t.alpha}:{hue:n,saturation:u,lightness:c}})(ch(e))}var sT=function(e){return e.length===7&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?"#"+e[1]+e[3]+e[5]:e};function Ul(e){var t=e.toString(16);return t.length===1?"0"+t:t}function qI(e){return Ul(Math.round(255*e))}function o0t(e,t,n){return sT("#"+qI(e)+qI(t)+qI(n))}function fb(e,t,n){return Rf(e,t,n,o0t)}function aT(e,t,n){if(typeof e=="number"&&typeof t=="number"&&typeof n=="number")return sT("#"+Ul(e)+Ul(t)+Ul(n));if(typeof e=="object"&&t===void 0&&n===void 0)return sT("#"+Ul(e.red)+Ul(e.green)+Ul(e.blue));throw new Po(6)}function Fb(e,t,n,i){if(typeof e=="string"&&typeof t=="number"){var o=ch(e);return"rgba("+o.red+","+o.green+","+o.blue+","+t+")"}if(typeof e=="number"&&typeof t=="number"&&typeof n=="number"&&typeof i=="number")return i>=1?aT(e,t,n):"rgba("+e+","+t+","+n+","+i+")";if(typeof e=="object"&&t===void 0&&n===void 0&&i===void 0)return e.alpha>=1?aT(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new Po(7)}function cc(e){if(typeof e!="object")throw new Po(8);if((function(t){return typeof t.red=="number"&&typeof t.green=="number"&&typeof t.blue=="number"&&typeof t.alpha=="number"})(e))return Fb(e);if((function(t){return typeof t.red=="number"&&typeof t.green=="number"&&typeof t.blue=="number"&&(typeof t.alpha!="number"||t.alpha===void 0)})(e))return aT(e);if((function(t){return typeof t.hue=="number"&&typeof t.saturation=="number"&&typeof t.lightness=="number"&&typeof t.alpha=="number"})(e))return(function(t,n,i,o){if(typeof t=="number"&&typeof n=="number"&&typeof i=="number"&&typeof o=="number")return o>=1?fb(t,n,i):"rgba("+Rf(t,n,i)+","+o+")";if(typeof t=="object"&&n===void 0&&i===void 0&&o===void 0)return t.alpha>=1?fb(t.hue,t.saturation,t.lightness):"rgba("+Rf(t.hue,t.saturation,t.lightness)+","+t.alpha+")";throw new Po(2)})(e);if((function(t){return typeof t.hue=="number"&&typeof t.saturation=="number"&&typeof t.lightness=="number"&&(typeof t.alpha!="number"||t.alpha===void 0)})(e))return(function(t,n,i){if(typeof t=="number"&&typeof n=="number"&&typeof i=="number")return fb(t,n,i);if(typeof t=="object"&&n===void 0&&i===void 0)return fb(t.hue,t.saturation,t.lightness);throw new Po(1)})(e);throw new Po(8)}function j$(e,t,n){return function(){var i=n.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):j$(e,t,i)}}function Bo(e){return j$(e,e.length,[])}Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{hue:n.hue+parseFloat(e)}))});function ph(e,t,n){return Math.max(e,Math.min(t,n))}Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{lightness:ph(0,1,n.lightness-parseFloat(e))}))});Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{saturation:ph(0,1,n.saturation-parseFloat(e))}))});Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{lightness:ph(0,1,n.lightness+parseFloat(e))}))});var B$=Bo(function(e,t,n){if(t==="transparent")return n;if(n==="transparent")return t;if(e===0)return n;var i=ch(t),o=Io({},i,{alpha:typeof i.alpha=="number"?i.alpha:1}),r=ch(n),s=Io({},r,{alpha:typeof r.alpha=="number"?r.alpha:1}),a=o.alpha-s.alpha,c=2*parseFloat(e)-1,l=((c*a===-1?c:c+a)/(1+c*a)+1)/2,u=1-l;return Fb({red:Math.floor(o.red*l+s.red*u),green:Math.floor(o.green*l+s.green*u),blue:Math.floor(o.blue*l+s.blue*u),alpha:o.alpha*parseFloat(e)+s.alpha*(1-parseFloat(e))})});Bo(function(e,t){if(t==="transparent")return t;var n=ch(t);return Fb(Io({},n,{alpha:ph(0,1,(100*(typeof n.alpha=="number"?n.alpha:1)+100*parseFloat(e))/100)}))});Bo(function(e,t){if(t==="transparent")return t;var n=ac(t);return cc(Io({},n,{saturation:ph(0,1,n.saturation+parseFloat(e))}))});Bo(function(e,t){return t==="transparent"?t:cc(Io({},ac(t),{hue:parseFloat(e)}))});Bo(function(e,t){return t==="transparent"?t:cc(Io({},ac(t),{lightness:parseFloat(e)}))});Bo(function(e,t){return t==="transparent"?t:cc(Io({},ac(t),{saturation:parseFloat(e)}))});Bo(function(e,t){return t==="transparent"?t:B$(parseFloat(e),"rgb(0, 0, 0)",t)});Bo(function(e,t){return t==="transparent"?t:B$(parseFloat(e),"rgb(255, 255, 255)",t)});var r0t=Bo(function(e,t){if(t==="transparent")return t;var n=ch(t);return Fb(Io({},n,{alpha:ph(0,1,+(100*(typeof n.alpha=="number"?n.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))}),u$=["blue","orange","purple","cyan","magenta","yellowgreen","darkgoldenrod","deeppink"],Of=(e,t)=>{let n={};for(let i=0;i<e.connections.length;i++){let o=e.connections[i],r=t?.getNetConnectedToId(o.name);r&&!n[r]&&(n[r]=`hsl(${300*i/e.connections.length}, 100%, 50%)`),n[o.name]=(r?n[r]:null)??`hsl(${340*i/e.connections.length}, 100%, 50%)`}return n},$n=(e,t)=>{try{return r0t(t,e)}catch(n){return console.error(n),e}},Zl=(e,t)=>e==="top"?0:e==="bottom"?t-1:parseInt(e.slice(5)),zr=(e,t=1)=>{let n=(("width"in e?e.width:e)/.5/2)**1.1*t;return e.availableZ?.length===1&&n>1?1:n},mT=(e,t=.5,n=16)=>{let i=0,o=e;for(;i<n&&!(zr({width:o})<=t);)o/=2,i++;return Math.max(1,i)};function Y$(e,t,n=0,i=e.length-1,o=s0t){for(;i>n;){if(i-n>600){let c=i-n+1,l=t-n+1,u=Math.log(c),h=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*h*(c-h)/c)*(l-c/2<0?-1:1);Y$(e,t,Math.max(n,Math.floor(t-l*h/c+d)),Math.min(i,Math.floor(t+(c-l)*h/c+d)),o)}let r=e[t],s=n,a=i;for(Tf(e,n,t),o(e[i],r)>0&&Tf(e,n,i);s<a;){for(Tf(e,s,a),s++,a--;o(e[s],r)<0;)s++;for(;o(e[a],r)>0;)a--}o(e[n],r)===0?Tf(e,n,a):(a++,Tf(e,a,i)),a<=t&&(n=a+1),t<=a&&(i=a-1)}}function Tf(e,t,n){let i=e[t];e[t]=e[n],e[n]=i}function s0t(e,t){return e<t?-1:e>t?1:0}var a0t=class{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data,n=[];if(!_b(e,t))return n;let i=this.toBBox,o=[];for(;t;){for(let r=0;r<t.children.length;r++){let s=t.children[r],a=t.leaf?i(s):s;_b(e,a)&&(t.leaf?n.push(s):ZI(e,a)?this._all(s,n):o.push(s))}t=o.pop()}return n}collides(e){let t=this.data;if(!_b(e,t))return!1;let n=[];for(;t;){for(let i=0;i<t.children.length;i++){let o=t.children[i],r=t.leaf?this.toBBox(o):o;if(_b(e,r)){if(t.leaf||ZI(e,r))return!0;n.push(o)}}t=n.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let n=0;n<e.length;n++)this.insert(e[n]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){let n=this.data;this.data=t,t=n}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=rh([]),this}remove(e,t){if(!e)return this;let n=this.data,i=this.toBBox(e),o=[],r=[],s,a,c;for(;n||o.length;){if(n||(n=o.pop(),a=o[o.length-1],s=r.pop(),c=!0),n.leaf){let l=c0t(e,n.children,t);if(l!==-1)return n.children.splice(l,1),o.push(n),this._condense(o),this}c||n.leaf||!ZI(n,i)?a?(s++,n=a.children[s],c=!1):n=null:(o.push(n),r.push(s),s=0,a=n,n=n.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){let n=[];for(;e;)e.leaf?t.push(...e.children):n.push(...e.children),e=n.pop();return t}_build(e,t,n,i){let o=n-t+1,r,s=this._maxEntries;if(o<=s)return r=rh(e.slice(t,n+1)),oh(r,this.toBBox),r;i||(i=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/Math.pow(s,i-1))),r=rh([]),r.leaf=!1,r.height=i;let a=Math.ceil(o/s),c=a*Math.ceil(Math.sqrt(s));p$(e,t,n,c,this.compareMinX);for(let l=t;l<=n;l+=c){let u=Math.min(l+c-1,n);p$(e,l,u,a,this.compareMinY);for(let h=l;h<=u;h+=a){let d=Math.min(h+a-1,u);r.children.push(this._build(e,h,d,i-1))}}return oh(r,this.toBBox),r}_chooseSubtree(e,t,n,i){for(;i.push(t),!t.leaf&&i.length-1!==n;){let o,r=1/0,s=1/0;for(let a=0;a<t.children.length;a++){let c=t.children[a],l=WI(c),u=p0t(e,c)-l;u<s?(s=u,r=l<r?l:r,o=c):u===s&&l<r&&(r=l,o=c)}t=o||t.children[0]}return t}_insert(e,t,n){let i=n?e:this.toBBox(e),o=[],r=this._chooseSubtree(i,this.data,t,o);for(r.children.push(e),Cf(r,i);t>=0&&o[t].children.length>this._maxEntries;)this._split(o,t),t--;this._adjustParentBBoxes(i,o,t)}_split(e,t){let n=e[t],i=n.children.length,o=this._minEntries;this._chooseSplitAxis(n,o,i);let r=this._chooseSplitIndex(n,o,i),s=rh(n.children.splice(r,n.children.length-r));s.height=n.height,s.leaf=n.leaf,oh(n,this.toBBox),oh(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)}_splitRoot(e,t){this.data=rh([e,t]),this.data.height=e.height+1,this.data.leaf=!1,oh(this.data,this.toBBox)}_chooseSplitIndex(e,t,n){let i,o=1/0,r=1/0;for(let s=t;s<=n-t;s++){let a=Mf(e,0,s,this.toBBox),c=Mf(e,s,n,this.toBBox),l=h0t(a,c),u=WI(a)+WI(c);l<o?(o=l,i=s,r=u<r?u:r):l===o&&u<r&&(r=u,i=s)}return i||n-t}_chooseSplitAxis(e,t,n){let i=e.leaf?this.compareMinX:l0t,o=e.leaf?this.compareMinY:u0t;this._allDistMargin(e,t,n,i)<this._allDistMargin(e,t,n,o)&&e.children.sort(i)}_allDistMargin(e,t,n,i){e.children.sort(i);let o=this.toBBox,r=Mf(e,0,t,o),s=Mf(e,n-t,n,o),a=mb(r)+mb(s);for(let c=t;c<n-t;c++){let l=e.children[c];Cf(r,e.leaf?o(l):l),a+=mb(r)}for(let c=n-t-1;c>=t;c--){let l=e.children[c];Cf(s,e.leaf?o(l):l),a+=mb(s)}return a}_adjustParentBBoxes(e,t,n){for(let i=n;i>=0;i--)Cf(t[i],e)}_condense(e){for(let t,n=e.length-1;n>=0;n--)e[n].children.length===0?n>0?(t=e[n-1].children,t.splice(t.indexOf(e[n]),1)):this.clear():oh(e[n],this.toBBox)}};function c0t(e,t,n){if(!n)return t.indexOf(e);for(let i=0;i<t.length;i++)if(n(e,t[i]))return i;return-1}function oh(e,t){Mf(e,0,e.children.length,t,e)}function Mf(e,t,n,i,o){o||(o=rh(null)),o.minX=1/0,o.minY=1/0,o.maxX=-1/0,o.maxY=-1/0;for(let r=t;r<n;r++){let s=e.children[r];Cf(o,e.leaf?i(s):s)}return o}function Cf(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function l0t(e,t){return e.minX-t.minX}function u0t(e,t){return e.minY-t.minY}function WI(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function mb(e){return e.maxX-e.minX+(e.maxY-e.minY)}function p0t(e,t){return(Math.max(t.maxX,e.maxX)-Math.min(t.minX,e.minX))*(Math.max(t.maxY,e.maxY)-Math.min(t.minY,e.minY))}function h0t(e,t){let n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),o=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return Math.max(0,o-n)*Math.max(0,r-i)}function ZI(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function _b(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function rh(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function p$(e,t,n,i,o){let r=[t,n];for(;r.length;){if((n=r.pop())-(t=r.pop())<=i)continue;let s=t+Math.ceil((n-t)/i/2)*i;Y$(e,s,t,n,o),r.push(t,s,s,n)}}var h$=class{constructor(e=9){P(this,"tree");this.tree=new a0t(e)}insert(e,t,n,i,o){this.tree.insert({minX:t,minY:n,maxX:i,maxY:o,data:e})}bulkLoad(e){let t=e.map(({item:n,minX:i,minY:o,maxX:r,maxY:s})=>({minX:i,minY:o,maxX:r,maxY:s,data:n}));this.tree.load(t)}search(e,t,n,i){return this.tree.search({minX:e,minY:t,maxX:n,maxY:i}).map(o=>o.data)}clear(){this.tree.clear()}},d0t=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(e,t){let n=this.length++;for(;n>0;){let i=n-1>>1,o=this.values[i];if(t>=o)break;this.ids[n]=this.ids[i],this.values[n]=o,n=i}this.ids[n]=e,this.values[n]=t}pop(){if(this.length===0)return;let e=this.ids,t=this.values,n=e[0],i=--this.length;if(i>0){let o=e[i],r=t[i],s=0,a=i>>1;for(;s<a;){let c=1+(s<<1),l=c+1,u=c+(+(l<i)&+(t[l]<t[c]));if(t[u]>=r)break;e[s]=e[u],t[s]=t[u],s=u}e[s]=o,t[s]=r}return n}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){this.ids.length=this.values.length=this.length}},d$=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],f$=class X${static from(t,n=0){if(n%8!=0)throw new Error("byteOffset must be 8-byte aligned.");if(!t||t.byteLength===void 0||t.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[i,o]=new Uint8Array(t,n+0,2);if(i!==251)throw new Error("Data does not appear to be in a Flatbush format.");let r=o>>4;if(r!==3)throw new Error(`Got v${r} data when expected v3.`);let s=d$[15&o];if(!s)throw new Error("Unrecognized array type.");let[a]=new Uint16Array(t,n+2,1),[c]=new Uint32Array(t,n+4,1);return new X$(c,a,s,void 0,t,n)}constructor(t,n=16,i=Float64Array,o=ArrayBuffer,r,s=0){if(t===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(t)||t<=0)throw new Error(`Unexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+n,2),65535),this.byteOffset=s;let a=t,c=a;this._levelBounds=[4*a];do a=Math.ceil(a/this.nodeSize),c+=a,this._levelBounds.push(4*c);while(a!==1);this.ArrayType=i,this.IndexArrayType=c<16384?Uint16Array:Uint32Array;let l=d$.indexOf(i),u=4*c*i.BYTES_PER_ELEMENT;if(l<0)throw new Error(`Unexpected typed array class: ${i}.`);if(r)this.data=r,this._boxes=new i(r,s+8,4*c),this._indices=new this.IndexArrayType(r,s+8+u,c),this._pos=4*c,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1];else{let h=this.data=new o(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(h,8,4*c),this._indices=new this.IndexArrayType(h,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(h,0,2).set([251,48+l]),new Uint16Array(h,2,1)[0]=n,new Uint32Array(h,4,1)[0]=t}this._queue=new d0t}add(t,n,i=t,o=n){let r=this._pos>>2,s=this._boxes;return this._indices[r]=r,s[this._pos++]=t,s[this._pos++]=n,s[this._pos++]=i,s[this._pos++]=o,t<this.minX&&(this.minX=t),n<this.minY&&(this.minY=n),i>this.maxX&&(this.maxX=i),o>this.maxY&&(this.maxY=o),r}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let t=this._boxes;if(this.numItems<=this.nodeSize)return t[this._pos++]=this.minX,t[this._pos++]=this.minY,t[this._pos++]=this.maxX,void(t[this._pos++]=this.maxY);let n=this.maxX-this.minX||1,i=this.maxY-this.minY||1,o=new Uint32Array(this.numItems);for(let r=0,s=0;r<this.numItems;r++){let a=t[s++],c=t[s++],l=t[s++],u=t[s++],h=Math.floor(65535*((a+l)/2-this.minX)/n),d=Math.floor(65535*((c+u)/2-this.minY)/i);o[r]=m0t(h,d)}cT(o,t,this._indices,0,this.numItems-1,this.nodeSize);for(let r=0,s=0;r<this._levelBounds.length-1;r++){let a=this._levelBounds[r];for(;s<a;){let c=s,l=t[s++],u=t[s++],h=t[s++],d=t[s++];for(let _=1;_<this.nodeSize&&s<a;_++)l=Math.min(l,t[s++]),u=Math.min(u,t[s++]),h=Math.max(h,t[s++]),d=Math.max(d,t[s++]);this._indices[this._pos>>2]=c,t[this._pos++]=l,t[this._pos++]=u,t[this._pos++]=h,t[this._pos++]=d}}}search(t,n,i,o,r){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=[],c=[];for(;s!==void 0;){let l=Math.min(s+4*this.nodeSize,m$(s,this._levelBounds));for(let u=s;u<l;u+=4){let h=this._boxes[u];if(i<h)continue;let d=this._boxes[u+1];if(o<d)continue;let _=this._boxes[u+2];if(t>_)continue;let y=this._boxes[u+3];if(n>y)continue;let g=0|this._indices[u>>2];s>=4*this.numItems?a.push(g):(r===void 0||r(g,h,d,_,y))&&c.push(g)}s=a.pop()}return c}neighbors(t,n,i=1/0,o=1/0,r){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=this._queue,c=[],l=o*o;t:for(;s!==void 0;){let u=Math.min(s+4*this.nodeSize,m$(s,this._levelBounds));for(let h=s;h<u;h+=4){let d=0|this._indices[h>>2],_=this._boxes[h],y=this._boxes[h+1],g=this._boxes[h+2],x=this._boxes[h+3],w=t<_?_-t:t>g?t-g:0,S=n<y?y-n:n>x?n-x:0,T=w*w+S*S;T>l||(s>=4*this.numItems?a.push(d<<1,T):(r===void 0||r(d))&&a.push(1+(d<<1),T))}for(;a.length&&1&a.peek();)if(a.peekValue()>l||(c.push(a.pop()>>1),c.length===i))break t;s=a.length?a.pop()>>1:void 0}return a.clear(),c}};function m$(e,t){let n=0,i=t.length-1;for(;n<i;){let o=n+i>>1;t[o]>e?i=o:n=o+1}return t[n]}function cT(e,t,n,i,o,r){if(Math.floor(i/r)>=Math.floor(o/r))return;let s=e[i],a=e[i+o>>1],c=e[o],l=c,u=Math.max(s,a);c>u?l=u:u===s?l=Math.max(a,c):u===a&&(l=Math.max(s,c));let h=i-1,d=o+1;for(;;){do h++;while(e[h]<l);do d--;while(e[d]>l);if(h>=d)break;f0t(e,t,n,h,d)}cT(e,t,n,i,d,r),cT(e,t,n,d+1,o,r)}function f0t(e,t,n,i,o){let r=e[i];e[i]=e[o],e[o]=r;let s=4*i,a=4*o,c=t[s],l=t[s+1],u=t[s+2],h=t[s+3];t[s]=t[a],t[s+1]=t[a+1],t[s+2]=t[a+2],t[s+3]=t[a+3],t[a]=c,t[a+1]=l,t[a+2]=u,t[a+3]=h;let d=n[i];n[i]=n[o],n[o]=d}function m0t(e,t){let n=e^t,i=65535^n,o=65535^(e|t),r=e&(65535^t),s=n|i>>1,a=n>>1^n,c=o>>1^i&r>>1^o,l=n&o>>1^r>>1^r;n=s,i=a,o=c,r=l,s=n&n>>2^i&i>>2,a=n&i>>2^i&(n^i)>>2,c^=n&o>>2^i&r>>2,l^=i&o>>2^(n^i)&r>>2,n=s,i=a,o=c,r=l,s=n&n>>4^i&i>>4,a=n&i>>4^i&(n^i)>>4,c^=n&o>>4^i&r>>4,l^=i&o>>4^(n^i)&r>>4,n=s,i=a,o=c,r=l,c^=n&o>>8^i&r>>8,l^=i&o>>8^(n^i)&r>>8,n=c^c>>1,i=l^l>>1;let u=e^t,h=i|65535^(u|n);return u=16711935&(u|u<<8),u=252645135&(u|u<<4),u=858993459&(u|u<<2),u=1431655765&(u|u<<1),h=16711935&(h|h<<8),h=252645135&(h|h<<4),h=858993459&(h|h<<2),h=1431655765&(h|h<<1),(h<<1|u)>>>0}var _0t=class{constructor(e){P(this,"index");P(this,"items",[]);P(this,"currentIndex",0);P(this,"capacity");this.capacity=Math.max(1,e),this.index=new f$(this.capacity)}insert(e,t,n,i,o){if(this.currentIndex>=this.index.numItems)throw new Error("Exceeded initial capacity");this.items[this.currentIndex]=e,this.index.add(t,n,i,o),this.currentIndex++}finish(){this.index.finish()}search(e,t,n,i){return this.index.search(e,t,n,i).map(o=>this.items[o]||null).filter(Boolean)}clear(){this.items=[],this.currentIndex=0,this.index=new f$(this.capacity)}},V$=class{constructor(e="native",t=[]){P(this,"idx");P(this,"storage",[]);e==="flatbush"?t.length===0?(this.idx=new h$,e="rbush"):this.idx=new _0t(t.length):this.idx=e==="rbush"?new h$:new class{constructor(){P(this,"shi",new y0t(t))}insert(n){}search(n,i,o,r){let s=(n+o)/2,a=(i+r)/2,c=o-n,l=r-i;return this.shi.getNodesInArea(s,a,c,l)}clear(){}},t.forEach(n=>this.insert(n)),e==="flatbush"&&t.length>0&&this.idx.finish?.()}insert(e){this.storage.push(e),this.idx.insert(e,e.center.x-e.width/2,e.center.y-e.height/2,e.center.x+e.width/2,e.center.y+e.height/2)}search(e){return this.idx.search(e.minX,e.minY,e.maxX,e.maxY)}searchArea(e,t,n,i){return this.search({minX:e-n/2,minY:t-i/2,maxX:e+n/2,maxY:t+i/2})}},y0t=class{constructor(e){P(this,"buckets");P(this,"CELL_SIZE",.4);this.obstacles=e,this.buckets=new Map;for(let t=0;t<e.length;t++){let n=e[t],i=n.center.x-n.width/2,o=n.center.y-n.height/2,r=n.center.x+n.width/2,s=n.center.y+n.height/2;for(let a=i;a<=r;a+=this.CELL_SIZE)for(let c=o;c<=s;c+=this.CELL_SIZE){let l=this.getBucketKey(a,c),u=this.buckets.get(l);u?u.push([n,t]):this.buckets.set(l,[[n,t]])}}}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getNodesInArea(e,t,n,i){let o=[],r=new Set,s=t-i/2,a=e+n/2,c=t+i/2;for(let l=e-n/2;l<=a;l+=this.CELL_SIZE)for(let u=s;u<=c;u+=this.CELL_SIZE){let h=this.getBucketKey(l,u),d=this.buckets.get(h)||[];for(let _ of d)r.has(_[1])||(r.add(_[1]),o.push(_[0]))}return o}},g0t=class{constructor(e){P(this,"buckets");P(this,"CELL_SIZE",5);this.targets=e,this.buckets=new Map;for(let t=0;t<e.length;t++){let n=e[t],i=Math.floor(n.bounds.minX/this.CELL_SIZE)*this.CELL_SIZE,o=Math.floor(n.bounds.minY/this.CELL_SIZE)*this.CELL_SIZE,r=n.bounds.maxX,s=n.bounds.maxY;for(let a=i;a<=r;a+=this.CELL_SIZE)for(let c=o;c<=s;c+=this.CELL_SIZE){let l=this.getBucketKey(a,c),u=this.buckets.get(l);u?u.push([n,t]):this.buckets.set(l,[[n,t]])}}}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getTargetsInArea(e,t,n,i){let o=[],r=new Set,s=Math.floor((e-n/2)/this.CELL_SIZE)*this.CELL_SIZE,a=Math.floor((t-i/2)/this.CELL_SIZE)*this.CELL_SIZE,c=e+n/2,l=t+i/2;for(let u=s;u<=c;u+=this.CELL_SIZE)for(let h=a;h<=l;h+=this.CELL_SIZE){let d=this.getBucketKey(u,h),_=this.buckets.get(d)||[];for(let y of _)r.has(y[1])||(r.add(y[1]),o.push(y[0]))}return o}},b0t=class extends Ke{constructor(t,n={}){super();P(this,"unfinishedNodes");P(this,"finishedNodes");P(this,"nodeToXYOverlappingObstaclesMap");P(this,"layerCount");P(this,"outlinePolygon");P(this,"MAX_DEPTH",4);P(this,"targets");P(this,"targetTree");P(this,"obstacleTree");P(this,"_nextNodeCounter",0);this.srj=t,this.opts=n,this.MAX_DEPTH=n?.capacityDepth??this.MAX_DEPTH,this.MAX_ITERATIONS=1e5,this.layerCount=t.layerCount??2,this.outlinePolygon=t.outline&&t.outline.length>=3?t.outline:void 0;for(let s of t.obstacles)if(!s.zLayers){let a=[];for(let c of s.layers)a.push(Zl(c,t.layerCount));s.zLayers=a}let i={x:(t.bounds.minX+t.bounds.maxX)/2,y:(t.bounds.minY+t.bounds.maxY)/2},o={width:t.bounds.maxX-t.bounds.minX,height:t.bounds.maxY-t.bounds.minY},r=Math.max(o.width,o.height);this.unfinishedNodes=[{capacityMeshNodeId:this.getNextNodeId(),center:i,width:r,height:r,layer:"top",availableZ:Array.from({length:this.layerCount},(s,a)=>a),_depth:0,_containsTarget:!0,_containsObstacle:!0,_completelyInsideObstacle:!1}],this.finishedNodes=[],this.nodeToXYOverlappingObstaclesMap=new Map,this.obstacleTree=new V$("flatbush",this.srj.obstacles),this.targets=this.computeTargets(),this.targetTree=new g0t(this.targets)}computeTargets(){let t=[];for(let n of this.srj.connections)for(let i of n.pointsToConnect){let o=this.obstacleTree.searchArea(i.x,i.y,.01,.01).filter(a=>a.zLayers.some(c=>c===Zl(i.layer,this.layerCount))),r={minX:i.x-.005,minY:i.y-.005,maxX:i.x+.005,maxY:i.y+.005};o.length>0&&(r={minX:Math.min(...o.map(a=>a.center.x-a.width/2)),minY:Math.min(...o.map(a=>a.center.y-a.height/2)),maxX:Math.max(...o.map(a=>a.center.x+a.width/2)),maxY:Math.max(...o.map(a=>a.center.y+a.height/2))});let s={...i,connectionName:n.name,availableZ:[Zl(i.layer,this.layerCount)],bounds:r};t.push(s)}return t}getNodeBounds(t){let n=t.width/2,i=t.height/2;return{minX:t.center.x-n,maxX:t.center.x+n,minY:t.center.y-i,maxY:t.center.y+i}}getNodeRect(t){return{center:{x:t.center.x,y:t.center.y},width:t.width,height:t.height}}getNextNodeId(){return"cn"+this._nextNodeCounter++}getCapacityFromDepth(t){return(this.MAX_DEPTH-t+1)**2}getTargetIfNodeContainsTarget(t){let n=t.width>4*this.targetTree.CELL_SIZE?this.targets:this.targetTree.getTargetsInArea(t.center.x,t.center.y,t.width,t.height);for(let i of n)if(i.bounds.minX<=t.center.x+t.width/2&&i.bounds.maxX>=t.center.x-t.width/2&&i.bounds.minY<=t.center.y+t.height/2&&i.bounds.maxY>=t.center.y-t.height/2&&i.availableZ.some(o=>t.availableZ.includes(o)))return i;return null}getXYOverlappingObstacles(t){let n=this.nodeToXYOverlappingObstaclesMap.get(t.capacityMeshNodeId);if(n)return n;let i=[],o=this.getNodeBounds(t),r=o.minX,s=o.maxX,a=o.minY,c=o.maxY,l=t._parent?this.getXYOverlappingObstacles(t._parent):this.srj.obstacles;for(let u of l){let h=u.center.x-u.width/2,d=u.center.x+u.width/2,_=u.center.y-u.height/2,y=u.center.y+u.height/2;(s>=h&&r<=d&&c>=_&&a<=y||r>=h&&s<=d&&a>=_&&c<=y||h>=r&&d<=s&&_>=a&&y<=c)&&i.push(u)}return this.nodeToXYOverlappingObstaclesMap.set(t.capacityMeshNodeId,i),i}getXYZOverlappingObstacles(t){let n=this.getXYOverlappingObstacles(t),i=[];for(let o of n)t.availableZ.some(r=>o.zLayers.includes(r))&&i.push(o);return i}doesNodeOverlapObstacle(t){if(this.getXYZOverlappingObstacles(t).length>0)return!0;let n=this.getNodeBounds(t);if(this.outlinePolygon){let i=this.getNodeRect(t);if(!F$(i,this.outlinePolygon))return!0}return n.minX<this.srj.bounds.minX||n.maxX>this.srj.bounds.maxX||n.minY<this.srj.bounds.minY||n.maxY>this.srj.bounds.maxY}isNodeCompletelyInsideObstacle(t){let n=this.getXYZOverlappingObstacles(t),i=this.getNodeBounds(t);if(this.outlinePolygon){let o=this.getNodeRect(t);if(!iT(o,this.outlinePolygon))return!0}for(let o of n){let r=o.center.x-o.width/2,s=o.center.x+o.width/2,a=o.center.y-o.height/2,c=o.center.y+o.height/2;if(i.minX>=r&&i.maxX<=s&&i.minY>=a&&i.maxY<=c)return!0}return!1}getChildNodes(t){if(t._depth===this.MAX_DEPTH)return[];let n=[],i={width:t.width/2,height:t.height/2},o=[{x:t.center.x-i.width/2,y:t.center.y-i.height/2},{x:t.center.x+i.width/2,y:t.center.y-i.height/2},{x:t.center.x-i.width/2,y:t.center.y+i.height/2},{x:t.center.x+i.width/2,y:t.center.y+i.height/2}];for(let r of o){let s={capacityMeshNodeId:this.getNextNodeId(),center:r,width:i.width,height:i.height,layer:t.layer,availableZ:t.availableZ,_depth:(t._depth??0)+1,_parent:t};s._containsObstacle=this.doesNodeOverlapObstacle(s);let a=this.getTargetIfNodeContainsTarget(s);a&&(s._targetConnectionName=a.connectionName,s.availableZ=a.availableZ,s._containsTarget=!0),s._containsObstacle&&(s._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(s)),s._completelyInsideObstacle&&!s._containsTarget||n.push(s)}return n}shouldNodeBeXYSubdivided(t){return!(t._depth>=this.MAX_DEPTH)&&(!!t._containsTarget||!(!t._containsObstacle||t._completelyInsideObstacle))}_step(){let t=this.unfinishedNodes.pop();if(!t)return void(this.solved=!0);let n=this.getChildNodes(t),i=[],o=[];for(let r of n){let s=this.shouldNodeBeXYSubdivided(r);s?o.push(r):s||r._containsObstacle?!s&&r._containsTarget&&i.push(r):i.push(r)}this.unfinishedNodes.push(...o),this.finishedNodes.push(...i)}visualize(){let t={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Capacity Mesh Visualization"};if(this.outlinePolygon&&this.outlinePolygon.length>=2){let i=this.outlinePolygon.map(o=>({x:o.x,y:o.y}));i.push({...i[0]}),t.lines.push({points:i,strokeColor:"rgba(0, 136, 255, 0.95)",label:"outline"});for(let o of this.outlinePolygon)t.points.push({x:o.x,y:o.y,color:"rgba(0, 136, 255, 0.95)"})}for(let i of this.srj.obstacles)t.rects.push({center:i.center,width:i.width,height:i.height,fill:i.zLayers?.length===1&&i.zLayers?.includes(1)?"rgba(0,0,255,0.3)":"rgba(255,0,0,0.3)",stroke:"red",label:["obstacle",`z: ${i.zLayers.join(",")}`].join(`
|
|
162
162
|
`)});let n=[...this.finishedNodes,...this.unfinishedNodes];for(let i of n){let o=Math.min(...i.availableZ),r=this.unfinishedNodes.length>0&&i===this.unfinishedNodes[this.unfinishedNodes.length-1];t.rects.push({center:{x:i.center.x+o*i.width*.05,y:i.center.y-o*i.width*.05},width:Math.max(i.width-2,.8*i.width),height:Math.max(i.height-2,.8*i.height),fill:i._containsObstacle?"rgba(255,0,0,0.1)":{"0,1":"rgba(0,0,0,0.1)",0:"rgba(0,200,200, 0.1)",1:"rgba(0,0,200, 0.1)"}[i.availableZ.join(",")]??"rgba(0,200,200,0.1)",stroke:r?"rgba(255,165,0,0.5)":void 0,label:[i.capacityMeshNodeId,`availableZ: ${i.availableZ.join(",")}`,`target? ${i._containsTarget??!1}`,`obs? ${i._containsObstacle??!1}`,`${i.width.toFixed(2)}x${i.height.toFixed(2)}`,`capacity: ${zr(i).toFixed(2)}`].join(`
|
|
163
163
|
`)})}return t.rects.sort((i,o)=>i.center.y-o.center.y),this.srj.connections.forEach((i,o)=>{let r=u$[o%u$.length];for(let s of i.pointsToConnect)t.points.push({x:s.x,y:s.y,label:`conn-${o} (${s.layer})`,color:r})}),t}},H$=class extends b0t{constructor(t,n={}){super(t,n);P(this,"VIA_DIAMETER",.6);P(this,"OBSTACLE_MARGIN",.1);P(this,"OVERLAP_THRESHOLD_FOR_SINGLE_LAYER_NODES",.2);this.srj=t,this.opts=n}isNodeCompletelyOutsideBounds(t){if(this.outlinePolygon){let n=this.getNodeRect(t);if(!iT(n,this.outlinePolygon))return!0}return t.center.x+t.width/2<this.srj.bounds.minX||t.center.x-t.width/2>this.srj.bounds.maxX||t.center.y+t.height/2<this.srj.bounds.minY||t.center.y-t.height/2>this.srj.bounds.maxY}isNodePartiallyOutsideBounds(t){if(this.outlinePolygon){let n=this.getNodeRect(t);return!!iT(n,this.outlinePolygon)&&!F$(n,this.outlinePolygon)}return t.center.x-t.width/2<this.srj.bounds.minX||t.center.x+t.width/2>this.srj.bounds.maxX||t.center.y-t.height/2<this.srj.bounds.minY||t.center.y+t.height/2>this.srj.bounds.maxY}getObstacleCoveragePercentage(t){let n=this.getXYZOverlappingObstacles(t);if(n.length===0)return 0;let i=t.center.x-t.width/2,o=t.center.x+t.width/2,r=t.center.y-t.height/2,s=t.center.y+t.height/2,a=t.width*t.height,c=0;for(let l of n){let u=Math.max(i,l.center.x-l.width/2),h=Math.min(o,l.center.x+l.width/2),d=Math.max(r,l.center.y-l.height/2),_=Math.min(s,l.center.y+l.height/2);u<h&&d<_&&(c+=(h-u)*(_-d))}return c/a}shouldFilterSingleLayerNodeForObstacle(t){return t.availableZ.length!==1||!t._containsObstacle?!1:this.getObstacleCoveragePercentage(t)>this.OVERLAP_THRESHOLD_FOR_SINGLE_LAYER_NODES}shouldFilterNodeForObstacle(t){return!!t._containsObstacle&&(t.availableZ.length!==1||this.shouldFilterSingleLayerNodeForObstacle(t))}createChildNodeAtPosition(t,n){let i={capacityMeshNodeId:this.getNextNodeId(),center:n.center,width:n.width,height:n.height,layer:t.layer,availableZ:n.availableZ,_depth:n._depth??(t._depth??0)+1,_parent:t},o=this.getXYZOverlappingObstacles(i);i._containsObstacle=o.length>0||this.isNodePartiallyOutsideBounds(i);let r=this.getTargetIfNodeContainsTarget(i);return r&&(i._targetConnectionName=r.connectionName,i._containsTarget=!0),i._containsObstacle&&(i._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(i)),i}getZSubdivisionChildNodes(t){if(t.availableZ.length===1)return[];let n=[],i=t.availableZ.map(o=>[o]);for(let o of i){let r=this.createChildNodeAtPosition(t,{center:{...t.center},width:t.width,height:t.height,availableZ:o,_depth:t._depth});this.isNodeCompletelyOutsideBounds(r)||n.push(r)}return n}getChildNodes(t){if(t._depth>=this.MAX_DEPTH)return[];let n=[],i={width:t.width/2,height:t.height/2},o=[{x:t.center.x-i.width/2,y:t.center.y-i.height/2},{x:t.center.x+i.width/2,y:t.center.y-i.height/2},{x:t.center.x-i.width/2,y:t.center.y+i.height/2},{x:t.center.x+i.width/2,y:t.center.y+i.height/2}];for(let r of o){let s=this.createChildNodeAtPosition(t,{center:r,width:i.width,height:i.height,availableZ:t.availableZ});this.isNodeCompletelyOutsideBounds(s)||n.push(s)}return n}shouldNodeBeXYSubdivided(t){return!(t._depth>=this.MAX_DEPTH)&&(!!t._containsTarget||t.availableZ.length===1&&t._depth<=this.MAX_DEPTH||!(!t._containsObstacle||t._completelyInsideObstacle))}_step(){let t=this.unfinishedNodes.pop();if(!t)return void(this.solved=!0);let n=this.getChildNodes(t),i=[],o=[];for(let r of n){let s=this.shouldNodeBeXYSubdivided(r),a=r.availableZ.length>1&&!s&&(r._containsObstacle||r.width<this.VIA_DIAMETER+this.OBSTACLE_MARGIN);if(s)o.push(r);else if(s||this.shouldFilterNodeForObstacle(r)||a)if(!s&&r._containsTarget)if(a){let c=this.getZSubdivisionChildNodes(r);i.push(...c.filter(l=>l._containsTarget||!this.shouldFilterNodeForObstacle(l)))}else i.push(r);else a&&i.push(...this.getZSubdivisionChildNodes(r).filter(c=>!this.shouldFilterNodeForObstacle(c)));else i.push(r)}this.unfinishedNodes.push(...o),this.finishedNodes.push(...i)}};function lh(e){let t=new Map;for(let n of e)for(let i of n.nodeIds)t.set(i,[...t.get(i)??[],n]);return t}var G$=class extends Ke{constructor({nodes:t,edges:n,capacityPaths:i,colorMap:o}){super();P(this,"nodes");P(this,"edges");P(this,"capacityPaths");P(this,"nodeMap");P(this,"nodeEdgeMap");P(this,"unprocessedNodeIds");P(this,"nodePortSegments");P(this,"colorMap");this.nodes=t,this.edges=n,this.nodeMap=new Map(t.map(r=>[r.capacityMeshNodeId,r])),this.nodeEdgeMap=lh(n),this.capacityPaths=i,this.colorMap=o??{},this.unprocessedNodeIds=[...new Set(i.flatMap(r=>r.nodeIds))],this.nodePortSegments=new Map}step(){let t=this.unprocessedNodeIds.pop();if(!t)return void(this.solved=!0);let n=[];for(let s of this.capacityPaths){let a=s.nodeIds.indexOf(t);a!==-1&&n.push({path:s,indexOfNodeInPath:a})}let i=this.nodeMap.get(t),o=[];for(let{path:s,indexOfNodeInPath:a}of n){let c=s.nodeIds[a-1],l=s.nodeIds[a+1];for(let u of[c,l]){let h=this.nodeMap.get(u);if(!h)continue;let d=x0t(i,h),_=h.availableZ.filter(g=>i.availableZ.includes(g));if(_.length===0)continue;let y={capacityMeshNodeId:t,start:d.start,end:d.end,connectionNames:[s.connectionName],availableZ:_};o.push(y)}}let r=(function(s){let a=[],c=s.map(l=>({...l,connectionNames:[...l.connectionNames],availableZ:[...l.availableZ].sort((u,h)=>u-h)}));for(;c.length>0;){let l=c.pop(),u=!1;for(let h=0;h<a.length;h++){let d=a[h],_=yb(d.start,l.start)&&yb(d.end,l.end)||yb(d.start,l.end)&&yb(d.end,l.start),y=v0t(d.availableZ,l.availableZ);if(_&&y){let g=new Set(d.connectionNames);l.connectionNames.forEach(x=>g.add(x)),d.connectionNames=Array.from(g),u=!0;break}}u||a.push(l)}return a})(o);this.nodePortSegments.set(t,r)}visualize(){let t={lines:[],points:[],rects:[],circles:[]};return this.nodePortSegments.forEach((n,i)=>{this.nodeMap.get(i),n.forEach(o=>{o.start.x,o.end.x;for(let r=0;r<o.connectionNames.length;r++){let s={x:.05*Math.max(...o.availableZ),y:.05*Math.max(...o.availableZ)},a={x:(o.start.x+o.end.x)/2,y:(o.start.y+o.end.y)/2},c={x:a.x+s.x,y:a.y+s.y};s.x>0&&t.lines.push({points:[a,c],strokeColor:"rgba(0, 0, 0, 0.25)",strokeDash:"5 5"}),t.points.push({x:c.x,y:c.y,label:`${i}: ${o.connectionNames.join(", ")}
|
|
164
164
|
availableZ: ${o.availableZ.join(",")}
|
|
@@ -245,10 +245,10 @@ ${_.join(`
|
|
|
245
245
|
</div>`},Svt=e=>{let t=e.layout(),n={title:"CssGrid",coordinateSystem:"screen",lines:[],circles:[],points:[],rects:[],texts:[]},{cells:i}=t;for(let o of i){let{x:r,y:s,width:a,height:c,key:l}=o;n.rects.push({center:{x:r+a/2,y:s+c/2},width:a,height:c,fill:tX(l),label:l})}return n};function fx(e){return e.replace(/repeat\((\d+),\s*([^)]+)\)/g,(t,n,i)=>Array(Number(n)).fill(i.trim()).join(" "))}function mx(e){return e.trim().split(/\s+/).filter(Boolean)}function KY(e){return e?mx(fx(e)).length:0}function JY(e,t){if(e==="auto")return{fr:1};if(e.endsWith("%")){let i=parseFloat(e);return t!=null?t*i/100:0}if(e.endsWith("px"))return parseFloat(e);if(e.endsWith("em"))return parseFloat(e)*16;if(e.endsWith("fr"))return{fr:parseFloat(e)};let n=parseFloat(e);return Number.isNaN(n)?0:n}function QY(e,t){return e>0?e:t+2+e}var wvt=e=>{let t=e.opts,n=t.children,i,o;if("gridTemplate"in t&&typeof t.gridTemplate=="string"){let[M,k]=t.gridTemplate.split("/");i=M?.trim(),o=k?.trim()}else i=typeof t.gridTemplateRows=="string"?t.gridTemplateRows:void 0,o=typeof t.gridTemplateColumns=="string"?t.gridTemplateColumns:void 0;let r=KY(o),s=KY(i);function a(M,k,N,A){if(!M)return 0;let R=fx(M),$=mx(R),j=$.length,H=0,X=!1;for(let tt=0;tt<$.length;tt++){let Q=$[tt];if(Q.endsWith("px"))H+=parseFloat(Q);else if(Q.endsWith("em"))H+=parseFloat(Q)*16;else if(Q.endsWith("fr")||Q==="auto"){X=!0;let V=0;for(let rt of k){let et=N?rt.columnStart||rt.column:rt.rowStart||rt.row,J=N?rt.columnSpan||1:rt.rowSpan||1,pt=N?rt.contentWidth:rt.contentHeight,ht=(typeof et=="number"?et:parseInt(et||"1"))-1,St=typeof J=="number"?J:parseInt(J.toString());if(ht<=tt&&tt<ht+St&&pt){let wt=typeof pt=="string"&&pt.endsWith("px")?parseFloat(pt):typeof pt=="number"?pt:0;V=Math.max(V,wt/St)}}H+=V}}let G=A*(j-1);return H+G}function c(M,k,N,A=!0,R=1){if(!M)return[];if(k==null){let J=fx(M),pt=mx(J),ht=pt.length,St=B=>B===void 0?0:typeof B=="number"?B:(B.endsWith("px"),parseFloat(B)),wt=new Array(ht).fill(0),lt=0;for(let B of n){let q=A?typeof B.columnSpan=="number"?B.columnSpan:B.columnSpan?parseInt(B.columnSpan.toString()):1:typeof B.rowSpan=="number"?B.rowSpan:B.rowSpan?parseInt(B.rowSpan.toString()):1,it=A?B.contentWidth:B.contentHeight,ut=St(it)/q,_t;A?(B.columnStart!==void 0||B.column!==void 0)&&(_t=parseInt(B.columnStart??B.column)-1):(B.rowStart!==void 0||B.row!==void 0)&&(_t=parseInt(B.rowStart??B.row)-1),(_t===void 0||Number.isNaN(_t))&&(A?_t=lt%ht:_t=Math.floor(lt/R),lt+=q);for(let W=0;W<q&&_t+W<ht;W++)wt[_t+W]=Math.max(wt[_t+W],ut)}return pt.forEach((B,q)=>{let it=JY(B,void 0);typeof it=="number"&&(wt[q]=it)}),wt}let $=fx(M),j=mx($),H=j.length,X=k;X==null&&(X=a(M,n,A,N));let G=X-N*(H-1),tt=0,Q=0,V=[],rt=[];j.forEach((J,pt)=>{let ht=JY(J,G);typeof ht=="number"?(rt.push(ht),tt+=ht):ht&&typeof ht=="object"&&"fr"in ht?(rt.push(ht),Q+=ht.fr,V.push({idx:pt,fr:ht.fr})):(rt.push(0),tt+=0)});let et=Math.max(G-tt,0);return rt.map(J=>typeof J=="number"?J:Q>0?et/Q*J.fr:0)}let l=typeof t.gap=="number"?t.gap:Array.isArray(t.gap)?t.gap[0]:0,u=typeof t.gap=="number"?t.gap:Array.isArray(t.gap)?t.gap[1]:0,h=c(i,t.containerHeight,l,!1,r||1),d=c(o,t.containerWidth,u,!0,s||1),_=h.length,y=d.length;y===0&&n.length>0&&(y=1);let g=[],x=0;for(let M of n){let k=M.rowStart!==void 0?M.rowStart:M.row,N=M.columnStart!==void 0?M.columnStart:M.column,A=M.rowSpan!==void 0?typeof M.rowSpan=="string"?parseInt(M.rowSpan):M.rowSpan:1,R=M.columnSpan!==void 0?typeof M.columnSpan=="string"?parseInt(M.columnSpan):M.columnSpan:1;if(M.rowEnd!==void 0){let H=typeof M.rowEnd=="string"?parseInt(M.rowEnd):M.rowEnd;k!==void 0?A=H-(typeof k=="string"?parseInt(k):k):k=H-A}if(M.columnEnd!==void 0){let H=typeof M.columnEnd=="string"?parseInt(M.columnEnd):M.columnEnd;N!==void 0?R=H-(typeof N=="string"?parseInt(N):N):N=H-R}if(typeof k=="string"&&(k=parseInt(k)),typeof N=="string"&&(N=parseInt(N)),typeof k=="number"&&k<0&&(k=QY(k,_)),typeof N=="number"&&N<0&&(N=QY(N,y)),k===void 0&&N!==void 0)k=1;else if(N===void 0&&k!==void 0)N=1;else if(k===void 0&&N===void 0){let H=x;k=Math.floor(H/y)+1,N=H%y+1}let $=k-1,j=N-1;A=Math.max(1,A),R=Math.max(1,R),g.push({key:M.key,row:$,column:j,rowSpan:A,columnSpan:R,x:0,y:0,width:0,height:0}),x+=R}let w=h.length,S=d.length;for(let M of g)M.row+M.rowSpan>w&&(w=M.row+M.rowSpan),M.column+M.columnSpan>S&&(S=M.column+M.columnSpan);if(h.length===0&&w>0&&t.containerHeight){let M=w,N=(t.containerHeight-l*(M-1))/M;for(let A=0;A<M;A++)h.push(N)}else for(;h.length<w;)h.push(0);if(d.length===0&&S>0&&t.containerWidth){let M=S,N=(t.containerWidth-u*(M-1))/M;for(let A=0;A<M;A++)d.push(N)}else if(d.length===0&&n.length>0&&t.containerWidth)d.push(t.containerWidth);else for(;d.length<S;)d.push(0);let T=(M,k,N)=>{let A=0;for(let R=0;R<M;R++)A+=k[R]||0,A+=N;return A},I=(M,k,N,A)=>{let R=0;for(let $=M;$<M+k;$++)R+=N[$]||0,$>M&&(R+=A);return R},E={};for(let M of g){let k=n.find(rt=>rt.key===M.key),N=T(M.column,d,u),A=T(M.row,h,l),R=I(M.column,M.columnSpan,d,u),$=I(M.row,M.rowSpan,h,l),j=rt=>rt===void 0?0:typeof rt=="string"?rt.endsWith("px")?parseFloat(rt):rt.endsWith("%")?0:parseFloat(rt):rt,H=j(k?.contentWidth),X=j(k?.contentHeight),G=R,tt=$,Q=N,V=A;if(H>0)switch(G=H,t.justifyItems||"stretch"){case"start":Q=N;break;case"end":Q=N+R-G;break;case"center":Q=N+(R-G)/2;break;case"stretch":G=R,Q=N;break}if(X>0)switch(tt=X,t.alignItems||"stretch"){case"start":V=A;break;case"end":V=A+$-tt;break;case"center":V=A+($-tt)/2;break;case"stretch":tt=$,V=A;break}M.x=Q,M.y=V,M.width=G,M.height=tt,E[M.key]={x:Q,y:V,width:G,height:tt}}return{cells:g,rowSizes:h,columnSizes:d,rowGap:l,columnGap:u,itemCoordinates:E}},eX=class{constructor(e){P(this,"opts");this.opts=e}layout(){return wvt(this)}convertToHtml(){return vvt(this)}visualize(){return Svt(this)}};vt();var qH=Xt(Sn(),1);ke();ke();vt();var LM=class{constructor(e){P(this,"netMap");P(this,"idToNetMap");this.netMap=e,this.idToNetMap={};for(let[t,n]of Object.entries(e))for(let i of n)this.idToNetMap[i]=t}addConnections(e){for(let t of e){let n=new Set;for(let o of t){let r=this.idToNetMap[o];r&&n.add(r)}let i;if(n.size===0)i=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[i]=[];else if(n.size===1)i=n.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{i=n.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(let o of n)if(o!==i){let r=this.netMap[i],s=this.netMap[o];if(r&&s){r.push(...s),this.netMap[o]=r;for(let a of r)this.idToNetMap[a]=i}}}for(let o of t){let r=this.netMap[i];r&&!r.includes(o)&&r.push(o),this.idToNetMap[o]=i}}}getIdsConnectedToNet(e){return this.netMap[e]||[]}getNetConnectedToId(e){return this.idToNetMap[e]}areIdsConnected(e,t){if(e===t)return!0;let n=this.getNetConnectedToId(e);if(!n)return!1;let i=this.getNetConnectedToId(t);return i?n===i||i===e||i===e:!1}areAllIdsConnected(e){if(e.length===0)return!0;let t=this.getNetConnectedToId(e[0]);if(!t)return!1;for(let n of e){let i=this.getNetConnectedToId(n);if(i===void 0||i!==t)return!1}return!0}};Pf();var pm=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(t,n){let i=this.length++;for(;i>0;){let o=i-1>>1,r=this.values[o];if(n>=r)break;this.ids[i]=this.ids[o],this.values[i]=r,i=o}this.ids[i]=t,this.values[i]=n}pop(){if(this.length===0)return;let t=this.ids,n=this.values,i=t[0],o=--this.length;if(o>0){let r=t[o],s=n[o],a=0,c=o>>1;for(;a<c;){let l=(a<<1)+1,u=l+1,h=l+(+(u<o)&+(n[u]<n[l]));if(n[h]>=s)break;t[a]=t[h],n[a]=n[h],a=h}t[a]=r,n[a]=s}return i}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 nX=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],FM=3,hm=class e{static from(t,n=0){if(n%8!==0)throw new Error("byteOffset must be 8-byte aligned.");if(!t||t.byteLength===void 0||t.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[i,o]=new Uint8Array(t,n+0,2);if(i!==251)throw new Error("Data does not appear to be in a Flatbush format.");let r=o>>4;if(r!==FM)throw new Error(`Got v${r} data when expected v${FM}.`);let s=nX[o&15];if(!s)throw new Error("Unrecognized array type.");let[a]=new Uint16Array(t,n+2,1),[c]=new Uint32Array(t,n+4,1);return new e(c,a,s,void 0,t,n)}constructor(t,n=16,i=Float64Array,o=ArrayBuffer,r,s=0){if(t===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(t)||t<=0)throw new Error(`Unexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+n,2),65535),this.byteOffset=s;let a=t,c=a;this._levelBounds=[a*4];do a=Math.ceil(a/this.nodeSize),c+=a,this._levelBounds.push(c*4);while(a!==1);this.ArrayType=i,this.IndexArrayType=c<16384?Uint16Array:Uint32Array;let l=nX.indexOf(i),u=c*4*i.BYTES_PER_ELEMENT;if(l<0)throw new Error(`Unexpected typed array class: ${i}.`);if(r)this.data=r,this._boxes=new i(r,s+8,c*4),this._indices=new this.IndexArrayType(r,s+8+u,c),this._pos=c*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 h=this.data=new o(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(h,8,c*4),this._indices=new this.IndexArrayType(h,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(h,0,2).set([251,(FM<<4)+l]),new Uint16Array(h,2,1)[0]=n,new Uint32Array(h,4,1)[0]=t}this._queue=new pm}add(t,n,i=t,o=n){let r=this._pos>>2,s=this._boxes;return this._indices[r]=r,s[this._pos++]=t,s[this._pos++]=n,s[this._pos++]=i,s[this._pos++]=o,t<this.minX&&(this.minX=t),n<this.minY&&(this.minY=n),i>this.maxX&&(this.maxX=i),o>this.maxY&&(this.maxY=o),r}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let t=this._boxes;if(this.numItems<=this.nodeSize){t[this._pos++]=this.minX,t[this._pos++]=this.minY,t[this._pos++]=this.maxX,t[this._pos++]=this.maxY;return}let n=this.maxX-this.minX||1,i=this.maxY-this.minY||1,o=new Uint32Array(this.numItems),r=65535;for(let s=0,a=0;s<this.numItems;s++){let c=t[a++],l=t[a++],u=t[a++],h=t[a++],d=Math.floor(r*((c+u)/2-this.minX)/n),_=Math.floor(r*((l+h)/2-this.minY)/i);o[s]=Ivt(d,_)}zM(o,t,this._indices,0,this.numItems-1,this.nodeSize);for(let s=0,a=0;s<this._levelBounds.length-1;s++){let c=this._levelBounds[s];for(;a<c;){let l=a,u=t[a++],h=t[a++],d=t[a++],_=t[a++];for(let y=1;y<this.nodeSize&&a<c;y++)u=Math.min(u,t[a++]),h=Math.min(h,t[a++]),d=Math.max(d,t[a++]),_=Math.max(_,t[a++]);this._indices[this._pos>>2]=l,t[this._pos++]=u,t[this._pos++]=h,t[this._pos++]=d,t[this._pos++]=_}}}search(t,n,i,o,r){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=[],c=[];for(;s!==void 0;){let l=Math.min(s+this.nodeSize*4,iX(s,this._levelBounds));for(let u=s;u<l;u+=4){let h=this._boxes[u];if(i<h)continue;let d=this._boxes[u+1];if(o<d)continue;let _=this._boxes[u+2];if(t>_)continue;let y=this._boxes[u+3];if(n>y)continue;let g=this._indices[u>>2]|0;s>=this.numItems*4?a.push(g):(r===void 0||r(g,h,d,_,y))&&c.push(g)}s=a.pop()}return c}neighbors(t,n,i=1/0,o=1/0,r){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=this._queue,c=[],l=o*o;t:for(;s!==void 0;){let u=Math.min(s+this.nodeSize*4,iX(s,this._levelBounds));for(let h=s;h<u;h+=4){let d=this._indices[h>>2]|0,_=this._boxes[h],y=this._boxes[h+1],g=this._boxes[h+2],x=this._boxes[h+3],w=t<_?_-t:t>g?t-g:0,S=n<y?y-n:n>x?n-x:0,T=w*w+S*S;T>l||(s>=this.numItems*4?a.push(d<<1,T):(r===void 0||r(d))&&a.push((d<<1)+1,T))}for(;a.length&&a.peek()&1;)if(a.peekValue()>l||(c.push(a.pop()>>1),c.length===i))break t;s=a.length?a.pop()>>1:void 0}return a.clear(),c}};function iX(e,t){let n=0,i=t.length-1;for(;n<i;){let o=n+i>>1;t[o]>e?i=o:n=o+1}return t[n]}function zM(e,t,n,i,o,r){if(Math.floor(i/r)>=Math.floor(o/r))return;let s=e[i],a=e[i+o>>1],c=e[o],l=c,u=Math.max(s,a);c>u?l=u:u===s?l=Math.max(a,c):u===a&&(l=Math.max(s,c));let h=i-1,d=o+1;for(;;){do h++;while(e[h]<l);do d--;while(e[d]>l);if(h>=d)break;Pvt(e,t,n,h,d)}zM(e,t,n,i,d,r),zM(e,t,n,d+1,o,r)}function Pvt(e,t,n,i,o){let r=e[i];e[i]=e[o],e[o]=r;let s=4*i,a=4*o,c=t[s],l=t[s+1],u=t[s+2],h=t[s+3];t[s]=t[a],t[s+1]=t[a+1],t[s+2]=t[a+2],t[s+3]=t[a+3],t[a]=c,t[a+1]=l,t[a+2]=u,t[a+3]=h;let d=n[i];n[i]=n[o],n[o]=d}function Ivt(e,t){let n=e^t,i=65535^n,o=65535^(e|t),r=e&(t^65535),s=n|i>>1,a=n>>1^n,c=o>>1^i&r>>1^o,l=n&o>>1^r>>1^r;n=s,i=a,o=c,r=l,s=n&n>>2^i&i>>2,a=n&i>>2^i&(n^i)>>2,c^=n&o>>2^i&r>>2,l^=i&o>>2^(n^i)&r>>2,n=s,i=a,o=c,r=l,s=n&n>>4^i&i>>4,a=n&i>>4^i&(n^i)>>4,c^=n&o>>4^i&r>>4,l^=i&o>>4^(n^i)&r>>4,n=s,i=a,o=c,r=l,c^=n&o>>8^i&r>>8,l^=i&o>>8^(n^i)&r>>8,n=c^c>>1,i=l^l>>1;let u=e^t,h=i|65535^(u|n);return u=(u|u<<8)&16711935,u=(u|u<<4)&252645135,u=(u|u<<2)&858993459,u=(u|u<<1)&1431655765,h=(h|h<<8)&16711935,h=(h|h<<4)&252645135,h=(h|h<<2)&858993459,h=(h|h<<1)&1431655765,(h<<1|u)>>>0}var co=class{constructor(){P(this,"MAX_ITERATIONS",1e5);P(this,"solved",!1);P(this,"failed",!1);P(this,"iterations",0);P(this,"progress",0);P(this,"error",null);P(this,"activeSubSolver");P(this,"failedSubSolvers");P(this,"timeToSolve");P(this,"stats",{})}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.constructor.name} error: ${e}`,this.failed=!0,e}!this.solved&&this.iterations>this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){let e=Date.now();for(;!this.solved&&!this.failed;)this.step();let t=Date.now();this.timeToSolve=t-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}},HM=e=>{let t=new LM({});for(let i of e.directConnections)t.addConnections([i.netId?[i.netId,...i.pinIds]:i.pinIds]);let n=new LM(t.netMap);for(let i of e.netConnections)n.addConnections([[i.netId,...i.pinIds]]);return{directConnMap:t,netConnMap:n}};function Tvt(e,t={}){let n=e.length,i=t?.maxDistance??Number.POSITIVE_INFINITY;if(n<=1)return[];{let u=new Set;for(let h of e){if(u.has(h.pinId))throw new Error(`Duplicate pinId detected: "${h.pinId}"`);u.add(h.pinId)}}let o=(u,h)=>Math.abs(u.x-h.x)+Math.abs(u.y-h.y),r=new Array(n).fill(!1),s=new Array(n).fill(Number.POSITIVE_INFINITY),a=new Array(n).fill(-1),c=0;for(let u=1;u<n;u++)e[u].pinId<e[c].pinId&&(c=u);s[c]=0;let l=[];for(let u=0;u<n;u++){let h=-1,d=Number.POSITIVE_INFINITY,_="";for(let y=0;y<n;y++)if(!r[y]){let g=s[y];(g<d||g===d&&(_===""||e[y].pinId<_))&&(d=g,_=e[y].pinId,h=y)}r[h]=!0,a[h]!==-1&&l.push([e[h].pinId,e[a[h]].pinId]);for(let y=0;y<n;y++)if(!r[y]){let g=o(e[h],e[y]),x=t?.forbidEdge?.(e[h],e[y])??!1,w=g>i||x?Number.POSITIVE_INFINITY:g;(w<s[y]||w===s[y]&&e[h].pinId<e[a[y]]?.pinId)&&(s[y]=w,a[y]=h)}}return l}var dm=(e,t)=>{let{x:n,y:i}=e,{center:o,width:r,height:s}=t,a=o.y+s/2,c=o.y-s/2,l=o.x+r/2,u=o.x-r/2,h=a-i,d=i-c,_=l-n,y=n-u,g=Math.min(h,d,_,y);return g===h?"y+":g===d?"y-":g===_?"x+":"x-"},Mvt=e=>{let{pins:t,inputProblem:n,pinIdMap:i,chipMap:o}=e,r=d=>{let _=new Set,y=[d];_.add(d);let g=n.directConnections||[];for(;y.length;){let x=y.shift();for(let w of g)if(w.pinIds.includes(x))for(let S of w.pinIds)_.has(S)||(_.add(S),y.push(S))}return _},s=t[0].pinId,a=t[1].pinId,c=new Set([...r(s),...r(a)]),l=new Map,u=new Map,h=new Set(t.map(d=>d.chipId));for(let d of c){let _=i.get(d);if(!_)continue;let y=o[_.chipId];if(!y)continue;let g=_._facingDirection??dm(_,y),x=u.get(y.chipId);if(!x){x={center:y.center};let w={xPos:0,xNeg:0,yPos:0,yNeg:0};for(let S of y.pins){let T=S._facingDirection??dm(S,y);T==="x+"&&w.xPos++,T==="x-"&&w.xNeg++,T==="y+"&&w.yPos++,T==="y-"&&w.yNeg++}x.counts=w,u.set(y.chipId,x)}g==="x+"&&(x.hasXPos=!0),g==="x-"&&(x.hasXNeg=!0),g==="y+"&&(x.hasYPos=!0),g==="y-"&&(x.hasYNeg=!0)}for(let[d,_]of u){let y=new Set,g={axes:y},x=_.counts;!!!(x&&(x.xPos>1||x.xNeg>1||x.yPos>1||x.yNeg>1))&&h.has(d)||(_.hasXPos&&_.hasXNeg&&(g.x=_.center.x,y.add("x")),_.hasYPos&&_.hasYNeg&&(g.y=_.center.y,y.add("y"))),y.size>0&&l.set(d,g)}return l},DM=e=>{let{inputProblem:t,chipMap:n,pinIdMap:i,p1:o,p2:r}=e,s=Mvt({pins:[o,r],inputProblem:t,pinIdMap:i,chipMap:n});if(s.size===0)return!1;let a=1e-9,c=(_,y)=>{for(let[,g]of s)if(g.axes.has("x")&&typeof g.x=="number"&&(_.x-g.x)*(y.x-g.x)<-a||g.axes.has("y")&&typeof g.y=="number"&&(_.y-g.y)*(y.y-g.y)<-a)return!0;return!1};if(Math.abs(o.x-r.x)<a||Math.abs(o.y-r.y)<a)return c({x:o.x,y:o.y},{x:r.x,y:r.y});let l={x:r.x,y:o.y},u={x:o.x,y:r.y},h=c({x:o.x,y:o.y},l)||c(l,{x:r.x,y:r.y}),d=c({x:o.x,y:o.y},u)||c(u,{x:r.x,y:r.y});return h&&d},fr=(e,t=1)=>`hsl(${e.split("").reduce((i,o)=>i*31+o.charCodeAt(0),0)%360}, 100%, 50%, ${t})`,Vo=(e,t={})=>{let{connectionAlpha:n=.8,chipAlpha:i=.8}=t,o={lines:[],points:[],rects:[]},r=new Map;for(let s of e.chips)for(let a of s.pins)r.set(a.pinId,a);for(let s of e.chips){o.rects.push({label:s.chipId,center:s.center,width:s.width,height:s.height,fill:fr(s.chipId,i)});for(let a of s.pins)o.points.push({label:`${a.pinId}
|
|
246
246
|
${a._facingDirection??dm(a,s)}`,x:a.x,y:a.y,color:fr(a.pinId,.8)})}for(let s of e.directConnections){let[a,c]=s.pinIds,l=r.get(a),u=r.get(c);o.lines.push({points:[{x:l.x,y:l.y},{x:u.x,y:u.y}],strokeColor:fr(s.netId??`${a}-${c}`,n)})}for(let s of e.netConnections){let a=s.pinIds.map(c=>r.get(c));for(let c=0;c<a.length-1;c++)for(let l=c+1;l<a.length;l++){let u=a[c],h=a[l];o.lines.push({points:[{x:u.x,y:u.y},{x:h.x,y:h.y}],strokeColor:fr(s.netId,n),strokeDash:"4 2"})}}return o},Cvt=class extends co{constructor({inputProblem:t}){super();P(this,"inputProblem");P(this,"mspConnectionPairs",[]);P(this,"dcConnMap");P(this,"globalConnMap");P(this,"queuedDcNetIds");P(this,"chipMap");P(this,"maxMspPairDistance");P(this,"pinMap");P(this,"userNetIdByPinId");this.inputProblem=t,this.maxMspPairDistance=t.maxMspPairDistance??1;let{directConnMap:n,netConnMap:i}=HM(t);this.dcConnMap=n,this.globalConnMap=i,this.pinMap={};for(let o of t.chips)for(let r of o.pins)this.pinMap[r.pinId]={...r,chipId:o.chipId};this.chipMap={};for(let o of t.chips)this.chipMap[o.chipId]=o;this.userNetIdByPinId={};for(let o of t.directConnections)if(o.netId){let[r,s]=o.pinIds;this.userNetIdByPinId[r]=o.netId,this.userNetIdByPinId[s]=o.netId}for(let o of t.netConnections)for(let r of o.pinIds)this.userNetIdByPinId[r]=o.netId;this.queuedDcNetIds=Object.keys(i.netMap)}getConstructorParams(){return{inputProblem:this.inputProblem}}_step(){if(this.queuedDcNetIds.length===0){this.solved=!0;return}let t=this.queuedDcNetIds.shift(),i=this.globalConnMap.getIdsConnectedToNet(t).filter(s=>!!this.pinMap[s]);if(i.length<=1)return;if(i.length===2){let[s,a]=i,c=this.pinMap[s],l=this.pinMap[a];if(Math.abs(c.x-l.x)+Math.abs(c.y-l.y)>this.maxMspPairDistance)return;let h=new Map(Object.entries(this.pinMap));if(DM({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:h,p1:c,p2:l}))return;let d=this.globalConnMap.getNetConnectedToId(s),_=this.userNetIdByPinId[s]??this.userNetIdByPinId[a];this.mspConnectionPairs.push({mspPairId:`${s}-${a}`,dcConnNetId:t,globalConnNetId:d,userNetId:_,pins:[c,l]});return}let o=new Map(Object.entries(this.pinMap)),r=Tvt(i.map(s=>this.pinMap[s]).filter(Boolean),{maxDistance:this.maxMspPairDistance,forbidEdge:(s,a)=>DM({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:o,p1:s,p2:a})});for(let[s,a]of r){let c=this.pinMap[s],l=this.pinMap[a];if(DM({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:o,p1:c,p2:l}))continue;let u=this.globalConnMap.getNetConnectedToId(s),h=this.userNetIdByPinId[s]??this.userNetIdByPinId[a];this.mspConnectionPairs.push({mspPairId:`${s}-${a}`,dcConnNetId:t,globalConnNetId:u,userNetId:h,pins:[c,l]})}}visualize(){let t=Vo(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let n of this.mspConnectionPairs)t.lines.push({points:[{x:n.pins[0].x,y:n.pins[0].y},{x:n.pins[1].x,y:n.pins[1].y}],strokeColor:fr(n.mspPairId,.75)});return t}};function GM(e){let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,maxX:e.center.x+t,minY:e.center.y-n,maxY:e.center.y+n}}var Evt=e=>{let t=GM(e);return{chipId:e.chipId,...t}},yx=e=>e.chips.map(Evt),UM=1e-9,ta=(e,t,n=UM)=>Math.abs(e.x-t.x)<n,bc=(e,t,n=UM)=>Math.abs(e.y-t.y)<n,mm=(e,t,n,i=UM)=>{let o=ta(e,t,i),r=bc(e,t,i);if(!o&&!r)return!1;if(o){let s=e.x;if(s<n.minX-i||s>n.maxX+i)return!1;let a=Math.min(e.y,t.y),c=Math.max(e.y,t.y);return Math.min(c,n.maxY)-Math.max(a,n.minY)>i}else{let s=e.y;if(s<n.minY-i||s>n.maxY+i)return!1;let a=Math.min(e.x,t.x),c=Math.max(e.x,t.x);return Math.min(c,n.maxX)-Math.max(a,n.minX)>i}},Nvt=(e,t,n={})=>{for(let i=0;i<e.length-1;i++){let o=e[i],r=e[i+1],s=n.excludeRectIdsForSegment?.(i)??new Set;for(let a of t)if(!s.has(a.chipId)&&mm(o,r,a))return{segIndex:i,rect:a}}return null},kvt=(e,t)=>{for(let n=0;n<e.length-1;n++)for(let i of t)if(mm(e[n],e[n+1],i))return!0;return!1},fX=1e-9,Avt=(e,t)=>({minX:Math.min(e.x,t.x),maxX:Math.max(e.x,t.x),minY:Math.min(e.y,t.y),maxY:Math.max(e.y,t.y)}),oX=(e,t,n,i=fX)=>e==="x"?t.x<n.minX-i?[(t.x+n.minX)/2]:t.x>n.maxX+i?[(t.x+n.maxX)/2]:[n.minX-.2,n.maxX+.2]:t.y<n.minY-i?[(t.y+n.minY)/2]:t.y>n.maxY+i?[(t.y+n.maxY)/2]:[n.minY-.2,n.maxY+.2],Rvt=(e,t,n,i,o,r=fX)=>{let s=[...i].map(a=>n.get(a)).filter(a=>!!a);if(e==="x"){let a=[o.minX,...s.map(d=>d.maxX)].filter(d=>d<t.minX-r),c=[o.maxX,...s.map(d=>d.minX)].filter(d=>d>t.maxX+r),l=a.length>0?Math.max(...a):void 0,u=c.length>0?Math.min(...c):void 0,h=[];return l!==void 0&&h.push((l+t.minX)/2),u!==void 0&&h.push((t.maxX+u)/2),h}else{let a=[o.minY,...s.map(d=>d.maxY)].filter(d=>d<t.minY-r),c=[o.maxY,...s.map(d=>d.minY)].filter(d=>d>t.maxY+r),l=a.length>0?Math.max(...a):void 0,u=c.length>0?Math.min(...c):void 0,h=[];return l!==void 0&&h.push((l+t.minY)/2),u!==void 0&&h.push((t.maxY+u)/2),h}},Ovt=1e-9,Lvt=(e,t,n,i,o=Ovt)=>{if(t<0||t>=e.length-1)return null;let r=e[t],s=e[t+1],a=ta(r,s,o),c=bc(r,s,o);if(!a&&!c||a&&n!=="x"||c&&n!=="y")return null;let l=e.map(u=>({...u}));if(n==="x"){if(Math.abs(r.x-i)<o&&Math.abs(s.x-i)<o)return null;l[t]={...l[t],x:i},l[t+1]={...l[t+1],x:i}}else{if(Math.abs(r.y-i)<o&&Math.abs(s.y-i)<o)return null;l[t]={...l[t],y:i},l[t+1]={...l[t+1],y:i}}if(t-1>=0){let u=l[t-1],h=l[t];if(Math.abs(u.x-h.x)+Math.abs(u.y-h.y)<o)return null}if(t+2<=l.length-1){let u=l[t+1],h=l[t+2];if(Math.abs(u.x-h.x)+Math.abs(u.y-h.y)<o)return null}for(let u=0;u<l.length-1;u++){let h=l[u],d=l[u+1];if(!bc(h,d,o)&&!ta(h,d,o))return null}return l},rX=(e,t=6)=>e.map(i=>`${i.x.toFixed(t)},${i.y.toFixed(t)}`).join("|"),mX=class extends co{constructor(t){super();P(this,"pins");P(this,"inputProblem");P(this,"chipMap");P(this,"obstacles");P(this,"rectById");P(this,"aabb");P(this,"baseElbow");P(this,"solvedTracePath",null);P(this,"queue",[]);P(this,"visited",new Set);this.pins=t.pins,this.inputProblem=t.inputProblem,this.chipMap=t.chipMap;for(let o of this.pins)if(!o._facingDirection){let r=this.chipMap[o.chipId];o._facingDirection=dm(o,r)}this.obstacles=yx(this.inputProblem),this.rectById=new Map(this.obstacles.map(o=>[o.chipId,o]));let[n,i]=this.pins;this.baseElbow=oc({x:n.x,y:n.y,facingDirection:n._facingDirection},{x:i.x,y:i.y,facingDirection:i._facingDirection},{overshoot:.2}),this.aabb=Avt({x:n.x,y:n.y},{x:i.x,y:i.y}),this.queue.push({path:this.baseElbow,collisionChipIds:new Set}),this.visited.add(rX(this.baseElbow))}getConstructorParams(){return{chipMap:this.chipMap,pins:this.pins,inputProblem:this.inputProblem}}axisOfSegment(t,n){return ta(t,n)?"x":bc(t,n)?"y":null}pathLength(t){let n=0;for(let i=0;i<t.length-1;i++)n+=Math.abs(t[i+1].x-t[i].x)+Math.abs(t[i+1].y-t[i].y);return n}_step(){if(this.solvedTracePath){this.solved=!0;return}let t=this.queue.shift();if(!t){this.failed=!0,this.error="No collision-free path found";return}let{path:n,collisionChipIds:i}=t,[o,r]=this.pins,s=Nvt(n,this.obstacles);if(!s){let x=n[0],w=n[n.length-1],S=1e-9,T=(I,E)=>Math.abs(I.x-E.x)<S&&Math.abs(I.y-E.y)<S;T(x,{x:o.x,y:o.y})&&T(w,{x:r.x,y:r.y})&&(this.solvedTracePath=n,this.solved=!0);return}let{segIndex:a,rect:c}=s,l=a===0,u=a===n.length-2;if(l){if(n.length<3)return;a=1}else if(u){if(n.length<3)return;a=n.length-3}let h=n[a],d=n[a+1],_=this.axisOfSegment(h,d);if(!_)return;let y=[];if(i.size===0){let x=oX(_,{x:o.x,y:o.y},c),w=oX(_,{x:r.x,y:r.y},c),S=[...x,...w],T=[...new Set(S)];y.push(...T)}else{let x=Rvt(_,c,this.rectById,i,this.aabb);y.push(...x)}let g=[];for(let x of y){let w=Lvt(n,a,_,x);if(!w)continue;let S=rX(w);if(this.visited.has(S))continue;this.visited.add(S);let T=new Set(i);T.add(c.chipId);let I=this.pathLength(w);g.push({path:w,collisionRectIds:T,len:I})}g.sort((x,w)=>x.len-w.len);for(let x of g)this.queue.push({path:x.path,collisionChipIds:x.collisionRectIds})}visualize(){let t=Vo(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});t.lines.push({points:this.baseElbow,strokeColor:"red",strokeDash:"4 4"});let[n,i]=this.pins;t.lines.push({points:[{x:n.x,y:n.y},{x:i.x,y:i.y}],strokeColor:"blue",strokeDash:"5 5"});for(let{path:o,collisionChipIds:r}of this.queue)t.lines.push({points:o,strokeColor:"teal",strokeDash:"2 2"});return this.solvedTracePath?t.lines.push({points:this.solvedTracePath,strokeColor:"green"}):this.queue.length>0&&t.lines.push({points:this.queue[0].path,strokeColor:"orange"}),t}},Fvt=class extends co{constructor(t){super();P(this,"inputProblem");P(this,"mspConnectionPairs");P(this,"dcConnMap");P(this,"globalConnMap");P(this,"queuedConnectionPairs");P(this,"chipMap");P(this,"currentConnectionPair",null);P(this,"solvedTracePaths",[]);P(this,"failedConnectionPairs",[]);this.inputProblem=t.inputProblem,this.mspConnectionPairs=t.mspConnectionPairs,this.dcConnMap=t.dcConnMap,this.globalConnMap=t.globalConnMap,this.chipMap=t.chipMap,this.queuedConnectionPairs=[...this.mspConnectionPairs]}getConstructorParams(){return{inputProblem:this.inputProblem,chipMap:this.chipMap,mspConnectionPairs:this.mspConnectionPairs,dcConnMap:this.dcConnMap,globalConnMap:this.globalConnMap}}_step(){if(this.activeSubSolver?.solved&&(this.solvedTracePaths.push({...this.currentConnectionPair,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 t=this.queuedConnectionPairs.shift();if(!t){this.solved=!0;return}this.currentConnectionPair=t;let{pins:n}=t;this.activeSubSolver=new mX({inputProblem:this.inputProblem,pins:n,chipMap:this.chipMap})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Vo(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let{mspPairId:n,tracePath:i}of this.solvedTracePaths)t.lines.push({points:i,strokeColor:"green"});for(let n of this.failedConnectionPairs)t.lines.push({points:[{x:n.pins[0].x,y:n.pins[0].y},{x:n.pins[1].x,y:n.pins[1].y}],strokeColor:"red",strokeDash:"4 2"});return t}},zvt=({pts:e,segmentIndex:t,offset:n,JOG_SIZE:i,EPS:o=1e-6})=>{if(t!==0&&t!==e.length-2)return;let r=e[t],s=e[t+1],a=Math.abs(r.x-s.x)<o,c=Math.abs(r.y-s.y)<o;if(!a&&!c)return;let l=a?s.y>r.y?1:-1:s.x>r.x?1:-1;if(t===0)if(a){let u=r.y+l*i;e.splice(1,1,{x:r.x,y:u},{x:r.x+n,y:u},{x:s.x+n,y:s.y})}else{let u=r.x+l*i;e.splice(1,1,{x:u,y:r.y},{x:u,y:r.y+n},{x:s.x,y:s.y+n})}else if(a){let u=s.y-l*i;e.splice(t,1,{x:r.x+n,y:r.y},{x:s.x+n,y:u},{x:s.x,y:u})}else{let u=s.x-l*i;e.splice(t,1,{x:r.x,y:r.y+n},{x:u,y:s.y+n},{x:u,y:s.y})}},Dvt=class extends co{constructor(t){super();P(this,"overlappingTraceSegments");P(this,"traceNetIslands");P(this,"SHIFT_DISTANCE",.1);P(this,"correctedTraceMap",{});this.overlappingTraceSegments=t.overlappingTraceSegments,this.traceNetIslands=t.traceNetIslands;for(let{connNetId:n,pathsWithOverlap:i}of this.overlappingTraceSegments)for(let{solvedTracePathIndex:o,traceSegmentIndex:r}of i){let s=this.traceNetIslands[n][o].mspPairId;this.correctedTraceMap[s]=this.traceNetIslands[n][o]}}_step(){let n=this.overlappingTraceSegments.map((r,s)=>{let a=Math.floor(s/2)+1;return(s%2===0?-a:a)*this.SHIFT_DISTANCE}),i=(r,s)=>Math.abs(r-s)<1e-6,o=(r,s)=>!!r&&!!s&&i(r.x,s.x)&&i(r.y,s.y);this.overlappingTraceSegments.forEach((r,s)=>{let a=n[s],c=new Map;for(let l of r.pathsWithOverlap)c.has(l.solvedTracePathIndex)||c.set(l.solvedTracePathIndex,new Set),c.get(l.solvedTracePathIndex).add(l.traceSegmentIndex);for(let[l,u]of c){let h=this.traceNetIslands[r.connNetId][l],d=this.correctedTraceMap[h.mspPairId]??h,_=d.tracePath.map(S=>({...S})),y=Array.from(u).sort((S,T)=>S-T),g=Array.from(u).sort((S,T)=>S-T).reverse(),x=this.SHIFT_DISTANCE;for(let S of g)if(!(S<0||S>=_.length-1))if(S===0||S===_.length-2)zvt({pts:_,segmentIndex:S,offset:a,JOG_SIZE:x,EPS:1e-6});else{let T=_[S],I=_[S+1],E=Math.abs(T.x-I.x)<1e-6,M=Math.abs(T.y-I.y)<1e-6;if(!E&&!M)continue;E?(T.x+=a,I.x+=a):(T.y+=a,I.y+=a)}let w=[];for(let S of _)(w.length===0||!o(w[w.length-1],S))&&w.push(S);this.correctedTraceMap[h.mspPairId]={...d,tracePath:w}}}),this.solved=!0}visualize(){let t={lines:[],points:[],rects:[],circles:[]};for(let n of this.overlappingTraceSegments)for(let{solvedTracePathIndex:i,traceSegmentIndex:o}of n.pathsWithOverlap){let r=this.traceNetIslands[n.connNetId][i],s=r.tracePath[o],a=r.tracePath[o+1];t.lines.push({points:[s,a],strokeColor:"red"})}for(let n of Object.values(this.correctedTraceMap))t.lines.push({points:n.tracePath,strokeColor:"blue",strokeDash:"4 2"});return t}},$vt=class extends co{constructor(t){super();P(this,"inputProblem");P(this,"inputTracePaths");P(this,"globalConnMap");P(this,"traceNetIslands",{});P(this,"correctedTraceMap",{});P(this,"cleanupPhase",null);this.inputProblem=t.inputProblem,this.inputTracePaths=t.inputTracePaths,this.globalConnMap=t.globalConnMap;for(let n of this.inputTracePaths){let{mspPairId:i}=n;this.correctedTraceMap[i]=n}this.traceNetIslands=this.computeTraceNetIslands()}getConstructorParams(){return{inputProblem:this.inputProblem,inputTracePaths:this.inputTracePaths,globalConnMap:this.globalConnMap}}computeTraceNetIslands(){let t={};for(let n of this.inputTracePaths){let i=this.correctedTraceMap[n.mspPairId]??n,o=i.globalConnNetId;t[o]||(t[o]=[]),t[o].push(i)}return t}findNextOverlapIssue(){let n=Object.keys(this.traceNetIslands);for(let i=0;i<n.length;i++)for(let o=i+1;o<n.length;o++){let r=n[i],s=n[o],a=this.traceNetIslands[r]||[],c=this.traceNetIslands[s]||[],l=[],u=[],h=new Set,d=new Set,_=(y,g,x,w)=>{let S=Math.min(y,g),T=Math.max(y,g),I=Math.min(x,w),E=Math.max(x,w);return Math.min(T,E)-Math.max(S,I)>.002};for(let y=0;y<a.length;y++){let x=a[y].tracePath;for(let w=0;w<x.length-1;w++){let S=x[w],T=x[w+1],I=Math.abs(S.x-T.x)<.002,E=Math.abs(S.y-T.y)<.002;if(!(!I&&!E))for(let M=0;M<c.length;M++){let N=c[M].tracePath;for(let A=0;A<N.length-1;A++){let R=N[A],$=N[A+1],j=Math.abs(R.x-$.x)<.002,H=Math.abs(R.y-$.y)<.002;if(!(!j&&!H)){if(I&&j){if(Math.abs(S.x-R.x)<.002&&_(S.y,T.y,R.y,$.y)){let X=`${y}:${w}`,G=`${M}:${A}`;h.has(X)||(l.push({solvedTracePathIndex:y,traceSegmentIndex:w}),h.add(X)),d.has(G)||(u.push({solvedTracePathIndex:M,traceSegmentIndex:A}),d.add(G))}}else if(E&&H&&Math.abs(S.y-R.y)<.002&&_(S.x,T.x,R.x,$.x)){let X=`${y}:${w}`,G=`${M}:${A}`;h.has(X)||(l.push({solvedTracePathIndex:y,traceSegmentIndex:w}),h.add(X)),d.has(G)||(u.push({solvedTracePathIndex:M,traceSegmentIndex:A}),d.add(G))}}}}}}if(l.length>0&&u.length>0)return{overlappingTraceSegments:[{connNetId:r,pathsWithOverlap:l},{connNetId:s,pathsWithOverlap:u}]}}return null}findNextDiagonalSegment(){for(let n in this.correctedTraceMap){let i=this.correctedTraceMap[n].tracePath;for(let o=0;o<i.length-1;o++){let r=i[o],s=i[o+1],a=Math.abs(r.y-s.y)<.002,c=Math.abs(r.x-s.x)<.002;if(!a&&!c)return{mspPairId:n,tracePath:i,i:o,p1:r,p2:s}}}return null}findAndFixNextDiagonalSegment(){let t=this.findNextDiagonalSegment();if(!t)return!1;let{mspPairId:n,tracePath:i,i:o,p1:r,p2:s}=t,a=.002,c=o>0?i[o-1]:null,l=o+2<i.length?i[o+2]:null,u=c?Math.abs(c.x-r.x)<a:!1,h=c?Math.abs(c.y-r.y)<a:!1,d=l?Math.abs(s.x-l.x)<a:!1,_=l?Math.abs(s.y-l.y)<a:!1,y={x:r.x,y:s.y},g={x:s.x,y:r.y},x=0;u&&x++,_&&x++;let w=0;h&&w++,d&&w++;let S=x<w?y:g;return i.splice(o+1,0,S),!0}_step(){if(this.activeSubSolver?.solved){for(let[i,o]of Object.entries(this.activeSubSolver.correctedTraceMap))this.correctedTraceMap[i]=o;this.activeSubSolver=null,this.traceNetIslands=this.computeTraceNetIslands()}if(this.activeSubSolver){this.activeSubSolver.step();return}let t=this.findNextOverlapIssue();if(t===null){if(this.cleanupPhase===null&&(this.cleanupPhase="diagonals"),this.cleanupPhase==="diagonals"){this.findAndFixNextDiagonalSegment()||(this.cleanupPhase="done",this.solved=!0);return}this.solved=!0;return}let{overlappingTraceSegments:n}=t;this.activeSubSolver=new Dvt({overlappingTraceSegments:n,traceNetIslands:this.traceNetIslands})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Vo(this.inputProblem);t.circles=t.circles||[];for(let n of Object.values(this.correctedTraceMap))t.lines.push({points:n.tracePath,strokeColor:"purple"});if(this.cleanupPhase==="diagonals"){let n=this.findNextDiagonalSegment();n&&t.lines.push({points:[n.p1,n.p2],strokeColor:"red",strokeWidth:.05})}return t}},jvt=class{constructor(e){P(this,"chips");P(this,"spatialIndex");P(this,"spatialIndexIdToChip");this.chips=e.map(t=>({...t,bounds:GM(t),spatialIndexId:null})),this.spatialIndexIdToChip=new Map,this.spatialIndex=new hm(e.length);for(let t of this.chips)t.spatialIndexId=this.spatialIndex.add(t.bounds.minX,t.bounds.minY,t.bounds.maxX,t.bounds.maxY),this.spatialIndexIdToChip.set(t.spatialIndexId,t);this.spatialIndex.finish()}getChipsInBounds(e){return this.spatialIndex.search(e.minX,e.minY,e.maxX,e.maxY).map(n=>this.spatialIndexIdToChip.get(n))}doesOrthogonalLineIntersectChip(e,t={}){let n=t.excludeChipIds??[],[i,o]=e,{x:r,y:s}=i,{x:a,y:c}=o;return this.getChipsInBounds({minX:Math.min(r,a),minY:Math.min(s,c),maxX:Math.max(r,a),maxY:Math.max(s,c)}).filter(u=>!n.includes(u.chipId)).length>0}},Bvt=.45,sX=.2;function XM(e){let{orientation:t,netLabelWidth:n}=e,i=typeof n=="number"?n:Bvt;return t==="y+"||t==="y-"?{width:sX,height:i}:{width:i,height:sX}}function VM(e,t,n,i){switch(t){case"x+":return{x:e.x+n/2,y:e.y};case"x-":return{x:e.x-n/2,y:e.y};case"y+":return{x:e.x,y:e.y+i/2};case"y-":return{x:e.x,y:e.y-i/2}}}function lu(e,t,n){return{minX:e.x-t/2,minY:e.y-n/2,maxX:e.x+t/2,maxY:e.y+n/2}}function _X(e,t,n,i=1e-9){let o=Math.abs(e.x-t.x)<i,r=Math.abs(e.y-t.y)<i;if(!o&&!r)return!1;if(o){let s=e.x;if(s<n.minX-i||s>n.maxX+i)return!1;let a=Math.min(e.y,t.y),c=Math.max(e.y,t.y);return Math.min(c,n.maxY)-Math.max(a,n.minY)>i}else{let s=e.y;if(s<n.minY-i||s>n.maxY+i)return!1;let a=Math.min(e.x,t.x),c=Math.max(e.x,t.x);return Math.min(c,n.maxX)-Math.max(a,n.minX)>i}}function yX(e,t,n,i){for(let[o,r]of Object.entries(t)){let s=r.tracePath;for(let a=0;a<s.length-1;a++)if(!(o===n&&a===i)&&_X(s[a],s[a+1],e))return{hasIntersection:!0,mspPairId:o,segIndex:a}}return{hasIntersection:!1}}function aX(e){let t=0,n=e.tracePath;for(let i=0;i<n.length-1;i++)t+=Math.abs(n[i+1].x-n[i].x)+Math.abs(n[i+1].y-n[i].y);return t}function gX(e){let{inputProblem:t,inputTraceMap:n,globalConnNetId:i,fallbackTrace:o,mspConnectionPairIds:r}=e,s=Object.fromEntries(t.chips.map(d=>[d.chipId,d])),a=Object.values(n).filter(d=>d.globalConnNetId===i);if(r&&r.length>0){let d=new Set(r);a=a.filter(_=>_.mspConnectionPairIds.some(y=>d.has(y)))}let c=new Set;for(let d of a)c.add(d.pins[0].chipId),c.add(d.pins[1].chipId);let l=null,u=-1;for(let d of c){let y=s[d]?.pins?.length??0;y>u&&(u=y,l=d)}let h=l==null?[]:a.filter(d=>d.pins[0].chipId===l||d.pins[1].chipId===l);return h.length>0?h.reduce((d,_)=>aX(d)>=aX(_)?d:_):o}function Yvt(e,t){return[{x:e.x,y:e.y},{x:(e.x+t.x)/2,y:(e.y+t.y)/2},{x:t.x,y:t.y}]}function Xvt(e){let{inputProblem:t,inputTraceMap:n,chipObstacleSpatialIndex:i,overlappingSameNetTraceGroup:o,availableOrientations:r,netLabelWidth:s}=e,a=o.portOnlyPinId;if(!a)return{placement:null,testedCandidates:[],error:"No portOnlyPinId provided"};let c=null,l=null;for(let M of t.chips){let k=M.pins.find(N=>N.pinId===a);if(k){c={x:k.x,y:k.y},l=k._facingDirection||dm(k,M);break}}if(!c||!l)return{placement:null,testedCandidates:[],error:`Port-only pin not found: ${a}`};let u=r.length>0?r:["x+","x-","y+","y-"],h={x:c.x,y:c.y},d=M=>M==="x+"?{x:1,y:0}:M==="x-"?{x:-1,y:0}:M==="y+"?{x:0,y:1}:{x:0,y:-1},_=[];for(let M of u){let{width:k,height:N}=XM({orientation:M,netLabelWidth:s}),A=VM(h,M,k,N),R=d(M),$=.001,j={x:A.x+R.x*$,y:A.y+R.y*$},H=lu(j,k,N);if(i.getChipsInBounds(H).length>0){_.push({center:j,width:k,height:N,bounds:H,anchor:h,orientation:M,status:"chip-collision",hostSegIndex:-1});continue}if(yX(H,n,"",-1).hasIntersection){_.push({center:j,width:k,height:N,bounds:H,anchor:h,orientation:M,status:"trace-collision",hostSegIndex:-1});continue}return _.push({center:j,width:k,height:N,bounds:H,anchor:h,orientation:M,status:"ok",hostSegIndex:-1}),{placement:{globalConnNetId:o.globalConnNetId,dcConnNetId:void 0,netId:o.netId,mspConnectionPairIds:[],pinIds:[a],orientation:M,anchorPoint:h,width:k,height:N,center:j},testedCandidates:_}}let y=l,{width:g,height:x}=XM({orientation:y,netLabelWidth:s}),w=VM(h,y,g,x),S=d(y),T=.001,I={x:w.x+S.x*T,y:w.y+S.y*T};return{placement:{globalConnNetId:o.globalConnNetId,dcConnNetId:void 0,netId:o.netId,mspConnectionPairIds:[],pinIds:[a],orientation:y,anchorPoint:h,width:g,height:x,center:I},testedCandidates:_}}function Vvt(e){let t=Vo(e.inputProblem),n=e.overlappingSameNetTraceGroup.globalConnNetId,i=gX({inputProblem:e.inputProblem,inputTraceMap:e.inputTraceMap,globalConnNetId:n,fallbackTrace:e.overlappingSameNetTraceGroup.overlappingTraces}),o=fr(n,.9),r=fr(n,.5);for(let s of Object.values(e.inputTraceMap)){let a=i?s.mspPairId===i.mspPairId:!1;t.lines.push({points:s.tracePath})}for(let s of e.testedCandidates){let a=s.status==="ok"?"rgba(0, 180, 0, 0.25)":s.status==="chip-collision"?"rgba(220, 0, 0, 0.25)":s.status==="trace-collision"?"rgba(220, 140, 0, 0.25)":"rgba(120, 120, 120, 0.15)",c=s.status==="ok"?"green":s.status==="chip-collision"?"red":s.status==="trace-collision"?"orange":"gray";t.rects.push({center:{x:(s.bounds.minX+s.bounds.maxX)/2,y:(s.bounds.minY+s.bounds.maxY)/2},width:s.width,height:s.height,fill:a,strokeColor:c}),t.points.push({x:s.anchor.x,y:s.anchor.y,color:c})}if(e.netLabelPlacement){let s=e.netLabelPlacement;t.rects.push({center:s.center,width:s.width,height:s.height,fill:"rgba(0, 128, 255, 0.35)",strokeColor:"blue"}),t.points.push({x:s.anchorPoint.x,y:s.anchorPoint.y,color:"blue"})}return t}var cX=class extends co{constructor(t){super();P(this,"inputProblem");P(this,"inputTraceMap");P(this,"overlappingSameNetTraceGroup");P(this,"availableOrientations");P(this,"chipObstacleSpatialIndex");P(this,"netLabelWidth");P(this,"netLabelPlacement",null);P(this,"testedCandidates",[]);this.inputProblem=t.inputProblem,this.inputTraceMap=t.inputTraceMap,this.overlappingSameNetTraceGroup=t.overlappingSameNetTraceGroup,this.availableOrientations=t.availableOrientations,this.netLabelWidth=t.netLabelWidth,this.chipObstacleSpatialIndex=t.inputProblem._chipObstacleSpatialIndex??new jvt(t.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 d=Xvt({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,chipObstacleSpatialIndex:this.chipObstacleSpatialIndex,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth});if(this.testedCandidates.push(...d.testedCandidates),d.placement){this.netLabelPlacement=d.placement,this.solved=!0;return}this.failed=!0,this.error=d.error??"Could not place net label at port without collisions";return}let t=this.overlappingSameNetTraceGroup.globalConnNetId,n=gX({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,globalConnNetId:t,fallbackTrace:this.overlappingSameNetTraceGroup.overlappingTraces,mspConnectionPairIds:this.overlappingSameNetTraceGroup.mspConnectionPairIds});if(!n){this.failed=!0,this.error="No host trace found for net label placement";return}let i=new Set(this.overlappingSameNetTraceGroup.mspConnectionPairIds??[]),o=Object.values(this.inputTraceMap).filter(d=>d.globalConnNetId===t&&(i.size===0||d.mspConnectionPairIds.some(_=>i.has(_)))),r=this.availableOrientations.length===1?[n,...o.filter(d=>d.mspPairId!==n.mspPairId)]:[n],s=this.availableOrientations.length>0?this.availableOrientations:["x+","x-","y+","y-"],a=this.availableOrientations.length===1,c=(d,_)=>{switch(d){case"y+":return _.y;case"y-":return-_.y;case"x+":return _.x;case"x-":return-_.x}},l=null,u=-1/0,h=1e-6;for(let d of r){let _=d.tracePath.slice();for(let y=0;y<_.length-1;y++){let g=_[y],x=_[y+1],w=Math.abs(g.y-x.y)<h,S=Math.abs(g.x-x.x)<h;if(!w&&!S)continue;let T=w?["y+","y-"]:["x+","x-"],I=s.filter(M=>T.includes(M));if(I.length===0)continue;let E=Yvt(g,x);for(let M of E)for(let k of I){let{width:N,height:A}=XM({orientation:k,netLabelWidth:this.netLabelWidth}),R=VM(M,k,N,A),$=k==="x+"?{x:1,y:0}:k==="x-"?{x:-1,y:0}:k==="y+"?{x:0,y:1}:{x:0,y:-1},j=1e-4,H={x:R.x+$.x*j,y:R.y+$.y*j},X=lu(H,N,A);if(this.chipObstacleSpatialIndex.getChipsInBounds(X).length>0){this.testedCandidates.push({center:H,width:N,height:A,bounds:X,anchor:M,orientation:k,status:"chip-collision",hostSegIndex:y});continue}if(yX(X,this.inputTraceMap,d.mspPairId,y).hasIntersection){this.testedCandidates.push({center:H,width:N,height:A,bounds:X,anchor:M,orientation:k,status:"trace-collision",hostSegIndex:y});continue}if(this.testedCandidates.push({center:H,width:N,height:A,bounds:X,anchor:M,orientation:k,status:"ok",hostSegIndex:y}),a){let Q=c(k,M);Q>u+1e-9&&(u=Q,l={anchor:M,orientation:k,width:N,height:A,center:R,hostSegIndex:y,dcConnNetId:d.dcConnNetId,mspPairId:d.mspPairId,pinIds:[d.pins[0].pinId,d.pins[1].pinId]});continue}this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:d.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[d.mspPairId],pinIds:[d.pins[0].pinId,d.pins[1].pinId],orientation:k,anchorPoint:M,width:N,height:A,center:R},this.solved=!0;return}}}if(a&&l){this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:l.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[l.mspPairId],pinIds:l.pinIds,orientation:l.orientation,anchorPoint:l.anchor,width:l.width,height:l.height,center:l.center},this.solved=!0;return}this.failed=!0,this.error="Could not place net label without collisions"}visualize(){return Vvt(this)}},lX=class extends co{constructor(t){super();P(this,"inputProblem");P(this,"inputTraceMap");P(this,"overlappingSameNetTraceGroups");P(this,"queuedOverlappingSameNetTraceGroups");P(this,"netLabelPlacements",[]);P(this,"currentGroup",null);P(this,"triedAnyOrientationFallbackForCurrentGroup",!1);this.inputProblem=t.inputProblem,this.inputTraceMap=t.inputTraceMap,this.overlappingSameNetTraceGroups=this.computeOverlappingSameNetTraceGroups(),this.queuedOverlappingSameNetTraceGroups=[...this.overlappingSameNetTraceGroups]}computeOverlappingSameNetTraceGroups(){let t={};for(let c of Object.values(this.inputTraceMap)){let l=c.globalConnNetId;t[l]||(t[l]=[]),t[l].push(c)}let{netConnMap:n}=HM(this.inputProblem),i=new Map;for(let c of this.inputProblem.chips)for(let l of c.pins)i.set(l.pinId,l);let o={};for(let c of this.inputProblem.directConnections)if(c.netId){let[l,u]=c.pinIds;o[l]=c.netId,o[u]=c.netId}for(let c of this.inputProblem.netConnections)for(let l of c.pinIds)o[l]=c.netId;let r=[],s=this.inputProblem.chips.flatMap(c=>c.pins.map(l=>l.pinId)),a=new Set;for(let c of s){let l=n.getNetConnectedToId(c);l&&a.add(l)}for(let c of a){let u=n.getIdsConnectedToNet(c).filter(_=>i.has(_)),h={};for(let _ of u)h[_]=new Set;for(let _ of t[c]??[]){let y=_.pins[0].pinId,g=_.pins[1].pinId;h[y]&&h[g]&&(h[y].add(g),h[g].add(y))}let d=new Set;for(let _ of u){if(d.has(_))continue;let y=[_],g=new Set;for(d.add(_);y.length>0;){let w=y.pop();g.add(w);for(let S of h[w]??[])d.has(S)||(d.add(S),y.push(S))}let x=(t[c]??[]).filter(w=>g.has(w.pins[0].pinId)&&g.has(w.pins[1].pinId));if(x.length>0){let w=k=>{let N=0,A=k.tracePath;for(let R=0;R<A.length-1;R++)N+=Math.abs(A[R+1].x-A[R].x)+Math.abs(A[R+1].y-A[R].y);return N},S=x[0],T=w(S);for(let k=1;k<x.length;k++){let N=w(x[k]);N>T&&(S=x[k],T=N)}let I=x.find(k=>k.userNetId!=null)?.userNetId;if(!I){for(let k of g)if(o[k]){I=o[k];break}}let E=Array.from(new Set(x.flatMap(k=>k.mspConnectionPairIds??[k.mspPairId]))),M={globalConnNetId:c,netId:I,overlappingTraces:S,mspConnectionPairIds:E};r.push(M)}else for(let w of g){let S=o[w];S&&r.push({globalConnNetId:c,netId:S,portOnlyPinId:w})}}}return r}_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 o=["x+","x-","y+","y-"],r=this.activeSubSolver.availableOrientations,s=r.length===4&&o.every(a=>r.includes(a));if(!this.triedAnyOrientationFallbackForCurrentGroup&&!s&&this.currentGroup){this.triedAnyOrientationFallbackForCurrentGroup=!0;let a=this.currentGroup.netId?this.inputProblem.netConnections.find(c=>c.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new cX({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.currentGroup,availableOrientations:o,netLabelWidth:a});return}this.failed=!0,this.error=this.activeSubSolver.error;return}if(this.activeSubSolver){this.activeSubSolver.step();return}let t=this.queuedOverlappingSameNetTraceGroups.shift();if(!t){this.solved=!0;return}let n=t.netId??t.globalConnNetId;this.currentGroup=t,this.triedAnyOrientationFallbackForCurrentGroup=!1;let i=this.currentGroup.netId?this.inputProblem.netConnections.find(o=>o.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new cX({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:t,availableOrientations:this.inputProblem.availableNetLabelOrientations[n]??["x+","x-","y+","y-"],netLabelWidth:i})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Vo(this.inputProblem);for(let n of Object.values(this.inputTraceMap))t.lines.push({points:n.tracePath,strokeColor:"purple"});for(let n of this.netLabelPlacements)t.rects.push({center:n.center,width:n.width,height:n.height,fill:fr(n.globalConnNetId,.35),strokeColor:fr(n.globalConnNetId,.9)}),t.points.push({x:n.anchorPoint.x,y:n.anchorPoint.y,color:fr(n.globalConnNetId,.9)});return t}},Hvt=class extends co{constructor(t){super();P(this,"input");P(this,"output");P(this,"inputProblem");P(this,"traces");this.input=t,this.inputProblem=t.inputProblem,this.traces=t.traces,this.output={netLabelPlacements:t.netLabelPlacements,mergedLabelNetIdMap:{}}}_step(){let t=this.input.netLabelPlacements,n={};if(!t||t.length===0){this.output={netLabelPlacements:[],mergedLabelNetIdMap:{}},this.solved=!0;return}let i={};for(let r of t){if(r.pinIds.length===0)continue;let s=r.pinIds[0].split(".")[0];if(!s)continue;let a=`${s}-${r.orientation}`;a in i||(i[a]=[]),i[a].push(r)}let o=[];for(let[r,s]of Object.entries(i)){if(s.length<=1){o.push(...s);continue}let a=1/0,c=1/0,l=-1/0,u=-1/0;for(let x of s){let w=lu(x.center,x.width,x.height);a=Math.min(a,w.minX),c=Math.min(c,w.minY),l=Math.max(l,w.maxX),u=Math.max(u,w.maxY)}let h=l-a,d=u-c,_=s[0],y=`merged-group-${r}`,g=new Set(s.map(x=>x.globalConnNetId));n[y]=g,o.push({..._,globalConnNetId:y,width:h,height:d,center:{x:a+h/2,y:c+d/2},pinIds:[...new Set(s.flatMap(x=>x.pinIds))],mspConnectionPairIds:[...new Set(s.flatMap(x=>x.mspConnectionPairIds))]})}this.output={netLabelPlacements:o,mergedLabelNetIdMap:n},this.solved=!0}getOutput(){return this.output}visualize(){let t=Vo(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});t.rects||(t.rects=[]),t.lines||(t.lines=[]),t.points||(t.points=[]),t.texts||(t.texts=[]);let n=new Map;for(let i of this.input.netLabelPlacements)n.set(i.globalConnNetId,i);for(let i of this.traces){let o={points:i.tracePath.map(r=>({x:r.x,y:r.y})),strokeColor:"blue"};t.lines.push(o)}for(let i of this.output.netLabelPlacements){let o=i.globalConnNetId.startsWith("merged-group-"),r=fr(i.globalConnNetId);if(o){t.rects.push({center:i.center,width:i.width,height:i.height,fill:r.replace(/, 1\)/,", 0.2)"),stroke:r,label:i.globalConnNetId});let s=this.output.mergedLabelNetIdMap[i.globalConnNetId];if(s)for(let a of s){let c=n.get(a);if(c){let l=lu(c.center,c.width,c.height),u={x:l.minX,y:l.minY},h={x:l.maxX,y:l.minY},d={x:l.maxX,y:l.maxY},_={x:l.minX,y:l.maxY};t.lines.push({points:[u,h,d,_,u],strokeColor:r,strokeDash:"4 4"}),t.lines.push({points:[c.center,i.center],strokeColor:r,strokeDash:"2 2"})}}}else t.rects.push({center:i.center,width:i.width,height:i.height,stroke:r,label:i.globalConnNetId})}return t}},Gvt=(e,t)=>{let n=[];for(let i of e)for(let o of t){let r=lu(o.center,o.width,o.height);for(let s=0;s<i.tracePath.length-1;s++){let a=i.tracePath[s],c=i.tracePath[s+1];if(_X(a,c,r)){if(i.globalConnNetId===o.globalConnNetId)break;n.push({trace:i,label:o});break}}}return n},Uvt=(e,t)=>{let n=r=>r.x>t.minX&&r.x<t.maxX&&r.y>t.minY&&r.y<t.maxY,i=-1,o=-1;for(let r=0;r<e.length;r++)n(e[r])&&(i===-1&&(i=r),o=r);return{firstInsideIndex:i,lastInsideIndex:o}},qvt=({initialTrace:e,firstInsideIndex:t,lastInsideIndex:n,labelBounds:i,paddingBuffer:o,detourCount:r})=>{if(t<=0||n>=e.tracePath.length-1)return[];let s=e.tracePath[t-1],a=e.tracePath[n+1],c=e.tracePath.slice(0,t),l=e.tracePath.slice(n+1),u=[];s.x!==a.x&&s.y!==a.y?(u.push([{x:a.x,y:s.y}]),u.push([{x:s.x,y:a.y}])):(s.x===a.x||s.y===a.y)&&u.push([]);let h=o+r*o,d=i.minX-h,_=i.maxX+h,y=i.maxY+h,g=i.minY-h;return(s.x<=i.minX||a.x<=i.minX)&&s.x<i.maxX&&a.x<i.maxX&&u.push([{x:d,y:s.y},{x:d,y:a.y}]),(s.x>=i.maxX||a.x>=i.maxX)&&s.x>i.minX&&a.x>i.minX&&u.push([{x:_,y:s.y},{x:_,y:a.y}]),(s.y>=i.maxY||a.y>=i.maxY)&&s.y>i.minY&&a.y>i.minY&&u.push([{x:s.x,y},{x:a.x,y}]),(s.y<=i.minY||a.y<=i.minY)&&s.y<i.maxY&&a.y<i.maxY&&u.push([{x:s.x,y:g},{x:a.x,y:g}]),u.map(x=>[...c,...x,...l])},Wvt=({initialTrace:e,label:t,labelBounds:n,paddingBuffer:i,detourCount:o})=>{let r=-1;for(let h=0;h<e.tracePath.length-1;h++)if(mm(e.tracePath[h],e.tracePath[h+1],n)){r=h;break}if(r===-1)return[];let s=e.tracePath[r],a=e.tracePath[r+1];if(!s||!a)return[];let c=[],l=lu(t.center,t.width,t.height),u=i+o*i;if(ta(s,a)){let h=[l.maxX+u,l.minX-u];for(let d of h)c.push(a.y>s.y?[{x:s.x,y:l.minY-u},{x:d,y:l.minY-u},{x:d,y:l.maxY+u},{x:a.x,y:l.maxY+u}]:[{x:s.x,y:l.maxY+u},{x:d,y:l.maxY+u},{x:d,y:l.minY-u},{x:a.x,y:l.minY-u}])}else{let h=[l.maxY+u,l.minY-u];for(let d of h)c.push(a.x>s.x?[{x:l.minX-u,y:s.y},{x:l.minX-u,y:d},{x:l.maxX+u,y:d},{x:l.maxX+u,y:a.y}]:[{x:l.maxX+u,y:s.y},{x:l.maxX+u,y:d},{x:l.minX-u,y:d},{x:l.minX-u,y:a.y}])}return c.map(h=>[...e.tracePath.slice(0,r+1),...h,...e.tracePath.slice(r+1)])},fm=e=>{if(e.length<3)return e;let t=[e[0]];for(let i=1;i<e.length-1;i++){let o=t[t.length-1],r=e[i],s=e[i+1];ta(o,r)&&ta(r,s)||bc(o,r)&&bc(r,s)||t.push(r)}if(t.push(e[e.length-1]),t.length<3)return t;let n=[t[0]];for(let i=1;i<t.length-1;i++){let o=n[n.length-1],r=t[i],s=t[i+1];ta(o,r)&&ta(r,s)||bc(o,r)&&bc(r,s)||n.push(r)}return n.push(t[t.length-1]),n},Zvt=({trace:e,label:t,paddingBuffer:n,detourCount:i})=>{let o={...e,tracePath:fm(e.tracePath)};if(e.globalConnNetId===t.globalConnNetId)return[o.tracePath];let r=n,s=lu(t.center,t.width,t.height),a={minX:s.minX-r,minY:s.minY-r,maxX:s.maxX+r,maxY:s.maxY+r,chipId:`netlabel-${t.netId}`},c=Wvt({initialTrace:o,label:t,labelBounds:a,paddingBuffer:n,detourCount:i}),{firstInsideIndex:l,lastInsideIndex:u}=Uvt(o.tracePath,a),h=qvt({initialTrace:o,firstInsideIndex:l,lastInsideIndex:u,labelBounds:a,paddingBuffer:n,detourCount:i});return[...c,...h]},Kvt=class extends co{constructor(t){super();P(this,"queuedCandidatePaths");P(this,"solvedTracePath",null);P(this,"initialTrace");P(this,"problem");P(this,"obstacles");P(this,"label");this.initialTrace=t.trace,this.problem=t.problem,this.label=t.label;let n=Zvt({...t}),i=o=>{let r=0;for(let s=0;s<o.length-1;s++){let a=o[s+1].x-o[s].x,c=o[s+1].y-o[s].y;r+=Math.sqrt(a*a+c*c)}return r};this.queuedCandidatePaths=n.sort((o,r)=>i(o)-i(r)),this.obstacles=yx(this.problem)}_step(){if(this.queuedCandidatePaths.length===0){this.failed=!0;return}let t=this.queuedCandidatePaths.shift(),n=fm(t);kvt(n,this.obstacles)||(this.solvedTracePath=n,this.solved=!0)}visualize(){let t=Vo(this.problem,{chipAlpha:.1,connectionAlpha:.1});return t.lines||(t.lines=[]),t.rects||(t.rects=[]),t.lines.push({points:this.initialTrace.tracePath,strokeColor:"red",strokeDash:"4 4"}),t.rects.push({center:this.label.center,width:this.label.width,height:this.label.height,fill:"rgba(255, 0, 0, 0.2)"}),this.queuedCandidatePaths.length>0&&t.lines.push({points:this.queuedCandidatePaths[0],strokeColor:"orange"}),this.solvedTracePath&&t.lines.push({points:this.solvedTracePath,strokeColor:"green"}),t}},Jvt=class extends co{constructor(t){super();P(this,"inputProblem");P(this,"netLabelPlacements");P(this,"mergedLabelNetIdMap");P(this,"allTraces");P(this,"modifiedTraces",[]);P(this,"detourCountByLabel",{});P(this,"PADDING_BUFFER",.1);P(this,"activeSubSolver",null);P(this,"overlapQueue",[]);P(this,"recentlyFailed",new Set);this.inputProblem=t.inputProblem,this.netLabelPlacements=t.netLabelPlacements,this.mergedLabelNetIdMap=t.mergedLabelNetIdMap,this.allTraces=[...t.traces]}_step(){if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){let o=this.activeSubSolver.solvedTracePath;if(o){let r=this.allTraces.findIndex(s=>s.mspPairId===this.activeSubSolver.initialTrace.mspPairId);r!==-1&&(this.allTraces[r].tracePath=o,this.modifiedTraces.push(this.allTraces[r]))}this.activeSubSolver=null,this.recentlyFailed.clear()}else if(this.activeSubSolver.failed){let o=`${this.activeSubSolver.initialTrace.mspPairId}-${this.activeSubSolver.label.globalConnNetId}`;this.recentlyFailed.add(o),this.activeSubSolver=null}return}let t=Gvt(this.allTraces,this.netLabelPlacements).filter(o=>{let r=this.mergedLabelNetIdMap[o.label.globalConnNetId];return r?!r.has(o.trace.globalConnNetId):o.trace.globalConnNetId!==o.label.globalConnNetId});if(t.length===0){this.solved=!0;return}let n=t.filter(o=>{let r=`${o.trace.mspPairId}-${o.label.globalConnNetId}`;return!this.recentlyFailed.has(r)});if(n.length===0){this.solved=!0;return}this.overlapQueue=n;let i=this.overlapQueue.shift();if(i){let o=this.allTraces.find(r=>r.mspPairId===i.trace.mspPairId);if(o){let r=i.label.globalConnNetId,s=this.detourCountByLabel[r]||0;this.detourCountByLabel[r]=s+1,this.activeSubSolver=new Kvt({trace:o,label:i.label,problem:this.inputProblem,paddingBuffer:this.PADDING_BUFFER,detourCount:s})}}}getOutput(){return{allTraces:this.allTraces,modifiedTraces:this.modifiedTraces}}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Vo(this.inputProblem);t.lines||(t.lines=[]);for(let n of this.allTraces)t.lines.push({points:n.tracePath,strokeColor:"purple"});return t}},Qvt=class extends co{constructor(t){super();P(this,"inputProblem");P(this,"traces");P(this,"netLabelPlacements");P(this,"labelMergingSolver");P(this,"overlapAvoidanceSolver");P(this,"pipelineStepIndex",0);this.inputProblem=t.inputProblem,this.traces=t.traces,this.netLabelPlacements=t.netLabelPlacements}_step(){if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.activeSubSolver=null,this.pipelineStepIndex++):this.activeSubSolver.failed&&(this.failed=!0,this.activeSubSolver=null);return}switch(this.pipelineStepIndex){case 0:this.labelMergingSolver=new Hvt({netLabelPlacements:this.netLabelPlacements,inputProblem:this.inputProblem,traces:this.traces}),this.activeSubSolver=this.labelMergingSolver;break;case 1:this.overlapAvoidanceSolver=new Jvt({inputProblem:this.inputProblem,traces:this.traces,netLabelPlacements:this.labelMergingSolver.getOutput().netLabelPlacements,mergedLabelNetIdMap:this.labelMergingSolver.getOutput().mergedLabelNetIdMap}),this.activeSubSolver=this.overlapAvoidanceSolver;break;default:this.solved=!0;break}}getOutput(){return{traces:this.overlapAvoidanceSolver?.getOutput().allTraces??this.traces,netLabelPlacements:this.labelMergingSolver?.getOutput().netLabelPlacements??this.netLabelPlacements}}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Vo(this.inputProblem);t.lines||(t.lines=[]),t.rects||(t.rects=[]);let n=this.getOutput();for(let i of n.traces)t.lines.push({points:i.tracePath,strokeColor:"purple"});for(let i of n.netLabelPlacements){let o=fr(i.globalConnNetId,.3);t.rects.push({center:i.center,width:i.width,height:i.height,fill:o,stroke:o.replace("0.3","1"),label:i.globalConnNetId})}return t}},tSt=e=>{for(let t of e.chips){let n=GM(t);for(let i of t.pins){if(!(i.x>n.minX&&i.x<n.maxX&&i.y>n.minY&&i.y<n.maxY))continue;let r=i.x-n.minX,s=n.maxX-i.x,a=i.y-n.minY,c=n.maxY-i.y,l=Math.min(r,s,a,c);l===r?i.x=n.minX:l===s?i.x=n.maxX:l===a?i.y=n.minY:i.y=n.maxY,i._facingDirection=void 0}}},eSt=e=>{for(let t of e.chips){let n=t.width/2,i=t.height/2,o=0,r=0;for(let c of t.pins){let l=Math.abs(c.x-t.center.x),u=Math.abs(c.y-t.center.y);l>o&&(o=l),u>r&&(r=u)}let s=Math.max(n,o),a=Math.max(i,r);if(s>n||a>i){t.width=s*2,t.height=a*2;for(let c of t.pins)c._facingDirection=void 0}}};function nSt(e,t){for(let n=0;n<e.length-1;n++){let i=e[n],o=e[n+1];for(let r of t)for(let s=0;s<r.tracePath.length-1;s++){let a=r.tracePath[s],c=r.tracePath[s+1];if(li(i,o,a,c))return!0}}return!1}var iSt=3,oSt=(e,t)=>Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2)),rSt=class extends co{constructor(t){super();P(this,"solvedLongDistanceTraces",[]);P(this,"queuedCandidatePairs",[]);P(this,"currentCandidatePair",null);P(this,"subSolver",null);P(this,"chipMap",{});P(this,"inputProblem");P(this,"netConnMap");P(this,"newlyConnectedPinIds",new Set);P(this,"allSolvedTraces",[]);this.params=t;let{inputProblem:n,primaryMspConnectionPairs:i,alreadySolvedTraces:o}=this.params;this.inputProblem=n,this.allSolvedTraces=[...o];let r=new Set;for(let u of i)r.add(u.pins[0].pinId),r.add(u.pins[1].pinId);let{netConnMap:s}=HM(n);this.netConnMap=s;let a=new Map;for(let u of n.chips){this.chipMap[u.chipId]=u;for(let h of u.pins)a.set(h.pinId,{...h,chipId:u.chipId})}let c=[],l=new Set;for(let u of Object.keys(s.netMap)){let h=s.getIdsConnectedToNet(u);if(h.length<2)continue;let d=h.filter(_=>!r.has(_));for(let _ of d){let y=a.get(_);if(!y)continue;let g=h.filter(x=>x!==_).flatMap(x=>{let w=a.get(x);return w?[{pin:w,distance:oSt(y,w)}]:[]}).sort((x,w)=>x.distance-w.distance).slice(0,iSt);for(let x of g){let w=[y,x.pin],S=w.map(T=>T.pinId).sort().join("--");l.has(S)||(c.push(w),l.add(S))}}}this.queuedCandidatePairs=c}getConstructorParams(){return this.params}_step(){if(this.subSolver?.solved){let t=this.subSolver.solvedTracePath;if(t&&this.currentCandidatePair&&!nSt(t,this.allSolvedTraces)){let[i,o]=this.currentCandidatePair,r=this.netConnMap.getNetConnectedToId(i.pinId),s=`${i.pinId}-${o.pinId}`,a={mspPairId:s,dcConnNetId:r,globalConnNetId:r,pins:[i,o],tracePath:t,mspConnectionPairIds:[s],pinIds:[i.pinId,o.pinId]};this.solvedLongDistanceTraces.push(a),this.allSolvedTraces.push(a),this.newlyConnectedPinIds.add(i.pinId),this.newlyConnectedPinIds.add(o.pinId)}this.subSolver=null,this.currentCandidatePair=null}else this.subSolver?.failed&&(this.subSolver=null,this.currentCandidatePair=null);if(this.subSolver){this.subSolver.step();return}for(;this.queuedCandidatePairs.length>0;){let t=this.queuedCandidatePairs.shift(),[n,i]=t;if(!(this.newlyConnectedPinIds.has(n.pinId)||this.newlyConnectedPinIds.has(i.pinId))){this.currentCandidatePair=t,this.subSolver=new mX({inputProblem:this.params.inputProblem,pins:this.currentCandidatePair,chipMap:this.chipMap});return}}this.solved=!0}visualize(){if(this.subSolver)return this.subSolver.visualize();let t=Vo(this.inputProblem);for(let n of this.solvedLongDistanceTraces)t.lines.push({points:n.tracePath,strokeColor:"purple"});for(let[n,i]of this.queuedCandidatePairs)t.lines.push({points:[n,i],strokeColor:"gray",strokeDash:"4 4"});return t}getOutput(){return this.solved?{newTraces:this.solvedLongDistanceTraces,allTracesMerged:[...this.params.alreadySolvedTraces,...this.solvedLongDistanceTraces]}:{newTraces:[],allTracesMerged:this.params.alreadySolvedTraces}}},$M=(e,t)=>{for(let n=0;n<e.length-1;n++){let i=e[n],o=e[n+1];for(let r of t){let s={center:{x:r.minX+(r.maxX-r.minX)/2,y:r.minY+(r.maxY-r.minY)/2},width:r.maxX-r.minX,height:r.maxY-r.minY};if(ib(i,o,s)<=0)return!0}}return!1},jM=e=>{let t=0;for(let n=1;n<e.length-1;n++){let i=e[n-1],o=e[n],r=e[n+1],s=i.x===o.x,a=o.x===r.x;s!==a&&t++}return t},uX=(e,t)=>{let n=[];return e.x===t.x||e.y===t.y?n.push([e,t]):(n.push([e,{x:t.x,y:e.y},t]),n.push([e,{x:e.x,y:t.y},t])),n},BM=(e,t)=>{for(let n=0;n<e.length-1;n++){let i=e[n],o=e[n+1];for(let r of t)if(mm(i,o,r))return!0}return!1},sSt=(e,t)=>{if(t>=e.length-3)return-1;let n=t,i=!0;for(let o=t;o<e.length-2&&o<t+10&&!(o+2>=e.length);o++){let r=e[o],s=e[o+1],a=e[o+2],c=r.x===s.x,l=s.x===a.x;if(c===l)break;let u=Math.sign(c?s.y-r.y:s.x-r.x);if(o>t){let h=e[o-1],d=h.x===r.x,_=Math.sign(d?r.y-h.y:r.x-h.x);if(c&&d&&u!==_||!c&&!d&&u!==_){i=!1;break}}n=o+2}return i&&n-t>=3?n:-1},Eh=(e,t,n)=>{if(n.length<2)return!1;let i=n[0],o=n[n.length-1];return e.x===i.x&&e.y===i.y&&t.x===n[1].x&&t.y===n[1].y||e.x===n[n.length-2].x&&e.y===n[n.length-2].y&&t.x===o.x&&t.y===o.y},aSt=({path:e,obstacles:t,labelBounds:n,originalPath:i})=>{if(e.length<=2)return e;let o=[...e],r=jM(o),s=!0;for(;s;){s=!1;for(let c=0;c<o.length-3;c++){let l=sSt(o,c);if(l>0){if(Eh(o[c],o[c+1],i)||Eh(o[l-1],o[l],i))continue;let u=o[c],h=o[l],d=uX(u,h);for(let _ of d){let y=[...o.slice(0,c+1),..._.slice(1,-1),...o.slice(l)],g=$M(_,t),x=BM(_,n);if(!g&&!x){let w=jM(y);o=y,r=w,s=!0;break}}if(s)break}}if(!s)for(let c=0;c<o.length-2;c++){let l=Math.min(o.length-c-2,o.length-2);for(let u=1;u<=l;u++){let h=c+u+1;if(h>=o.length||Eh(o[c],o[c+1],i)||Eh(o[h-1],o[h],i))continue;let d=o[c],_=o[h],y=uX(d,_);for(let g of y){let x=[...o.slice(0,c+1),...g.slice(1,-1),...o.slice(h)],w=g,S=$M(w,t),T=BM(w,n);if(!S&&!T){let I=jM(x);if(I<r||I===r&&x.length<o.length){o=x,r=I,s=!0;break}}}if(s)break}if(s)break}if(!s)for(let c=0;c<o.length-2;c++){let l=o[c],u=o[c+1],h=o[c+2];if(Eh(l,u,i)||Eh(u,h,i))continue;let d=l.x===u.x&&u.x===h.x,_=l.y===u.y&&u.y===h.y;if(d||_){let y=[...o.slice(0,c+1),...o.slice(c+2)],g=$M([l,h],t),x=BM([l,h],n);if(!g&&!x){o=y,s=!0;break}}}}return fm(o)},cSt=({targetMspConnectionPairId:e,traces:t,inputProblem:n,allLabelPlacements:i,mergedLabelNetIdMap:o,paddingBuffer:r})=>{let s=t.find(S=>S.mspPairId===e);if(!s)throw new Error(`Target trace ${e} not found`);let a=t.filter(S=>S.mspPairId!==e),c=.01,l=a.flatMap((S,T)=>S.tracePath.slice(0,-1).map((I,E)=>{let M=S.tracePath[E+1];return{chipId:`trace-obstacle-${T}-${E}`,minX:Math.min(I.x,M.x)-c/2,minY:Math.min(I.y,M.y)-c/2,maxX:Math.max(I.x,M.x)+c/2,maxY:Math.max(I.y,M.y)+c/2}})),u=yx(n),h=.01,_=[...u.map(S=>({...S,minX:S.minX-h,minY:S.minY-h,maxX:S.maxX+h,maxY:S.maxY+h})),...l],y=s.tracePath,x=i.filter(S=>{let T=o[S.globalConnNetId];return T?!T.has(s.globalConnNetId):S.globalConnNetId!==s.globalConnNetId}).map(S=>({minX:S.center.x-S.width/2-r,maxX:S.center.x+S.width/2+r,minY:S.center.y-S.height/2-r,maxY:S.center.y+S.height/2+r})),w=aSt({path:y,obstacles:_,labelBounds:x,originalPath:y});return{...s,tracePath:w}},lSt=({targetMspConnectionPairId:e,traces:t,inputProblem:n,allLabelPlacements:i,mergedLabelNetIdMap:o,paddingBuffer:r})=>{let s=t.find(S=>S.mspPairId===e);if(!s)throw new Error(`Target trace ${e} not found`);let a=1e-5,c=t.filter(S=>S.mspPairId!==e),l=.01,u=c.flatMap((S,T)=>S.tracePath.slice(0,-1).map((I,E)=>{let M=S.tracePath[E+1];return{chipId:`trace-obstacle-${T}-${E}`,minX:Math.min(I.x,M.x)-l/2,minY:Math.min(I.y,M.y)-l/2,maxX:Math.max(I.x,M.x)+l/2,maxY:Math.max(I.y,M.y)+l/2}})),d=[...yx(n).map(S=>({...S,minX:S.minX+a,maxX:S.maxX-a,minY:S.minY+a,maxY:S.maxY-a})),...u],_=(S,T,I)=>{for(let E of I)if(mm(S,T,E))return!0;return!1},g=i.filter(S=>{let T=o[S.globalConnNetId];return T?!T.has(s.globalConnNetId):S.globalConnNetId!==s.globalConnNetId}).map(S=>({minX:S.center.x-S.width/2+a,maxX:S.center.x+S.width/2-a,minY:S.center.y-S.height/2+a,maxY:S.center.y+S.height/2-a})),x=[...s.tracePath];if(x.length<4)return{...s};if(x.length===4){let[S,T,I,E]=x,M,k;if(S.y===T.y&&T.x===I.x&&I.y===E.y){let R=(S.x+E.x)/2;M={x:R,y:T.y},k={x:R,y:I.y}}else{let R=(S.y+E.y)/2;M={x:T.x,y:R},k={x:I.x,y:R}}return _(S,M,d)||_(M,k,d)||_(k,E,d)||_(S,M,g)||_(M,k,g)||_(k,E,g)||(x[1]=M,x[2]=k),{...s,tracePath:fm(x)}}for(let S=1;S<x.length-4;S++){let T=x[S],I=x[S+1],E=x[S+2],M=x[S+3],k=T.y===I.y&&I.x===E.x&&E.y===M.y,N=T.x===I.x&&I.y===E.y&&E.x===M.x,A=T.y===I.y&&I.y===E.y&&E.y===M.y,R=T.x===I.x&&I.x===E.x&&E.x===M.x,$=A||R,j=!1;if(k?j=Math.sign(I.x-T.x)===Math.sign(M.x-E.x):N&&(j=Math.sign(I.y-T.y)===Math.sign(M.y-E.y)),!((k||N)&&!$&&j))continue;let X,G,tt=Math.abs(k?T.x-I.x:T.y-I.y),Q=Math.abs(k?E.x-M.x:E.y-M.y);if(Math.abs(tt-Q)<.001)continue;if(k){let rt=(T.x+M.x)/2;X={x:rt,y:I.y},G={x:rt,y:E.y}}else{let rt=(T.y+M.y)/2;X={x:I.x,y:rt},G={x:E.x,y:rt}}_(T,X,d)||_(X,G,d)||_(G,M,d)||_(T,X,g)||_(X,G,g)||_(G,M,g)||(x[S+1]=X,x[S+2]=G,S=0)}let w=fm(x);return{...s,tracePath:w}},uSt=e=>{let t=[];if(e.length<3)return t;for(let n=0;n<e.length-2;n++){let i=e[n],o=e[n+1],r=e[n+2],s=o.x-i.x,a=o.y-i.y,c=r.x-o.x,l=r.y-o.y;(s===0&&l===0&&a!==0&&c!==0||a===0&&c===0&&s!==0&&l!==0)&&s*s+a*a>=.25&&c*c+l*l>=.25&&t.push({p1:i,p2:o,p3:r})}return t},pSt=(e,t)=>{let n=[];for(let i of e)i.mspPairId!==t&&n.push({points:i.tracePath});return n},pX=(e,t,n)=>{let i=[];for(let o of n){let r=o.points;for(let s=0;s<r.length-1;s++){let a=r[s],c=r[s+1];if(!a||!c)continue;let l=Xl(e,t,a,c);l&&i.push(l)}}return i},Qs=1e-6,yc=(e,t,n=Qs)=>Math.abs(e.x-t.x)<n,hSt=({lShape:e,rectangle:t,padding:n=.5,interactionPoint1:i,interactionPoint2:o})=>{let{p1:r,p2:s,p3:a}=e,{x:c,y:l,width:u,height:h}=t,d,_=i,y=o;if(Math.abs(s.x-c)<Qs&&Math.abs(s.y-(l+h))<Qs)d={x:c+u+n,y:l-n},yc(r,s)?_={x:i.x,y:i.y-n}:_={x:i.x+n,y:i.y},yc(s,a)?y={x:o.x,y:o.y-n}:y={x:o.x+n,y:o.y};else if(Math.abs(s.x-(c+u))<Qs&&Math.abs(s.y-(l+h))<Qs)d={x:c-n,y:l-n},yc(r,s)?_={x:i.x,y:i.y-n}:_={x:i.x-n,y:i.y},yc(s,a)?y={x:o.x,y:o.y-n}:y={x:o.x-n,y:o.y};else if(Math.abs(s.x-c)<Qs&&Math.abs(s.y-l)<Qs)d={x:c+u+n,y:l+h+n},yc(r,s)?_={x:i.x,y:i.y+n}:_={x:i.x+n,y:i.y},yc(s,a)?y={x:o.x,y:o.y+n}:y={x:o.x+n,y:o.y};else if(Math.abs(s.x-(c+u))<Qs&&Math.abs(s.y-l)<Qs)d={x:c-n,y:l+h+n},yc(r,s)?_={x:i.x,y:i.y+n}:_={x:i.x-n,y:i.y},yc(s,a)?y={x:o.x,y:o.y+n}:y={x:o.x-n,y:o.y};else return[];return[[_,d,y]]},dSt=(e,t,n)=>{if(e.length<2)return{isColliding:!1};for(let i=0;i<e.length-1;i++){let o=e[i],r=e[i+1];for(let s of t)if(s.mspPairId!==n)for(let a=0;a<s.tracePath.length-1;a++){let c=s.tracePath[a],l=s.tracePath[a+1],u=Xl(o,r,c,l);if(u)return{isColliding:!0,collidingTraceId:s.mspPairId,collisionPoint:u}}}return{isColliding:!1}},fSt=(e,t)=>{let n=[];for(let i of e)for(let o of t){let r=Math.min(i.x,o.x),s=Math.min(i.y,o.y),a=Math.max(i.x,o.x),c=Math.max(i.y,o.y),l=a-r,u=c-s;l>1e-6&&u>1e-6&&n.push({rect:{x:r,y:s,width:l,height:u},i1:i,i2:o})}return n},_x=e=>{let t={circles:[],lines:[]},n=Array.isArray(e)?e:[e];for(let i of n)t.circles.push({center:{x:i.p2.x,y:i.p2.y},radius:.01,fill:"blue"}),t.lines.push({points:[i.p1,i.p2,i.p3],strokeColor:"lightblue"});return t},hX=(e,t="red")=>{let n={circles:[]};for(let i of e)n.circles.push({center:{x:i.x,y:i.y},radius:.01,fill:t});return n},dX=e=>{let t={rects:[]};return t.rects.push({center:{x:e.x+e.width/2,y:e.y+e.height/2},width:e.width,height:e.height,stroke:"green"}),t},mSt=(e,t="gray",n=[])=>{let i={lines:[],circles:[]};for(let o of e)i.lines.push({points:o,strokeColor:t});for(let o of n)i.circles.push({center:o,radius:.01,fill:"green"});return i},YM=e=>{let t={lines:[],points:[],rects:[],circles:[],texts:[]};for(let n of e)n&&(n.lines&&t.lines.push(...n.lines),n.points&&t.points.push(...n.points),n.rects&&t.rects.push(...n.rects),n.circles&&t.circles.push(...n.circles),n.texts&&t.texts.push(...n.texts));return t},_St=e=>{let t={circles:[]};return e?.isColliding&&e.collisionPoint&&t.circles.push({center:e.collisionPoint,radius:.01,fill:"red"}),t},ySt=class extends co{constructor(t){super();P(this,"input");P(this,"lShapesToProcess",[]);P(this,"visualizationMode","l_shapes");P(this,"currentLShape",null);P(this,"intersectionPoints",[]);P(this,"tightRectangle",null);P(this,"candidates",[]);P(this,"bestRoute",null);P(this,"lastCollision",null);P(this,"collidingCandidate",null);P(this,"rectangleCandidates",[]);P(this,"currentRectangleIndex",0);P(this,"isInitialStep",!0);P(this,"currentCandidateIndex",0);P(this,"lShapeProcessingStep","idle");P(this,"lShapeJustProcessed",!1);P(this,"bestRouteFound",null);this.input=t,this.visualizationMode="l_shapes";for(let n of this.input.allTraces){let i=uSt(n.tracePath);this.lShapesToProcess.push(...i.map(o=>({...o,traceId:n.mspPairId})))}}_step(){if(this.isInitialStep){this.isInitialStep=!1;return}if(this.lShapeJustProcessed){this._resetAfterLShapProcessing();return}if(this.lShapesToProcess.length===0&&this.currentLShape===null){this.solved=!0;return}switch(this.lShapeProcessingStep){case"idle":this._handleIdleStep();break;case"intersections":this._handleIntersectionsStep();break;case"rectangle_selection":this._handleRectangleSelectionStep();break;case"candidate_evaluation":this._handleCandidateEvaluationStep();break}}_resetAfterLShapProcessing(){this.lShapeProcessingStep="idle",this.currentLShape=null,this.currentCandidateIndex=0,this.lShapeJustProcessed=!1,this.visualizationMode="l_shapes",this.intersectionPoints=[],this.tightRectangle=null,this.candidates=[],this.bestRoute=null,this.lastCollision=null,this.collidingCandidate=null}_handleIdleStep(){if(this.currentLShape=this.lShapesToProcess.shift(),!this.currentLShape){this.solved=!0;return}this.lShapeProcessingStep="intersections",this.visualizationMode="l_shapes"}_handleIntersectionsStep(){if(!this.currentLShape.traceId){this.lShapeProcessingStep="idle";return}let t=pSt(this.input.allTraces,this.currentLShape.traceId),n=pX(this.currentLShape.p1,this.currentLShape.p2,t),i=pX(this.currentLShape.p2,this.currentLShape.p3,t);if(this.intersectionPoints=[...n,...i],n.length===0||i.length===0){this.lShapeProcessingStep="idle";return}this.rectangleCandidates=fSt(n,i),this.currentRectangleIndex=0,this.lShapeProcessingStep="rectangle_selection"}_handleRectangleSelectionStep(){if(this.currentRectangleIndex>=this.rectangleCandidates.length){this.lShapeProcessingStep="idle";return}let{rect:t,i1:n,i2:i}=this.rectangleCandidates[this.currentRectangleIndex];this.tightRectangle=t,this.candidates=hSt({lShape:this.currentLShape,rectangle:this.tightRectangle,padding:2*this.input.paddingBuffer,interactionPoint1:n,interactionPoint2:i}),this.currentCandidateIndex=0,this.lastCollision=null,this.collidingCandidate=null,this.visualizationMode="candidates",this.lShapeProcessingStep="candidate_evaluation"}_handleCandidateEvaluationStep(){if(this.visualizationMode="candidates",this.bestRouteFound){this._applyBestRoute(this.bestRouteFound),this.bestRouteFound=null;return}if(this.currentCandidateIndex>=this.candidates.length){this.currentRectangleIndex++,this.lShapeProcessingStep="rectangle_selection";return}let t=this.candidates[this.currentCandidateIndex],n=dSt(t,this.input.allTraces,this.currentLShape.traceId);n?.isColliding?(this.lastCollision=n,this.collidingCandidate=t,this.currentCandidateIndex++):(this.bestRouteFound=t,this.lastCollision=null,this.collidingCandidate=null)}_applyBestRoute(t){this.bestRoute=t,this.collidingCandidate=null,this.lastCollision=null;let n=this.input.allTraces.findIndex(i=>i.mspPairId===this.currentLShape.traceId);if(n!==-1){let i=this.input.allTraces[n],o=i.tracePath.findIndex(r=>r.x===this.currentLShape.p2.x&&r.y===this.currentLShape.p2.y);if(o!==-1){let r=[...i.tracePath.slice(0,o),...t,...i.tracePath.slice(o+1)];this.input.allTraces[n]={...i,tracePath:r},this.lShapesToProcess=this.lShapesToProcess.filter(s=>s.traceId!==this.currentLShape.traceId)}}this.lShapeJustProcessed=!0}getOutput(){return{traces:this.input.allTraces}}visualize(){switch(this.visualizationMode){case"l_shapes":return _x(this.lShapesToProcess);case"intersection_points":return YM([this.currentLShape?_x(this.currentLShape):void 0,hX(this.intersectionPoints)]);case"tight_rectangle":return YM([this.currentLShape?_x(this.currentLShape):void 0,hX(this.intersectionPoints),this.tightRectangle?dX(this.tightRectangle):void 0]);case"candidates":{if(this.lShapeJustProcessed){let i={lines:[]};for(let o of this.input.allTraces){let r=o.mspPairId===this.currentLShape?.traceId;for(let s=0;s<o.tracePath.length-1;s++)i.lines.push({points:[o.tracePath[s],o.tracePath[s+1]],strokeColor:r?"green":"#ccc"})}return i}let t={lines:[]};for(let i of this.input.allTraces)for(let o=0;o<i.tracePath.length-1;o++)t.lines.push({points:[i.tracePath[o],i.tracePath[o+1]],strokeColor:"#ccc"});let n;return this.bestRouteFound?n=this.bestRouteFound:this.lastCollision?.isColliding?n=this.collidingCandidate??void 0:this.currentCandidateIndex<this.candidates.length&&(n=this.candidates[this.currentCandidateIndex]),YM([t,this.currentLShape?_x(this.currentLShape):void 0,this.tightRectangle?dX(this.tightRectangle):void 0,n?mSt([n],this.bestRouteFound?"green":"blue",this.intersectionPoints):void 0,this.lastCollision?_St(this.lastCollision):void 0])}default:return{}}}},gSt=e=>{if(e.length!==4)return!1;let[t,n,i,o]=e,r=t.y===n.y&&n.x===i.x&&i.y===o.y&&t.x===o.x,s=t.x===n.x&&n.y===i.y&&i.x===o.x&&t.y===o.y;return r||s},bSt=class extends co{constructor(t){super();P(this,"input");P(this,"outputTraces");P(this,"traceIdQueue");P(this,"tracesMap");P(this,"pipelineStep","untangling_traces");P(this,"activeTraceId",null);P(this,"activeSubSolver",null);this.input=t,this.outputTraces=[...t.allTraces],this.tracesMap=new Map(this.outputTraces.map(n=>[n.mspPairId,n])),this.traceIdQueue=Array.from(t.allTraces.map(n=>n.mspPairId))}_step(){if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){let t=this.activeSubSolver.getOutput();this.outputTraces=t.traces,this.tracesMap=new Map(this.outputTraces.map(n=>[n.mspPairId,n])),this.activeSubSolver=null,this.pipelineStep="minimizing_turns"}else this.activeSubSolver.failed&&(this.activeSubSolver=null,this.pipelineStep="minimizing_turns");return}switch(this.pipelineStep){case"untangling_traces":this._runUntangleTracesStep();break;case"minimizing_turns":this._runMinimizeTurnsStep();break;case"balancing_l_shapes":this._runBalanceLShapesStep();break}}_runUntangleTracesStep(){this.activeSubSolver=new ySt({...this.input,allTraces:Array.from(this.tracesMap.values())})}_runMinimizeTurnsStep(){if(this.traceIdQueue.length===0){this.pipelineStep="balancing_l_shapes",this.traceIdQueue=Array.from(this.input.allTraces.map(t=>t.mspPairId));return}this._processTrace("minimizing_turns")}_runBalanceLShapesStep(){if(this.traceIdQueue.length===0){this.solved=!0;return}this._processTrace("balancing_l_shapes")}_processTrace(t){let n=this.traceIdQueue.shift();this.activeTraceId=n;let i=this.tracesMap.get(n);if(gSt(i.tracePath))return;let o=Array.from(this.tracesMap.values()),r;t==="minimizing_turns"?r=cSt({...this.input,targetMspConnectionPairId:n,traces:o}):r=lSt({...this.input,targetMspConnectionPairId:n,traces:o}),this.tracesMap.set(n,r),this.outputTraces=Array.from(this.tracesMap.values())}getOutput(){return{traces:this.outputTraces}}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Vo(this.input.inputProblem,{chipAlpha:.1,connectionAlpha:.1});t.lines||(t.lines=[]),t.points||(t.points=[]),t.rects||(t.rects=[]),t.circles||(t.circles=[]),t.texts||(t.texts=[]);for(let n of this.outputTraces){let i={points:n.tracePath.map(o=>({x:o.x,y:o.y})),strokeColor:n.mspPairId===this.activeTraceId?"red":"blue"};t.lines.push(i)}return t}};function gc(e,t,n,i={}){return{solverName:e,solverClass:t,getConstructorParams:n,onSolved:i.onSolved,shouldSkip:i.shouldSkip}}var bX=class extends co{constructor(t){super();P(this,"mspConnectionPairSolver");P(this,"schematicTraceLinesSolver");P(this,"longDistancePairSolver");P(this,"traceOverlapShiftSolver");P(this,"netLabelPlacementSolver");P(this,"labelMergingSolver");P(this,"traceLabelOverlapAvoidanceSolver");P(this,"traceCleanupSolver");P(this,"startTimeOfPhase");P(this,"endTimeOfPhase");P(this,"timeSpentOnPhase");P(this,"firstIterationOfPhase");P(this,"inputProblem");P(this,"pipelineDef",[gc("mspConnectionPairSolver",Cvt,()=>[{inputProblem:this.inputProblem}],{onSolved:t=>{}}),gc("schematicTraceLinesSolver",Fvt,()=>[{mspConnectionPairs:this.mspConnectionPairSolver.mspConnectionPairs,dcConnMap:this.mspConnectionPairSolver.dcConnMap,globalConnMap:this.mspConnectionPairSolver.globalConnMap,inputProblem:this.inputProblem,chipMap:this.mspConnectionPairSolver.chipMap}]),gc("longDistancePairSolver",rSt,t=>[{inputProblem:t.inputProblem,primaryMspConnectionPairs:t.mspConnectionPairSolver.mspConnectionPairs,alreadySolvedTraces:t.schematicTraceLinesSolver.solvedTracePaths}],{onSolved:t=>{}}),gc("traceOverlapShiftSolver",$vt,()=>[{inputProblem:this.inputProblem,inputTracePaths:this.longDistancePairSolver?.getOutput().allTracesMerged,globalConnMap:this.mspConnectionPairSolver.globalConnMap}],{onSolved:t=>{}}),gc("netLabelPlacementSolver",lX,()=>[{inputProblem:this.inputProblem,inputTraceMap:this.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(this.longDistancePairSolver.getOutput().allTracesMerged.map(t=>[t.mspPairId,t]))}],{onSolved:t=>{}}),gc("traceLabelOverlapAvoidanceSolver",Qvt,t=>{let n=t.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(t.longDistancePairSolver.getOutput().allTracesMerged.map(r=>[r.mspPairId,r])),i=Object.values(n),o=t.netLabelPlacementSolver.netLabelPlacements;return[{inputProblem:t.inputProblem,traces:i,netLabelPlacements:o}]}),gc("traceCleanupSolver",bSt,t=>{let i=t.traceLabelOverlapAvoidanceSolver.getOutput().traces,o=t.traceLabelOverlapAvoidanceSolver.labelMergingSolver.getOutput();return[{inputProblem:t.inputProblem,allTraces:i,allLabelPlacements:o.netLabelPlacements,mergedLabelNetIdMap:o.mergedLabelNetIdMap,paddingBuffer:.1}]}),gc("netLabelPlacementSolver",lX,t=>{let n=t.traceCleanupSolver?.getOutput().traces??t.traceLabelOverlapAvoidanceSolver.getOutput().traces;return[{inputProblem:t.inputProblem,inputTraceMap:Object.fromEntries(n.map(i=>[i.mspPairId,i]))}]})]);P(this,"currentPipelineStepIndex",0);this.inputProblem=this.cloneAndCorrectInputProblem(t),this.MAX_ITERATIONS=1e6,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={},this.firstIterationOfPhase={}}getConstructorParams(){return this.inputProblem}cloneAndCorrectInputProblem(t){let n=structuredClone({...t,_chipObstacleSpatialIndex:void 0});return eSt(n),tSt(n),n}_step(){let t=this.pipelineDef[this.currentPipelineStepIndex];if(!t){this.solved=!0;return}if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.endTimeOfPhase[t.solverName]=performance.now(),this.timeSpentOnPhase[t.solverName]=this.endTimeOfPhase[t.solverName]-this.startTimeOfPhase[t.solverName],t.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let n=t.getConstructorParams(this);this.activeSubSolver=new t.solverClass(...n),this[t.solverName]=this.activeSubSolver,this.timeSpentOnPhase[t.solverName]=0,this.startTimeOfPhase[t.solverName]=performance.now(),this.firstIterationOfPhase[t.solverName]=this.iterations}solveUntilPhase(t){for(;this.getCurrentPhase().toLowerCase()!==t.toLowerCase();)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let t=[Vo(this.inputProblem),...this.pipelineDef.map(i=>this[i.solverName]?.visualize()).filter(Boolean).map((i,o)=>{for(let r of i.rects??[])r.step=o;for(let r of i.points??[])r.step=o;for(let r of i.circles??[])r.step=o;for(let r of i.texts??[])r.step=o;for(let r of i.lines??[])r.step=o;return i})];return t.length===1?t[0]:{points:t.flatMap(i=>i.points||[]),rects:t.flatMap(i=>i.rects||[]),lines:t.flatMap(i=>i.lines||[]),circles:t.flatMap(i=>i.circles||[]),texts:t.flatMap(i=>i.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}};var WH=Xt(Sn(),1);var ZH=Xt(Sn(),1);var KH=Xt(Sn(),1);ji();var xSt=e=>{let t=[];t.push(e.title),e.models.size>0&&t.push(...Array.from(e.models.values()));for(let n of e.components)t.push(n.toSpiceString());for(let n of e.subcircuits)t.push(n.toSpiceString());return e.printStatements.length>0&&t.push(...e.printStatements),e.controls.length>0&&(t.push(".control"),t.push(...e.controls),t.push(".endc")),e.tranCommand&&!t.some(n=>n.trim().toLowerCase().startsWith(".tran"))&&t.push(e.tranCommand),t.push(".END"),t.join(`
|
|
247
247
|
`)},vSt=class{constructor(e="Circuit Netlist"){P(this,"title");P(this,"components");P(this,"nodes");P(this,"controls");P(this,"subcircuits");P(this,"models");P(this,"tranCommand");P(this,"printStatements");this.title=e,this.components=[],this.nodes=new Set,this.controls=[],this.subcircuits=[],this.models=new Map,this.tranCommand=null,this.printStatements=[]}addComponent(e){this.components.push(e);for(let t of e.nodes)this.nodes.add(t)}addSubcircuit(e){this.subcircuits.find(t=>t.name===e.name)||this.subcircuits.push(e)}toSpiceString(){return xSt(this)}},ea=class{constructor(e,t,n){P(this,"name");P(this,"command");P(this,"nodes");this.name=e,this.command=t,this.nodes=n}toSpiceString(){return this.command.toSpiceString()}},SSt=class{constructor(e){P(this,"commandName","resistor");P(this,"props");this.props=e}toSpiceString(){let{name:e,positiveNode:t,negativeNode:n,model:i,value:o}=this.props,r=`R${e} ${t} ${n}`;return i&&(r+=` ${i}`),r+=` ${o}`,r}},wSt=class{constructor(e){P(this,"commandName","capacitor");P(this,"props");this.props=e}toSpiceString(){let{name:e,positiveNode:t,negativeNode:n,modelName:i,value:o,initialCondition:r}=this.props,s=`C${e} ${t} ${n}`;return i&&(s+=` ${i}`),s+=` ${o}`,r&&(s+=` IC=${r}`),s}},qM=class{constructor(e){P(this,"commandName","voltage_source");P(this,"props");this.props=e}toSpiceString(){let{name:e,positiveNode:t,negativeNode:n,value:i,acMagnitude:o,acPhase:r}=this.props,s=`V${e} ${t} ${n}`;return i&&(s+=` ${i}`),o&&(s+=` AC ${o}`,r&&(s+=` ${r}`)),s}},PSt=class{constructor(e){P(this,"commandName","diode");P(this,"props");this.props=e}toSpiceString(){let{name:e,positiveNode:t,negativeNode:n,model:i,area:o}=this.props,r=`D${e} ${t} ${n} ${i}`;return o&&(r+=` ${o}`),r}},ISt=class{constructor(e){P(this,"commandName","inductor");P(this,"props");this.props=e}toSpiceString(){let{name:e,positiveNode:t,negativeNode:n,model:i,value:o,initialCondition:r}=this.props,s=`L${e} ${t} ${n}`;return i&&(s+=` ${i}`),s+=` ${o}`,r&&(s+=` IC=${r}`),s}},xX=class{constructor(e){P(this,"commandName","voltage_controlled_switch");P(this,"props");this.props=e}toSpiceString(){let{name:e,positiveNode:t,negativeNode:n,positiveControl:i,negativeControl:o,model:r}=this.props;return`S${e} ${t} ${n} ${i} ${o} ${r}`}};function vX(e){let t=new vSt("* Circuit JSON to SPICE Netlist"),n=Rr(e).source_component.list(),i=Rr(e).source_port.list(),o=e.filter(g=>g.type==="simulation_switch").map(g=>g),r=new Map;for(let g of o)g.source_component_id&&r.set(g.source_component_id,g);let s=$F(e),a=new Map,c=new Map,l=1,u=new Set,h=new Set(Rr(e).source_net.list().filter(g=>g.name?.toLowerCase().includes("gnd")).map(g=>g.source_net_id));if(h.size>0){for(let g of Rr(e).source_trace.list())if(g.connected_source_port_ids.length>0&&g.connected_source_net_ids.some(w=>h.has(w))){let w=g.connected_source_port_ids[0],S=s.getNetConnectedToId(w);S&&u.add(S)}}let d=i.filter(g=>g.name?.toLowerCase()==="gnd");for(let g of d){let x=s.getNetConnectedToId(g.source_port_id);x&&u.add(x)}for(let g of Rr(e).simulation_voltage_source.list()){let x=g.negative_source_port_id??g.terminal2_source_port_id;if(x){let w=s.getNetConnectedToId(x);w&&u.add(w)}}for(let g of u)c.set(g,"0");for(let g of i){let x=g.source_port_id,w=s.getNetConnectedToId(x);w&&(c.has(w)||c.set(w,`N${l++}`),a.set(x,c.get(w)))}for(let g of i){let x=g.source_port_id;a.has(x)||a.set(x,`N${l++}`)}for(let g of n){if(g.type!=="source_component")continue;let x=Rr(e).source_port.list({source_component_id:g.source_component_id}).sort((S,T)=>(S.pin_number??0)-(T.pin_number??0)),w=x.map(S=>a.get(S.source_port_id)||"0");if("ftype"in g){let S=null;switch(g.ftype){case"simple_resistor":{if("resistance"in g&&"name"in g){let T=new SSt({name:g.name,positiveNode:w[0]||"0",negativeNode:w[1]||"0",value:TSt(g.resistance)});S=new ea(g.name,T,w)}break}case"simple_switch":{let T=ESt(g.name??g.source_component_id,"SW"),I=w[0]||"0",E=w[1]||"0",M=`NCTRL_${T}`,k=`SW_${T}`,N=r.get(g.source_component_id),A=NSt(N),R=new xX({name:T,positiveNode:I,negativeNode:E,positiveControl:M,negativeControl:"0",model:k});S=new ea(T,R,[I,E,M,"0"]),t.models.has(k)||t.models.set(k,`.MODEL ${k} SW(Ron=0.1 Roff=1e9 Vt=2.5 Vh=0.1)`);let $=`CTRL_${T}`,j=new qM({name:$,positiveNode:M,negativeNode:"0",value:A}),H=new ea($,j,[M,"0"]);t.addComponent(H);break}case"simple_capacitor":{if("capacitance"in g&&"name"in g){let T=new wSt({name:g.name,positiveNode:w[0]||"0",negativeNode:w[1]||"0",value:MSt(g.capacitance)});S=new ea(g.name,T,w)}break}case"simple_diode":{if("name"in g){let T=x.find(A=>A.name?.toLowerCase()==="anode"||A.port_hints?.includes("anode")),I=x.find(A=>A.name?.toLowerCase()==="cathode"||A.port_hints?.includes("cathode")),E=a.get(T?.source_port_id??"")||"0",M=a.get(I?.source_port_id??"")||"0",k="D",N=new PSt({name:g.name,positiveNode:E,negativeNode:M,model:k});t.models.set(k,`.MODEL ${k} D`),S=new ea(g.name,N,[E,M])}break}case"simple_inductor":{if("inductance"in g&&"name"in g){let T=new ISt({name:g.name,positiveNode:w[0]||"0",negativeNode:w[1]||"0",value:CSt(g.inductance)});S=new ea(g.name,T,w)}break}case"simple_mosfet":{if("name"in g){let T=x.find($=>$.name?.toLowerCase()==="drain"||$.port_hints?.includes("drain")),I=x.find($=>$.name?.toLowerCase()==="gate"||$.port_hints?.includes("gate")),E=x.find($=>$.name?.toLowerCase()==="source"||$.port_hints?.includes("source")),M=a.get(T?.source_port_id??"")||"0",k=a.get(I?.source_port_id??"")||"0",N=a.get(E?.source_port_id??"")||"0",A="SWMOD",R=new xX({name:g.name,positiveNode:M,negativeNode:N,positiveControl:k,negativeControl:N,model:A});t.models.set(A,`.MODEL ${A} SW`),S=new ea(g.name,R,[M,k,N])}break}}S&&t.addComponent(S)}}let _=Rr(e).simulation_voltage_source.list();for(let g of _)if(g.type==="simulation_voltage_source")if(g.is_dc_source===!1){if("terminal1_source_port_id"in g&&"terminal2_source_port_id"in g&&g.terminal1_source_port_id&&g.terminal2_source_port_id){let x=a.get(g.terminal1_source_port_id)||"0",w=a.get(g.terminal2_source_port_id)||"0",S="",T=g.wave_shape;if(T==="sinewave"){let E=g.voltage??0,M=g.frequency??0,k=0,N=0,A=g.phase??0;M>0?S=`SIN(0 ${E} ${M} ${k} ${N} ${A})`:S=`DC ${g.voltage??0}`}else if(T==="square"){let E=g.voltage??0,M=g.frequency??0,k=M===0?1/0:1/M,N=g.period??k,A=g.duty_cycle??.5,R=N*A;S=`PULSE(0 ${E} 0 1n 1n ${R} ${N})`}else g.voltage!==void 0&&(S=`DC ${g.voltage}`);if(S){let I=new qM({name:g.simulation_voltage_source_id,positiveNode:x,negativeNode:w,value:S}),E=new ea(g.simulation_voltage_source_id,I,[x,w]);t.addComponent(E)}}}else{let x=g.positive_source_port_id??g.terminal1_source_port_id,w=g.negative_source_port_id??g.terminal2_source_port_id;if(x&&w&&"voltage"in g&&g.voltage!==void 0){let S=a.get(x)||"0",T=a.get(w)||"0",I=new qM({name:g.simulation_voltage_source_id,positiveNode:S,negativeNode:T,value:`DC ${g.voltage}`}),E=new ea(g.simulation_voltage_source_id,I,[S,T]);t.addComponent(E)}}let y=e.find(g=>g.type==="simulation_experiment");if(y){let g=e.filter(T=>T.type==="simulation_voltage_probe");if(g.length>0){let T=Rr(e).source_trace.list(),I=new Set;for(let E of g){let M;if(E.source_port_id)M=a.get(E.source_port_id);else if(E.source_net_id){let k=T.find(N=>N.connected_source_net_ids.includes(E.source_net_id));if(k&&k.connected_source_port_ids.length>0){let N=k.connected_source_port_ids[0];M=a.get(N)}}M&&M!=="0"&&I.add(`V(${M.toLowerCase()})`)}I.size>0&&y.experiment_type?.includes("transient")&&t.printStatements.push(`.PRINT TRAN ${[...I].join(" ")}`)}let x=y.time_per_step,w=y.end_time_ms,S=y.start_time_ms;if(x&&w){let T=(S??0)/1e3,I=`.tran ${Ci(x/1e3)} ${Ci(w/1e3)}`;T>0&&(I+=` ${Ci(T)}`),I+=" UIC",t.tranCommand=I}}return t}function TSt(e){return e>=1e6?`${e/1e6}MEG`:e>=1e3?`${e/1e3}K`:e.toString()}function MSt(e){return e>=.001?`${e*1e3}M`:e>=1e-6?`${e*1e6}U`:e>=1e-9?`${e*1e9}N`:e>=1e-12?`${e*1e12}P`:e.toString()}function CSt(e){return e>=1?e.toString():e>=.001?`${e*1e3}m`:e>=1e-6?`${e*1e6}u`:e>=1e-9?`${e*1e9}n`:e>=1e-12?`${e*1e12}p`:e.toString()}function ESt(e,t){if(!e)return t;let n=e.replace(/[^A-Za-z0-9_]/g,"_");return n?/^[0-9]/.test(n)?`${t}_${n}`:n:t}function NSt(e){if(!e)return"DC 0";let r=e.starts_closed??!1,s=e.closes_at??0,a=e.opens_at,c=e.switching_frequency,[l,u]=r?[5,0]:[0,5];if(c&&c>0){let h=1/c,d=a&&a>s?Math.min(a-s,h):0,_=d>0?d:Math.max(h/2,1e-9);return`PULSE(${Ci(l)} ${Ci(u)} ${Ci(s)} 1n 1n ${Ci(_)} ${Ci(h)})`}if(a!==void 0&&a>s){let h=Math.max(a-s,1e-9),d=s+h*2;return`PULSE(${Ci(l)} ${Ci(u)} ${Ci(s)} 1n 1n ${Ci(h)} ${Ci(d)})`}if(s>0){let h=s*2,d=Math.max(h/2,1e-9);return`PULSE(${Ci(l)} ${Ci(u)} ${Ci(s)} 1n 1n ${Ci(d)} ${Ci(h)})`}return`DC ${r?5:0}`}function Ci(e){if(!Number.isFinite(e))return`${e}`;if(e===0)return"0";let t=Math.abs(e);return t>=1e3||t<=.001?Number(e.toExponential(6)).toString():Number(e.toPrecision(6)).toString()}var JH=Xt(Sn(),1);var Hn=1e-15,kSt=class{constructor(){P(this,"map");P(this,"rev");this.map=new Map([["0",0]]),this.rev=["0"]}getOrCreate(e){let t=String(e),n=t.toUpperCase();if(this.map.has(n))return this.map.get(n);let i=this.rev.length;return this.map.set(n,i),this.rev.push(t),i}get(e){return this.map.get(String(e).toUpperCase())}count(){return this.rev.length}matrixIndexOfNode(e){return e===0?-1:e-1}};function to(e){if(e==null)return NaN;let t=String(e).trim();if(t==="")return NaN;if(/^[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?$/.test(t))return parseFloat(t);let n={t:1e12,g:1e9,meg:1e6,k:1e3,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15},i=t.match(/^([+-]?\d*\.?\d+(?:[eE][+-]?\d+)?)([a-zA-Z]+)$/);if(!i)return parseFloat(t);let[,o,r]=i;if(o==null)return parseFloat(t);let s=parseFloat(o),a=(r??"").toLowerCase();return a=a.replace(/(ohm|v|a|s|h|f)$/g,""),a==="meg"?s*n.meg:a.length===1&&a in n?s*n[a]:s}function ASt(e){let t=/"[^"]*"|\w+\s*\([^)]*\)|\([^()]*\)|\S+/g,n=[],i;for(;(i=t.exec(e))!==null;)n.push(i[0]);return n}function tn(e,t,n){let i=e[t];if(i==null)throw new Error(n);return i}function RSt(e){let i=e.trim().replace(/^pulse\s*\(/i,"(").replace(/^\(/,"").replace(/\)$/,"").trim().split(/[\s,]+/).filter(r=>r.length);if(i.length<7)throw new Error("PULSE(...) requires 7 or 8 args");let o=i.map(r=>to(r));if(o.some(r=>Number.isNaN(r)))throw new Error("Invalid PULSE() numeric value");return{v1:o[0],v2:o[1],td:o[2],tr:o[3],tf:o[4],ton:o[5],period:o[6],ncycles:i[7]!=null?o[7]:1/0}}function OSt(e){let i=e.trim().replace(/^pwl\s*\(/i,"(").replace(/^\(/,"").replace(/\)$/,"").trim().split(/[\s,]+/).filter(r=>r.length);if(i.length===0||i.length%2!==0)throw new Error("PWL(...) requires an even number of time/value pairs");let o=[];for(let r=0;r<i.length;r+=2){let s=to(i[r]),a=to(i[r+1]);if(Number.isNaN(s)||Number.isNaN(a))throw new Error("Invalid PWL() numeric value");o.push({t:s,v:a})}return o}function LSt(e,t){if(e.length===0)return 0;if(t<=e[0].t)return e[0].v;for(let n=1;n<e.length;n++){let i=e[n-1],o=e[n];if(t<=o.t){let r=Math.max(o.t-i.t,Hn),s=(t-i.t)/r;return i.v+(o.v-i.v)*s}}return e[e.length-1].v}function FSt(e,t){if(t<e.td)return e.v1;let n=t-e.td,i=Math.floor(n/e.period);if(i>=e.ncycles)return e.v1;let o=n-i*e.period;if(o<e.tr){let r=o/Math.max(e.tr,Hn);return e.v1+(e.v2-e.v1)*r}if(o<e.tr+e.ton)return e.v2;if(o<e.tr+e.ton+e.tf){let r=(o-(e.tr+e.ton))/Math.max(e.tf,Hn);return e.v2+(e.v1-e.v2)*r}return e.v1}function zSt(e){let t=new Map,n=new Map,i={nodes:new kSt,R:[],C:[],L:[],V:[],S:[],D:[],analyses:{ac:null,tran:null},probes:{tran:[]},skipped:[],models:{vswitch:t,diode:n}},o=e.split(/\r?\n/),r=!1;for(let a of o){let c=a.trim();if(!c||/^\*/.test(c))continue;if(/^\s*\.end\b/i.test(c))break;c=c.replace(/\/\/.*$/,""),c=c.replace(/;.*$/,"");let l=ASt(c);if(l.length===0)continue;let u=l[0];if(u.length===0)continue;if(!r&&!/^[rclvgsmiqd]\w*$/i.test(u)&&!/^\./.test(u)){r=!0;continue}if(/^\./.test(u)){let _=u.toLowerCase();if(_===".ac"){let y=tn(l,1,".ac missing mode").toLowerCase();if(y!=="dec"&&y!=="lin")throw new Error(".ac supports 'dec' or 'lin'");let g=parseInt(tn(l,2,".ac missing point count"),10),x=to(tn(l,3,".ac missing start frequency")),w=to(tn(l,4,".ac missing stop frequency"));i.analyses.ac={mode:y,N:g,f1:x,f2:w}}else if(_===".tran"){let y=to(tn(l,1,".tran missing timestep")),g=to(tn(l,2,".tran missing stop time"));i.analyses.tran={dt:y,tstop:g}}else if(_===".print")if(tn(l,1,".print missing analysis type").toLowerCase()==="tran"){let g=l.slice(2);for(let x of g){let w=x.match(/^v\(([^)]+)\)$/i);if(w&&w[1]){let S=w[1];i.probes.tran.some(T=>T.toUpperCase()===S.toUpperCase())||i.probes.tran.push(S)}}}else i.skipped.push(c);else if(_===".model"){let y=tn(l,1,".model missing name"),x=tn(l,2,".model missing type"),w="";if(x.includes("(")){let T=x.indexOf("(");w=x.slice(T+1),x=x.slice(0,T)}if(!w)w=l.slice(3).join(" ").replace(/^\(/,"").replace(/\)$/,"");else{let T=l.slice(3).join(" ").replace(/\)$/,"");w=`${w} ${T}`.trim()}w=w.replace(/^\(/,"").replace(/\)$/,"").trim();let S=x.toLowerCase();if(S==="vswitch"||S==="sw"){let T={name:y,Ron:1,Roff:1e12,Von:0,Voff:0},I,E;if(w.length>0){let M=w.split(/[\s,]+/).filter(Boolean);for(let k of M){let[N,A]=k.split("=");if(!N||A==null)continue;let R=N.toLowerCase(),$=to(A);Number.isNaN($)||(R==="ron"?T.Ron=$:R==="roff"?T.Roff=$:R==="von"?T.Von=$:R==="voff"?T.Voff=$:R==="vt"?I=$:R==="vh"&&(E=$))}}if(I!==void 0){let M=E??0;T.Von=I+M/2,T.Voff=I-M/2}t.set(y.toLowerCase(),T)}else if(S==="d"){let T={name:y,Is:1e-14,N:1};if(w.length>0){let I=w.split(/[\s,]+/).filter(Boolean);for(let E of I){let[M,k]=E.split("=");if(!M||k==null)continue;let N=M.toLowerCase(),A=to(k);Number.isNaN(A)||(N==="is"?T.Is=A:N==="n"&&(T.N=A))}}n.set(y.toLowerCase(),T)}else i.skipped.push(c)}else i.skipped.push(c);continue}let h=u.charAt(0).toLowerCase(),d=u;try{if(h==="r"){let _=i.nodes.getOrCreate(tn(l,1,"Resistor missing node")),y=i.nodes.getOrCreate(tn(l,2,"Resistor missing node")),g=to(tn(l,3,"Resistor missing value"));i.R.push({name:d,n1:_,n2:y,R:g})}else if(h==="c"){let _=i.nodes.getOrCreate(tn(l,1,"Capacitor missing node")),y=i.nodes.getOrCreate(tn(l,2,"Capacitor missing node")),g=to(tn(l,3,"Capacitor missing value"));i.C.push({name:d,n1:_,n2:y,C:g,vPrev:0})}else if(h==="l"){let _=i.nodes.getOrCreate(tn(l,1,"Inductor missing node")),y=i.nodes.getOrCreate(tn(l,2,"Inductor missing node")),g=to(tn(l,3,"Inductor missing value"));i.L.push({name:d,n1:_,n2:y,L:g,iPrev:0})}else if(h==="v"){let _=i.nodes.getOrCreate(tn(l,1,"Voltage source missing node")),y=i.nodes.getOrCreate(tn(l,2,"Voltage source missing node")),g={dc:0,acMag:0,acPhaseDeg:0,waveform:null,index:-1},x=3;for(x<l.length&&!/^[a-zA-Z]/.test(l[x])&&(g.dc=to(l[x]),x++);x<l.length;){let w=l[x].toLowerCase();if(w==="dc"){let S=tn(l,x+1,"DC value missing");g.dc=to(S),x+=2}else if(w==="ac"){let S=tn(l,x+1,"AC magnitude missing");g.acMag=to(S);let T=l[x+2];T!=null&&/^[+-]?\d/.test(T)?(g.acPhaseDeg=to(T),x+=3):x+=2}else if(w.startsWith("pulse")){let S=w.includes("(")?w:tn(l,x+1,"PULSE() missing arguments");if(!S||!/\(.*\)/.test(S))throw new Error("Malformed PULSE() specification");let T=RSt(S);g.waveform=I=>FSt(T,I),x+=w.includes("(")?1:2}else if(w.startsWith("pwl")){let S=w.includes("(")?w:tn(l,x+1,"PWL() missing arguments");if(!S||!/\(.*\)/.test(S))throw new Error("Malformed PWL() specification");let T=OSt(S);g.waveform=I=>LSt(T,I),x+=w.includes("(")?1:2}else/^\(.*\)$/.test(w),x++}i.V.push({name:d,n1:_,n2:y,dc:g.dc,acMag:g.acMag,acPhaseDeg:g.acPhaseDeg,waveform:g.waveform,index:g.index??-1})}else if(h==="s"){let _=i.nodes.getOrCreate(tn(l,1,"Switch missing node")),y=i.nodes.getOrCreate(tn(l,2,"Switch missing node")),g=i.nodes.getOrCreate(tn(l,3,"Switch missing control node")),x=i.nodes.getOrCreate(tn(l,4,"Switch missing control node")),w=tn(l,5,"Switch missing model");i.S.push({name:d,n1:_,n2:y,ncPos:g,ncNeg:x,modelName:w.toLowerCase(),model:null,isOn:!1})}else if(h==="d")if(l.length===4){let _=i.nodes.getOrCreate(tn(l,1,"Diode missing node")),y=i.nodes.getOrCreate(tn(l,2,"Diode missing node")),g=tn(l,3,"Diode missing model");i.D.push({name:d,nPlus:_,nMinus:y,modelName:g.toLowerCase(),model:null,vdPrev:0})}else i.skipped.push(c);else i.skipped.push(c)}catch(_){throw _ instanceof Error?new Error(`Parse error on line: "${c}"
|
|
248
|
-
${_.message}`):_}}let s=i.nodes.count()-1;for(let a=0;a<i.V.length;a++){let c=i.V[a];c&&(c.index=s+a)}for(let a of i.S){let c=t.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by switch ${a.name}`);a.model=c,a.isOn=!1}for(let a of i.D){let c=n.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by diode ${a.name}`);a.model=c}return i}var qe=class na{constructor(t=0,n=0){P(this,"re");P(this,"im");this.re=t,this.im=n}static from(t,n=0){return new na(t,n)}static fromPolar(t,n=0){let i=n*Math.PI/180;return new na(t*Math.cos(i),t*Math.sin(i))}clone(){return new na(this.re,this.im)}add(t){return new na(this.re+t.re,this.im+t.im)}sub(t){return new na(this.re-t.re,this.im-t.im)}mul(t){return new na(this.re*t.re-this.im*t.im,this.re*t.im+this.im*t.re)}div(t){let n=t.re*t.re+t.im*t.im;if(n<Hn)throw new Error("Complex divide by ~0");return new na((this.re*t.re+this.im*t.im)/n,(this.im*t.re-this.re*t.im)/n)}inv(){let t=this.re*this.re+this.im*this.im;if(t<Hn)throw new Error("Complex invert by ~0");return new na(this.re/t,-this.im/t)}abs(){return Math.hypot(this.re,this.im)}phaseDeg(){return Math.atan2(this.im,this.re)*180/Math.PI}};function DSt(e,t){let n=e.length;for(let o=0;o<n;o++){let r=e[o],s=t[o];if(!r||!s)throw new Error("Matrix dimensions mismatch");let a=r.map(c=>c.clone());a.push(s.clone()),e[o]=a}for(let o=0;o<n;o++){let r=o,s=e[o];if(!s)throw new Error("Matrix row missing");let a=s[o]?.abs()??0;for(let u=o+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[o]?.abs()??0;d>a&&(a=d,r=u)}if(a<Hn)throw new Error("Singular matrix (complex)");if(r!==o){let u=e[o];e[o]=e[r],e[r]=u}let c=e[o];if(!c)throw new Error("Pivot row missing");let l=c[o];if(!l)throw new Error("Zero pivot encountered");for(let u=o+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[o];if(!d)continue;let _=d.div(l);if(!(_.abs()<Hn))for(let y=o;y<=n;y++){let g=h[y],x=c[y];!g||!x||(h[y]=g.sub(_.mul(x)))}}}let i=new Array(n);for(let o=n-1;o>=0;o--){let r=e[o];if(!r)throw new Error("Matrix row missing");let s=r[n];if(!s)throw new Error("Augmented column missing");for(let c=o+1;c<n;c++){let l=r[c],u=i[c];!l||!u||(s=s.sub(l.mul(u)))}let a=r[o];if(!a)throw new Error("Zero pivot on back-substitution");i[o]=s.div(a)}return i}function $St(e,t,n){if(e<=0||t<=0)throw new Error(".ac frequencies must be > 0");t<e&&([e,t]=[t,e]);let i=Math.log10(t/e),o=Math.max(1,Math.ceil(i*n)),r=[];for(let a=0;a<=o;a++)r.push(e*Math.pow(10,a/n));let s=r[r.length-1];return(s==null||s<t*(1-Hn))&&r.push(t),r}function WM(e,t,n,i,o){let r=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);if(r>=0){let a=e[r];if(!a)throw new Error("Matrix row missing while stamping");a[r]=a[r]?.add(o)??o}if(s>=0){let a=e[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.add(o)??o}if(r>=0&&s>=0){let a=e[r],c=e[s];if(!a||!c)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.sub(o)??qe.from(0,0).sub(o),c[r]=c[r]?.sub(o)??qe.from(0,0).sub(o)}}function jSt(e,t,n,i,o){let r=n.matrixIndexOfNode(i.n1),s=n.matrixIndexOfNode(i.n2),a=i.index,c=qe.from(1,0);if(r>=0){let u=e[r];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.add(c)??c}if(s>=0){let u=e[s];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.sub(c)??qe.from(0,0).sub(c)}let l=e[a];if(!l)throw new Error("Branch row missing while stamping voltage source");r>=0&&(l[r]=l[r]?.add(c)??c),s>=0&&(l[s]=l[s]?.sub(c)??qe.from(0,0).sub(c)),t[a]=(t[a]??qe.from(0,0)).add(o)}function BSt(e){var d,_,y,g;if(!e.analyses.ac)return null;let{mode:t,N:n,f1:i,f2:o}=e.analyses.ac,r=e.nodes.count()-1,s=e.V.length,a=r+s,c=t==="dec"?$St(i,o,n):(()=>{let x=[],w=Math.max(2,n),S=(o-i)/(w-1);for(let T=0;T<w;T++)x.push(i+T*S);return x})(),l={};e.nodes.rev.forEach((x,w)=>{w!==0&&(l[x]=[])});let u={},h=2*Math.PI;for(let x of c){let w=Array.from({length:a},()=>Array.from({length:a},()=>qe.from(0,0))),S=Array.from({length:a},()=>qe.from(0,0));for(let I of e.R){if(I.R<=0)throw new Error(`R ${I.name} must be > 0`);let E=qe.from(1/I.R,0);WM(w,e.nodes,I.n1,I.n2,E)}for(let I of e.C){let E=qe.from(0,h*x*I.C);WM(w,e.nodes,I.n1,I.n2,E)}for(let I of e.L){let E=qe.from(0,h*x*I.L),M=E.abs()<Hn?qe.from(0,0):qe.from(1,0).div(E);WM(w,e.nodes,I.n1,I.n2,M)}for(let I of e.V){let E=qe.fromPolar(I.acMag||0,I.acPhaseDeg||0);jSt(w,S,e.nodes,I,E)}let T=DSt(w,S);for(let I=1;I<e.nodes.count();I++){let E=I-1,M=e.nodes.rev[I];if(!M)continue;let k=l[M];k&&k.push(T[E]??qe.from(0,0))}for(let I of e.R){let E=I.n1===0?qe.from(0,0):T[I.n1-1]??qe.from(0,0),M=I.n2===0?qe.from(0,0):T[I.n2-1]??qe.from(0,0),N=qe.from(1/I.R,0).mul(E.sub(M));(u[d=I.name]||(u[d]=[])).push(N)}for(let I of e.C){let E=I.n1===0?qe.from(0,0):T[I.n1-1]??qe.from(0,0),M=I.n2===0?qe.from(0,0):T[I.n2-1]??qe.from(0,0),N=qe.from(0,h*x*I.C).mul(E.sub(M));(u[_=I.name]||(u[_]=[])).push(N)}for(let I of e.L){let E=I.n1===0?qe.from(0,0):T[I.n1-1]??qe.from(0,0),M=I.n2===0?qe.from(0,0):T[I.n2-1]??qe.from(0,0),k=qe.from(0,h*x*I.L),A=(k.abs()<Hn?qe.from(0,0):qe.from(1,0).div(k)).mul(E.sub(M));(u[y=I.name]||(u[y]=[])).push(A)}for(let I of e.V){let E=T[I.index]??qe.from(0,0);(u[g=I.name]||(u[g]=[])).push(E)}}return{freqs:c,nodeVoltages:l,elementCurrents:u}}function YSt(e,t){let n=e.length;for(let o=0;o<n;o++){let r=e[o],s=t[o];if(!r||s==null)throw new Error("Matrix dimensions mismatch");let a=r.slice();a.push(s),e[o]=a}for(let o=0;o<n;o++){let r=o,s=e[o];if(!s)throw new Error("Matrix row missing");let a=Math.abs(s[o]??0);for(let u=o+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=Math.abs(h[o]??0);d>a&&(a=d,r=u)}if(a<Hn)throw new Error("Singular matrix (real)");if(r!==o){let u=e[o];e[o]=e[r],e[r]=u}let c=e[o];if(!c)throw new Error("Pivot row missing");let l=c[o];if(l==null)throw new Error("Zero pivot encountered");for(let u=o+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[o];if(d==null)continue;let _=d/l;if(!(Math.abs(_)<Hn))for(let y=o;y<=n;y++){let g=h[y],x=c[y];g==null||x==null||(h[y]=g-_*x)}}}let i=new Array(n).fill(0);for(let o=n-1;o>=0;o--){let r=e[o];if(!r)throw new Error("Matrix row missing");let s=r[n];if(s==null)throw new Error("Augmented column missing");for(let c=o+1;c<n;c++){let l=r[c],u=i[c];l==null||u==null||(s-=l*u)}let a=r[o];if(a==null)throw new Error("Zero pivot on back-substitution");i[o]=s/a}return i}function _m(e,t,n,i,o){let r=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);if(r>=0){let a=e[r];if(!a)throw new Error("Matrix row missing while stamping");a[r]=(a[r]??0)+o}if(s>=0){let a=e[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)+o}if(r>=0&&s>=0){let a=e[r],c=e[s];if(!a||!c)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)-o,c[r]=(c[r]??0)-o}}function ZM(e,t,n,i,o){let r=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);r>=0&&(e[r]=(e[r]??0)-o),s>=0&&(e[s]=(e[s]??0)+o)}function XSt(e,t,n,i,o){let r=n.matrixIndexOfNode(i.n1),s=n.matrixIndexOfNode(i.n2),a=i.index;if(r>=0){let l=e[r];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)+1}if(s>=0){let l=e[s];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)-1}let c=e[a];if(!c)throw new Error("Branch row missing while stamping voltage source");r>=0&&(c[r]=(c[r]??0)+1),s>=0&&(c[s]=(c[s]??0)-1),t[a]=(t[a]??0)+o}function VSt(e){var _,y,g,x,w,S;if(!e.analyses.tran)return null;let{dt:t,tstop:n}=e.analyses.tran,i=t>Hn?t:Math.max(n/1e3,Hn),o=Math.max(1,Math.ceil(n/Math.max(i,Hn))),r=o>0?n/o:n,s=e.nodes.count()-1,a=e.V.length,c=s+a,l=[],u={};e.nodes.rev.forEach((T,I)=>{I!==0&&(u[T]=[])});let h={},d=0;for(let T=0;T<=o;T++,d=T*r){l.push(d);let I=new Array(c).fill(0);for(let E=0;E<20;E++){let M=Array.from({length:c},()=>new Array(c).fill(0)),k=new Array(c).fill(0);for(let R of e.R){let $=1/R.R;_m(M,e.nodes,R.n1,R.n2,$)}for(let R of e.C){let $=R.C/Math.max(r,Hn);_m(M,e.nodes,R.n1,R.n2,$);let j=-$*R.vPrev;ZM(k,e.nodes,R.n1,R.n2,j)}for(let R of e.L){let $=Math.max(r,Hn)/R.L;_m(M,e.nodes,R.n1,R.n2,$),ZM(k,e.nodes,R.n1,R.n2,R.iPrev)}for(let R of e.S){let $=R.model;if(!$)continue;let j=R.isOn?$.Ron:$.Roff,X=1/Math.max(Math.abs(j),Hn);_m(M,e.nodes,R.n1,R.n2,X)}for(let R of e.V){let $=R.waveform?R.waveform(d):R.dc||0;XSt(M,k,e.nodes,R,$)}let N=.02585;for(let R of e.D){let $=R.model;if(!$)continue;let{nPlus:j,nMinus:H}=R,X=e.nodes.matrixIndexOfNode(j),G=e.nodes.matrixIndexOfNode(H),tt=j===0?0:I[X]??0,Q=H===0?0:I[G]??0,V=tt-Q,rt=E===0?R.vdPrev:V,et=$.N*N,J=rt;rt>.8&&(J=.8),rt<-1&&(J=-1);let pt=Math.exp(J/et),ht=$.Is*(pt-1),St=Math.max($.Is/et*pt,1e-12),wt=ht-St*J;_m(M,e.nodes,j,H,St),ZM(k,e.nodes,j,H,wt)}I=YSt(M,k);let A=!1;for(let R of e.S){let $=R.model;if(!$)continue;let j=R.ncPos===0?0:I[R.ncPos-1]??0,H=R.ncNeg===0?0:I[R.ncNeg-1]??0,X=j-H,G=R.isOn;R.isOn?X<$.Voff&&(G=!1):X>$.Von&&(G=!0),G!==R.isOn&&(R.isOn=G,A=!0)}if(!A||E===19)break}for(let E=1;E<e.nodes.count();E++){let M=E-1,k=e.nodes.rev[E];if(!k)continue;let N=u[k];N&&N.push(I[M]??0)}for(let E of e.R){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0,N=(M-k)/E.R;(h[_=E.name]||(h[_]=[])).push(N)}for(let E of e.C){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0,N=E.C*(M-k-E.vPrev)/Math.max(r,Hn);(h[y=E.name]||(h[y]=[])).push(N)}for(let E of e.L){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0,A=Math.max(r,Hn)/E.L*(M-k)+E.iPrev;(h[g=E.name]||(h[g]=[])).push(A)}for(let E of e.V){let M=I[E.index]??0;(h[x=E.name]||(h[x]=[])).push(M)}for(let E of e.S){let M=E.model;if(!M)continue;let k=E.n1===0?0:I[E.n1-1]??0,N=E.n2===0?0:I[E.n2-1]??0,A=E.isOn?M.Ron:M.Roff,R=Math.max(Math.abs(A),Hn),$=(k-N)/R;(h[w=E.name]||(h[w]=[])).push($)}for(let E of e.D){if(!E.model)continue;let{nPlus:M,nMinus:k,model:N}=E,A=M===0?0:I[M-1]??0,R=k===0?0:I[k-1]??0,$=A-R,H=N.N*.02585,X=Math.exp($/H),G=N.Is*(X-1);(h[S=E.name]||(h[S]=[])).push(G)}for(let E of e.C){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0;E.vPrev=M-k}for(let E of e.L){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0,N=Math.max(r,Hn)/E.L;E.iPrev=N*(M-k)+E.iPrev}for(let E of e.D){let M=E.nPlus===0?0:I[E.nPlus-1]??0,k=E.nMinus===0?0:I[E.nMinus-1]??0;E.vdPrev=M-k}}if(e.probes.tran.length>0){let T={},I=e.probes.tran.map(E=>E.toUpperCase());for(let E in u)I.includes(E.toUpperCase())&&(T[E]=u[E]);return{times:l,nodeVoltages:T,elementCurrents:h}}return{times:l,nodeVoltages:u,elementCurrents:h}}function SX(e){let t=zSt(e),n=BSt(t),i=VSt(t);return{circuit:t,ac:n,tran:i}}function wX(e,t,n){if(!e||!t.analyses.tran)return[];let{dt:i,tstop:o}=t.analyses.tran,{times:r,nodeVoltages:s}=e,a=[];for(let c in s){let l=s[c];a.push({type:"simulation_transient_voltage_graph",simulation_transient_voltage_graph_id:`stvg_${n}_${c}`,simulation_experiment_id:n,timestamps_ms:r.map(u=>u*1e3),voltage_levels:l,time_per_step:i*1e3,start_time_ms:0,end_time_ms:o*1e3,name:`V(${c})`})}return a}ji();ke();ji();ke();ke();vt();ke();ke();Qr();ke();ji();ke();ji();ke();ke();ji();ke();function PX(e,t,n,i){return Math.sqrt((n-e)**2+(i-t)**2)}var HSt=e=>{let t=e.filter(r=>r.type==="pcb_port"),n=e.filter(r=>r.type==="pcb_smtpad"),i=e.filter(r=>r.type==="pcb_trace");function o(r,s={}){let a=s.traceWidth||0,c=t.find(l=>PX(l.x,l.y,r.x,r.y)<.01);if(c)return c.pcb_port_id;if(s.isFirstOrLastPoint){let l=n.find(u=>{if(u.shape==="rect")return Math.abs(r.x-u.x)<u.width/2+a/2&&Math.abs(r.y-u.y)<u.height/2+a/2;if(u.shape==="circle")return PX(r.x,r.y,u.x,u.y)<u.radius});if(l)return l.pcb_port_id??null}return null}for(let r of i)for(let s=0;s<r.route.length;s++){let a=r.route[s],c=s===0||s===r.route.length-1;if(a.route_type==="wire"){if(!a.start_pcb_port_id&&s===0){let l=o(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.start_pcb_port_id=l)}if(!a.end_pcb_port_id&&s===r.route.length-1){let l=o(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.end_pcb_port_id=l)}}}};function TX(e){HSt(e);let t=e.filter(s=>s.type==="source_trace"),n=e.filter(s=>s.type==="pcb_port"),i=[],o=$i(e),r=new Map;for(let s of n)r.set(s.source_port_id,s);for(let s of t){let a=s.connected_source_port_ids;if(a.length<2)continue;let c=[],l=[];for(let y of a){let g=r.get(y);g?c.push(g):l.push(y)}if(c.length<2)continue;let u=c[0],h=o.getNetConnectedToId(u.pcb_port_id);o.getIdsConnectedToNet(h).filter(y=>e.some(g=>g.type==="pcb_trace"&&("pcb_trace_id"in g&&g.pcb_trace_id===y||"route_id"in g&&g.route_id===y))).length===0&&new Set(c.map(g=>g.pcb_component_id)).size>1&&i.push({type:"pcb_port_not_connected_error",message:`pcb_port_not_connected_error: Pcb ports [${c.map(g=>g.pcb_port_id).join(", ")}] are not connected together through the same net.`,error_type:"pcb_port_not_connected_error",pcb_port_ids:c.map(g=>g.pcb_port_id),pcb_component_ids:c.map(g=>g.pcb_component_id),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${s.source_trace_id}`})}return i}var GSt=class{constructor({objects:e,getBounds:t,getId:n,CELL_SIZE:i}){P(this,"buckets");P(this,"objectsById");P(this,"getBounds");P(this,"getId");P(this,"CELL_SIZE",.4);P(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=t,this.getId=n??(()=>this._getNextId()),this.CELL_SIZE=i??this.CELL_SIZE;for(let o of e)this.addObject(o)}_getNextId(){return`${this._idCounter++}`}addObject(e){let t=this.getBounds(e),n=this.getId(e),i={...e,spatialIndexId:n};this.objectsById.set(n,i);let o=Math.floor(t.minX/this.CELL_SIZE),r=Math.floor(t.minY/this.CELL_SIZE),s=Math.floor(t.maxX/this.CELL_SIZE),a=Math.floor(t.maxY/this.CELL_SIZE);for(let c=o;c<=s;c++)for(let l=r;l<=a;l++){let u=`${c}x${l}`,h=this.buckets.get(u);h?h.push(i):this.buckets.set(u,[i])}}removeObject(e){let t=this.objectsById.get(e);if(!t)return!1;this.objectsById.delete(e);let n=this.getBounds(t),i=Math.floor(n.minX/this.CELL_SIZE),o=Math.floor(n.minY/this.CELL_SIZE),r=Math.floor(n.maxX/this.CELL_SIZE),s=Math.floor(n.maxY/this.CELL_SIZE);for(let a=i;a<=r;a++)for(let c=o;c<=s;c++){let l=`${a}x${c}`,u=this.buckets.get(l);if(u){let h=u.findIndex(d=>d.spatialIndexId===e);h!==-1&&(u.splice(h,1),u.length===0&&this.buckets.delete(l))}}return!0}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getObjectsInBounds(e,t=0){let n=[],i=new Set,o=Math.floor((e.minX-t)/this.CELL_SIZE),r=Math.floor((e.minY-t)/this.CELL_SIZE),s=Math.floor((e.maxX+t)/this.CELL_SIZE),a=Math.floor((e.maxY+t)/this.CELL_SIZE);for(let c=o;c<=s;c++)for(let l=r;l<=a;l++){let u=`${c}x${l}`,h=this.buckets.get(u)||[];for(let d of h){let _=d.spatialIndexId;i.has(_)||(i.add(_),n.push(d))}}return n}},ym=e=>e.type==="pcb_trace_segment"?{minX:Math.min(e.x1,e.x2),minY:Math.min(e.y1,e.y2),maxX:Math.max(e.x1,e.x2),maxY:Math.max(e.y1,e.y2)}:nh([e]),KM=.1,USt=.15;var qSt=.2,WSt=.3,gm=.005;function ZSt(e){let t=new Set;for(let n of e.route)n.route_type==="wire"&&(n.start_pcb_port_id&&t.add(n.start_pcb_port_id),n.end_pcb_port_id&&t.add(n.end_pcb_port_id));return Array.from(t)}function JM(e){let t=new Set;for(let n of e)for(let i of ZSt(n))t.add(i);return Array.from(t)}var KSt=(e,t)=>{let n={x:e.x1,y:e.y1},i={x:e.x2,y:e.y2},o={x:t.x1,y:t.y1},r={x:t.x2,y:t.y2},s={x:i.x-n.x,y:i.y-n.y},a={x:r.x-o.x,y:r.y-o.y},c=s.x*s.x+s.y*s.y,l=a.x*a.x+a.y*a.y;if(c===0||l===0){if(c===0&&l===0)return{x:(n.x+o.x)/2,y:(n.y+o.y)/2};if(c===0){let $=ds(((n.x-o.x)*a.x+(n.y-o.y)*a.y)/l,0,1),j={x:o.x+$*a.x,y:o.y+$*a.y};return{x:(n.x+j.x)/2,y:(n.y+j.y)/2}}let A=ds(((o.x-n.x)*s.x+(o.y-n.y)*s.y)/c,0,1),R={x:n.x+A*s.x,y:n.y+A*s.y};return{x:(R.x+o.x)/2,y:(R.y+o.y)/2}}let u={x:n.x-o.x,y:n.y-o.y},h=s.x*s.x+s.y*s.y,d=s.x*a.x+s.y*a.y,_=s.x*u.x+s.y*u.y,y=a.x*a.x+a.y*a.y,g=a.x*u.x+a.y*u.y,x=h*y-d*d;if(x<1e-10)return JSt(n,i,o,r,s,a,c,l);let w=(d*g-y*_)/x,S=(h*g-d*_)/x;w=ds(w,0,1),S=ds(S,0,1),S=(w*d+g)/y,S=ds(S,0,1),w=(S*d-_)/h,w=ds(w,0,1);let T={x:n.x+w*s.x,y:n.y+w*s.y},I={x:o.x+S*a.x,y:o.y+S*a.y},E=T.x-I.x,M=T.y-I.y,k=Math.sqrt(E*E+M*M);return{x:(T.x+I.x)/2,y:(T.y+I.y)/2}},JSt=(e,t,n,i,o,r,s,a)=>{let c=((n.x-e.x)*o.x+(n.y-e.y)*o.y)/s;c=ds(c,0,1);let l={x:e.x+c*o.x,y:e.y+c*o.y},u=((i.x-e.x)*o.x+(i.y-e.y)*o.y)/s;u=ds(u,0,1);let h={x:e.x+u*o.x,y:e.y+u*o.y},d=((e.x-n.x)*r.x+(e.y-n.y)*r.y)/a;d=ds(d,0,1);let _={x:n.x+d*r.x,y:n.y+d*r.y},y=((t.x-n.x)*r.x+(t.y-n.y)*r.y)/a;y=ds(y,0,1);let g={x:n.x+y*r.x,y:n.y+y*r.y},w=[{pointA:l,pointB:n,distance:Math.sqrt((l.x-n.x)**2+(l.y-n.y)**2)},{pointA:h,pointB:i,distance:Math.sqrt((h.x-i.x)**2+(h.y-i.y)**2)},{pointA:e,pointB:_,distance:Math.sqrt((e.x-_.x)**2+(e.y-_.y)**2)},{pointA:t,pointB:g,distance:Math.sqrt((t.x-g.x)**2+(t.y-g.y)**2)}].reduce((S,T)=>T.distance<S.distance?T:S);return{x:(w.pointA.x+w.pointB.x)/2,y:(w.pointA.y+w.pointB.y)/2}},ds=(e,t,n)=>Math.max(t,Math.min(n,e)),QSt=e=>{if(e.type==="pcb_via"||e.type==="pcb_plated_hole"&&e.shape==="circle")return e.outer_diameter/2;if(e.type==="pcb_hole"&&e.hole_shape==="circle")return e.hole_diameter/2;if(e.type==="pcb_smtpad"&&e.shape==="circle")return e.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(e)}`)},IX=(e,t)=>{let n={x:e.x1,y:e.y1},i={x:e.x2,y:e.y2},o=t.minX,r=t.minY,s=t.maxX,a=t.maxY;if(n.x===i.x&&n.y===i.y){let N=Math.max(o,Math.min(s,n.x)),A=Math.max(r,Math.min(a,n.y));return N===n.x&&A===n.y?{x:n.x,y:n.y}:{x:N,y:A}}let c=i.x-n.x,l=i.y-n.y,u=c!==0?(o-n.x)/c:Number.NEGATIVE_INFINITY,h=c!==0?(s-n.x)/c:Number.POSITIVE_INFINITY,d=l!==0?(r-n.y)/l:Number.NEGATIVE_INFINITY,_=l!==0?(a-n.y)/l:Number.POSITIVE_INFINITY,y=Math.max(Math.min(u,h),Math.min(d,_)),g=Math.min(Math.max(u,h),Math.max(d,_));if(y<=g&&g>=0&&y<=1){let N=Math.max(0,Math.min(1,y));return{x:n.x+N*c,y:n.y+N*l}}let x={x:Math.max(o,Math.min(s,n.x)),y:Math.max(r,Math.min(a,n.y))},w={x:Math.max(o,Math.min(s,i.x)),y:Math.max(r,Math.min(a,i.y))},S=(x.x-n.x)**2+(x.y-n.y)**2,T=(w.x-i.x)**2+(w.y-i.y)**2,I=[{start:{x:o,y:r},end:{x:s,y:r}},{start:{x:s,y:r},end:{x:s,y:a}},{start:{x:s,y:a},end:{x:o,y:a}},{start:{x:o,y:a},end:{x:o,y:r}}],E=Math.min(S,T),M=S<=T?x:w,k=(N,A,R)=>Math.max(A,Math.min(R,N));for(let N of I){let A={x:i.x-n.x,y:i.y-n.y},R={x:N.end.x-N.start.x,y:N.end.y-N.start.y},$={x:n.x-N.start.x,y:n.y-N.start.y},j=A.x*A.x+A.y*A.y,H=A.x*R.x+A.y*R.y,X=A.x*$.x+A.y*$.y,G=R.x*R.x+R.y*R.y,tt=R.x*$.x+R.y*$.y,Q=j*G-H*H;if(Math.abs(Q)<1e-10)continue;let V=(H*tt-G*X)/Q,rt=(j*tt-H*X)/Q;V=k(V,0,1),rt=k(rt,0,1);let et={x:n.x+V*A.x,y:n.y+V*A.y},J={x:N.start.x+rt*R.x,y:N.start.y+rt*R.y},pt=et.x-J.x,ht=et.y-J.y,St=pt*pt+ht*ht;St<E&&(E=St,M={x:(et.x+J.x)/2,y:(et.y+J.y)/2})}return M};function twt(e){return e.type==="pcb_trace_segment"?[e.layer]:e.type==="pcb_smtpad"?[e.layer]:e.type==="pcb_plated_hole"?Array.isArray(e.layers)?e.layers:[...Cp]:e.type==="pcb_hole"?[...Cp]:e.type==="pcb_via"?Array.isArray(e.layers)?e.layers:[...Cp]:e.type==="pcb_keepout"?Array.isArray(e.layers)?e.layers:[]:[]}function MX(e,{connMap:t}={}){let n=[];t??(t=$i(e));let o=Ge(e).pcb_trace.list().flatMap(y=>{let g=[];for(let x=0;x<y.route.length-1;x++){let w=y.route[x],S=y.route[x+1];w.route_type==="wire"&&S.route_type==="wire"&&w.layer===S.layer&&g.push({type:"pcb_trace_segment",pcb_trace_id:y.pcb_trace_id,_pcbTrace:y,thickness:"width"in w?w.width:"width"in S?S.width:USt,layer:w.layer,x1:w.x,y1:w.y,x2:S.x,y2:S.y})}return g}),r=Ge(e).pcb_smtpad.list(),s=Ge(e).pcb_plated_hole.list(),a=Ge(e).pcb_hole.list(),c=Ge(e).pcb_via.list(),l=Ge(e).pcb_keepout.list(),u=[...o,...r,...s,...a,...c,...l],h=new GSt({objects:u,getBounds:ym}),d=y=>pr(e,y),_=new Set;for(let y of o){let g=KM,x=ym(y),w=h.getObjectsInBounds(x,g+y.thickness/2);if(!(y.x1===y.x2&&y.y1===y.y2))for(let S of w){if(!twt(S).includes(y.layer))continue;if(S.type==="pcb_trace_segment"){let M=S;if(y.layer!==M.layer||t.areIdsConnected(y.pcb_trace_id,M.pcb_trace_id))continue;let k=th({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},{x:M.x1,y:M.y1},{x:M.x2,y:M.y2})-y.thickness/2-M.thickness/2;if(k>KM-gm)continue;let N=`overlap_${y.pcb_trace_id}_${M.pcb_trace_id}`,A=`overlap_${M.pcb_trace_id}_${y.pcb_trace_id}`;if(_.has(N)||_.has(A))continue;_.add(N),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${d(M.pcb_trace_id)} ${k<0?"(accidental contact)":`(gap: ${k.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:N,pcb_component_ids:[],center:KSt(y,M),pcb_port_ids:JM([y._pcbTrace,M._pcbTrace])});continue}let T=is(S);if(t.areIdsConnected(y.pcb_trace_id,"pcb_trace_id"in S?S.pcb_trace_id:T))continue;if(S.type==="pcb_via"||S.type==="pcb_plated_hole"&&S.shape==="circle"||S.type==="pcb_hole"||S.type==="pcb_smtpad"&&S.shape==="circle"){let M=QSt(S),N=ob({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},{x:S.x,y:S.y,radius:M})-y.thickness/2;if(N>KM-gm)continue;let A=`overlap_${y.pcb_trace_id}_${T}`;if(_.has(A))continue;_.add(A),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${S.type} "${d(is(S))}" ${N<0?"(accidental contact)":`(gap: ${N.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,center:IX(y,ym(S)),source_trace_id:"",pcb_trace_error_id:A,pcb_component_ids:["pcb_component_id"in S?S.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...JM([y._pcbTrace]),"pcb_port_id"in S?S.pcb_port_id:void 0].filter(Boolean)})}let E=wf({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},ym(S))-y.thickness/2;if(E+gm<g){let M=`overlap_${y.pcb_trace_id}_${T}`;if(_.has(M))continue;_.add(M),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${S.type} "${d(is(S))}" ${E<0?"(accidental contact)":`(gap: ${E.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:M,pcb_component_ids:["pcb_component_id"in S?S.pcb_component_id:void 0].filter(Boolean),center:IX(y,ym(S)),pcb_port_ids:[...JM([y._pcbTrace]),"pcb_port_id"in S?S.pcb_port_id:void 0].filter(Boolean)})}}}return n}function CX(e){return e.area()>=0}function EX({center:e,size:t,rotationDeg:n=0}){let i=e.x,o=e.y,r=t.width/2,s=t.height/2,a=[new hs(i-r,o-s),new hs(i+r,o-s),new hs(i+r,o+s),new hs(i-r,o+s)],c=new lm(a);if(n){let l=Yg(n,i,o),u=a.map(h=>{let d=yn(l,{x:h.x,y:h.y});return new hs(d.x,d.y)});c=new lm(u)}return CX(c)||c.reverse(),c}function ewt({board:e}){if(e.outline&&e.outline.length>0){let t=e.outline.map(i=>new hs(i.x,i.y)),n=new lm(t);return CX(n)||n.reverse(),n}return e.center&&typeof e.width=="number"&&typeof e.height=="number"?EX({center:e.center,size:{width:e.width,height:e.height},rotationDeg:0}):null}function nwt({circuitJson:e,component:t}){if(t.source_component_id){let n=e.find(i=>i.type==="source_component"&&i.source_component_id===t.source_component_id);if(n&&"name"in n&&n.name)return n.name}return pr(e,t.pcb_component_id)||"Unknown"}function iwt(e,t,n,i,o,r){let s=new hs(n.x,n.y);if(!t.contains(s)){let g=t.distanceTo(s);return Array.isArray(g)?g[0]:Number(g)||0}let a=i/2,c=o/2,l=[{x:n.x-a,y:n.y-c},{x:n.x+a,y:n.y-c},{x:n.x+a,y:n.y+c},{x:n.x-a,y:n.y+c}],u=[];for(let g=0;g<4;g++){let x=(g+1)%4;u.push({x:(l[g].x+l[x].x)/2,y:(l[g].y+l[x].y)/2})}let h=Yg(r,n.x,n.y),d=g=>{let x=yn(h,g);return new hs(x.x,x.y)},_=l.concat(u).map(d),y=0;for(let g of _)if(!t.contains(g)){let x=t.distanceTo(g),w=Array.isArray(x)?x[0]:Number(x)||0;w>y&&(y=w)}if(y>0)return y;try{let g=PM.intersect(e,t),x=0;g?Array.isArray(g)?x=g.reduce((S,T)=>S+(typeof T.area=="function"?T.area():0),0):typeof g.area=="function"?x=g.area():x=0:x=0;let w=e.area();if(x>0&&x<w){let S=1-x/w,T=Math.abs(i),I=Math.abs(o);return Math.min(T,I)*S}else return .1}catch{return .1}}function NX(e){let t=e.find(r=>r.type==="pcb_board");if(!t)return[];let n=ewt({board:t});if(!n)return[];let i=e.filter(r=>r.type==="pcb_component");if(i.length===0)return[];let o=[];for(let r of i){if(!r.center||typeof r.width!="number"||typeof r.height!="number"||r.width<=0||r.height<=0)continue;let s=EX({center:r.center,size:{width:r.width,height:r.height},rotationDeg:r.rotation||0});if(s.area()===0||n.contains(s))continue;let c=iwt(s,n,r.center,r.width,r.height,r.rotation||0),l=nwt({circuitJson:e,component:r}),u=Math.round(c*100)/100;o.push({type:"pcb_component_outside_board_error",error_type:"pcb_component_outside_board_error",pcb_component_outside_board_error_id:`pcb_component_outside_board_${r.pcb_component_id}`,message:`Component ${l} (${r.pcb_component_id}) extends outside board boundaries by ${u}mm`,pcb_component_id:r.pcb_component_id,pcb_board_id:t.pcb_board_id,component_center:r.center,component_bounds:{min_x:s.box.xmin,max_x:s.box.xmax,min_y:s.box.ymin,max_y:s.box.ymax},subcircuit_id:r.subcircuit_id,source_component_id:r.source_component_id})}return o}function owt(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function kX(e,{connMap:t,minSpacing:n=qSt}={}){let i=e.filter(s=>s.type==="pcb_via");if(i.length<2)return[];t??(t=$i(e));let o=[],r=new Set;for(let s=0;s<i.length;s++)for(let a=s+1;a<i.length;a++){let c=i[s],l=i[a];if(!t.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=owt(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+gm>=n)continue;let h=[c.pcb_via_id,l.pcb_via_id].sort().join("_");r.has(h)||(r.add(h),o.push({type:"pcb_via_clearance_error",pcb_error_id:`same_net_vias_close_${h}`,message:`Vias ${pr(e,c.pcb_via_id)} and ${pr(e,l.pcb_via_id)} are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:n,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return o}function rwt(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function AX(e,{connMap:t,minSpacing:n=WSt}={}){let i=e.filter(s=>s.type==="pcb_via");if(i.length<2)return[];t??(t=$i(e));let o=[],r=new Set;for(let s=0;s<i.length;s++)for(let a=s+1;a<i.length;a++){let c=i[s],l=i[a];if(t.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=rwt(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+gm>=n)continue;let h=[c.pcb_via_id,l.pcb_via_id].sort().join("_");r.has(h)||(r.add(h),o.push({type:"pcb_via_clearance_error",pcb_error_id:`different_net_vias_close_${h}`,message:`Vias ${pr(e,c.pcb_via_id)} and ${pr(e,l.pcb_via_id)} from different nets are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:n,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return o}var swt=.2;function awt(e){if(e.outline&&e.outline.length>0)return e.outline.map(t=>({x:t.x,y:t.y}));if(e.center&&typeof e.width=="number"&&typeof e.height=="number"){let t=e.center.x,n=e.center.y,i=e.width/2,o=e.height/2;return[{x:t-i,y:n-o},{x:t+i,y:n-o},{x:t+i,y:n+o},{x:t-i,y:n+o}]}return null}function RX(e,t={}){let n=[],i=t.margin??swt,o=e.find(a=>a.type==="pcb_board");if(!o)return n;let r=awt(o);if(!r)return n;let s=Ge(e).pcb_trace.list();for(let a of s)if(!(a.route.length<2))for(let c=0;c<a.route.length-1;c++){let l=a.route[c],u=a.route[c+1];if(l.route_type!=="wire"||u.route_type!=="wire")continue;let h="width"in l?l.width:"width"in u?u.width:.1,d={x:l.x,y:l.y},_={x:u.x,y:u.y},y=1/0;for(let x=0;x<r.length;x++){let w=r[x],S=r[(x+1)%r.length],T=th(d,_,w,S);T<y&&(y=T)}let g=h/2+i;if(y<g){let x={type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:`trace_too_close_to_board_${a.pcb_trace_id}_segment_${c}`,message:`Trace too close to board edge (${y.toFixed(3)}mm < ${g.toFixed(3)}mm required, margin: ${i}mm)`,pcb_trace_id:a.pcb_trace_id,source_trace_id:a.source_trace_id||"",center:{x:(d.x+_.x)/2,y:(d.y+_.y)/2},pcb_component_ids:[],pcb_port_ids:[]};n.push(x)}}return n}function cwt(e,t){let n=nh([e]),i=nh([t]);return ic(n,i)}function OX(e){let t=[],n=$i(e),i=Ge(e).pcb_smtpad.list(),o=Ge(e).pcb_plated_hole.list(),r=Ge(e).pcb_hole.list(),s=new Map;for(let c of i){let l=c.pcb_component_id||`standalone_pad_${is(c)}`;s.has(l)||s.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),s.get(l).elements.push(c)}for(let c of o){let l=c.pcb_component_id||`standalone_plated_hole_${is(c)}`;s.has(l)||s.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),s.get(l).elements.push(c)}for(let c of r){let l=`standalone_hole_${is(c)}`;s.set(l,{component_id:l,elements:[c],bounds:{minX:0,minY:0,maxX:0,maxY:0}})}for(let[c,l]of s)l.elements.length>0&&(l.bounds=nh(l.elements));let a=Array.from(s.values());for(let c=0;c<a.length;c++)for(let l=c+1;l<a.length;l++){let u=a[c],h=a[l];if(ic(u.bounds,h.bounds))for(let d of u.elements)for(let _ of h.elements){let y=is(d),g=is(_);if(!(d.type==="pcb_smtpad"&&_.type==="pcb_smtpad"&&n.areIdsConnected(y,g))&&cwt(d,_)){let x={type:"pcb_footprint_overlap_error",pcb_error_id:`pcb_footprint_overlap_${y}_${g}`,error_type:"pcb_footprint_overlap_error",message:`PCB component ${d.type} "${y}" overlaps with ${_.type} "${g}"`};(d.type==="pcb_smtpad"||_.type==="pcb_smtpad")&&(x.pcb_smtpad_ids=[],d.type==="pcb_smtpad"&&x.pcb_smtpad_ids.push(y),_.type==="pcb_smtpad"&&x.pcb_smtpad_ids.push(g)),(d.type==="pcb_plated_hole"||_.type==="pcb_plated_hole")&&(x.pcb_plated_hole_ids=[],d.type==="pcb_plated_hole"&&x.pcb_plated_hole_ids.push(y),_.type==="pcb_plated_hole"&&x.pcb_plated_hole_ids.push(g)),(d.type==="pcb_hole"||_.type==="pcb_hole")&&(x.pcb_hole_ids=[],d.type==="pcb_hole"&&x.pcb_hole_ids.push(y),_.type==="pcb_hole"&&x.pcb_hole_ids.push(g)),t.push(x)}}}return t}var QM=[{value:1e12,symbol:"T"},{value:1e9,symbol:"G"},{value:1e6,symbol:"M"},{value:1e3,symbol:"k"},{value:1,symbol:""},{value:.001,symbol:"m"},{value:1e-6,symbol:"\xB5"},{value:1e-9,symbol:"n"},{value:1e-12,symbol:"p"}];function ni(e){if(e==null)return"";if(e===0)return"0";let t=Math.abs(e),n=QM.find(r=>{let s=t/r.value;return s>=1&&s<1e3})||QM[QM.length-1],o=(e/n.value).toPrecision(3);return o.includes(".")&&!/\.0+$/.test(o)&&(o=o.replace(/0+$/,"")),o=o.replace(/\.0+$/,""),`${o}${n.symbol}`}vt();vt();K();ke();Pf();var lwt=class{constructor(){P(this,"MAX_ITERATIONS",1e5);P(this,"solved",!1);P(this,"failed",!1);P(this,"iterations",0);P(this,"progress",0);P(this,"error",null);P(this,"activeSubSolver");P(this,"failedSubSolvers");P(this,"timeToSolve");P(this,"stats",{});P(this,"_setupDone",!1)}setup(){this._setupDone||(this._setup(),this._setupDone=!0)}_setup(){}step(){if(this._setupDone||this.setup(),!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.constructor.name} error: ${e}`,console.error(this.error),this.failed=!0,e}!this.solved&&this.iterations>=this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>=this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,console.error(this.error),this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}getOutput(){return null}solve(){let e=Date.now();for(;!this.solved&&!this.failed;)this.step();let t=Date.now();this.timeToSolve=t-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};var LX=class extends lwt{constructor(t){super();P(this,"startTimeOfPhase",{});P(this,"endTimeOfPhase",{});P(this,"timeSpentOnPhase",{});P(this,"firstIterationOfPhase",{});P(this,"currentPipelineStepIndex",0);P(this,"inputProblem");P(this,"pipelineOutputs",{});this.inputProblem=t,this.MAX_ITERATIONS=1e6}_step(){let t=this.pipelineDef[this.currentPipelineStepIndex];if(!t){this.solved=!0;return}if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){this.endTimeOfPhase[t.solverName]=performance.now(),this.timeSpentOnPhase[t.solverName]=this.endTimeOfPhase[t.solverName]-this.startTimeOfPhase[t.solverName];let i=this.activeSubSolver.getOutput();i!==null&&(this.pipelineOutputs[t.solverName]=i),t.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++}else this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let n=t.getConstructorParams(this);this.activeSubSolver=new t.solverClass(...n),this[t.solverName]=this.activeSubSolver,this.timeSpentOnPhase[t.solverName]=0,this.startTimeOfPhase[t.solverName]=performance.now(),this.firstIterationOfPhase[t.solverName]=this.iterations}solveUntilPhase(t){for(;this.getCurrentPhase().toLowerCase()!==t.toLowerCase()&&(this.step(),!(this.failed||this.solved)););}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}getPhaseProgress(){let t=this.pipelineDef.length;if(t===0)return 1;let n=this.activeSubSolver?.progress??0;return(this.currentPipelineStepIndex+n)/t}getPhaseStats(){let t={};for(let n of this.pipelineDef){let i=this.timeSpentOnPhase[n.solverName]||0,o=this.firstIterationOfPhase[n.solverName]||0,r=this.iterations,s=n.solverName===this.getCurrentPhase()?r-o:0,a=this.currentPipelineStepIndex>this.pipelineDef.findIndex(c=>c.solverName===n.solverName);t[n.solverName]={timeSpent:i,iterations:s,completed:a}}return t}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let t=this.pipelineDef.map((n,i)=>{let r=this[n.solverName]?.visualize();if(!r)return null;for(let s of r.rects??[])s.step=i;for(let s of r.points??[])s.step=i;for(let s of r.circles??[])s.step=i;for(let s of r.texts??[])s.step=i;for(let s of r.lines??[])s.step=i;return r}).filter(Boolean);return t.length===0?{points:[],rects:[],lines:[],circles:[],texts:[]}:t.length===1?t[0]:{points:t.flatMap(n=>n.points||[]),rects:t.flatMap(n=>n.rects||[]),lines:t.flatMap(n=>n.lines||[]),circles:t.flatMap(n=>n.circles||[]),texts:t.flatMap(n=>n.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}computeProgress(){return this.getPhaseProgress()}getStepOutput(t){return this.pipelineOutputs[t]}getAllOutputs(){return{...this.pipelineOutputs}}hasStepOutput(t){return t in this.pipelineOutputs}getSolver(t){return this[t]}};var uwt=e=>{let t=e.board_edge_margin??0;if(e.outline&&e.outline.length>0){let o=new L.Polygon(e.outline.map(r=>L.point(r.x,r.y)));return o.orientation()===L.ORIENTATION.CW&&o.reverse(),o}let{bounds:n}=e,i={minX:n.minX+t,minY:n.minY+t,maxX:n.maxX-t,maxY:n.maxY-t};return i.minX>=i.maxX||i.minY>=i.maxY?new L.Polygon:new L.Polygon(new L.Box(i.minX,i.minY,i.maxX,i.maxY).toPoints())},t4=(e,t=32)=>{let n=[];for(let i=0;i<t;i++){let o=i/t*2*Math.PI;n.push(new L.Point(e.center.x+e.r*Math.cos(o),e.center.y+e.r*Math.sin(o)))}return new L.Polygon(n)},pwt=e=>e.shape==="rect",hwt=e=>e.shape==="trace",dwt=e=>e.shape==="circle",fwt=e=>e.shape==="polygon",mwt=(e,t,n,i)=>{let o=[],{padMargin:r,traceMargin:s,board_edge_margin:a,cutoutMargin:c}=n;if(i&&i.length>0&&a&&a>0){let l=new L.Polygon(i.map(h=>L.point(h.x,h.y)));l.area()<0&&l.reverse();let u=l.vertices;for(let h=0;h<u.length;h++){let d=u[h===0?u.length-1:h-1],_=u[h],y=u[(h+1)%u.length];if(!d||!_||!y)continue;let g=new L.Vector(d,_),x=new L.Vector(_,y),w=g.cross(x),S=new L.Circle(_,a);if(o.push(t4(S)),w<0){let T=new L.Box(_.x-a,_.y-a,_.x+a,_.y+a);o.push(new L.Polygon(T.toPoints()))}}for(let h=0;h<u.length;h++){let d=u[h],_=u[(h+1)%u.length];if(!d||!_)continue;let y=Math.hypot(d.x-_.x,d.y-_.y);if(y===0)continue;let g=a*2,x=(d.x+_.x)/2,w=(d.y+_.y)/2,S=Math.atan2(_.y-d.y,_.x-d.x)*180/Math.PI,T=y/2,I=g/2,E=S*Math.PI/180,M=Math.cos(E),k=Math.sin(E),A=[{x:-T,y:-I},{x:T,y:-I},{x:T,y:I},{x:-T,y:I}].map(R=>({x:x+R.x*M-R.y*k,y:w+R.x*k+R.y*M}));o.push(new L.Polygon(A.map(R=>L.point(R.x,R.y))))}}for(let l of e){if(l.connectivityKey===t)continue;let h=l.connectivityKey.startsWith("hole:")||l.connectivityKey.startsWith("cutout:");if(dwt(l)){let d=h?c??0:r,_=new L.Circle(new L.Point(l.x,l.y),l.radius+d);o.push(t4(_));continue}if(pwt(l)){let d=h?c??0:r,{bounds:_}=l,y=new L.Box(_.minX-d,_.minY-d,_.maxX+d,_.maxY+d);o.push(new L.Polygon(y.toPoints()));continue}if(fwt(l)){let d=h?c??0:0,_=new Set,y=l.points.filter(T=>{let I=`${T.x},${T.y}`;return _.has(I)?!1:(_.add(I),!0)});if(y.length<3)continue;let g=new L.Polygon(y.map(T=>L.point(T.x,T.y)));if(Math.abs(g.area())<1e-9)continue;if(d<=0){o.push(g);continue}g.area()>0&&g.reverse();let x=[],w=g.vertices;for(let T=0;T<w.length;T++){let I=w[T],E=w[(T+1)%w.length],M=L.segment(I,E);if(M.length===0)continue;let k=L.line(M.start,M.end),N=k.norm,A=k.translate(N.multiply(-d));x.push(A)}let S=[];for(let T=0;T<x.length;T++){let I=x[T],E=x[(T+1)%x.length],M=I.intersect(E);M.length>0&&S.push(M[0])}S.length>=3&&o.push(new L.Polygon(S));continue}if(hwt(l)){for(let d of l.segments){let _=new L.Circle(new L.Point(d.x,d.y),l.width/2+s);o.push(t4(_))}for(let d=0;d<l.segments.length-1;d++){let _=l.segments[d],y=l.segments[d+1];if(!_||!y)continue;let g=Math.hypot(_.x-y.x,_.y-y.y);if(g===0)continue;let x=l.width+s*2,w=(_.x+y.x)/2,S=(_.y+y.y)/2,T=Math.atan2(y.y-_.y,y.x-_.x)*180/Math.PI,I=g/2,E=x/2,M=T*Math.PI/180,k=Math.cos(M),N=Math.sin(M),R=[{x:-I,y:-E},{x:I,y:-E},{x:I,y:E},{x:-I,y:E}].map($=>({x:w+$.x*k-$.y*N,y:S+$.x*N+$.y*k}));o.push(new L.Polygon(R.map($=>L.point($.x,$.y))))}continue}}return{polygonsToSubtract:o}},FX=e=>e.edges.map(t=>{let n={x:t.start.x,y:t.start.y};if(t.isArc){let i=Math.tan(t.shape.sweep/4);Math.abs(i)>1e-9&&(n.bulge=i)}return n}),_wt=e=>{let t=[],n=Array.isArray(e)?e:[e];for(let i of n){let o=i.splitToIslands();for(let r of o){if(r.isEmpty())continue;let s=[...r.faces],a=s.find(h=>h.orientation()===L.ORIENTATION.CCW),c=s.filter(h=>h.orientation()===L.ORIENTATION.CW);if(!a)continue;a.reverse();let l=FX(a),u=c.map(h=>(h.reverse(),{vertices:FX(h)}));t.push({outer_ring:{vertices:l},inner_rings:u})}}return t},zX=class extends LX{constructor(t){super(t);P(this,"pipelineDef",[]);this.input=t}getOutput(){let t=[];for(let n of this.input.regionsForPour){let i=uwt(n),o=this.input.pads.filter(c=>c.layer===n.layer),{polygonsToSubtract:r}=mwt(o,n.connectivityKey,{padMargin:n.padMargin,traceMargin:n.traceMargin,board_edge_margin:n.board_edge_margin,cutoutMargin:n.cutout_margin},n.outline),s=i;for(let c of r){let l=Array.isArray(s)?s:[s],u=[];for(let h of l){let d=L.BooleanOperations.subtract(h,c);d&&(Array.isArray(d)?u.push(...d.filter(_=>!_.isEmpty())):d.isEmpty()||u.push(d))}s=u}let a=_wt(s);t.push(...a)}return{brep_shapes:t}}},DX=(e,t)=>{let n=e.filter(T=>T.type==="source_port"),i=e.filter(T=>T.type==="pcb_port"),o=e.filter(T=>T.type==="source_trace"),r=e.filter(T=>T.type==="pcb_trace"),s=e.filter(T=>T.type==="source_net"),a=e.find(T=>T.type==="pcb_board");if(!a)throw new Error("No pcb_board found in circuit json");let c=Object.fromEntries(n.map(T=>[T.source_port_id,T.subcircuit_connectivity_map_key])),l=Object.fromEntries(i.map(T=>[T.pcb_port_id,c[T.source_port_id]])),u={};for(let T of i)T.pcb_port_id&&(u[T.pcb_port_id]=l[T.pcb_port_id]);let h=Object.fromEntries(o.map(T=>[T.source_trace_id,T.subcircuit_connectivity_map_key])),d=Object.fromEntries(s.map(T=>[T.source_net_id,T.subcircuit_connectivity_map_key])),_={...h,...d},y=Object.fromEntries(r.map(T=>[T.pcb_trace_id,T.source_trace_id?_[T.source_trace_id]:void 0]).filter(T=>!!T[1])),g=[];for(let T of e)if(T.type==="pcb_smtpad"){let I=T;if(I.layer!==t.layer)continue;let E;I.pcb_port_id&&(E=l[I.pcb_port_id]),E||(E=`unconnected:${I.pcb_smtpad_id}`),I.shape==="rect"?g.push({shape:"rect",padId:I.pcb_smtpad_id,layer:I.layer,connectivityKey:E,bounds:{minX:I.x-I.width/2,minY:I.y-I.height/2,maxX:I.x+I.width/2,maxY:I.y+I.height/2}}):I.shape==="circle"&&g.push({shape:"circle",padId:I.pcb_smtpad_id,layer:I.layer,connectivityKey:E,x:I.x,y:I.y,radius:I.radius})}else if(T.type==="pcb_plated_hole"){let I=T;if(I.shape!=="circle"||!I.layers.includes(t.layer))continue;let E=u[I.pcb_plated_hole_id];E||(E=`unconnected-plated-hole:${I.pcb_plated_hole_id}`),g.push({shape:"circle",padId:I.pcb_plated_hole_id,layer:t.layer,connectivityKey:E,x:I.x,y:I.y,radius:I.outer_diameter/2})}else if(T.type==="pcb_hole"){let I=T;if(I.hole_shape!=="circle")continue;g.push({shape:"circle",padId:I.pcb_hole_id,layer:t.layer,connectivityKey:`hole:${I.pcb_hole_id}`,x:I.x,y:I.y,radius:I.hole_diameter/2})}else if(T.type==="pcb_cutout"){let I=T;I.shape==="rect"?g.push({shape:"rect",padId:I.pcb_cutout_id,layer:t.layer,connectivityKey:`cutout:${I.pcb_cutout_id}`,bounds:{minX:I.center.x-I.width/2,minY:I.center.y-I.height/2,maxX:I.center.x+I.width/2,maxY:I.center.y+I.height/2}}):I.shape==="circle"?g.push({shape:"circle",padId:I.pcb_cutout_id,layer:t.layer,connectivityKey:`cutout:${I.pcb_cutout_id}`,x:I.center.x,y:I.center.y,radius:I.radius}):I.shape==="polygon"&&g.push({shape:"polygon",padId:I.pcb_cutout_id,layer:t.layer,connectivityKey:`cutout:${I.pcb_cutout_id}`,points:I.points})}else if(T.type==="pcb_via"){let I=T;if(!I.layers.includes(t.layer))continue;let E;I.pcb_trace_id&&(E=y[I.pcb_trace_id]),E||(E=`unconnected-via:${I.pcb_via_id}`),g.push({shape:"circle",padId:I.pcb_via_id,layer:t.layer,connectivityKey:E,x:I.x,y:I.y,radius:I.outer_diameter/2})}else if(T.type==="pcb_trace"){let I=T;if(!I.source_trace_id)continue;let E=_[I.source_trace_id];if(!E)continue;let M=[],k=null,N=()=>{M.length>1&&g.push({shape:"trace",padId:`${I.pcb_trace_id}-${g.length}`,layer:t.layer,connectivityKey:E,segments:M,width:k}),M=[],k=null};for(let A of I.route){let R=A;R.route_type==="wire"&&R.layer===t.layer?(k===null&&(k=R.width),M.push({x:R.x,y:R.y})):N()}N()}let{width:x,height:w}=a,S=[{shape:"rect",layer:t.layer,bounds:{minX:-x/2,minY:-w/2,maxX:x/2,maxY:w/2},outline:a.outline,connectivityKey:t.pour_connectivity_key,padMargin:t.pad_margin,traceMargin:t.trace_margin,board_edge_margin:t.board_edge_margin??0,cutout_margin:t.cutout_margin}];return{pads:g,regionsForPour:S}};Ys();vt();ke();var QG=Xt(Mr(),1);var O4=Xt(Sn(),1),Bh=Xt(Mr(),1),Fne=Xt(Mr(),1);var mu=Xt(uu(),1);var tU=Xt(uu(),1),eU=Xt(uu(),1);var nU=Xt(uu(),1);var iU=Xt(uu(),1);var oU=Xt(uu(),1),rU=Xt(Mr(),1);var y5t=Object.defineProperty,g5t=(e,t)=>{for(var n in t)y5t(e,n,{get:t[n],enumerable:!0})},SH={};g5t(SH,{AnalogSimulation:()=>KG,Battery:()=>NG,Board:()=>QH,Breakout:()=>SG,BreakoutPoint:()=>wG,CadAssembly:()=>DH,CadModel:()=>zH,Capacitor:()=>eG,Chip:()=>Fm,Constraint:()=>uG,CopperPour:()=>EG,Crystal:()=>FG,Cutout:()=>Rm,Diode:()=>iG,FabricationNoteDimension:()=>fG,FabricationNotePath:()=>hG,FabricationNoteRect:()=>pG,FabricationNoteText:()=>dG,Footprint:()=>OH,Fuse:()=>oG,Group:()=>Tc,Hole:()=>Xh,Inductor:()=>RG,Jumper:()=>rG,Keepout:()=>Rx,Led:()=>aG,Mosfet:()=>DG,Net:()=>z4,NetLabel:()=>PG,NormalComponent:()=>On,Panel:()=>tG,PcbNoteDimension:()=>bG,PcbNoteLine:()=>mG,PcbNotePath:()=>gG,PcbNoteRect:()=>_G,PcbNoteText:()=>yG,PcbTrace:()=>$4,PinHeader:()=>kG,Pinout:()=>nG,PlatedHole:()=>Yh,Port:()=>Ni,Potentiometer:()=>OG,PowerSource:()=>cG,PrimitiveComponent:()=>xe,PushButton:()=>LG,Renderable:()=>L4,Resistor:()=>X4,Resonator:()=>AG,SchematicArc:()=>VG,SchematicBox:()=>GG,SchematicCell:()=>WG,SchematicCircle:()=>HG,SchematicLine:()=>YG,SchematicRect:()=>XG,SchematicRow:()=>qG,SchematicTable:()=>UG,SchematicText:()=>BG,SilkscreenCircle:()=>IG,SilkscreenLine:()=>MG,SilkscreenPath:()=>D4,SilkscreenRect:()=>TG,SilkscreenText:()=>Dx,SmtPad:()=>Am,SolderJumper:()=>sG,Subcircuit:()=>vG,Switch:()=>$G,Symbol:()=>ZG,TestPoint:()=>jG,Trace:()=>$r,TraceHint:()=>B4,Transistor:()=>zG,Via:()=>CG,VoltageProbe:()=>JG,VoltageSource:()=>lG});var b5t=(0,IH.default)("tscircuit:renderable"),aa=["ReactSubtreesRender","InflateSubcircuitCircuitJson","SourceNameDuplicateComponentRemoval","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","AssignFallbackProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SourceDesignRuleChecks","SimulationRender","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicComponentSizeCalculation","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbComponentAnchorAlignment","PcbLayout","PcbBoardAutoSize","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbCopperPourRender","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender","SimulationSpiceEngineRender"],x5t={PcbFootprintLayout:["PcbFootprintStringRender"],PcbComponentSizeCalculation:["PcbFootprintStringRender"],PcbLayout:["PcbFootprintStringRender"],PcbBoardAutoSize:["PcbFootprintStringRender"],PcbTraceHintRender:["PcbFootprintStringRender"],PcbManualTraceRender:["PcbFootprintStringRender"],PcbCopperPourRender:["PcbFootprintStringRender","PcbTraceRender","PcbRouteNetIslands"],PcbTraceRender:["PcbFootprintStringRender"],PcbRouteNetIslands:["PcbFootprintStringRender"],PcbDesignRuleChecks:["PcbFootprintStringRender"],SilkscreenOverlapAdjustment:["PcbFootprintStringRender"],CadModelRender:["PcbFootprintStringRender"],PartsEngineRender:["PcbFootprintStringRender"],PcbComponentAnchorAlignment:["PcbFootprintStringRender"]},v5t=0,L4=class TH{constructor(t){P(this,"renderPhaseStates");P(this,"shouldBeRemoved",!1);P(this,"children");P(this,"isPcbPrimitive",!1);P(this,"isSchematicPrimitive",!1);P(this,"_renderId");P(this,"_currentRenderPhase",null);P(this,"_asyncEffects",[]);P(this,"parent",null);this._renderId=`${v5t++}`,this.children=[],this.renderPhaseStates={};for(let n of aa)this.renderPhaseStates[n]={initialized:!1,dirty:!1}}_markDirty(t){this.renderPhaseStates[t].dirty=!0;let n=aa.indexOf(t);for(let i=n+1;i<aa.length;i++)this.renderPhaseStates[aa[i]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(t)}_queueAsyncEffect(t,n){let i={promise:n(),phase:this._currentRenderPhase,effectName:t,complete:!1};this._asyncEffects.push(i),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:t,componentDisplayName:this.getString(),phase:i.phase}),i.promise.then(()=>{i.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:t,componentDisplayName:this.getString(),phase:i.phase})}).catch(o=>{console.error(`Async effect error in ${i.phase} "${t}":
|
|
249
|
-
${o.stack}`),i.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:t,componentDisplayName:this.getString(),phase:i.phase,error:o.toString()})})}_emitRenderLifecycleEvent(t,n){b5t(`${t}:${n} ${this.getString()}`);let i=`renderable:renderLifecycle:${t}:${n}`,o={renderId:this._renderId,componentDisplayName:this.getString(),type:i};"root"in this&&this.root&&(this.root.emit(i,o),this.root.emit("renderable:renderLifecycle:anyEvent",{...o,type:i}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(t=>!t.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(t){for(let n of this._asyncEffects)if(!n.complete&&n.phase===t)return!0;for(let n of this.children)if(n._hasIncompleteAsyncEffectsInSubtreeForPhase(t))return!0;return!1}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(t=>t.getRenderGraph())}}getTopLevelRenderable(){let t=this;for(;t.parent&&t.parent instanceof TH;)t=t.parent;return t}runRenderCycle(){for(let t of aa)this.runRenderPhaseForChildren(t),this.runRenderPhase(t)}runRenderPhase(t){this._currentRenderPhase=t;let n=this.renderPhaseStates[t],i=n.initialized,o=n.dirty;if(!i&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&i){this._emitRenderLifecycleEvent(t,"start"),this?.[`remove${t}`]?.(),n.initialized=!1,n.dirty=!1,this._emitRenderLifecycleEvent(t,"end");return}let r=aa.indexOf(t)-1;if(r>=0){let a=aa[r];if(this._asyncEffects.filter(l=>l.phase===a).some(l=>!l.complete))return}let s=x5t[t]||[];if(s.length>0){let a=this.getTopLevelRenderable();for(let c of s)if(a._hasIncompleteAsyncEffectsInSubtreeForPhase(c))return}if(this._emitRenderLifecycleEvent(t,"start"),i){o&&(this?.[`update${t}`]?.(),n.dirty=!1),this._emitRenderLifecycleEvent(t,"end");return}n.dirty=!1,this?.[`doInitial${t}`]?.(),n.initialized=!0,this._emitRenderLifecycleEvent(t,"end")}runRenderPhaseForChildren(t){for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}renderError(t){throw typeof t=="string"?new Error(t):new Error(JSON.stringify(t,null,2))}},Ax={},MH=e=>{let t=Object.fromEntries(Object.entries(e).map(([n,i])=>[n.toLowerCase(),i]));Object.assign(Ax,e),Object.assign(Ax,t)},S5t=class extends Error{constructor(e,t,n){let i,o=Object.keys(n).filter(c=>c!=="_errors"),r=[],s=t.pinLabels;if(s)for(let[c,l]of Object.entries(s)){let u=Array.isArray(l)?l:[l];for(let h of u)typeof h=="string"&&(h.startsWith(" ")||h.endsWith(" "))&&r.push(`pinLabels.${c} ("${h}" has leading or trailing spaces)`)}let a=o.map(c=>c==="pinLabels"&&r.length>0?r.join(", "):n[c]._errors[0]?`${c} (${n[c]._errors[0]})`:`${c} (${JSON.stringify(n[c])})`).join(", ");"name"in t?i=`Invalid props for ${e} "${t.name}": ${a}`:"footprint"in t&&typeof t.footprint=="string"?i=`Invalid props for ${e} (unnamed ${t.footprint} component): ${a}`:i=`Invalid props for ${e} (unnamed): ${a}`,super(i),this.componentName=e,this.originalProps=t,this.formattedError=n}};function b4(e,t){let n=t.match(/^#(\w+)/);if(n)return e.props.id===n[1];let i=t.match(/^\.(\w+)/);if(i)return e.isMatchingNameOrAlias(i[1]);let[o,...r]=t.split(/(?=[#.[])/);return o==="pin"&&(o="port"),o&&o!=="*"&&e.lowercaseComponentName!==o.toLowerCase()?!1:r.every(s=>{if(s.startsWith("#"))return e.props.id===s.slice(1);if(s.startsWith("."))return e.isMatchingNameOrAlias(s.slice(1));let a=s.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!a)return!0;let[,c,l]=a;return e.props[c].toString()===l})}var F4={isTag:e=>!0,getParent:e=>e.parent,getChildren:e=>e.children,getName:e=>e.lowercaseComponentName,getAttributeValue:(e,t)=>{if(t==="class"&&"getNameAndAliases"in e)return e.getNameAndAliases().join(" ");if(t==="name"&&e._parsedProps?.name)return e._parsedProps.name;if(e._parsedProps&&t in e._parsedProps){let i=e._parsedProps[t];return typeof i=="string"?i:i!=null?String(i):null}if(t in e){let i=e[t];return typeof i=="string"?i:i!=null?String(i):null}let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e){let o=e[i];return typeof o=="string"?o:o!=null?String(o):null}}return null},hasAttrib:(e,t)=>{if(t==="class")return!!e._parsedProps?.name;if(e._parsedProps&&t in e._parsedProps||t in e)return!0;let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e)return!0}return!1},getSiblings:e=>e.parent?e.parent.children:[],prevElementSibling:e=>{if(!e.parent)return null;let t=e.parent.children,n=t.indexOf(e);return n>0?t[n-1]:null},getText:()=>"",removeSubsets:e=>e.filter((t,n)=>!e.some((i,o)=>n!==o&&i!==t&&i.getDescendants().includes(t))),existsOne:(e,t)=>t.some(e),findAll:(e,t)=>{let n=[],i=o=>{e(o)&&n.push(o);for(let r of o.children)i(r)};for(let o of t)i(o);return n},findOne:(e,t)=>{for(let n of t){if(e(n))return n;let i=n.children;if(i.length>0){let o=F4.findOne(e,i);if(o)return o}}return null},equals:(e,t)=>e._renderId===t._renderId,isHovered:e=>!1,isVisited:e=>!1,isActive:e=>!1},w5t={...F4,getChildren:e=>e.children.filter(t=>!t.isSubcircuit)},KV={...F4,getChildren:e=>e.children.filter(t=>t.isSubcircuit)},JV=e=>{if(/net\.[^\s>]*\./.test(e))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(e))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(e)){let t=e.match(/net\.([^ >]+)/),n=t?t[1]:"";throw new Error(`Net name "${n}" cannot start with a number, try using a prefix like "VBUS1"`)}return e.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(t,n,i,o)=>{let r=/^\d+$/.test(o)?`pin${o}`:o;return`${n}.${i} > .${r}`}).trim()},x4={adapter:w5t,cacheResults:!0},xe=class extends L4{constructor(t){super(t);P(this,"parent",null);P(this,"children");P(this,"childrenPendingRemoval");P(this,"props");P(this,"_parsedProps");P(this,"externallyAddedAliases");P(this,"isPrimitiveContainer",!1);P(this,"canHaveTextChildren",!1);P(this,"source_group_id",null);P(this,"source_component_id",null);P(this,"schematic_component_id",null);P(this,"pcb_component_id",null);P(this,"cad_component_id",null);P(this,"fallbackUnassignedName");P(this,"_cachedSelectAllQueries",new Map);P(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=t??{},this.externallyAddedAliases=[];let i=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(t??{});if(i.success)this._parsedProps=i.data;else throw new S5t(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:p.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(t){let n=this;for(;n;){if(n._parsedProps&&t in n._parsedProps)return n._parsedProps[t];n=n.parent}if(this.root?.platform&&t in this.root.platform)return this.root.platform[t]}getInheritedMergedProperty(t){let n=this.parent?.getInheritedMergedProperty?.(t),i=this._parsedProps?.[t];return{...n,...i}}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(t){let n=this.config.zodProps.parse({...this.props,...t}),i=this.props;this.props=n,this._parsedProps=this.config.zodProps.parse(t),this.onPropsChange({oldProps:i,newProps:n,changedProps:Object.keys(t)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:t}=this.props;return typeof t=="string"?parseFloat(t):t??null}computePcbPropsTransform(){let{_parsedProps:t}=this,n=this._getPcbRotationBeforeLayout()??0;return Qn(vn(t.pcbX??0,t.pcbY??0),Ua(n*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let t=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(t&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let n=this._getPcbRotationBeforeLayout()??0;return Qn(this.parent?._computePcbGlobalTransformBeforeLayout()??zi(),Qn(vn(t.x,t.y),Ua(n*Math.PI/180)))}if(this.isPcbPrimitive){let n=this.getPrimitiveContainer();if(n&&n._parsedProps.layer==="bottom")return Qn(this.parent?._computePcbGlobalTransformBeforeLayout()??zi(),y8(),this.computePcbPropsTransform())}return Qn(this.parent?._computePcbGlobalTransformBeforeLayout()??zi(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}getParentNormalComponent(){let t=this.parent;for(;t;){if(t.isPrimitiveContainer&&t.doInitialPcbComponentRender)return t;t=t.parent}return null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let t=this.getPrimitiveContainer(),n=t?t._parsedProps.layer==="bottom":!1;return{isFlipped:n,maybeFlipLayer:o=>n?o==="top"?"bottom":"top":o}}_setPositionFromLayout(t){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:t}=this;return Qn(vn(t.schX??0,t.schY??0))}computeSchematicGlobalTransform(){let t=this._getSchematicGlobalManualPlacementTransform(this);return t||Qn(this.parent?.computeSchematicGlobalTransform?.()??zi(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:t}=this,n=this.config.schematicSymbolName,i={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},o=t.schOrientation!==void 0?i[t.schOrientation]:t.schRotation;if(o===void 0&&(o=0),o=o%360,o<0&&(o+=360),t.schRotation!==void 0&&o%90!==0)throw new Error(`Schematic rotation ${t.schRotation} is not supported for ${this.componentName}`);let r=`${n}_horz`,s=`${n}_vert`,a=`${n}_up`,c=`${n}_down`,l=`${n}_left`,u=`${n}_right`;if(u in ti&&o===0)return u;if(a in ti&&o===90)return a;if(l in ti&&o===180)return l;if(c in ti&&o===270)return c;if(r in ti&&(o===0||o===180))return r;if(s in ti&&(o===90||o===270))return s;if(n in ti)return n}_getSchematicSymbolNameOrThrow(){let t=this._getSchematicSymbolName();if(!t)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return t}getSchematicSymbol(){let t=this._getSchematicSymbolName();return t?ti[t]??null:null}_getPcbManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n?.pcb_placements;if(!i)return null;for(let o of i)if(b4(t,o.selector)||t.props.name===o.selector)return Ne(this._computePcbGlobalTransformBeforeLayout(),o.center);return null}_getSchematicManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n.schematic_placements;if(!i)return null;for(let o of i)if(b4(t,o.selector)||t.props.name===o.selector)return Ne(this.computeSchematicGlobalTransform(),o.center);return null}_getSchematicGlobalManualPlacementTransform(t){let n=this.getSubcircuit()?._parsedProps.manualEdits;if(!n)return null;for(let i of n.schematic_placements??[])if((b4(t,i.selector)||t.props.name===i.selector)&&i.relative_to==="group_center")return Qn(this.parent?._computePcbGlobalTransformBeforeLayout()??zi(),vn(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return Ne(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return Ne(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(t){this.parent=t}onPropsChange(t){}onChildChanged(t){this.parent?.onChildChanged?.(t)}add(t){let n=t.__text;if(typeof n=="string"){if(this.canHaveTextChildren||n.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${n}"`)}if(Object.keys(t).length!==0){if(this.lowercaseComponentName==="board"&&t.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(t.lowercaseComponentName==="panel")throw new Error("<panel> must be a root-level element");if(!t.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(t)}"`);t.onAddToParent(this),t.parent=this,this.children.push(t)}}addAll(t){for(let n of t)this.add(n)}remove(t){this.children=this.children.filter(n=>n!==t),this.childrenPendingRemoval.push(t),t.shouldBeRemoved=!0}getSubcircuitSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?n:`${this.parent.getSubcircuitSelector()} > ${n}`}getFullPathSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName,i=this.parent?.getFullPathSelector?.();return i?`${i} > ${n}`:n}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(t){return this.getNameAndAliases().includes(t)}isMatchingAnyOf(t){return this.getNameAndAliases().some(n=>t.map(i=>i.toString()).includes(n))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(t){let n=[this.componentName,this.lowercaseComponentName],i=[this.name].filter(Boolean),o=t.trim().split(/\> /)[0],r=o[0];return o.length>1?!1:!!(t==="*"||t[0]==="#"&&t.slice(1)===this.props.id||t[0]==="."&&i.includes(t.slice(1))||/^[a-zA-Z0-9_]/.test(r)&&n.includes(r))}getSubcircuit(){if(this.isSubcircuit)return this;let t=this.parent?.getSubcircuit?.();if(!t)throw new Error("Component is not inside an opaque group (no board?)");return t}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let t=this.selectAll("port");for(let n of t){let o=(n.getParentNormalComponent?.()??n.parent)?.getNameAndAliases(),r=n.getNameAndAliases();if(o)for(let s of o)for(let a of r){let c=[`.${s} > .${a}`,`.${s} .${a}`];for(let l of c){let u=this._cachedSelectAllQueries.get(l);u?u.push(n):this._cachedSelectAllQueries.set(l,[n])}}}for(let[n,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(n,i[0])}selectAll(t){if(this._cachedSelectAllQueries.has(t))return this._cachedSelectAllQueries.get(t);let n=JV(t),i=hI(n,this,x4);if(i.length>0)return this._cachedSelectAllQueries.set(t,i),i;let[o,...r]=n.split(" "),s=jg(o,this,{adapter:KV});if(!s)return[];let a=s.selectAll(r.join(" "));return this._cachedSelectAllQueries.set(t,a),a}selectOne(t,n){if(this._cachedSelectOneQueries.has(t))return this._cachedSelectOneQueries.get(t);let i=JV(t);n?.port&&(n.type="port");let o=null;if(n?.type&&(o=hI(i,this,x4).find(l=>l.lowercaseComponentName===n.type)),o??(o=jg(i,this,x4)),o)return this._cachedSelectOneQueries.set(t,o),o;let[r,...s]=i.split(" "),a=jg(r,this,{adapter:KV});return a?(o=a.selectOne(s.join(" "),n),this._cachedSelectOneQueries.set(t,o),o):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:t}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[t(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?this.root?._getBoard()?.allLayers??["top","bottom"]:[]}return[]}getDescendants(){let t=[];for(let n of this.children)t.push(n),t.push(...n.getDescendants());return t}getSelectableDescendants(){let t=[];for(let n of this.children)n.isSubcircuit?t.push(n):(t.push(n),t.push(...n.getSelectableDescendants()));return t}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this;return{schWidth:t.schWidth,schHeight:t.schHeight}}renderError(t){if(typeof t=="string")return super.renderError(t);switch(t.type){case"pcb_placement_error":this.root?.db.pcb_placement_error.insert(t);break;case"pcb_via_clearance_error":this.root?.db.pcb_via_clearance_error.insert(t);break;case"pcb_trace_error":this.root?.db.pcb_trace_error.insert(t);break;case"pcb_manual_edit_conflict_warning":this.root?.db.pcb_manual_edit_conflict_warning.insert(t);break;default:this.root?.db.pcb_placement_error.insert(t)}}getString(){let{lowercaseComponentName:t,_parsedProps:n,parent:i}=this;return n?.pinNumber!==void 0&&i?.props?.name&&n?.name?`<${t}#${this._renderId}(pin:${n.pinNumber} .${i?.props.name}>.${n.name}) />`:i?.props?.name&&n?.name?`<${t}#${this._renderId}(.${i?.props.name}>.${n?.name}) />`:n?.from&&n?.to?`<${t}#${this._renderId}(from:${n.from} to:${n?.to}) />`:n?.name?`<${t}#${this._renderId} name=".${n?.name}" />`:n?.portHints?`<${t}#${this._renderId}(${n.portHints.map(o=>`.${o}`).join(", ")}) />`:`<${t}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},P5t=class extends xe{constructor(e,t){super(e),this._parsedProps={...e,error:t,type:e.type||"unknown",component_name:e.name,error_type:"source_failed_to_create_component_error",message:t instanceof Error?t.message:String(t),pcbX:e.pcbX,pcbY:e.pcbY,schX:e.schX,schY:e.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:p.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let e=this._getGlobalPcbPositionBeforeLayout(),t=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:e,schematic_center:t})}}};function I5t(e,t){return new P5t(e,t)}function T5t(e,t){let n=e;return n.__tsci={...t},e}var M5t={supportsMutation:!0,createInstance(e,t){let n=Ax[e];if(!n)throw Object.keys(Ax).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type "${e}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return T5t(new n(t),{})}catch(i){return I5t({...t,componentType:e},i)}},createTextInstance(e){return{__text:e}},appendInitialChild(e,t){e.add(t)},appendChild(e,t){e.add(t)},appendChildToContainer(e,t){e.add(t)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(e){return e},preparePortalMount(e){throw new Error("Function not implemented.")},scheduleTimeout(e,t){throw new Error("Function not implemented.")},cancelTimeout(e){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(e){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(e,t)=>{throw new Error("Function not implemented.")},getInstanceFromScope:e=>{throw new Error("Function not implemented.")},detachDeletedInstance:e=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>Nx.DefaultEventPriority,getCurrentUpdatePriority:()=>Nx.DefaultEventPriority,resolveUpdatePriority:()=>Nx.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},Tx=(0,PH.default)(M5t),CH=e=>{let t={children:[],props:{name:"$root"},add(r){r.parent=this,this.children.push(r)},computePcbGlobalTransform(){return zi()}},n=[],i=Tx.createContainer(t,0,null,!1,null,"tsci",r=>{console.log("Error in createContainer"),console.error(r),n.push(r)},null);if(Tx.updateContainerSync(e,i,null,()=>{}),Tx.flushSyncWork(),n.length>0)throw n[0];let o=Tx.getPublicRootInstance(i);return o||t.children[0]},Om=(e,t)=>{if(typeof e=="number")return e;if(e.startsWith("pin"))return Number(e.slice(3));if(!t)throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`);for(let n in t)if((Array.isArray(t[n])?t[n]:[t[n]]).includes(e))return Number(n.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`)},C5t=(e,t)=>{if(!e)return;let n={},i={};for(let[o,r]of Object.entries(e)){let s=Om(o,t);i[s]={...i[s],...r}}for(let[o,r]of Object.entries(i)){let s=`pin${o}`;n[s]={bottom_margin:r.bottomMargin,left_margin:r.leftMargin,right_margin:r.rightMargin,top_margin:r.topMargin}}return n},E5t=e=>{if(e){if("leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e)return{left_side:e.leftSide,right_side:e.rightSide,top_side:e.topSide,bottom_side:e.bottomSide};if("leftPinCount"in e||"rightPinCount"in e||"topPinCount"in e||"bottomPinCount"in e)return{left_size:e.leftPinCount,right_size:e.rightPinCount,top_size:e.topPinCount,bottom_size:e.bottomPinCount};if("leftSize"in e||"rightSize"in e||"topSize"in e||"bottomSize"in e)return{left_size:e.leftSize,right_size:e.rightSize,top_size:e.topSize,bottom_size:e.bottomSize}}};function EH(e){let t=[];for(let n=0;n<e.length-1;n++)t.push([e[n],e[n+1]]);return t}var N5t=p.object({name:p.string().refine(e=>!/[+-]/.test(e),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),z4=class extends xe{constructor(){super(...arguments);P(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:N5t}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=n.name.startsWith("GND"),o=n.name.startsWith("V"),r=t.source_net.insert({name:n.name,member_source_group_ids:[],is_ground:i,is_power:o,is_positive_voltage_source:o});this.source_net_id=r.source_net_id}doInitialSourceParentAttachment(){let t=this.getSubcircuit();if(!t)return;let{db:n}=this.root;n.source_net.update(this.source_net_id,{subcircuit_id:t.subcircuit_id})}getAllConnectedPorts(){let t=this.getSubcircuit().selectAll("port"),n=[];for(let i of t){let o=i._getDirectlyConnectedTraces();for(let r of o)if(r._isExplicitlyConnectedToNet(this)){n.push(i);break}}return n}_getAllDirectlyConnectedTraces(){let t=this.getSubcircuit().selectAll("trace"),n=[];for(let i of t)i._isExplicitlyConnectedToNet(this)&&n.push(i);return n}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getAllDirectlyConnectedTraces().filter(s=>(s._portsRoutedOnPcb?.length??0)>0),o=[];for(let s of i){let a=s._portsRoutedOnPcb,c=o.find(l=>a.some(u=>l.ports.includes(u)));if(!c){o.push({ports:[...a],traces:[s]});continue}c.traces.push(s),c.ports.push(...a)}if(o.length===0)return;let r=EH(o);for(let[s,a]of r){let c=s.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),u=1/0,h=[-1,-1];for(let w=0;w<c.length;w++){let S=c[w];for(let T=0;T<l.length;T++){let I=l[T],E=Math.sqrt((S.x-I.x)**2+(S.y-I.y)**2);E<u&&(u=E,h=[w,T])}}let d=s.ports[h[0]],_=a.ports[h[1]],y=t.toArray().filter(w=>w.type==="pcb_smtpad"||w.type==="pcb_trace"||w.type==="pcb_plated_hole"||w.type==="pcb_hole"||w.type==="source_port"||w.type==="pcb_port"),{solution:g}=oz(y.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[d.source_port_id,_.source_port_id]}])),x=g[0];if(!x){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[d.pcb_component_id,_.pcb_component_id].filter(Boolean),pcb_port_ids:[d.pcb_port_id,_.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}t.pcb_trace.insert(x)}}renderError(t){if(typeof t=="string")return super.renderError(t);this.root?.db.pcb_trace_error.insert(t)}},zx=(e,t)=>{for(let n of t)if(typeof n=="string"&&n.startsWith("net.")){if(/net\.[^\s>]*\./.test(n))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(n))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(n)){let o=n.split("net.")[1];throw new Error(`Net name "${o}" cannot start with a number, try using a prefix like "VBUS1"`)}let i=e.getSubcircuit();if(!i.selectOne(n)){let o=new z4({name:n.split("net.")[1]});i.add(o)}}},Am=class extends xe{constructor(){super(...arguments);P(this,"pcb_smtpad_id",null);P(this,"matchedPort",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:Nz}}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="rotated_rect"){let i=(t.ccwRotation??0)*Math.PI/180,o=Math.cos(i),r=Math.sin(i),s=Math.abs(t.width*o)+Math.abs(t.height*r),a=Math.abs(t.width*r)+Math.abs(t.height*o);return{width:s,height:a}}if(t.shape==="polygon"){let n=t.points,i=n.map(l=>l.x),o=n.map(l=>l.y),r=Math.min(...i),s=Math.max(...i),a=Math.min(...o),c=Math.max(...o);return{width:s-r,height:c-a}}if(t.shape==="pill")return{width:t.width,height:t.height};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.coveredWithSolderMask??!1,o=!i;if(!n.portHints)return;let r=this.getSubcircuit(),s=this._getGlobalPcbPositionBeforeLayout(),a=this._computePcbGlobalTransformBeforeLayout(),u=(Ar(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,h=.01,d=Math.abs(u)<h||Math.abs(u-180)<h||Math.abs(u-360)<h,_=Math.abs(u-90)<h||Math.abs(u-270)<h,y=Math.abs(u-360)<h?0:u,g=y,{maybeFlipLayer:x,isFlipped:w}=this._getPcbPrimitiveFlippedHelpers();w&&(y=(360-y+360)%360);let S=null,T=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(n.shape==="circle")S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"circle",radius:n.radius,port_hints:n.portHints.map(I=>I.toString()),is_covered_with_solder_mask:i,x:s.x,y:s.y,subcircuit_id:r?.subcircuit_id??void 0}),o&&t.pcb_solder_paste.insert({layer:S.layer,shape:"circle",radius:S.radius*.7,x:S.x,y:S.y,pcb_component_id:S.pcb_component_id,pcb_smtpad_id:S.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});else if(n.shape==="rect")!d&&!_?S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"rotated_rect",width:n.width,height:n.height,corner_radius:n.cornerRadius??void 0,x:s.x,y:s.y,ccw_rotation:y,port_hints:n.portHints.map(E=>E.toString()),is_covered_with_solder_mask:i,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"rect",width:_?n.height:n.width,height:_?n.width:n.height,corner_radius:n.cornerRadius??void 0,port_hints:n.portHints.map(E=>E.toString()),is_covered_with_solder_mask:i,x:s.x,y:s.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),o&&(S.shape==="rect"?t.pcb_solder_paste.insert({layer:x(n.layer??"top"),shape:"rect",width:S.width*.7,height:S.height*.7,x:S.x,y:S.y,pcb_component_id:S.pcb_component_id,pcb_smtpad_id:S.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):S.shape==="rotated_rect"&&t.pcb_solder_paste.insert({layer:x(n.layer??"top"),shape:"rotated_rect",width:S.width*.7,height:S.height*.7,x:S.x,y:S.y,ccw_rotation:S.ccw_rotation,pcb_component_id:S.pcb_component_id,pcb_smtpad_id:S.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));else if(n.shape==="rotated_rect"){let I=n.ccwRotation??0,E=(g+I+360)%360,M=w?(360-E+360)%360:E;S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"rotated_rect",width:n.width,height:n.height,corner_radius:n.cornerRadius??void 0,x:s.x,y:s.y,ccw_rotation:M,port_hints:n.portHints.map(k=>k.toString()),is_covered_with_solder_mask:i,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),o&&t.pcb_solder_paste.insert({layer:x(n.layer??"top"),shape:"rotated_rect",width:S.width*.7,height:S.height*.7,x:s.x,y:s.y,ccw_rotation:M,pcb_component_id:T,pcb_smtpad_id:S.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="polygon"){let I=n.points.map(E=>{let M=Ne(a,{x:Y.parse(E.x),y:Y.parse(E.y)});return{x:M.x,y:M.y}});S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"polygon",points:I,port_hints:n.portHints.map(E=>E.toString()),is_covered_with_solder_mask:i,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else n.shape==="pill"&&(S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"pill",x:s.x,y:s.y,radius:n.radius,height:n.height,width:n.width,port_hints:n.portHints.map(I=>I.toString()),is_covered_with_solder_mask:i,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));S&&(this.pcb_smtpad_id=S.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_smtpad.get(this.pcb_smtpad_id);if(n.shape==="rect")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.width/2,top:n.y+n.height/2,right:n.x+n.width/2,bottom:n.y-n.height/2},width:n.width,height:n.height};if(n.shape==="rotated_rect"){let i=n.ccw_rotation*Math.PI/180,o=Math.cos(i),r=Math.sin(i),s=n.width/2,a=n.height/2,c=Math.abs(s*o)+Math.abs(a*r),l=Math.abs(s*r)+Math.abs(a*o);return{center:{x:n.x,y:n.y},bounds:{left:n.x-c,right:n.x+c,top:n.y-l,bottom:n.y+l},width:c*2,height:l*2}}if(n.shape==="circle")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.radius,top:n.y-n.radius,right:n.x+n.radius,bottom:n.y+n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){let i=n.points,o=i.map(u=>u.x),r=i.map(u=>u.y),s=Math.min(...o),a=Math.max(...o),c=Math.min(...r),l=Math.max(...r);return{center:{x:(s+a)/2,y:(c+l)/2},bounds:{left:s,top:l,right:a,bottom:c},width:a-s,height:l-c}}if(n.shape==="pill"){let i=n.width/2,o=n.height/2;return{center:{x:n.x,y:n.y},bounds:{left:n.x-i,top:n.y-o,right:n.x+i,bottom:n.y+o},width:n.width,height:n.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${n.shape}"`)}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y});let i=n.pcb_solder_paste.list().find(o=>o.pcb_smtpad_id===this.pcb_smtpad_id);i&&n.pcb_solder_paste.update(i.pcb_solder_paste_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}},D4=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_path_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:yD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenPath. Must be "top" or "bottom".`);let r=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_path.insert({pcb_component_id:a,layer:o,route:n.route.map(l=>{let u=Ne(r,{x:l.x,y:l.y});return{...l,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=c.pcb_silkscreen_path_id}_setPositionFromLayout(t){let{db:n}=this.root,{_parsedProps:i}=this,o=n.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!o)return;let r=0,s=0;for(let u of o.route)r+=u.x,s+=u.y;r/=o.route.length,s/=o.route.length;let a=t.x-r,c=t.y-s,l=o.route.map(u=>({...u,x:u.x+a,y:u.y+c}));n.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:l})}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,o=1/0,r=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),o=Math.min(o,s.y),r=Math.max(r,s.y);return{width:i-n,height:r-o}}},k5t=p.object({route:p.array(N_),source_trace_id:p.string().optional()}),$4=class extends xe{constructor(){super(...arguments);P(this,"pcb_trace_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:k5t}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),o=this.getSubcircuit(),{maybeFlipLayer:r}=this._getPcbPrimitiveFlippedHelpers(),s=this._computePcbGlobalTransformBeforeLayout(),a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=Ne(s,{x:u,y:h});return l.route_type==="wire"&&l.layer?{..._,...d,layer:r(l.layer)}:{..._,...d}}),c=t.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:n.source_trace_id,route:a,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,o=1/0,r=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),o=Math.min(o,s.y),r=Math.max(r,s.y),s.route_type==="wire"&&(n=Math.min(n,s.x-s.width/2),i=Math.max(i,s.x+s.width/2),o=Math.min(o,s.y-s.width/2),r=Math.max(r,s.y+s.width/2));return n===1/0||i===-1/0||o===1/0||r===-1/0?{width:0,height:0}:{width:i-n,height:r-o}}},Yh=class extends xe{constructor(){super(...arguments);P(this,"pcb_plated_hole_id",null);P(this,"matchedPort",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:xz}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.outerDiameter,height:t.outerDiameter};if(t.shape==="oval"||t.shape==="pill")return{width:t.outerWidth,height:t.outerHeight};if(t.shape==="circular_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};if(t.shape==="pill_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_plated_hole.get(this.pcb_plated_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y+i.height/2,right:n.x+i.width/2,bottom:n.y-i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,r=this.getSubcircuit();if(n.shape==="circle"){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:n.outerDiameter,hole_diameter:n.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="pill"&&n.rectPad){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:n.pcbRotation??0,rect_ccw_rotation:n.pcbRotation??0,rect_pad_width:n.outerWidth,rect_pad_height:n.outerHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill"||n.shape==="oval"){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:n.shape,port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:n.pcbRotation??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="circular_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:n.holeDiameter,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,rect_border_radius:n.rectBorderRadius??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:n.holeWidth,hole_height:n.holeHeight,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},Rx=class extends xe{constructor(){super(...arguments);P(this,"pcb_keepout_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:eD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let t=this.getSubcircuit(),{db:n}=this.root,{_parsedProps:i}=this,o=this._getGlobalPcbPositionBeforeLayout(),r=Ar(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(r.rotation.angle*(180/Math.PI)-90)%180<.01,a=null;i.shape==="circle"?a=n.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:o.x,y:o.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0}):i.shape==="rect"&&(a=n.pcb_keepout.insert({layers:["top"],shape:"rect",...s?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:o.x,y:o.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0})),a&&(this.pcb_keepout_id=a.pcb_keepout_id)}},Xh=class extends xe{constructor(){super(...arguments);P(this,"pcb_hole_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:kz}}getPcbSize(){let{_parsedProps:t}=this,n=t.shape==="pill",i=t.shape==="rect";return n?{width:t.width,height:t.height}:i?{width:t.width,height:t.height}:{width:t.diameter,height:t.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),o=this._getGlobalPcbPositionBeforeLayout();if(n.shape==="pill")if(n.pcbRotation&&n.pcbRotation!==0){let r=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"rotated_pill",hole_width:n.width,hole_height:n.height,x:o.x,y:o.y,ccw_rotation:n.pcbRotation,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=r.pcb_hole_id}else{let r=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"pill",hole_width:n.width,hole_height:n.height,x:o.x,y:o.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=r.pcb_hole_id}else if(n.shape==="rect"){let r=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"rect",hole_width:n.width,hole_height:n.height,x:o.x,y:o.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=r.pcb_hole_id}else{let r=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"circle",hole_diameter:n.diameter,x:o.x,y:o.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=r.pcb_hole_id}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_hole.get(this.pcb_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_hole.update(this.pcb_hole_id,{x:t.x,y:t.y})}},Dx=class extends xe{constructor(){super(...arguments);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:_D}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),o=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:r,isFlipped:s}=this._getPcbPrimitiveFlippedHelpers(),a=this.getSubcircuit(),c=0;if(n.pcbRotation!==void 0&&n.pcbRotation!==0)c=n.pcbRotation;else{let d=this._computePcbGlobalTransformBeforeLayout();c=Ar(d).rotation.angle*180/Math.PI}s&&(c=(c+180)%360);let l=new Set(n.layers);n.layer&&l.add(n.layer);let u=l.size>0?Array.from(l):["top"],h=n.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1;for(let d of u)t.pcb_silkscreen_text.insert({anchor_alignment:n.anchorAlignment,anchor_position:{x:o.x,y:o.y},font:n.font??"tscircuit2024",font_size:h,layer:r(d),text:n.text??"",ccw_rotation:c,pcb_component_id:i.pcb_component_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:t}=this,n=t.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1,o=(t.text??"").length*n,r=n;return{width:o*n,height:r*n}}},Rm=class extends xe{constructor(){super(...arguments);P(this,"pcb_cutout_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:Ez}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),o=this.getGroup()?.pcb_group_id??void 0,r=this._getGlobalPcbPositionBeforeLayout(),a=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,c;if(n.shape==="rect"){let l=typeof a=="string"?parseInt(a.replace("deg",""),10):a,u=Math.abs(l%180)===90,h={shape:"rect",center:r,width:u?n.height:n.width,height:u?n.width:n.height,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:o};c=t.pcb_cutout.insert(h)}else if(n.shape==="circle"){let l={shape:"circle",center:r,radius:n.radius,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:o};c=t.pcb_cutout.insert(l)}else if(n.shape==="polygon"){let l=this._computePcbGlobalTransformBeforeLayout(),h={shape:"polygon",points:n.points.map(d=>Ne(l,d)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:o};c=t.pcb_cutout.insert(h)}c&&(this.pcb_cutout_id=c.pcb_cutout_id)}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return{width:0,height:0};let n=1/0,i=-1/0,o=1/0,r=-1/0;for(let s of t.points)n=Math.min(n,s.x),i=Math.max(i,s.x),o=Math.min(o,s.y),r=Math.max(r,s.y);return{width:i-n,height:r-o}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_cutout.get(this.pcb_cutout_id);if(!n)return super._getPcbCircuitJsonBounds();if(n.shape==="rect")return{center:n.center,bounds:{left:n.center.x-n.width/2,top:n.center.y+n.height/2,right:n.center.x+n.width/2,bottom:n.center.y-n.height/2},width:n.width,height:n.height};if(n.shape==="circle")return{center:n.center,bounds:{left:n.center.x-n.radius,top:n.center.y+n.radius,right:n.center.x+n.radius,bottom:n.center.y-n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){if(n.points.length===0)return super._getPcbCircuitJsonBounds();let i=1/0,o=-1/0,r=1/0,s=-1/0;for(let a of n.points)i=Math.min(i,a.x),o=Math.max(o,a.x),r=Math.min(r,a.y),s=Math.max(s,a.y);return{center:{x:(i+o)/2,y:(r+s)/2},bounds:{left:i,top:s,right:o,bottom:r},width:o-i,height:s-r}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(t){if(!this.pcb_cutout_id)return;let{db:n}=this.root,i=n.pcb_cutout.get(this.pcb_cutout_id);if(i){if(i.shape==="rect"||i.shape==="circle")n.pcb_cutout.update(this.pcb_cutout_id,{...i,center:t});else if(i.shape==="polygon"){let o=this._getPcbCircuitJsonBounds().center,r=t.x-o.x,s=t.y-o.y,a=i.points.map(c=>({x:c.x+r,y:c.y+s}));n.pcb_cutout.update(this.pcb_cutout_id,{...i,points:a})}}}},A5t=({elm:e,pinLabels:t,layer:n,readableRotation:i,anchorAlignment:o})=>{let r=e.text.replace(/[{}]/g,"").toLowerCase(),s=r;if(Array.isArray(t)){let a=parseInt(r.replace(/[^\d]/g,""),10)-1;s=String(t[a]??r)}else typeof t=="object"&&(s=String(t[r]??r));return new Dx({anchorAlignment:o||"center",text:s??r,layer:n||"top",fontSize:e.font_size+.2,pcbX:isNaN(e.anchor_position.x)?0:e.anchor_position.x,pcbY:e.anchor_position.y,pcbRotation:i??0})},R5t=(e,t)=>{let n=parseInt(e||"0",10),i;return t!=null?i=t-n:i=n,(i%360+360)%360},Vh=({componentName:e,componentRotation:t,footprinterString:n,pinLabels:i,pcbPinLabels:o},r)=>{let s=[];for(let a of r)if(a.type==="pcb_smtpad"&&a.shape==="rect")s.push(new Am({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"rect",height:a.height,width:a.width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius}));else if(a.type==="pcb_smtpad"&&a.shape==="circle")s.push(new Am({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"circle",radius:a.radius,portHints:a.port_hints}));else if(a.type==="pcb_smtpad"&&a.shape==="pill")s.push(new Am({shape:"pill",height:a.height,width:a.width,radius:a.radius,portHints:a.port_hints,pcbX:a.x,pcbY:a.y,layer:a.layer}));else if(a.type==="pcb_silkscreen_path")s.push(new D4({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?s.push(new Yh({pcbX:a.x,pcbY:a.y,shape:"circle",holeDiameter:a.hole_diameter,outerDiameter:a.outer_diameter,portHints:a.port_hints})):a.shape==="circular_hole_with_rect_pad"?s.push(new Yh({pcbX:a.x,pcbY:a.y,shape:"circular_hole_with_rect_pad",holeDiameter:a.hole_diameter,rectPadHeight:a.rect_pad_height,rectPadWidth:a.rect_pad_width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y})):a.shape==="pill"||a.shape==="oval"?s.push(new Yh({pcbX:a.x,pcbY:a.y,shape:a.shape,holeWidth:a.hole_width,holeHeight:a.hole_height,outerWidth:a.outer_width,outerHeight:a.outer_height,portHints:a.port_hints})):a.shape==="pill_hole_with_rect_pad"&&s.push(new Yh({pcbX:a.x,pcbY:a.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:a.hole_width,holeHeight:a.hole_height,rectPadWidth:a.rect_pad_width,rectPadHeight:a.rect_pad_height,portHints:a.port_hints,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y}));else if(a.type==="pcb_keepout"&&a.shape==="circle")s.push(new Rx({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius}));else if(a.type==="pcb_keepout"&&a.shape==="rect")s.push(new Rx({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height}));else if(a.type==="pcb_hole"&&a.hole_shape==="circle")s.push(new Xh({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_hole"&&a.hole_shape==="rect")s.push(new Xh({pcbX:a.x,pcbY:a.y,shape:"rect",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="pill")s.push(new Xh({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="rotated_pill")s.push(new Xh({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height,pcbRotation:a.ccw_rotation}));else if(a.type==="pcb_cutout")a.shape==="rect"?s.push(new Rm({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?s.push(new Rm({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&s.push(new Rm({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=R5t(t,a.ccw_rotation);n?.includes("pinrow")&&a.text.includes("PIN")?s.push(A5t({elm:a,pinLabels:o??i??{},layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):s.push(new Dx({anchorAlignment:a.anchor_alignment||"center",text:e,fontSize:a.font_size+.2,pcbX:Number.isNaN(a.anchor_position.x)?0:a.anchor_position.x,pcbY:a.anchor_position.y,pcbRotation:c??0}))}else a.type==="pcb_trace"&&s.push(new $4({route:a.route}));return s};function $x(e){let t=1/0,n=1/0,i=-1/0,o=-1/0,r=!1;for(let c of e)if(c.isPcbPrimitive&&!c.componentName.startsWith("Silkscreen")){let{x:l,y:u}=c._getGlobalPcbPositionBeforeLayout(),{width:h,height:d}=c.getPcbSize();t=Math.min(t,l-h/2),n=Math.min(n,u-d/2),i=Math.max(i,l+h/2),o=Math.max(o,u+d/2),r=!0}else if(c.children.length>0){let l=$x(c.children);(l.width>0||l.height>0)&&(t=Math.min(t,l.minX),n=Math.min(n,l.minY),i=Math.max(i,l.maxX),o=Math.max(o,l.maxY),r=!0)}if(!r)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let s=i-t,a=o-n;return s<0&&(s=0),a<0&&(a=0),{minX:t,minY:n,maxX:i,maxY:o,width:s,height:a}}function QV(e){let t=e%360;return t<0?t+360:t}function O5t(e,t,n,i){return i==="counterclockwise"?n>=t?e>=t&&e<=n:e>=t||e<=n:n<=t?e<=t&&e>=n:e<=t||e>=n}function L5t(e){let t=e.center,n=e.radius,i=e.start_angle_degrees,o=e.end_angle_degrees,r=e.direction??"counterclockwise";if(!t||typeof t.x!="number"||typeof t.y!="number"||typeof n!="number"||typeof i!="number"||typeof o!="number")return null;let s=QV(i),a=QV(o),c=new Set([s,a]),l=[0,90,180,270];for(let y of l)O5t(y,s,a,r)&&c.add(y);let u=1/0,h=1/0,d=-1/0,_=-1/0;for(let y of c){let g=y*Math.PI/180,x=t.x+n*Math.cos(g),w=t.y+n*Math.sin(g);u=Math.min(u,x),d=Math.max(d,x),h=Math.min(h,w),_=Math.max(_,w)}return!Number.isFinite(u)||!Number.isFinite(h)?null:{minX:u,maxX:d,minY:h,maxY:_}}function NH(e){let t=1/0,n=1/0,i=-1/0,o=-1/0;for(let r of e){let s,a,c,l;if(r.type==="schematic_component")s=r.center?.x,a=r.center?.y,c=r.size?.width,l=r.size?.height;else if(r.type==="schematic_box")s=r.x,a=r.y,c=r.width,l=r.height;else if(r.type==="schematic_port")s=r.center?.x,a=r.center?.y,c=.2,l=.2;else if(r.type==="schematic_text")s=r.position?.x,a=r.position?.y,c=(r.text?.length??0)*.1,l=.2;else if(r.type==="schematic_line"){let u=r.x1??0,h=r.y1??0,d=r.x2??0,_=r.y2??0;s=(u+d)/2,a=(h+_)/2,c=Math.abs(d-u),l=Math.abs(_-h)}else if(r.type==="schematic_rect")s=r.center?.x,a=r.center?.y,c=r.width,l=r.height;else if(r.type==="schematic_circle"){s=r.center?.x,a=r.center?.y;let u=r.radius;typeof u=="number"&&(c=u*2,l=u*2)}else if(r.type==="schematic_arc"){let u=L5t(r);u&&(t=Math.min(t,u.minX),i=Math.max(i,u.maxX),n=Math.min(n,u.minY),o=Math.max(o,u.maxY));continue}typeof s=="number"&&typeof a=="number"&&typeof c=="number"&&typeof l=="number"&&(t=Math.min(t,s-c/2),i=Math.max(i,s+c/2),n=Math.min(n,a-l/2),o=Math.max(o,a+l/2))}return{minX:t,maxX:i,minY:n,maxY:o}}function F5t(e,t){let n=t.x-e.x,i=t.y-e.y;return Math.abs(n)>Math.abs(i)?n>=0?"right":"left":i>=0?"up":"down"}var tH=e=>{if(e.length<=1)return!0;let t=e.map(r=>{let s=r._getPcbCircuitJsonBounds();return{left:s.bounds.left,right:s.bounds.right,top:s.bounds.top,bottom:s.bounds.bottom}}),n=Array(t.length).fill(!1).map(()=>Array(t.length).fill(!1));for(let r=0;r<t.length;r++)for(let s=r+1;s<t.length;s++){let a=t[r],c=t[s];n[r][s]=n[s][r]=!(a.right<c.left||a.left>c.right||a.bottom>c.top||a.top<c.bottom)}let i=new Set,o=r=>{i.add(r);for(let s=0;s<t.length;s++)n[r][s]&&!i.has(s)&&o(s)};return o(0),i.size===t.length},eH=e=>{if(e.length===0)throw new Error("Cannot get center of empty PCB primitives array");let t=e.map(o=>o._getPcbCircuitJsonBounds().center).filter(Boolean),n=t.reduce((o,r)=>o+r.x,0),i=t.reduce((o,r)=>o+r.y,0);return{x:n/t.length,y:i/t.length}},z5t=p.object({name:p.string().optional(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),layer:p.string().optional(),layers:p.array(p.string()).optional(),schX:p.number().optional(),schY:p.number().optional(),direction:p.enum(["up","down","left","right"]).optional(),connectsTo:p.union([p.string(),p.array(p.string())]).optional()}),Ni=class extends xe{constructor(t,n={}){if(!t.name&&t.pinNumber!==void 0&&(t.name=`pin${t.pinNumber}`),!t.name)throw new Error("Port must have a name or a pinNumber");super(t);P(this,"source_port_id",null);P(this,"pcb_port_id",null);P(this,"schematic_port_id",null);P(this,"schematicSymbolPortDef",null);P(this,"matchedComponents");P(this,"facingDirection",null);P(this,"originDescription",null);n.originDescription&&(this.originDescription=n.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:z5t}}isGroupPort(){return this.parent?.componentName==="Group"}isComponentPort(){return!this.isGroupPort()}_getConnectedPortsFromConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo;if(!n)return[];let i=[],o=Array.isArray(n)?n:[n];for(let r of o){let s=this.getSubcircuit().selectOne(r,{type:"port"});s&&i.push(s)}return i}_isBoardPinoutFromAttributes(){let t=this.parent;if(t?._parsedProps?.pinAttributes){let n=t._parsedProps.pinAttributes;for(let i of this.getNameAndAliases())if(n[i]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let t=this.matchedComponents.find(i=>i.isPcbPrimitive),n=this.parent;if(n&&!n.props.footprint)throw new Error(`${n.componentName} "${n.props.name}" does not have a footprint. Add a footprint prop, e.g. <${n.componentName.toLowerCase()} footprint="..." />`);if(!t)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return t?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_port.get(this.pcb_port_id);return{center:{x:n.x,y:n.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let t=this.parent;if(!t||!t._getInternallyConnectedPins)return[];let n=t._getInternallyConnectedPins();for(let i of n)if(i.some(o=>o===this))return i;return[]}_hasSchematicPort(){let{schX:t,schY:n}=this._parsedProps;if(t!==void 0&&n!==void 0)return!0;let i=this.getParentNormalComponent();if(i?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(a=>a.schematicSymbolPortDef));let r=i?._getSchematicBoxDimensions();return!!(r&&this.props.pinNumber!==void 0&&r.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let{schX:t,schY:n}=this._parsedProps;if(t!==void 0&&n!==void 0)return{x:t,y:n};let i=this.getParentNormalComponent(),o=i?.getSchematicSymbol();if(o){let s=this.schematicSymbolPortDef;if(!s&&(s=this._getPortsInternallyConnectedToThisPort().find(c=>c.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!s))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let a=Qn(i.computeSchematicGlobalTransform(),vn(-o.center.x,-o.center.y));return Ne(a,s)}let r=i?._getSchematicBoxDimensions();if(r&&this.props.pinNumber!==void 0){let s=r.getPortPositionByPinNumber(this.props.pinNumber);if(!s)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return Ne(i.computeSchematicGlobalTransform(),s)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:t}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let n=t.schematic_port.get(this.schematic_port_id);if(!n)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return n.center}registerMatch(t){this.matchedComponents.push(t)}getNameAndAliases(){let{_parsedProps:t}=this;return Array.from(new Set([...t.name?[t.name]:[],...t.aliases??[],...typeof t.pinNumber=="number"?[`pin${t.pinNumber}`,t.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let t=this.parent?._parsedProps?.pinAttributes;if(!t)return[];let n=[];for(let i of this.getNameAndAliases()){let o=t[i];o&&n.push(o)}return n}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(t=>t.includeInBoardPinout===!0)}isMatchingPort(t){return this.isMatchingAnyOf(t.getNameAndAliases())}getPortSelector(){return`.${(this.getParentNormalComponent()??this.parent)?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:t,layers:n}=this._parsedProps;return n||(t?[t]:Array.from(new Set(this.matchedComponents.flatMap(i=>i.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(i=>!i._couldNotFindPort).filter(i=>i._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getNameAndAliases(),o=this.getParentNormalComponent(),s=(this.parent?.source_component_id?this.parent:o)?.source_component_id??null,a=t.source_port.insert({name:n.name,pin_number:n.pinNumber,port_hints:i,source_component_id:s,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=a.source_port_id}doInitialSourceParentAttachment(){let{db:t}=this.root,n=this.getParentNormalComponent(),i=this.parent?.source_component_id?this.parent:n;if(this.isGroupPort()){t.source_port.update(this.source_port_id,{source_component_id:null,subcircuit_id:this.getSubcircuit()?.subcircuit_id});return}if(!i?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);t.source_port.update(this.source_port_id,{source_component_id:i.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=i.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{matchedComponents:n}=this;if(this.isGroupPort()){let a=this._getConnectedPortsFromConnectsTo();if(a.length===0)return;let c=a[0];if(!c.pcb_port_id)return;let l=t.pcb_port.get(c.pcb_port_id),u={x:l.x,y:l.y},h=this.getSubcircuit(),d=t.pcb_port.insert({pcb_component_id:void 0,layers:c.getAvailablePcbLayers(),subcircuit_id:h?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...u,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=d.pcb_port_id;return}let i=this.getParentNormalComponent(),o=this.parent?.pcb_component_id?this.parent:i;if(!o?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()}, parentNormalComponent: ${i?.getString()})`);let r=n.filter(a=>a.isPcbPrimitive);if(r.length===0)return;let s=null;if(r.length===1&&(s=r[0]._getPcbCircuitJsonBounds().center),r.length>1){if(!tH(r))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${r.map(a=>a.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);s=eH(r)}if(s){let a=this.getSubcircuit(),c=this._shouldIncludeInBoardPinout(),l=t.pcb_port.insert({pcb_component_id:o.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...c?{is_board_pinout:!0}:{},...s,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=l.pcb_port_id}else{let a=r[0];throw new Error(`${a.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;if(this.pcb_port_id)return;if(this.isGroupPort()){let l=this._getConnectedPortsFromConnectsTo();if(l.length===0)return;let u=l[0];if(!u.pcb_port_id)return;let h=t.pcb_port.get(u.pcb_port_id),d={x:h.x,y:h.y},_=this.getSubcircuit(),y=t.pcb_port.insert({pcb_component_id:void 0,layers:u.getAvailablePcbLayers(),subcircuit_id:_?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...d,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=y.pcb_port_id;return}let n=this.matchedComponents.filter(l=>l.isPcbPrimitive);if(n.length===0)return;let i=null;if(n.length===1&&(i=n[0]._getPcbCircuitJsonBounds().center),n.length>1)try{tH(n)&&(i=eH(n))}catch{}if(!i)return;let o=this.getParentNormalComponent(),r=this.parent?.pcb_component_id?this.parent:o,s=this.getSubcircuit(),a=this._shouldIncludeInBoardPinout(),c=t.pcb_port.insert({pcb_component_id:r?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...a?{is_board_pinout:!0}:{},...i,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=c.pcb_port_id}_getBestDisplayPinLabel(){let{db:t}=this.root,n=t.source_port.get(this.source_port_id),i=[];for(let s of n?.port_hints??[])s.match(/^(pin)?\d+$/)||s.match(/^(left|right)/)&&!n?.name.match(/^(left|right)/)||i.push(s);if(this.getParentNormalComponent()?.props?.showPinAliases&&i.length>0)return i.join("/");if(i.length>0)return i[0]}doInitialSchematicPortRender(){let{db:t}=this.root,{_parsedProps:n}=this,{schX:i,schY:o}=n,r=i!==void 0&&o!==void 0?this.getParentNormalComponent():this.getPrimitiveContainer();if(!r||!this._hasSchematicPort())return;let s=r._getGlobalSchematicPositionBeforeLayout(),a=this._getGlobalSchematicPositionBeforeLayout(),c=null,l=r._getSchematicBoxDimensions();l&&n.pinNumber!==void 0&&(c=l.getPortPositionByPinNumber(n.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&t.schematic_debug_object.insert({shape:"rect",center:a,size:{width:.1,height:.1},label:"obstacle"}),c?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[c.side]:this.facingDirection=F5t(s,a);let u=this._getBestDisplayPinLabel(),d={type:"schematic_port",schematic_component_id:this.getParentNormalComponent()?.schematic_component_id,center:a,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:c?.side,pin_number:n.pinNumber,true_ccw_index:c?.trueIndex,display_pin_label:u,is_connected:!1};for(let y of this._getMatchingPinAttributes())y.requiresPower&&(d.has_input_arrow=!0),y.providesPower&&(d.has_output_arrow=!0);let _=t.schematic_port.insert(d);this.schematic_port_id=_.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_port_id&&n.pcb_port.update(this.pcb_port_id,{x:t.x,y:t.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(t=>t.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},kH=e=>{let t=e.find(n=>/^(pin)?\d+$/.test(n));return t?Number.parseInt(t.replace(/^pin/,"")):null};function Cm(e,t){let n=kH(e);if(!n)return null;let o=[...e.filter(r=>r.toString()!==n.toString()&&r!==`pin${n}`),...t?.additionalAliases?.[`pin${n}`]??[]];return new Ni({pinNumber:n,aliases:o})}var D5t=e=>{for(let t of["leftSide","rightSide","topSide","bottomSide"])if(t in e&&typeof e[t]=="number")throw new Error(`A number was specified for "${t}", you probably meant to use "size" not "side"`);return"leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e},$5t=e=>{if(D5t(e))return{leftSize:e.leftSide?.pins.length??0,rightSize:e.rightSide?.pins.length??0,topSize:e.topSide?.pins.length??0,bottomSize:e.bottomSide?.pins.length??0};let{leftSize:t=0,rightSize:n=0,topSize:i=0,bottomSize:o=0}=e;return{leftSize:t,rightSize:n,topSize:i,bottomSize:o}},Mx=.4;function AH(e){let t=e;return t.leftSide!==void 0||t.rightSide!==void 0||t.topSide!==void 0||t.bottomSide!==void 0}var j5t=e=>{let t=e.portDistanceFromEdge??.4,n=e.schPortArrangement?$5t(e.schPortArrangement):null,i={left:0,right:0,top:0,bottom:0},o=e.pinCount??null;if(o===null)if(n)o=n.leftSize+n.rightSize+n.topSize;else throw new Error("Could not determine pin count for the schematic box");if(o&&!n){let y=Math.floor(o/2);n={leftSize:o-y,rightSize:y,topSize:0,bottomSize:0}}n||(n={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let r=({side:y,sideIndex:g,truePinIndex:x})=>{if(!e.schPortArrangement||!AH(e.schPortArrangement))return x+1;let w={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[y],S=e.schPortArrangement?.[`${y}Side`]?.direction??w,T=e.schPortArrangement?.[`${y}Side`]?.pins,I=g;return S!==w&&(I=T.length-g-1),Om(T[I],e.pinLabels)},s=[],a=0,c=0;for(let y=0;y<n.leftSize;y++){let g=r({side:"left",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.topMargin&&(a+=x.topMargin),s.push({trueIndex:c,pinNumber:g,side:"left",distanceFromOrthogonalEdge:a}),x?.bottomMargin&&(a+=x.bottomMargin),y===n.leftSize-1?i.left=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.bottomSize;y++){let g=r({side:"bottom",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.leftMargin&&(a+=x.leftMargin),s.push({trueIndex:c,pinNumber:g,side:"bottom",distanceFromOrthogonalEdge:a}),x?.rightMargin&&(a+=x.rightMargin),y===n.bottomSize-1?i.bottom=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.rightSize;y++){let g=r({side:"right",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.bottomMargin&&(a+=x.bottomMargin),s.push({trueIndex:c,pinNumber:g,side:"right",distanceFromOrthogonalEdge:a}),x?.topMargin&&(a+=x.topMargin),y===n.rightSize-1?i.right=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.topSize;y++){let g=r({side:"top",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.rightMargin&&(a+=x.rightMargin),s.push({trueIndex:c,pinNumber:g,side:"top",distanceFromOrthogonalEdge:a}),x?.leftMargin&&(a+=x.leftMargin),y===n.topSize-1?i.top=a:a+=e.schPinSpacing,c++}let l=e.schWidth;if(l===void 0){l=Math.max(i.top+Mx,i.bottom+Mx),e.pinLabels&&s.filter(S=>S.side==="left"||S.side==="right").some(S=>e.pinLabels?.[`pin${S.pinNumber}`]||e.pinLabels?.[S.pinNumber])&&(l=Math.max(l,.5));let y=e.pinLabels?Math.max(...Object.values(e.pinLabels).map(x=>x.length*.1)):0,g=y>0?1.1:0;l=Math.max(l,y+g)}let u=e.schHeight;u||(u=Math.max(i.left+Mx,i.right+Mx));let h={left:{x:-l/2-t,y:i.left/2},bottom:{x:-i.bottom/2,y:-u/2-t},right:{x:l/2+t,y:-i.right/2},top:{x:i.top/2,y:u/2+t}},d={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},_=s.map(y=>{let{distanceFromOrthogonalEdge:g,side:x}=y,w=h[x],S=d[x];return{x:w.x+g*S.x,y:w.y+g*S.y,...y}});return{getPortPositionByPinNumber(y){let g=_.find(x=>x.pinNumber.toString()===y.toString());return g||null},getSize(){return{width:l,height:u}},getSizeIncludingPins(){return{width:l+(n.leftSize||n.rightSize?.4:0),height:u+(n.topSize||n.bottomSize?.4:0)}},pinCount:o}},B5t=(0,RH.default)("tscircuit:core:footprint"),OH=class extends xe{get config(){return{componentName:"Footprint",zodProps:Rz}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let e=this.children.filter(h=>h.componentName==="Constraint");if(e.length===0)return;let{isFlipped:t}=this._getPcbPrimitiveFlippedHelpers(),n=h=>t&&"left"in h&&"right"in h?{...h,left:h.right,right:h.left}:h,i=e.flatMap(h=>h._getAllReferencedComponents().componentsWithSelectors).map(({component:h,selector:d,componentSelector:_,edge:y})=>({component:h,selector:d,componentSelector:_,edge:y,bounds:h._getPcbCircuitJsonBounds()}));if(i.some(h=>h.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function o(h){return i.find(({selector:d})=>d===h)}let r=new Qp,s={};function a(h){return h in s||(s[h]=new Us(h),r.addEditVariable(s[h],wn.weak)),s[h]}for(let{selector:h,bounds:d}of i){let _=a(`${h}_x`),y=a(`${h}_y`);r.suggestValue(_,d.center.x),r.suggestValue(y,d.center.y)}for(let h of e){let d=h._parsedProps;if("xDist"in d){let{xDist:_,left:y,right:g,edgeToEdge:x,centerToCenter:w}=n(d),S=a(`${y}_x`),T=a(`${g}_x`),I=o(y)?.bounds,E=o(g)?.bounds;if(w){let M=new Cn(T,[-1,S]);r.addConstraint(new ci(M,Vn.Eq,d.xDist,wn.required))}else if(x){let M=new Cn(T,-E.width/2,[-1,S],-I.width/2);r.addConstraint(new ci(M,Vn.Eq,d.xDist,wn.required))}}else if("yDist"in d){let{yDist:_,top:y,bottom:g,edgeToEdge:x,centerToCenter:w}=d,S=a(`${y}_y`),T=a(`${g}_y`),I=o(y)?.bounds,E=o(g)?.bounds;if(w){let M=new Cn(S,[-1,T]);r.addConstraint(new ci(M,Vn.Eq,d.yDist,wn.required))}else if(x){let M=new Cn(S,I.height/2,[-1,T],-E.height/2);r.addConstraint(new ci(M,Vn.Eq,d.yDist,wn.required))}}else if("sameY"in d){let{for:_}=d;if(_.length<2)continue;let y=_.map(x=>a(`${x}_y`)),g=new Cn(...y.slice(1));r.addConstraint(new ci(g,Vn.Eq,y[0],wn.required))}else if("sameX"in d){let{for:_}=d;if(_.length<2)continue;let y=_.map(x=>a(`${x}_x`)),g=new Cn(...y.slice(1));r.addConstraint(new ci(g,Vn.Eq,y[0],wn.required))}}r.updateVariables(),B5t.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(s).map(([h,d])=>({var:h,val:d.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:h,bounds:{width:d,height:_}}of i){let y=a(`${h}_x`),g=a(`${h}_y`),x=y.value()-d/2,w=y.value()+d/2,S=g.value()+_/2,T=g.value()-_/2;c.left=Math.min(c.left,x),c.right=Math.max(c.right,w),c.top=Math.max(c.top,S),c.bottom=Math.min(c.bottom,T)}let l={x:-(c.right+c.left)/2,y:-(c.top+c.bottom)/2},u=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();l.x+=u.x,l.y+=u.y;for(let{component:h,selector:d}of i){let _=a(`${d}_x`),y=a(`${d}_y`);h._setPositionFromLayout({x:_.value()+l.x,y:y.value()+l.y})}}},LH=e=>{if(!e)return null;let n=e.split("?")[0].split("#")[0],i=n.split("/").pop()??n;return i.includes(".")?i.split(".").pop()?.toLowerCase()??null:null},Y5t=(e,t)=>{let n=e.replace(/\/+$/,""),i=t.replace(/^\/+/,"");return`${n}/${i}`},FH=(e,t)=>{if(!t||!e.startsWith("/"))return e;try{let n=new URL(t);return n.pathname!=="/"&&e.startsWith(n.pathname)?new URL(e,n.origin).toString():Y5t(t,e)}catch{return e}},v4=p.union([p.number(),p.string()]),nH=p.object({x:v4,y:v4,z:v4}),zH=class extends xe{get config(){return{componentName:"CadModel",zodProps:oD}}doInitialCadModelRender(){let e=this._findParentWithPcbComponent();if(!e||!e.pcb_component_id)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=e._getPcbCircuitJsonBounds(),o=t.pcb_component.get(e.pcb_component_id),r=this._parsedProps;if(!r||typeof r.modelUrl!="string"&&typeof r.stepUrl!="string")return;let s=e._computePcbGlobalTransformBeforeLayout(),c=Ar(s).rotation.angle*180/Math.PI,l=nH.parse({x:0,y:0,z:0});if(typeof r.rotationOffset=="number")l.z=Number(r.rotationOffset);else if(typeof r.rotationOffset=="object"){let x=nH.parse(r.rotationOffset);l.x=Number(x.x),l.y=Number(x.y),l.z=Number(x.z)}let u=Zg.parse({x:r.pcbX??0,y:r.pcbY??0,z:r.pcbZ??0,...typeof r.positionOffset=="object"?r.positionOffset:{}}),h=r.zOffsetFromSurface!==void 0?Y.parse(r.zOffsetFromSurface):0,d=e.props.layer==="bottom"?"bottom":"top",_=r.modelUrl?LH(r.modelUrl):void 0,y={};if(_==="stl"?y.model_stl_url=this._addCachebustToModelUrl(r.modelUrl):_==="obj"?y.model_obj_url=this._addCachebustToModelUrl(r.modelUrl):_==="gltf"?y.model_gltf_url=this._addCachebustToModelUrl(r.modelUrl):_==="glb"?y.model_glb_url=this._addCachebustToModelUrl(r.modelUrl):_==="step"||_==="stp"?y.model_step_url=this._addCachebustToModelUrl(r.modelUrl):_==="wrl"||_==="vrml"?y.model_wrl_url=this._addCachebustToModelUrl(r.modelUrl):y.model_stl_url=this._addCachebustToModelUrl(r.modelUrl),r.stepUrl){let x=this._addCachebustToModelUrl(r.stepUrl);x&&(y.model_step_url=x)}let g=t.cad_component.insert({position:{x:i.center.x+Number(u.x),y:i.center.y+Number(u.y),z:(d==="bottom"?-n/2:n/2)+(d==="bottom"?-h:h)+Number(u.z)},rotation:{x:Number(l.x),y:(d==="top"?0:180)+Number(l.y),z:d==="bottom"?-(c+Number(l.z))+180:c+Number(l.z)},pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,model_unit_to_mm_scale_factor:typeof r.modelUnitToMmScale=="number"?r.modelUnitToMmScale:void 0,...y});this.cad_component_id=g.cad_component_id}_findParentWithPcbComponent(){let e=this.parent;for(;e&&!e.pcb_component_id;)e=e.parent;return e}_addCachebustToModelUrl(e){if(!e)return e;let t=this.root?.platform?.projectBaseUrl,n=FH(e,t);if(!n.includes("modelcdn.tscircuit.com"))return n;let i=this.root?.getClientOrigin()??"";return`${n}${n.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(i)}`}},DH=class extends xe{constructor(){super(...arguments);P(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:iD}}},X5t=(e,t)=>{if(!e)return;let n={};for(let[i,o]of Object.entries(e)){let r=Om(i,t),s={leftMargin:o.marginLeft??o.leftMargin,rightMargin:o.marginRight??o.rightMargin,topMargin:o.marginTop??o.topMargin,bottomMargin:o.marginBottom??o.bottomMargin};n[`pin${r}`]={...n[`pin${r}`],...s}}return n},iH=class{constructor({input:e}){P(this,"input");this.input=e}solveAndMapToTraces(){let e=[];for(let t of this.input.connections){if(t.pointsToConnect.length!==2)continue;let[n,i]=t.pointsToConnect,o={type:"pcb_trace",pcb_trace_id:"",connection_name:t.name,route:[{route_type:"wire",x:n.x,y:n.y,layer:"top",width:.1},{route_type:"wire",x:i.x,y:i.y,layer:"top",width:.1}]};e.push(o)}return e}},V5t=e=>{let t=Math.min(...e.map(r=>r.center.x)),n=Math.max(...e.map(r=>r.center.x)),i=Math.min(...e.map(r=>r.center.y)),o=Math.max(...e.map(r=>r.center.y));return{minX:t,maxX:n,minY:i,maxY:o}},oH=["top","bottom","inner1","inner2"],kx=(e,t=[])=>{let n=[];if(t.length===0){let a=e[0].layers;for(let c of a)n.push(...kx(e.slice(1),[c]));return n}if(e.length===0)return[];let i=e[0],o=i.via||i.optional_via,r=t[t.length-1];if(e.length===1){let a=i;return a.layers&&o?a.layers.map(c=>({layer_path:[...t,c]})):a.layers?.includes(r)?[{layer_path:[...t,r]}]:[]}if(!o)return i.layers&&!i.layers.includes(r)?[]:kx(e.slice(1),t.concat([r]));let s=(i.optional_via?oH:oH.filter(a=>a!==r)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of s)n.push(...kx(e.slice(1),t.concat(a)));return n};function rH(e){let t={x:e.to.x-e.from.x,y:e.to.y-e.from.y},n=Math.abs(t.x),i=Math.abs(t.y);return n>i?t.x>0?"right":"left":t.y>0?"down":"up"}function zh(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}var H5t=e=>{if(e.length===1)return e[0];if(e.some(c=>c.length===0))throw new Error("Cannot merge routes with zero length");let t=[],n=e[0][0],i=e[0][e[0].length-1],o=e[1][0],r=e[1][e[1].length-1],s=Math.min(zh(n,o),zh(n,r)),a=Math.min(zh(i,o),zh(i,r));s<a?t.push(...e[0].reverse()):t.push(...e[0]);for(let c=1;c<e.length;c++){let l=t[t.length-1],u=e[c],h=u[0],d=u[u.length-1],_=zh(l,h),y=zh(l,d);_<y?t.push(...u):t.push(...u.reverse())}for(let c=1;c<t.length-1;c++){let l=t[c-1],u=t[c];l.route_type==="wire"&&u.route_type==="wire"&&l.layer!==u.layer&&t.splice(c,0,{x:l.x,y:l.y,from_layer:l.layer,to_layer:u.layer,route_type:"via"})}return t},G5t=(e,t)=>{let n="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e,i="_getGlobalPcbPositionBeforeLayout"in t?t._getGlobalPcbPositionBeforeLayout():t;return Math.sqrt((n.x-i.x)**2+(n.y-i.y)**2)};function U5t(e,t){if(t.length===0)throw new Error("No candidates given to getClosest method");let n=t[0],i=1/0;for(let o of t){let r=G5t(e,o);r<i&&(n=o,i=r)}return n}var q5t=(e,t)=>{let n=0;n+=e.length??0,n+=t.filter(i=>i.is_crossing).length;for(let i=1;i<t.length;i++){let o=t[i-1],r=t[i],s=Math.abs(o.from.x-o.to.x)<.01,a=Math.abs(r.from.x-r.to.x)<.01;s!==a&&n++}return n},Lm=e=>({up:"bottom",down:"top",left:"right",right:"left"})[e]??null,M4=({firstEdge:e,firstEdgePort:t,firstDominantDirection:n,lastEdge:i,lastEdgePort:o,lastDominantDirection:r})=>{if(e&&t)return M4({lastEdge:{from:e.to,to:e.from},lastEdgePort:t,lastDominantDirection:n}).reverse().map(a=>({from:a.to,to:a.from}));let s=[];if(i&&o){let a={x:i.to.x,y:i.to.y};r==="left"||r==="right"?(a.x=o.position.x,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...o.position}})):(a.y=o.position.y,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...o.position}}))}return s=s.filter(a=>vi(a.from,a.to)>.01),s};function W5t(e){try{return[e(),null]}catch(t){return[null,t]}}var Z5t=(e,{db:t})=>{let n=e.map(i=>{let o=t.source_port.get(i.source_port_id);if(!o?.source_component_id)return null;let r=t.source_component.get(o.source_component_id);return r?.ftype==="simple_capacitor"?r.max_decoupling_trace_length:null}).filter(i=>i!==null);if(n.length!==0)return Math.min(...n)};function K5t({ports:e,nets:t}){if(e.length>=2)return`${e[0]?.selector} to ${e[1]?.selector}`;if(e.length===1&&t.length===1)return`${e[0]?.selector} to net.${t[0]._parsedProps.name}`}var J5t=(e,{db:t})=>{let n=t.pcb_board.list()[0];if(n.outline){let c=n.outline,l=(u,h)=>{let d=!1;for(let _=0,y=h.length-1;_<h.length;y=_++){let g=h[_].x,x=h[_].y,w=h[y].x,S=h[y].y;x>u.y!=S>u.y&&u.x<(w-g)*(u.y-x)/(S-x)+g&&(d=!d)}return d};return e.some(u=>!l(u,c))}let i=n.width,o=n.height,r=n.center.x,s=n.center.y;return e.some(c=>c.x<r-i/2||c.y<s-o/2||c.x>r+i/2||c.y>s+o/2)},sH=(e,t)=>Math.abs(e-t)<1e-4,Q5t=(e,t,{viaDiameter:n=.5}={})=>{let i=[];for(let o=0;o<e.length-1;o++){let[r,s]=[e[o],e[o+1]],a=o-1>=0?e[o-1]:null,c=sH(r.y,s.y),l=sH(r.x,s.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${t}, start: (${r.x}, ${r.y}), end: (${s.x}, ${s.y})`);let u={type:"rect",layers:[r.layer],center:{x:(r.x+s.x)/2,y:(r.y+s.y)/2},width:c?Math.abs(r.x-s.x):.1,height:l?Math.abs(r.y-s.y):.1,connectedTo:[t]};if(i.push(u),a&&a.layer===r.layer&&r.layer!==s.layer){let h={type:"rect",layers:[r.layer,s.layer],center:{x:r.x,y:r.y},connectedTo:[t],width:n,height:n};i.push(h)}}return i};function tIt(e,t=4){let{center:n,width:i,height:o,rotation:r}=e,s=[],a=r*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(r%360+360)%360;if(o<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*c,x=-y*l,w=d*1.1,S=Math.abs(o*c)+Math.abs(d*l);s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}else{let d=o/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*l,x=y*c,w=Math.abs(i*c)+Math.abs(d*l),S=d*1.1;s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}return s}function eIt(e,t={}){if(e.length<3)return[];let{rectHeight:n=.1}=t,i=[],o=e.map(a=>a.y),r=Math.min(...o),s=Math.max(...o);for(let a=r;a<s;a+=n){let c=a+n/2,l=[];for(let u=0;u<e.length;u++){let h=e[u],d=e[(u+1)%e.length];if(h.y<=c&&d.y>c||d.y<=c&&h.y>c){let _=(c-h.y)*(d.x-h.x)/(d.y-h.y)+h.x;l.push(_)}}l.sort((u,h)=>u-h);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let h=l[u],_=l[u+1]-h;_>1e-6&&i.push({center:{x:h+_/2,y:c},width:_,height:n})}}return i}function nIt(e,t={}){let{center:n,radius:i}=e,{rectHeight:o=.1}=t,r=[],s=Math.ceil(i*2/o);for(let a=0;a<s;a++){let c=n.y-i+(a+.5)*o,l=c-n.y,u=Math.sqrt(i*i-l*l);u>0&&r.push({center:{x:n.x,y:c},width:u*2,height:o})}return r}var ra=["top","inner1","inner2","bottom"],$H=(e,t)=>{let n=o=>t?o.concat(o.map(r=>t?.getNetConnectedToId(r)).filter(Boolean)):o,i=[];for(let o of e)if(o.type==="pcb_smtpad"){if(o.shape==="circle")i.push({type:"oval",layers:[o.layer],center:{x:o.x,y:o.y},width:o.radius*2,height:o.radius*2,connectedTo:n([o.pcb_smtpad_id])});else if(o.shape==="rect")i.push({type:"rect",layers:[o.layer],center:{x:o.x,y:o.y},width:o.width,height:o.height,connectedTo:n([o.pcb_smtpad_id])});else if(o.shape==="rotated_rect"){let r={center:{x:o.x,y:o.y},width:o.width,height:o.height,rotation:o.ccw_rotation},s=tIt(r);for(let a of s)i.push({type:"rect",layers:[o.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([o.pcb_smtpad_id])})}}else if(o.type==="pcb_keepout")o.shape==="circle"?i.push({type:"oval",layers:o.layers,center:{x:o.center.x,y:o.center.y},width:o.radius*2,height:o.radius*2,connectedTo:[]}):o.shape==="rect"&&i.push({type:"rect",layers:o.layers,center:{x:o.center.x,y:o.center.y},width:o.width,height:o.height,connectedTo:[]});else if(o.type==="pcb_cutout"){if(o.shape==="rect")i.push({type:"rect",layers:ra,center:{x:o.center.x,y:o.center.y},width:o.width,height:o.height,connectedTo:[]});else if(o.shape==="circle"){let r=nIt({center:o.center,radius:o.radius},{rectHeight:.6});for(let s of r)i.push({type:"rect",layers:ra,center:s.center,width:s.width,height:s.height,connectedTo:[]})}else if(o.shape==="polygon"){let r=eIt(o.points,{rectHeight:.6});for(let s of r)i.push({type:"rect",layers:ra,center:s.center,width:s.width,height:s.height,connectedTo:[]})}}else if(o.type==="pcb_hole")o.hole_shape==="oval"?i.push({type:"oval",center:{x:o.x,y:o.y},width:o.hole_width,height:o.hole_height,connectedTo:[]}):o.hole_shape==="rect"?i.push({type:"rect",layers:ra,center:{x:o.x,y:o.y},width:o.hole_width,height:o.hole_height,connectedTo:[]}):o.hole_shape==="square"?i.push({type:"rect",layers:ra,center:{x:o.x,y:o.y},width:o.hole_diameter,height:o.hole_diameter,connectedTo:[]}):(o.hole_shape==="round"||o.hole_shape==="circle")&&i.push({type:"rect",layers:ra,center:{x:o.x,y:o.y},width:o.hole_diameter,height:o.hole_diameter,connectedTo:[]});else if(o.type==="pcb_plated_hole")o.shape==="circle"?i.push({type:"oval",layers:ra,center:{x:o.x,y:o.y},width:o.outer_diameter,height:o.outer_diameter,connectedTo:n([o.pcb_plated_hole_id])}):o.shape==="circular_hole_with_rect_pad"?i.push({type:"rect",layers:ra,center:{x:o.x,y:o.y},width:o.rect_pad_width,height:o.rect_pad_height,connectedTo:n([o.pcb_plated_hole_id])}):(o.shape==="oval"||o.shape==="pill")&&i.push({type:"oval",layers:ra,center:{x:o.x,y:o.y},width:o.outer_width,height:o.outer_height,connectedTo:n([o.pcb_plated_hole_id])});else if(o.type==="pcb_trace"){let r=Q5t(o.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),o.source_trace_id);i.push(...r)}else if(o.type==="pcb_via"){let r=!!(o.net_is_assignable??o.netIsAssignable);i.push({type:"rect",layers:o.layers,center:{x:o.x,y:o.y},connectedTo:[],width:o.outer_diameter,height:o.outer_diameter,netIsAssignable:r||void 0})}return i},Ic=({anchor_position:e,anchor_side:t,text:n,font_size:i=.18})=>{let o=.1*(i/.18),r=n.length*o,s=i,a={...e};switch(t){case"right":a.x-=r/2;break;case"left":a.x+=r/2;break;case"top":a.y-=s/2;break;case"bottom":a.y+=s/2;break}return a},j4=({db:e,source_trace_id:t,sameNetOnly:n,differentNetOnly:i})=>{!n&&!i&&(i=!0);let o=e.source_trace.get(t),r=[];for(let s of e.schematic_trace.list()){if(s.source_trace_id===t)continue;let c=e.source_trace.get(s.source_trace_id)?.subcircuit_connectivity_map_key===o.subcircuit_connectivity_map_key;i&&c||n&&!c||r.push(s)}return r},iIt=({edges:e,otherEdges:t})=>{let n=[...e];for(let i=0;i<n.length;i++){if(i>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let o=n[i],r=Math.abs(o.from.x-o.to.x)<.01?"vertical":o.from.y===o.to.y?"horizontal":"not-orthogonal";if(r==="not-orthogonal")continue;let s=[];for(let g of t){let x=g.from.x===g.to.x?"vertical":g.from.y===g.to.y?"horizontal":"not-orthogonal";if(x==="not-orthogonal"||r===x)continue;if(qs([o.from,o.to],[g.from,g.to],{lineThickness:.01})){let S=r==="vertical"?o.from.x:g.from.x,T=r==="vertical"?g.from.y:o.from.y,I={x:S,y:T};s.push({otherEdge:g,crossingPoint:I,distanceFromEdgeFrom:vi(o.from,I)})}}if(s.length===0)continue;let a=s[0];for(let g of s)g.distanceFromEdgeFrom<a.distanceFromEdgeFrom&&(a=g);let c=a.crossingPoint,l=.075;if(c.x===o.from.x&&c.y===o.from.y)continue;let u=sb(o.from,c),h={x:c.x-u.x*l/2,y:c.y-u.y*l/2},d={x:c.x+u.x*l/2,y:c.y+u.y*l/2},_=vi(d,o.to)<l,y=[{from:o.from,to:h},{from:h,to:d,is_crossing:!0},{from:d,to:o.to}];n.splice(i,1,...y),i+=y.length-2,_&&i++}return n},C4=.001,Dh=(e,t)=>{let n=Math.min(t.from.x,t.to.x),i=Math.max(t.from.x,t.to.x),o=Math.min(t.from.y,t.to.y),r=Math.max(t.from.y,t.to.y);return e.x>=n&&e.x<=i&&e.y>=o&&e.y<=r},aH=e=>{let t=Math.abs(e.from.x-e.to.x)<C4,n=Math.abs(e.from.y-e.to.y)<C4;return t?"vertical":n?"horizontal":"diagonal"},oIt=(e,t)=>{let n=aH(e),i=aH(t);if(n===i)return null;if(n==="vertical"&&i==="horizontal"||n==="horizontal"&&i==="vertical"){let h=n==="vertical"?e:t,d=n==="horizontal"?e:t,_=h.from.x,y=d.from.y,g={x:_,y};return Dh(g,e)&&Dh(g,t)?g:null}if(n==="vertical"||i==="vertical"){let h=n==="vertical"?e:t,d=n==="vertical"?t:e,_=h.from.x,y=(d.to.y-d.from.y)/(d.to.x-d.from.x),g=d.from.y-y*d.from.x,x=y*_+g,w={x:_,y:x};return Dh(w,e)&&Dh(w,t)?w:null}let o=(e.to.y-e.from.y)/(e.to.x-e.from.x),r=e.from.y-o*e.from.x,s=(t.to.y-t.from.y)/(t.to.x-t.from.x),a=t.from.y-s*t.from.x;if(Math.abs(o-s)<C4)return null;let c=(a-r)/(o-s),l=o*c+r,u={x:c,y:l};return Dh(u,e)&&Dh(u,t)?u:null},rIt=({edges:e,db:t,source_trace_id:n})=>{let i=j4({db:t,source_trace_id:n,sameNetOnly:!0}).flatMap(r=>r.edges),o=new Map;for(let r of e)for(let s of i){let a=oIt(r,s);if(a){let c=`${a.x.toFixed(6)},${a.y.toFixed(6)}`;o.has(c)||o.set(c,a)}}return Array.from(o.values())};function sIt(e,t={}){let{minX:n,maxX:i,minY:o,maxY:r}=e,s=t.padding??1;if(!isFinite(n)||!isFinite(i)||!isFinite(o)||!isFinite(r))return[];let a=n-s,c=i+s,l=r+s,u=o-s,h=.01;return[{type:"rect",layers:["top"],center:{x:(a+c)/2,y:l},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+c)/2,y:u},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(l+u)/2},width:h,height:l-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:c,y:(l+u)/2},width:h,height:l-u,connectedTo:[]}]}var aIt=e=>{let t=e.root.db,n=e._findConnectedPorts().ports??[],i=new Set(n.map(s=>s.schematic_port_id)),o=[];for(let s of t.toArray()){if(s.type==="schematic_component"){let a=!!s.symbol_name,c=s.size.width>s.size.height?"horz":"vert";o.push({type:"rect",layers:["top"],center:s.center,width:s.size.width+(a&&c==="horz"?-.5:0),height:s.size.height+(a&&c==="vert"?-.5:0),connectedTo:[]})}if(s.type==="schematic_port"){if(i.has(s.schematic_port_id))continue;let a=s.facing_direction?ab(s.facing_direction):{x:0,y:0};o.push({type:"rect",layers:["top"],center:{x:s.center.x-a.x*.1,y:s.center.y-a.y*.1},width:.1+Math.abs(a.x)*.3,height:.1+Math.abs(a.y)*.3,connectedTo:[]})}s.type==="schematic_text"&&o.push({type:"rect",layers:["top"],center:s.position,width:(s.text?.length??0)*.1,height:.2,connectedTo:[]}),s.type==="schematic_box"&&o.push({type:"rect",layers:["top"],center:{x:s.x,y:s.y},width:s.width,height:s.height,connectedTo:[]})}let r=NH(t.toArray());return o.push(...sIt(r,{padding:1})),o},cIt=({edges:e,db:t,source_trace_id:n})=>{let i=t.source_trace.get(n),o=j4({db:t,source_trace_id:n,differentNetOnly:!0}).flatMap(s=>s.edges),r=s=>{let{from:a,to:c}=s;return a.x===c.x?"vertical":"horizontal"};for(let s of e){let a=r(s),c=()=>o.find(u=>r(u)===a&&qs([s.from,s.to],[u.from,u.to],{lineThickness:.05})),l=c();for(;l;)a==="horizontal"?(s.from.y+=.1,s.to.y+=.1):(s.from.x+=.1,s.to.x+=.1),l=c()}},E4=e=>{switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},lIt=VD.version??"unknown",Em=class extends Error{constructor(e){super(`${e} (capacity-autorouter@${lIt})`),this.name="AutorouterError"}},Ox=class extends Error{constructor(e){super(e.message),this.errorData=e,this.name="TraceConnectionError"}},uIt=e=>{if(e.root?._featureMspSchematicTraceRouting||e._couldNotFindPort||e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let o,r;try{let X=e._findConnectedPorts();o=X.allPortsFound,r=X.portsWithSelectors??[]}catch(X){if(X instanceof Ox){t.source_trace_not_connected_error.insert({...X.errorData,error_type:"source_trace_not_connected_error"});return}throw X}let{netsWithSelectors:s}=e._findConnectedNets();if(!o)return;let c=r.map(X=>X.port.schematic_port_id).sort().join(","),l=e.root?._getBoard();if(l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.has(c))return;let u={name:e.source_trace_id,pointsToConnect:[]},h=aIt(e),d=r.filter(({port:X})=>X.schematic_port_id!==null).map(({port:X})=>({port:X,position:X._getGlobalSchematicPositionAfterLayout(),schematic_port_id:X.schematic_port_id??void 0,facingDirection:X.facingDirection}));if(d.length===1&&s.length===1){let X=s[0].net,{port:G,position:tt}=d[0],Q=e.getSubcircuit().selectAll("netlabel").find(et=>{let J=et._parsedProps.connection??et._parsedProps.connectsTo;return J?Array.isArray(J)?J.some(ht=>e.getSubcircuit().selectOne(ht,{port:!0})===G):e.getSubcircuit().selectOne(J,{port:!0})===G:!1});if(!Q){let et=t.schematic_net_label.getWhere({source_trace_id:e.source_trace_id});et&&(Q=et)}if(Q){let et="_getGlobalSchematicPositionBeforeLayout"in Q?Q._getGlobalSchematicPositionBeforeLayout():Q.anchor_position,J=[];tt.x===et.x||tt.y===et.y?J.push({from:tt,to:et}):(J.push({from:tt,to:{x:et.x,y:tt.y}}),J.push({from:{x:et.x,y:tt.y},to:et}));let pt=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:J,junctions:[],subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=pt.schematic_trace_id;return}if(e.props.schDisplayLabel){let et=Lm(G.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel,source_net_id:X.source_net_id,anchor_position:tt,center:Ic({anchor_position:tt,anchor_side:et,text:e.props.schDisplayLabel}),anchor_side:et});return}let V=Lm(G.facingDirection)??"bottom",rt=t.schematic_net_label.insert({text:X._parsedProps.name,source_net_id:X.source_net_id,anchor_position:tt,center:Ic({anchor_position:tt,anchor_side:V,text:X._parsedProps.name}),anchor_side:V});return}if(e.props.schDisplayLabel&&("from"in e.props&&"to"in e.props||"path"in e.props)){e._doInitialSchematicTraceRenderWithDisplayLabel();return}if(d.length<2)return;let g=(()=>{let X=[];for(let tt=0;tt<d.length-1;tt++){let Q=d[tt],V=d[tt+1],rt=oc({x:Q.position.x,y:Q.position.y,facingDirection:E4(Q.facingDirection)},{x:V.position.x,y:V.position.y,facingDirection:E4(V.facingDirection)});for(let et=0;et<rt.length-1;et++)X.push({from:rt[et],to:rt[et+1]})}let G=(tt,Q)=>{let V=Q.width/2,rt=Q.height/2,et=Q.center.x-V,J=Q.center.x+V,pt=Q.center.y-rt,ht=Q.center.y+rt,St=lt=>lt.x>=et&<.x<=J&<.y>=pt&<.y<=ht;return St(tt.from)||St(tt.to)?!0:[[{x:et,y:pt},{x:J,y:pt}],[{x:J,y:pt},{x:J,y:ht}],[{x:J,y:ht},{x:et,y:ht}],[{x:et,y:ht},{x:et,y:pt}]].some(lt=>qs([tt.from,tt.to],lt,{lineThickness:0}))};for(let tt of X)for(let Q of h)if(G(tt,Q))return null;return X})();g&&g.length===0&&(g=null),u.pointsToConnect=d.map(({position:X})=>({...X,layer:"top"}));let x=V5t(h),w=2,S={minTraceWidth:.1,obstacles:h,connections:[u],bounds:{minX:x.minX-w,maxX:x.maxX+w,minY:x.minY-w,maxY:x.maxY+w},layerCount:1},T=Ug,I=!1;if(e.getSubcircuit().props._schDirectLineRoutingEnabled&&(T=iH,I=!0),!g){let G=new T({input:S,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(G.length===0){if(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection()){e._doInitialSchematicTraceRenderWithDisplayLabel();return}G=new iH({input:S}).solveAndMapToTraces(),I=!0}let[{route:tt}]=G;g=[];for(let Q=0;Q<tt.length-1;Q++)g.push({from:tt[Q],to:tt[Q+1]})}let E=e.source_trace_id,M=[];if(!I){cIt({edges:g,db:t,source_trace_id:E});let X=j4({db:t,source_trace_id:E,differentNetOnly:!0}).flatMap(G=>G.edges);g=iIt({edges:g,otherEdges:X}),M=rIt({edges:g,db:t,source_trace_id:e.source_trace_id})}if(!g||g.length===0)return;let k=g[g.length-1],N=d[d.length-1],A=rH(k);g.push(...M4({lastEdge:k,lastEdgePort:N,lastDominantDirection:A}));let R=g[0],$=d[0],j=rH(R);if(g.unshift(...M4({firstEdge:R,firstEdgePort:$,firstDominantDirection:j})),!e.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(e.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&q5t(M,g)>=5&&(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection())){e._doInitialSchematicTraceRenderWithDisplayLabel();return}let H=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:g,junctions:M,subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=H.schematic_trace_id;for(let{port:X}of r)X.schematic_port_id&&t.schematic_port.update(X.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function jH(e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];if(i.route_type==="wire"){let o=e[n+1];if(o){let r=o.x-i.x,s=o.y-i.y;t+=Math.sqrt(r*r+s*s)}}else i.route_type==="via"&&(t+=1.6)}return t}var Cx=e=>({...e._getGlobalPcbPositionAfterLayout(),layers:e.getAvailablePcbLayers()}),pIt=!1;function hIt(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e,o=e.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(o._parsedProps.routingDisabled)return;let r=o._parsedProps.pcbRouteCache?.pcbTraces;if(r){let A=t.pcb_trace.insert({route:r.flatMap(R=>R.route),source_trace_id:e.source_trace_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});e.pcb_trace_id=A.pcb_trace_id;return}if(n.pcbPath&&n.pcbPath.length>0||!o._shouldUseTraceByTraceRouting())return;let{allPortsFound:s,ports:a}=e._findConnectedPorts(),c=[];if(!s)return;let l=[];for(let A of a)A._hasMatchedPcbPrimitive()||l.push(A);if(l.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${l.map(A=>A.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(A=>A.pcb_port_id).filter(Boolean)});return}let u=e._findConnectedNets().netsWithSelectors;if(a.length===0&&u.length===2){e.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(a.length===1&&u.length===1){let A=a[0],$=u[0].net.getAllConnectedPorts().filter(H=>H!==A);if($.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let j=U5t(A,$);c.push(j),a.push(j)}else if(a.length>1&&u.length>=1){e.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let h=a.flatMap(A=>A.matchedComponents.filter(R=>R.componentName==="TraceHint")),d=(e._parsedProps.pcbRouteHints??[]).concat(h.flatMap(A=>A.getPcbRouteHints()));if(a.length>2){e.renderError(`Trace has more than two ports (${a.map(A=>A.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(e.getSubcircuit().selectAll("trace").filter(A=>A.renderPhaseStates.PcbTraceRender.initialized).some(A=>A._portsRoutedOnPcb.length===a.length&&A._portsRoutedOnPcb.every(R=>a.includes(R))))return;let g=[];d.length===0?g=[Cx(a[0]),Cx(a[1])]:g=[Cx(a[0]),...d,Cx(a[1])];let x=kx(g);if(pIt&&x.length===0){e.renderError(`Could not find a common layer (using hints) for trace ${e.getString()}`);return}let w=$i(e.root.db.toArray()),[S,T]=W5t(()=>$H(e.root.db.toArray()));if(T){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Error getting obstacles for autorouting: ${T.message}`,source_trace_id:e.source_trace_id,center:{x:0,y:0},pcb_port_ids:a.map(A=>A.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[]});return}for(let A of S)if(A.connectedTo.length>0){let $=w.getNetConnectedToId(A.connectedTo[0]);$&&A.connectedTo.push($)}let I=[];if(x.length===0)I=g;else{let A=x[0].layer_path;I=g.map((R,$)=>R.via?{...R,via_to_layer:A[$]}:{...R,layers:[A[$]]})}I[0].pcb_port_id=a[0].pcb_port_id,I[I.length-1].pcb_port_id=a[1].pcb_port_id;let E=[];for(let[A,R]of EH(I)){let $="via_to_layer"in A?A.via_to_layer:null,j=2,H="layers"in A&&A.layers.length===1?A.layers[0]:$??"top",X="layers"in R&&R.layers.length===1?R.layers[0]:$??"top",G="pcb_port_id"in A?A.pcb_port_id:null,tt="pcb_port_id"in R?R.pcb_port_id:null,Q=e._getExplicitTraceThickness()??e.getSubcircuit()._parsedProps.minTraceWidth??.16,V=new Ug({OBSTACLE_MARGIN:Q*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(G&&tt),connMap:w,input:{obstacles:S,minTraceWidth:Q,connections:[{name:e.source_trace_id,pointsToConnect:[{...A,layer:H,pcb_port_id:G},{...R,layer:X,pcb_port_id:tt}]}],layerCount:e.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(A.x,R.x)-j,maxX:Math.max(A.x,R.x)+j,minY:Math.min(A.y,R.y)-j,maxY:Math.max(A.y,R.y)+j}}}),rt=null;try{rt=V.solveAndMapToTraces()}catch(pt){e.renderError({type:"pcb_trace_error",pcb_trace_error_id:e.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${pt.message}`,source_trace_id:e.pcb_trace_id,center:{x:(A.x+R.x)/2,y:(A.y+R.y)/2},pcb_port_ids:a.map(ht=>ht.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(ht=>ht.pcb_component_id)})}if(!rt)return;if(rt.length===0){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Could not find a route for ${e}`,source_trace_id:e.source_trace_id,center:{x:(A.x+R.x)/2,y:(A.y+R.y)/2},pcb_port_ids:a.map(pt=>pt.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(pt=>pt.pcb_component_id)});return}let[et]=rt;$&&(et.route=et.route.map(pt=>(pt.route_type==="wire"&&!pt.layer&&(pt.layer=$),pt))),G&&et.route[0].route_type==="wire"&&(et.route[0].start_pcb_port_id=G);let J=et.route[et.route.length-1];tt&&J.route_type==="wire"&&(J.end_pcb_port_id=tt),E.push(et.route)}let M=H5t(E),k=jH(M),N=t.pcb_trace.insert({route:M,source_trace_id:e.source_trace_id,subcircuit_id:e.getSubcircuit()?.subcircuit_id,trace_length:k});e._portsRoutedOnPcb=a,e.pcb_trace_id=N.pcb_trace_id;for(let A of M)A.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:N.pcb_trace_id,x:A.x,y:A.y,hole_diameter:.3,outer_diameter:.6,layers:[A.from_layer,A.to_layer],from_layer:A.from_layer,to_layer:A.to_layer});e._insertErrorIfTraceIsOutsideBoard(M,a)}function dIt(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n}=e,i=e.getSubcircuit();if(!n.pcbPath)return;let{allPortsFound:o,ports:r,portsWithSelectors:s}=e._findConnectedPorts();if(!o)return;let a=[];for(let S of r)S._hasMatchedPcbPrimitive()||a.push(S);if(a.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${a.map(S=>S.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:a.map(S=>S.pcb_port_id).filter(Boolean)});return}let c;n.pcbPathRelativeTo&&(c=s.find(S=>S.selector===n.pcbPathRelativeTo)?.port,c||(c=e.getSubcircuit().selectOne(n.pcbPathRelativeTo))),c||(c=r[0]);let l=r.find(S=>S!==c)??r[1],u=c.getAvailablePcbLayers()[0]||"top",h=e._getExplicitTraceThickness()??e.getSubcircuit()._parsedProps.minTraceWidth??.16,d=c._getGlobalPcbPositionAfterLayout(),_=l._getGlobalPcbPositionAfterLayout(),y=[];y.push({route_type:"wire",x:d.x,y:d.y,width:h,layer:u,start_pcb_port_id:c.pcb_port_id});let g=c?._computePcbGlobalTransformBeforeLayout?.()||zi();for(let S of n.pcbPath){let T,I=!1;if(typeof S=="string"){let M=e.getSubcircuit().selectOne(S,{type:"port"});if(!M){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Could not resolve pcbPath selector "${S}" for ${e}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:[]});continue}let k=M._getGlobalPcbPositionAfterLayout();T={x:k.x,y:k.y},I=!0}else T={x:S.x,y:S.y},I=!1;let E=I?T:Ne(g,T);y.push({route_type:"wire",x:E.x,y:E.y,width:h,layer:u})}y.push({route_type:"wire",x:_.x,y:_.y,width:h,layer:u,end_pcb_port_id:l.pcb_port_id});let x=jH(y),w=t.pcb_trace.insert({route:y,source_trace_id:e.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,trace_length:x});e._portsRoutedOnPcb=r,e.pcb_trace_id=w.pcb_trace_id,e._insertErrorIfTraceIsOutsideBoard(y,r)}function fIt(e){if(e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let{allPortsFound:o,portsWithSelectors:r}=e._findConnectedPorts();if(!o)return;let s=r.map(({port:I})=>({port:I,position:I._getGlobalSchematicPositionAfterLayout(),schematic_port_id:I.schematic_port_id,facingDirection:I.facingDirection}));if(s.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let a,c,l=s[0].position,u=s[0].port;if("path"in e.props){if(e.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[a,c]=e.props.path}else{if(!("from"in e.props&&"to"in e.props))throw new Error("Missing 'from' or 'to' properties in props.");a=e.props.from,c=e.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${a}).`);let h=s[1].position,d=s[1].port;if(!d.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);let _=t.schematic_net_label.list().find(I=>I.source_net_id===u.source_port_id),y=t.schematic_net_label.list().find(I=>I.source_net_id===d.source_port_id),[g,x]=r.map(({port:I})=>I),S=g.parent?.config.shouldRenderAsSchematicBox?`${g?.parent?.props.name}_${g?.props.name}`:`${x?.parent?.props.name}_${x?.props.name}`,T=e.props.schDisplayLabel??S;if(_&&_.text!==T&&(_.text=`${T} / ${_.text}`),y&&y?.text!==T&&(y.text=`${T} / ${y.text}`),!y){let I=Lm(d.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:d.source_port_id,anchor_position:h,center:Ic({anchor_position:h,anchor_side:I,text:e.props.schDisplayLabel??S}),anchor_side:I})}if(!_){let I=Lm(u.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:u.source_port_id,anchor_position:l,center:Ic({anchor_position:l,anchor_side:I,text:e.props.schDisplayLabel??S}),anchor_side:I})}}function mIt(e){let{_parsedProps:t,parent:n}=e;if(!n)throw new Error("Trace has no parent");let o=e.getTracePortPathSelectors().map(r=>({selector:r,port:e.getSubcircuit().selectOne(r,{type:"port"})??null}));for(let{selector:r,port:s}of o)if(!s){let a,c,l=r.lastIndexOf(".");if(l!==-1&&l>r.lastIndexOf(" "))a=r.slice(0,l),c=r.slice(l+1);else{let I=r.match(/^(.*[ >])?([^ >]+)$/);a=I?.[1]?.trim()??"",c=I?.[2]??r}let u=a?e.getSubcircuit().selectOne(a):null;if(!u&&a&&!/[.#\[]/.test(a)&&(u=e.getSubcircuit().selectOne(`.${a}`)),!u){let I=a?`Could not find port for selector "${r}". Component "${a}" not found`:`Could not find port for selector "${r}"`,E=e.getSubcircuit(),M=E.getGroup();throw new Ox({error_type:"source_trace_not_connected_error",message:I,subcircuit_id:E.subcircuit_id??void 0,source_group_id:M?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[r]})}let h=u.children.filter(I=>I.componentName==="Port"),d=c.includes(".")?c.split(".").pop()??"":c,_=h.flatMap(I=>I.getNameAndAliases()),y=_.some(I=>!/^(pin\d+|\d+)$/.test(I)),g=Array.from(new Set(_)).join(", "),x;h.length===0?x="It has no ports":y?x=`It has [${g}]`:x=`It has ${h.length} pins and no pinLabels (consider adding pinLabels)`;let w=`Could not find port for selector "${r}". Component "${u.props.name??a}" found, but does not have pin "${d}". ${x}`,S=e.getSubcircuit(),T=S.getGroup();throw new Ox({error_type:"source_trace_not_connected_error",message:w,subcircuit_id:S.subcircuit_id??void 0,source_group_id:T?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[r]})}return o.some(r=>!r.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:o,ports:o.map(({port:r})=>r)}}var $r=class extends xe{constructor(t){super(t);P(this,"source_trace_id",null);P(this,"pcb_trace_id",null);P(this,"schematic_trace_id",null);P(this,"_portsRoutedOnPcb");P(this,"subcircuit_connectivity_map_key",null);P(this,"_traceConnectionHash",null);P(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}_getExplicitTraceThickness(){return this._parsedProps.thickness??this._parsedProps.width}get config(){return{zodProps:Az,componentName:"Trace"}}_getTracePortOrNetSelectorListFromProps(){return"from"in this.props&&"to"in this.props?[typeof this.props.from=="string"?this.props.from:this.props.from.getPortSelector(),typeof this.props.to=="string"?this.props.to:this.props.to.getPortSelector()]:"path"in this.props?this.props.path.map(t=>typeof t=="string"?t:t.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(t=>!t.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(t=>t.includes("net."))}_findConnectedPorts(){return mIt(this)}_resolveNet(t){let n=this.getSubcircuit().selectOne(t,{type:"net"});if(n)return n;let i=t.match(/^net\.(.+)$/),o=i?i[1]:null;if(!o)return null;let r=this.root?._getBoard();return r?r.getDescendants().find(a=>a.componentName==="Net"&&a._parsedProps.name===o)||null:(this.renderError(`Could not find a <board> ancestor for ${this}, so net "${t}" cannot be resolved`),null)}_findConnectedNets(){let t=this.getTracePathNetSelectors().map(i=>({selector:i,net:this._resolveNet(i)})),n=t.filter(i=>!i.net);return n.length>0&&this.renderError(`Could not find net for selector "${n[0].selector}" inside ${this}`),{netsWithSelectors:t,nets:t.map(i=>i.net)}}_getAllTracesConnectedToSameNet(){let t=this.getSubcircuit().selectAll("trace"),n=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return t.filter(o=>{if(o===this)return!1;let r=o._findConnectedNets().nets,s=o._findConnectedPorts().ports??[];return r.some(a=>n.includes(a))||s.some(a=>i.includes(a))})}_isExplicitlyConnectedToPort(t){let{allPortsFound:n,portsWithSelectors:i}=this._findConnectedPorts();return n?i.map(r=>r.port).includes(t):!1}_isExplicitlyConnectedToNet(t){return this._findConnectedNets().nets.includes(t)}doInitialCreateNetsFromProps(){zx(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();return!t||!n?null:[...n].sort((r,s)=>(r.pcb_port_id||"").localeCompare(s.pcb_port_id||"")).map(r=>r.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}let o,r;try{let h=this._findConnectedPorts();o=h.allPortsFound,r=h.portsWithSelectors??[]}catch(h){if(h instanceof Ox){t.source_trace_not_connected_error.insert({...h.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw h}if(!o)return;this._traceConnectionHash=this._computeTraceConnectionHash();let a=t.source_trace.list().find(h=>h.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&h.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(a){this.source_trace_id=a.source_trace_id;return}let c=this._findConnectedNets().nets,l=K5t({ports:r,nets:c}),u=t.source_trace.insert({connected_source_port_ids:r.map(h=>h.port.source_port_id),connected_source_net_ids:c.map(h=>h.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:Z5t(r.map(h=>h.port),{db:t})??n.maxLength,display_name:l,min_trace_thickness:this._getExplicitTraceThickness()});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(t,n){let{db:i}=this.root;J5t(t,{db:i})&&i.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:n.map(r=>r.pcb_port_id)})}doInitialPcbManualTraceRender(){dIt(this)}doInitialPcbTraceRender(){hIt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){fIt(this)}_isSymbolToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,o]=n;if(!i?.parent||!o?.parent)return!1;let r=i.parent.config.shouldRenderAsSchematicBox,s=o.parent.config.shouldRenderAsSchematicBox;return r&&!s||!r&&s}_isSymbolToSymbolConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,o]=n;if(!i?.parent||!o?.parent)return!1;let r=!i.parent.config.shouldRenderAsSchematicBox,s=!o.parent.config.shouldRenderAsSchematicBox;return r&&s}_isChipToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,o]=n;if(!i?.parent||!o?.parent)return!1;let r=i.parent.config.shouldRenderAsSchematicBox,s=o.parent.config.shouldRenderAsSchematicBox;return r&&s}doInitialSchematicTraceRender(){uIt(this)}},_It=e=>{let{db:t}=e.root;if(e.pcb_component_id){let n=t.pcb_component.get(e.pcb_component_id);return n?{width:n.width,height:n.height}:null}if(e.pcb_group_id){let n=t.pcb_group.get(e.pcb_group_id);if(!n)return null;if(n.outline&&n.outline.length>0){let i=ns(n.outline);return i?{width:i.maxX-i.minX,height:i.maxY-i.minY}:null}return{width:n.width??0,height:n.height??0}}return null},yIt=(e,t)=>{let{db:n}=e.root,i=n.toArray();if(e.pcb_component_id){cb(i,e.pcb_component_id,t);return}if(e.source_group_id){lb(i,e.source_group_id,t);return}throw new Error(`Cannot reposition component ${e.getString()}: no pcb_component_id or source_group_id`)},gIt=e=>{let{db:t}=e.root;if(!e.source_component_id)return;let n=e.selectAll("port"),i=t.source_trace.list(),o=new Set;for(let s of i)for(let a of s.connected_source_port_ids)o.add(a);let r=e._getInternallyConnectedPins();for(let s of r)if(s.some(a=>a.source_port_id&&o.has(a.source_port_id)))for(let a of s)a.source_port_id&&o.add(a.source_port_id);for(let s of n)s.source_port_id&&bIt(e,s)&&(o.has(s.source_port_id)||t.source_pin_missing_trace_warning.insert({message:`Port ${s.getNameAndAliases()[0]} on ${e.props.name} is missing a trace`,source_component_id:e.source_component_id,source_port_id:s.source_port_id,subcircuit_id:e.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},bIt=(e,t)=>{if(e.config.componentName==="Chip"){let n=e.props.pinAttributes;if(!n)return!1;for(let i of t.getNameAndAliases()){let o=n[i];if(o?.requiresPower||o?.requiresGround||o?.requiresVoltage!==void 0)return!0}return!1}return!0};function xIt(e){let t=e.font_size,n=e.text.length*t*.6,i=t,o=e.anchor_alignment||"center",r=e.anchor_position.x,s=e.anchor_position.y;switch(o){case"top_left":r=e.anchor_position.x+n/2,s=e.anchor_position.y+i/2;break;case"top_center":r=e.anchor_position.x,s=e.anchor_position.y+i/2;break;case"top_right":r=e.anchor_position.x-n/2,s=e.anchor_position.y+i/2;break;case"center_left":r=e.anchor_position.x+n/2,s=e.anchor_position.y;break;case"center":r=e.anchor_position.x,s=e.anchor_position.y;break;case"center_right":r=e.anchor_position.x-n/2,s=e.anchor_position.y;break;case"bottom_left":r=e.anchor_position.x+n/2,s=e.anchor_position.y-i/2;break;case"bottom_center":r=e.anchor_position.x,s=e.anchor_position.y-i/2;break;case"bottom_right":r=e.anchor_position.x-n/2,s=e.anchor_position.y-i/2;break;default:r=e.anchor_position.x,s=e.anchor_position.y;break}return{x:r-n/2,y:s-i/2,width:n,height:i}}function vIt(e){if(!e._adjustSilkscreenTextAutomatically||e.root?.pcbDisabled||!e.pcb_component_id)return;let{db:t}=e.root,i=e._getPcbCircuitJsonBounds().center,o=t.pcb_silkscreen_text.list({pcb_component_id:e.pcb_component_id}).filter(c=>c.text===e.name);if(o.length===0)return;let a=e.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(c=>c!==e&&c.pcb_component_id).map(c=>{let l=c._getPcbCircuitJsonBounds(),u={center:l.center,width:l.width,height:l.height};return Or(u)});for(let c of o){let l=c.anchor_position,u=xIt(c),h={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},d=Or(h);if(!a.some(T=>ic(d,T)))continue;let y=2*i.x-l.x,g=2*i.y-l.y,x={center:{x:y,y:g},width:u.width,height:u.height},w=Or(x);a.some(T=>ic(w,T))||t.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:y,y:g}})}}function SIt(e){if(!e)return{validPinLabels:e,invalidPinLabelsMessages:[]};let t={},n=[];for(let[i,o]of Object.entries(e)){let r=Array.isArray(o)?o.slice():[o],s=[];for(let a of r)wIt(i,a)?s.push(a):n.push(`Invalid pin label: ${i} = '${a}' - excluding from component. Please use a valid pin label.`);s.length>0&&(t[i]=Array.isArray(o)?s:s[0])}return{validPinLabels:Object.keys(t).length>0?t:void 0,invalidPinLabelsMessages:n}}function wIt(e,t){try{let n={name:"test",footprint:"test",pinLabels:{[e]:t}};return Jp.safeParse(n).success}catch{return!1}}var Hh=e=>e.startsWith("http://")||e.startsWith("https://"),k4=e=>{if(Hh(e))return null;let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t),i=e.slice(t+1);return!n||!i?null:{footprintLib:n,footprintName:i}},A4=e=>e.startsWith("/"),PIt=(0,BH.default)("tscircuit:core:resolveStaticFileImport");async function YH(e,t){if(!e)return e;let n=t?.resolveProjectStaticFileImportUrl;if(n&&e.startsWith("/"))try{let i=await n(e);if(i)return i}catch(i){PIt("failed to resolve static file via platform resolver",i)}return FH(e,t?.projectBaseUrl)}function IIt(e,t){let{footprint:n}=e.props;if(n??(n=e._getImpliedFootprintString?.()),!n)return;let{pcbRotation:i,pinLabels:o,pcbPinLabels:r}=e.props,s=LH(String(n)),a=s?e.root?.platform?.footprintFileParserMap?.[s]:null;if(typeof n=="string"&&(Hh(n)||A4(n))&&a){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0,t("load-footprint-from-platform-file-parser",async()=>{let c=Hh(n)?n:await YH(n,e.root?.platform);try{let l=await a.loadFromUrl(c),u=Vh({componentName:e.name,componentRotation:i,footprinterString:c,pinLabels:o,pcbPinLabels:r},l.footprintCircuitJson);e.addAll(u),e._markDirty("InitializePortsFromChildren")}catch(l){let u=e.root?.db;if(u&&e.source_component_id&&e.pcb_component_id){let h=e.getSubcircuit(),d=`${e.getString()} failed to load footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Ep.parse({type:"external_footprint_load_error",message:d,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:h.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof n=="string"&&Hh(n)){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let c=n;t("load-footprint-url",async()=>{try{let l=await fetch(c);if(!l.ok)throw new Error(`Failed to fetch footprint: ${l.status}`);let u=await l.json(),h=Vh({componentName:e.name,componentRotation:i,footprinterString:c,pinLabels:o,pcbPinLabels:r},u);e.addAll(h),e._markDirty("InitializePortsFromChildren")}catch(l){let u=e.root?.db;if(u&&e.source_component_id&&e.pcb_component_id){let h=e.getSubcircuit(),d=`${e.getString()} failed to load external footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Ep.parse({type:"external_footprint_load_error",message:d,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:h.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof n=="string"){let c=k4(n);if(!c||e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let u=e.root?.platform?.footprintLibraryMap?.[c.footprintLib],h;if(typeof u=="function"&&(h=u),!h)return;let d=e.getInheritedMergedProperty("pcbStyle");t("load-lib-footprint",async()=>{try{let _=await h(c.footprintName,{resolvedPcbStyle:d}),y=null;if(Array.isArray(_)?y=_:Array.isArray(_.footprintCircuitJson)&&(y=_.footprintCircuitJson),!y)return;let g=Vh({componentName:e.name,componentRotation:i,footprinterString:n,pinLabels:o,pcbPinLabels:r},y);e.addAll(g),!Array.isArray(_)&&_.cadModel&&(e._asyncFootprintCadModel=_.cadModel);for(let x of e.children)x.componentName==="Port"&&x._markDirty?.("PcbPortRender");e._markDirty("InitializePortsFromChildren")}catch(_){let y=e.root?.db;if(y&&e.source_component_id&&e.pcb_component_id){let g=e.getSubcircuit(),x=`${e.getString()} failed to load external footprint "${n}": `+(_ instanceof Error?_.message:String(_)),w=Ep.parse({type:"external_footprint_load_error",message:x,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:g.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:n});y.external_footprint_load_error.insert(w)}throw _}});return}if(!(0,N4.isValidElement)(n)&&n.componentName==="Footprint"&&e.add(n),Array.isArray(n)&&!(0,N4.isValidElement)(n)&&n.length>0){try{let c=Vh({componentName:e.name,componentRotation:i,footprinterString:"",pinLabels:o,pcbPinLabels:r},n);e.addAll(c)}catch(c){let l=e.root?.db;if(l&&e.source_component_id&&e.pcb_component_id){let u=e.getSubcircuit(),h=`${e.getString()} failed to load json footprint: `+(c instanceof Error?c.message:String(c)),d=k_.parse({type:"circuit_json_footprint_load_error",message:h,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:u.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});l.circuit_json_footprint_load_error.insert(d)}throw c}return}}function TIt(e){if(e.root?.pcbDisabled||!e.pcb_component_id)return;let{pcbX:t,pcbY:n}=e._parsedProps,i=e.props?.pcbPositionAnchor;if(!i||t===void 0&&n===void 0)return;let o=$x(e.children);if(o.width===0||o.height===0)return;let s={...{x:(o.minX+o.maxX)/2,y:(o.minY+o.maxY)/2}},a=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(i)){let u={left:o.minX,right:o.maxX,top:o.minY,bottom:o.maxY};switch(i){case"center":a=s;break;case"top_left":a={x:u.left,y:u.top};break;case"top_center":a={x:s.x,y:u.top};break;case"top_right":a={x:u.right,y:u.top};break;case"center_left":a={x:u.left,y:s.y};break;case"center_right":a={x:u.right,y:s.y};break;case"bottom_left":a={x:u.left,y:u.bottom};break;case"bottom_center":a={x:s.x,y:u.bottom};break;case"bottom_right":a={x:u.right,y:u.bottom};break}}else try{let u=e.portMap[i];u&&(a=u._getGlobalPcbPositionBeforeLayout())}catch{}if(!a)return;let l={...s};t!==void 0&&(l.x+=t-a.x),n!==void 0&&(l.y+=n-a.y),(Math.abs(l.x-s.x)>1e-6||Math.abs(l.y-s.y)>1e-6)&&e._repositionOnPcb(l)}var MIt=(0,wH.default)("tscircuit:core"),CIt=p.object({x:Be,y:Be,z:Be}),On=class extends xe{constructor(t){let n={...t},i=[];if(n.pinLabels&&!Array.isArray(n.pinLabels)){let{validPinLabels:o,invalidPinLabelsMessages:r}=SIt(n.pinLabels);n.pinLabels=o,i=r}super(n);P(this,"reactSubtrees",[]);P(this,"_impliedFootprint");P(this,"isPrimitiveContainer",!0);P(this,"_isNormalComponent",!0);P(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});P(this,"_asyncSupplierPartNumbers");P(this,"_asyncFootprintCadModel");P(this,"_isCadModelChild");P(this,"pcb_missing_footprint_error_id");P(this,"_hasStartedFootprintUrlLoad",!1);P(this,"_invalidPinLabelMessages",[]);P(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=i,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(n=>n.map(i=>typeof i=="number"?`pin${i}`:i))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let t=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(o=>o!==this&&o._isNormalComponent&&o.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let o=this._getGlobalPcbPositionBeforeLayout(),r=this._getGlobalSchematicPositionBeforeLayout();t.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:o,schematic_center:r}),this.shouldBeRemoved=!0;let s=[...this.children];for(let a of s)this.remove(a)}}initPorts(t={}){if(this.root?.schematicDisabled)return;let{config:n}=this,i=[],o=this._getSchematicPortArrangement();if(o&&!this._parsedProps.pinLabels){for(let l in o){let u=o[l].pins;if(Array.isArray(u))for(let h of u){let d=Om(h,this._parsedProps.pinLabels);i.push(new Ni({pinNumber:d,aliases:t.additionalAliases?.[`pin${d}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let a=["left","right","top","bottom"],c=1;for(let l of a){let u=o[`${l}Size`];for(let h=0;h<u;h++)i.push(new Ni({pinNumber:c++,aliases:t.additionalAliases?.[`pin${c}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let r=this._parsedProps.pinLabels;if(r)for(let[a,c]of Object.entries(r)){a=a.replace("pin","");let l=i.find(d=>d._parsedProps.pinNumber===Number(a)),u=Array.isArray(c)?c[0]:c,h=Array.isArray(c)?c.slice(1):[];l?(l.externallyAddedAliases.push(u,...h),l.props.name=u):(l=new Ni({pinNumber:parseInt(a),name:u,aliases:[...h,...t.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(n.schematicSymbolName&&!t.ignoreSymbolPorts){let a=ti[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=kH(c.labels);if(!l)continue;let u=i.find(h=>h._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let h=Cm(c.labels.concat(t.additionalAliases?.[`pin${l}`]??[]));h&&(h.originDescription=`schematicSymbol:labels[0]:${c.labels[0]}`,h.schematicSymbolPortDef=c,i.push(h))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){let a=this.getPortsFromFootprint(t);for(let c of a)i.some(l=>l.isMatchingAnyOf(c.getNameAndAliases()))||i.push(c)}let s=t.pinCount??this._getPinCount()??0;for(let a=1;a<=s;a++){if(i.find(l=>l._parsedProps.pinNumber===a))continue;if(!o){i.push(new Ni({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...o.leftSide?.pins??[],...o.rightSide?.pins??[],...o.topSide?.pins??[],...o.bottomSide?.pins??[]].map(l=>Om(l,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(l=>l in o)&&(c=Array.from({length:this._getPinCount()},(l,u)=>u+1)),c.includes(a)&&i.push(new Ni({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${a}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:t,pinLabels:n,pcbPinLabels:i}=this.props,{footprint:o}=this.props;if(o??(o=this._getImpliedFootprintString?.()),!!o&&typeof o=="string"){if(Hh(o)||A4(o)||k4(o))return;let r=GS.string(o).soup(),s=Vh({componentName:this.name??this.componentName,componentRotation:t,footprinterString:o,pinLabels:n,pcbPinLabels:i},r);this.addAll(s)}}get portMap(){return new Proxy({},{get:(t,n)=>{let i=this.children.find(o=>o.componentName==="Port"&&o.isMatchingNameOrAlias(n));if(!i)throw new Error(`There was an issue finding the port "${n.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return i}})}getInstanceForReactElement(t){for(let n of this.reactSubtrees)if(n.element===t)return n.component;return null}doInitialSourceRender(){let t=this.config.sourceFtype;if(!t)return;let{db:n}=this.root,{_parsedProps:i}=this,o=n.source_component.insert({ftype:t,name:this.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=o.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let r of this._invalidPinLabelMessages){let s="pinLabels",a=r.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);a&&(s=`pinLabels['${a[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:s,message:r,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:n}=this.config,{_parsedProps:i}=this;i.symbol&&(0,ca.isValidElement)(i.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(i.symbol):n?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let o=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&o){if(!this.schematic_component_id)return;let r=E_.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});t.schematic_manual_edit_conflict_warning.insert(r)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let t=[];for(let n of this.internallyConnectedPinNames){let i=[];for(let o of n)i.push(this.portMap[o]);t.push(i)}return t}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicSymbolNameOrThrow(),o=ti[i],r=this._getGlobalSchematicPositionBeforeLayout();if(o){let s=t.schematic_component.insert({center:r,size:o.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=s.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(t){if(this.root?.schematicDisabled)return;let{db:n}=this.root,i=this._getGlobalSchematicPositionBeforeLayout(),o=n.schematic_component.insert({center:i,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=o.schematic_component_id}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicBoxDimensions(),o={};if(Array.isArray(n.pinLabels))n.pinLabels.forEach((_,y)=>{o[String(y+1)]=_});else for(let[_,y]of Object.entries(n.pinLabels??{}))o[_]=Array.isArray(y)?y[0]:y;let r=this._getGlobalSchematicPositionBeforeLayout(),s=this._getSchematicPortArrangement(),a=t.schematic_component.insert({center:r,rotation:n.schRotation??0,size:i.getSize(),port_arrangement:E5t(s),pin_spacing:n.schPinSpacing??.2,pin_styles:C5t(n.schPinStyle,n.pinLabels),port_labels:o,source_component_id:this.source_component_id}),c=s?.topSide!==void 0||s?.bottomSide!==void 0,l=i?.getSize().width,u=i?.getSize().height,h=t.schematic_text.insert({text:n.manufacturerPartNumber??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?r.x+(l??0)/2+.1:r.x-(l??0)/2,y:c?r.y+(u??0)/2+.35:r.y-(u??0)/2-.13},color:"#006464",font_size:.18}),d=t.schematic_text.insert({text:n.name??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?r.x+(l??0)/2+.1:r.x-(l??0)/2,y:c?r.y+(u??0)/2+.55:r.y+(u??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=a.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),o=n.layer??"top";if(o!=="top"&&o!=="bottom"){let h=Np.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${o}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:o,subcircuit_id:i.subcircuit_id??void 0});t.pcb_component_invalid_layer_error.insert(h)}let r=this._computePcbGlobalTransformBeforeLayout(),a=Ar(r).rotation.angle*180/Math.PI,c=t.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:o==="top"||o==="bottom"?o:"top",rotation:n.pcbRotation??a,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});if(!(n.footprint??this._getImpliedFootprintString())&&!this.isGroup){let h=t.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=h.pcb_missing_footprint_error_id}this.pcb_component_id=c.pcb_component_id;let u=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&u){let h=A_.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0});t.pcb_manual_edit_conflict_warning.insert(h)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:t}=this.root,{_parsedProps:n}=this,i=$x(this.children);if(i.width===0||i.height===0)return;let o={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};t.pcb_component.update(this.pcb_component_id,{center:o,width:i.width,height:i.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db:t}=this.root;if(!t.schematic_component.get(this.schematic_component_id))return;let i=[],o=u=>{for(let h of u){if(h.isSchematicPrimitive&&h.componentName==="SchematicLine"){let d=t.schematic_line.get(h.schematic_line_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicRect"){let d=t.schematic_rect.get(h.schematic_rect_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicCircle"){let d=t.schematic_circle.get(h.schematic_circle_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicArc"){let d=t.schematic_arc.get(h.schematic_arc_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicText"){let d=t.schematic_text.get(h.schematic_text_id);d&&i.push(d)}h.children&&h.children.length>0&&o(h.children)}};if(o(this.children),i.length===0)return;let r=NH(i),s=Math.abs(r.maxX-r.minX),a=Math.abs(r.maxY-r.minY);if(s===0&&a===0)return;let c=(r.minX+r.maxX)/2,l=(r.minY+r.maxY)/2;t.schematic_component.update(this.schematic_component_id,{center:{x:c,y:l},size:{width:s,height:a}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){TIt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(t){let n=CH(t);return{element:t,component:n}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let t=this.props.footprint;(0,ca.isValidElement)(t)&&(this.children.some(r=>r.componentName==="Footprint")||this.add(t));let n=this.props.symbol;(0,ca.isValidElement)(n)&&(this.children.some(r=>r.componentName==="Symbol")||this.add(n));let i=this.props.cadModel;if((0,ca.isValidElement)(i)){this._isCadModelChild=!0;let o=this.children.some(s=>s.componentName==="CadAssembly"),r=this.children.some(s=>s.componentName==="CadModel");!o&&!r&&this.add(i)}}doInitialPcbFootprintStringRender(){IIt(this,(t,n)=>this._queueAsyncEffect(t,n))}_hasExistingPortExactly(t){return this.children.filter(i=>i.componentName==="Port").some(i=>{let o=t.getNameAndAliases(),r=i.getNameAndAliases();return o.length===r.length&&o.every(s=>r.includes(s))})}add(t){let n;if((0,ca.isValidElement)(t)){let i=this._renderReactSubtree(t);this.reactSubtrees.push(i),n=i.component}else n=t;if(n.componentName==="Port"){if(this._hasExistingPortExactly(n))return;let o=this.children.filter(r=>r.componentName==="Port").find(r=>r.isMatchingAnyOf(n.getNameAndAliases()));o&&MIt(`Similar ports added. Port 1: ${o}, Port 2: ${n}`)}super.add(n)}getPortsFromFootprint(t){let{footprint:n}=this.props;if((!n||(0,ca.isValidElement)(n))&&(n=this.children.find(o=>o.componentName==="Footprint")),typeof n=="string"){if(Hh(n))return[];if(A4(n))return[];if(k4(n))return[];let o=GS.string(n).soup(),r=[];for(let s of o)if("port_hints"in s&&s.port_hints){let a=Cm(s.port_hints,t);if(!a)continue;a.originDescription=`footprint:string:${n}:port_hints[0]:${s.port_hints[0]}`,r.push(a)}return r}if(!(0,ca.isValidElement)(n)&&n&&n.componentName==="Footprint"){let o=n,r=1,s=[];for(let a of o.children){if(!a.props.portHints)continue;let c=a.props.portHints;c.some(h=>h.startsWith("pin"))||(c=[...c,`pin${r}`]),r++;let u=Cm(c);u&&(u.originDescription=`footprint:${n}`,s.push(u))}return s}let i=[];if(!n){for(let o of this.children)if(o.props.portHints&&o.isPcbPrimitive){let r=Cm(o.props.portHints);r&&i.push(r)}}return i}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:t}=this;if(!t.schematicSymbolName)return[];let n=ti[t.schematicSymbolName];if(!n)return[];let i=[];for(let o of n.ports){let r=Cm(o.labels);r&&(r.schematicSymbolPortDef=o,i.push(r))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:t}=this,n=[];if(t.connections)for(let[i,o]of Object.entries(t.connections)){let r=Array.isArray(o)?o:[o];for(let s of r)n.push(String(s))}return n}_createNetsFromProps(t){zx(this,t)}_getPcbCircuitJsonBounds(){let{db:t}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let n=t.pcb_component.get(this.pcb_component_id);return{center:{x:n.center.x,y:n.center.y},bounds:{left:n.center.x-n.width/2,top:n.center.y-n.height/2,right:n.center.x+n.width/2,bottom:n.center.y+n.height/2},width:n.width,height:n.height}}_getPinCountFromSchematicPortArrangement(){let t=this._getSchematicPortArrangement();if(!t)return 0;if(!AH(t))return(t.leftSize??t.leftPinCount??0)+(t.rightSize??t.rightPinCount??0)+(t.topSize??t.topPinCount??0)+(t.bottomSize??t.bottomPinCount??0);let{leftSide:i,rightSide:o,topSide:r,bottomSide:s}=t;return Math.max(...i?.pins??[],...o?.pins??[],...r?.pins??[],...s?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let n=this.getPortsFromFootprint();if(n.length>0)return n.length;let{pinLabels:i}=this._parsedProps;if(i){if(Array.isArray(i))return i.length;let o=Object.keys(i).map(r=>r.startsWith("pin")?parseInt(r.slice(3)):parseInt(r)).filter(r=>!Number.isNaN(r));return o.length>0?Math.max(...o):Object.keys(i).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getPinLabelsFromPorts(){let t=this.selectAll("port"),n={};for(let i of t){let o=i.props.pinNumber;if(o!==void 0){let r=i._getBestDisplayPinLabel();r&&(n[`pin${o}`]=r)}}return n}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this,n=this._getPinCount(),i=t.schPinSpacing??.2,r={...this._getPinLabelsFromPorts(),...t.pinLabels};return j5t({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:i,numericSchPinStyle:X5t(t.schPinStyle,r),pinCount:n,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:r})}getFootprinterString(){return typeof this._parsedProps.footprint=="string"?this._parsedProps.footprint:null}doInitialCadModelRender(){if(this._isCadModelChild||this.props.doNotPlace)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=this._parsedProps.cadModel,o=i===void 0?this._asyncFootprintCadModel:i,r=this.getFootprinterString()??this._getImpliedFootprintString();if(!this.pcb_component_id||!o&&!r||o===null)return;let s=this._getPcbCircuitJsonBounds();if(typeof o=="string")throw new Error("String cadModel not yet implemented");let a=CIt.parse({x:0,y:0,z:typeof o?.rotationOffset=="number"?o.rotationOffset:0,...typeof o?.rotationOffset=="object"?o.rotationOffset??{}:{}}),c=vl.parse({x:0,y:0,z:0,...typeof o?.positionOffset=="object"?o.positionOffset:{}}),l=o&&typeof o=="object"&&"zOffsetFromSurface"in o&&o.zOffsetFromSurface!==void 0?Y.parse(o.zOffsetFromSurface):0,u=this.props.layer==="bottom"?"bottom":"top",h=this._computePcbGlobalTransformBeforeLayout(),_=Ar(h).rotation.angle*180/Math.PI,y=u==="bottom",g=_+(a.z??0),x=Vl(g),w=t.cad_component.insert({position:{x:s.center.x+c.x,y:s.center.y+c.y,z:(u==="bottom"?-n/2:n/2)+(u==="bottom"?-l:l)+c.z},rotation:{x:a.x,y:a.y+(y?180:0),z:Vl(y?-x:x)},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(o??{})?this._addCachebustToModelUrl(o.stlUrl):void 0,model_obj_url:"objUrl"in(o??{})?this._addCachebustToModelUrl(o.objUrl):void 0,model_mtl_url:"mtlUrl"in(o??{})?this._addCachebustToModelUrl(o.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(o??{})?this._addCachebustToModelUrl(o.gltfUrl):void 0,model_glb_url:"glbUrl"in(o??{})?this._addCachebustToModelUrl(o.glbUrl):void 0,model_step_url:"stepUrl"in(o??{})?this._addCachebustToModelUrl(o.stepUrl):void 0,model_wrl_url:"wrlUrl"in(o??{})?this._addCachebustToModelUrl(o.wrlUrl):void 0,model_jscad:"jscad"in(o??{})?o.jscad:void 0,model_unit_to_mm_scale_factor:typeof o?.modelUnitToMmScale=="number"?o.modelUnitToMmScale:void 0,footprinter_string:typeof r=="string"&&!o?r:void 0});this.cad_component_id=w.cad_component_id}_addCachebustToModelUrl(t){if(!t||!t.includes("modelcdn.tscircuit.com"))return t;let n=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(n)}`}_getPartsEngineCacheKey(t,n){return JSON.stringify({ftype:t.ftype,name:t.name,manufacturer_part_number:t.manufacturer_part_number,footprinterString:n})}async _getSupplierPartNumbers(t,n,i){if(this.props.doNotPlace)return{};let o=this.root?.platform?.localCacheEngine,r=this._getPartsEngineCacheKey(n,i);if(o){let c=await o.getItem(r);if(c)try{return JSON.parse(c)}catch{}}let s=await Promise.resolve(t.findPart({sourceComponent:n,footprinterString:i}));if(typeof s=="string"){if(s.includes("<!DOCTYPE")||s.includes("<html"))throw new Error(`Failed to fetch supplier part numbers: Received HTML response instead of JSON. Response starts with: ${s.substring(0,100)}`);if(s==="Not found")return{};throw new Error(`Invalid supplier part numbers format: Expected object but got string: "${s}"`)}if(!s||Array.isArray(s)||typeof s!="object"){let c=s===null?"null":Array.isArray(s)?"array":typeof s;throw new Error(`Invalid supplier part numbers format: Expected object but got ${c}`)}let a=s;if(o)try{await o.setItem(r,JSON.stringify(a))}catch{}return a}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let t=this.getInheritedProperty("partsEngine");if(!t)return;let{db:n}=this.root,i=n.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let o;this.props.footprint&&typeof this.props.footprint=="string"&&(o=this.props.footprint);let r=this._getSupplierPartNumbers(t,i,o);if(!(r instanceof Promise)){n.source_component.update(this.source_component_id,{supplier_part_numbers:r});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{await r.then(s=>{this._asyncSupplierPartNumbers=s,this._markDirty("PartsEngineRender")}).catch(s=>{this._asyncSupplierPartNumbers={};let a=M_.parse({type:"unknown_error_finding_part",message:`Failed to fetch supplier part numbers for ${this.getString()}: ${s.message}`,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});n.unknown_error_finding_part.insert(a),this._markDirty("PartsEngineRender")})})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(n&&!n.supplier_part_numbers&&this._asyncSupplierPartNumbers){t.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:t}=this;t.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:t}=this;if(t.connections)for(let[n,i]of Object.entries(t.connections)){let o=Array.isArray(i)?i:[i];for(let r of o)this.add(new $r({from:`.${this.name} > .${n}`,to:String(r)}))}}doInitialSourceDesignRuleChecks(){gIt(this)}_getMinimumFlexContainerSize(){return _It(this)}_repositionOnPcb(t){return yIt(this,t)}doInitialSilkscreenOverlapAdjustment(){return vIt(this)}isRelativelyPositioned(){return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0}},EIt=({boardAnchorPosition:e,boardAnchorAlignment:t,width:n,height:i})=>{let{x:o,y:r}=e,s=o,a=r;switch(t){case"top_left":s=o+n/2,a=r-i/2;break;case"top_right":s=o-n/2,a=r-i/2;break;case"bottom_left":s=o+n/2,a=r+i/2;break;case"bottom_right":s=o-n/2,a=r+i/2;break;case"top":s=o,a=r-i/2;break;case"bottom":s=o,a=r+i/2;break;case"left":s=o+n/2,a=r;break;case"right":s=o-n/2,a=r;break;case"center":default:break}return{x:s,y:a}},NIt=class{constructor(e,t={}){P(this,"input");P(this,"isRouting",!1);P(this,"solver");P(this,"eventHandlers",{complete:[],error:[],progress:[]});P(this,"cycleCount",0);P(this,"stepDelay");P(this,"timeoutId");this.input=e;let{capacityDepth:n,targetMinCapacity:i,stepDelay:o=0,useAssignableViaSolver:r=!1}=t,{AutoroutingPipelineSolver:s,AssignableViaAutoroutingPipelineSolver:a}=bT,c=r?a:s;this.solver=new c(e,{capacityDepth:n,targetMinCapacity:i,cacheProvider:null}),this.stepDelay=o}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new Em(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;let i=this.solver?.preview()||void 0,o=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:o,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(e){this.emitEvent({type:"error",error:e instanceof Error?new Em(e.message):new Em(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(e,t){e==="complete"?this.eventHandlers.complete.push(t):e==="error"?this.eventHandlers.error.push(t):e==="progress"&&this.eventHandlers.progress.push(t)}emitEvent(e){if(e.type==="complete")for(let t of this.eventHandlers.complete)t(e);else if(e.type==="error")for(let t of this.eventHandlers.error)t(e);else if(e.type==="progress")for(let t of this.eventHandlers.progress)t(e)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Em(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},B4=class extends xe{constructor(){super(...arguments);P(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:vD}}doInitialPortMatching(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)return;if(i.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!i)throw new Error("TraceHint has no parent");if(!n.for){this.renderError(`TraceHint has no for property (${this})`);return}let o=i.selectOne(n.for,{type:"port"});o||this.renderError(`${this} could not find port for selector "${n.for}"`),this.matchedPort=o,o.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:t}=this,n=t.offset?[t.offset]:t.offsets;if(!n)return[];let i=this._computePcbGlobalTransformBeforeLayout();return n.map(o=>({...Ne(i,o),via:o.via,to_layer:o.to_layer,trace_width:o.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this;t.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},XH=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,pcb_placements:[...n.pcb_placements??[]]};for(let o of t)if(o.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:r,new_center:s}=o,a=Le(e).pcb_component.get(r);if(!a)continue;let c=Le(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.pcb_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.pcb_placements[l]=u:i.pcb_placements.push(u)}return i},VH=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,schematic_placements:[...n.schematic_placements??[]]};for(let o of t)if(o.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:r,new_center:s}=o,a=Le(e).schematic_component.get(r);if(!a||!a.source_component_id)continue;let c=Le(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.schematic_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.schematic_placements[l]=u:i.schematic_placements.push(u)}return i},kIt=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i=t.filter(s=>s.edit_event_type==="edit_schematic_component_location"),o=t.filter(s=>s.edit_event_type==="edit_pcb_component_location"),r=n;return i.length>0&&(r=VH({circuitJson:e,editEvents:i,manualEditsFile:r})),o.length>0&&(r=XH({circuitJson:e,editEvents:o,manualEditsFile:r})),r},AIt=(e,t)=>{if(Le(e).pcb_trace_hint.get(t.pcb_trace_hint_id))e=e.map(i=>i.pcb_trace_hint_id===t.pcb_trace_hint_id?{...i,route:t.route}:i);else{let i=Le(e).pcb_port.get(t.pcb_port_id);e=e.filter(o=>!(o.type==="pcb_trace_hint"&&o.pcb_port_id===t.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:t.pcb_trace_hint_id,route:t.route,pcb_port_id:t.pcb_port_id,pcb_component_id:i?.pcb_component_id}])}return e},RIt=({circuitJson:e,editEvents:t})=>{e=JSON.parse(JSON.stringify(e));for(let n of t)if(n.edit_event_type==="edit_pcb_component_location"){let i=e.find(r=>r.type==="pcb_component"&&r.pcb_component_id===n.pcb_component_id);if((!i||i.center.x!==n.new_center.x||i.center.y!==n.new_center.y)&&n.original_center){let r=vn(n.new_center.x-n.original_center.x,n.new_center.y-n.original_center.y);e=e.map(s=>s.pcb_component_id!==n.pcb_component_id?s:VI(s,r))}}else n.edit_event_type==="edit_schematic_component_location"?e=e.map(i=>i.type==="schematic_component"&&i.schematic_component_id===n.schematic_component_id?{...i,center:n.new_center}:i):n.edit_event_type==="edit_pcb_trace_hint"&&(e=AIt(e,n));return e},HH=(e,t)=>{let n=e.source_group.list(),i=[],o=r=>{let s=n.filter(a=>a.parent_subcircuit_id===r);for(let a of s)a.subcircuit_id&&(i.push(a.subcircuit_id),o(a.subcircuit_id))};return o(t),i},R4=({db:e,circuitJson:t,subcircuit_id:n,minTraceWidth:i=.1})=>{if(!e&&t&&(e=Le(t)),!e)throw new Error("db or circuitJson is required");let o=e.pcb_trace_hint.list(),r=n?new Set([n]):null;if(n){let k=HH(e,n);for(let N of k)r.add(N)}let s=(t??e.toArray()).filter(k=>!n||"subcircuit_id"in k&&r.has(k.subcircuit_id)),a=e.pcb_board.list()[0];e=Le(s);let c=$i(s),l=$H([...e.pcb_component.list(),...e.pcb_smtpad.list(),...e.pcb_plated_hole.list(),...e.pcb_hole.list(),...e.pcb_via.list(),...e.pcb_cutout.list()].filter(k=>!n||r?.has(k.subcircuit_id)),c);for(let k of l){let N=k.connectedTo.flatMap(A=>c.getIdsConnectedToNet(A));k.connectedTo.push(...N)}let u=l.flatMap(k=>[{x:k.center.x-k.width/2,y:k.center.y-k.height/2},{x:k.center.x+k.width/2,y:k.center.y+k.height/2}]).concat(a?.outline??[]),h;if(a&&!a.outline?h={minX:a.center.x-a.width/2,maxX:a.center.x+a.width/2,minY:a.center.y-a.height/2,maxY:a.center.y+a.height/2}:h={minX:Math.min(...u.map(k=>k.x))-1,maxX:Math.max(...u.map(k=>k.x))+1,minY:Math.min(...u.map(k=>k.y))-1,maxY:Math.max(...u.map(k=>k.y))+1},n){let k=e.pcb_group.getWhere({subcircuit_id:n});if(k?.width&&k.height){let N={minX:k.center.x-k.width/2,maxX:k.center.x+k.width/2,minY:k.center.y-k.height/2,maxY:k.center.y+k.height/2};h={minX:Math.min(h.minX,N.minX),maxX:Math.max(h.maxX,N.maxX),minY:Math.min(h.minY,N.minY),maxY:Math.max(h.maxY,N.maxY)}}}let d=new Set(e.pcb_trace.list().map(k=>k.source_trace_id).filter(k=>!!k)),_=e.source_trace.list().filter(k=>!d.has(k.source_trace_id)).map(k=>{let N=k.connected_source_port_ids.map(G=>{let tt=e.source_port.get(G),Q=e.pcb_port.getWhere({source_port_id:G});return{...tt,...Q}});if(N.length<2)return null;let[A,R]=N,$=A.layers?.[0]??"top",j=R.layers?.[0]??"top",H=o.filter(G=>G.pcb_port_id===A.pcb_port_id||G.pcb_port_id===R.pcb_port_id),X=[];for(let G of H){let Q=e.pcb_port.get(G.pcb_port_id)?.layers?.[0]??"top";for(let V of G.route)X.push({x:V.x,y:V.y,layer:Q})}return{name:k.source_trace_id??c.getNetConnectedToId(k.source_trace_id)??"",source_trace_id:k.source_trace_id,width:k.min_trace_thickness,pointsToConnect:[{x:A.x,y:A.y,layer:$,pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},...X,{x:R.x,y:R.y,layer:j,pointId:R.pcb_port_id,pcb_port_id:R.pcb_port_id}]}}).filter(k=>k!==null),y=new Map(_.map(k=>[k.source_trace_id,k])),g=e.source_net.list().filter(k=>!n||r?.has(k.subcircuit_id)),x=[];for(let k of g){let N=e.source_trace.list().filter(A=>A.connected_source_net_ids?.includes(k.source_net_id));x.push({name:k.source_net_id??c.getNetConnectedToId(k.source_net_id),pointsToConnect:N.flatMap(A=>e.pcb_port.list().filter($=>A.connected_source_port_ids.includes($.source_port_id)).map($=>({x:$.x,y:$.y,layer:$.layers?.[0]??"top",pointId:$.pcb_port_id,pcb_port_id:$.pcb_port_id})))})}let w=e.pcb_breakout_point.list().filter(k=>!n||r?.has(k.subcircuit_id)),S=[],T=new Map;for(let k of w){let N={x:k.x,y:k.y,layer:"top"};if(k.source_trace_id){let A=y.get(k.source_trace_id)??T.get(k.source_trace_id);if(A)A.pointsToConnect.push(N);else{let R={name:k.source_trace_id,source_trace_id:k.source_trace_id,pointsToConnect:[N]};S.push(R),T.set(k.source_trace_id,R)}}else if(k.source_net_id){let A=x.find(R=>R.name===k.source_net_id);A?A.pointsToConnect.push(N):S.push({name:k.source_net_id,pointsToConnect:[N]})}else if(k.source_port_id){let A=e.pcb_port.getWhere({source_port_id:k.source_port_id});A&&S.push({name:k.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:A.x,y:A.y,layer:A.layers?.[0]??"top",pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},N]})}}let I=[..._,...x,...S],E=new Map;for(let k of I)for(let N of k.pointsToConnect)N.pointId&&E.set(N.pointId,k);let M=e.pcb_trace.list().filter(k=>!n||r?.has(k.subcircuit_id));for(let k of M){let N=new Set;for(let $ of k.route)$.start_pcb_port_id&&N.add($.start_pcb_port_id),$.end_pcb_port_id&&N.add($.end_pcb_port_id);if(N.size<2)continue;let A=N.values().next().value;if(!A)continue;let R=E.get(A);R&&[...N].every($=>E.get($)===R)&&(R.externallyConnectedPointIds??(R.externallyConnectedPointIds=[]),R.externallyConnectedPointIds.push([...N]))}return{simpleRouteJson:{bounds:h,obstacles:l,connections:I,layerCount:a?.num_layers??2,minTraceWidth:i,outline:a?.outline?.map(k=>({...k}))},connMap:c}},OIt=e=>{let t={};if(!e)return t;for(let i of aa)t[i]=0;let n=new Map;for(let i of e){let[,,o,r]=i.type.split(":");if(r==="start"){n.set(`${o}:${i.renderId}`,i);continue}if(r==="end"){let s=n.get(`${o}:${i.renderId}`);if(s){let a=i.createdAt-s.createdAt;t[o]=(t[o]||0)+a}}}return t},LIt=e=>{let t=e.map(c=>[...new Set(c)]),n=t.map(()=>[]),i=t.map(()=>null);for(let c=0;c<t.length;c++)for(let l of t[c])if(/^\d+$/.test(l)){i[c]=Number.parseInt(l);break}let o=0,r=new Set;for(let c=0;c<i.length;c++){let l=i[c];if(l===null||l<1)continue;if(!r.has(l)){r.add(l),n[c].push(`pin${l}`),o=Math.max(o,l);continue}let u=0;for(let h of n[c])h.startsWith(`pin${l}_alt`)&&u++;n[c].push(`pin${l}_alt${u+1}`)}for(let c=0;c<n.length;c++)n[c][0]?.includes("_alt")&&(o++,n[c].unshift(`pin${o}`));for(let c=0;c<n.length;c++)n[c].length===0&&(o++,n[c].push(`pin${o}`));let s={};for(let c of t)for(let l of c)/^\d+$/.test(l)||(s[l]=(s[l]??0)+1);let a={};for(let c=0;c<t.length;c++){let l=t[c];for(let u of l)/^\d+$/.test(u)||(s[u]===1?n[c].push(u):(a[u]=(a[u]??0)+1,n[c].push(`${u}${a[u]}`)))}return n};function Y4({db:e,schematicComponentId:t,deltaX:n,deltaY:i}){let o=e.schematic_rect.list({schematic_component_id:t});for(let c of o)c.center.x+=n,c.center.y+=i;let r=e.schematic_line.list({schematic_component_id:t});for(let c of r)c.x1+=n,c.y1+=i,c.x2+=n,c.y2+=i;let s=e.schematic_circle.list({schematic_component_id:t});for(let c of s)c.center.x+=n,c.center.y+=i;let a=e.schematic_arc.list({schematic_component_id:t});for(let c of a)c.center.x+=n,c.center.y+=i}var cH=(0,GH.default)("Group_doInitialSchematicLayoutMatchAdapt");function FIt(e){let{db:t}=e.root,n=If(t.toArray(),{source_group_id:e.source_group_id}),i=xT(n);cH.enabled&&global.debugGraphics?.push(dc(i,{title:`floatingBpcGraph-${e.name}`}));let o=xT(n),r={boxes:o.boxes,pins:o.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:s}=YB([{variantName:"default",floatingGraph:o},{variantName:"noNotConnected",floatingGraph:r}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(o.boxes.filter(c=>o.pins.filter(h=>h.boxId===c.boxId).filter(h=>!h.color.includes("center")).length<=2).map(c=>c.boxId)),corpus:{}});cH.enabled&&global.debugGraphics?.push(dc(s,{title:`laidOutBpcGraph-${e.name}`}));let a=e._getGlobalSchematicPositionBeforeLayout();for(let c of s.boxes){if(!c.center)continue;let l=t.schematic_component.get(c.boxId);if(l){let h={x:c.center.x+a.x,y:c.center.y+a.y},d=t.schematic_port.list({schematic_component_id:l.schematic_component_id}),_=t.schematic_text.list({schematic_component_id:l.schematic_component_id}),y={x:h.x-l.center.x,y:h.y-l.center.y};for(let g of d)g.center.x+=y.x,g.center.y+=y.y;for(let g of _)g.position.x+=y.x,g.position.y+=y.y;Y4({db:t,schematicComponentId:l.schematic_component_id,deltaX:y.x,deltaY:y.y}),l.center=h;continue}let u=t.schematic_net_label.get(c.boxId);if(u){let h=s.pins.find(_=>_.boxId===c.boxId&&_.color==="netlabel_center");if(!h)throw new Error(`No pin found for net label: ${c.boxId}`);let d={x:c.center.x+a.x,y:c.center.y+a.y};u.center=d,u.anchor_position={x:d.x+h.offset.x,y:d.y+h.offset.y};continue}console.error(`No schematic element found for box: ${c.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var de=(0,UH.default)("Group_doInitialSchematicLayoutMatchpack");function lH(e){switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function uH(e,t){let n=["right","up","left","down"],i=n.indexOf(e);if(i===-1)return e;let o=Math.round(t/90),r=(i+o)%4;return n[r<0?r+4:r]}function zIt(e,t,n){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};de(`[${n.name}] Processing ${e.childNodes.length} child nodes for input problem`),e.childNodes.forEach((r,s)=>{if(de(`[${n.name}] Processing child ${s}: nodeType=${r.nodeType}`),r.nodeType==="component"?de(`[${n.name}] - Component: ${r.sourceComponent?.name}`):r.nodeType==="group"&&de(`[${n.name}] - Group: ${r.sourceGroup?.name}`),r.nodeType==="component"&&r.sourceComponent){let a=r.sourceComponent.name||`chip_${s}`,c=t.schematic_component.getWhere({source_component_id:r.sourceComponent.source_component_id});if(!c)return;let l=n.children.find(S=>S.source_component_id===r.sourceComponent?.source_component_id),u=[0,90,180,270];l?._parsedProps?.schOrientation&&(u=[0]),l?._parsedProps?.schRotation!==void 0&&(u=[0]),l?._parsedProps?.facingDirection&&(u=[0]),l?._parsedProps?.schFacingDirection&&(u=[0]),l?.componentName==="Chip"&&(u=[0]);let h=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,d=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,_=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,y=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0;l?.config.shouldRenderAsSchematicBox&&(_+=.4,y+=.4);let g=(d-h)/2,x=(_-y)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+h+d,y:(c.size?.height||1)+_+y},availableRotations:u};let w=t.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let S of w){let T=t.source_port.get(S.source_port_id);if(!T)continue;let I=`${a}.${T.pin_number||T.name||S.schematic_port_id}`;i.chipMap[a].pins.push(I);let E=lH(S.facing_direction);i.chipPinMap[I]={pinId:I,offset:{x:(S.center?.x||0)-(c.center.x||0)+g,y:(S.center?.y||0)-(c.center.y||0)+x},side:E}}}else if(r.nodeType==="group"&&r.sourceGroup){let a=r.sourceGroup.name||`group_${s}`;de(`[${n.name}] Processing nested group: ${a}`);let c=t.schematic_group?.getWhere?.({source_group_id:r.sourceGroup.source_group_id}),l=n.children.find(u=>u.source_group_id===r.sourceGroup?.source_group_id);if(de(`[${n.name}] Found schematic_group for ${a}:`,c),c){de(`[${n.name}] Treating group ${a} as composite chip`);let u=t.schematic_component.list({schematic_group_id:c.schematic_group_id});de(`[${n.name}] Group ${a} has ${u.length} components:`,u.map(A=>A.source_component_id));let h=1/0,d=-1/0,_=1/0,y=-1/0,g=!1;for(let A of u)if(A.center&&A.size){g=!0;let R=A.size.width/2,$=A.size.height/2;h=Math.min(h,A.center.x-R),d=Math.max(d,A.center.x+R),_=Math.min(_,A.center.y-$),y=Math.max(y,A.center.y+$)}let x=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,w=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,S=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,T=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,I=(w-x)/2,E=(S-T)/2,M=(g?d-h:2)+x+w,k=(g?y-_:2)+S+T;de(`[${n.name}] Group ${a} computed size: ${M} x ${k}`);let N=[];for(let A of u){let R=t.schematic_port.list({schematic_component_id:A.schematic_component_id});for(let $ of R){let j=t.source_port.get($.source_port_id);if(!j)continue;let H=`${a}.${j.pin_number||j.name||$.schematic_port_id}`;N.push(H);let X=c.center||{x:0,y:0},G=lH($.facing_direction);i.chipPinMap[H]={pinId:H,offset:{x:($.center?.x||0)-X.x+I,y:($.center?.y||0)-X.y+E},side:G}}}de(`[${n.name}] Group ${a} has ${N.length} pins:`,N),i.chipMap[a]={chipId:a,pins:N,size:{x:M,y:k}},de(`[${n.name}] Added group ${a} to chipMap`)}else de(`[${n.name}] Warning: No schematic_group found for group ${a}`)}}),de(`[${n.name}] Creating connections using connectivity keys`);let o=new Map;for(let[r,s]of Object.entries(i.chipMap))for(let a of s.pins){let c=a.split(".").pop(),l=e.childNodes.find(u=>u.nodeType==="component"&&u.sourceComponent?u.sourceComponent.name===r:u.nodeType==="group"&&u.sourceGroup?`group_${e.childNodes.indexOf(u)}`===r:!1);if(l?.nodeType==="group"&&l.sourceGroup){let u=t.schematic_group?.getWhere?.({source_group_id:l.sourceGroup.source_group_id});if(u){let h=t.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let d of h){let _=t.source_port.list({source_component_id:d.source_component_id});for(let y of _){let g=y.pin_number||y.name;if(String(g)===String(c))if(y.subcircuit_connectivity_map_key){let x=y.subcircuit_connectivity_map_key;o.has(x)||o.set(x,[]),o.get(x).push(a),de(`[${n.name}] \u2713 Pin ${a} has connectivity key: ${x}`)}else de(`[${n.name}] Pin ${a} has no connectivity key`)}}}}else if(l?.nodeType==="component"&&l.sourceComponent){let u=t.source_port.list({source_component_id:l.sourceComponent.source_component_id});for(let h of u){let d=h.pin_number||h.name;if(String(d)===String(c)&&h.subcircuit_connectivity_map_key){let _=h.subcircuit_connectivity_map_key;o.has(_)||o.set(_,[]),o.get(_).push(a),de(`[${n.name}] Pin ${a} has connectivity key: ${_}`)}}}}de(`[${n.name}] Found ${o.size} connectivity groups:`,Array.from(o.entries()).map(([r,s])=>({key:r,pins:s})));for(let[r,s]of o)if(s.length>=2){let a=t.source_trace.list().filter(u=>u.subcircuit_connectivity_map_key===r),c=a.some(u=>u.connected_source_net_ids&&u.connected_source_net_ids.length>0),l=a.some(u=>u.connected_source_port_ids&&u.connected_source_port_ids.length>=2);if(de(`[${n.name}] Connectivity ${r}: hasNetConnections=${c}, hasDirectConnections=${l}`),l){for(let u of a)if(u.connected_source_port_ids&&u.connected_source_port_ids.length>=2){let h=[];for(let d of u.connected_source_port_ids)for(let _ of s){let y=_.split(".").pop(),g=t.source_port.get(d);if(g&&String(g.pin_number||g.name)===String(y)){let x=_.split(".")[0],w=e.childNodes.find(S=>S.nodeType==="component"&&S.sourceComponent?S.sourceComponent.name===x:S.nodeType==="group"&&S.sourceGroup?`group_${e.childNodes.indexOf(S)}`===x:!1);w?.nodeType==="component"&&w.sourceComponent&&t.source_port.list({source_component_id:w.sourceComponent.source_component_id}).some(T=>T.source_port_id===d)&&h.push(_)}}for(let d=0;d<h.length;d++)for(let _=d+1;_<h.length;_++){let y=h[d],g=h[_];i.pinStrongConnMap[`${y}-${g}`]=!0,i.pinStrongConnMap[`${g}-${y}`]=!0,de(`[${n.name}] Created strong connection: ${y} <-> ${g}`)}}}if(c){let u=t.source_net.getWhere({subcircuit_connectivity_map_key:r}),h=u?.is_ground??!1,d=u?.is_power??!1;i.netMap[r]={netId:r,isGround:h,isPositiveVoltageSource:d};for(let _ of s)i.netConnMap[`${_}-${r}`]=!0;de(`[${n.name}] Created net ${r} with ${s.length} pins:`,s)}}return i}function DIt(e){let{db:t}=e.root,n=ih(t.toArray(),{source_group_id:e.source_group_id});if(de(`[${e.name}] Starting matchpack layout with ${n.childNodes.length} children`),de(`[${e.name}] Tree structure:`,JSON.stringify(n,null,2)),n.childNodes.length<=1){de(`[${e.name}] Only ${n.childNodes.length} children, skipping layout`);return}de("Converting circuit tree to InputProblem...");let i=zIt(n,t,e);de.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${e.name}`,content:JSON.stringify(i,null,2)});let o=new GY(i);if(de("Starting LayoutPipelineSolver..."),de.enabled&&global.debugGraphics){let c=o.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${e.name}`})}if(o.solve(),de(`Solver completed in ${o.iterations} iterations`),de(`Solved: ${o.solved}, Failed: ${o.failed}`),o.failed)throw de(`Solver failed with error: ${o.error}`),new Error(`Matchpack layout solver failed: ${o.error}`);let r=o.getOutputLayout();if(de("OutputLayout:",JSON.stringify(r,null,2)),de("Solver completed successfully:",!o.failed),de.enabled&&global.debugGraphics){let c=o.visualize();global.debugGraphics.push({...c,title:`matchpack-final-${e.name}`})}let s=o.checkForOverlaps(r);if(s.length>0){de(`Warning: Found ${s.length} overlapping components:`);for(let c of s)de(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=e._getGlobalSchematicPositionBeforeLayout();de(`Group offset: x=${a.x}, y=${a.y}`),de(`Applying layout results for ${Object.keys(r.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(r.chipPlacements)){de(`Processing placement for chip: ${c} at (${l.x}, ${l.y})`);let u=n.childNodes.find(d=>{if(d.nodeType==="component"&&d.sourceComponent){let _=d.sourceComponent.name===c;return de(` Checking component ${d.sourceComponent.name}: matches=${_}`),_}if(d.nodeType==="group"&&d.sourceGroup){let _=d.sourceGroup.name,y=`group_${n.childNodes.indexOf(d)}`,g=y===c;return de(` Checking group ${_} (expected chipId: ${y}): matches=${g}`),g}return!1});if(!u){de(`Warning: No tree node found for chip: ${c}`),de("Available tree nodes:",n.childNodes.map((d,_)=>({type:d.nodeType,name:d.nodeType==="component"?d.sourceComponent?.name:d.sourceGroup?.name,expectedChipId:d.nodeType==="group"?`group_${_}`:d.sourceComponent?.name})));continue}let h={x:l.x+a.x,y:l.y+a.y};if(u.nodeType==="component"&&u.sourceComponent){let d=t.schematic_component.getWhere({source_component_id:u.sourceComponent.source_component_id});if(d){de(`Moving component ${c} to (${h.x}, ${h.y})`);let _=t.schematic_port.list({schematic_component_id:d.schematic_component_id}),y=t.schematic_text.list({schematic_component_id:d.schematic_component_id}),g={x:h.x-d.center.x,y:h.y-d.center.y};for(let x of _)x.center.x+=g.x,x.center.y+=g.y;for(let x of y)x.position.x+=g.x,x.position.y+=g.y;if(Y4({db:t,schematicComponentId:d.schematic_component_id,deltaX:g.x,deltaY:g.y}),d.center=h,l.ccwRotationDegrees!==0){de(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let x=l.ccwRotationDegrees*Math.PI/180,w=Math.cos(x),S=Math.sin(x);for(let T of _){let I=T.center.x-h.x,E=T.center.y-h.y,M=I*w-E*S,k=I*S+E*w;T.center.x=h.x+M,T.center.y=h.y+k;let N=T.facing_direction||"right";T.facing_direction=uH(N,l.ccwRotationDegrees),T.side_of_component=(T.facing_direction==="up"?"top":T.facing_direction==="down"?"bottom":T.facing_direction)||T.side_of_component}for(let T of y){let I=T.position.x-h.x,E=T.position.y-h.y,M=I*w-E*S,k=I*S+E*w;T.position.x=h.x+M,T.position.y=h.y+k}if(d.symbol_name){let T=d.symbol_name.match(/_(right|left|up|down)$/);T&&(d.symbol_name=d.symbol_name.replace(T[0],`_${uH(T[1],l.ccwRotationDegrees)}`))}}}}else if(u.nodeType==="group"&&u.sourceGroup){let d=t.schematic_group?.getWhere?.({source_group_id:u.sourceGroup.source_group_id});if(d){de(`Moving group ${c} to (${h.x}, ${h.y}) from (${d.center?.x}, ${d.center?.y})`);let _=t.schematic_component.list({schematic_group_id:d.schematic_group_id});de(`Group ${c} has ${_.length} components to move`);let y=d.center||{x:0,y:0},g={x:h.x-y.x,y:h.y-y.y};de(`Position delta for group ${c}: (${g.x}, ${g.y})`);for(let x of _)if(x.center){let w={...x.center};x.center.x+=g.x,x.center.y+=g.y,de(`Moved component ${x.source_component_id} from (${w.x}, ${w.y}) to (${x.center.x}, ${x.center.y})`);let S=t.schematic_port.list({schematic_component_id:x.schematic_component_id}),T=t.schematic_text.list({schematic_component_id:x.schematic_component_id});for(let I of S)I.center&&(I.center.x+=g.x,I.center.y+=g.y);for(let I of T)I.position&&(I.position.x+=g.x,I.position.y+=g.y)}d.center=h,de(`Updated group ${c} center to (${h.x}, ${h.y})`)}}}de("Matchpack layout completed successfully")}function $It(e){if(!e.isSubcircuit)return;let{db:t}=e.root,n=e.selectAll("trace"),i=new qp({});i.addConnections(n.map(a=>{let c=t.source_trace.get(a.source_trace_id);return c?[c.source_trace_id,...c.connected_source_port_ids,...c.connected_source_net_ids]:null}).filter(a=>a!==null));let{name:o}=e._parsedProps;for(let a of n){if(!a.source_trace_id)continue;let c=i.getNetConnectedToId(a.source_trace_id);c&&(a.subcircuit_connectivity_map_key=`${o??`unnamedsubcircuit${e._renderId}`}_${c}`,t.source_trace.update(a.source_trace_id,{subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}))}let r=new Set;for(let a of n){if(!a.source_trace_id)continue;let c=t.source_trace.get(a.source_trace_id);if(c)for(let l of c.connected_source_port_ids)r.add(l)}for(let a of r){let c=i.getNetConnectedToId(a);if(!c)continue;let l=`${o??`unnamedsubcircuit${e._renderId}`}_${c}`;t.source_port.update(a,{subcircuit_connectivity_map_key:l})}let s=new Set;for(let a of n){if(!a.source_trace_id)continue;let c=t.source_trace.get(a.source_trace_id);if(c)for(let l of c.connected_source_net_ids)s.add(l)}for(let a of s){let c=i.getNetConnectedToId(a);if(!c)continue;let l=`${o??`unnamedsubcircuit${e._renderId}`}_${c}`;t.source_net.update(a,{subcircuit_connectivity_map_key:l})}}function jIt(e){let{db:t}=e.root,n=e._parsedProps,i=e.children.filter(E=>{let M=E._parsedProps?.schX!==void 0||E._parsedProps?.schY!==void 0;return E.schematic_component_id&&!M});if(i.length===0)return;let o=0,r=0;for(let E of i){let M=t.schematic_component.get(E.schematic_component_id);M?.size&&(o=Math.max(o,M.size.width),r=Math.max(r,M.size.height))}o===0&&i.length>0&&(o=1),r===0&&i.length>0&&(r=1);let s=n.gridCols,a,c=n.gridGap,l=n.gridRowGap,u=n.gridColumnGap;n.schLayout?.grid&&(s=n.schLayout.grid.cols??s,a=n.schLayout.grid.rows,c=n.schLayout.gridGap??c,l=n.schLayout.gridRowGap??l,u=n.schLayout.gridColumnGap??u);let h,d;s!==void 0&&a!==void 0?(h=s,d=a):s!==void 0?(h=s,d=Math.ceil(i.length/h)):a!==void 0?(d=a,h=Math.ceil(i.length/d)):(h=Math.ceil(Math.sqrt(i.length)),d=Math.ceil(i.length/h)),h===0&&i.length>0&&(h=1),d===0&&i.length>0&&(d=i.length);let _,y,g=E=>{if(E!==void 0)return typeof E=="number"?E:D.parse(E)};if(l!==void 0||u!==void 0){let E=typeof c=="object"&&c!==null?c.x:c,M=typeof c=="object"&&c!==null?c.y:c;_=g(u??E)??1,y=g(l??M)??1}else if(typeof c=="number")_=c,y=c;else if(typeof c=="string"){let E=D.parse(c);_=E,y=E}else if(typeof c=="object"&&c!==null){let E=c.x,M=c.y;_=typeof E=="number"?E:D.parse(E??"0mm"),y=typeof M=="number"?M:D.parse(M??"0mm")}else _=1,y=1;let x=h*o+Math.max(0,h-1)*_,w=d*r+Math.max(0,d-1)*y,S=e._getGlobalSchematicPositionBeforeLayout(),T=S.x-x/2+o/2,I=S.y+w/2-r/2;for(let E=0;E<i.length;E++){let M=i[E];if(!M.schematic_component_id)continue;let k=Math.floor(E/h),N=E%h;if(k>=d||N>=h){console.warn(`Schematic grid layout: Child ${M.getString()} at index ${E} (row ${k}, col ${N}) exceeds specified grid dimensions (${d}x${h}). Skipping placement.`);continue}let A=T+N*(o+_),R=I-k*(r+y),$=t.schematic_component.get(M.schematic_component_id);if($){let j=$.center,H={x:A,y:R};t.schematic_component.update(M.schematic_component_id,{center:H});let X=H.x-j.x,G=H.y-j.y,tt=t.schematic_port.list({schematic_component_id:M.schematic_component_id});for(let V of tt)t.schematic_port.update(V.schematic_port_id,{center:{x:V.center.x+X,y:V.center.y+G}});let Q=t.schematic_text.list({schematic_component_id:M.schematic_component_id});for(let V of Q)t.schematic_text.update(V.schematic_text_id,{position:{x:V.position.x+X,y:V.position.y+G}});Y4({db:t,schematicComponentId:M.schematic_component_id,deltaX:X,deltaY:G})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:x,height:w,center:S})}var pH=(e,t)=>{let{sourceComponent:n,sourceGroup:i}=t;if(t.nodeType==="component"){let o=e.schematic_component.getWhere({source_component_id:n?.source_component_id});return o?.size?{width:o.size.width,height:o.size.height}:null}if(t.nodeType==="group"){let o=e.schematic_group.getWhere({source_group_id:i?.source_group_id});if(o?.width&&o?.height)return{width:o.width,height:o.height};let r=e.schematic_component.list({schematic_group_id:o?.schematic_group_id}),s=1/0,a=-1/0,c=1/0,l=-1/0;for(let d of r)if(d.center&&d.size){let _=d.size.width/2,y=d.size.height/2;s=Math.min(s,d.center.x-_),a=Math.max(a,d.center.x+_),c=Math.min(c,d.center.y-y),l=Math.max(l,d.center.y+y)}let u=a-s,h=l-c;return{width:u,height:h}}return null},BIt=e=>{let{db:t}=e.root,n=e._parsedProps,i=ih(t.toArray(),{source_group_id:e.source_group_id}),o=n.schJustifyContent??n.justifyContent,r=n.schAlignItems??n.alignItems,s=n.schFlexGap??n.schGap??n.gap,a=n.schFlexDirection??"row",c={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[o??"space-between"],l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[r??"center"];if(!c)throw new Error(`Invalid justifyContent value: "${o}"`);if(!l)throw new Error(`Invalid alignItems value: "${r}"`);let u=0,h=0;typeof s=="object"?(u=s.y??0,h=s.x??0):typeof s=="number"?(u=s,h=s):typeof s=="string"&&(u=D.parse(s),h=D.parse(s));let d,_=n.width??n.schWidth??void 0,y=n.height??n.schHeight??void 0;(_===void 0||y===void 0)&&(d=ub(i.childNodes.map(I=>pH(t,I)).filter(I=>I!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h}),_=d.width,y=d.height);let x=new dx(_,y,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h});for(let I of i.childNodes){let E=pH(t,I);x.addChild({metadata:I,width:E?.width??0,height:E?.height??0,flexBasis:E?a==="row"?E.width:E.height:void 0})}x.build();let w={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let I of x.children)w.minX=Math.min(w.minX,I.position.x),w.minY=Math.min(w.minY,I.position.y),w.maxX=Math.max(w.maxX,I.position.x+I.size.width),w.maxY=Math.max(w.maxY,I.position.y+I.size.height);w.width=w.maxX-w.minX,w.height=w.maxY-w.minY;let S={x:-(w.maxX+w.minX)/2,y:-(w.maxY+w.minY)/2},T=t.toArray();for(let I of x.children){let{sourceComponent:E,sourceGroup:M}=I.metadata;if(E){let k=t.schematic_component.getWhere({source_component_id:E.source_component_id});if(!k)continue;QD(T,k.schematic_component_id,{x:I.position.x+I.size.width/2+S.x,y:I.position.y+I.size.height/2+S.y})}if(M){if(!t.schematic_group.getWhere({source_group_id:M.source_group_id}))continue;e$(T,M.source_group_id,{x:I.position.x+I.size.width/2+S.x,y:I.position.y+I.size.height/2+S.y})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:w.width,height:w.height})},S4=1;function YIt(e){let{db:t}=e.root,n=e._parsedProps,i=XIt(e);if(i.length===0)return;let o=VIt({db:t,pcbChildren:i}),r=HIt(n),s=GIt({props:n,pcbChildren:i,childDimensions:o,gridConfig:r}),a=WIt({pcbChildren:i,childDimensions:o,gridLayout:s,gridConfig:r}),{itemCoordinates:c}=a.layout();ZIt({db:t,group:e,pcbChildren:i,itemCoordinates:c,gridLayout:s}),KIt({db:t,group:e,props:n,gridLayout:s})}function XIt(e){return e.children.filter(t=>t.pcb_component_id||t.pcb_group_id)}function VIt(e){let{db:t,pcbChildren:n}=e,i=0,o=0;for(let r of n){let s=0,a=0;if(r.pcb_group_id){let c=t.pcb_group.get(r.pcb_group_id);s=c?.width??0,a=c?.height??0}else if(r.pcb_component_id){let c=t.pcb_component.get(r.pcb_component_id);s=c?.width??0,a=c?.height??0}i=Math.max(i,s),o=Math.max(o,a)}return{width:i,height:o}}function HIt(e){let t=e.pcbGridCols??e.gridCols??e.pcbLayout?.grid?.cols,n=e.pcbGridRows??e.pcbLayout?.grid?.rows,i=e.pcbGridTemplateColumns,o=e.pcbGridTemplateRows,r=h=>h===void 0?S4:typeof h=="number"?h:D.parse(h),s=e.pcbGridGap??e.gridGap??e.pcbLayout?.gridGap,a=e.pcbGridRowGap??e.gridRowGap??e.pcbLayout?.gridRowGap,c=e.pcbGridColumnGap??e.gridColumnGap??e.pcbLayout?.gridColumnGap,l=S4,u=S4;if(a!==void 0||c!==void 0){let h=typeof s=="object"?s?.x:s,d=typeof s=="object"?s?.y:s;l=r(c??h),u=r(a??d)}else if(typeof s=="object"&&s!==null)l=r(s.x),u=r(s.y);else{let h=r(s);l=h,u=h}return{cols:t,rows:n,gapX:l,gapY:u,templateColumns:i,templateRows:o}}function GIt(e){let{props:t,pcbChildren:n,childDimensions:i,gridConfig:o}=e;return t.pcbGridTemplateColumns||t.pcbGridTemplateRows?UIt({props:t,gridConfig:o,pcbChildren:n,childDimensions:i}):qIt({gridConfig:o,pcbChildren:n,childDimensions:i})}function UIt(e){let{props:t,gridConfig:n,pcbChildren:i,childDimensions:o}=e,r=t.pcbGridTemplateColumns??"",s=t.pcbGridTemplateRows??"",a=d=>{let _=d.match(/repeat\((\d+),/);return _?parseInt(_[1]):Math.ceil(Math.sqrt(i.length))},c=t.pcbGridTemplateColumns?a(r):Math.ceil(Math.sqrt(i.length)),l=t.pcbGridTemplateRows?a(s):Math.ceil(i.length/c),u=c*o.width+Math.max(0,c-1)*n.gapX,h=l*o.height+Math.max(0,l-1)*n.gapY;return{gridTemplateColumns:r,gridTemplateRows:s,containerWidth:u,containerHeight:h}}function qIt(e){let{gridConfig:t,pcbChildren:n,childDimensions:i}=e,o,r;t.cols!==void 0&&t.rows!==void 0?(o=t.cols,r=t.rows):t.cols!==void 0?(o=t.cols,r=Math.ceil(n.length/o)):t.rows!==void 0?(r=t.rows,o=Math.ceil(n.length/r)):(o=Math.ceil(Math.sqrt(n.length)),r=Math.ceil(n.length/o)),o=Math.max(1,o),r=Math.max(1,r);let s=o*i.width+Math.max(0,o-1)*t.gapX,a=r*i.height+Math.max(0,r-1)*t.gapY,c=`repeat(${o}, ${i.width}px)`,l=`repeat(${r}, ${i.height}px)`;return{gridTemplateColumns:c,gridTemplateRows:l,containerWidth:s,containerHeight:a}}function WIt(e){let{pcbChildren:t,childDimensions:n,gridLayout:i,gridConfig:o}=e,r=t.map((s,a)=>({key:s.getString()||`child-${a}`,contentWidth:n.width,contentHeight:n.height}));return new eX({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[o.gapY,o.gapX],children:r})}function ZIt(e){let{db:t,group:n,pcbChildren:i,itemCoordinates:o,gridLayout:r}=e,s=n._getGlobalPcbPositionBeforeLayout(),a=t.toArray();for(let c=0;c<i.length;c++){let l=i[c],u=l.getString()||`child-${c}`,h=o[u];if(!h){console.warn(`PCB grid layout: No coordinates found for child ${u}`);continue}let d=s.x-r.containerWidth/2+h.x+h.width/2,_=s.y+r.containerHeight/2-h.y-h.height/2;if(l.pcb_component_id)cb(a,l.pcb_component_id,{x:d,y:_});else{let y=l;y.pcb_group_id&&y.source_group_id&&lb(a,y.source_group_id,{x:d,y:_})}}}function KIt(e){let{db:t,group:n,props:i,gridLayout:o}=e;if(n.pcb_group_id){let r=n._getGlobalPcbPositionBeforeLayout();t.pcb_group.update(n.pcb_group_id,{width:i.width??o.containerWidth,height:i.height??o.containerHeight,center:r})}}function JIt(e){let t={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof e=="object"&&!e.preset)return{local:!(e.serverUrl||e.serverMode||e.serverCacheEnabled),...t,...e};let n=typeof e=="object"?e.preset:e,i=typeof e=="object"?e:{};switch(typeof n=="string"?n.replace(/_/g,"-"):n){case"auto-local":return{local:!0,groupMode:"subcircuit"};case"sequential-trace":return{local:!0,groupMode:"sequential-trace"};case"subcircuit":return{local:!0,groupMode:"subcircuit"};case"auto-cloud":{let{preset:r,local:s,groupMode:a,...c}=i;return{local:!1,groupMode:"subcircuit",...t,...c}}case"laser-prefab":{let{preset:r,local:s,groupMode:a,...c}=i;return{local:!0,groupMode:"subcircuit",preset:"laser_prefab",...c}}default:return{local:!0,groupMode:"subcircuit"}}}var QIt=(e,t)=>{let n=e.children.filter(h=>h.componentName==="Constraint"&&h._parsedProps.pcb),i=new Map,o={},r=h=>(o[h]!==h&&(o[h]=r(o[h])),o[h]),s=(h,d)=>{let _=r(h),y=r(d);_!==y&&(o[y]=_)},a=h=>{h in o||(o[h]=h)},c=h=>{let d=h.startsWith(".")?h.slice(1):h;return e.children.find(y=>y.name===d)?.pcb_component_id??void 0};for(let h of n){let d=h._parsedProps;if("left"in d&&"right"in d){let _=c(d.left),y=c(d.right);_&&y&&(a(_),a(y),s(_,y))}else if("top"in d&&"bottom"in d){let _=c(d.top),y=c(d.bottom);_&&y&&(a(_),a(y),s(_,y))}else if("for"in d&&Array.isArray(d.for)){let _=d.for.map(y=>c(y)).filter(y=>!!y);for(let y of _)a(y);for(let y=1;y<_.length;y++)s(_[0],_[y])}}for(let h of Object.keys(o)){let d=r(h);i.has(d)||i.set(d,{componentIds:[],constraints:[]}),i.get(d).componentIds.push(h)}for(let h of n){let d=h._parsedProps,_;if("left"in d?_=c(d.left):"top"in d?_=c(d.top):"for"in d&&(_=c(d.for[0])),!_)continue;let y=r(_);i.get(y)?.constraints.push(h)}let l={},u=Object.fromEntries(t.components.map(h=>[h.componentId,h]));for(let[h,d]of i.entries()){if(d.componentIds.length<=1)continue;let _=new Qp,y={},g=(A,R)=>{let $=`${A}_${R}`;return y[$]||(y[$]=new Us($)),y[$]},x=d.componentIds[0];_.addConstraint(new ci(g(x,"x"),Vn.Eq,0,wn.required)),_.addConstraint(new ci(g(x,"y"),Vn.Eq,0,wn.required));for(let A of d.constraints){let R=A._parsedProps;if("xDist"in R){let $=c(R.left),j=c(R.right);$&&j&&_.addConstraint(new ci(new Cn(g(j,"x"),[-1,g($,"x")]),Vn.Eq,R.xDist,wn.required))}else if("yDist"in R){let $=c(R.top),j=c(R.bottom);$&&j&&_.addConstraint(new ci(new Cn(g($,"y"),[-1,g(j,"y")]),Vn.Eq,R.yDist,wn.required))}else if("sameX"in R&&Array.isArray(R.for)){let $=R.for.map(j=>c(j)).filter(j=>!!j);if($.length>1){let j=g($[0],"x");for(let H=1;H<$.length;H++)_.addConstraint(new ci(new Cn(g($[H],"x"),[-1,j]),Vn.Eq,0,wn.required))}}else if("sameY"in R&&Array.isArray(R.for)){let $=R.for.map(j=>c(j)).filter(j=>!!j);if($.length>1){let j=g($[0],"y");for(let H=1;H<$.length;H++)_.addConstraint(new ci(new Cn(g($[H],"y"),[-1,j]),Vn.Eq,0,wn.required))}}}_.updateVariables();let w={};for(let A of d.componentIds)w[A]={x:g(A,"x").value(),y:g(A,"y").value()};let S=1/0,T=1/0,I=-1/0,E=-1/0;for(let A of d.componentIds){let R=u[A],$=w[A];if(R)for(let j of R.pads){let H=$.x+j.offset.x,X=$.y+j.offset.y;S=Math.min(S,H-j.size.x/2),I=Math.max(I,H+j.size.x/2),T=Math.min(T,X-j.size.y/2),E=Math.max(E,X+j.size.y/2)}}let M={x:(S+I)/2,y:(T+E)/2},k=[],N={};for(let A of d.componentIds){let R=u[A],$=w[A];if(R){N[A]={x:$.x-M.x,y:$.y-M.y};for(let j of R.pads)k.push({padId:j.padId,networkId:j.networkId,type:j.type,size:j.size,offset:{x:$.x+j.offset.x-M.x,y:$.y+j.offset.y-M.y}})}}t.components=t.components.filter(A=>!d.componentIds.includes(A.componentId)),t.components.push({componentId:d.componentIds[0],pads:k,availableRotationDegrees:[0]}),d.relativeCenters=N,l[d.componentIds[0]]=d}return l},hH=({db:e,pcbComponentId:t,rotationDegrees:n,layer:i})=>{if(n==null||!e?.cad_component?.list)return;let o=e.cad_component.getWhere({pcb_component_id:t});if(!o)return;let r=i?.toLowerCase?.()==="bottom"?-n:n,s=o.rotation?.z??0,a={...o.rotation??{x:0,y:0,z:0},z:Vl(s+r)};e.cad_component.update(o.cad_component_id,{rotation:a}),o.rotation=a},Nm=(e,t,n)=>{if(t===n)return!0;let i=e.source_group.get(t);return!i||!i.parent_source_group_id?!1:Nm(e,i.parent_source_group_id,n)},tTt=(e,t,n)=>{let{db:i}=e.root;for(let o of t.components){let{center:r,componentId:s,ccwRotationOffset:a,ccwRotationDegrees:c}=o,l=n[s];if(l){let x=c??a??0,w=x*Math.PI/180;for(let S of l.componentIds){let T=l.relativeCenters[S];if(!T)continue;let I={x:T.x*Math.cos(w)-T.y*Math.sin(w),y:T.x*Math.sin(w)+T.y*Math.cos(w)},E=i.pcb_component.get(S);if(!E)continue;let M=E.center,k=Qn(e._computePcbGlobalTransformBeforeLayout(),vn(r.x+I.x,r.y+I.y),Ua(w),vn(-M.x,-M.y)),N=i.toArray().filter(A=>"pcb_component_id"in A&&A.pcb_component_id===S);eh(N,k),hH({db:i,pcbComponentId:S,rotationDegrees:x,layer:E.layer})}continue}let u=i.pcb_component.get(s);if(u){let x=e.source_group_id,S=i.source_component.get(u.source_component_id)?.source_group_id;if(S!==void 0&&!Nm(i,S,x))continue;let T=u.center,I=c??a??0,E=Qn(e._computePcbGlobalTransformBeforeLayout(),vn(r.x,r.y),Ua(I*Math.PI/180),vn(-T.x,-T.y)),M=i.toArray().filter(k=>"pcb_component_id"in k&&k.pcb_component_id===s);eh(M,E),hH({db:i,pcbComponentId:s,rotationDegrees:I,layer:u.layer});continue}let h=i.pcb_group.list().find(x=>x.source_group_id===s);if(!h)continue;let d=h.center,_=c??a??0,y=Qn(e._computePcbGlobalTransformBeforeLayout(),vn(r.x,r.y),Ua(_*Math.PI/180),vn(-d.x,-d.y)),g=i.toArray().filter(x=>{if("source_group_id"in x&&x.source_group_id&&(x.source_group_id===s||Nm(i,x.source_group_id,s)))return!0;if("source_component_id"in x&&x.source_component_id){let w=i.source_component.get(x.source_component_id);if(w?.source_group_id&&(w.source_group_id===s||Nm(i,w.source_group_id,s)))return!0}if("pcb_component_id"in x&&x.pcb_component_id){let w=i.pcb_component.get(x.pcb_component_id);if(w?.source_component_id){let S=i.source_component.get(w.source_component_id);if(S?.source_group_id&&(S.source_group_id===s||Nm(i,S.source_group_id,s)))return!0}}return!1});eh(g,y),i.pcb_group.update(h.pcb_group_id,{center:r})}};function eTt(e){switch(e.shape){case"rect":case"rotated_rect":case"pill":case"rotated_pill":return{width:e.width,height:e.height};case"circle":return{width:e.radius*2,height:e.radius*2};case"polygon":if(!e.points||e.points.length===0)return null;let t=e.points.map(a=>a.x),n=e.points.map(a=>a.y),i=Math.min(...t),o=Math.max(...t),r=Math.min(...n),s=Math.max(...n);return{width:o-i,height:s-r};default:return null}}function nTt(e){switch(e.shape){case"circular_hole_with_rect_pad":case"pill_hole_with_rect_pad":case"rotated_pill_hole_with_rect_pad":return{width:e.rect_pad_width,height:e.rect_pad_height};case"circle":return{width:e.outer_diameter,height:e.outer_diameter};case"oval":return{width:e.outer_width,height:e.outer_height};case"pill":return{width:e.outer_width,height:e.outer_height};default:return null}}var iTt="1mm",dH=(0,qH.default)("Group_doInitialPcbLayoutPack"),oTt=e=>{let{db:t}=e.root,{_parsedProps:n}=e,{packOrderStrategy:i,packPlacementStrategy:o,gap:r,pcbGap:s,pcbPackGap:a}=n,c=a??s??r,l=D.parse(c??iTt),u={},h=new Set,d=I=>{if(I?.pcb_component_id&&I?._parsedProps){let E=I._parsedProps,M=D.parse(E.pcbMarginLeft??E.pcbMarginX??0),k=D.parse(E.pcbMarginRight??E.pcbMarginX??0),N=D.parse(E.pcbMarginTop??E.pcbMarginY??0),A=D.parse(E.pcbMarginBottom??E.pcbMarginY??0);(M||k||N||A)&&(u[I.pcb_component_id]={left:M,right:k,top:N,bottom:A})}I?.children&&I.children.forEach(d)};d(e);let _=new Set;for(let I of e.children){let E=I;E._isNormalComponent&&E.isRelativelyPositioned?.()&&(E.pcb_component_id&&h.add(E.pcb_component_id),E.pcb_group_id&&_.add(E.pcb_group_id))}let y=t.toArray().filter(I=>I.type==="pcb_component"?!h.has(I.pcb_component_id):I.type==="pcb_group"?!_.has(I.pcb_group_id):!0),g=[];for(let I of h){let E=t.toArray().find(R=>R.type==="pcb_component"&&R.pcb_component_id===I);if(!E)continue;let M=E.center.x,k=E.center.y,N=t.toArray().filter(R=>R.type==="pcb_smtpad"&&R.pcb_component_id===I);for(let R of N){let $=eTt(R);if(!$||$.width===0||$.height===0)continue;let j,H;if(R.shape==="polygon"){let X=R.points.map(tt=>tt.x),G=R.points.map(tt=>tt.y);j=M+(Math.min(...X)+Math.max(...X))/2,H=k+(Math.min(...G)+Math.max(...G))/2}else j=M+R.x,H=k+R.y;g.push({obstacleId:R.pcb_smtpad_id,absoluteCenter:{x:j,y:H},width:$.width,height:$.height})}let A=t.toArray().filter(R=>R.type==="pcb_plated_hole"&&R.pcb_component_id===I);for(let R of A){let $=nTt(R);if(!$||$.width===0||$.height===0)continue;let j=M+R.x,H=k+R.y;g.push({obstacleId:R.pcb_plated_hole_id,absoluteCenter:{x:j,y:H},width:$.width,height:$.height})}}let x;if(n.width!==void 0&&n.height!==void 0){let I=D.parse(n.width),E=D.parse(n.height);x={minX:-I/2,maxX:I/2,minY:-E/2,maxY:E/2}}let w={...VY(XY(y,{source_group_id:e.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:u})),orderStrategy:i??"largest_to_smallest",placementStrategy:o??"minimum_sum_squared_distance_to_network",minGap:l,obstacles:g,bounds:x},S=QIt(e,w);dH.enabled&&(e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${e.name}`,content:JSON.stringify(t.toArray())}),e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${e.name}`,content:w}));let T=ux(w);if(dH.enabled){let I=kM(T);I.title=`packOutput-${e.name}`,global.debugGraphics?.push(I)}tTt(e,T,S)},rTt=e=>{let{db:t}=e.root,{_parsedProps:n}=e,i=e.children.filter(E=>E.pcb_component_id||E.pcb_group_id);if(i.some(E=>{let M=E._parsedProps;return M?.pcbX!==void 0||M?.pcbY!==void 0}))return;let r=n.pcbJustifyContent??n.justifyContent,s=n.pcbAlignItems??n.alignItems,a=n.pcbFlexGap??n.pcbGap??n.gap,c=n.pcbFlexDirection??"row",l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[r??"space-between"],u={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[s??"center"];if(!l)throw new Error(`Invalid justifyContent value: "${r}"`);if(!u)throw new Error(`Invalid alignItems value: "${s}"`);let h=0,d=0;typeof a=="object"?(h=a.y??0,d=a.x??0):typeof a=="number"?(h=a,d=a):typeof a=="string"&&(h=D.parse(a),d=D.parse(a));let _,y=n.width??n.pcbWidth??void 0,g=n.height??n.pcbHeight??void 0;(y===void 0||g===void 0)&&(_=ub(i.map(E=>E._getMinimumFlexContainerSize()).filter(E=>E!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d}),y=_.width,g=_.height);let w=new dx(y,g,{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d});for(let E of i){let M=E._getMinimumFlexContainerSize();w.addChild({metadata:E,width:M?.width??0,height:M?.height??0,flexBasis:M?c==="row"?M.width:M.height:void 0})}w.build();let S={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let E of w.children)S.minX=Math.min(S.minX,E.position.x),S.minY=Math.min(S.minY,E.position.y),S.maxX=Math.max(S.maxX,E.position.x+E.size.width),S.maxY=Math.max(S.maxY,E.position.y+E.size.height);S.width=S.maxX-S.minX,S.height=S.maxY-S.minY;let T=e._getGlobalPcbPositionBeforeLayout(),I={x:T.x-(S.maxX+S.minX)/2,y:T.y-(S.maxY+S.minY)/2};for(let E of w.children)E.metadata._repositionOnPcb({x:E.position.x+E.size.width/2+I.x,y:E.position.y+E.size.height/2+I.y});t.pcb_group.update(e.pcb_group_id,{width:S.width,height:S.height,center:T})};function sTt(e){let{db:t}=e.root,n=new Map,i=new Map,o=new Set,s=e.selectAll("trace").filter(R=>R._parsedProps?.schDisplayLabel),a=e.selectAll("group"),c=[e.schematic_group_id,...a.map(R=>R.schematic_group_id)],l=t.schematic_component.list().filter(R=>c.includes(R.schematic_group_id)),u=[],h=new Map,d=new Map;for(let R of l){let $=R.schematic_component_id,j=[],H=t.source_component.getWhere({source_component_id:R.source_component_id}),X=t.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let G of X){let tt=`${H?.name??R.schematic_component_id}.${G.pin_number}`;h.set(tt,G.schematic_port_id),d.set(G.schematic_port_id,tt)}for(let G of X){let tt=d.get(G.schematic_port_id);j.push({pinId:tt,x:G.center.x,y:G.center.y})}u.push({chipId:$,center:R.center,width:R.size.width,height:R.size.height,pins:j})}let _=new Set,y=new Map,g=new Map,x=new Map;for(let R of l){let $=t.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let j of $)_.add(j.schematic_port_id),j.source_port_id&&(y.set(j.schematic_port_id,j.source_port_id),g.set(j.source_port_id,j.schematic_port_id))}let w=new Set;e.subcircuit_id&&w.add(e.subcircuit_id);for(let R of a)R.subcircuit_id&&w.add(R.subcircuit_id);let T=t.source_trace.list().filter(R=>{if(R.subcircuit_id===e.subcircuit_id)return!0;for(let $ of R.connected_source_port_ids)if(g.has($))return!0;return!1}).flatMap(R=>R.connected_source_net_ids);for(let R of T){let $=t.source_net.get(R);$?.subcircuit_id&&w.add($.subcircuit_id)}let I=[],E=new Map;for(let R of t.source_trace.list()){if(R.subcircuit_id&&!w.has(R.subcircuit_id))continue;let $=(R.connected_source_port_ids??[]).map(j=>g.get(j)).filter(j=>!!j&&_.has(j));if($.length>=2){let[j,H]=$.slice(0,2),X=[j,H].sort().join("::");if(!E.has(X)){E.set(X,R.source_trace_id);let G=R.display_name??R.source_trace_id;R.subcircuit_connectivity_map_key&&(o.add(R.subcircuit_connectivity_map_key),x.set(G,R.subcircuit_connectivity_map_key),i.set(R.subcircuit_connectivity_map_key,G)),I.push({pinIds:[j,H].map(tt=>d.get(tt)),netId:G})}}}let M=[];for(let R of t.source_net.list().filter($=>!$.subcircuit_id||w.has($.subcircuit_id)))R.subcircuit_connectivity_map_key&&(o.add(R.subcircuit_connectivity_map_key),n.set(R.subcircuit_connectivity_map_key,R));let k=new Map;for(let[R,$]of y){let j=t.source_port.get($);if(!j?.subcircuit_connectivity_map_key)continue;let H=j.subcircuit_connectivity_map_key;o.add(H),k.has(H)||k.set(H,[]),k.get(H).push(R)}for(let[R,$]of k){let j=n.get(R);if(j&&$.length>=2){let H=String(j.name||j.source_net_id||R);x.set(H,R),i.set(R,H);let G=.1*(.18/.18),tt=Number((String(H).length*G).toFixed(2));M.push({netId:H,pinIds:$.map(Q=>d.get(Q)),netLabelWidth:tt})}}let N=(()=>{let R={},$=new Set(M.map(j=>j.netId));for(let j of t.source_net.list().filter(H=>!H.subcircuit_id||w.has(H.subcircuit_id)))j.name&&$.has(j.name)&&(j.is_ground||j.name.toLowerCase().startsWith("gnd")?R[j.name]=["y-"]:j.is_power||j.name.toLowerCase().startsWith("v")?R[j.name]=["y+"]:R[j.name]=["x-","x+"]);return R})();return{inputProblem:{chips:u,directConnections:I,netConnections:M,availableNetLabelOrientations:N,maxMspPairDistance:e._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:h,pairKeyToSourceTraceId:E,sckToSourceNet:n,sckToUserNetId:i,userNetIdToSck:x,allSourceAndSchematicPortIdsInScope:_,schPortIdToSourcePortId:y,displayLabelTraces:s,allScks:o}}var no=1e-6;function fH(e){let t=Math.abs(e.to.x-e.from.x),n=Math.abs(e.to.y-e.from.y);return t>=n}function Lx(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function mH(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function _H(e,t,n){let i=Lx(e,t);if(i<no)return 0;let o=((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/((t.x-e.x)*(t.x-e.x)+(t.y-e.y)*(t.y-e.y));return Math.max(0,Math.min(1,o))*i}function Ex(e,t,n,i){return e*i-t*n}function aTt(e,t,n,i){let o={x:t.x-e.x,y:t.y-e.y},r={x:i.x-n.x,y:i.y-n.y},s=Ex(o.x,o.y,r.x,r.y),a={x:n.x-e.x,y:n.y-e.y},c=Ex(a.x,a.y,o.x,o.y);if(Math.abs(s)<no&&Math.abs(c)<no||Math.abs(s)<no&&Math.abs(c)>=no)return null;let l=Ex(a.x,a.y,r.x,r.y)/s,u=Ex(a.x,a.y,o.x,o.y)/s;return l<-no||l>1+no||u<-no||u>1+no?null:{x:e.x+l*o.x,y:e.y+l*o.y}}function cTt(e,t=no){if(e.length===0)return e;e.sort((o,r)=>o.start-r.start);let n=[],i={...e[0]};for(let o=1;o<e.length;o++){let r=e[o];r.start<=i.end+t?i.end=Math.max(i.end,r.end):(n.push(i),i={...r})}return n.push(i),n}function lTt(e,t,n){let i=Lx(e.from,e.to);if(i<no||t.length===0)return[e];let o=n/2,r=t.map(h=>({start:Math.max(0,h-o),end:Math.min(i,h+o)})).filter(h=>h.end-h.start>no),s=cTt(r),a=[],c=0,l={x:e.to.x-e.from.x,y:e.to.y-e.from.y},u=(h,d,_)=>{if(d-h<=no)return;let y=h/i,g=d/i;a.push({from:mH(e.from,e.to,y),to:mH(e.from,e.to,g),..._?{is_crossing:!0}:{}})};for(let h of s)h.start-c>no&&u(c,h.start,!1),u(h.start,h.end,!0),c=h.end;return i-c>no&&u(c,i,!1),a.length>0?a:[e]}function uTt(e,t={}){let n=t.crossSegmentLength??.075,i=t.tolerance??no,o=new Map,r=c=>`${c.traceIdx}:${c.edgeIdx}`,s=c=>e[c.traceIdx].edges[c.edgeIdx];for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=l.edges[u];for(let d=c;d<e.length;d++){let _=e[d];for(let y=d===c?u+1:0;y<_.edges.length;y++){let g=_.edges[y],x=aTt(h.from,h.to,g.from,g.to);if(!x)continue;let w=Lx(h.from,h.to),S=Lx(g.from,g.to);if(w<i||S<i)continue;let T=_H(h.from,h.to,x),I=_H(g.from,g.to,x),E=T<=i||Math.abs(w-T)<=i||Number.isNaN(T),M=I<=i||Math.abs(S-I)<=i||Number.isNaN(I);if(!E&&!M){let k=fH(h),N=fH(g),A;if(k!==N)A=k;else{let j=Math.abs(h.to.x-h.from.x),H=Math.abs(h.to.y-h.from.y),X=Math.abs(g.to.x-g.from.x),G=Math.abs(g.to.y-g.from.y),tt=j-H,Q=X-G;A=tt===Q?!0:tt>Q}let R=r({traceIdx:A?c:d,edgeIdx:A?u:y}),$=o.get(R)??[];$.push(A?T:I),o.set(R,$)}}}}}let a=e.map(c=>({source_trace_id:c.source_trace_id,edges:[]}));for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=r({traceIdx:c,edgeIdx:u}),d=o.get(h)??[];if(d.length===0){a[c].edges.push(l.edges[u]);continue}let _=Array.from(new Set(d.map(g=>Number(g.toFixed(6))))).sort((g,x)=>g-x),y=lTt(l.edges[u],_,n);a[c].edges.push(...y)}}return a}var fs=1e-6;function Fx(e,t,n=fs){return Math.abs(e-t)<=n}function Gh(e,t,n=fs){return Fx(e.x,t.x,n)&&Fx(e.y,t.y,n)}function yH(e,t,n,i=fs){let o=Math.min(t.x,n.x)-i,r=Math.max(t.x,n.x)+i,s=Math.min(t.y,n.y)-i,a=Math.max(t.y,n.y)+i;return e.x<o||e.x>r||e.y<s||e.y>a?!1:Math.abs((n.x-t.x)*(e.y-t.y)-(n.y-t.y)*(e.x-t.x))<=i}function gH(e,t=fs){let n=new Map;for(let i of e){let o=`${i.x.toFixed(6)},${i.y.toFixed(6)}`;n.has(o)||n.set(o,i)}return Array.from(n.values())}function bH(e){return{x:e.to.x-e.from.x,y:e.to.y-e.from.y}}function w4(e,t,n=fs){let i=bH(e),o=bH(t),r=Math.hypot(i.x,i.y),s=Math.hypot(o.x,o.y);if(r<n||s<n)return!0;let a=i.x*o.y-i.y*o.x;return Math.abs(a)<=n*r*s}function km(e,t,n=fs){return e.edges.filter(i=>Gh(i.from,t,n)||Gh(i.to,t,n))}function xH(e,t,n=fs){for(let i of e.edges){if(Gh(i.from,t,n))return i.from;if(Gh(i.to,t,n))return i.to}return null}function pTt(e,t,n=fs){let i=Gh(e.from,t,n)||Fx(e.from.x,t.x,n)&&Fx(e.from.y,t.y,n)?e.to:e.from,o=i.x-t.x,r=i.y-t.y;return Math.abs(o)<n&&Math.abs(r)<n?null:Math.abs(o)>=Math.abs(r)?o>=0?"right":"left":r>=0?"up":"down"}function $h(e,t,n=fs){let i=km(e,t,n);if(i.length<2)return null;let o=i.map(h=>pTt(h,t,n)),r=o.includes("up"),s=o.includes("down"),a=o.includes("left"),c=o.includes("right"),l=r?"up":s?"down":null,u=c?"right":a?"left":null;return l&&u?`${l}-${u}`:null}function hTt(e,t={}){let n=t.tolerance??fs,i={};for(let r of e)i[r.source_trace_id]=[];let o=e.map(r=>{let s=[];for(let a of r.edges)s.push(a.from,a.to);return gH(s,n)});for(let r=0;r<e.length;r++){let s=e[r],a=o[r];for(let c=r+1;c<e.length;c++){let l=e[c],u=o[c];for(let h of a)for(let d of u)if(Gh(h,d,n)){let _=km(s,h,n),y=km(l,d,n),g=_.some(T=>y.some(I=>!w4(T,I,n))),x=$h(s,h,n),w=$h(l,d,n);g&&!(x!==null&&w!==null&&x===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(d))}for(let h of a)for(let d of l.edges)if(yH(h,d.from,d.to,n)){let y=km(s,h,n).some(T=>!w4(T,d,n)),g=$h(s,h,n),x=xH(l,h,n*1e3),w=x?$h(l,x,n):null;y&&!(g!==null&&w!==null&&g===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(h))}for(let h of u)for(let d of s.edges)if(yH(h,d.from,d.to,n)){let y=km(l,h,n).some(T=>!w4(d,T,n)),g=$h(l,h,n),x=xH(s,h,n*1e3),w=x?$h(s,x,n):null;y&&!(w!==null&&g!==null&&w===g)&&(i[l.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[s.source_trace_id].push(h))}}}for(let r of Object.keys(i))i[r]=gH(i[r],n);return i}var P4=(0,ZH.default)("Group_doInitialSchematicTraceRender");function dTt(e){let{group:t,solver:n,pinIdToSchematicPortId:i,userNetIdToSck:o}=e,{db:r}=t.root,s=n.traceCleanupSolver?.getOutput().traces??n.traceLabelOverlapAvoidanceSolver?.getOutput().traces??n.schematicTraceLinesSolver?.solvedTracePaths,a=[];P4(`Traces inside SchematicTraceSolver output: ${(s??[]).length}`);for(let u of s??[]){let h=u?.tracePath;if(!Array.isArray(h)||h.length<2){P4(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let d=[];for(let g=0;g<h.length-1;g++)d.push({from:{x:h[g].x,y:h[g].y},to:{x:h[g+1].x,y:h[g+1].y}});let _=null,y;if(Array.isArray(u?.pins)&&u.pins.length===2){let g=i.get(u.pins[0]?.pinId),x=i.get(u.pins[1]?.pinId);if(g&&x){for(let w of[g,x])r.schematic_port.get(w)&&r.schematic_port.update(w,{is_connected:!0});y=o.get(String(u.userNetId))}}_||(_=`solver_${u?.mspPairId}`,y=o.get(String(u.userNetId))),a.push({source_trace_id:_,edges:d,subcircuit_connectivity_map_key:y})}P4(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=uTt(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=hTt(c);for(let u of c)r.schematic_trace.insert({source_trace_id:u.source_trace_id,edges:u.edges,junctions:l[u.source_trace_id]??[],subcircuit_connectivity_map_key:a.find(h=>h.source_trace_id===u.source_trace_id)?.subcircuit_connectivity_map_key})}var fTt=e=>{switch(e){case"x+":return"left";case"x-":return"right";case"y+":return"bottom";case"y-":return"top";case"left":return"right";case"top":return"bottom";case"right":return"left";case"bottom":return"top"}},mTt=e=>{for(let n of e){let i=n._getDirectlyConnectedTraces();for(let o of i){let r=o._parsedProps.schDisplayLabel;if(r)return{name:r,wasAssignedDisplayLabel:!0}}}return{name:e.map(n=>n._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},I4=(0,KH.default)("Group_doInitialSchematicTraceRender");function _Tt(e){let{group:t,solver:n,sckToSourceNet:i,allScks:o,allSourceAndSchematicPortIdsInScope:r,schPortIdToSourcePortId:s,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=e,{db:h}=t.root,d=n.netLabelPlacementSolver?.netLabelPlacements??n.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],_=n.mspConnectionPairSolver.globalConnMap;for(let y of d){I4(`processing placement: ${y.netId}`);let g=_.getIdsConnectedToNet(y.globalConnNetId).find(R=>a.get(R)),x=a.get(g),w=y.anchorPoint,S=y.orientation,T=fTt(S),I=x?i.get(x):void 0,E=y.pinIds.map(R=>c.get(R));if(E.some(R=>l.has(R))){I4(`skipping net label placement for "${y.netId}" REASON:schematic port has pre-existing net label`);continue}if(I){let R=I.name,$=Ic({anchor_position:w,anchor_side:T,text:R});h.schematic_net_label.insert({text:R,anchor_position:w,center:$,anchor_side:T,...I?.source_net_id?{source_net_id:I.source_net_id}:{}});continue}let M=t.selectAll("port").filter(R=>R._getSubcircuitConnectivityKey()===x),{name:k,wasAssignedDisplayLabel:N}=mTt(M);if(!N&&E.some(R=>u.has(R))){I4(`skipping net label placement for "${y.netId}" REASON:schematic port has routed traces and no display label`);continue}let A=Ic({anchor_position:w,anchor_side:T,text:k});h.schematic_net_label.insert({text:k,anchor_position:w,center:A,anchor_side:T})}}var yTt=({allSourceAndSchematicPortIdsInScope:e,group:t,schPortIdToSourcePortId:n,sckToSourceNet:i,pinIdToSchematicPortId:o,schematicPortIdsWithPreExistingNetLabels:r})=>{let{db:s}=t.root;for(let a of Array.from(e)){let c=s.schematic_port.get(a);if(!c||c.is_connected)continue;let l=n.get(a);if(!l)continue;let h=s.source_port.get(l)?.subcircuit_connectivity_map_key;if(!h)continue;let d=i.get(h);if(!d||s.schematic_net_label.list().some(w=>Math.abs(w.anchor_position.x-c.center.x)<.1&&Math.abs(w.anchor_position.y-c.center.y)<.1?d.source_net_id&&w.source_net_id?w.source_net_id===d.source_net_id:w.text===(d.name||h):!1))continue;let y=d.name||d.source_net_id||h,g=Lm(c.facing_direction||"right")||"right",x=Ic({anchor_position:c.center,anchor_side:g,text:y});s.schematic_net_label.insert({text:y,anchor_position:c.center,center:x,anchor_side:g,...d.source_net_id?{source_net_id:d.source_net_id}:{}})}},gTt=e=>{let t=new Set,n=e.selectAll("netlabel");for(let i of n){let o=i._getConnectedPorts();for(let r of o)r.schematic_port_id&&t.add(r.schematic_port_id)}return t},bTt=({solver:e,pinIdToSchematicPortId:t})=>{let n=e.schematicTraceLinesSolver.solvedTracePaths,i=new Set;for(let o of n)for(let r of o.pinIds){let s=t.get(r);s&&i.add(s)}return i},xTt=(0,WH.default)("Group_doInitialSchematicTraceRender"),vTt=e=>{if(!e.root?._featureMspSchematicTraceRouting||!e.isSubcircuit||e.root?.schematicDisabled)return;let{inputProblem:t,pinIdToSchematicPortId:n,pairKeyToSourceTraceId:i,sckToSourceNet:o,allSourceAndSchematicPortIdsInScope:r,schPortIdToSourcePortId:s,displayLabelTraces:a,allScks:c,userNetIdToSck:l}=sTt(e),u=gTt(e);xTt.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(t,null,2)});let h=new bX(t);h.solve();let d=bTt({solver:h,pinIdToSchematicPortId:n});dTt({group:e,solver:h,pinIdToSchematicPortId:n,userNetIdToSck:l}),_Tt({group:e,solver:h,sckToSourceNet:o,allSourceAndSchematicPortIdsInScope:r,schPortIdToSourcePortId:s,pinIdToSchematicPortId:n,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:d}),yTt({group:e,allSourceAndSchematicPortIdsInScope:r,schPortIdToSourcePortId:s,sckToSourceNet:o,pinIdToSchematicPortId:n,schematicPortIdsWithPreExistingNetLabels:u})},STt=()=>({async simulate(e){let t="spice-experiment-1",{circuit:n,tran:i}=SX(e);return{simulationResultCircuitJson:wX(i,n,t)}}}),sa=(0,JH.default)("tscircuit:core:Group_doInitialSimulationSpiceEngineRender");function wTt(e){if(!e.isSubcircuit)return;let{root:t}=e;if(!t)return;let n=e.selectAll("analogsimulation");if(n.length===0)return;let i={...t.platform?.spiceEngineMap};i.spicey||(i.spicey=STt());let o=t.db.toArray(),r;try{r=vX(o).toSpiceString(),sa(`Generated SPICE string:
|
|
248
|
+
${_.message}`):_}}let s=i.nodes.count()-1;for(let a=0;a<i.V.length;a++){let c=i.V[a];c&&(c.index=s+a)}for(let a of i.S){let c=t.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by switch ${a.name}`);a.model=c,a.isOn=!1}for(let a of i.D){let c=n.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by diode ${a.name}`);a.model=c}return i}var qe=class na{constructor(t=0,n=0){P(this,"re");P(this,"im");this.re=t,this.im=n}static from(t,n=0){return new na(t,n)}static fromPolar(t,n=0){let i=n*Math.PI/180;return new na(t*Math.cos(i),t*Math.sin(i))}clone(){return new na(this.re,this.im)}add(t){return new na(this.re+t.re,this.im+t.im)}sub(t){return new na(this.re-t.re,this.im-t.im)}mul(t){return new na(this.re*t.re-this.im*t.im,this.re*t.im+this.im*t.re)}div(t){let n=t.re*t.re+t.im*t.im;if(n<Hn)throw new Error("Complex divide by ~0");return new na((this.re*t.re+this.im*t.im)/n,(this.im*t.re-this.re*t.im)/n)}inv(){let t=this.re*this.re+this.im*this.im;if(t<Hn)throw new Error("Complex invert by ~0");return new na(this.re/t,-this.im/t)}abs(){return Math.hypot(this.re,this.im)}phaseDeg(){return Math.atan2(this.im,this.re)*180/Math.PI}};function DSt(e,t){let n=e.length;for(let o=0;o<n;o++){let r=e[o],s=t[o];if(!r||!s)throw new Error("Matrix dimensions mismatch");let a=r.map(c=>c.clone());a.push(s.clone()),e[o]=a}for(let o=0;o<n;o++){let r=o,s=e[o];if(!s)throw new Error("Matrix row missing");let a=s[o]?.abs()??0;for(let u=o+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[o]?.abs()??0;d>a&&(a=d,r=u)}if(a<Hn)throw new Error("Singular matrix (complex)");if(r!==o){let u=e[o];e[o]=e[r],e[r]=u}let c=e[o];if(!c)throw new Error("Pivot row missing");let l=c[o];if(!l)throw new Error("Zero pivot encountered");for(let u=o+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[o];if(!d)continue;let _=d.div(l);if(!(_.abs()<Hn))for(let y=o;y<=n;y++){let g=h[y],x=c[y];!g||!x||(h[y]=g.sub(_.mul(x)))}}}let i=new Array(n);for(let o=n-1;o>=0;o--){let r=e[o];if(!r)throw new Error("Matrix row missing");let s=r[n];if(!s)throw new Error("Augmented column missing");for(let c=o+1;c<n;c++){let l=r[c],u=i[c];!l||!u||(s=s.sub(l.mul(u)))}let a=r[o];if(!a)throw new Error("Zero pivot on back-substitution");i[o]=s.div(a)}return i}function $St(e,t,n){if(e<=0||t<=0)throw new Error(".ac frequencies must be > 0");t<e&&([e,t]=[t,e]);let i=Math.log10(t/e),o=Math.max(1,Math.ceil(i*n)),r=[];for(let a=0;a<=o;a++)r.push(e*Math.pow(10,a/n));let s=r[r.length-1];return(s==null||s<t*(1-Hn))&&r.push(t),r}function WM(e,t,n,i,o){let r=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);if(r>=0){let a=e[r];if(!a)throw new Error("Matrix row missing while stamping");a[r]=a[r]?.add(o)??o}if(s>=0){let a=e[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.add(o)??o}if(r>=0&&s>=0){let a=e[r],c=e[s];if(!a||!c)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.sub(o)??qe.from(0,0).sub(o),c[r]=c[r]?.sub(o)??qe.from(0,0).sub(o)}}function jSt(e,t,n,i,o){let r=n.matrixIndexOfNode(i.n1),s=n.matrixIndexOfNode(i.n2),a=i.index,c=qe.from(1,0);if(r>=0){let u=e[r];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.add(c)??c}if(s>=0){let u=e[s];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.sub(c)??qe.from(0,0).sub(c)}let l=e[a];if(!l)throw new Error("Branch row missing while stamping voltage source");r>=0&&(l[r]=l[r]?.add(c)??c),s>=0&&(l[s]=l[s]?.sub(c)??qe.from(0,0).sub(c)),t[a]=(t[a]??qe.from(0,0)).add(o)}function BSt(e){var d,_,y,g;if(!e.analyses.ac)return null;let{mode:t,N:n,f1:i,f2:o}=e.analyses.ac,r=e.nodes.count()-1,s=e.V.length,a=r+s,c=t==="dec"?$St(i,o,n):(()=>{let x=[],w=Math.max(2,n),S=(o-i)/(w-1);for(let T=0;T<w;T++)x.push(i+T*S);return x})(),l={};e.nodes.rev.forEach((x,w)=>{w!==0&&(l[x]=[])});let u={},h=2*Math.PI;for(let x of c){let w=Array.from({length:a},()=>Array.from({length:a},()=>qe.from(0,0))),S=Array.from({length:a},()=>qe.from(0,0));for(let I of e.R){if(I.R<=0)throw new Error(`R ${I.name} must be > 0`);let E=qe.from(1/I.R,0);WM(w,e.nodes,I.n1,I.n2,E)}for(let I of e.C){let E=qe.from(0,h*x*I.C);WM(w,e.nodes,I.n1,I.n2,E)}for(let I of e.L){let E=qe.from(0,h*x*I.L),M=E.abs()<Hn?qe.from(0,0):qe.from(1,0).div(E);WM(w,e.nodes,I.n1,I.n2,M)}for(let I of e.V){let E=qe.fromPolar(I.acMag||0,I.acPhaseDeg||0);jSt(w,S,e.nodes,I,E)}let T=DSt(w,S);for(let I=1;I<e.nodes.count();I++){let E=I-1,M=e.nodes.rev[I];if(!M)continue;let k=l[M];k&&k.push(T[E]??qe.from(0,0))}for(let I of e.R){let E=I.n1===0?qe.from(0,0):T[I.n1-1]??qe.from(0,0),M=I.n2===0?qe.from(0,0):T[I.n2-1]??qe.from(0,0),N=qe.from(1/I.R,0).mul(E.sub(M));(u[d=I.name]||(u[d]=[])).push(N)}for(let I of e.C){let E=I.n1===0?qe.from(0,0):T[I.n1-1]??qe.from(0,0),M=I.n2===0?qe.from(0,0):T[I.n2-1]??qe.from(0,0),N=qe.from(0,h*x*I.C).mul(E.sub(M));(u[_=I.name]||(u[_]=[])).push(N)}for(let I of e.L){let E=I.n1===0?qe.from(0,0):T[I.n1-1]??qe.from(0,0),M=I.n2===0?qe.from(0,0):T[I.n2-1]??qe.from(0,0),k=qe.from(0,h*x*I.L),A=(k.abs()<Hn?qe.from(0,0):qe.from(1,0).div(k)).mul(E.sub(M));(u[y=I.name]||(u[y]=[])).push(A)}for(let I of e.V){let E=T[I.index]??qe.from(0,0);(u[g=I.name]||(u[g]=[])).push(E)}}return{freqs:c,nodeVoltages:l,elementCurrents:u}}function YSt(e,t){let n=e.length;for(let o=0;o<n;o++){let r=e[o],s=t[o];if(!r||s==null)throw new Error("Matrix dimensions mismatch");let a=r.slice();a.push(s),e[o]=a}for(let o=0;o<n;o++){let r=o,s=e[o];if(!s)throw new Error("Matrix row missing");let a=Math.abs(s[o]??0);for(let u=o+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=Math.abs(h[o]??0);d>a&&(a=d,r=u)}if(a<Hn)throw new Error("Singular matrix (real)");if(r!==o){let u=e[o];e[o]=e[r],e[r]=u}let c=e[o];if(!c)throw new Error("Pivot row missing");let l=c[o];if(l==null)throw new Error("Zero pivot encountered");for(let u=o+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[o];if(d==null)continue;let _=d/l;if(!(Math.abs(_)<Hn))for(let y=o;y<=n;y++){let g=h[y],x=c[y];g==null||x==null||(h[y]=g-_*x)}}}let i=new Array(n).fill(0);for(let o=n-1;o>=0;o--){let r=e[o];if(!r)throw new Error("Matrix row missing");let s=r[n];if(s==null)throw new Error("Augmented column missing");for(let c=o+1;c<n;c++){let l=r[c],u=i[c];l==null||u==null||(s-=l*u)}let a=r[o];if(a==null)throw new Error("Zero pivot on back-substitution");i[o]=s/a}return i}function _m(e,t,n,i,o){let r=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);if(r>=0){let a=e[r];if(!a)throw new Error("Matrix row missing while stamping");a[r]=(a[r]??0)+o}if(s>=0){let a=e[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)+o}if(r>=0&&s>=0){let a=e[r],c=e[s];if(!a||!c)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)-o,c[r]=(c[r]??0)-o}}function ZM(e,t,n,i,o){let r=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);r>=0&&(e[r]=(e[r]??0)-o),s>=0&&(e[s]=(e[s]??0)+o)}function XSt(e,t,n,i,o){let r=n.matrixIndexOfNode(i.n1),s=n.matrixIndexOfNode(i.n2),a=i.index;if(r>=0){let l=e[r];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)+1}if(s>=0){let l=e[s];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)-1}let c=e[a];if(!c)throw new Error("Branch row missing while stamping voltage source");r>=0&&(c[r]=(c[r]??0)+1),s>=0&&(c[s]=(c[s]??0)-1),t[a]=(t[a]??0)+o}function VSt(e){var _,y,g,x,w,S;if(!e.analyses.tran)return null;let{dt:t,tstop:n}=e.analyses.tran,i=t>Hn?t:Math.max(n/1e3,Hn),o=Math.max(1,Math.ceil(n/Math.max(i,Hn))),r=o>0?n/o:n,s=e.nodes.count()-1,a=e.V.length,c=s+a,l=[],u={};e.nodes.rev.forEach((T,I)=>{I!==0&&(u[T]=[])});let h={},d=0;for(let T=0;T<=o;T++,d=T*r){l.push(d);let I=new Array(c).fill(0);for(let E=0;E<20;E++){let M=Array.from({length:c},()=>new Array(c).fill(0)),k=new Array(c).fill(0);for(let R of e.R){let $=1/R.R;_m(M,e.nodes,R.n1,R.n2,$)}for(let R of e.C){let $=R.C/Math.max(r,Hn);_m(M,e.nodes,R.n1,R.n2,$);let j=-$*R.vPrev;ZM(k,e.nodes,R.n1,R.n2,j)}for(let R of e.L){let $=Math.max(r,Hn)/R.L;_m(M,e.nodes,R.n1,R.n2,$),ZM(k,e.nodes,R.n1,R.n2,R.iPrev)}for(let R of e.S){let $=R.model;if(!$)continue;let j=R.isOn?$.Ron:$.Roff,X=1/Math.max(Math.abs(j),Hn);_m(M,e.nodes,R.n1,R.n2,X)}for(let R of e.V){let $=R.waveform?R.waveform(d):R.dc||0;XSt(M,k,e.nodes,R,$)}let N=.02585;for(let R of e.D){let $=R.model;if(!$)continue;let{nPlus:j,nMinus:H}=R,X=e.nodes.matrixIndexOfNode(j),G=e.nodes.matrixIndexOfNode(H),tt=j===0?0:I[X]??0,Q=H===0?0:I[G]??0,V=tt-Q,rt=E===0?R.vdPrev:V,et=$.N*N,J=rt;rt>.8&&(J=.8),rt<-1&&(J=-1);let pt=Math.exp(J/et),ht=$.Is*(pt-1),St=Math.max($.Is/et*pt,1e-12),wt=ht-St*J;_m(M,e.nodes,j,H,St),ZM(k,e.nodes,j,H,wt)}I=YSt(M,k);let A=!1;for(let R of e.S){let $=R.model;if(!$)continue;let j=R.ncPos===0?0:I[R.ncPos-1]??0,H=R.ncNeg===0?0:I[R.ncNeg-1]??0,X=j-H,G=R.isOn;R.isOn?X<$.Voff&&(G=!1):X>$.Von&&(G=!0),G!==R.isOn&&(R.isOn=G,A=!0)}if(!A||E===19)break}for(let E=1;E<e.nodes.count();E++){let M=E-1,k=e.nodes.rev[E];if(!k)continue;let N=u[k];N&&N.push(I[M]??0)}for(let E of e.R){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0,N=(M-k)/E.R;(h[_=E.name]||(h[_]=[])).push(N)}for(let E of e.C){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0,N=E.C*(M-k-E.vPrev)/Math.max(r,Hn);(h[y=E.name]||(h[y]=[])).push(N)}for(let E of e.L){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0,A=Math.max(r,Hn)/E.L*(M-k)+E.iPrev;(h[g=E.name]||(h[g]=[])).push(A)}for(let E of e.V){let M=I[E.index]??0;(h[x=E.name]||(h[x]=[])).push(M)}for(let E of e.S){let M=E.model;if(!M)continue;let k=E.n1===0?0:I[E.n1-1]??0,N=E.n2===0?0:I[E.n2-1]??0,A=E.isOn?M.Ron:M.Roff,R=Math.max(Math.abs(A),Hn),$=(k-N)/R;(h[w=E.name]||(h[w]=[])).push($)}for(let E of e.D){if(!E.model)continue;let{nPlus:M,nMinus:k,model:N}=E,A=M===0?0:I[M-1]??0,R=k===0?0:I[k-1]??0,$=A-R,H=N.N*.02585,X=Math.exp($/H),G=N.Is*(X-1);(h[S=E.name]||(h[S]=[])).push(G)}for(let E of e.C){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0;E.vPrev=M-k}for(let E of e.L){let M=E.n1===0?0:I[E.n1-1]??0,k=E.n2===0?0:I[E.n2-1]??0,N=Math.max(r,Hn)/E.L;E.iPrev=N*(M-k)+E.iPrev}for(let E of e.D){let M=E.nPlus===0?0:I[E.nPlus-1]??0,k=E.nMinus===0?0:I[E.nMinus-1]??0;E.vdPrev=M-k}}if(e.probes.tran.length>0){let T={},I=e.probes.tran.map(E=>E.toUpperCase());for(let E in u)I.includes(E.toUpperCase())&&(T[E]=u[E]);return{times:l,nodeVoltages:T,elementCurrents:h}}return{times:l,nodeVoltages:u,elementCurrents:h}}function SX(e){let t=zSt(e),n=BSt(t),i=VSt(t);return{circuit:t,ac:n,tran:i}}function wX(e,t,n){if(!e||!t.analyses.tran)return[];let{dt:i,tstop:o}=t.analyses.tran,{times:r,nodeVoltages:s}=e,a=[];for(let c in s){let l=s[c];a.push({type:"simulation_transient_voltage_graph",simulation_transient_voltage_graph_id:`stvg_${n}_${c}`,simulation_experiment_id:n,timestamps_ms:r.map(u=>u*1e3),voltage_levels:l,time_per_step:i*1e3,start_time_ms:0,end_time_ms:o*1e3,name:`V(${c})`})}return a}ji();ke();ji();ke();ke();vt();ke();ke();Qr();ke();ji();ke();ji();ke();ke();ji();ke();function PX(e,t,n,i){return Math.sqrt((n-e)**2+(i-t)**2)}var HSt=e=>{let t=e.filter(r=>r.type==="pcb_port"),n=e.filter(r=>r.type==="pcb_smtpad"),i=e.filter(r=>r.type==="pcb_trace");function o(r,s={}){let a=s.traceWidth||0,c=t.find(l=>PX(l.x,l.y,r.x,r.y)<.01);if(c)return c.pcb_port_id;if(s.isFirstOrLastPoint){let l=n.find(u=>{if(u.shape==="rect")return Math.abs(r.x-u.x)<u.width/2+a/2&&Math.abs(r.y-u.y)<u.height/2+a/2;if(u.shape==="circle")return PX(r.x,r.y,u.x,u.y)<u.radius});if(l)return l.pcb_port_id??null}return null}for(let r of i)for(let s=0;s<r.route.length;s++){let a=r.route[s],c=s===0||s===r.route.length-1;if(a.route_type==="wire"){if(!a.start_pcb_port_id&&s===0){let l=o(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.start_pcb_port_id=l)}if(!a.end_pcb_port_id&&s===r.route.length-1){let l=o(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.end_pcb_port_id=l)}}}};function TX(e){HSt(e);let t=e.filter(s=>s.type==="source_trace"),n=e.filter(s=>s.type==="pcb_port"),i=[],o=$i(e),r=new Map;for(let s of n)r.set(s.source_port_id,s);for(let s of t){let a=s.connected_source_port_ids;if(a.length<2)continue;let c=[],l=[];for(let y of a){let g=r.get(y);g?c.push(g):l.push(y)}if(c.length<2)continue;let u=c[0],h=o.getNetConnectedToId(u.pcb_port_id);o.getIdsConnectedToNet(h).filter(y=>e.some(g=>g.type==="pcb_trace"&&("pcb_trace_id"in g&&g.pcb_trace_id===y||"route_id"in g&&g.route_id===y))).length===0&&new Set(c.map(g=>g.pcb_component_id)).size>1&&i.push({type:"pcb_port_not_connected_error",message:`pcb_port_not_connected_error: Pcb ports [${c.map(g=>g.pcb_port_id).join(", ")}] are not connected together through the same net.`,error_type:"pcb_port_not_connected_error",pcb_port_ids:c.map(g=>g.pcb_port_id),pcb_component_ids:c.map(g=>g.pcb_component_id),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${s.source_trace_id}`})}return i}var GSt=class{constructor({objects:e,getBounds:t,getId:n,CELL_SIZE:i}){P(this,"buckets");P(this,"objectsById");P(this,"getBounds");P(this,"getId");P(this,"CELL_SIZE",.4);P(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=t,this.getId=n??(()=>this._getNextId()),this.CELL_SIZE=i??this.CELL_SIZE;for(let o of e)this.addObject(o)}_getNextId(){return`${this._idCounter++}`}addObject(e){let t=this.getBounds(e),n=this.getId(e),i={...e,spatialIndexId:n};this.objectsById.set(n,i);let o=Math.floor(t.minX/this.CELL_SIZE),r=Math.floor(t.minY/this.CELL_SIZE),s=Math.floor(t.maxX/this.CELL_SIZE),a=Math.floor(t.maxY/this.CELL_SIZE);for(let c=o;c<=s;c++)for(let l=r;l<=a;l++){let u=`${c}x${l}`,h=this.buckets.get(u);h?h.push(i):this.buckets.set(u,[i])}}removeObject(e){let t=this.objectsById.get(e);if(!t)return!1;this.objectsById.delete(e);let n=this.getBounds(t),i=Math.floor(n.minX/this.CELL_SIZE),o=Math.floor(n.minY/this.CELL_SIZE),r=Math.floor(n.maxX/this.CELL_SIZE),s=Math.floor(n.maxY/this.CELL_SIZE);for(let a=i;a<=r;a++)for(let c=o;c<=s;c++){let l=`${a}x${c}`,u=this.buckets.get(l);if(u){let h=u.findIndex(d=>d.spatialIndexId===e);h!==-1&&(u.splice(h,1),u.length===0&&this.buckets.delete(l))}}return!0}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getObjectsInBounds(e,t=0){let n=[],i=new Set,o=Math.floor((e.minX-t)/this.CELL_SIZE),r=Math.floor((e.minY-t)/this.CELL_SIZE),s=Math.floor((e.maxX+t)/this.CELL_SIZE),a=Math.floor((e.maxY+t)/this.CELL_SIZE);for(let c=o;c<=s;c++)for(let l=r;l<=a;l++){let u=`${c}x${l}`,h=this.buckets.get(u)||[];for(let d of h){let _=d.spatialIndexId;i.has(_)||(i.add(_),n.push(d))}}return n}},ym=e=>e.type==="pcb_trace_segment"?{minX:Math.min(e.x1,e.x2),minY:Math.min(e.y1,e.y2),maxX:Math.max(e.x1,e.x2),maxY:Math.max(e.y1,e.y2)}:nh([e]),KM=.1,USt=.15;var qSt=.2,WSt=.3,gm=.005;function ZSt(e){let t=new Set;for(let n of e.route)n.route_type==="wire"&&(n.start_pcb_port_id&&t.add(n.start_pcb_port_id),n.end_pcb_port_id&&t.add(n.end_pcb_port_id));return Array.from(t)}function JM(e){let t=new Set;for(let n of e)for(let i of ZSt(n))t.add(i);return Array.from(t)}var KSt=(e,t)=>{let n={x:e.x1,y:e.y1},i={x:e.x2,y:e.y2},o={x:t.x1,y:t.y1},r={x:t.x2,y:t.y2},s={x:i.x-n.x,y:i.y-n.y},a={x:r.x-o.x,y:r.y-o.y},c=s.x*s.x+s.y*s.y,l=a.x*a.x+a.y*a.y;if(c===0||l===0){if(c===0&&l===0)return{x:(n.x+o.x)/2,y:(n.y+o.y)/2};if(c===0){let $=ds(((n.x-o.x)*a.x+(n.y-o.y)*a.y)/l,0,1),j={x:o.x+$*a.x,y:o.y+$*a.y};return{x:(n.x+j.x)/2,y:(n.y+j.y)/2}}let A=ds(((o.x-n.x)*s.x+(o.y-n.y)*s.y)/c,0,1),R={x:n.x+A*s.x,y:n.y+A*s.y};return{x:(R.x+o.x)/2,y:(R.y+o.y)/2}}let u={x:n.x-o.x,y:n.y-o.y},h=s.x*s.x+s.y*s.y,d=s.x*a.x+s.y*a.y,_=s.x*u.x+s.y*u.y,y=a.x*a.x+a.y*a.y,g=a.x*u.x+a.y*u.y,x=h*y-d*d;if(x<1e-10)return JSt(n,i,o,r,s,a,c,l);let w=(d*g-y*_)/x,S=(h*g-d*_)/x;w=ds(w,0,1),S=ds(S,0,1),S=(w*d+g)/y,S=ds(S,0,1),w=(S*d-_)/h,w=ds(w,0,1);let T={x:n.x+w*s.x,y:n.y+w*s.y},I={x:o.x+S*a.x,y:o.y+S*a.y},E=T.x-I.x,M=T.y-I.y,k=Math.sqrt(E*E+M*M);return{x:(T.x+I.x)/2,y:(T.y+I.y)/2}},JSt=(e,t,n,i,o,r,s,a)=>{let c=((n.x-e.x)*o.x+(n.y-e.y)*o.y)/s;c=ds(c,0,1);let l={x:e.x+c*o.x,y:e.y+c*o.y},u=((i.x-e.x)*o.x+(i.y-e.y)*o.y)/s;u=ds(u,0,1);let h={x:e.x+u*o.x,y:e.y+u*o.y},d=((e.x-n.x)*r.x+(e.y-n.y)*r.y)/a;d=ds(d,0,1);let _={x:n.x+d*r.x,y:n.y+d*r.y},y=((t.x-n.x)*r.x+(t.y-n.y)*r.y)/a;y=ds(y,0,1);let g={x:n.x+y*r.x,y:n.y+y*r.y},w=[{pointA:l,pointB:n,distance:Math.sqrt((l.x-n.x)**2+(l.y-n.y)**2)},{pointA:h,pointB:i,distance:Math.sqrt((h.x-i.x)**2+(h.y-i.y)**2)},{pointA:e,pointB:_,distance:Math.sqrt((e.x-_.x)**2+(e.y-_.y)**2)},{pointA:t,pointB:g,distance:Math.sqrt((t.x-g.x)**2+(t.y-g.y)**2)}].reduce((S,T)=>T.distance<S.distance?T:S);return{x:(w.pointA.x+w.pointB.x)/2,y:(w.pointA.y+w.pointB.y)/2}},ds=(e,t,n)=>Math.max(t,Math.min(n,e)),QSt=e=>{if(e.type==="pcb_via"||e.type==="pcb_plated_hole"&&e.shape==="circle")return e.outer_diameter/2;if(e.type==="pcb_hole"&&e.hole_shape==="circle")return e.hole_diameter/2;if(e.type==="pcb_smtpad"&&e.shape==="circle")return e.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(e)}`)},IX=(e,t)=>{let n={x:e.x1,y:e.y1},i={x:e.x2,y:e.y2},o=t.minX,r=t.minY,s=t.maxX,a=t.maxY;if(n.x===i.x&&n.y===i.y){let N=Math.max(o,Math.min(s,n.x)),A=Math.max(r,Math.min(a,n.y));return N===n.x&&A===n.y?{x:n.x,y:n.y}:{x:N,y:A}}let c=i.x-n.x,l=i.y-n.y,u=c!==0?(o-n.x)/c:Number.NEGATIVE_INFINITY,h=c!==0?(s-n.x)/c:Number.POSITIVE_INFINITY,d=l!==0?(r-n.y)/l:Number.NEGATIVE_INFINITY,_=l!==0?(a-n.y)/l:Number.POSITIVE_INFINITY,y=Math.max(Math.min(u,h),Math.min(d,_)),g=Math.min(Math.max(u,h),Math.max(d,_));if(y<=g&&g>=0&&y<=1){let N=Math.max(0,Math.min(1,y));return{x:n.x+N*c,y:n.y+N*l}}let x={x:Math.max(o,Math.min(s,n.x)),y:Math.max(r,Math.min(a,n.y))},w={x:Math.max(o,Math.min(s,i.x)),y:Math.max(r,Math.min(a,i.y))},S=(x.x-n.x)**2+(x.y-n.y)**2,T=(w.x-i.x)**2+(w.y-i.y)**2,I=[{start:{x:o,y:r},end:{x:s,y:r}},{start:{x:s,y:r},end:{x:s,y:a}},{start:{x:s,y:a},end:{x:o,y:a}},{start:{x:o,y:a},end:{x:o,y:r}}],E=Math.min(S,T),M=S<=T?x:w,k=(N,A,R)=>Math.max(A,Math.min(R,N));for(let N of I){let A={x:i.x-n.x,y:i.y-n.y},R={x:N.end.x-N.start.x,y:N.end.y-N.start.y},$={x:n.x-N.start.x,y:n.y-N.start.y},j=A.x*A.x+A.y*A.y,H=A.x*R.x+A.y*R.y,X=A.x*$.x+A.y*$.y,G=R.x*R.x+R.y*R.y,tt=R.x*$.x+R.y*$.y,Q=j*G-H*H;if(Math.abs(Q)<1e-10)continue;let V=(H*tt-G*X)/Q,rt=(j*tt-H*X)/Q;V=k(V,0,1),rt=k(rt,0,1);let et={x:n.x+V*A.x,y:n.y+V*A.y},J={x:N.start.x+rt*R.x,y:N.start.y+rt*R.y},pt=et.x-J.x,ht=et.y-J.y,St=pt*pt+ht*ht;St<E&&(E=St,M={x:(et.x+J.x)/2,y:(et.y+J.y)/2})}return M};function twt(e){return e.type==="pcb_trace_segment"?[e.layer]:e.type==="pcb_smtpad"?[e.layer]:e.type==="pcb_plated_hole"?Array.isArray(e.layers)?e.layers:[...Cp]:e.type==="pcb_hole"?[...Cp]:e.type==="pcb_via"?Array.isArray(e.layers)?e.layers:[...Cp]:e.type==="pcb_keepout"?Array.isArray(e.layers)?e.layers:[]:[]}function MX(e,{connMap:t}={}){let n=[];t??(t=$i(e));let o=Ge(e).pcb_trace.list().flatMap(y=>{let g=[];for(let x=0;x<y.route.length-1;x++){let w=y.route[x],S=y.route[x+1];w.route_type==="wire"&&S.route_type==="wire"&&w.layer===S.layer&&g.push({type:"pcb_trace_segment",pcb_trace_id:y.pcb_trace_id,_pcbTrace:y,thickness:"width"in w?w.width:"width"in S?S.width:USt,layer:w.layer,x1:w.x,y1:w.y,x2:S.x,y2:S.y})}return g}),r=Ge(e).pcb_smtpad.list(),s=Ge(e).pcb_plated_hole.list(),a=Ge(e).pcb_hole.list(),c=Ge(e).pcb_via.list(),l=Ge(e).pcb_keepout.list(),u=[...o,...r,...s,...a,...c,...l],h=new GSt({objects:u,getBounds:ym}),d=y=>pr(e,y),_=new Set;for(let y of o){let g=KM,x=ym(y),w=h.getObjectsInBounds(x,g+y.thickness/2);if(!(y.x1===y.x2&&y.y1===y.y2))for(let S of w){if(!twt(S).includes(y.layer))continue;if(S.type==="pcb_trace_segment"){let M=S;if(y.layer!==M.layer||t.areIdsConnected(y.pcb_trace_id,M.pcb_trace_id))continue;let k=th({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},{x:M.x1,y:M.y1},{x:M.x2,y:M.y2})-y.thickness/2-M.thickness/2;if(k>KM-gm)continue;let N=`overlap_${y.pcb_trace_id}_${M.pcb_trace_id}`,A=`overlap_${M.pcb_trace_id}_${y.pcb_trace_id}`;if(_.has(N)||_.has(A))continue;_.add(N),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${d(M.pcb_trace_id)} ${k<0?"(accidental contact)":`(gap: ${k.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:N,pcb_component_ids:[],center:KSt(y,M),pcb_port_ids:JM([y._pcbTrace,M._pcbTrace])});continue}let T=is(S);if(t.areIdsConnected(y.pcb_trace_id,"pcb_trace_id"in S?S.pcb_trace_id:T))continue;if(S.type==="pcb_via"||S.type==="pcb_plated_hole"&&S.shape==="circle"||S.type==="pcb_hole"||S.type==="pcb_smtpad"&&S.shape==="circle"){let M=QSt(S),N=ob({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},{x:S.x,y:S.y,radius:M})-y.thickness/2;if(N>KM-gm)continue;let A=`overlap_${y.pcb_trace_id}_${T}`;if(_.has(A))continue;_.add(A),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${S.type} "${d(is(S))}" ${N<0?"(accidental contact)":`(gap: ${N.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,center:IX(y,ym(S)),source_trace_id:"",pcb_trace_error_id:A,pcb_component_ids:["pcb_component_id"in S?S.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...JM([y._pcbTrace]),"pcb_port_id"in S?S.pcb_port_id:void 0].filter(Boolean)})}let E=wf({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},ym(S))-y.thickness/2;if(E+gm<g){let M=`overlap_${y.pcb_trace_id}_${T}`;if(_.has(M))continue;_.add(M),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${S.type} "${d(is(S))}" ${E<0?"(accidental contact)":`(gap: ${E.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:M,pcb_component_ids:["pcb_component_id"in S?S.pcb_component_id:void 0].filter(Boolean),center:IX(y,ym(S)),pcb_port_ids:[...JM([y._pcbTrace]),"pcb_port_id"in S?S.pcb_port_id:void 0].filter(Boolean)})}}}return n}function CX(e){return e.area()>=0}function EX({center:e,size:t,rotationDeg:n=0}){let i=e.x,o=e.y,r=t.width/2,s=t.height/2,a=[new hs(i-r,o-s),new hs(i+r,o-s),new hs(i+r,o+s),new hs(i-r,o+s)],c=new lm(a);if(n){let l=Yg(n,i,o),u=a.map(h=>{let d=yn(l,{x:h.x,y:h.y});return new hs(d.x,d.y)});c=new lm(u)}return CX(c)||c.reverse(),c}function ewt({board:e}){if(e.outline&&e.outline.length>0){let t=e.outline.map(i=>new hs(i.x,i.y)),n=new lm(t);return CX(n)||n.reverse(),n}return e.center&&typeof e.width=="number"&&typeof e.height=="number"?EX({center:e.center,size:{width:e.width,height:e.height},rotationDeg:0}):null}function nwt({circuitJson:e,component:t}){if(t.source_component_id){let n=e.find(i=>i.type==="source_component"&&i.source_component_id===t.source_component_id);if(n&&"name"in n&&n.name)return n.name}return pr(e,t.pcb_component_id)||"Unknown"}function iwt(e,t,n,i,o,r){let s=new hs(n.x,n.y);if(!t.contains(s)){let g=t.distanceTo(s);return Array.isArray(g)?g[0]:Number(g)||0}let a=i/2,c=o/2,l=[{x:n.x-a,y:n.y-c},{x:n.x+a,y:n.y-c},{x:n.x+a,y:n.y+c},{x:n.x-a,y:n.y+c}],u=[];for(let g=0;g<4;g++){let x=(g+1)%4;u.push({x:(l[g].x+l[x].x)/2,y:(l[g].y+l[x].y)/2})}let h=Yg(r,n.x,n.y),d=g=>{let x=yn(h,g);return new hs(x.x,x.y)},_=l.concat(u).map(d),y=0;for(let g of _)if(!t.contains(g)){let x=t.distanceTo(g),w=Array.isArray(x)?x[0]:Number(x)||0;w>y&&(y=w)}if(y>0)return y;try{let g=PM.intersect(e,t),x=0;g?Array.isArray(g)?x=g.reduce((S,T)=>S+(typeof T.area=="function"?T.area():0),0):typeof g.area=="function"?x=g.area():x=0:x=0;let w=e.area();if(x>0&&x<w){let S=1-x/w,T=Math.abs(i),I=Math.abs(o);return Math.min(T,I)*S}else return .1}catch{return .1}}function NX(e){let t=e.find(r=>r.type==="pcb_board");if(!t)return[];let n=ewt({board:t});if(!n)return[];let i=e.filter(r=>r.type==="pcb_component");if(i.length===0)return[];let o=[];for(let r of i){if(!r.center||typeof r.width!="number"||typeof r.height!="number"||r.width<=0||r.height<=0)continue;let s=EX({center:r.center,size:{width:r.width,height:r.height},rotationDeg:r.rotation||0});if(s.area()===0||n.contains(s))continue;let c=iwt(s,n,r.center,r.width,r.height,r.rotation||0),l=nwt({circuitJson:e,component:r}),u=Math.round(c*100)/100;o.push({type:"pcb_component_outside_board_error",error_type:"pcb_component_outside_board_error",pcb_component_outside_board_error_id:`pcb_component_outside_board_${r.pcb_component_id}`,message:`Component ${l} (${r.pcb_component_id}) extends outside board boundaries by ${u}mm`,pcb_component_id:r.pcb_component_id,pcb_board_id:t.pcb_board_id,component_center:r.center,component_bounds:{min_x:s.box.xmin,max_x:s.box.xmax,min_y:s.box.ymin,max_y:s.box.ymax},subcircuit_id:r.subcircuit_id,source_component_id:r.source_component_id})}return o}function owt(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function kX(e,{connMap:t,minSpacing:n=qSt}={}){let i=e.filter(s=>s.type==="pcb_via");if(i.length<2)return[];t??(t=$i(e));let o=[],r=new Set;for(let s=0;s<i.length;s++)for(let a=s+1;a<i.length;a++){let c=i[s],l=i[a];if(!t.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=owt(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+gm>=n)continue;let h=[c.pcb_via_id,l.pcb_via_id].sort().join("_");r.has(h)||(r.add(h),o.push({type:"pcb_via_clearance_error",pcb_error_id:`same_net_vias_close_${h}`,message:`Vias ${pr(e,c.pcb_via_id)} and ${pr(e,l.pcb_via_id)} are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:n,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return o}function rwt(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function AX(e,{connMap:t,minSpacing:n=WSt}={}){let i=e.filter(s=>s.type==="pcb_via");if(i.length<2)return[];t??(t=$i(e));let o=[],r=new Set;for(let s=0;s<i.length;s++)for(let a=s+1;a<i.length;a++){let c=i[s],l=i[a];if(t.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=rwt(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+gm>=n)continue;let h=[c.pcb_via_id,l.pcb_via_id].sort().join("_");r.has(h)||(r.add(h),o.push({type:"pcb_via_clearance_error",pcb_error_id:`different_net_vias_close_${h}`,message:`Vias ${pr(e,c.pcb_via_id)} and ${pr(e,l.pcb_via_id)} from different nets are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:n,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return o}var swt=.2;function awt(e){if(e.outline&&e.outline.length>0)return e.outline.map(t=>({x:t.x,y:t.y}));if(e.center&&typeof e.width=="number"&&typeof e.height=="number"){let t=e.center.x,n=e.center.y,i=e.width/2,o=e.height/2;return[{x:t-i,y:n-o},{x:t+i,y:n-o},{x:t+i,y:n+o},{x:t-i,y:n+o}]}return null}function RX(e,t={}){let n=[],i=t.margin??swt,o=e.find(a=>a.type==="pcb_board");if(!o)return n;let r=awt(o);if(!r)return n;let s=Ge(e).pcb_trace.list();for(let a of s)if(!(a.route.length<2))for(let c=0;c<a.route.length-1;c++){let l=a.route[c],u=a.route[c+1];if(l.route_type!=="wire"||u.route_type!=="wire")continue;let h="width"in l?l.width:"width"in u?u.width:.1,d={x:l.x,y:l.y},_={x:u.x,y:u.y},y=1/0;for(let x=0;x<r.length;x++){let w=r[x],S=r[(x+1)%r.length],T=th(d,_,w,S);T<y&&(y=T)}let g=h/2+i;if(y<g){let x={type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:`trace_too_close_to_board_${a.pcb_trace_id}_segment_${c}`,message:`Trace too close to board edge (${y.toFixed(3)}mm < ${g.toFixed(3)}mm required, margin: ${i}mm)`,pcb_trace_id:a.pcb_trace_id,source_trace_id:a.source_trace_id||"",center:{x:(d.x+_.x)/2,y:(d.y+_.y)/2},pcb_component_ids:[],pcb_port_ids:[]};n.push(x)}}return n}function cwt(e,t){let n=nh([e]),i=nh([t]);return ic(n,i)}function OX(e){let t=[],n=$i(e),i=Ge(e).pcb_smtpad.list(),o=Ge(e).pcb_plated_hole.list(),r=Ge(e).pcb_hole.list(),s=new Map;for(let c of i){let l=c.pcb_component_id||`standalone_pad_${is(c)}`;s.has(l)||s.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),s.get(l).elements.push(c)}for(let c of o){let l=c.pcb_component_id||`standalone_plated_hole_${is(c)}`;s.has(l)||s.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),s.get(l).elements.push(c)}for(let c of r){let l=`standalone_hole_${is(c)}`;s.set(l,{component_id:l,elements:[c],bounds:{minX:0,minY:0,maxX:0,maxY:0}})}for(let[c,l]of s)l.elements.length>0&&(l.bounds=nh(l.elements));let a=Array.from(s.values());for(let c=0;c<a.length;c++)for(let l=c+1;l<a.length;l++){let u=a[c],h=a[l];if(ic(u.bounds,h.bounds))for(let d of u.elements)for(let _ of h.elements){let y=is(d),g=is(_);if(!(d.type==="pcb_smtpad"&&_.type==="pcb_smtpad"&&n.areIdsConnected(y,g))&&cwt(d,_)){let x={type:"pcb_footprint_overlap_error",pcb_error_id:`pcb_footprint_overlap_${y}_${g}`,error_type:"pcb_footprint_overlap_error",message:`PCB component ${d.type} "${y}" overlaps with ${_.type} "${g}"`};(d.type==="pcb_smtpad"||_.type==="pcb_smtpad")&&(x.pcb_smtpad_ids=[],d.type==="pcb_smtpad"&&x.pcb_smtpad_ids.push(y),_.type==="pcb_smtpad"&&x.pcb_smtpad_ids.push(g)),(d.type==="pcb_plated_hole"||_.type==="pcb_plated_hole")&&(x.pcb_plated_hole_ids=[],d.type==="pcb_plated_hole"&&x.pcb_plated_hole_ids.push(y),_.type==="pcb_plated_hole"&&x.pcb_plated_hole_ids.push(g)),(d.type==="pcb_hole"||_.type==="pcb_hole")&&(x.pcb_hole_ids=[],d.type==="pcb_hole"&&x.pcb_hole_ids.push(y),_.type==="pcb_hole"&&x.pcb_hole_ids.push(g)),t.push(x)}}}return t}var QM=[{value:1e12,symbol:"T"},{value:1e9,symbol:"G"},{value:1e6,symbol:"M"},{value:1e3,symbol:"k"},{value:1,symbol:""},{value:.001,symbol:"m"},{value:1e-6,symbol:"\xB5"},{value:1e-9,symbol:"n"},{value:1e-12,symbol:"p"}];function ni(e){if(e==null)return"";if(e===0)return"0";let t=Math.abs(e),n=QM.find(r=>{let s=t/r.value;return s>=1&&s<1e3})||QM[QM.length-1],o=(e/n.value).toPrecision(3);return o.includes(".")&&!/\.0+$/.test(o)&&(o=o.replace(/0+$/,"")),o=o.replace(/\.0+$/,""),`${o}${n.symbol}`}vt();vt();K();ke();Pf();var lwt=class{constructor(){P(this,"MAX_ITERATIONS",1e5);P(this,"solved",!1);P(this,"failed",!1);P(this,"iterations",0);P(this,"progress",0);P(this,"error",null);P(this,"activeSubSolver");P(this,"failedSubSolvers");P(this,"timeToSolve");P(this,"stats",{});P(this,"_setupDone",!1)}setup(){this._setupDone||(this._setup(),this._setupDone=!0)}_setup(){}step(){if(this._setupDone||this.setup(),!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.constructor.name} error: ${e}`,console.error(this.error),this.failed=!0,e}!this.solved&&this.iterations>=this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>=this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,console.error(this.error),this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}getOutput(){return null}solve(){let e=Date.now();for(;!this.solved&&!this.failed;)this.step();let t=Date.now();this.timeToSolve=t-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};var LX=class extends lwt{constructor(t){super();P(this,"startTimeOfPhase",{});P(this,"endTimeOfPhase",{});P(this,"timeSpentOnPhase",{});P(this,"firstIterationOfPhase",{});P(this,"currentPipelineStepIndex",0);P(this,"inputProblem");P(this,"pipelineOutputs",{});this.inputProblem=t,this.MAX_ITERATIONS=1e6}_step(){let t=this.pipelineDef[this.currentPipelineStepIndex];if(!t){this.solved=!0;return}if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){this.endTimeOfPhase[t.solverName]=performance.now(),this.timeSpentOnPhase[t.solverName]=this.endTimeOfPhase[t.solverName]-this.startTimeOfPhase[t.solverName];let i=this.activeSubSolver.getOutput();i!==null&&(this.pipelineOutputs[t.solverName]=i),t.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++}else this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let n=t.getConstructorParams(this);this.activeSubSolver=new t.solverClass(...n),this[t.solverName]=this.activeSubSolver,this.timeSpentOnPhase[t.solverName]=0,this.startTimeOfPhase[t.solverName]=performance.now(),this.firstIterationOfPhase[t.solverName]=this.iterations}solveUntilPhase(t){for(;this.getCurrentPhase().toLowerCase()!==t.toLowerCase()&&(this.step(),!(this.failed||this.solved)););}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}getPhaseProgress(){let t=this.pipelineDef.length;if(t===0)return 1;let n=this.activeSubSolver?.progress??0;return(this.currentPipelineStepIndex+n)/t}getPhaseStats(){let t={};for(let n of this.pipelineDef){let i=this.timeSpentOnPhase[n.solverName]||0,o=this.firstIterationOfPhase[n.solverName]||0,r=this.iterations,s=n.solverName===this.getCurrentPhase()?r-o:0,a=this.currentPipelineStepIndex>this.pipelineDef.findIndex(c=>c.solverName===n.solverName);t[n.solverName]={timeSpent:i,iterations:s,completed:a}}return t}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let t=this.pipelineDef.map((n,i)=>{let r=this[n.solverName]?.visualize();if(!r)return null;for(let s of r.rects??[])s.step=i;for(let s of r.points??[])s.step=i;for(let s of r.circles??[])s.step=i;for(let s of r.texts??[])s.step=i;for(let s of r.lines??[])s.step=i;return r}).filter(Boolean);return t.length===0?{points:[],rects:[],lines:[],circles:[],texts:[]}:t.length===1?t[0]:{points:t.flatMap(n=>n.points||[]),rects:t.flatMap(n=>n.rects||[]),lines:t.flatMap(n=>n.lines||[]),circles:t.flatMap(n=>n.circles||[]),texts:t.flatMap(n=>n.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}computeProgress(){return this.getPhaseProgress()}getStepOutput(t){return this.pipelineOutputs[t]}getAllOutputs(){return{...this.pipelineOutputs}}hasStepOutput(t){return t in this.pipelineOutputs}getSolver(t){return this[t]}};var uwt=e=>{let t=e.board_edge_margin??0;if(e.outline&&e.outline.length>0){let o=new L.Polygon(e.outline.map(r=>L.point(r.x,r.y)));return o.orientation()===L.ORIENTATION.CW&&o.reverse(),o}let{bounds:n}=e,i={minX:n.minX+t,minY:n.minY+t,maxX:n.maxX-t,maxY:n.maxY-t};return i.minX>=i.maxX||i.minY>=i.maxY?new L.Polygon:new L.Polygon(new L.Box(i.minX,i.minY,i.maxX,i.maxY).toPoints())},t4=(e,t=32)=>{let n=[];for(let i=0;i<t;i++){let o=i/t*2*Math.PI;n.push(new L.Point(e.center.x+e.r*Math.cos(o),e.center.y+e.r*Math.sin(o)))}return new L.Polygon(n)},pwt=e=>e.shape==="rect",hwt=e=>e.shape==="trace",dwt=e=>e.shape==="circle",fwt=e=>e.shape==="polygon",mwt=(e,t,n,i)=>{let o=[],{padMargin:r,traceMargin:s,board_edge_margin:a,cutoutMargin:c}=n;if(i&&i.length>0&&a&&a>0){let l=new L.Polygon(i.map(h=>L.point(h.x,h.y)));l.area()<0&&l.reverse();let u=l.vertices;for(let h=0;h<u.length;h++){let d=u[h===0?u.length-1:h-1],_=u[h],y=u[(h+1)%u.length];if(!d||!_||!y)continue;let g=new L.Vector(d,_),x=new L.Vector(_,y),w=g.cross(x),S=new L.Circle(_,a);if(o.push(t4(S)),w<0){let T=new L.Box(_.x-a,_.y-a,_.x+a,_.y+a);o.push(new L.Polygon(T.toPoints()))}}for(let h=0;h<u.length;h++){let d=u[h],_=u[(h+1)%u.length];if(!d||!_)continue;let y=Math.hypot(d.x-_.x,d.y-_.y);if(y===0)continue;let g=a*2,x=(d.x+_.x)/2,w=(d.y+_.y)/2,S=Math.atan2(_.y-d.y,_.x-d.x)*180/Math.PI,T=y/2,I=g/2,E=S*Math.PI/180,M=Math.cos(E),k=Math.sin(E),A=[{x:-T,y:-I},{x:T,y:-I},{x:T,y:I},{x:-T,y:I}].map(R=>({x:x+R.x*M-R.y*k,y:w+R.x*k+R.y*M}));o.push(new L.Polygon(A.map(R=>L.point(R.x,R.y))))}}for(let l of e){if(l.connectivityKey===t)continue;let h=l.connectivityKey.startsWith("hole:")||l.connectivityKey.startsWith("cutout:");if(dwt(l)){let d=h?c??0:r,_=new L.Circle(new L.Point(l.x,l.y),l.radius+d);o.push(t4(_));continue}if(pwt(l)){let d=h?c??0:r,{bounds:_}=l,y=new L.Box(_.minX-d,_.minY-d,_.maxX+d,_.maxY+d);o.push(new L.Polygon(y.toPoints()));continue}if(fwt(l)){let d=h?c??0:0,_=new Set,y=l.points.filter(T=>{let I=`${T.x},${T.y}`;return _.has(I)?!1:(_.add(I),!0)});if(y.length<3)continue;let g=new L.Polygon(y.map(T=>L.point(T.x,T.y)));if(Math.abs(g.area())<1e-9)continue;if(d<=0){o.push(g);continue}g.area()>0&&g.reverse();let x=[],w=g.vertices;for(let T=0;T<w.length;T++){let I=w[T],E=w[(T+1)%w.length],M=L.segment(I,E);if(M.length===0)continue;let k=L.line(M.start,M.end),N=k.norm,A=k.translate(N.multiply(-d));x.push(A)}let S=[];for(let T=0;T<x.length;T++){let I=x[T],E=x[(T+1)%x.length],M=I.intersect(E);M.length>0&&S.push(M[0])}S.length>=3&&o.push(new L.Polygon(S));continue}if(hwt(l)){for(let d of l.segments){let _=new L.Circle(new L.Point(d.x,d.y),l.width/2+s);o.push(t4(_))}for(let d=0;d<l.segments.length-1;d++){let _=l.segments[d],y=l.segments[d+1];if(!_||!y)continue;let g=Math.hypot(_.x-y.x,_.y-y.y);if(g===0)continue;let x=l.width+s*2,w=(_.x+y.x)/2,S=(_.y+y.y)/2,T=Math.atan2(y.y-_.y,y.x-_.x)*180/Math.PI,I=g/2,E=x/2,M=T*Math.PI/180,k=Math.cos(M),N=Math.sin(M),R=[{x:-I,y:-E},{x:I,y:-E},{x:I,y:E},{x:-I,y:E}].map($=>({x:w+$.x*k-$.y*N,y:S+$.x*N+$.y*k}));o.push(new L.Polygon(R.map($=>L.point($.x,$.y))))}continue}}return{polygonsToSubtract:o}},FX=e=>e.edges.map(t=>{let n={x:t.start.x,y:t.start.y};if(t.isArc){let i=Math.tan(t.shape.sweep/4);Math.abs(i)>1e-9&&(n.bulge=i)}return n}),_wt=e=>{let t=[],n=Array.isArray(e)?e:[e];for(let i of n){let o=i.splitToIslands();for(let r of o){if(r.isEmpty())continue;let s=[...r.faces],a=s.find(h=>h.orientation()===L.ORIENTATION.CCW),c=s.filter(h=>h.orientation()===L.ORIENTATION.CW);if(!a)continue;a.reverse();let l=FX(a),u=c.map(h=>(h.reverse(),{vertices:FX(h)}));t.push({outer_ring:{vertices:l},inner_rings:u})}}return t},zX=class extends LX{constructor(t){super(t);P(this,"pipelineDef",[]);this.input=t}getOutput(){let t=[];for(let n of this.input.regionsForPour){let i=uwt(n),o=this.input.pads.filter(c=>c.layer===n.layer),{polygonsToSubtract:r}=mwt(o,n.connectivityKey,{padMargin:n.padMargin,traceMargin:n.traceMargin,board_edge_margin:n.board_edge_margin,cutoutMargin:n.cutout_margin},n.outline),s=i;for(let c of r){let l=Array.isArray(s)?s:[s],u=[];for(let h of l){let d=L.BooleanOperations.subtract(h,c);d&&(Array.isArray(d)?u.push(...d.filter(_=>!_.isEmpty())):d.isEmpty()||u.push(d))}s=u}let a=_wt(s);t.push(...a)}return{brep_shapes:t}}},DX=(e,t)=>{let n=e.filter(T=>T.type==="source_port"),i=e.filter(T=>T.type==="pcb_port"),o=e.filter(T=>T.type==="source_trace"),r=e.filter(T=>T.type==="pcb_trace"),s=e.filter(T=>T.type==="source_net"),a=e.find(T=>T.type==="pcb_board");if(!a)throw new Error("No pcb_board found in circuit json");let c=Object.fromEntries(n.map(T=>[T.source_port_id,T.subcircuit_connectivity_map_key])),l=Object.fromEntries(i.map(T=>[T.pcb_port_id,c[T.source_port_id]])),u={};for(let T of i)T.pcb_port_id&&(u[T.pcb_port_id]=l[T.pcb_port_id]);let h=Object.fromEntries(o.map(T=>[T.source_trace_id,T.subcircuit_connectivity_map_key])),d=Object.fromEntries(s.map(T=>[T.source_net_id,T.subcircuit_connectivity_map_key])),_={...h,...d},y=Object.fromEntries(r.map(T=>[T.pcb_trace_id,T.source_trace_id?_[T.source_trace_id]:void 0]).filter(T=>!!T[1])),g=[];for(let T of e)if(T.type==="pcb_smtpad"){let I=T;if(I.layer!==t.layer)continue;let E;I.pcb_port_id&&(E=l[I.pcb_port_id]),E||(E=`unconnected:${I.pcb_smtpad_id}`),I.shape==="rect"?g.push({shape:"rect",padId:I.pcb_smtpad_id,layer:I.layer,connectivityKey:E,bounds:{minX:I.x-I.width/2,minY:I.y-I.height/2,maxX:I.x+I.width/2,maxY:I.y+I.height/2}}):I.shape==="circle"&&g.push({shape:"circle",padId:I.pcb_smtpad_id,layer:I.layer,connectivityKey:E,x:I.x,y:I.y,radius:I.radius})}else if(T.type==="pcb_plated_hole"){let I=T;if(I.shape!=="circle"||!I.layers.includes(t.layer))continue;let E=u[I.pcb_plated_hole_id];E||(E=`unconnected-plated-hole:${I.pcb_plated_hole_id}`),g.push({shape:"circle",padId:I.pcb_plated_hole_id,layer:t.layer,connectivityKey:E,x:I.x,y:I.y,radius:I.outer_diameter/2})}else if(T.type==="pcb_hole"){let I=T;if(I.hole_shape!=="circle")continue;g.push({shape:"circle",padId:I.pcb_hole_id,layer:t.layer,connectivityKey:`hole:${I.pcb_hole_id}`,x:I.x,y:I.y,radius:I.hole_diameter/2})}else if(T.type==="pcb_cutout"){let I=T;I.shape==="rect"?g.push({shape:"rect",padId:I.pcb_cutout_id,layer:t.layer,connectivityKey:`cutout:${I.pcb_cutout_id}`,bounds:{minX:I.center.x-I.width/2,minY:I.center.y-I.height/2,maxX:I.center.x+I.width/2,maxY:I.center.y+I.height/2}}):I.shape==="circle"?g.push({shape:"circle",padId:I.pcb_cutout_id,layer:t.layer,connectivityKey:`cutout:${I.pcb_cutout_id}`,x:I.center.x,y:I.center.y,radius:I.radius}):I.shape==="polygon"&&g.push({shape:"polygon",padId:I.pcb_cutout_id,layer:t.layer,connectivityKey:`cutout:${I.pcb_cutout_id}`,points:I.points})}else if(T.type==="pcb_via"){let I=T;if(!I.layers.includes(t.layer))continue;let E=I.subcircuit_connectivity_map_key??y[I.pcb_trace_id??""]??`unconnected-via:${I.pcb_via_id}`;g.push({shape:"circle",padId:I.pcb_via_id,layer:t.layer,connectivityKey:E,x:I.x,y:I.y,radius:I.outer_diameter/2})}else if(T.type==="pcb_trace"){let I=T;if(!I.source_trace_id)continue;let E=_[I.source_trace_id];if(!E)continue;let M=[],k=null,N=()=>{M.length>1&&g.push({shape:"trace",padId:`${I.pcb_trace_id}-${g.length}`,layer:t.layer,connectivityKey:E,segments:M,width:k}),M=[],k=null};for(let A of I.route){let R=A;R.route_type==="wire"&&R.layer===t.layer?(k===null&&(k=R.width),M.push({x:R.x,y:R.y})):N()}N()}let{width:x,height:w}=a,S=[{shape:"rect",layer:t.layer,bounds:{minX:-x/2,minY:-w/2,maxX:x/2,maxY:w/2},outline:a.outline,connectivityKey:t.pour_connectivity_key,padMargin:t.pad_margin,traceMargin:t.trace_margin,board_edge_margin:t.board_edge_margin??0,cutout_margin:t.cutout_margin}];return{pads:g,regionsForPour:S}};Ys();vt();ke();var QG=Xt(Mr(),1);var O4=Xt(Sn(),1),Bh=Xt(Mr(),1),Fne=Xt(Mr(),1);var mu=Xt(uu(),1);var tU=Xt(uu(),1),eU=Xt(uu(),1);var nU=Xt(uu(),1);var iU=Xt(uu(),1);var oU=Xt(uu(),1),rU=Xt(Mr(),1);var y5t=Object.defineProperty,g5t=(e,t)=>{for(var n in t)y5t(e,n,{get:t[n],enumerable:!0})},SH={};g5t(SH,{AnalogSimulation:()=>KG,Battery:()=>NG,Board:()=>QH,Breakout:()=>SG,BreakoutPoint:()=>wG,CadAssembly:()=>DH,CadModel:()=>zH,Capacitor:()=>eG,Chip:()=>Fm,Constraint:()=>uG,CopperPour:()=>EG,Crystal:()=>FG,Cutout:()=>Rm,Diode:()=>iG,FabricationNoteDimension:()=>fG,FabricationNotePath:()=>hG,FabricationNoteRect:()=>pG,FabricationNoteText:()=>dG,Footprint:()=>OH,Fuse:()=>oG,Group:()=>Tc,Hole:()=>Xh,Inductor:()=>RG,Jumper:()=>rG,Keepout:()=>Rx,Led:()=>aG,Mosfet:()=>DG,Net:()=>z4,NetLabel:()=>PG,NormalComponent:()=>On,Panel:()=>tG,PcbNoteDimension:()=>bG,PcbNoteLine:()=>mG,PcbNotePath:()=>gG,PcbNoteRect:()=>_G,PcbNoteText:()=>yG,PcbTrace:()=>$4,PinHeader:()=>kG,Pinout:()=>nG,PlatedHole:()=>Yh,Port:()=>Ni,Potentiometer:()=>OG,PowerSource:()=>cG,PrimitiveComponent:()=>xe,PushButton:()=>LG,Renderable:()=>L4,Resistor:()=>X4,Resonator:()=>AG,SchematicArc:()=>VG,SchematicBox:()=>GG,SchematicCell:()=>WG,SchematicCircle:()=>HG,SchematicLine:()=>YG,SchematicRect:()=>XG,SchematicRow:()=>qG,SchematicTable:()=>UG,SchematicText:()=>BG,SilkscreenCircle:()=>IG,SilkscreenLine:()=>MG,SilkscreenPath:()=>D4,SilkscreenRect:()=>TG,SilkscreenText:()=>Dx,SmtPad:()=>Am,SolderJumper:()=>sG,Subcircuit:()=>vG,Switch:()=>$G,Symbol:()=>ZG,TestPoint:()=>jG,Trace:()=>$r,TraceHint:()=>B4,Transistor:()=>zG,Via:()=>CG,VoltageProbe:()=>JG,VoltageSource:()=>lG});var b5t=(0,IH.default)("tscircuit:renderable"),aa=["ReactSubtreesRender","InflateSubcircuitCircuitJson","SourceNameDuplicateComponentRemoval","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","AssignFallbackProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SourceDesignRuleChecks","SimulationRender","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicComponentSizeCalculation","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbComponentAnchorAlignment","PcbLayout","PcbBoardAutoSize","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbCopperPourRender","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender","SimulationSpiceEngineRender"],x5t={PcbFootprintLayout:["PcbFootprintStringRender"],PcbComponentSizeCalculation:["PcbFootprintStringRender"],PcbLayout:["PcbFootprintStringRender"],PcbBoardAutoSize:["PcbFootprintStringRender"],PcbTraceHintRender:["PcbFootprintStringRender"],PcbManualTraceRender:["PcbFootprintStringRender"],PcbCopperPourRender:["PcbFootprintStringRender","PcbTraceRender","PcbRouteNetIslands"],PcbTraceRender:["PcbFootprintStringRender"],PcbRouteNetIslands:["PcbFootprintStringRender"],PcbDesignRuleChecks:["PcbFootprintStringRender"],SilkscreenOverlapAdjustment:["PcbFootprintStringRender"],CadModelRender:["PcbFootprintStringRender"],PartsEngineRender:["PcbFootprintStringRender"],PcbComponentAnchorAlignment:["PcbFootprintStringRender"]},v5t=0,L4=class TH{constructor(t){P(this,"renderPhaseStates");P(this,"shouldBeRemoved",!1);P(this,"children");P(this,"isPcbPrimitive",!1);P(this,"isSchematicPrimitive",!1);P(this,"_renderId");P(this,"_currentRenderPhase",null);P(this,"_asyncEffects",[]);P(this,"parent",null);this._renderId=`${v5t++}`,this.children=[],this.renderPhaseStates={};for(let n of aa)this.renderPhaseStates[n]={initialized:!1,dirty:!1}}_markDirty(t){this.renderPhaseStates[t].dirty=!0;let n=aa.indexOf(t);for(let i=n+1;i<aa.length;i++)this.renderPhaseStates[aa[i]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(t)}_queueAsyncEffect(t,n){let i={promise:n(),phase:this._currentRenderPhase,effectName:t,complete:!1};this._asyncEffects.push(i),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:t,componentDisplayName:this.getString(),phase:i.phase}),i.promise.then(()=>{i.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:t,componentDisplayName:this.getString(),phase:i.phase})}).catch(o=>{console.error(`Async effect error in ${i.phase} "${t}":
|
|
249
|
+
${o.stack}`),i.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:t,componentDisplayName:this.getString(),phase:i.phase,error:o.toString()})})}_emitRenderLifecycleEvent(t,n){b5t(`${t}:${n} ${this.getString()}`);let i=`renderable:renderLifecycle:${t}:${n}`,o={renderId:this._renderId,componentDisplayName:this.getString(),type:i};"root"in this&&this.root&&(this.root.emit(i,o),this.root.emit("renderable:renderLifecycle:anyEvent",{...o,type:i}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(t=>!t.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(t){for(let n of this._asyncEffects)if(!n.complete&&n.phase===t)return!0;for(let n of this.children)if(n._hasIncompleteAsyncEffectsInSubtreeForPhase(t))return!0;return!1}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(t=>t.getRenderGraph())}}getTopLevelRenderable(){let t=this;for(;t.parent&&t.parent instanceof TH;)t=t.parent;return t}runRenderCycle(){for(let t of aa)this.runRenderPhaseForChildren(t),this.runRenderPhase(t)}runRenderPhase(t){this._currentRenderPhase=t;let n=this.renderPhaseStates[t],i=n.initialized,o=n.dirty;if(!i&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&i){this._emitRenderLifecycleEvent(t,"start"),this?.[`remove${t}`]?.(),n.initialized=!1,n.dirty=!1,this._emitRenderLifecycleEvent(t,"end");return}let r=aa.indexOf(t)-1;if(r>=0){let a=aa[r];if(this._asyncEffects.filter(l=>l.phase===a).some(l=>!l.complete))return}let s=x5t[t]||[];if(s.length>0){let a=this.getTopLevelRenderable();for(let c of s)if(a._hasIncompleteAsyncEffectsInSubtreeForPhase(c))return}if(this._emitRenderLifecycleEvent(t,"start"),i){o&&(this?.[`update${t}`]?.(),n.dirty=!1),this._emitRenderLifecycleEvent(t,"end");return}n.dirty=!1,this?.[`doInitial${t}`]?.(),n.initialized=!0,this._emitRenderLifecycleEvent(t,"end")}runRenderPhaseForChildren(t){for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}renderError(t){throw typeof t=="string"?new Error(t):new Error(JSON.stringify(t,null,2))}},Ax={},MH=e=>{let t=Object.fromEntries(Object.entries(e).map(([n,i])=>[n.toLowerCase(),i]));Object.assign(Ax,e),Object.assign(Ax,t)},S5t=class extends Error{constructor(e,t,n){let i,o=Object.keys(n).filter(c=>c!=="_errors"),r=[],s=t.pinLabels;if(s)for(let[c,l]of Object.entries(s)){let u=Array.isArray(l)?l:[l];for(let h of u)typeof h=="string"&&(h.startsWith(" ")||h.endsWith(" "))&&r.push(`pinLabels.${c} ("${h}" has leading or trailing spaces)`)}let a=o.map(c=>c==="pinLabels"&&r.length>0?r.join(", "):n[c]._errors[0]?`${c} (${n[c]._errors[0]})`:`${c} (${JSON.stringify(n[c])})`).join(", ");"name"in t?i=`Invalid props for ${e} "${t.name}": ${a}`:"footprint"in t&&typeof t.footprint=="string"?i=`Invalid props for ${e} (unnamed ${t.footprint} component): ${a}`:i=`Invalid props for ${e} (unnamed): ${a}`,super(i),this.componentName=e,this.originalProps=t,this.formattedError=n}};function b4(e,t){let n=t.match(/^#(\w+)/);if(n)return e.props.id===n[1];let i=t.match(/^\.(\w+)/);if(i)return e.isMatchingNameOrAlias(i[1]);let[o,...r]=t.split(/(?=[#.[])/);return o==="pin"&&(o="port"),o&&o!=="*"&&e.lowercaseComponentName!==o.toLowerCase()?!1:r.every(s=>{if(s.startsWith("#"))return e.props.id===s.slice(1);if(s.startsWith("."))return e.isMatchingNameOrAlias(s.slice(1));let a=s.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!a)return!0;let[,c,l]=a;return e.props[c].toString()===l})}var F4={isTag:e=>!0,getParent:e=>e.parent,getChildren:e=>e.children,getName:e=>e.lowercaseComponentName,getAttributeValue:(e,t)=>{if(t==="class"&&"getNameAndAliases"in e)return e.getNameAndAliases().join(" ");if(t==="name"&&e._parsedProps?.name)return e._parsedProps.name;if(e._parsedProps&&t in e._parsedProps){let i=e._parsedProps[t];return typeof i=="string"?i:i!=null?String(i):null}if(t in e){let i=e[t];return typeof i=="string"?i:i!=null?String(i):null}let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e){let o=e[i];return typeof o=="string"?o:o!=null?String(o):null}}return null},hasAttrib:(e,t)=>{if(t==="class")return!!e._parsedProps?.name;if(e._parsedProps&&t in e._parsedProps||t in e)return!0;let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e)return!0}return!1},getSiblings:e=>e.parent?e.parent.children:[],prevElementSibling:e=>{if(!e.parent)return null;let t=e.parent.children,n=t.indexOf(e);return n>0?t[n-1]:null},getText:()=>"",removeSubsets:e=>e.filter((t,n)=>!e.some((i,o)=>n!==o&&i!==t&&i.getDescendants().includes(t))),existsOne:(e,t)=>t.some(e),findAll:(e,t)=>{let n=[],i=o=>{e(o)&&n.push(o);for(let r of o.children)i(r)};for(let o of t)i(o);return n},findOne:(e,t)=>{for(let n of t){if(e(n))return n;let i=n.children;if(i.length>0){let o=F4.findOne(e,i);if(o)return o}}return null},equals:(e,t)=>e._renderId===t._renderId,isHovered:e=>!1,isVisited:e=>!1,isActive:e=>!1},w5t={...F4,getChildren:e=>e.children.filter(t=>!t.isSubcircuit)},KV={...F4,getChildren:e=>e.children.filter(t=>t.isSubcircuit)},JV=e=>{if(/net\.[^\s>]*\./.test(e))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(e))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(e)){let t=e.match(/net\.([^ >]+)/),n=t?t[1]:"";throw new Error(`Net name "${n}" cannot start with a number, try using a prefix like "VBUS1"`)}return e.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(t,n,i,o)=>{let r=/^\d+$/.test(o)?`pin${o}`:o;return`${n}.${i} > .${r}`}).trim()},x4={adapter:w5t,cacheResults:!0},xe=class extends L4{constructor(t){super(t);P(this,"parent",null);P(this,"children");P(this,"childrenPendingRemoval");P(this,"props");P(this,"_parsedProps");P(this,"externallyAddedAliases");P(this,"isPrimitiveContainer",!1);P(this,"canHaveTextChildren",!1);P(this,"source_group_id",null);P(this,"source_component_id",null);P(this,"schematic_component_id",null);P(this,"pcb_component_id",null);P(this,"cad_component_id",null);P(this,"fallbackUnassignedName");P(this,"_cachedSelectAllQueries",new Map);P(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=t??{},this.externallyAddedAliases=[];let i=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(t??{});if(i.success)this._parsedProps=i.data;else throw new S5t(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:p.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(t){let n=this;for(;n;){if(n._parsedProps&&t in n._parsedProps)return n._parsedProps[t];n=n.parent}if(this.root?.platform&&t in this.root.platform)return this.root.platform[t]}getInheritedMergedProperty(t){let n=this.parent?.getInheritedMergedProperty?.(t),i=this._parsedProps?.[t];return{...n,...i}}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(t){let n=this.config.zodProps.parse({...this.props,...t}),i=this.props;this.props=n,this._parsedProps=this.config.zodProps.parse(t),this.onPropsChange({oldProps:i,newProps:n,changedProps:Object.keys(t)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:t}=this.props;return typeof t=="string"?parseFloat(t):t??null}computePcbPropsTransform(){let{_parsedProps:t}=this,n=this._getPcbRotationBeforeLayout()??0;return Qn(vn(t.pcbX??0,t.pcbY??0),Ua(n*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let t=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(t&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let n=this._getPcbRotationBeforeLayout()??0;return Qn(this.parent?._computePcbGlobalTransformBeforeLayout()??zi(),Qn(vn(t.x,t.y),Ua(n*Math.PI/180)))}if(this.isPcbPrimitive){let n=this.getPrimitiveContainer();if(n&&n._parsedProps.layer==="bottom")return Qn(this.parent?._computePcbGlobalTransformBeforeLayout()??zi(),y8(),this.computePcbPropsTransform())}return Qn(this.parent?._computePcbGlobalTransformBeforeLayout()??zi(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}getParentNormalComponent(){let t=this.parent;for(;t;){if(t.isPrimitiveContainer&&t.doInitialPcbComponentRender)return t;t=t.parent}return null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let t=this.getPrimitiveContainer(),n=t?t._parsedProps.layer==="bottom":!1;return{isFlipped:n,maybeFlipLayer:o=>n?o==="top"?"bottom":"top":o}}_setPositionFromLayout(t){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:t}=this;return Qn(vn(t.schX??0,t.schY??0))}computeSchematicGlobalTransform(){let t=this._getSchematicGlobalManualPlacementTransform(this);return t||Qn(this.parent?.computeSchematicGlobalTransform?.()??zi(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:t}=this,n=this.config.schematicSymbolName,i={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},o=t.schOrientation!==void 0?i[t.schOrientation]:t.schRotation;if(o===void 0&&(o=0),o=o%360,o<0&&(o+=360),t.schRotation!==void 0&&o%90!==0)throw new Error(`Schematic rotation ${t.schRotation} is not supported for ${this.componentName}`);let r=`${n}_horz`,s=`${n}_vert`,a=`${n}_up`,c=`${n}_down`,l=`${n}_left`,u=`${n}_right`;if(u in ti&&o===0)return u;if(a in ti&&o===90)return a;if(l in ti&&o===180)return l;if(c in ti&&o===270)return c;if(r in ti&&(o===0||o===180))return r;if(s in ti&&(o===90||o===270))return s;if(n in ti)return n}_getSchematicSymbolNameOrThrow(){let t=this._getSchematicSymbolName();if(!t)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return t}getSchematicSymbol(){let t=this._getSchematicSymbolName();return t?ti[t]??null:null}_getPcbManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n?.pcb_placements;if(!i)return null;for(let o of i)if(b4(t,o.selector)||t.props.name===o.selector)return Ne(this._computePcbGlobalTransformBeforeLayout(),o.center);return null}_getSchematicManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n.schematic_placements;if(!i)return null;for(let o of i)if(b4(t,o.selector)||t.props.name===o.selector)return Ne(this.computeSchematicGlobalTransform(),o.center);return null}_getSchematicGlobalManualPlacementTransform(t){let n=this.getSubcircuit()?._parsedProps.manualEdits;if(!n)return null;for(let i of n.schematic_placements??[])if((b4(t,i.selector)||t.props.name===i.selector)&&i.relative_to==="group_center")return Qn(this.parent?._computePcbGlobalTransformBeforeLayout()??zi(),vn(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return Ne(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return Ne(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(t){this.parent=t}onPropsChange(t){}onChildChanged(t){this.parent?.onChildChanged?.(t)}add(t){let n=t.__text;if(typeof n=="string"){if(this.canHaveTextChildren||n.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${n}"`)}if(Object.keys(t).length!==0){if(this.lowercaseComponentName==="board"&&t.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(t.lowercaseComponentName==="panel")throw new Error("<panel> must be a root-level element");if(!t.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(t)}"`);t.onAddToParent(this),t.parent=this,this.children.push(t)}}addAll(t){for(let n of t)this.add(n)}remove(t){this.children=this.children.filter(n=>n!==t),this.childrenPendingRemoval.push(t),t.shouldBeRemoved=!0}getSubcircuitSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?n:`${this.parent.getSubcircuitSelector()} > ${n}`}getFullPathSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName,i=this.parent?.getFullPathSelector?.();return i?`${i} > ${n}`:n}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(t){return this.getNameAndAliases().includes(t)}isMatchingAnyOf(t){return this.getNameAndAliases().some(n=>t.map(i=>i.toString()).includes(n))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(t){let n=[this.componentName,this.lowercaseComponentName],i=[this.name].filter(Boolean),o=t.trim().split(/\> /)[0],r=o[0];return o.length>1?!1:!!(t==="*"||t[0]==="#"&&t.slice(1)===this.props.id||t[0]==="."&&i.includes(t.slice(1))||/^[a-zA-Z0-9_]/.test(r)&&n.includes(r))}getSubcircuit(){if(this.isSubcircuit)return this;let t=this.parent?.getSubcircuit?.();if(!t)throw new Error("Component is not inside an opaque group (no board?)");return t}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let t=this.selectAll("port");for(let n of t){let o=(n.getParentNormalComponent?.()??n.parent)?.getNameAndAliases(),r=n.getNameAndAliases();if(o)for(let s of o)for(let a of r){let c=[`.${s} > .${a}`,`.${s} .${a}`];for(let l of c){let u=this._cachedSelectAllQueries.get(l);u?u.push(n):this._cachedSelectAllQueries.set(l,[n])}}}for(let[n,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(n,i[0])}selectAll(t){if(this._cachedSelectAllQueries.has(t))return this._cachedSelectAllQueries.get(t);let n=JV(t),i=hI(n,this,x4);if(i.length>0)return this._cachedSelectAllQueries.set(t,i),i;let[o,...r]=n.split(" "),s=jg(o,this,{adapter:KV});if(!s)return[];let a=s.selectAll(r.join(" "));return this._cachedSelectAllQueries.set(t,a),a}selectOne(t,n){if(this._cachedSelectOneQueries.has(t))return this._cachedSelectOneQueries.get(t);let i=JV(t);n?.port&&(n.type="port");let o=null;if(n?.type&&(o=hI(i,this,x4).find(l=>l.lowercaseComponentName===n.type)),o??(o=jg(i,this,x4)),o)return this._cachedSelectOneQueries.set(t,o),o;let[r,...s]=i.split(" "),a=jg(r,this,{adapter:KV});return a?(o=a.selectOne(s.join(" "),n),this._cachedSelectOneQueries.set(t,o),o):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:t}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[t(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?this.root?._getBoard()?.allLayers??["top","bottom"]:[]}return[]}getDescendants(){let t=[];for(let n of this.children)t.push(n),t.push(...n.getDescendants());return t}getSelectableDescendants(){let t=[];for(let n of this.children)n.isSubcircuit?t.push(n):(t.push(n),t.push(...n.getSelectableDescendants()));return t}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this;return{schWidth:t.schWidth,schHeight:t.schHeight}}renderError(t){if(typeof t=="string")return super.renderError(t);switch(t.type){case"pcb_placement_error":this.root?.db.pcb_placement_error.insert(t);break;case"pcb_via_clearance_error":this.root?.db.pcb_via_clearance_error.insert(t);break;case"pcb_trace_error":this.root?.db.pcb_trace_error.insert(t);break;case"pcb_manual_edit_conflict_warning":this.root?.db.pcb_manual_edit_conflict_warning.insert(t);break;default:this.root?.db.pcb_placement_error.insert(t)}}getString(){let{lowercaseComponentName:t,_parsedProps:n,parent:i}=this;return n?.pinNumber!==void 0&&i?.props?.name&&n?.name?`<${t}#${this._renderId}(pin:${n.pinNumber} .${i?.props.name}>.${n.name}) />`:i?.props?.name&&n?.name?`<${t}#${this._renderId}(.${i?.props.name}>.${n?.name}) />`:n?.from&&n?.to?`<${t}#${this._renderId}(from:${n.from} to:${n?.to}) />`:n?.name?`<${t}#${this._renderId} name=".${n?.name}" />`:n?.portHints?`<${t}#${this._renderId}(${n.portHints.map(o=>`.${o}`).join(", ")}) />`:`<${t}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},P5t=class extends xe{constructor(e,t){super(e),this._parsedProps={...e,error:t,type:e.type||"unknown",component_name:e.name,error_type:"source_failed_to_create_component_error",message:t instanceof Error?t.message:String(t),pcbX:e.pcbX,pcbY:e.pcbY,schX:e.schX,schY:e.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:p.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let e=this._getGlobalPcbPositionBeforeLayout(),t=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:e,schematic_center:t})}}};function I5t(e,t){return new P5t(e,t)}function T5t(e,t){let n=e;return n.__tsci={...t},e}var M5t={supportsMutation:!0,createInstance(e,t){let n=Ax[e];if(!n)throw Object.keys(Ax).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type "${e}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return T5t(new n(t),{})}catch(i){return I5t({...t,componentType:e},i)}},createTextInstance(e){return{__text:e}},appendInitialChild(e,t){e.add(t)},appendChild(e,t){e.add(t)},appendChildToContainer(e,t){e.add(t)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(e){return e},preparePortalMount(e){throw new Error("Function not implemented.")},scheduleTimeout(e,t){throw new Error("Function not implemented.")},cancelTimeout(e){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(e){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(e,t)=>{throw new Error("Function not implemented.")},getInstanceFromScope:e=>{throw new Error("Function not implemented.")},detachDeletedInstance:e=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>Nx.DefaultEventPriority,getCurrentUpdatePriority:()=>Nx.DefaultEventPriority,resolveUpdatePriority:()=>Nx.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},Tx=(0,PH.default)(M5t),CH=e=>{let t={children:[],props:{name:"$root"},add(r){r.parent=this,this.children.push(r)},computePcbGlobalTransform(){return zi()}},n=[],i=Tx.createContainer(t,0,null,!1,null,"tsci",r=>{console.log("Error in createContainer"),console.error(r),n.push(r)},null);if(Tx.updateContainerSync(e,i,null,()=>{}),Tx.flushSyncWork(),n.length>0)throw n[0];let o=Tx.getPublicRootInstance(i);return o||t.children[0]},Om=(e,t)=>{if(typeof e=="number")return e;if(e.startsWith("pin"))return Number(e.slice(3));if(!t)throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`);for(let n in t)if((Array.isArray(t[n])?t[n]:[t[n]]).includes(e))return Number(n.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`)},C5t=(e,t)=>{if(!e)return;let n={},i={};for(let[o,r]of Object.entries(e)){let s=Om(o,t);i[s]={...i[s],...r}}for(let[o,r]of Object.entries(i)){let s=`pin${o}`;n[s]={bottom_margin:r.bottomMargin,left_margin:r.leftMargin,right_margin:r.rightMargin,top_margin:r.topMargin}}return n},E5t=e=>{if(e){if("leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e)return{left_side:e.leftSide,right_side:e.rightSide,top_side:e.topSide,bottom_side:e.bottomSide};if("leftPinCount"in e||"rightPinCount"in e||"topPinCount"in e||"bottomPinCount"in e)return{left_size:e.leftPinCount,right_size:e.rightPinCount,top_size:e.topPinCount,bottom_size:e.bottomPinCount};if("leftSize"in e||"rightSize"in e||"topSize"in e||"bottomSize"in e)return{left_size:e.leftSize,right_size:e.rightSize,top_size:e.topSize,bottom_size:e.bottomSize}}};function EH(e){let t=[];for(let n=0;n<e.length-1;n++)t.push([e[n],e[n+1]]);return t}var N5t=p.object({name:p.string().refine(e=>!/[+-]/.test(e),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),z4=class extends xe{constructor(){super(...arguments);P(this,"source_net_id");P(this,"subcircuit_connectivity_map_key",null)}get config(){return{componentName:"Net",zodProps:N5t}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=n.name.startsWith("GND"),o=n.name.startsWith("V"),r=t.source_net.insert({name:n.name,member_source_group_ids:[],is_ground:i,is_power:o,is_positive_voltage_source:o});this.source_net_id=r.source_net_id}doInitialSourceParentAttachment(){let t=this.getSubcircuit();if(!t)return;let{db:n}=this.root;n.source_net.update(this.source_net_id,{subcircuit_id:t.subcircuit_id})}getAllConnectedPorts(){let t=this.getSubcircuit().selectAll("port"),n=[];for(let i of t){let o=i._getDirectlyConnectedTraces();for(let r of o)if(r._isExplicitlyConnectedToNet(this)){n.push(i);break}}return n}_getAllDirectlyConnectedTraces(){let t=this.getSubcircuit().selectAll("trace"),n=[];for(let i of t)i._isExplicitlyConnectedToNet(this)&&n.push(i);return n}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getAllDirectlyConnectedTraces().filter(s=>(s._portsRoutedOnPcb?.length??0)>0),o=[];for(let s of i){let a=s._portsRoutedOnPcb,c=o.find(l=>a.some(u=>l.ports.includes(u)));if(!c){o.push({ports:[...a],traces:[s]});continue}c.traces.push(s),c.ports.push(...a)}if(o.length===0)return;let r=EH(o);for(let[s,a]of r){let c=s.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),u=1/0,h=[-1,-1];for(let w=0;w<c.length;w++){let S=c[w];for(let T=0;T<l.length;T++){let I=l[T],E=Math.sqrt((S.x-I.x)**2+(S.y-I.y)**2);E<u&&(u=E,h=[w,T])}}let d=s.ports[h[0]],_=a.ports[h[1]],y=t.toArray().filter(w=>w.type==="pcb_smtpad"||w.type==="pcb_trace"||w.type==="pcb_plated_hole"||w.type==="pcb_hole"||w.type==="source_port"||w.type==="pcb_port"),{solution:g}=oz(y.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[d.source_port_id,_.source_port_id]}])),x=g[0];if(!x){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[d.pcb_component_id,_.pcb_component_id].filter(Boolean),pcb_port_ids:[d.pcb_port_id,_.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}t.pcb_trace.insert(x)}}renderError(t){if(typeof t=="string")return super.renderError(t);this.root?.db.pcb_trace_error.insert(t)}},zx=(e,t)=>{for(let n of t)if(typeof n=="string"&&n.startsWith("net.")){if(/net\.[^\s>]*\./.test(n))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(n))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(n)){let o=n.split("net.")[1];throw new Error(`Net name "${o}" cannot start with a number, try using a prefix like "VBUS1"`)}let i=e.getSubcircuit();if(!i.selectOne(n)){let o=new z4({name:n.split("net.")[1]});i.add(o)}}},Am=class extends xe{constructor(){super(...arguments);P(this,"pcb_smtpad_id",null);P(this,"matchedPort",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:Nz}}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="rotated_rect"){let i=(t.ccwRotation??0)*Math.PI/180,o=Math.cos(i),r=Math.sin(i),s=Math.abs(t.width*o)+Math.abs(t.height*r),a=Math.abs(t.width*r)+Math.abs(t.height*o);return{width:s,height:a}}if(t.shape==="polygon"){let n=t.points,i=n.map(l=>l.x),o=n.map(l=>l.y),r=Math.min(...i),s=Math.max(...i),a=Math.min(...o),c=Math.max(...o);return{width:s-r,height:c-a}}if(t.shape==="pill")return{width:t.width,height:t.height};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.coveredWithSolderMask??!1,o=!i;if(!n.portHints)return;let r=this.getSubcircuit(),s=this._getGlobalPcbPositionBeforeLayout(),a=this._computePcbGlobalTransformBeforeLayout(),u=(Ar(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,h=.01,d=Math.abs(u)<h||Math.abs(u-180)<h||Math.abs(u-360)<h,_=Math.abs(u-90)<h||Math.abs(u-270)<h,y=Math.abs(u-360)<h?0:u,g=y,{maybeFlipLayer:x,isFlipped:w}=this._getPcbPrimitiveFlippedHelpers();w&&(y=(360-y+360)%360);let S=null,T=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(n.shape==="circle")S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"circle",radius:n.radius,port_hints:n.portHints.map(I=>I.toString()),is_covered_with_solder_mask:i,x:s.x,y:s.y,subcircuit_id:r?.subcircuit_id??void 0}),o&&t.pcb_solder_paste.insert({layer:S.layer,shape:"circle",radius:S.radius*.7,x:S.x,y:S.y,pcb_component_id:S.pcb_component_id,pcb_smtpad_id:S.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});else if(n.shape==="rect")!d&&!_?S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"rotated_rect",width:n.width,height:n.height,corner_radius:n.cornerRadius??void 0,x:s.x,y:s.y,ccw_rotation:y,port_hints:n.portHints.map(E=>E.toString()),is_covered_with_solder_mask:i,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"rect",width:_?n.height:n.width,height:_?n.width:n.height,corner_radius:n.cornerRadius??void 0,port_hints:n.portHints.map(E=>E.toString()),is_covered_with_solder_mask:i,x:s.x,y:s.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),o&&(S.shape==="rect"?t.pcb_solder_paste.insert({layer:x(n.layer??"top"),shape:"rect",width:S.width*.7,height:S.height*.7,x:S.x,y:S.y,pcb_component_id:S.pcb_component_id,pcb_smtpad_id:S.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):S.shape==="rotated_rect"&&t.pcb_solder_paste.insert({layer:x(n.layer??"top"),shape:"rotated_rect",width:S.width*.7,height:S.height*.7,x:S.x,y:S.y,ccw_rotation:S.ccw_rotation,pcb_component_id:S.pcb_component_id,pcb_smtpad_id:S.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));else if(n.shape==="rotated_rect"){let I=n.ccwRotation??0,E=(g+I+360)%360,M=w?(360-E+360)%360:E;S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"rotated_rect",width:n.width,height:n.height,corner_radius:n.cornerRadius??void 0,x:s.x,y:s.y,ccw_rotation:M,port_hints:n.portHints.map(k=>k.toString()),is_covered_with_solder_mask:i,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),o&&t.pcb_solder_paste.insert({layer:x(n.layer??"top"),shape:"rotated_rect",width:S.width*.7,height:S.height*.7,x:s.x,y:s.y,ccw_rotation:M,pcb_component_id:T,pcb_smtpad_id:S.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="polygon"){let I=n.points.map(E=>{let M=Ne(a,{x:Y.parse(E.x),y:Y.parse(E.y)});return{x:M.x,y:M.y}});S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"polygon",points:I,port_hints:n.portHints.map(E=>E.toString()),is_covered_with_solder_mask:i,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else n.shape==="pill"&&(S=t.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(n.layer??"top"),shape:"pill",x:s.x,y:s.y,radius:n.radius,height:n.height,width:n.width,port_hints:n.portHints.map(I=>I.toString()),is_covered_with_solder_mask:i,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));S&&(this.pcb_smtpad_id=S.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_smtpad.get(this.pcb_smtpad_id);if(n.shape==="rect")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.width/2,top:n.y+n.height/2,right:n.x+n.width/2,bottom:n.y-n.height/2},width:n.width,height:n.height};if(n.shape==="rotated_rect"){let i=n.ccw_rotation*Math.PI/180,o=Math.cos(i),r=Math.sin(i),s=n.width/2,a=n.height/2,c=Math.abs(s*o)+Math.abs(a*r),l=Math.abs(s*r)+Math.abs(a*o);return{center:{x:n.x,y:n.y},bounds:{left:n.x-c,right:n.x+c,top:n.y-l,bottom:n.y+l},width:c*2,height:l*2}}if(n.shape==="circle")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.radius,top:n.y-n.radius,right:n.x+n.radius,bottom:n.y+n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){let i=n.points,o=i.map(u=>u.x),r=i.map(u=>u.y),s=Math.min(...o),a=Math.max(...o),c=Math.min(...r),l=Math.max(...r);return{center:{x:(s+a)/2,y:(c+l)/2},bounds:{left:s,top:l,right:a,bottom:c},width:a-s,height:l-c}}if(n.shape==="pill"){let i=n.width/2,o=n.height/2;return{center:{x:n.x,y:n.y},bounds:{left:n.x-i,top:n.y-o,right:n.x+i,bottom:n.y+o},width:n.width,height:n.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${n.shape}"`)}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y});let i=n.pcb_solder_paste.list().find(o=>o.pcb_smtpad_id===this.pcb_smtpad_id);i&&n.pcb_solder_paste.update(i.pcb_solder_paste_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}},D4=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_path_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:yD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenPath. Must be "top" or "bottom".`);let r=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_path.insert({pcb_component_id:a,layer:o,route:n.route.map(l=>{let u=Ne(r,{x:l.x,y:l.y});return{...l,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=c.pcb_silkscreen_path_id}_setPositionFromLayout(t){let{db:n}=this.root,{_parsedProps:i}=this,o=n.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!o)return;let r=0,s=0;for(let u of o.route)r+=u.x,s+=u.y;r/=o.route.length,s/=o.route.length;let a=t.x-r,c=t.y-s,l=o.route.map(u=>({...u,x:u.x+a,y:u.y+c}));n.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:l})}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,o=1/0,r=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),o=Math.min(o,s.y),r=Math.max(r,s.y);return{width:i-n,height:r-o}}},k5t=p.object({route:p.array(N_),source_trace_id:p.string().optional()}),$4=class extends xe{constructor(){super(...arguments);P(this,"pcb_trace_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:k5t}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),o=this.getSubcircuit(),{maybeFlipLayer:r}=this._getPcbPrimitiveFlippedHelpers(),s=this._computePcbGlobalTransformBeforeLayout(),a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=Ne(s,{x:u,y:h});return l.route_type==="wire"&&l.layer?{..._,...d,layer:r(l.layer)}:{..._,...d}}),c=t.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:n.source_trace_id,route:a,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,o=1/0,r=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),o=Math.min(o,s.y),r=Math.max(r,s.y),s.route_type==="wire"&&(n=Math.min(n,s.x-s.width/2),i=Math.max(i,s.x+s.width/2),o=Math.min(o,s.y-s.width/2),r=Math.max(r,s.y+s.width/2));return n===1/0||i===-1/0||o===1/0||r===-1/0?{width:0,height:0}:{width:i-n,height:r-o}}},Yh=class extends xe{constructor(){super(...arguments);P(this,"pcb_plated_hole_id",null);P(this,"matchedPort",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:xz}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.outerDiameter,height:t.outerDiameter};if(t.shape==="oval"||t.shape==="pill")return{width:t.outerWidth,height:t.outerHeight};if(t.shape==="circular_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};if(t.shape==="pill_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_plated_hole.get(this.pcb_plated_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y+i.height/2,right:n.x+i.width/2,bottom:n.y-i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,r=this.getSubcircuit();if(n.shape==="circle"){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:n.outerDiameter,hole_diameter:n.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="pill"&&n.rectPad){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:n.pcbRotation??0,rect_ccw_rotation:n.pcbRotation??0,rect_pad_width:n.outerWidth,rect_pad_height:n.outerHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill"||n.shape==="oval"){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:n.shape,port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:n.pcbRotation??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="circular_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:n.holeDiameter,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,rect_border_radius:n.rectBorderRadius??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:n.holeWidth,hole_height:n.holeHeight,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},Rx=class extends xe{constructor(){super(...arguments);P(this,"pcb_keepout_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:eD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let t=this.getSubcircuit(),{db:n}=this.root,{_parsedProps:i}=this,o=this._getGlobalPcbPositionBeforeLayout(),r=Ar(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(r.rotation.angle*(180/Math.PI)-90)%180<.01,a=null;i.shape==="circle"?a=n.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:o.x,y:o.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0}):i.shape==="rect"&&(a=n.pcb_keepout.insert({layers:["top"],shape:"rect",...s?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:o.x,y:o.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0})),a&&(this.pcb_keepout_id=a.pcb_keepout_id)}},Xh=class extends xe{constructor(){super(...arguments);P(this,"pcb_hole_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:kz}}getPcbSize(){let{_parsedProps:t}=this,n=t.shape==="pill",i=t.shape==="rect";return n?{width:t.width,height:t.height}:i?{width:t.width,height:t.height}:{width:t.diameter,height:t.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),o=this._getGlobalPcbPositionBeforeLayout();if(n.shape==="pill")if(n.pcbRotation&&n.pcbRotation!==0){let r=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"rotated_pill",hole_width:n.width,hole_height:n.height,x:o.x,y:o.y,ccw_rotation:n.pcbRotation,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=r.pcb_hole_id}else{let r=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"pill",hole_width:n.width,hole_height:n.height,x:o.x,y:o.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=r.pcb_hole_id}else if(n.shape==="rect"){let r=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"rect",hole_width:n.width,hole_height:n.height,x:o.x,y:o.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=r.pcb_hole_id}else{let r=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"circle",hole_diameter:n.diameter,x:o.x,y:o.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=r.pcb_hole_id}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_hole.get(this.pcb_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_hole.update(this.pcb_hole_id,{x:t.x,y:t.y})}},Dx=class extends xe{constructor(){super(...arguments);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:_D}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),o=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:r,isFlipped:s}=this._getPcbPrimitiveFlippedHelpers(),a=this.getSubcircuit(),c=0;if(n.pcbRotation!==void 0&&n.pcbRotation!==0)c=n.pcbRotation;else{let d=this._computePcbGlobalTransformBeforeLayout();c=Ar(d).rotation.angle*180/Math.PI}s&&(c=(c+180)%360);let l=new Set(n.layers);n.layer&&l.add(n.layer);let u=l.size>0?Array.from(l):["top"],h=n.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1;for(let d of u)t.pcb_silkscreen_text.insert({anchor_alignment:n.anchorAlignment,anchor_position:{x:o.x,y:o.y},font:n.font??"tscircuit2024",font_size:h,layer:r(d),text:n.text??"",ccw_rotation:c,pcb_component_id:i.pcb_component_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:t}=this,n=t.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1,o=(t.text??"").length*n,r=n;return{width:o*n,height:r*n}}},Rm=class extends xe{constructor(){super(...arguments);P(this,"pcb_cutout_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:Ez}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),o=this.getGroup()?.pcb_group_id??void 0,r=this._getGlobalPcbPositionBeforeLayout(),a=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,c;if(n.shape==="rect"){let l=typeof a=="string"?parseInt(a.replace("deg",""),10):a,u=Math.abs(l%180)===90,h={shape:"rect",center:r,width:u?n.height:n.width,height:u?n.width:n.height,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:o};c=t.pcb_cutout.insert(h)}else if(n.shape==="circle"){let l={shape:"circle",center:r,radius:n.radius,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:o};c=t.pcb_cutout.insert(l)}else if(n.shape==="polygon"){let l=this._computePcbGlobalTransformBeforeLayout(),h={shape:"polygon",points:n.points.map(d=>Ne(l,d)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:o};c=t.pcb_cutout.insert(h)}c&&(this.pcb_cutout_id=c.pcb_cutout_id)}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return{width:0,height:0};let n=1/0,i=-1/0,o=1/0,r=-1/0;for(let s of t.points)n=Math.min(n,s.x),i=Math.max(i,s.x),o=Math.min(o,s.y),r=Math.max(r,s.y);return{width:i-n,height:r-o}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_cutout.get(this.pcb_cutout_id);if(!n)return super._getPcbCircuitJsonBounds();if(n.shape==="rect")return{center:n.center,bounds:{left:n.center.x-n.width/2,top:n.center.y+n.height/2,right:n.center.x+n.width/2,bottom:n.center.y-n.height/2},width:n.width,height:n.height};if(n.shape==="circle")return{center:n.center,bounds:{left:n.center.x-n.radius,top:n.center.y+n.radius,right:n.center.x+n.radius,bottom:n.center.y-n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){if(n.points.length===0)return super._getPcbCircuitJsonBounds();let i=1/0,o=-1/0,r=1/0,s=-1/0;for(let a of n.points)i=Math.min(i,a.x),o=Math.max(o,a.x),r=Math.min(r,a.y),s=Math.max(s,a.y);return{center:{x:(i+o)/2,y:(r+s)/2},bounds:{left:i,top:s,right:o,bottom:r},width:o-i,height:s-r}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(t){if(!this.pcb_cutout_id)return;let{db:n}=this.root,i=n.pcb_cutout.get(this.pcb_cutout_id);if(i){if(i.shape==="rect"||i.shape==="circle")n.pcb_cutout.update(this.pcb_cutout_id,{...i,center:t});else if(i.shape==="polygon"){let o=this._getPcbCircuitJsonBounds().center,r=t.x-o.x,s=t.y-o.y,a=i.points.map(c=>({x:c.x+r,y:c.y+s}));n.pcb_cutout.update(this.pcb_cutout_id,{...i,points:a})}}}},A5t=({elm:e,pinLabels:t,layer:n,readableRotation:i,anchorAlignment:o})=>{let r=e.text.replace(/[{}]/g,"").toLowerCase(),s=r;if(Array.isArray(t)){let a=parseInt(r.replace(/[^\d]/g,""),10)-1;s=String(t[a]??r)}else typeof t=="object"&&(s=String(t[r]??r));return new Dx({anchorAlignment:o||"center",text:s??r,layer:n||"top",fontSize:e.font_size+.2,pcbX:isNaN(e.anchor_position.x)?0:e.anchor_position.x,pcbY:e.anchor_position.y,pcbRotation:i??0})},R5t=(e,t)=>{let n=parseInt(e||"0",10),i;return t!=null?i=t-n:i=n,(i%360+360)%360},Vh=({componentName:e,componentRotation:t,footprinterString:n,pinLabels:i,pcbPinLabels:o},r)=>{let s=[];for(let a of r)if(a.type==="pcb_smtpad"&&a.shape==="rect")s.push(new Am({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"rect",height:a.height,width:a.width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius}));else if(a.type==="pcb_smtpad"&&a.shape==="circle")s.push(new Am({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"circle",radius:a.radius,portHints:a.port_hints}));else if(a.type==="pcb_smtpad"&&a.shape==="pill")s.push(new Am({shape:"pill",height:a.height,width:a.width,radius:a.radius,portHints:a.port_hints,pcbX:a.x,pcbY:a.y,layer:a.layer}));else if(a.type==="pcb_silkscreen_path")s.push(new D4({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?s.push(new Yh({pcbX:a.x,pcbY:a.y,shape:"circle",holeDiameter:a.hole_diameter,outerDiameter:a.outer_diameter,portHints:a.port_hints})):a.shape==="circular_hole_with_rect_pad"?s.push(new Yh({pcbX:a.x,pcbY:a.y,shape:"circular_hole_with_rect_pad",holeDiameter:a.hole_diameter,rectPadHeight:a.rect_pad_height,rectPadWidth:a.rect_pad_width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y})):a.shape==="pill"||a.shape==="oval"?s.push(new Yh({pcbX:a.x,pcbY:a.y,shape:a.shape,holeWidth:a.hole_width,holeHeight:a.hole_height,outerWidth:a.outer_width,outerHeight:a.outer_height,portHints:a.port_hints})):a.shape==="pill_hole_with_rect_pad"&&s.push(new Yh({pcbX:a.x,pcbY:a.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:a.hole_width,holeHeight:a.hole_height,rectPadWidth:a.rect_pad_width,rectPadHeight:a.rect_pad_height,portHints:a.port_hints,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y}));else if(a.type==="pcb_keepout"&&a.shape==="circle")s.push(new Rx({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius}));else if(a.type==="pcb_keepout"&&a.shape==="rect")s.push(new Rx({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height}));else if(a.type==="pcb_hole"&&a.hole_shape==="circle")s.push(new Xh({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_hole"&&a.hole_shape==="rect")s.push(new Xh({pcbX:a.x,pcbY:a.y,shape:"rect",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="pill")s.push(new Xh({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="rotated_pill")s.push(new Xh({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height,pcbRotation:a.ccw_rotation}));else if(a.type==="pcb_cutout")a.shape==="rect"?s.push(new Rm({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?s.push(new Rm({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&s.push(new Rm({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=R5t(t,a.ccw_rotation);n?.includes("pinrow")&&a.text.includes("PIN")?s.push(A5t({elm:a,pinLabels:o??i??{},layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):s.push(new Dx({anchorAlignment:a.anchor_alignment||"center",text:e,fontSize:a.font_size+.2,pcbX:Number.isNaN(a.anchor_position.x)?0:a.anchor_position.x,pcbY:a.anchor_position.y,pcbRotation:c??0}))}else a.type==="pcb_trace"&&s.push(new $4({route:a.route}));return s};function $x(e){let t=1/0,n=1/0,i=-1/0,o=-1/0,r=!1;for(let c of e)if(c.isPcbPrimitive&&!c.componentName.startsWith("Silkscreen")){let{x:l,y:u}=c._getGlobalPcbPositionBeforeLayout(),{width:h,height:d}=c.getPcbSize();t=Math.min(t,l-h/2),n=Math.min(n,u-d/2),i=Math.max(i,l+h/2),o=Math.max(o,u+d/2),r=!0}else if(c.children.length>0){let l=$x(c.children);(l.width>0||l.height>0)&&(t=Math.min(t,l.minX),n=Math.min(n,l.minY),i=Math.max(i,l.maxX),o=Math.max(o,l.maxY),r=!0)}if(!r)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let s=i-t,a=o-n;return s<0&&(s=0),a<0&&(a=0),{minX:t,minY:n,maxX:i,maxY:o,width:s,height:a}}function QV(e){let t=e%360;return t<0?t+360:t}function O5t(e,t,n,i){return i==="counterclockwise"?n>=t?e>=t&&e<=n:e>=t||e<=n:n<=t?e<=t&&e>=n:e<=t||e>=n}function L5t(e){let t=e.center,n=e.radius,i=e.start_angle_degrees,o=e.end_angle_degrees,r=e.direction??"counterclockwise";if(!t||typeof t.x!="number"||typeof t.y!="number"||typeof n!="number"||typeof i!="number"||typeof o!="number")return null;let s=QV(i),a=QV(o),c=new Set([s,a]),l=[0,90,180,270];for(let y of l)O5t(y,s,a,r)&&c.add(y);let u=1/0,h=1/0,d=-1/0,_=-1/0;for(let y of c){let g=y*Math.PI/180,x=t.x+n*Math.cos(g),w=t.y+n*Math.sin(g);u=Math.min(u,x),d=Math.max(d,x),h=Math.min(h,w),_=Math.max(_,w)}return!Number.isFinite(u)||!Number.isFinite(h)?null:{minX:u,maxX:d,minY:h,maxY:_}}function NH(e){let t=1/0,n=1/0,i=-1/0,o=-1/0;for(let r of e){let s,a,c,l;if(r.type==="schematic_component")s=r.center?.x,a=r.center?.y,c=r.size?.width,l=r.size?.height;else if(r.type==="schematic_box")s=r.x,a=r.y,c=r.width,l=r.height;else if(r.type==="schematic_port")s=r.center?.x,a=r.center?.y,c=.2,l=.2;else if(r.type==="schematic_text")s=r.position?.x,a=r.position?.y,c=(r.text?.length??0)*.1,l=.2;else if(r.type==="schematic_line"){let u=r.x1??0,h=r.y1??0,d=r.x2??0,_=r.y2??0;s=(u+d)/2,a=(h+_)/2,c=Math.abs(d-u),l=Math.abs(_-h)}else if(r.type==="schematic_rect")s=r.center?.x,a=r.center?.y,c=r.width,l=r.height;else if(r.type==="schematic_circle"){s=r.center?.x,a=r.center?.y;let u=r.radius;typeof u=="number"&&(c=u*2,l=u*2)}else if(r.type==="schematic_arc"){let u=L5t(r);u&&(t=Math.min(t,u.minX),i=Math.max(i,u.maxX),n=Math.min(n,u.minY),o=Math.max(o,u.maxY));continue}typeof s=="number"&&typeof a=="number"&&typeof c=="number"&&typeof l=="number"&&(t=Math.min(t,s-c/2),i=Math.max(i,s+c/2),n=Math.min(n,a-l/2),o=Math.max(o,a+l/2))}return{minX:t,maxX:i,minY:n,maxY:o}}function F5t(e,t){let n=t.x-e.x,i=t.y-e.y;return Math.abs(n)>Math.abs(i)?n>=0?"right":"left":i>=0?"up":"down"}var tH=e=>{if(e.length<=1)return!0;let t=e.map(r=>{let s=r._getPcbCircuitJsonBounds();return{left:s.bounds.left,right:s.bounds.right,top:s.bounds.top,bottom:s.bounds.bottom}}),n=Array(t.length).fill(!1).map(()=>Array(t.length).fill(!1));for(let r=0;r<t.length;r++)for(let s=r+1;s<t.length;s++){let a=t[r],c=t[s];n[r][s]=n[s][r]=!(a.right<c.left||a.left>c.right||a.bottom>c.top||a.top<c.bottom)}let i=new Set,o=r=>{i.add(r);for(let s=0;s<t.length;s++)n[r][s]&&!i.has(s)&&o(s)};return o(0),i.size===t.length},eH=e=>{if(e.length===0)throw new Error("Cannot get center of empty PCB primitives array");let t=e.map(o=>o._getPcbCircuitJsonBounds().center).filter(Boolean),n=t.reduce((o,r)=>o+r.x,0),i=t.reduce((o,r)=>o+r.y,0);return{x:n/t.length,y:i/t.length}},z5t=p.object({name:p.string().optional(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),layer:p.string().optional(),layers:p.array(p.string()).optional(),schX:p.number().optional(),schY:p.number().optional(),direction:p.enum(["up","down","left","right"]).optional(),connectsTo:p.union([p.string(),p.array(p.string())]).optional()}),Ni=class extends xe{constructor(t,n={}){if(!t.name&&t.pinNumber!==void 0&&(t.name=`pin${t.pinNumber}`),!t.name)throw new Error("Port must have a name or a pinNumber");super(t);P(this,"source_port_id",null);P(this,"pcb_port_id",null);P(this,"schematic_port_id",null);P(this,"schematicSymbolPortDef",null);P(this,"matchedComponents");P(this,"facingDirection",null);P(this,"originDescription",null);n.originDescription&&(this.originDescription=n.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:z5t}}isGroupPort(){return this.parent?.componentName==="Group"}isComponentPort(){return!this.isGroupPort()}_getConnectedPortsFromConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo;if(!n)return[];let i=[],o=Array.isArray(n)?n:[n];for(let r of o){let s=this.getSubcircuit().selectOne(r,{type:"port"});s&&i.push(s)}return i}_isBoardPinoutFromAttributes(){let t=this.parent;if(t?._parsedProps?.pinAttributes){let n=t._parsedProps.pinAttributes;for(let i of this.getNameAndAliases())if(n[i]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let t=this.matchedComponents.find(i=>i.isPcbPrimitive),n=this.parent;if(n&&!n.props.footprint)throw new Error(`${n.componentName} "${n.props.name}" does not have a footprint. Add a footprint prop, e.g. <${n.componentName.toLowerCase()} footprint="..." />`);if(!t)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return t?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_port.get(this.pcb_port_id);return{center:{x:n.x,y:n.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let t=this.parent;if(!t||!t._getInternallyConnectedPins)return[];let n=t._getInternallyConnectedPins();for(let i of n)if(i.some(o=>o===this))return i;return[]}_hasSchematicPort(){let{schX:t,schY:n}=this._parsedProps;if(t!==void 0&&n!==void 0)return!0;let i=this.getParentNormalComponent();if(i?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(a=>a.schematicSymbolPortDef));let r=i?._getSchematicBoxDimensions();return!!(r&&this.props.pinNumber!==void 0&&r.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let{schX:t,schY:n}=this._parsedProps;if(t!==void 0&&n!==void 0)return{x:t,y:n};let i=this.getParentNormalComponent(),o=i?.getSchematicSymbol();if(o){let s=this.schematicSymbolPortDef;if(!s&&(s=this._getPortsInternallyConnectedToThisPort().find(c=>c.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!s))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let a=Qn(i.computeSchematicGlobalTransform(),vn(-o.center.x,-o.center.y));return Ne(a,s)}let r=i?._getSchematicBoxDimensions();if(r&&this.props.pinNumber!==void 0){let s=r.getPortPositionByPinNumber(this.props.pinNumber);if(!s)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return Ne(i.computeSchematicGlobalTransform(),s)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:t}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let n=t.schematic_port.get(this.schematic_port_id);if(!n)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return n.center}registerMatch(t){this.matchedComponents.push(t)}getNameAndAliases(){let{_parsedProps:t}=this;return Array.from(new Set([...t.name?[t.name]:[],...t.aliases??[],...typeof t.pinNumber=="number"?[`pin${t.pinNumber}`,t.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let t=this.parent?._parsedProps?.pinAttributes;if(!t)return[];let n=[];for(let i of this.getNameAndAliases()){let o=t[i];o&&n.push(o)}return n}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(t=>t.includeInBoardPinout===!0)}isMatchingPort(t){return this.isMatchingAnyOf(t.getNameAndAliases())}getPortSelector(){return`.${(this.getParentNormalComponent()??this.parent)?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:t,layers:n}=this._parsedProps;return n||(t?[t]:Array.from(new Set(this.matchedComponents.flatMap(i=>i.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(i=>!i._couldNotFindPort).filter(i=>i._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getNameAndAliases(),o=this.getParentNormalComponent(),s=(this.parent?.source_component_id?this.parent:o)?.source_component_id??null,a=t.source_port.insert({name:n.name,pin_number:n.pinNumber,port_hints:i,source_component_id:s,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=a.source_port_id}doInitialSourceParentAttachment(){let{db:t}=this.root,n=this.getParentNormalComponent(),i=this.parent?.source_component_id?this.parent:n;if(this.isGroupPort()){t.source_port.update(this.source_port_id,{source_component_id:null,subcircuit_id:this.getSubcircuit()?.subcircuit_id});return}if(!i?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);t.source_port.update(this.source_port_id,{source_component_id:i.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=i.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{matchedComponents:n}=this;if(this.isGroupPort()){let a=this._getConnectedPortsFromConnectsTo();if(a.length===0)return;let c=a[0];if(!c.pcb_port_id)return;let l=t.pcb_port.get(c.pcb_port_id),u={x:l.x,y:l.y},h=this.getSubcircuit(),d=t.pcb_port.insert({pcb_component_id:void 0,layers:c.getAvailablePcbLayers(),subcircuit_id:h?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...u,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=d.pcb_port_id;return}let i=this.getParentNormalComponent(),o=this.parent?.pcb_component_id?this.parent:i;if(!o?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()}, parentNormalComponent: ${i?.getString()})`);let r=n.filter(a=>a.isPcbPrimitive);if(r.length===0)return;let s=null;if(r.length===1&&(s=r[0]._getPcbCircuitJsonBounds().center),r.length>1){if(!tH(r))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${r.map(a=>a.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);s=eH(r)}if(s){let a=this.getSubcircuit(),c=this._shouldIncludeInBoardPinout(),l=t.pcb_port.insert({pcb_component_id:o.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...c?{is_board_pinout:!0}:{},...s,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=l.pcb_port_id}else{let a=r[0];throw new Error(`${a.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;if(this.pcb_port_id)return;if(this.isGroupPort()){let l=this._getConnectedPortsFromConnectsTo();if(l.length===0)return;let u=l[0];if(!u.pcb_port_id)return;let h=t.pcb_port.get(u.pcb_port_id),d={x:h.x,y:h.y},_=this.getSubcircuit(),y=t.pcb_port.insert({pcb_component_id:void 0,layers:u.getAvailablePcbLayers(),subcircuit_id:_?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...d,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=y.pcb_port_id;return}let n=this.matchedComponents.filter(l=>l.isPcbPrimitive);if(n.length===0)return;let i=null;if(n.length===1&&(i=n[0]._getPcbCircuitJsonBounds().center),n.length>1)try{tH(n)&&(i=eH(n))}catch{}if(!i)return;let o=this.getParentNormalComponent(),r=this.parent?.pcb_component_id?this.parent:o,s=this.getSubcircuit(),a=this._shouldIncludeInBoardPinout(),c=t.pcb_port.insert({pcb_component_id:r?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...a?{is_board_pinout:!0}:{},...i,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=c.pcb_port_id}_getBestDisplayPinLabel(){let{db:t}=this.root,n=t.source_port.get(this.source_port_id),i=[];for(let s of n?.port_hints??[])s.match(/^(pin)?\d+$/)||s.match(/^(left|right)/)&&!n?.name.match(/^(left|right)/)||i.push(s);if(this.getParentNormalComponent()?.props?.showPinAliases&&i.length>0)return i.join("/");if(i.length>0)return i[0]}doInitialSchematicPortRender(){let{db:t}=this.root,{_parsedProps:n}=this,{schX:i,schY:o}=n,r=i!==void 0&&o!==void 0?this.getParentNormalComponent():this.getPrimitiveContainer();if(!r||!this._hasSchematicPort())return;let s=r._getGlobalSchematicPositionBeforeLayout(),a=this._getGlobalSchematicPositionBeforeLayout(),c=null,l=r._getSchematicBoxDimensions();l&&n.pinNumber!==void 0&&(c=l.getPortPositionByPinNumber(n.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&t.schematic_debug_object.insert({shape:"rect",center:a,size:{width:.1,height:.1},label:"obstacle"}),c?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[c.side]:this.facingDirection=F5t(s,a);let u=this._getBestDisplayPinLabel(),d={type:"schematic_port",schematic_component_id:this.getParentNormalComponent()?.schematic_component_id,center:a,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:c?.side,pin_number:n.pinNumber,true_ccw_index:c?.trueIndex,display_pin_label:u,is_connected:!1};for(let y of this._getMatchingPinAttributes())y.requiresPower&&(d.has_input_arrow=!0),y.providesPower&&(d.has_output_arrow=!0);let _=t.schematic_port.insert(d);this.schematic_port_id=_.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_port_id&&n.pcb_port.update(this.pcb_port_id,{x:t.x,y:t.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(t=>t.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},kH=e=>{let t=e.find(n=>/^(pin)?\d+$/.test(n));return t?Number.parseInt(t.replace(/^pin/,"")):null};function Cm(e,t){let n=kH(e);if(!n)return null;let o=[...e.filter(r=>r.toString()!==n.toString()&&r!==`pin${n}`),...t?.additionalAliases?.[`pin${n}`]??[]];return new Ni({pinNumber:n,aliases:o})}var D5t=e=>{for(let t of["leftSide","rightSide","topSide","bottomSide"])if(t in e&&typeof e[t]=="number")throw new Error(`A number was specified for "${t}", you probably meant to use "size" not "side"`);return"leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e},$5t=e=>{if(D5t(e))return{leftSize:e.leftSide?.pins.length??0,rightSize:e.rightSide?.pins.length??0,topSize:e.topSide?.pins.length??0,bottomSize:e.bottomSide?.pins.length??0};let{leftSize:t=0,rightSize:n=0,topSize:i=0,bottomSize:o=0}=e;return{leftSize:t,rightSize:n,topSize:i,bottomSize:o}},Mx=.4;function AH(e){let t=e;return t.leftSide!==void 0||t.rightSide!==void 0||t.topSide!==void 0||t.bottomSide!==void 0}var j5t=e=>{let t=e.portDistanceFromEdge??.4,n=e.schPortArrangement?$5t(e.schPortArrangement):null,i={left:0,right:0,top:0,bottom:0},o=e.pinCount??null;if(o===null)if(n)o=n.leftSize+n.rightSize+n.topSize;else throw new Error("Could not determine pin count for the schematic box");if(o&&!n){let y=Math.floor(o/2);n={leftSize:o-y,rightSize:y,topSize:0,bottomSize:0}}n||(n={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let r=({side:y,sideIndex:g,truePinIndex:x})=>{if(!e.schPortArrangement||!AH(e.schPortArrangement))return x+1;let w={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[y],S=e.schPortArrangement?.[`${y}Side`]?.direction??w,T=e.schPortArrangement?.[`${y}Side`]?.pins,I=g;return S!==w&&(I=T.length-g-1),Om(T[I],e.pinLabels)},s=[],a=0,c=0;for(let y=0;y<n.leftSize;y++){let g=r({side:"left",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.topMargin&&(a+=x.topMargin),s.push({trueIndex:c,pinNumber:g,side:"left",distanceFromOrthogonalEdge:a}),x?.bottomMargin&&(a+=x.bottomMargin),y===n.leftSize-1?i.left=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.bottomSize;y++){let g=r({side:"bottom",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.leftMargin&&(a+=x.leftMargin),s.push({trueIndex:c,pinNumber:g,side:"bottom",distanceFromOrthogonalEdge:a}),x?.rightMargin&&(a+=x.rightMargin),y===n.bottomSize-1?i.bottom=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.rightSize;y++){let g=r({side:"right",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.bottomMargin&&(a+=x.bottomMargin),s.push({trueIndex:c,pinNumber:g,side:"right",distanceFromOrthogonalEdge:a}),x?.topMargin&&(a+=x.topMargin),y===n.rightSize-1?i.right=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.topSize;y++){let g=r({side:"top",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.rightMargin&&(a+=x.rightMargin),s.push({trueIndex:c,pinNumber:g,side:"top",distanceFromOrthogonalEdge:a}),x?.leftMargin&&(a+=x.leftMargin),y===n.topSize-1?i.top=a:a+=e.schPinSpacing,c++}let l=e.schWidth;if(l===void 0){l=Math.max(i.top+Mx,i.bottom+Mx),e.pinLabels&&s.filter(S=>S.side==="left"||S.side==="right").some(S=>e.pinLabels?.[`pin${S.pinNumber}`]||e.pinLabels?.[S.pinNumber])&&(l=Math.max(l,.5));let y=e.pinLabels?Math.max(...Object.values(e.pinLabels).map(x=>x.length*.1)):0,g=y>0?1.1:0;l=Math.max(l,y+g)}let u=e.schHeight;u||(u=Math.max(i.left+Mx,i.right+Mx));let h={left:{x:-l/2-t,y:i.left/2},bottom:{x:-i.bottom/2,y:-u/2-t},right:{x:l/2+t,y:-i.right/2},top:{x:i.top/2,y:u/2+t}},d={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},_=s.map(y=>{let{distanceFromOrthogonalEdge:g,side:x}=y,w=h[x],S=d[x];return{x:w.x+g*S.x,y:w.y+g*S.y,...y}});return{getPortPositionByPinNumber(y){let g=_.find(x=>x.pinNumber.toString()===y.toString());return g||null},getSize(){return{width:l,height:u}},getSizeIncludingPins(){return{width:l+(n.leftSize||n.rightSize?.4:0),height:u+(n.topSize||n.bottomSize?.4:0)}},pinCount:o}},B5t=(0,RH.default)("tscircuit:core:footprint"),OH=class extends xe{get config(){return{componentName:"Footprint",zodProps:Rz}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let e=this.children.filter(h=>h.componentName==="Constraint");if(e.length===0)return;let{isFlipped:t}=this._getPcbPrimitiveFlippedHelpers(),n=h=>t&&"left"in h&&"right"in h?{...h,left:h.right,right:h.left}:h,i=e.flatMap(h=>h._getAllReferencedComponents().componentsWithSelectors).map(({component:h,selector:d,componentSelector:_,edge:y})=>({component:h,selector:d,componentSelector:_,edge:y,bounds:h._getPcbCircuitJsonBounds()}));if(i.some(h=>h.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function o(h){return i.find(({selector:d})=>d===h)}let r=new Qp,s={};function a(h){return h in s||(s[h]=new Us(h),r.addEditVariable(s[h],wn.weak)),s[h]}for(let{selector:h,bounds:d}of i){let _=a(`${h}_x`),y=a(`${h}_y`);r.suggestValue(_,d.center.x),r.suggestValue(y,d.center.y)}for(let h of e){let d=h._parsedProps;if("xDist"in d){let{xDist:_,left:y,right:g,edgeToEdge:x,centerToCenter:w}=n(d),S=a(`${y}_x`),T=a(`${g}_x`),I=o(y)?.bounds,E=o(g)?.bounds;if(w){let M=new Cn(T,[-1,S]);r.addConstraint(new ci(M,Vn.Eq,d.xDist,wn.required))}else if(x){let M=new Cn(T,-E.width/2,[-1,S],-I.width/2);r.addConstraint(new ci(M,Vn.Eq,d.xDist,wn.required))}}else if("yDist"in d){let{yDist:_,top:y,bottom:g,edgeToEdge:x,centerToCenter:w}=d,S=a(`${y}_y`),T=a(`${g}_y`),I=o(y)?.bounds,E=o(g)?.bounds;if(w){let M=new Cn(S,[-1,T]);r.addConstraint(new ci(M,Vn.Eq,d.yDist,wn.required))}else if(x){let M=new Cn(S,I.height/2,[-1,T],-E.height/2);r.addConstraint(new ci(M,Vn.Eq,d.yDist,wn.required))}}else if("sameY"in d){let{for:_}=d;if(_.length<2)continue;let y=_.map(x=>a(`${x}_y`)),g=new Cn(...y.slice(1));r.addConstraint(new ci(g,Vn.Eq,y[0],wn.required))}else if("sameX"in d){let{for:_}=d;if(_.length<2)continue;let y=_.map(x=>a(`${x}_x`)),g=new Cn(...y.slice(1));r.addConstraint(new ci(g,Vn.Eq,y[0],wn.required))}}r.updateVariables(),B5t.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(s).map(([h,d])=>({var:h,val:d.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:h,bounds:{width:d,height:_}}of i){let y=a(`${h}_x`),g=a(`${h}_y`),x=y.value()-d/2,w=y.value()+d/2,S=g.value()+_/2,T=g.value()-_/2;c.left=Math.min(c.left,x),c.right=Math.max(c.right,w),c.top=Math.max(c.top,S),c.bottom=Math.min(c.bottom,T)}let l={x:-(c.right+c.left)/2,y:-(c.top+c.bottom)/2},u=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();l.x+=u.x,l.y+=u.y;for(let{component:h,selector:d}of i){let _=a(`${d}_x`),y=a(`${d}_y`);h._setPositionFromLayout({x:_.value()+l.x,y:y.value()+l.y})}}},LH=e=>{if(!e)return null;let n=e.split("?")[0].split("#")[0],i=n.split("/").pop()??n;return i.includes(".")?i.split(".").pop()?.toLowerCase()??null:null},Y5t=(e,t)=>{let n=e.replace(/\/+$/,""),i=t.replace(/^\/+/,"");return`${n}/${i}`},FH=(e,t)=>{if(!t||!e.startsWith("/"))return e;try{let n=new URL(t);return n.pathname!=="/"&&e.startsWith(n.pathname)?new URL(e,n.origin).toString():Y5t(t,e)}catch{return e}},v4=p.union([p.number(),p.string()]),nH=p.object({x:v4,y:v4,z:v4}),zH=class extends xe{get config(){return{componentName:"CadModel",zodProps:oD}}doInitialCadModelRender(){let e=this._findParentWithPcbComponent();if(!e||!e.pcb_component_id)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=e._getPcbCircuitJsonBounds(),o=t.pcb_component.get(e.pcb_component_id),r=this._parsedProps;if(!r||typeof r.modelUrl!="string"&&typeof r.stepUrl!="string")return;let s=e._computePcbGlobalTransformBeforeLayout(),c=Ar(s).rotation.angle*180/Math.PI,l=nH.parse({x:0,y:0,z:0});if(typeof r.rotationOffset=="number")l.z=Number(r.rotationOffset);else if(typeof r.rotationOffset=="object"){let x=nH.parse(r.rotationOffset);l.x=Number(x.x),l.y=Number(x.y),l.z=Number(x.z)}let u=Zg.parse({x:r.pcbX??0,y:r.pcbY??0,z:r.pcbZ??0,...typeof r.positionOffset=="object"?r.positionOffset:{}}),h=r.zOffsetFromSurface!==void 0?Y.parse(r.zOffsetFromSurface):0,d=e.props.layer==="bottom"?"bottom":"top",_=r.modelUrl?LH(r.modelUrl):void 0,y={};if(_==="stl"?y.model_stl_url=this._addCachebustToModelUrl(r.modelUrl):_==="obj"?y.model_obj_url=this._addCachebustToModelUrl(r.modelUrl):_==="gltf"?y.model_gltf_url=this._addCachebustToModelUrl(r.modelUrl):_==="glb"?y.model_glb_url=this._addCachebustToModelUrl(r.modelUrl):_==="step"||_==="stp"?y.model_step_url=this._addCachebustToModelUrl(r.modelUrl):_==="wrl"||_==="vrml"?y.model_wrl_url=this._addCachebustToModelUrl(r.modelUrl):y.model_stl_url=this._addCachebustToModelUrl(r.modelUrl),r.stepUrl){let x=this._addCachebustToModelUrl(r.stepUrl);x&&(y.model_step_url=x)}let g=t.cad_component.insert({position:{x:i.center.x+Number(u.x),y:i.center.y+Number(u.y),z:(d==="bottom"?-n/2:n/2)+(d==="bottom"?-h:h)+Number(u.z)},rotation:{x:Number(l.x),y:(d==="top"?0:180)+Number(l.y),z:d==="bottom"?-(c+Number(l.z))+180:c+Number(l.z)},pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,model_unit_to_mm_scale_factor:typeof r.modelUnitToMmScale=="number"?r.modelUnitToMmScale:void 0,...y});this.cad_component_id=g.cad_component_id}_findParentWithPcbComponent(){let e=this.parent;for(;e&&!e.pcb_component_id;)e=e.parent;return e}_addCachebustToModelUrl(e){if(!e)return e;let t=this.root?.platform?.projectBaseUrl,n=FH(e,t);if(!n.includes("modelcdn.tscircuit.com"))return n;let i=this.root?.getClientOrigin()??"";return`${n}${n.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(i)}`}},DH=class extends xe{constructor(){super(...arguments);P(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:iD}}},X5t=(e,t)=>{if(!e)return;let n={};for(let[i,o]of Object.entries(e)){let r=Om(i,t),s={leftMargin:o.marginLeft??o.leftMargin,rightMargin:o.marginRight??o.rightMargin,topMargin:o.marginTop??o.topMargin,bottomMargin:o.marginBottom??o.bottomMargin};n[`pin${r}`]={...n[`pin${r}`],...s}}return n},iH=class{constructor({input:e}){P(this,"input");this.input=e}solveAndMapToTraces(){let e=[];for(let t of this.input.connections){if(t.pointsToConnect.length!==2)continue;let[n,i]=t.pointsToConnect,o={type:"pcb_trace",pcb_trace_id:"",connection_name:t.name,route:[{route_type:"wire",x:n.x,y:n.y,layer:"top",width:.1},{route_type:"wire",x:i.x,y:i.y,layer:"top",width:.1}]};e.push(o)}return e}},V5t=e=>{let t=Math.min(...e.map(r=>r.center.x)),n=Math.max(...e.map(r=>r.center.x)),i=Math.min(...e.map(r=>r.center.y)),o=Math.max(...e.map(r=>r.center.y));return{minX:t,maxX:n,minY:i,maxY:o}},oH=["top","bottom","inner1","inner2"],kx=(e,t=[])=>{let n=[];if(t.length===0){let a=e[0].layers;for(let c of a)n.push(...kx(e.slice(1),[c]));return n}if(e.length===0)return[];let i=e[0],o=i.via||i.optional_via,r=t[t.length-1];if(e.length===1){let a=i;return a.layers&&o?a.layers.map(c=>({layer_path:[...t,c]})):a.layers?.includes(r)?[{layer_path:[...t,r]}]:[]}if(!o)return i.layers&&!i.layers.includes(r)?[]:kx(e.slice(1),t.concat([r]));let s=(i.optional_via?oH:oH.filter(a=>a!==r)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of s)n.push(...kx(e.slice(1),t.concat(a)));return n};function rH(e){let t={x:e.to.x-e.from.x,y:e.to.y-e.from.y},n=Math.abs(t.x),i=Math.abs(t.y);return n>i?t.x>0?"right":"left":t.y>0?"down":"up"}function zh(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}var H5t=e=>{if(e.length===1)return e[0];if(e.some(c=>c.length===0))throw new Error("Cannot merge routes with zero length");let t=[],n=e[0][0],i=e[0][e[0].length-1],o=e[1][0],r=e[1][e[1].length-1],s=Math.min(zh(n,o),zh(n,r)),a=Math.min(zh(i,o),zh(i,r));s<a?t.push(...e[0].reverse()):t.push(...e[0]);for(let c=1;c<e.length;c++){let l=t[t.length-1],u=e[c],h=u[0],d=u[u.length-1],_=zh(l,h),y=zh(l,d);_<y?t.push(...u):t.push(...u.reverse())}for(let c=1;c<t.length-1;c++){let l=t[c-1],u=t[c];l.route_type==="wire"&&u.route_type==="wire"&&l.layer!==u.layer&&t.splice(c,0,{x:l.x,y:l.y,from_layer:l.layer,to_layer:u.layer,route_type:"via"})}return t},G5t=(e,t)=>{let n="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e,i="_getGlobalPcbPositionBeforeLayout"in t?t._getGlobalPcbPositionBeforeLayout():t;return Math.sqrt((n.x-i.x)**2+(n.y-i.y)**2)};function U5t(e,t){if(t.length===0)throw new Error("No candidates given to getClosest method");let n=t[0],i=1/0;for(let o of t){let r=G5t(e,o);r<i&&(n=o,i=r)}return n}var q5t=(e,t)=>{let n=0;n+=e.length??0,n+=t.filter(i=>i.is_crossing).length;for(let i=1;i<t.length;i++){let o=t[i-1],r=t[i],s=Math.abs(o.from.x-o.to.x)<.01,a=Math.abs(r.from.x-r.to.x)<.01;s!==a&&n++}return n},Lm=e=>({up:"bottom",down:"top",left:"right",right:"left"})[e]??null,M4=({firstEdge:e,firstEdgePort:t,firstDominantDirection:n,lastEdge:i,lastEdgePort:o,lastDominantDirection:r})=>{if(e&&t)return M4({lastEdge:{from:e.to,to:e.from},lastEdgePort:t,lastDominantDirection:n}).reverse().map(a=>({from:a.to,to:a.from}));let s=[];if(i&&o){let a={x:i.to.x,y:i.to.y};r==="left"||r==="right"?(a.x=o.position.x,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...o.position}})):(a.y=o.position.y,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...o.position}}))}return s=s.filter(a=>vi(a.from,a.to)>.01),s};function W5t(e){try{return[e(),null]}catch(t){return[null,t]}}var Z5t=(e,{db:t})=>{let n=e.map(i=>{let o=t.source_port.get(i.source_port_id);if(!o?.source_component_id)return null;let r=t.source_component.get(o.source_component_id);return r?.ftype==="simple_capacitor"?r.max_decoupling_trace_length:null}).filter(i=>i!==null);if(n.length!==0)return Math.min(...n)};function K5t({ports:e,nets:t}){if(e.length>=2)return`${e[0]?.selector} to ${e[1]?.selector}`;if(e.length===1&&t.length===1)return`${e[0]?.selector} to net.${t[0]._parsedProps.name}`}var J5t=(e,{db:t})=>{let n=t.pcb_board.list()[0];if(n.outline){let c=n.outline,l=(u,h)=>{let d=!1;for(let _=0,y=h.length-1;_<h.length;y=_++){let g=h[_].x,x=h[_].y,w=h[y].x,S=h[y].y;x>u.y!=S>u.y&&u.x<(w-g)*(u.y-x)/(S-x)+g&&(d=!d)}return d};return e.some(u=>!l(u,c))}let i=n.width,o=n.height,r=n.center.x,s=n.center.y;return e.some(c=>c.x<r-i/2||c.y<s-o/2||c.x>r+i/2||c.y>s+o/2)},sH=(e,t)=>Math.abs(e-t)<1e-4,Q5t=(e,t,{viaDiameter:n=.5}={})=>{let i=[];for(let o=0;o<e.length-1;o++){let[r,s]=[e[o],e[o+1]],a=o-1>=0?e[o-1]:null,c=sH(r.y,s.y),l=sH(r.x,s.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${t}, start: (${r.x}, ${r.y}), end: (${s.x}, ${s.y})`);let u={type:"rect",layers:[r.layer],center:{x:(r.x+s.x)/2,y:(r.y+s.y)/2},width:c?Math.abs(r.x-s.x):.1,height:l?Math.abs(r.y-s.y):.1,connectedTo:[t]};if(i.push(u),a&&a.layer===r.layer&&r.layer!==s.layer){let h={type:"rect",layers:[r.layer,s.layer],center:{x:r.x,y:r.y},connectedTo:[t],width:n,height:n};i.push(h)}}return i};function tIt(e,t=4){let{center:n,width:i,height:o,rotation:r}=e,s=[],a=r*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(r%360+360)%360;if(o<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*c,x=-y*l,w=d*1.1,S=Math.abs(o*c)+Math.abs(d*l);s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}else{let d=o/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*l,x=y*c,w=Math.abs(i*c)+Math.abs(d*l),S=d*1.1;s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}return s}function eIt(e,t={}){if(e.length<3)return[];let{rectHeight:n=.1}=t,i=[],o=e.map(a=>a.y),r=Math.min(...o),s=Math.max(...o);for(let a=r;a<s;a+=n){let c=a+n/2,l=[];for(let u=0;u<e.length;u++){let h=e[u],d=e[(u+1)%e.length];if(h.y<=c&&d.y>c||d.y<=c&&h.y>c){let _=(c-h.y)*(d.x-h.x)/(d.y-h.y)+h.x;l.push(_)}}l.sort((u,h)=>u-h);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let h=l[u],_=l[u+1]-h;_>1e-6&&i.push({center:{x:h+_/2,y:c},width:_,height:n})}}return i}function nIt(e,t={}){let{center:n,radius:i}=e,{rectHeight:o=.1}=t,r=[],s=Math.ceil(i*2/o);for(let a=0;a<s;a++){let c=n.y-i+(a+.5)*o,l=c-n.y,u=Math.sqrt(i*i-l*l);u>0&&r.push({center:{x:n.x,y:c},width:u*2,height:o})}return r}var ra=["top","inner1","inner2","bottom"],$H=(e,t)=>{let n=o=>t?o.concat(o.map(r=>t?.getNetConnectedToId(r)).filter(Boolean)):o,i=[];for(let o of e)if(o.type==="pcb_smtpad"){if(o.shape==="circle")i.push({type:"oval",layers:[o.layer],center:{x:o.x,y:o.y},width:o.radius*2,height:o.radius*2,connectedTo:n([o.pcb_smtpad_id])});else if(o.shape==="rect")i.push({type:"rect",layers:[o.layer],center:{x:o.x,y:o.y},width:o.width,height:o.height,connectedTo:n([o.pcb_smtpad_id])});else if(o.shape==="rotated_rect"){let r={center:{x:o.x,y:o.y},width:o.width,height:o.height,rotation:o.ccw_rotation},s=tIt(r);for(let a of s)i.push({type:"rect",layers:[o.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([o.pcb_smtpad_id])})}}else if(o.type==="pcb_keepout")o.shape==="circle"?i.push({type:"oval",layers:o.layers,center:{x:o.center.x,y:o.center.y},width:o.radius*2,height:o.radius*2,connectedTo:[]}):o.shape==="rect"&&i.push({type:"rect",layers:o.layers,center:{x:o.center.x,y:o.center.y},width:o.width,height:o.height,connectedTo:[]});else if(o.type==="pcb_cutout"){if(o.shape==="rect")i.push({type:"rect",layers:ra,center:{x:o.center.x,y:o.center.y},width:o.width,height:o.height,connectedTo:[]});else if(o.shape==="circle"){let r=nIt({center:o.center,radius:o.radius},{rectHeight:.6});for(let s of r)i.push({type:"rect",layers:ra,center:s.center,width:s.width,height:s.height,connectedTo:[]})}else if(o.shape==="polygon"){let r=eIt(o.points,{rectHeight:.6});for(let s of r)i.push({type:"rect",layers:ra,center:s.center,width:s.width,height:s.height,connectedTo:[]})}}else if(o.type==="pcb_hole")o.hole_shape==="oval"?i.push({type:"oval",center:{x:o.x,y:o.y},width:o.hole_width,height:o.hole_height,connectedTo:[]}):o.hole_shape==="rect"?i.push({type:"rect",layers:ra,center:{x:o.x,y:o.y},width:o.hole_width,height:o.hole_height,connectedTo:[]}):o.hole_shape==="square"?i.push({type:"rect",layers:ra,center:{x:o.x,y:o.y},width:o.hole_diameter,height:o.hole_diameter,connectedTo:[]}):(o.hole_shape==="round"||o.hole_shape==="circle")&&i.push({type:"rect",layers:ra,center:{x:o.x,y:o.y},width:o.hole_diameter,height:o.hole_diameter,connectedTo:[]});else if(o.type==="pcb_plated_hole")o.shape==="circle"?i.push({type:"oval",layers:ra,center:{x:o.x,y:o.y},width:o.outer_diameter,height:o.outer_diameter,connectedTo:n([o.pcb_plated_hole_id])}):o.shape==="circular_hole_with_rect_pad"?i.push({type:"rect",layers:ra,center:{x:o.x,y:o.y},width:o.rect_pad_width,height:o.rect_pad_height,connectedTo:n([o.pcb_plated_hole_id])}):(o.shape==="oval"||o.shape==="pill")&&i.push({type:"oval",layers:ra,center:{x:o.x,y:o.y},width:o.outer_width,height:o.outer_height,connectedTo:n([o.pcb_plated_hole_id])});else if(o.type==="pcb_trace"){let r=Q5t(o.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),o.source_trace_id);i.push(...r)}else if(o.type==="pcb_via"){let r=!!(o.net_is_assignable??o.netIsAssignable);i.push({type:"rect",layers:o.layers,center:{x:o.x,y:o.y},connectedTo:[],width:o.outer_diameter,height:o.outer_diameter,netIsAssignable:r||void 0})}return i},Ic=({anchor_position:e,anchor_side:t,text:n,font_size:i=.18})=>{let o=.1*(i/.18),r=n.length*o,s=i,a={...e};switch(t){case"right":a.x-=r/2;break;case"left":a.x+=r/2;break;case"top":a.y-=s/2;break;case"bottom":a.y+=s/2;break}return a},j4=({db:e,source_trace_id:t,sameNetOnly:n,differentNetOnly:i})=>{!n&&!i&&(i=!0);let o=e.source_trace.get(t),r=[];for(let s of e.schematic_trace.list()){if(s.source_trace_id===t)continue;let c=e.source_trace.get(s.source_trace_id)?.subcircuit_connectivity_map_key===o.subcircuit_connectivity_map_key;i&&c||n&&!c||r.push(s)}return r},iIt=({edges:e,otherEdges:t})=>{let n=[...e];for(let i=0;i<n.length;i++){if(i>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let o=n[i],r=Math.abs(o.from.x-o.to.x)<.01?"vertical":o.from.y===o.to.y?"horizontal":"not-orthogonal";if(r==="not-orthogonal")continue;let s=[];for(let g of t){let x=g.from.x===g.to.x?"vertical":g.from.y===g.to.y?"horizontal":"not-orthogonal";if(x==="not-orthogonal"||r===x)continue;if(qs([o.from,o.to],[g.from,g.to],{lineThickness:.01})){let S=r==="vertical"?o.from.x:g.from.x,T=r==="vertical"?g.from.y:o.from.y,I={x:S,y:T};s.push({otherEdge:g,crossingPoint:I,distanceFromEdgeFrom:vi(o.from,I)})}}if(s.length===0)continue;let a=s[0];for(let g of s)g.distanceFromEdgeFrom<a.distanceFromEdgeFrom&&(a=g);let c=a.crossingPoint,l=.075;if(c.x===o.from.x&&c.y===o.from.y)continue;let u=sb(o.from,c),h={x:c.x-u.x*l/2,y:c.y-u.y*l/2},d={x:c.x+u.x*l/2,y:c.y+u.y*l/2},_=vi(d,o.to)<l,y=[{from:o.from,to:h},{from:h,to:d,is_crossing:!0},{from:d,to:o.to}];n.splice(i,1,...y),i+=y.length-2,_&&i++}return n},C4=.001,Dh=(e,t)=>{let n=Math.min(t.from.x,t.to.x),i=Math.max(t.from.x,t.to.x),o=Math.min(t.from.y,t.to.y),r=Math.max(t.from.y,t.to.y);return e.x>=n&&e.x<=i&&e.y>=o&&e.y<=r},aH=e=>{let t=Math.abs(e.from.x-e.to.x)<C4,n=Math.abs(e.from.y-e.to.y)<C4;return t?"vertical":n?"horizontal":"diagonal"},oIt=(e,t)=>{let n=aH(e),i=aH(t);if(n===i)return null;if(n==="vertical"&&i==="horizontal"||n==="horizontal"&&i==="vertical"){let h=n==="vertical"?e:t,d=n==="horizontal"?e:t,_=h.from.x,y=d.from.y,g={x:_,y};return Dh(g,e)&&Dh(g,t)?g:null}if(n==="vertical"||i==="vertical"){let h=n==="vertical"?e:t,d=n==="vertical"?t:e,_=h.from.x,y=(d.to.y-d.from.y)/(d.to.x-d.from.x),g=d.from.y-y*d.from.x,x=y*_+g,w={x:_,y:x};return Dh(w,e)&&Dh(w,t)?w:null}let o=(e.to.y-e.from.y)/(e.to.x-e.from.x),r=e.from.y-o*e.from.x,s=(t.to.y-t.from.y)/(t.to.x-t.from.x),a=t.from.y-s*t.from.x;if(Math.abs(o-s)<C4)return null;let c=(a-r)/(o-s),l=o*c+r,u={x:c,y:l};return Dh(u,e)&&Dh(u,t)?u:null},rIt=({edges:e,db:t,source_trace_id:n})=>{let i=j4({db:t,source_trace_id:n,sameNetOnly:!0}).flatMap(r=>r.edges),o=new Map;for(let r of e)for(let s of i){let a=oIt(r,s);if(a){let c=`${a.x.toFixed(6)},${a.y.toFixed(6)}`;o.has(c)||o.set(c,a)}}return Array.from(o.values())};function sIt(e,t={}){let{minX:n,maxX:i,minY:o,maxY:r}=e,s=t.padding??1;if(!isFinite(n)||!isFinite(i)||!isFinite(o)||!isFinite(r))return[];let a=n-s,c=i+s,l=r+s,u=o-s,h=.01;return[{type:"rect",layers:["top"],center:{x:(a+c)/2,y:l},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+c)/2,y:u},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(l+u)/2},width:h,height:l-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:c,y:(l+u)/2},width:h,height:l-u,connectedTo:[]}]}var aIt=e=>{let t=e.root.db,n=e._findConnectedPorts().ports??[],i=new Set(n.map(s=>s.schematic_port_id)),o=[];for(let s of t.toArray()){if(s.type==="schematic_component"){let a=!!s.symbol_name,c=s.size.width>s.size.height?"horz":"vert";o.push({type:"rect",layers:["top"],center:s.center,width:s.size.width+(a&&c==="horz"?-.5:0),height:s.size.height+(a&&c==="vert"?-.5:0),connectedTo:[]})}if(s.type==="schematic_port"){if(i.has(s.schematic_port_id))continue;let a=s.facing_direction?ab(s.facing_direction):{x:0,y:0};o.push({type:"rect",layers:["top"],center:{x:s.center.x-a.x*.1,y:s.center.y-a.y*.1},width:.1+Math.abs(a.x)*.3,height:.1+Math.abs(a.y)*.3,connectedTo:[]})}s.type==="schematic_text"&&o.push({type:"rect",layers:["top"],center:s.position,width:(s.text?.length??0)*.1,height:.2,connectedTo:[]}),s.type==="schematic_box"&&o.push({type:"rect",layers:["top"],center:{x:s.x,y:s.y},width:s.width,height:s.height,connectedTo:[]})}let r=NH(t.toArray());return o.push(...sIt(r,{padding:1})),o},cIt=({edges:e,db:t,source_trace_id:n})=>{let i=t.source_trace.get(n),o=j4({db:t,source_trace_id:n,differentNetOnly:!0}).flatMap(s=>s.edges),r=s=>{let{from:a,to:c}=s;return a.x===c.x?"vertical":"horizontal"};for(let s of e){let a=r(s),c=()=>o.find(u=>r(u)===a&&qs([s.from,s.to],[u.from,u.to],{lineThickness:.05})),l=c();for(;l;)a==="horizontal"?(s.from.y+=.1,s.to.y+=.1):(s.from.x+=.1,s.to.x+=.1),l=c()}},E4=e=>{switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},lIt=VD.version??"unknown",Em=class extends Error{constructor(e){super(`${e} (capacity-autorouter@${lIt})`),this.name="AutorouterError"}},Ox=class extends Error{constructor(e){super(e.message),this.errorData=e,this.name="TraceConnectionError"}},uIt=e=>{if(e.root?._featureMspSchematicTraceRouting||e._couldNotFindPort||e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let o,r;try{let X=e._findConnectedPorts();o=X.allPortsFound,r=X.portsWithSelectors??[]}catch(X){if(X instanceof Ox){t.source_trace_not_connected_error.insert({...X.errorData,error_type:"source_trace_not_connected_error"});return}throw X}let{netsWithSelectors:s}=e._findConnectedNets();if(!o)return;let c=r.map(X=>X.port.schematic_port_id).sort().join(","),l=e.root?._getBoard();if(l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.has(c))return;let u={name:e.source_trace_id,pointsToConnect:[]},h=aIt(e),d=r.filter(({port:X})=>X.schematic_port_id!==null).map(({port:X})=>({port:X,position:X._getGlobalSchematicPositionAfterLayout(),schematic_port_id:X.schematic_port_id??void 0,facingDirection:X.facingDirection}));if(d.length===1&&s.length===1){let X=s[0].net,{port:G,position:tt}=d[0],Q=e.getSubcircuit().selectAll("netlabel").find(et=>{let J=et._parsedProps.connection??et._parsedProps.connectsTo;return J?Array.isArray(J)?J.some(ht=>e.getSubcircuit().selectOne(ht,{port:!0})===G):e.getSubcircuit().selectOne(J,{port:!0})===G:!1});if(!Q){let et=t.schematic_net_label.getWhere({source_trace_id:e.source_trace_id});et&&(Q=et)}if(Q){let et="_getGlobalSchematicPositionBeforeLayout"in Q?Q._getGlobalSchematicPositionBeforeLayout():Q.anchor_position,J=[];tt.x===et.x||tt.y===et.y?J.push({from:tt,to:et}):(J.push({from:tt,to:{x:et.x,y:tt.y}}),J.push({from:{x:et.x,y:tt.y},to:et}));let pt=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:J,junctions:[],subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=pt.schematic_trace_id;return}if(e.props.schDisplayLabel){let et=Lm(G.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel,source_net_id:X.source_net_id,anchor_position:tt,center:Ic({anchor_position:tt,anchor_side:et,text:e.props.schDisplayLabel}),anchor_side:et});return}let V=Lm(G.facingDirection)??"bottom",rt=t.schematic_net_label.insert({text:X._parsedProps.name,source_net_id:X.source_net_id,anchor_position:tt,center:Ic({anchor_position:tt,anchor_side:V,text:X._parsedProps.name}),anchor_side:V});return}if(e.props.schDisplayLabel&&("from"in e.props&&"to"in e.props||"path"in e.props)){e._doInitialSchematicTraceRenderWithDisplayLabel();return}if(d.length<2)return;let g=(()=>{let X=[];for(let tt=0;tt<d.length-1;tt++){let Q=d[tt],V=d[tt+1],rt=oc({x:Q.position.x,y:Q.position.y,facingDirection:E4(Q.facingDirection)},{x:V.position.x,y:V.position.y,facingDirection:E4(V.facingDirection)});for(let et=0;et<rt.length-1;et++)X.push({from:rt[et],to:rt[et+1]})}let G=(tt,Q)=>{let V=Q.width/2,rt=Q.height/2,et=Q.center.x-V,J=Q.center.x+V,pt=Q.center.y-rt,ht=Q.center.y+rt,St=lt=>lt.x>=et&<.x<=J&<.y>=pt&<.y<=ht;return St(tt.from)||St(tt.to)?!0:[[{x:et,y:pt},{x:J,y:pt}],[{x:J,y:pt},{x:J,y:ht}],[{x:J,y:ht},{x:et,y:ht}],[{x:et,y:ht},{x:et,y:pt}]].some(lt=>qs([tt.from,tt.to],lt,{lineThickness:0}))};for(let tt of X)for(let Q of h)if(G(tt,Q))return null;return X})();g&&g.length===0&&(g=null),u.pointsToConnect=d.map(({position:X})=>({...X,layer:"top"}));let x=V5t(h),w=2,S={minTraceWidth:.1,obstacles:h,connections:[u],bounds:{minX:x.minX-w,maxX:x.maxX+w,minY:x.minY-w,maxY:x.maxY+w},layerCount:1},T=Ug,I=!1;if(e.getSubcircuit().props._schDirectLineRoutingEnabled&&(T=iH,I=!0),!g){let G=new T({input:S,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(G.length===0){if(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection()){e._doInitialSchematicTraceRenderWithDisplayLabel();return}G=new iH({input:S}).solveAndMapToTraces(),I=!0}let[{route:tt}]=G;g=[];for(let Q=0;Q<tt.length-1;Q++)g.push({from:tt[Q],to:tt[Q+1]})}let E=e.source_trace_id,M=[];if(!I){cIt({edges:g,db:t,source_trace_id:E});let X=j4({db:t,source_trace_id:E,differentNetOnly:!0}).flatMap(G=>G.edges);g=iIt({edges:g,otherEdges:X}),M=rIt({edges:g,db:t,source_trace_id:e.source_trace_id})}if(!g||g.length===0)return;let k=g[g.length-1],N=d[d.length-1],A=rH(k);g.push(...M4({lastEdge:k,lastEdgePort:N,lastDominantDirection:A}));let R=g[0],$=d[0],j=rH(R);if(g.unshift(...M4({firstEdge:R,firstEdgePort:$,firstDominantDirection:j})),!e.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(e.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&q5t(M,g)>=5&&(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection())){e._doInitialSchematicTraceRenderWithDisplayLabel();return}let H=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:g,junctions:M,subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=H.schematic_trace_id;for(let{port:X}of r)X.schematic_port_id&&t.schematic_port.update(X.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function jH(e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];if(i.route_type==="wire"){let o=e[n+1];if(o){let r=o.x-i.x,s=o.y-i.y;t+=Math.sqrt(r*r+s*s)}}else i.route_type==="via"&&(t+=1.6)}return t}var Cx=e=>({...e._getGlobalPcbPositionAfterLayout(),layers:e.getAvailablePcbLayers()}),pIt=!1;function hIt(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e,o=e.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(o._parsedProps.routingDisabled)return;let r=o._parsedProps.pcbRouteCache?.pcbTraces;if(r){let A=t.pcb_trace.insert({route:r.flatMap(R=>R.route),source_trace_id:e.source_trace_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});e.pcb_trace_id=A.pcb_trace_id;return}if(n.pcbPath&&n.pcbPath.length>0||!o._shouldUseTraceByTraceRouting())return;let{allPortsFound:s,ports:a}=e._findConnectedPorts(),c=[];if(!s)return;let l=[];for(let A of a)A._hasMatchedPcbPrimitive()||l.push(A);if(l.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${l.map(A=>A.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(A=>A.pcb_port_id).filter(Boolean)});return}let u=e._findConnectedNets().netsWithSelectors;if(a.length===0&&u.length===2){e.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(a.length===1&&u.length===1){let A=a[0],$=u[0].net.getAllConnectedPorts().filter(H=>H!==A);if($.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let j=U5t(A,$);c.push(j),a.push(j)}else if(a.length>1&&u.length>=1){e.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let h=a.flatMap(A=>A.matchedComponents.filter(R=>R.componentName==="TraceHint")),d=(e._parsedProps.pcbRouteHints??[]).concat(h.flatMap(A=>A.getPcbRouteHints()));if(a.length>2){e.renderError(`Trace has more than two ports (${a.map(A=>A.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(e.getSubcircuit().selectAll("trace").filter(A=>A.renderPhaseStates.PcbTraceRender.initialized).some(A=>A._portsRoutedOnPcb.length===a.length&&A._portsRoutedOnPcb.every(R=>a.includes(R))))return;let g=[];d.length===0?g=[Cx(a[0]),Cx(a[1])]:g=[Cx(a[0]),...d,Cx(a[1])];let x=kx(g);if(pIt&&x.length===0){e.renderError(`Could not find a common layer (using hints) for trace ${e.getString()}`);return}let w=$i(e.root.db.toArray()),[S,T]=W5t(()=>$H(e.root.db.toArray()));if(T){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Error getting obstacles for autorouting: ${T.message}`,source_trace_id:e.source_trace_id,center:{x:0,y:0},pcb_port_ids:a.map(A=>A.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[]});return}for(let A of S)if(A.connectedTo.length>0){let $=w.getNetConnectedToId(A.connectedTo[0]);$&&A.connectedTo.push($)}let I=[];if(x.length===0)I=g;else{let A=x[0].layer_path;I=g.map((R,$)=>R.via?{...R,via_to_layer:A[$]}:{...R,layers:[A[$]]})}I[0].pcb_port_id=a[0].pcb_port_id,I[I.length-1].pcb_port_id=a[1].pcb_port_id;let E=[];for(let[A,R]of EH(I)){let $="via_to_layer"in A?A.via_to_layer:null,j=2,H="layers"in A&&A.layers.length===1?A.layers[0]:$??"top",X="layers"in R&&R.layers.length===1?R.layers[0]:$??"top",G="pcb_port_id"in A?A.pcb_port_id:null,tt="pcb_port_id"in R?R.pcb_port_id:null,Q=e._getExplicitTraceThickness()??e.getSubcircuit()._parsedProps.minTraceWidth??.16,V=new Ug({OBSTACLE_MARGIN:Q*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(G&&tt),connMap:w,input:{obstacles:S,minTraceWidth:Q,connections:[{name:e.source_trace_id,pointsToConnect:[{...A,layer:H,pcb_port_id:G},{...R,layer:X,pcb_port_id:tt}]}],layerCount:e.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(A.x,R.x)-j,maxX:Math.max(A.x,R.x)+j,minY:Math.min(A.y,R.y)-j,maxY:Math.max(A.y,R.y)+j}}}),rt=null;try{rt=V.solveAndMapToTraces()}catch(pt){e.renderError({type:"pcb_trace_error",pcb_trace_error_id:e.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${pt.message}`,source_trace_id:e.pcb_trace_id,center:{x:(A.x+R.x)/2,y:(A.y+R.y)/2},pcb_port_ids:a.map(ht=>ht.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(ht=>ht.pcb_component_id)})}if(!rt)return;if(rt.length===0){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Could not find a route for ${e}`,source_trace_id:e.source_trace_id,center:{x:(A.x+R.x)/2,y:(A.y+R.y)/2},pcb_port_ids:a.map(pt=>pt.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(pt=>pt.pcb_component_id)});return}let[et]=rt;$&&(et.route=et.route.map(pt=>(pt.route_type==="wire"&&!pt.layer&&(pt.layer=$),pt))),G&&et.route[0].route_type==="wire"&&(et.route[0].start_pcb_port_id=G);let J=et.route[et.route.length-1];tt&&J.route_type==="wire"&&(J.end_pcb_port_id=tt),E.push(et.route)}let M=H5t(E),k=jH(M),N=t.pcb_trace.insert({route:M,source_trace_id:e.source_trace_id,subcircuit_id:e.getSubcircuit()?.subcircuit_id,trace_length:k});e._portsRoutedOnPcb=a,e.pcb_trace_id=N.pcb_trace_id;for(let A of M)A.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:N.pcb_trace_id,x:A.x,y:A.y,hole_diameter:.3,outer_diameter:.6,layers:[A.from_layer,A.to_layer],from_layer:A.from_layer,to_layer:A.to_layer});e._insertErrorIfTraceIsOutsideBoard(M,a)}function dIt(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n}=e,i=e.getSubcircuit();if(!n.pcbPath)return;let{allPortsFound:o,ports:r,portsWithSelectors:s}=e._findConnectedPorts();if(!o)return;let a=[];for(let S of r)S._hasMatchedPcbPrimitive()||a.push(S);if(a.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${a.map(S=>S.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:a.map(S=>S.pcb_port_id).filter(Boolean)});return}let c;n.pcbPathRelativeTo&&(c=s.find(S=>S.selector===n.pcbPathRelativeTo)?.port,c||(c=e.getSubcircuit().selectOne(n.pcbPathRelativeTo))),c||(c=r[0]);let l=r.find(S=>S!==c)??r[1],u=c.getAvailablePcbLayers()[0]||"top",h=e._getExplicitTraceThickness()??e.getSubcircuit()._parsedProps.minTraceWidth??.16,d=c._getGlobalPcbPositionAfterLayout(),_=l._getGlobalPcbPositionAfterLayout(),y=[];y.push({route_type:"wire",x:d.x,y:d.y,width:h,layer:u,start_pcb_port_id:c.pcb_port_id});let g=c?._computePcbGlobalTransformBeforeLayout?.()||zi();for(let S of n.pcbPath){let T,I=!1;if(typeof S=="string"){let M=e.getSubcircuit().selectOne(S,{type:"port"});if(!M){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Could not resolve pcbPath selector "${S}" for ${e}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:[]});continue}let k=M._getGlobalPcbPositionAfterLayout();T={x:k.x,y:k.y},I=!0}else T={x:S.x,y:S.y},I=!1;let E=I?T:Ne(g,T);y.push({route_type:"wire",x:E.x,y:E.y,width:h,layer:u})}y.push({route_type:"wire",x:_.x,y:_.y,width:h,layer:u,end_pcb_port_id:l.pcb_port_id});let x=jH(y),w=t.pcb_trace.insert({route:y,source_trace_id:e.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,trace_length:x});e._portsRoutedOnPcb=r,e.pcb_trace_id=w.pcb_trace_id,e._insertErrorIfTraceIsOutsideBoard(y,r)}function fIt(e){if(e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let{allPortsFound:o,portsWithSelectors:r}=e._findConnectedPorts();if(!o)return;let s=r.map(({port:I})=>({port:I,position:I._getGlobalSchematicPositionAfterLayout(),schematic_port_id:I.schematic_port_id,facingDirection:I.facingDirection}));if(s.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let a,c,l=s[0].position,u=s[0].port;if("path"in e.props){if(e.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[a,c]=e.props.path}else{if(!("from"in e.props&&"to"in e.props))throw new Error("Missing 'from' or 'to' properties in props.");a=e.props.from,c=e.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${a}).`);let h=s[1].position,d=s[1].port;if(!d.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);let _=t.schematic_net_label.list().find(I=>I.source_net_id===u.source_port_id),y=t.schematic_net_label.list().find(I=>I.source_net_id===d.source_port_id),[g,x]=r.map(({port:I})=>I),S=g.parent?.config.shouldRenderAsSchematicBox?`${g?.parent?.props.name}_${g?.props.name}`:`${x?.parent?.props.name}_${x?.props.name}`,T=e.props.schDisplayLabel??S;if(_&&_.text!==T&&(_.text=`${T} / ${_.text}`),y&&y?.text!==T&&(y.text=`${T} / ${y.text}`),!y){let I=Lm(d.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:d.source_port_id,anchor_position:h,center:Ic({anchor_position:h,anchor_side:I,text:e.props.schDisplayLabel??S}),anchor_side:I})}if(!_){let I=Lm(u.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:u.source_port_id,anchor_position:l,center:Ic({anchor_position:l,anchor_side:I,text:e.props.schDisplayLabel??S}),anchor_side:I})}}function mIt(e){let{_parsedProps:t,parent:n}=e;if(!n)throw new Error("Trace has no parent");let o=e.getTracePortPathSelectors().map(r=>({selector:r,port:e.getSubcircuit().selectOne(r,{type:"port"})??null}));for(let{selector:r,port:s}of o)if(!s){let a,c,l=r.lastIndexOf(".");if(l!==-1&&l>r.lastIndexOf(" "))a=r.slice(0,l),c=r.slice(l+1);else{let I=r.match(/^(.*[ >])?([^ >]+)$/);a=I?.[1]?.trim()??"",c=I?.[2]??r}let u=a?e.getSubcircuit().selectOne(a):null;if(!u&&a&&!/[.#\[]/.test(a)&&(u=e.getSubcircuit().selectOne(`.${a}`)),!u){let I=a?`Could not find port for selector "${r}". Component "${a}" not found`:`Could not find port for selector "${r}"`,E=e.getSubcircuit(),M=E.getGroup();throw new Ox({error_type:"source_trace_not_connected_error",message:I,subcircuit_id:E.subcircuit_id??void 0,source_group_id:M?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[r]})}let h=u.children.filter(I=>I.componentName==="Port"),d=c.includes(".")?c.split(".").pop()??"":c,_=h.flatMap(I=>I.getNameAndAliases()),y=_.some(I=>!/^(pin\d+|\d+)$/.test(I)),g=Array.from(new Set(_)).join(", "),x;h.length===0?x="It has no ports":y?x=`It has [${g}]`:x=`It has ${h.length} pins and no pinLabels (consider adding pinLabels)`;let w=`Could not find port for selector "${r}". Component "${u.props.name??a}" found, but does not have pin "${d}". ${x}`,S=e.getSubcircuit(),T=S.getGroup();throw new Ox({error_type:"source_trace_not_connected_error",message:w,subcircuit_id:S.subcircuit_id??void 0,source_group_id:T?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[r]})}return o.some(r=>!r.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:o,ports:o.map(({port:r})=>r)}}var $r=class extends xe{constructor(t){super(t);P(this,"source_trace_id",null);P(this,"pcb_trace_id",null);P(this,"schematic_trace_id",null);P(this,"_portsRoutedOnPcb");P(this,"subcircuit_connectivity_map_key",null);P(this,"_traceConnectionHash",null);P(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}_getExplicitTraceThickness(){return this._parsedProps.thickness??this._parsedProps.width}get config(){return{zodProps:Az,componentName:"Trace"}}_getTracePortOrNetSelectorListFromProps(){return"from"in this.props&&"to"in this.props?[typeof this.props.from=="string"?this.props.from:this.props.from.getPortSelector(),typeof this.props.to=="string"?this.props.to:this.props.to.getPortSelector()]:"path"in this.props?this.props.path.map(t=>typeof t=="string"?t:t.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(t=>!t.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(t=>t.includes("net."))}_findConnectedPorts(){return mIt(this)}_resolveNet(t){let n=this.getSubcircuit().selectOne(t,{type:"net"});if(n)return n;let i=t.match(/^net\.(.+)$/),o=i?i[1]:null;if(!o)return null;let r=this.root?._getBoard();return r?r.getDescendants().find(a=>a.componentName==="Net"&&a._parsedProps.name===o)||null:(this.renderError(`Could not find a <board> ancestor for ${this}, so net "${t}" cannot be resolved`),null)}_findConnectedNets(){let t=this.getTracePathNetSelectors().map(i=>({selector:i,net:this._resolveNet(i)})),n=t.filter(i=>!i.net);return n.length>0&&this.renderError(`Could not find net for selector "${n[0].selector}" inside ${this}`),{netsWithSelectors:t,nets:t.map(i=>i.net)}}_getAllTracesConnectedToSameNet(){let t=this.getSubcircuit().selectAll("trace"),n=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return t.filter(o=>{if(o===this)return!1;let r=o._findConnectedNets().nets,s=o._findConnectedPorts().ports??[];return r.some(a=>n.includes(a))||s.some(a=>i.includes(a))})}_isExplicitlyConnectedToPort(t){let{allPortsFound:n,portsWithSelectors:i}=this._findConnectedPorts();return n?i.map(r=>r.port).includes(t):!1}_isExplicitlyConnectedToNet(t){return this._findConnectedNets().nets.includes(t)}doInitialCreateNetsFromProps(){zx(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();return!t||!n?null:[...n].sort((r,s)=>(r.pcb_port_id||"").localeCompare(s.pcb_port_id||"")).map(r=>r.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}let o,r;try{let h=this._findConnectedPorts();o=h.allPortsFound,r=h.portsWithSelectors??[]}catch(h){if(h instanceof Ox){t.source_trace_not_connected_error.insert({...h.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw h}if(!o)return;this._traceConnectionHash=this._computeTraceConnectionHash();let a=t.source_trace.list().find(h=>h.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&h.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(a){this.source_trace_id=a.source_trace_id;return}let c=this._findConnectedNets().nets,l=K5t({ports:r,nets:c}),u=t.source_trace.insert({connected_source_port_ids:r.map(h=>h.port.source_port_id),connected_source_net_ids:c.map(h=>h.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:Z5t(r.map(h=>h.port),{db:t})??n.maxLength,display_name:l,min_trace_thickness:this._getExplicitTraceThickness()});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(t,n){let{db:i}=this.root;J5t(t,{db:i})&&i.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:n.map(r=>r.pcb_port_id)})}doInitialPcbManualTraceRender(){dIt(this)}doInitialPcbTraceRender(){hIt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){fIt(this)}_isSymbolToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,o]=n;if(!i?.parent||!o?.parent)return!1;let r=i.parent.config.shouldRenderAsSchematicBox,s=o.parent.config.shouldRenderAsSchematicBox;return r&&!s||!r&&s}_isSymbolToSymbolConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,o]=n;if(!i?.parent||!o?.parent)return!1;let r=!i.parent.config.shouldRenderAsSchematicBox,s=!o.parent.config.shouldRenderAsSchematicBox;return r&&s}_isChipToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,o]=n;if(!i?.parent||!o?.parent)return!1;let r=i.parent.config.shouldRenderAsSchematicBox,s=o.parent.config.shouldRenderAsSchematicBox;return r&&s}doInitialSchematicTraceRender(){uIt(this)}},_It=e=>{let{db:t}=e.root;if(e.pcb_component_id){let n=t.pcb_component.get(e.pcb_component_id);return n?{width:n.width,height:n.height}:null}if(e.pcb_group_id){let n=t.pcb_group.get(e.pcb_group_id);if(!n)return null;if(n.outline&&n.outline.length>0){let i=ns(n.outline);return i?{width:i.maxX-i.minX,height:i.maxY-i.minY}:null}return{width:n.width??0,height:n.height??0}}return null},yIt=(e,t)=>{let{db:n}=e.root,i=n.toArray();if(e.pcb_component_id){cb(i,e.pcb_component_id,t);return}if(e.source_group_id){lb(i,e.source_group_id,t);return}throw new Error(`Cannot reposition component ${e.getString()}: no pcb_component_id or source_group_id`)},gIt=e=>{let{db:t}=e.root;if(!e.source_component_id)return;let n=e.selectAll("port"),i=t.source_trace.list(),o=new Set;for(let s of i)for(let a of s.connected_source_port_ids)o.add(a);let r=e._getInternallyConnectedPins();for(let s of r)if(s.some(a=>a.source_port_id&&o.has(a.source_port_id)))for(let a of s)a.source_port_id&&o.add(a.source_port_id);for(let s of n)s.source_port_id&&bIt(e,s)&&(o.has(s.source_port_id)||t.source_pin_missing_trace_warning.insert({message:`Port ${s.getNameAndAliases()[0]} on ${e.props.name} is missing a trace`,source_component_id:e.source_component_id,source_port_id:s.source_port_id,subcircuit_id:e.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},bIt=(e,t)=>{if(e.config.componentName==="Chip"){let n=e.props.pinAttributes;if(!n)return!1;for(let i of t.getNameAndAliases()){let o=n[i];if(o?.requiresPower||o?.requiresGround||o?.requiresVoltage!==void 0)return!0}return!1}return!0};function xIt(e){let t=e.font_size,n=e.text.length*t*.6,i=t,o=e.anchor_alignment||"center",r=e.anchor_position.x,s=e.anchor_position.y;switch(o){case"top_left":r=e.anchor_position.x+n/2,s=e.anchor_position.y+i/2;break;case"top_center":r=e.anchor_position.x,s=e.anchor_position.y+i/2;break;case"top_right":r=e.anchor_position.x-n/2,s=e.anchor_position.y+i/2;break;case"center_left":r=e.anchor_position.x+n/2,s=e.anchor_position.y;break;case"center":r=e.anchor_position.x,s=e.anchor_position.y;break;case"center_right":r=e.anchor_position.x-n/2,s=e.anchor_position.y;break;case"bottom_left":r=e.anchor_position.x+n/2,s=e.anchor_position.y-i/2;break;case"bottom_center":r=e.anchor_position.x,s=e.anchor_position.y-i/2;break;case"bottom_right":r=e.anchor_position.x-n/2,s=e.anchor_position.y-i/2;break;default:r=e.anchor_position.x,s=e.anchor_position.y;break}return{x:r-n/2,y:s-i/2,width:n,height:i}}function vIt(e){if(!e._adjustSilkscreenTextAutomatically||e.root?.pcbDisabled||!e.pcb_component_id)return;let{db:t}=e.root,i=e._getPcbCircuitJsonBounds().center,o=t.pcb_silkscreen_text.list({pcb_component_id:e.pcb_component_id}).filter(c=>c.text===e.name);if(o.length===0)return;let a=e.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(c=>c!==e&&c.pcb_component_id).map(c=>{let l=c._getPcbCircuitJsonBounds(),u={center:l.center,width:l.width,height:l.height};return Or(u)});for(let c of o){let l=c.anchor_position,u=xIt(c),h={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},d=Or(h);if(!a.some(T=>ic(d,T)))continue;let y=2*i.x-l.x,g=2*i.y-l.y,x={center:{x:y,y:g},width:u.width,height:u.height},w=Or(x);a.some(T=>ic(w,T))||t.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:y,y:g}})}}function SIt(e){if(!e)return{validPinLabels:e,invalidPinLabelsMessages:[]};let t={},n=[];for(let[i,o]of Object.entries(e)){let r=Array.isArray(o)?o.slice():[o],s=[];for(let a of r)wIt(i,a)?s.push(a):n.push(`Invalid pin label: ${i} = '${a}' - excluding from component. Please use a valid pin label.`);s.length>0&&(t[i]=Array.isArray(o)?s:s[0])}return{validPinLabels:Object.keys(t).length>0?t:void 0,invalidPinLabelsMessages:n}}function wIt(e,t){try{let n={name:"test",footprint:"test",pinLabels:{[e]:t}};return Jp.safeParse(n).success}catch{return!1}}var Hh=e=>e.startsWith("http://")||e.startsWith("https://"),k4=e=>{if(Hh(e))return null;let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t),i=e.slice(t+1);return!n||!i?null:{footprintLib:n,footprintName:i}},A4=e=>e.startsWith("/"),PIt=(0,BH.default)("tscircuit:core:resolveStaticFileImport");async function YH(e,t){if(!e)return e;let n=t?.resolveProjectStaticFileImportUrl;if(n&&e.startsWith("/"))try{let i=await n(e);if(i)return i}catch(i){PIt("failed to resolve static file via platform resolver",i)}return FH(e,t?.projectBaseUrl)}function IIt(e,t){let{footprint:n}=e.props;if(n??(n=e._getImpliedFootprintString?.()),!n)return;let{pcbRotation:i,pinLabels:o,pcbPinLabels:r}=e.props,s=LH(String(n)),a=s?e.root?.platform?.footprintFileParserMap?.[s]:null;if(typeof n=="string"&&(Hh(n)||A4(n))&&a){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0,t("load-footprint-from-platform-file-parser",async()=>{let c=Hh(n)?n:await YH(n,e.root?.platform);try{let l=await a.loadFromUrl(c),u=Vh({componentName:e.name,componentRotation:i,footprinterString:c,pinLabels:o,pcbPinLabels:r},l.footprintCircuitJson);e.addAll(u),e._markDirty("InitializePortsFromChildren")}catch(l){let u=e.root?.db;if(u&&e.source_component_id&&e.pcb_component_id){let h=e.getSubcircuit(),d=`${e.getString()} failed to load footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Ep.parse({type:"external_footprint_load_error",message:d,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:h.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof n=="string"&&Hh(n)){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let c=n;t("load-footprint-url",async()=>{try{let l=await fetch(c);if(!l.ok)throw new Error(`Failed to fetch footprint: ${l.status}`);let u=await l.json(),h=Vh({componentName:e.name,componentRotation:i,footprinterString:c,pinLabels:o,pcbPinLabels:r},u);e.addAll(h),e._markDirty("InitializePortsFromChildren")}catch(l){let u=e.root?.db;if(u&&e.source_component_id&&e.pcb_component_id){let h=e.getSubcircuit(),d=`${e.getString()} failed to load external footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Ep.parse({type:"external_footprint_load_error",message:d,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:h.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof n=="string"){let c=k4(n);if(!c||e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let u=e.root?.platform?.footprintLibraryMap?.[c.footprintLib],h;if(typeof u=="function"&&(h=u),!h)return;let d=e.getInheritedMergedProperty("pcbStyle");t("load-lib-footprint",async()=>{try{let _=await h(c.footprintName,{resolvedPcbStyle:d}),y=null;if(Array.isArray(_)?y=_:Array.isArray(_.footprintCircuitJson)&&(y=_.footprintCircuitJson),!y)return;let g=Vh({componentName:e.name,componentRotation:i,footprinterString:n,pinLabels:o,pcbPinLabels:r},y);e.addAll(g),!Array.isArray(_)&&_.cadModel&&(e._asyncFootprintCadModel=_.cadModel);for(let x of e.children)x.componentName==="Port"&&x._markDirty?.("PcbPortRender");e._markDirty("InitializePortsFromChildren")}catch(_){let y=e.root?.db;if(y&&e.source_component_id&&e.pcb_component_id){let g=e.getSubcircuit(),x=`${e.getString()} failed to load external footprint "${n}": `+(_ instanceof Error?_.message:String(_)),w=Ep.parse({type:"external_footprint_load_error",message:x,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:g.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:n});y.external_footprint_load_error.insert(w)}throw _}});return}if(!(0,N4.isValidElement)(n)&&n.componentName==="Footprint"&&e.add(n),Array.isArray(n)&&!(0,N4.isValidElement)(n)&&n.length>0){try{let c=Vh({componentName:e.name,componentRotation:i,footprinterString:"",pinLabels:o,pcbPinLabels:r},n);e.addAll(c)}catch(c){let l=e.root?.db;if(l&&e.source_component_id&&e.pcb_component_id){let u=e.getSubcircuit(),h=`${e.getString()} failed to load json footprint: `+(c instanceof Error?c.message:String(c)),d=k_.parse({type:"circuit_json_footprint_load_error",message:h,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:u.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});l.circuit_json_footprint_load_error.insert(d)}throw c}return}}function TIt(e){if(e.root?.pcbDisabled||!e.pcb_component_id)return;let{pcbX:t,pcbY:n}=e._parsedProps,i=e.props?.pcbPositionAnchor;if(!i||t===void 0&&n===void 0)return;let o=$x(e.children);if(o.width===0||o.height===0)return;let s={...{x:(o.minX+o.maxX)/2,y:(o.minY+o.maxY)/2}},a=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(i)){let u={left:o.minX,right:o.maxX,top:o.minY,bottom:o.maxY};switch(i){case"center":a=s;break;case"top_left":a={x:u.left,y:u.top};break;case"top_center":a={x:s.x,y:u.top};break;case"top_right":a={x:u.right,y:u.top};break;case"center_left":a={x:u.left,y:s.y};break;case"center_right":a={x:u.right,y:s.y};break;case"bottom_left":a={x:u.left,y:u.bottom};break;case"bottom_center":a={x:s.x,y:u.bottom};break;case"bottom_right":a={x:u.right,y:u.bottom};break}}else try{let u=e.portMap[i];u&&(a=u._getGlobalPcbPositionBeforeLayout())}catch{}if(!a)return;let l={...s};t!==void 0&&(l.x+=t-a.x),n!==void 0&&(l.y+=n-a.y),(Math.abs(l.x-s.x)>1e-6||Math.abs(l.y-s.y)>1e-6)&&e._repositionOnPcb(l)}var MIt=(0,wH.default)("tscircuit:core"),CIt=p.object({x:Be,y:Be,z:Be}),On=class extends xe{constructor(t){let n={...t},i=[];if(n.pinLabels&&!Array.isArray(n.pinLabels)){let{validPinLabels:o,invalidPinLabelsMessages:r}=SIt(n.pinLabels);n.pinLabels=o,i=r}super(n);P(this,"reactSubtrees",[]);P(this,"_impliedFootprint");P(this,"isPrimitiveContainer",!0);P(this,"_isNormalComponent",!0);P(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});P(this,"_asyncSupplierPartNumbers");P(this,"_asyncFootprintCadModel");P(this,"_isCadModelChild");P(this,"pcb_missing_footprint_error_id");P(this,"_hasStartedFootprintUrlLoad",!1);P(this,"_invalidPinLabelMessages",[]);P(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=i,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(n=>n.map(i=>typeof i=="number"?`pin${i}`:i))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let t=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(o=>o!==this&&o._isNormalComponent&&o.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let o=this._getGlobalPcbPositionBeforeLayout(),r=this._getGlobalSchematicPositionBeforeLayout();t.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:o,schematic_center:r}),this.shouldBeRemoved=!0;let s=[...this.children];for(let a of s)this.remove(a)}}initPorts(t={}){if(this.root?.schematicDisabled)return;let{config:n}=this,i=[],o=this._getSchematicPortArrangement();if(o&&!this._parsedProps.pinLabels){for(let l in o){let u=o[l].pins;if(Array.isArray(u))for(let h of u){let d=Om(h,this._parsedProps.pinLabels);i.push(new Ni({pinNumber:d,aliases:t.additionalAliases?.[`pin${d}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let a=["left","right","top","bottom"],c=1;for(let l of a){let u=o[`${l}Size`];for(let h=0;h<u;h++)i.push(new Ni({pinNumber:c++,aliases:t.additionalAliases?.[`pin${c}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let r=this._parsedProps.pinLabels;if(r)for(let[a,c]of Object.entries(r)){a=a.replace("pin","");let l=i.find(d=>d._parsedProps.pinNumber===Number(a)),u=Array.isArray(c)?c[0]:c,h=Array.isArray(c)?c.slice(1):[];l?(l.externallyAddedAliases.push(u,...h),l.props.name=u):(l=new Ni({pinNumber:parseInt(a),name:u,aliases:[...h,...t.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(n.schematicSymbolName&&!t.ignoreSymbolPorts){let a=ti[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=kH(c.labels);if(!l)continue;let u=i.find(h=>h._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let h=Cm(c.labels.concat(t.additionalAliases?.[`pin${l}`]??[]));h&&(h.originDescription=`schematicSymbol:labels[0]:${c.labels[0]}`,h.schematicSymbolPortDef=c,i.push(h))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){let a=this.getPortsFromFootprint(t);for(let c of a)i.some(l=>l.isMatchingAnyOf(c.getNameAndAliases()))||i.push(c)}let s=t.pinCount??this._getPinCount()??0;for(let a=1;a<=s;a++){if(i.find(l=>l._parsedProps.pinNumber===a))continue;if(!o){i.push(new Ni({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...o.leftSide?.pins??[],...o.rightSide?.pins??[],...o.topSide?.pins??[],...o.bottomSide?.pins??[]].map(l=>Om(l,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(l=>l in o)&&(c=Array.from({length:this._getPinCount()},(l,u)=>u+1)),c.includes(a)&&i.push(new Ni({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${a}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:t,pinLabels:n,pcbPinLabels:i}=this.props,{footprint:o}=this.props;if(o??(o=this._getImpliedFootprintString?.()),!!o&&typeof o=="string"){if(Hh(o)||A4(o)||k4(o))return;let r=GS.string(o).soup(),s=Vh({componentName:this.name??this.componentName,componentRotation:t,footprinterString:o,pinLabels:n,pcbPinLabels:i},r);this.addAll(s)}}get portMap(){return new Proxy({},{get:(t,n)=>{let i=this.children.find(o=>o.componentName==="Port"&&o.isMatchingNameOrAlias(n));if(!i)throw new Error(`There was an issue finding the port "${n.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return i}})}getInstanceForReactElement(t){for(let n of this.reactSubtrees)if(n.element===t)return n.component;return null}doInitialSourceRender(){let t=this.config.sourceFtype;if(!t)return;let{db:n}=this.root,{_parsedProps:i}=this,o=n.source_component.insert({ftype:t,name:this.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=o.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let r of this._invalidPinLabelMessages){let s="pinLabels",a=r.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);a&&(s=`pinLabels['${a[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:s,message:r,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:n}=this.config,{_parsedProps:i}=this;i.symbol&&(0,ca.isValidElement)(i.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(i.symbol):n?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let o=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&o){if(!this.schematic_component_id)return;let r=E_.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});t.schematic_manual_edit_conflict_warning.insert(r)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let t=[];for(let n of this.internallyConnectedPinNames){let i=[];for(let o of n)i.push(this.portMap[o]);t.push(i)}return t}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicSymbolNameOrThrow(),o=ti[i],r=this._getGlobalSchematicPositionBeforeLayout();if(o){let s=t.schematic_component.insert({center:r,size:o.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=s.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(t){if(this.root?.schematicDisabled)return;let{db:n}=this.root,i=this._getGlobalSchematicPositionBeforeLayout(),o=n.schematic_component.insert({center:i,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=o.schematic_component_id}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicBoxDimensions(),o={};if(Array.isArray(n.pinLabels))n.pinLabels.forEach((_,y)=>{o[String(y+1)]=_});else for(let[_,y]of Object.entries(n.pinLabels??{}))o[_]=Array.isArray(y)?y[0]:y;let r=this._getGlobalSchematicPositionBeforeLayout(),s=this._getSchematicPortArrangement(),a=t.schematic_component.insert({center:r,rotation:n.schRotation??0,size:i.getSize(),port_arrangement:E5t(s),pin_spacing:n.schPinSpacing??.2,pin_styles:C5t(n.schPinStyle,n.pinLabels),port_labels:o,source_component_id:this.source_component_id}),c=s?.topSide!==void 0||s?.bottomSide!==void 0,l=i?.getSize().width,u=i?.getSize().height,h=t.schematic_text.insert({text:n.manufacturerPartNumber??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?r.x+(l??0)/2+.1:r.x-(l??0)/2,y:c?r.y+(u??0)/2+.35:r.y-(u??0)/2-.13},color:"#006464",font_size:.18}),d=t.schematic_text.insert({text:n.name??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?r.x+(l??0)/2+.1:r.x-(l??0)/2,y:c?r.y+(u??0)/2+.55:r.y+(u??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=a.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),o=n.layer??"top";if(o!=="top"&&o!=="bottom"){let h=Np.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${o}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:o,subcircuit_id:i.subcircuit_id??void 0});t.pcb_component_invalid_layer_error.insert(h)}let r=this._computePcbGlobalTransformBeforeLayout(),a=Ar(r).rotation.angle*180/Math.PI,c=t.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:o==="top"||o==="bottom"?o:"top",rotation:n.pcbRotation??a,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});if(!(n.footprint??this._getImpliedFootprintString())&&!this.isGroup){let h=t.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=h.pcb_missing_footprint_error_id}this.pcb_component_id=c.pcb_component_id;let u=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&u){let h=A_.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0});t.pcb_manual_edit_conflict_warning.insert(h)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:t}=this.root,{_parsedProps:n}=this,i=$x(this.children);if(i.width===0||i.height===0)return;let o={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};t.pcb_component.update(this.pcb_component_id,{center:o,width:i.width,height:i.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db:t}=this.root;if(!t.schematic_component.get(this.schematic_component_id))return;let i=[],o=u=>{for(let h of u){if(h.isSchematicPrimitive&&h.componentName==="SchematicLine"){let d=t.schematic_line.get(h.schematic_line_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicRect"){let d=t.schematic_rect.get(h.schematic_rect_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicCircle"){let d=t.schematic_circle.get(h.schematic_circle_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicArc"){let d=t.schematic_arc.get(h.schematic_arc_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicText"){let d=t.schematic_text.get(h.schematic_text_id);d&&i.push(d)}h.children&&h.children.length>0&&o(h.children)}};if(o(this.children),i.length===0)return;let r=NH(i),s=Math.abs(r.maxX-r.minX),a=Math.abs(r.maxY-r.minY);if(s===0&&a===0)return;let c=(r.minX+r.maxX)/2,l=(r.minY+r.maxY)/2;t.schematic_component.update(this.schematic_component_id,{center:{x:c,y:l},size:{width:s,height:a}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){TIt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(t){let n=CH(t);return{element:t,component:n}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let t=this.props.footprint;(0,ca.isValidElement)(t)&&(this.children.some(r=>r.componentName==="Footprint")||this.add(t));let n=this.props.symbol;(0,ca.isValidElement)(n)&&(this.children.some(r=>r.componentName==="Symbol")||this.add(n));let i=this.props.cadModel;if((0,ca.isValidElement)(i)){this._isCadModelChild=!0;let o=this.children.some(s=>s.componentName==="CadAssembly"),r=this.children.some(s=>s.componentName==="CadModel");!o&&!r&&this.add(i)}}doInitialPcbFootprintStringRender(){IIt(this,(t,n)=>this._queueAsyncEffect(t,n))}_hasExistingPortExactly(t){return this.children.filter(i=>i.componentName==="Port").some(i=>{let o=t.getNameAndAliases(),r=i.getNameAndAliases();return o.length===r.length&&o.every(s=>r.includes(s))})}add(t){let n;if((0,ca.isValidElement)(t)){let i=this._renderReactSubtree(t);this.reactSubtrees.push(i),n=i.component}else n=t;if(n.componentName==="Port"){if(this._hasExistingPortExactly(n))return;let o=this.children.filter(r=>r.componentName==="Port").find(r=>r.isMatchingAnyOf(n.getNameAndAliases()));o&&MIt(`Similar ports added. Port 1: ${o}, Port 2: ${n}`)}super.add(n)}getPortsFromFootprint(t){let{footprint:n}=this.props;if((!n||(0,ca.isValidElement)(n))&&(n=this.children.find(o=>o.componentName==="Footprint")),typeof n=="string"){if(Hh(n))return[];if(A4(n))return[];if(k4(n))return[];let o=GS.string(n).soup(),r=[];for(let s of o)if("port_hints"in s&&s.port_hints){let a=Cm(s.port_hints,t);if(!a)continue;a.originDescription=`footprint:string:${n}:port_hints[0]:${s.port_hints[0]}`,r.push(a)}return r}if(!(0,ca.isValidElement)(n)&&n&&n.componentName==="Footprint"){let o=n,r=1,s=[];for(let a of o.children){if(!a.props.portHints)continue;let c=a.props.portHints;c.some(h=>h.startsWith("pin"))||(c=[...c,`pin${r}`]),r++;let u=Cm(c);u&&(u.originDescription=`footprint:${n}`,s.push(u))}return s}let i=[];if(!n){for(let o of this.children)if(o.props.portHints&&o.isPcbPrimitive){let r=Cm(o.props.portHints);r&&i.push(r)}}return i}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:t}=this;if(!t.schematicSymbolName)return[];let n=ti[t.schematicSymbolName];if(!n)return[];let i=[];for(let o of n.ports){let r=Cm(o.labels);r&&(r.schematicSymbolPortDef=o,i.push(r))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:t}=this,n=[];if(t.connections)for(let[i,o]of Object.entries(t.connections)){let r=Array.isArray(o)?o:[o];for(let s of r)n.push(String(s))}return n}_createNetsFromProps(t){zx(this,t)}_getPcbCircuitJsonBounds(){let{db:t}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let n=t.pcb_component.get(this.pcb_component_id);return{center:{x:n.center.x,y:n.center.y},bounds:{left:n.center.x-n.width/2,top:n.center.y-n.height/2,right:n.center.x+n.width/2,bottom:n.center.y+n.height/2},width:n.width,height:n.height}}_getPinCountFromSchematicPortArrangement(){let t=this._getSchematicPortArrangement();if(!t)return 0;if(!AH(t))return(t.leftSize??t.leftPinCount??0)+(t.rightSize??t.rightPinCount??0)+(t.topSize??t.topPinCount??0)+(t.bottomSize??t.bottomPinCount??0);let{leftSide:i,rightSide:o,topSide:r,bottomSide:s}=t;return Math.max(...i?.pins??[],...o?.pins??[],...r?.pins??[],...s?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let n=this.getPortsFromFootprint();if(n.length>0)return n.length;let{pinLabels:i}=this._parsedProps;if(i){if(Array.isArray(i))return i.length;let o=Object.keys(i).map(r=>r.startsWith("pin")?parseInt(r.slice(3)):parseInt(r)).filter(r=>!Number.isNaN(r));return o.length>0?Math.max(...o):Object.keys(i).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getPinLabelsFromPorts(){let t=this.selectAll("port"),n={};for(let i of t){let o=i.props.pinNumber;if(o!==void 0){let r=i._getBestDisplayPinLabel();r&&(n[`pin${o}`]=r)}}return n}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this,n=this._getPinCount(),i=t.schPinSpacing??.2,r={...this._getPinLabelsFromPorts(),...t.pinLabels};return j5t({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:i,numericSchPinStyle:X5t(t.schPinStyle,r),pinCount:n,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:r})}getFootprinterString(){return typeof this._parsedProps.footprint=="string"?this._parsedProps.footprint:null}doInitialCadModelRender(){if(this._isCadModelChild||this.props.doNotPlace)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=this._parsedProps.cadModel,o=i===void 0?this._asyncFootprintCadModel:i,r=this.getFootprinterString()??this._getImpliedFootprintString();if(!this.pcb_component_id||!o&&!r||o===null)return;let s=this._getPcbCircuitJsonBounds();if(typeof o=="string")throw new Error("String cadModel not yet implemented");let a=CIt.parse({x:0,y:0,z:typeof o?.rotationOffset=="number"?o.rotationOffset:0,...typeof o?.rotationOffset=="object"?o.rotationOffset??{}:{}}),c=vl.parse({x:0,y:0,z:0,...typeof o?.positionOffset=="object"?o.positionOffset:{}}),l=o&&typeof o=="object"&&"zOffsetFromSurface"in o&&o.zOffsetFromSurface!==void 0?Y.parse(o.zOffsetFromSurface):0,u=this.props.layer==="bottom"?"bottom":"top",h=this._computePcbGlobalTransformBeforeLayout(),_=Ar(h).rotation.angle*180/Math.PI,y=u==="bottom",g=_+(a.z??0),x=Vl(g),w=t.cad_component.insert({position:{x:s.center.x+c.x,y:s.center.y+c.y,z:(u==="bottom"?-n/2:n/2)+(u==="bottom"?-l:l)+c.z},rotation:{x:a.x,y:a.y+(y?180:0),z:Vl(y?-x:x)},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(o??{})?this._addCachebustToModelUrl(o.stlUrl):void 0,model_obj_url:"objUrl"in(o??{})?this._addCachebustToModelUrl(o.objUrl):void 0,model_mtl_url:"mtlUrl"in(o??{})?this._addCachebustToModelUrl(o.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(o??{})?this._addCachebustToModelUrl(o.gltfUrl):void 0,model_glb_url:"glbUrl"in(o??{})?this._addCachebustToModelUrl(o.glbUrl):void 0,model_step_url:"stepUrl"in(o??{})?this._addCachebustToModelUrl(o.stepUrl):void 0,model_wrl_url:"wrlUrl"in(o??{})?this._addCachebustToModelUrl(o.wrlUrl):void 0,model_jscad:"jscad"in(o??{})?o.jscad:void 0,model_unit_to_mm_scale_factor:typeof o?.modelUnitToMmScale=="number"?o.modelUnitToMmScale:void 0,footprinter_string:typeof r=="string"&&!o?r:void 0});this.cad_component_id=w.cad_component_id}_addCachebustToModelUrl(t){if(!t||!t.includes("modelcdn.tscircuit.com"))return t;let n=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(n)}`}_getPartsEngineCacheKey(t,n){return JSON.stringify({ftype:t.ftype,name:t.name,manufacturer_part_number:t.manufacturer_part_number,footprinterString:n})}async _getSupplierPartNumbers(t,n,i){if(this.props.doNotPlace)return{};let o=this.root?.platform?.localCacheEngine,r=this._getPartsEngineCacheKey(n,i);if(o){let c=await o.getItem(r);if(c)try{return JSON.parse(c)}catch{}}let s=await Promise.resolve(t.findPart({sourceComponent:n,footprinterString:i}));if(typeof s=="string"){if(s.includes("<!DOCTYPE")||s.includes("<html"))throw new Error(`Failed to fetch supplier part numbers: Received HTML response instead of JSON. Response starts with: ${s.substring(0,100)}`);if(s==="Not found")return{};throw new Error(`Invalid supplier part numbers format: Expected object but got string: "${s}"`)}if(!s||Array.isArray(s)||typeof s!="object"){let c=s===null?"null":Array.isArray(s)?"array":typeof s;throw new Error(`Invalid supplier part numbers format: Expected object but got ${c}`)}let a=s;if(o)try{await o.setItem(r,JSON.stringify(a))}catch{}return a}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let t=this.getInheritedProperty("partsEngine");if(!t)return;let{db:n}=this.root,i=n.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let o;this.props.footprint&&typeof this.props.footprint=="string"&&(o=this.props.footprint);let r=this._getSupplierPartNumbers(t,i,o);if(!(r instanceof Promise)){n.source_component.update(this.source_component_id,{supplier_part_numbers:r});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{await r.then(s=>{this._asyncSupplierPartNumbers=s,this._markDirty("PartsEngineRender")}).catch(s=>{this._asyncSupplierPartNumbers={};let a=M_.parse({type:"unknown_error_finding_part",message:`Failed to fetch supplier part numbers for ${this.getString()}: ${s.message}`,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});n.unknown_error_finding_part.insert(a),this._markDirty("PartsEngineRender")})})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(n&&!n.supplier_part_numbers&&this._asyncSupplierPartNumbers){t.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:t}=this;t.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:t}=this;if(t.connections)for(let[n,i]of Object.entries(t.connections)){let o=Array.isArray(i)?i:[i];for(let r of o)this.add(new $r({from:`.${this.name} > .${n}`,to:String(r)}))}}doInitialSourceDesignRuleChecks(){gIt(this)}_getMinimumFlexContainerSize(){return _It(this)}_repositionOnPcb(t){return yIt(this,t)}doInitialSilkscreenOverlapAdjustment(){return vIt(this)}isRelativelyPositioned(){return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0}},EIt=({boardAnchorPosition:e,boardAnchorAlignment:t,width:n,height:i})=>{let{x:o,y:r}=e,s=o,a=r;switch(t){case"top_left":s=o+n/2,a=r-i/2;break;case"top_right":s=o-n/2,a=r-i/2;break;case"bottom_left":s=o+n/2,a=r+i/2;break;case"bottom_right":s=o-n/2,a=r+i/2;break;case"top":s=o,a=r-i/2;break;case"bottom":s=o,a=r+i/2;break;case"left":s=o+n/2,a=r;break;case"right":s=o-n/2,a=r;break;case"center":default:break}return{x:s,y:a}},NIt=class{constructor(e,t={}){P(this,"input");P(this,"isRouting",!1);P(this,"solver");P(this,"eventHandlers",{complete:[],error:[],progress:[]});P(this,"cycleCount",0);P(this,"stepDelay");P(this,"timeoutId");this.input=e;let{capacityDepth:n,targetMinCapacity:i,stepDelay:o=0,useAssignableViaSolver:r=!1}=t,{AutoroutingPipelineSolver:s,AssignableViaAutoroutingPipelineSolver:a}=bT,c=r?a:s;this.solver=new c(e,{capacityDepth:n,targetMinCapacity:i,cacheProvider:null}),this.stepDelay=o}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new Em(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;let i=this.solver?.preview()||void 0,o=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:o,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(e){this.emitEvent({type:"error",error:e instanceof Error?new Em(e.message):new Em(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(e,t){e==="complete"?this.eventHandlers.complete.push(t):e==="error"?this.eventHandlers.error.push(t):e==="progress"&&this.eventHandlers.progress.push(t)}emitEvent(e){if(e.type==="complete")for(let t of this.eventHandlers.complete)t(e);else if(e.type==="error")for(let t of this.eventHandlers.error)t(e);else if(e.type==="progress")for(let t of this.eventHandlers.progress)t(e)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Em(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},B4=class extends xe{constructor(){super(...arguments);P(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:vD}}doInitialPortMatching(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)return;if(i.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!i)throw new Error("TraceHint has no parent");if(!n.for){this.renderError(`TraceHint has no for property (${this})`);return}let o=i.selectOne(n.for,{type:"port"});o||this.renderError(`${this} could not find port for selector "${n.for}"`),this.matchedPort=o,o.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:t}=this,n=t.offset?[t.offset]:t.offsets;if(!n)return[];let i=this._computePcbGlobalTransformBeforeLayout();return n.map(o=>({...Ne(i,o),via:o.via,to_layer:o.to_layer,trace_width:o.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this;t.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},XH=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,pcb_placements:[...n.pcb_placements??[]]};for(let o of t)if(o.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:r,new_center:s}=o,a=Le(e).pcb_component.get(r);if(!a)continue;let c=Le(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.pcb_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.pcb_placements[l]=u:i.pcb_placements.push(u)}return i},VH=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,schematic_placements:[...n.schematic_placements??[]]};for(let o of t)if(o.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:r,new_center:s}=o,a=Le(e).schematic_component.get(r);if(!a||!a.source_component_id)continue;let c=Le(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.schematic_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.schematic_placements[l]=u:i.schematic_placements.push(u)}return i},kIt=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i=t.filter(s=>s.edit_event_type==="edit_schematic_component_location"),o=t.filter(s=>s.edit_event_type==="edit_pcb_component_location"),r=n;return i.length>0&&(r=VH({circuitJson:e,editEvents:i,manualEditsFile:r})),o.length>0&&(r=XH({circuitJson:e,editEvents:o,manualEditsFile:r})),r},AIt=(e,t)=>{if(Le(e).pcb_trace_hint.get(t.pcb_trace_hint_id))e=e.map(i=>i.pcb_trace_hint_id===t.pcb_trace_hint_id?{...i,route:t.route}:i);else{let i=Le(e).pcb_port.get(t.pcb_port_id);e=e.filter(o=>!(o.type==="pcb_trace_hint"&&o.pcb_port_id===t.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:t.pcb_trace_hint_id,route:t.route,pcb_port_id:t.pcb_port_id,pcb_component_id:i?.pcb_component_id}])}return e},RIt=({circuitJson:e,editEvents:t})=>{e=JSON.parse(JSON.stringify(e));for(let n of t)if(n.edit_event_type==="edit_pcb_component_location"){let i=e.find(r=>r.type==="pcb_component"&&r.pcb_component_id===n.pcb_component_id);if((!i||i.center.x!==n.new_center.x||i.center.y!==n.new_center.y)&&n.original_center){let r=vn(n.new_center.x-n.original_center.x,n.new_center.y-n.original_center.y);e=e.map(s=>s.pcb_component_id!==n.pcb_component_id?s:VI(s,r))}}else n.edit_event_type==="edit_schematic_component_location"?e=e.map(i=>i.type==="schematic_component"&&i.schematic_component_id===n.schematic_component_id?{...i,center:n.new_center}:i):n.edit_event_type==="edit_pcb_trace_hint"&&(e=AIt(e,n));return e},HH=(e,t)=>{let n=e.source_group.list(),i=[],o=r=>{let s=n.filter(a=>a.parent_subcircuit_id===r);for(let a of s)a.subcircuit_id&&(i.push(a.subcircuit_id),o(a.subcircuit_id))};return o(t),i},R4=({db:e,circuitJson:t,subcircuit_id:n,minTraceWidth:i=.1})=>{if(!e&&t&&(e=Le(t)),!e)throw new Error("db or circuitJson is required");let o=e.pcb_trace_hint.list(),r=n?new Set([n]):null;if(n){let k=HH(e,n);for(let N of k)r.add(N)}let s=(t??e.toArray()).filter(k=>!n||"subcircuit_id"in k&&r.has(k.subcircuit_id)),a=e.pcb_board.list()[0];e=Le(s);let c=$i(s),l=$H([...e.pcb_component.list(),...e.pcb_smtpad.list(),...e.pcb_plated_hole.list(),...e.pcb_hole.list(),...e.pcb_via.list(),...e.pcb_cutout.list()].filter(k=>!n||r?.has(k.subcircuit_id)),c);for(let k of l){let N=k.connectedTo.flatMap(A=>c.getIdsConnectedToNet(A));k.connectedTo.push(...N)}let u=l.flatMap(k=>[{x:k.center.x-k.width/2,y:k.center.y-k.height/2},{x:k.center.x+k.width/2,y:k.center.y+k.height/2}]).concat(a?.outline??[]),h;if(a&&!a.outline?h={minX:a.center.x-a.width/2,maxX:a.center.x+a.width/2,minY:a.center.y-a.height/2,maxY:a.center.y+a.height/2}:h={minX:Math.min(...u.map(k=>k.x))-1,maxX:Math.max(...u.map(k=>k.x))+1,minY:Math.min(...u.map(k=>k.y))-1,maxY:Math.max(...u.map(k=>k.y))+1},n){let k=e.pcb_group.getWhere({subcircuit_id:n});if(k?.width&&k.height){let N={minX:k.center.x-k.width/2,maxX:k.center.x+k.width/2,minY:k.center.y-k.height/2,maxY:k.center.y+k.height/2};h={minX:Math.min(h.minX,N.minX),maxX:Math.max(h.maxX,N.maxX),minY:Math.min(h.minY,N.minY),maxY:Math.max(h.maxY,N.maxY)}}}let d=new Set(e.pcb_trace.list().map(k=>k.source_trace_id).filter(k=>!!k)),_=e.source_trace.list().filter(k=>!d.has(k.source_trace_id)).map(k=>{let N=k.connected_source_port_ids.map(G=>{let tt=e.source_port.get(G),Q=e.pcb_port.getWhere({source_port_id:G});return{...tt,...Q}});if(N.length<2)return null;let[A,R]=N,$=A.layers?.[0]??"top",j=R.layers?.[0]??"top",H=o.filter(G=>G.pcb_port_id===A.pcb_port_id||G.pcb_port_id===R.pcb_port_id),X=[];for(let G of H){let Q=e.pcb_port.get(G.pcb_port_id)?.layers?.[0]??"top";for(let V of G.route)X.push({x:V.x,y:V.y,layer:Q})}return{name:k.source_trace_id??c.getNetConnectedToId(k.source_trace_id)??"",source_trace_id:k.source_trace_id,width:k.min_trace_thickness,pointsToConnect:[{x:A.x,y:A.y,layer:$,pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},...X,{x:R.x,y:R.y,layer:j,pointId:R.pcb_port_id,pcb_port_id:R.pcb_port_id}]}}).filter(k=>k!==null),y=new Map(_.map(k=>[k.source_trace_id,k])),g=e.source_net.list().filter(k=>!n||r?.has(k.subcircuit_id)),x=[];for(let k of g){let N=e.source_trace.list().filter(A=>A.connected_source_net_ids?.includes(k.source_net_id));x.push({name:k.source_net_id??c.getNetConnectedToId(k.source_net_id),pointsToConnect:N.flatMap(A=>e.pcb_port.list().filter($=>A.connected_source_port_ids.includes($.source_port_id)).map($=>({x:$.x,y:$.y,layer:$.layers?.[0]??"top",pointId:$.pcb_port_id,pcb_port_id:$.pcb_port_id})))})}let w=e.pcb_breakout_point.list().filter(k=>!n||r?.has(k.subcircuit_id)),S=[],T=new Map;for(let k of w){let N={x:k.x,y:k.y,layer:"top"};if(k.source_trace_id){let A=y.get(k.source_trace_id)??T.get(k.source_trace_id);if(A)A.pointsToConnect.push(N);else{let R={name:k.source_trace_id,source_trace_id:k.source_trace_id,pointsToConnect:[N]};S.push(R),T.set(k.source_trace_id,R)}}else if(k.source_net_id){let A=x.find(R=>R.name===k.source_net_id);A?A.pointsToConnect.push(N):S.push({name:k.source_net_id,pointsToConnect:[N]})}else if(k.source_port_id){let A=e.pcb_port.getWhere({source_port_id:k.source_port_id});A&&S.push({name:k.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:A.x,y:A.y,layer:A.layers?.[0]??"top",pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},N]})}}let I=[..._,...x,...S],E=new Map;for(let k of I)for(let N of k.pointsToConnect)N.pointId&&E.set(N.pointId,k);let M=e.pcb_trace.list().filter(k=>!n||r?.has(k.subcircuit_id));for(let k of M){let N=new Set;for(let $ of k.route)$.start_pcb_port_id&&N.add($.start_pcb_port_id),$.end_pcb_port_id&&N.add($.end_pcb_port_id);if(N.size<2)continue;let A=N.values().next().value;if(!A)continue;let R=E.get(A);R&&[...N].every($=>E.get($)===R)&&(R.externallyConnectedPointIds??(R.externallyConnectedPointIds=[]),R.externallyConnectedPointIds.push([...N]))}return{simpleRouteJson:{bounds:h,obstacles:l,connections:I,layerCount:a?.num_layers??2,minTraceWidth:i,outline:a?.outline?.map(k=>({...k}))},connMap:c}},OIt=e=>{let t={};if(!e)return t;for(let i of aa)t[i]=0;let n=new Map;for(let i of e){let[,,o,r]=i.type.split(":");if(r==="start"){n.set(`${o}:${i.renderId}`,i);continue}if(r==="end"){let s=n.get(`${o}:${i.renderId}`);if(s){let a=i.createdAt-s.createdAt;t[o]=(t[o]||0)+a}}}return t},LIt=e=>{let t=e.map(c=>[...new Set(c)]),n=t.map(()=>[]),i=t.map(()=>null);for(let c=0;c<t.length;c++)for(let l of t[c])if(/^\d+$/.test(l)){i[c]=Number.parseInt(l);break}let o=0,r=new Set;for(let c=0;c<i.length;c++){let l=i[c];if(l===null||l<1)continue;if(!r.has(l)){r.add(l),n[c].push(`pin${l}`),o=Math.max(o,l);continue}let u=0;for(let h of n[c])h.startsWith(`pin${l}_alt`)&&u++;n[c].push(`pin${l}_alt${u+1}`)}for(let c=0;c<n.length;c++)n[c][0]?.includes("_alt")&&(o++,n[c].unshift(`pin${o}`));for(let c=0;c<n.length;c++)n[c].length===0&&(o++,n[c].push(`pin${o}`));let s={};for(let c of t)for(let l of c)/^\d+$/.test(l)||(s[l]=(s[l]??0)+1);let a={};for(let c=0;c<t.length;c++){let l=t[c];for(let u of l)/^\d+$/.test(u)||(s[u]===1?n[c].push(u):(a[u]=(a[u]??0)+1,n[c].push(`${u}${a[u]}`)))}return n};function Y4({db:e,schematicComponentId:t,deltaX:n,deltaY:i}){let o=e.schematic_rect.list({schematic_component_id:t});for(let c of o)c.center.x+=n,c.center.y+=i;let r=e.schematic_line.list({schematic_component_id:t});for(let c of r)c.x1+=n,c.y1+=i,c.x2+=n,c.y2+=i;let s=e.schematic_circle.list({schematic_component_id:t});for(let c of s)c.center.x+=n,c.center.y+=i;let a=e.schematic_arc.list({schematic_component_id:t});for(let c of a)c.center.x+=n,c.center.y+=i}var cH=(0,GH.default)("Group_doInitialSchematicLayoutMatchAdapt");function FIt(e){let{db:t}=e.root,n=If(t.toArray(),{source_group_id:e.source_group_id}),i=xT(n);cH.enabled&&global.debugGraphics?.push(dc(i,{title:`floatingBpcGraph-${e.name}`}));let o=xT(n),r={boxes:o.boxes,pins:o.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:s}=YB([{variantName:"default",floatingGraph:o},{variantName:"noNotConnected",floatingGraph:r}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(o.boxes.filter(c=>o.pins.filter(h=>h.boxId===c.boxId).filter(h=>!h.color.includes("center")).length<=2).map(c=>c.boxId)),corpus:{}});cH.enabled&&global.debugGraphics?.push(dc(s,{title:`laidOutBpcGraph-${e.name}`}));let a=e._getGlobalSchematicPositionBeforeLayout();for(let c of s.boxes){if(!c.center)continue;let l=t.schematic_component.get(c.boxId);if(l){let h={x:c.center.x+a.x,y:c.center.y+a.y},d=t.schematic_port.list({schematic_component_id:l.schematic_component_id}),_=t.schematic_text.list({schematic_component_id:l.schematic_component_id}),y={x:h.x-l.center.x,y:h.y-l.center.y};for(let g of d)g.center.x+=y.x,g.center.y+=y.y;for(let g of _)g.position.x+=y.x,g.position.y+=y.y;Y4({db:t,schematicComponentId:l.schematic_component_id,deltaX:y.x,deltaY:y.y}),l.center=h;continue}let u=t.schematic_net_label.get(c.boxId);if(u){let h=s.pins.find(_=>_.boxId===c.boxId&&_.color==="netlabel_center");if(!h)throw new Error(`No pin found for net label: ${c.boxId}`);let d={x:c.center.x+a.x,y:c.center.y+a.y};u.center=d,u.anchor_position={x:d.x+h.offset.x,y:d.y+h.offset.y};continue}console.error(`No schematic element found for box: ${c.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var de=(0,UH.default)("Group_doInitialSchematicLayoutMatchpack");function lH(e){switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function uH(e,t){let n=["right","up","left","down"],i=n.indexOf(e);if(i===-1)return e;let o=Math.round(t/90),r=(i+o)%4;return n[r<0?r+4:r]}function zIt(e,t,n){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};de(`[${n.name}] Processing ${e.childNodes.length} child nodes for input problem`),e.childNodes.forEach((r,s)=>{if(de(`[${n.name}] Processing child ${s}: nodeType=${r.nodeType}`),r.nodeType==="component"?de(`[${n.name}] - Component: ${r.sourceComponent?.name}`):r.nodeType==="group"&&de(`[${n.name}] - Group: ${r.sourceGroup?.name}`),r.nodeType==="component"&&r.sourceComponent){let a=r.sourceComponent.name||`chip_${s}`,c=t.schematic_component.getWhere({source_component_id:r.sourceComponent.source_component_id});if(!c)return;let l=n.children.find(S=>S.source_component_id===r.sourceComponent?.source_component_id),u=[0,90,180,270];l?._parsedProps?.schOrientation&&(u=[0]),l?._parsedProps?.schRotation!==void 0&&(u=[0]),l?._parsedProps?.facingDirection&&(u=[0]),l?._parsedProps?.schFacingDirection&&(u=[0]),l?.componentName==="Chip"&&(u=[0]);let h=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,d=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,_=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,y=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0;l?.config.shouldRenderAsSchematicBox&&(_+=.4,y+=.4);let g=(d-h)/2,x=(_-y)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+h+d,y:(c.size?.height||1)+_+y},availableRotations:u};let w=t.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let S of w){let T=t.source_port.get(S.source_port_id);if(!T)continue;let I=`${a}.${T.pin_number||T.name||S.schematic_port_id}`;i.chipMap[a].pins.push(I);let E=lH(S.facing_direction);i.chipPinMap[I]={pinId:I,offset:{x:(S.center?.x||0)-(c.center.x||0)+g,y:(S.center?.y||0)-(c.center.y||0)+x},side:E}}}else if(r.nodeType==="group"&&r.sourceGroup){let a=r.sourceGroup.name||`group_${s}`;de(`[${n.name}] Processing nested group: ${a}`);let c=t.schematic_group?.getWhere?.({source_group_id:r.sourceGroup.source_group_id}),l=n.children.find(u=>u.source_group_id===r.sourceGroup?.source_group_id);if(de(`[${n.name}] Found schematic_group for ${a}:`,c),c){de(`[${n.name}] Treating group ${a} as composite chip`);let u=t.schematic_component.list({schematic_group_id:c.schematic_group_id});de(`[${n.name}] Group ${a} has ${u.length} components:`,u.map(A=>A.source_component_id));let h=1/0,d=-1/0,_=1/0,y=-1/0,g=!1;for(let A of u)if(A.center&&A.size){g=!0;let R=A.size.width/2,$=A.size.height/2;h=Math.min(h,A.center.x-R),d=Math.max(d,A.center.x+R),_=Math.min(_,A.center.y-$),y=Math.max(y,A.center.y+$)}let x=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,w=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,S=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,T=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,I=(w-x)/2,E=(S-T)/2,M=(g?d-h:2)+x+w,k=(g?y-_:2)+S+T;de(`[${n.name}] Group ${a} computed size: ${M} x ${k}`);let N=[];for(let A of u){let R=t.schematic_port.list({schematic_component_id:A.schematic_component_id});for(let $ of R){let j=t.source_port.get($.source_port_id);if(!j)continue;let H=`${a}.${j.pin_number||j.name||$.schematic_port_id}`;N.push(H);let X=c.center||{x:0,y:0},G=lH($.facing_direction);i.chipPinMap[H]={pinId:H,offset:{x:($.center?.x||0)-X.x+I,y:($.center?.y||0)-X.y+E},side:G}}}de(`[${n.name}] Group ${a} has ${N.length} pins:`,N),i.chipMap[a]={chipId:a,pins:N,size:{x:M,y:k}},de(`[${n.name}] Added group ${a} to chipMap`)}else de(`[${n.name}] Warning: No schematic_group found for group ${a}`)}}),de(`[${n.name}] Creating connections using connectivity keys`);let o=new Map;for(let[r,s]of Object.entries(i.chipMap))for(let a of s.pins){let c=a.split(".").pop(),l=e.childNodes.find(u=>u.nodeType==="component"&&u.sourceComponent?u.sourceComponent.name===r:u.nodeType==="group"&&u.sourceGroup?`group_${e.childNodes.indexOf(u)}`===r:!1);if(l?.nodeType==="group"&&l.sourceGroup){let u=t.schematic_group?.getWhere?.({source_group_id:l.sourceGroup.source_group_id});if(u){let h=t.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let d of h){let _=t.source_port.list({source_component_id:d.source_component_id});for(let y of _){let g=y.pin_number||y.name;if(String(g)===String(c))if(y.subcircuit_connectivity_map_key){let x=y.subcircuit_connectivity_map_key;o.has(x)||o.set(x,[]),o.get(x).push(a),de(`[${n.name}] \u2713 Pin ${a} has connectivity key: ${x}`)}else de(`[${n.name}] Pin ${a} has no connectivity key`)}}}}else if(l?.nodeType==="component"&&l.sourceComponent){let u=t.source_port.list({source_component_id:l.sourceComponent.source_component_id});for(let h of u){let d=h.pin_number||h.name;if(String(d)===String(c)&&h.subcircuit_connectivity_map_key){let _=h.subcircuit_connectivity_map_key;o.has(_)||o.set(_,[]),o.get(_).push(a),de(`[${n.name}] Pin ${a} has connectivity key: ${_}`)}}}}de(`[${n.name}] Found ${o.size} connectivity groups:`,Array.from(o.entries()).map(([r,s])=>({key:r,pins:s})));for(let[r,s]of o)if(s.length>=2){let a=t.source_trace.list().filter(u=>u.subcircuit_connectivity_map_key===r),c=a.some(u=>u.connected_source_net_ids&&u.connected_source_net_ids.length>0),l=a.some(u=>u.connected_source_port_ids&&u.connected_source_port_ids.length>=2);if(de(`[${n.name}] Connectivity ${r}: hasNetConnections=${c}, hasDirectConnections=${l}`),l){for(let u of a)if(u.connected_source_port_ids&&u.connected_source_port_ids.length>=2){let h=[];for(let d of u.connected_source_port_ids)for(let _ of s){let y=_.split(".").pop(),g=t.source_port.get(d);if(g&&String(g.pin_number||g.name)===String(y)){let x=_.split(".")[0],w=e.childNodes.find(S=>S.nodeType==="component"&&S.sourceComponent?S.sourceComponent.name===x:S.nodeType==="group"&&S.sourceGroup?`group_${e.childNodes.indexOf(S)}`===x:!1);w?.nodeType==="component"&&w.sourceComponent&&t.source_port.list({source_component_id:w.sourceComponent.source_component_id}).some(T=>T.source_port_id===d)&&h.push(_)}}for(let d=0;d<h.length;d++)for(let _=d+1;_<h.length;_++){let y=h[d],g=h[_];i.pinStrongConnMap[`${y}-${g}`]=!0,i.pinStrongConnMap[`${g}-${y}`]=!0,de(`[${n.name}] Created strong connection: ${y} <-> ${g}`)}}}if(c){let u=t.source_net.getWhere({subcircuit_connectivity_map_key:r}),h=u?.is_ground??!1,d=u?.is_power??!1;i.netMap[r]={netId:r,isGround:h,isPositiveVoltageSource:d};for(let _ of s)i.netConnMap[`${_}-${r}`]=!0;de(`[${n.name}] Created net ${r} with ${s.length} pins:`,s)}}return i}function DIt(e){let{db:t}=e.root,n=ih(t.toArray(),{source_group_id:e.source_group_id});if(de(`[${e.name}] Starting matchpack layout with ${n.childNodes.length} children`),de(`[${e.name}] Tree structure:`,JSON.stringify(n,null,2)),n.childNodes.length<=1){de(`[${e.name}] Only ${n.childNodes.length} children, skipping layout`);return}de("Converting circuit tree to InputProblem...");let i=zIt(n,t,e);de.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${e.name}`,content:JSON.stringify(i,null,2)});let o=new GY(i);if(de("Starting LayoutPipelineSolver..."),de.enabled&&global.debugGraphics){let c=o.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${e.name}`})}if(o.solve(),de(`Solver completed in ${o.iterations} iterations`),de(`Solved: ${o.solved}, Failed: ${o.failed}`),o.failed)throw de(`Solver failed with error: ${o.error}`),new Error(`Matchpack layout solver failed: ${o.error}`);let r=o.getOutputLayout();if(de("OutputLayout:",JSON.stringify(r,null,2)),de("Solver completed successfully:",!o.failed),de.enabled&&global.debugGraphics){let c=o.visualize();global.debugGraphics.push({...c,title:`matchpack-final-${e.name}`})}let s=o.checkForOverlaps(r);if(s.length>0){de(`Warning: Found ${s.length} overlapping components:`);for(let c of s)de(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=e._getGlobalSchematicPositionBeforeLayout();de(`Group offset: x=${a.x}, y=${a.y}`),de(`Applying layout results for ${Object.keys(r.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(r.chipPlacements)){de(`Processing placement for chip: ${c} at (${l.x}, ${l.y})`);let u=n.childNodes.find(d=>{if(d.nodeType==="component"&&d.sourceComponent){let _=d.sourceComponent.name===c;return de(` Checking component ${d.sourceComponent.name}: matches=${_}`),_}if(d.nodeType==="group"&&d.sourceGroup){let _=d.sourceGroup.name,y=`group_${n.childNodes.indexOf(d)}`,g=y===c;return de(` Checking group ${_} (expected chipId: ${y}): matches=${g}`),g}return!1});if(!u){de(`Warning: No tree node found for chip: ${c}`),de("Available tree nodes:",n.childNodes.map((d,_)=>({type:d.nodeType,name:d.nodeType==="component"?d.sourceComponent?.name:d.sourceGroup?.name,expectedChipId:d.nodeType==="group"?`group_${_}`:d.sourceComponent?.name})));continue}let h={x:l.x+a.x,y:l.y+a.y};if(u.nodeType==="component"&&u.sourceComponent){let d=t.schematic_component.getWhere({source_component_id:u.sourceComponent.source_component_id});if(d){de(`Moving component ${c} to (${h.x}, ${h.y})`);let _=t.schematic_port.list({schematic_component_id:d.schematic_component_id}),y=t.schematic_text.list({schematic_component_id:d.schematic_component_id}),g={x:h.x-d.center.x,y:h.y-d.center.y};for(let x of _)x.center.x+=g.x,x.center.y+=g.y;for(let x of y)x.position.x+=g.x,x.position.y+=g.y;if(Y4({db:t,schematicComponentId:d.schematic_component_id,deltaX:g.x,deltaY:g.y}),d.center=h,l.ccwRotationDegrees!==0){de(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let x=l.ccwRotationDegrees*Math.PI/180,w=Math.cos(x),S=Math.sin(x);for(let T of _){let I=T.center.x-h.x,E=T.center.y-h.y,M=I*w-E*S,k=I*S+E*w;T.center.x=h.x+M,T.center.y=h.y+k;let N=T.facing_direction||"right";T.facing_direction=uH(N,l.ccwRotationDegrees),T.side_of_component=(T.facing_direction==="up"?"top":T.facing_direction==="down"?"bottom":T.facing_direction)||T.side_of_component}for(let T of y){let I=T.position.x-h.x,E=T.position.y-h.y,M=I*w-E*S,k=I*S+E*w;T.position.x=h.x+M,T.position.y=h.y+k}if(d.symbol_name){let T=d.symbol_name.match(/_(right|left|up|down)$/);T&&(d.symbol_name=d.symbol_name.replace(T[0],`_${uH(T[1],l.ccwRotationDegrees)}`))}}}}else if(u.nodeType==="group"&&u.sourceGroup){let d=t.schematic_group?.getWhere?.({source_group_id:u.sourceGroup.source_group_id});if(d){de(`Moving group ${c} to (${h.x}, ${h.y}) from (${d.center?.x}, ${d.center?.y})`);let _=t.schematic_component.list({schematic_group_id:d.schematic_group_id});de(`Group ${c} has ${_.length} components to move`);let y=d.center||{x:0,y:0},g={x:h.x-y.x,y:h.y-y.y};de(`Position delta for group ${c}: (${g.x}, ${g.y})`);for(let x of _)if(x.center){let w={...x.center};x.center.x+=g.x,x.center.y+=g.y,de(`Moved component ${x.source_component_id} from (${w.x}, ${w.y}) to (${x.center.x}, ${x.center.y})`);let S=t.schematic_port.list({schematic_component_id:x.schematic_component_id}),T=t.schematic_text.list({schematic_component_id:x.schematic_component_id});for(let I of S)I.center&&(I.center.x+=g.x,I.center.y+=g.y);for(let I of T)I.position&&(I.position.x+=g.x,I.position.y+=g.y)}d.center=h,de(`Updated group ${c} center to (${h.x}, ${h.y})`)}}}de("Matchpack layout completed successfully")}function $It(e){if(!e.isSubcircuit)return;let{db:t}=e.root,n=e.selectAll("trace"),i=e.selectAll("via"),o=e.selectAll("net"),r=new qp({});r.addConnections(n.map(u=>{let h=t.source_trace.get(u.source_trace_id);return h?[h.source_trace_id,...h.connected_source_port_ids,...h.connected_source_net_ids]:null}).filter(u=>u!==null));let s=t.source_net.list().filter(u=>u.subcircuit_id===e.subcircuit_id);for(let u of s)r.addConnections([[u.source_net_id]]);let{name:a}=e._parsedProps;for(let u of n){if(!u.source_trace_id)continue;let h=r.getNetConnectedToId(u.source_trace_id);h&&(u.subcircuit_connectivity_map_key=`${a??`unnamedsubcircuit${e._renderId}`}_${h}`,t.source_trace.update(u.source_trace_id,{subcircuit_connectivity_map_key:u.subcircuit_connectivity_map_key}))}let c=new Set;for(let u of n){if(!u.source_trace_id)continue;let h=t.source_trace.get(u.source_trace_id);if(h)for(let d of h.connected_source_port_ids)c.add(d)}for(let u of c){let h=r.getNetConnectedToId(u);if(!h)continue;let d=`${a??`unnamedsubcircuit${e._renderId}`}_${h}`;t.source_port.update(u,{subcircuit_connectivity_map_key:d})}let l=new Set;for(let u of n){if(!u.source_trace_id)continue;let h=t.source_trace.get(u.source_trace_id);if(h)for(let d of h.connected_source_net_ids)l.add(d)}for(let u of s)l.add(u.source_net_id);for(let u of l){let h=r.getNetConnectedToId(u);if(!h)continue;let d=`${a??`unnamedsubcircuit${e._renderId}`}_${h}`;t.source_net.update(u,{subcircuit_connectivity_map_key:d});let _=o.find(y=>y.source_net_id===u);_&&(_.subcircuit_connectivity_map_key=d)}for(let u of i){let h=u._getConnectedNetOrTrace();h&&h.subcircuit_connectivity_map_key&&(u.subcircuit_connectivity_map_key=h.subcircuit_connectivity_map_key)}}function jIt(e){let{db:t}=e.root,n=e._parsedProps,i=e.children.filter(E=>{let M=E._parsedProps?.schX!==void 0||E._parsedProps?.schY!==void 0;return E.schematic_component_id&&!M});if(i.length===0)return;let o=0,r=0;for(let E of i){let M=t.schematic_component.get(E.schematic_component_id);M?.size&&(o=Math.max(o,M.size.width),r=Math.max(r,M.size.height))}o===0&&i.length>0&&(o=1),r===0&&i.length>0&&(r=1);let s=n.gridCols,a,c=n.gridGap,l=n.gridRowGap,u=n.gridColumnGap;n.schLayout?.grid&&(s=n.schLayout.grid.cols??s,a=n.schLayout.grid.rows,c=n.schLayout.gridGap??c,l=n.schLayout.gridRowGap??l,u=n.schLayout.gridColumnGap??u);let h,d;s!==void 0&&a!==void 0?(h=s,d=a):s!==void 0?(h=s,d=Math.ceil(i.length/h)):a!==void 0?(d=a,h=Math.ceil(i.length/d)):(h=Math.ceil(Math.sqrt(i.length)),d=Math.ceil(i.length/h)),h===0&&i.length>0&&(h=1),d===0&&i.length>0&&(d=i.length);let _,y,g=E=>{if(E!==void 0)return typeof E=="number"?E:D.parse(E)};if(l!==void 0||u!==void 0){let E=typeof c=="object"&&c!==null?c.x:c,M=typeof c=="object"&&c!==null?c.y:c;_=g(u??E)??1,y=g(l??M)??1}else if(typeof c=="number")_=c,y=c;else if(typeof c=="string"){let E=D.parse(c);_=E,y=E}else if(typeof c=="object"&&c!==null){let E=c.x,M=c.y;_=typeof E=="number"?E:D.parse(E??"0mm"),y=typeof M=="number"?M:D.parse(M??"0mm")}else _=1,y=1;let x=h*o+Math.max(0,h-1)*_,w=d*r+Math.max(0,d-1)*y,S=e._getGlobalSchematicPositionBeforeLayout(),T=S.x-x/2+o/2,I=S.y+w/2-r/2;for(let E=0;E<i.length;E++){let M=i[E];if(!M.schematic_component_id)continue;let k=Math.floor(E/h),N=E%h;if(k>=d||N>=h){console.warn(`Schematic grid layout: Child ${M.getString()} at index ${E} (row ${k}, col ${N}) exceeds specified grid dimensions (${d}x${h}). Skipping placement.`);continue}let A=T+N*(o+_),R=I-k*(r+y),$=t.schematic_component.get(M.schematic_component_id);if($){let j=$.center,H={x:A,y:R};t.schematic_component.update(M.schematic_component_id,{center:H});let X=H.x-j.x,G=H.y-j.y,tt=t.schematic_port.list({schematic_component_id:M.schematic_component_id});for(let V of tt)t.schematic_port.update(V.schematic_port_id,{center:{x:V.center.x+X,y:V.center.y+G}});let Q=t.schematic_text.list({schematic_component_id:M.schematic_component_id});for(let V of Q)t.schematic_text.update(V.schematic_text_id,{position:{x:V.position.x+X,y:V.position.y+G}});Y4({db:t,schematicComponentId:M.schematic_component_id,deltaX:X,deltaY:G})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:x,height:w,center:S})}var pH=(e,t)=>{let{sourceComponent:n,sourceGroup:i}=t;if(t.nodeType==="component"){let o=e.schematic_component.getWhere({source_component_id:n?.source_component_id});return o?.size?{width:o.size.width,height:o.size.height}:null}if(t.nodeType==="group"){let o=e.schematic_group.getWhere({source_group_id:i?.source_group_id});if(o?.width&&o?.height)return{width:o.width,height:o.height};let r=e.schematic_component.list({schematic_group_id:o?.schematic_group_id}),s=1/0,a=-1/0,c=1/0,l=-1/0;for(let d of r)if(d.center&&d.size){let _=d.size.width/2,y=d.size.height/2;s=Math.min(s,d.center.x-_),a=Math.max(a,d.center.x+_),c=Math.min(c,d.center.y-y),l=Math.max(l,d.center.y+y)}let u=a-s,h=l-c;return{width:u,height:h}}return null},BIt=e=>{let{db:t}=e.root,n=e._parsedProps,i=ih(t.toArray(),{source_group_id:e.source_group_id}),o=n.schJustifyContent??n.justifyContent,r=n.schAlignItems??n.alignItems,s=n.schFlexGap??n.schGap??n.gap,a=n.schFlexDirection??"row",c={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[o??"space-between"],l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[r??"center"];if(!c)throw new Error(`Invalid justifyContent value: "${o}"`);if(!l)throw new Error(`Invalid alignItems value: "${r}"`);let u=0,h=0;typeof s=="object"?(u=s.y??0,h=s.x??0):typeof s=="number"?(u=s,h=s):typeof s=="string"&&(u=D.parse(s),h=D.parse(s));let d,_=n.width??n.schWidth??void 0,y=n.height??n.schHeight??void 0;(_===void 0||y===void 0)&&(d=ub(i.childNodes.map(I=>pH(t,I)).filter(I=>I!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h}),_=d.width,y=d.height);let x=new dx(_,y,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h});for(let I of i.childNodes){let E=pH(t,I);x.addChild({metadata:I,width:E?.width??0,height:E?.height??0,flexBasis:E?a==="row"?E.width:E.height:void 0})}x.build();let w={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let I of x.children)w.minX=Math.min(w.minX,I.position.x),w.minY=Math.min(w.minY,I.position.y),w.maxX=Math.max(w.maxX,I.position.x+I.size.width),w.maxY=Math.max(w.maxY,I.position.y+I.size.height);w.width=w.maxX-w.minX,w.height=w.maxY-w.minY;let S={x:-(w.maxX+w.minX)/2,y:-(w.maxY+w.minY)/2},T=t.toArray();for(let I of x.children){let{sourceComponent:E,sourceGroup:M}=I.metadata;if(E){let k=t.schematic_component.getWhere({source_component_id:E.source_component_id});if(!k)continue;QD(T,k.schematic_component_id,{x:I.position.x+I.size.width/2+S.x,y:I.position.y+I.size.height/2+S.y})}if(M){if(!t.schematic_group.getWhere({source_group_id:M.source_group_id}))continue;e$(T,M.source_group_id,{x:I.position.x+I.size.width/2+S.x,y:I.position.y+I.size.height/2+S.y})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:w.width,height:w.height})},S4=1;function YIt(e){let{db:t}=e.root,n=e._parsedProps,i=XIt(e);if(i.length===0)return;let o=VIt({db:t,pcbChildren:i}),r=HIt(n),s=GIt({props:n,pcbChildren:i,childDimensions:o,gridConfig:r}),a=WIt({pcbChildren:i,childDimensions:o,gridLayout:s,gridConfig:r}),{itemCoordinates:c}=a.layout();ZIt({db:t,group:e,pcbChildren:i,itemCoordinates:c,gridLayout:s}),KIt({db:t,group:e,props:n,gridLayout:s})}function XIt(e){return e.children.filter(t=>t.pcb_component_id||t.pcb_group_id)}function VIt(e){let{db:t,pcbChildren:n}=e,i=0,o=0;for(let r of n){let s=0,a=0;if(r.pcb_group_id){let c=t.pcb_group.get(r.pcb_group_id);s=c?.width??0,a=c?.height??0}else if(r.pcb_component_id){let c=t.pcb_component.get(r.pcb_component_id);s=c?.width??0,a=c?.height??0}i=Math.max(i,s),o=Math.max(o,a)}return{width:i,height:o}}function HIt(e){let t=e.pcbGridCols??e.gridCols??e.pcbLayout?.grid?.cols,n=e.pcbGridRows??e.pcbLayout?.grid?.rows,i=e.pcbGridTemplateColumns,o=e.pcbGridTemplateRows,r=h=>h===void 0?S4:typeof h=="number"?h:D.parse(h),s=e.pcbGridGap??e.gridGap??e.pcbLayout?.gridGap,a=e.pcbGridRowGap??e.gridRowGap??e.pcbLayout?.gridRowGap,c=e.pcbGridColumnGap??e.gridColumnGap??e.pcbLayout?.gridColumnGap,l=S4,u=S4;if(a!==void 0||c!==void 0){let h=typeof s=="object"?s?.x:s,d=typeof s=="object"?s?.y:s;l=r(c??h),u=r(a??d)}else if(typeof s=="object"&&s!==null)l=r(s.x),u=r(s.y);else{let h=r(s);l=h,u=h}return{cols:t,rows:n,gapX:l,gapY:u,templateColumns:i,templateRows:o}}function GIt(e){let{props:t,pcbChildren:n,childDimensions:i,gridConfig:o}=e;return t.pcbGridTemplateColumns||t.pcbGridTemplateRows?UIt({props:t,gridConfig:o,pcbChildren:n,childDimensions:i}):qIt({gridConfig:o,pcbChildren:n,childDimensions:i})}function UIt(e){let{props:t,gridConfig:n,pcbChildren:i,childDimensions:o}=e,r=t.pcbGridTemplateColumns??"",s=t.pcbGridTemplateRows??"",a=d=>{let _=d.match(/repeat\((\d+),/);return _?parseInt(_[1]):Math.ceil(Math.sqrt(i.length))},c=t.pcbGridTemplateColumns?a(r):Math.ceil(Math.sqrt(i.length)),l=t.pcbGridTemplateRows?a(s):Math.ceil(i.length/c),u=c*o.width+Math.max(0,c-1)*n.gapX,h=l*o.height+Math.max(0,l-1)*n.gapY;return{gridTemplateColumns:r,gridTemplateRows:s,containerWidth:u,containerHeight:h}}function qIt(e){let{gridConfig:t,pcbChildren:n,childDimensions:i}=e,o,r;t.cols!==void 0&&t.rows!==void 0?(o=t.cols,r=t.rows):t.cols!==void 0?(o=t.cols,r=Math.ceil(n.length/o)):t.rows!==void 0?(r=t.rows,o=Math.ceil(n.length/r)):(o=Math.ceil(Math.sqrt(n.length)),r=Math.ceil(n.length/o)),o=Math.max(1,o),r=Math.max(1,r);let s=o*i.width+Math.max(0,o-1)*t.gapX,a=r*i.height+Math.max(0,r-1)*t.gapY,c=`repeat(${o}, ${i.width}px)`,l=`repeat(${r}, ${i.height}px)`;return{gridTemplateColumns:c,gridTemplateRows:l,containerWidth:s,containerHeight:a}}function WIt(e){let{pcbChildren:t,childDimensions:n,gridLayout:i,gridConfig:o}=e,r=t.map((s,a)=>({key:s.getString()||`child-${a}`,contentWidth:n.width,contentHeight:n.height}));return new eX({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[o.gapY,o.gapX],children:r})}function ZIt(e){let{db:t,group:n,pcbChildren:i,itemCoordinates:o,gridLayout:r}=e,s=n._getGlobalPcbPositionBeforeLayout(),a=t.toArray();for(let c=0;c<i.length;c++){let l=i[c],u=l.getString()||`child-${c}`,h=o[u];if(!h){console.warn(`PCB grid layout: No coordinates found for child ${u}`);continue}let d=s.x-r.containerWidth/2+h.x+h.width/2,_=s.y+r.containerHeight/2-h.y-h.height/2;if(l.pcb_component_id)cb(a,l.pcb_component_id,{x:d,y:_});else{let y=l;y.pcb_group_id&&y.source_group_id&&lb(a,y.source_group_id,{x:d,y:_})}}}function KIt(e){let{db:t,group:n,props:i,gridLayout:o}=e;if(n.pcb_group_id){let r=n._getGlobalPcbPositionBeforeLayout();t.pcb_group.update(n.pcb_group_id,{width:i.width??o.containerWidth,height:i.height??o.containerHeight,center:r})}}function JIt(e){let t={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof e=="object"&&!e.preset)return{local:!(e.serverUrl||e.serverMode||e.serverCacheEnabled),...t,...e};let n=typeof e=="object"?e.preset:e,i=typeof e=="object"?e:{};switch(typeof n=="string"?n.replace(/_/g,"-"):n){case"auto-local":return{local:!0,groupMode:"subcircuit"};case"sequential-trace":return{local:!0,groupMode:"sequential-trace"};case"subcircuit":return{local:!0,groupMode:"subcircuit"};case"auto-cloud":{let{preset:r,local:s,groupMode:a,...c}=i;return{local:!1,groupMode:"subcircuit",...t,...c}}case"laser-prefab":{let{preset:r,local:s,groupMode:a,...c}=i;return{local:!0,groupMode:"subcircuit",preset:"laser_prefab",...c}}default:return{local:!0,groupMode:"subcircuit"}}}var QIt=(e,t)=>{let n=e.children.filter(h=>h.componentName==="Constraint"&&h._parsedProps.pcb),i=new Map,o={},r=h=>(o[h]!==h&&(o[h]=r(o[h])),o[h]),s=(h,d)=>{let _=r(h),y=r(d);_!==y&&(o[y]=_)},a=h=>{h in o||(o[h]=h)},c=h=>{let d=h.startsWith(".")?h.slice(1):h;return e.children.find(y=>y.name===d)?.pcb_component_id??void 0};for(let h of n){let d=h._parsedProps;if("left"in d&&"right"in d){let _=c(d.left),y=c(d.right);_&&y&&(a(_),a(y),s(_,y))}else if("top"in d&&"bottom"in d){let _=c(d.top),y=c(d.bottom);_&&y&&(a(_),a(y),s(_,y))}else if("for"in d&&Array.isArray(d.for)){let _=d.for.map(y=>c(y)).filter(y=>!!y);for(let y of _)a(y);for(let y=1;y<_.length;y++)s(_[0],_[y])}}for(let h of Object.keys(o)){let d=r(h);i.has(d)||i.set(d,{componentIds:[],constraints:[]}),i.get(d).componentIds.push(h)}for(let h of n){let d=h._parsedProps,_;if("left"in d?_=c(d.left):"top"in d?_=c(d.top):"for"in d&&(_=c(d.for[0])),!_)continue;let y=r(_);i.get(y)?.constraints.push(h)}let l={},u=Object.fromEntries(t.components.map(h=>[h.componentId,h]));for(let[h,d]of i.entries()){if(d.componentIds.length<=1)continue;let _=new Qp,y={},g=(A,R)=>{let $=`${A}_${R}`;return y[$]||(y[$]=new Us($)),y[$]},x=d.componentIds[0];_.addConstraint(new ci(g(x,"x"),Vn.Eq,0,wn.required)),_.addConstraint(new ci(g(x,"y"),Vn.Eq,0,wn.required));for(let A of d.constraints){let R=A._parsedProps;if("xDist"in R){let $=c(R.left),j=c(R.right);$&&j&&_.addConstraint(new ci(new Cn(g(j,"x"),[-1,g($,"x")]),Vn.Eq,R.xDist,wn.required))}else if("yDist"in R){let $=c(R.top),j=c(R.bottom);$&&j&&_.addConstraint(new ci(new Cn(g($,"y"),[-1,g(j,"y")]),Vn.Eq,R.yDist,wn.required))}else if("sameX"in R&&Array.isArray(R.for)){let $=R.for.map(j=>c(j)).filter(j=>!!j);if($.length>1){let j=g($[0],"x");for(let H=1;H<$.length;H++)_.addConstraint(new ci(new Cn(g($[H],"x"),[-1,j]),Vn.Eq,0,wn.required))}}else if("sameY"in R&&Array.isArray(R.for)){let $=R.for.map(j=>c(j)).filter(j=>!!j);if($.length>1){let j=g($[0],"y");for(let H=1;H<$.length;H++)_.addConstraint(new ci(new Cn(g($[H],"y"),[-1,j]),Vn.Eq,0,wn.required))}}}_.updateVariables();let w={};for(let A of d.componentIds)w[A]={x:g(A,"x").value(),y:g(A,"y").value()};let S=1/0,T=1/0,I=-1/0,E=-1/0;for(let A of d.componentIds){let R=u[A],$=w[A];if(R)for(let j of R.pads){let H=$.x+j.offset.x,X=$.y+j.offset.y;S=Math.min(S,H-j.size.x/2),I=Math.max(I,H+j.size.x/2),T=Math.min(T,X-j.size.y/2),E=Math.max(E,X+j.size.y/2)}}let M={x:(S+I)/2,y:(T+E)/2},k=[],N={};for(let A of d.componentIds){let R=u[A],$=w[A];if(R){N[A]={x:$.x-M.x,y:$.y-M.y};for(let j of R.pads)k.push({padId:j.padId,networkId:j.networkId,type:j.type,size:j.size,offset:{x:$.x+j.offset.x-M.x,y:$.y+j.offset.y-M.y}})}}t.components=t.components.filter(A=>!d.componentIds.includes(A.componentId)),t.components.push({componentId:d.componentIds[0],pads:k,availableRotationDegrees:[0]}),d.relativeCenters=N,l[d.componentIds[0]]=d}return l},hH=({db:e,pcbComponentId:t,rotationDegrees:n,layer:i})=>{if(n==null||!e?.cad_component?.list)return;let o=e.cad_component.getWhere({pcb_component_id:t});if(!o)return;let r=i?.toLowerCase?.()==="bottom"?-n:n,s=o.rotation?.z??0,a={...o.rotation??{x:0,y:0,z:0},z:Vl(s+r)};e.cad_component.update(o.cad_component_id,{rotation:a}),o.rotation=a},Nm=(e,t,n)=>{if(t===n)return!0;let i=e.source_group.get(t);return!i||!i.parent_source_group_id?!1:Nm(e,i.parent_source_group_id,n)},tTt=(e,t,n)=>{let{db:i}=e.root;for(let o of t.components){let{center:r,componentId:s,ccwRotationOffset:a,ccwRotationDegrees:c}=o,l=n[s];if(l){let x=c??a??0,w=x*Math.PI/180;for(let S of l.componentIds){let T=l.relativeCenters[S];if(!T)continue;let I={x:T.x*Math.cos(w)-T.y*Math.sin(w),y:T.x*Math.sin(w)+T.y*Math.cos(w)},E=i.pcb_component.get(S);if(!E)continue;let M=E.center,k=Qn(e._computePcbGlobalTransformBeforeLayout(),vn(r.x+I.x,r.y+I.y),Ua(w),vn(-M.x,-M.y)),N=i.toArray().filter(A=>"pcb_component_id"in A&&A.pcb_component_id===S);eh(N,k),hH({db:i,pcbComponentId:S,rotationDegrees:x,layer:E.layer})}continue}let u=i.pcb_component.get(s);if(u){let x=e.source_group_id,S=i.source_component.get(u.source_component_id)?.source_group_id;if(S!==void 0&&!Nm(i,S,x))continue;let T=u.center,I=c??a??0,E=Qn(e._computePcbGlobalTransformBeforeLayout(),vn(r.x,r.y),Ua(I*Math.PI/180),vn(-T.x,-T.y)),M=i.toArray().filter(k=>"pcb_component_id"in k&&k.pcb_component_id===s);eh(M,E),hH({db:i,pcbComponentId:s,rotationDegrees:I,layer:u.layer});continue}let h=i.pcb_group.list().find(x=>x.source_group_id===s);if(!h)continue;let d=h.center,_=c??a??0,y=Qn(e._computePcbGlobalTransformBeforeLayout(),vn(r.x,r.y),Ua(_*Math.PI/180),vn(-d.x,-d.y)),g=i.toArray().filter(x=>{if("source_group_id"in x&&x.source_group_id&&(x.source_group_id===s||Nm(i,x.source_group_id,s)))return!0;if("source_component_id"in x&&x.source_component_id){let w=i.source_component.get(x.source_component_id);if(w?.source_group_id&&(w.source_group_id===s||Nm(i,w.source_group_id,s)))return!0}if("pcb_component_id"in x&&x.pcb_component_id){let w=i.pcb_component.get(x.pcb_component_id);if(w?.source_component_id){let S=i.source_component.get(w.source_component_id);if(S?.source_group_id&&(S.source_group_id===s||Nm(i,S.source_group_id,s)))return!0}}return!1});eh(g,y),i.pcb_group.update(h.pcb_group_id,{center:r})}};function eTt(e){switch(e.shape){case"rect":case"rotated_rect":case"pill":case"rotated_pill":return{width:e.width,height:e.height};case"circle":return{width:e.radius*2,height:e.radius*2};case"polygon":if(!e.points||e.points.length===0)return null;let t=e.points.map(a=>a.x),n=e.points.map(a=>a.y),i=Math.min(...t),o=Math.max(...t),r=Math.min(...n),s=Math.max(...n);return{width:o-i,height:s-r};default:return null}}function nTt(e){switch(e.shape){case"circular_hole_with_rect_pad":case"pill_hole_with_rect_pad":case"rotated_pill_hole_with_rect_pad":return{width:e.rect_pad_width,height:e.rect_pad_height};case"circle":return{width:e.outer_diameter,height:e.outer_diameter};case"oval":return{width:e.outer_width,height:e.outer_height};case"pill":return{width:e.outer_width,height:e.outer_height};default:return null}}var iTt="1mm",dH=(0,qH.default)("Group_doInitialPcbLayoutPack"),oTt=e=>{let{db:t}=e.root,{_parsedProps:n}=e,{packOrderStrategy:i,packPlacementStrategy:o,gap:r,pcbGap:s,pcbPackGap:a}=n,c=a??s??r,l=D.parse(c??iTt),u={},h=new Set,d=I=>{if(I?.pcb_component_id&&I?._parsedProps){let E=I._parsedProps,M=D.parse(E.pcbMarginLeft??E.pcbMarginX??0),k=D.parse(E.pcbMarginRight??E.pcbMarginX??0),N=D.parse(E.pcbMarginTop??E.pcbMarginY??0),A=D.parse(E.pcbMarginBottom??E.pcbMarginY??0);(M||k||N||A)&&(u[I.pcb_component_id]={left:M,right:k,top:N,bottom:A})}I?.children&&I.children.forEach(d)};d(e);let _=new Set;for(let I of e.children){let E=I;E._isNormalComponent&&E.isRelativelyPositioned?.()&&(E.pcb_component_id&&h.add(E.pcb_component_id),E.pcb_group_id&&_.add(E.pcb_group_id))}let y=t.toArray().filter(I=>I.type==="pcb_component"?!h.has(I.pcb_component_id):I.type==="pcb_group"?!_.has(I.pcb_group_id):!0),g=[];for(let I of h){let E=t.toArray().find(R=>R.type==="pcb_component"&&R.pcb_component_id===I);if(!E)continue;let M=E.center.x,k=E.center.y,N=t.toArray().filter(R=>R.type==="pcb_smtpad"&&R.pcb_component_id===I);for(let R of N){let $=eTt(R);if(!$||$.width===0||$.height===0)continue;let j,H;if(R.shape==="polygon"){let X=R.points.map(tt=>tt.x),G=R.points.map(tt=>tt.y);j=M+(Math.min(...X)+Math.max(...X))/2,H=k+(Math.min(...G)+Math.max(...G))/2}else j=M+R.x,H=k+R.y;g.push({obstacleId:R.pcb_smtpad_id,absoluteCenter:{x:j,y:H},width:$.width,height:$.height})}let A=t.toArray().filter(R=>R.type==="pcb_plated_hole"&&R.pcb_component_id===I);for(let R of A){let $=nTt(R);if(!$||$.width===0||$.height===0)continue;let j=M+R.x,H=k+R.y;g.push({obstacleId:R.pcb_plated_hole_id,absoluteCenter:{x:j,y:H},width:$.width,height:$.height})}}let x;if(n.width!==void 0&&n.height!==void 0){let I=D.parse(n.width),E=D.parse(n.height);x={minX:-I/2,maxX:I/2,minY:-E/2,maxY:E/2}}let w={...VY(XY(y,{source_group_id:e.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:u})),orderStrategy:i??"largest_to_smallest",placementStrategy:o??"minimum_sum_squared_distance_to_network",minGap:l,obstacles:g,bounds:x},S=QIt(e,w);dH.enabled&&(e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${e.name}`,content:JSON.stringify(t.toArray())}),e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${e.name}`,content:w}));let T=ux(w);if(dH.enabled){let I=kM(T);I.title=`packOutput-${e.name}`,global.debugGraphics?.push(I)}tTt(e,T,S)},rTt=e=>{let{db:t}=e.root,{_parsedProps:n}=e,i=e.children.filter(E=>E.pcb_component_id||E.pcb_group_id);if(i.some(E=>{let M=E._parsedProps;return M?.pcbX!==void 0||M?.pcbY!==void 0}))return;let r=n.pcbJustifyContent??n.justifyContent,s=n.pcbAlignItems??n.alignItems,a=n.pcbFlexGap??n.pcbGap??n.gap,c=n.pcbFlexDirection??"row",l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[r??"space-between"],u={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[s??"center"];if(!l)throw new Error(`Invalid justifyContent value: "${r}"`);if(!u)throw new Error(`Invalid alignItems value: "${s}"`);let h=0,d=0;typeof a=="object"?(h=a.y??0,d=a.x??0):typeof a=="number"?(h=a,d=a):typeof a=="string"&&(h=D.parse(a),d=D.parse(a));let _,y=n.width??n.pcbWidth??void 0,g=n.height??n.pcbHeight??void 0;(y===void 0||g===void 0)&&(_=ub(i.map(E=>E._getMinimumFlexContainerSize()).filter(E=>E!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d}),y=_.width,g=_.height);let w=new dx(y,g,{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d});for(let E of i){let M=E._getMinimumFlexContainerSize();w.addChild({metadata:E,width:M?.width??0,height:M?.height??0,flexBasis:M?c==="row"?M.width:M.height:void 0})}w.build();let S={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let E of w.children)S.minX=Math.min(S.minX,E.position.x),S.minY=Math.min(S.minY,E.position.y),S.maxX=Math.max(S.maxX,E.position.x+E.size.width),S.maxY=Math.max(S.maxY,E.position.y+E.size.height);S.width=S.maxX-S.minX,S.height=S.maxY-S.minY;let T=e._getGlobalPcbPositionBeforeLayout(),I={x:T.x-(S.maxX+S.minX)/2,y:T.y-(S.maxY+S.minY)/2};for(let E of w.children)E.metadata._repositionOnPcb({x:E.position.x+E.size.width/2+I.x,y:E.position.y+E.size.height/2+I.y});t.pcb_group.update(e.pcb_group_id,{width:S.width,height:S.height,center:T})};function sTt(e){let{db:t}=e.root,n=new Map,i=new Map,o=new Set,s=e.selectAll("trace").filter(R=>R._parsedProps?.schDisplayLabel),a=e.selectAll("group"),c=[e.schematic_group_id,...a.map(R=>R.schematic_group_id)],l=t.schematic_component.list().filter(R=>c.includes(R.schematic_group_id)),u=[],h=new Map,d=new Map;for(let R of l){let $=R.schematic_component_id,j=[],H=t.source_component.getWhere({source_component_id:R.source_component_id}),X=t.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let G of X){let tt=`${H?.name??R.schematic_component_id}.${G.pin_number}`;h.set(tt,G.schematic_port_id),d.set(G.schematic_port_id,tt)}for(let G of X){let tt=d.get(G.schematic_port_id);j.push({pinId:tt,x:G.center.x,y:G.center.y})}u.push({chipId:$,center:R.center,width:R.size.width,height:R.size.height,pins:j})}let _=new Set,y=new Map,g=new Map,x=new Map;for(let R of l){let $=t.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let j of $)_.add(j.schematic_port_id),j.source_port_id&&(y.set(j.schematic_port_id,j.source_port_id),g.set(j.source_port_id,j.schematic_port_id))}let w=new Set;e.subcircuit_id&&w.add(e.subcircuit_id);for(let R of a)R.subcircuit_id&&w.add(R.subcircuit_id);let T=t.source_trace.list().filter(R=>{if(R.subcircuit_id===e.subcircuit_id)return!0;for(let $ of R.connected_source_port_ids)if(g.has($))return!0;return!1}).flatMap(R=>R.connected_source_net_ids);for(let R of T){let $=t.source_net.get(R);$?.subcircuit_id&&w.add($.subcircuit_id)}let I=[],E=new Map;for(let R of t.source_trace.list()){if(R.subcircuit_id&&!w.has(R.subcircuit_id))continue;let $=(R.connected_source_port_ids??[]).map(j=>g.get(j)).filter(j=>!!j&&_.has(j));if($.length>=2){let[j,H]=$.slice(0,2),X=[j,H].sort().join("::");if(!E.has(X)){E.set(X,R.source_trace_id);let G=R.display_name??R.source_trace_id;R.subcircuit_connectivity_map_key&&(o.add(R.subcircuit_connectivity_map_key),x.set(G,R.subcircuit_connectivity_map_key),i.set(R.subcircuit_connectivity_map_key,G)),I.push({pinIds:[j,H].map(tt=>d.get(tt)),netId:G})}}}let M=[];for(let R of t.source_net.list().filter($=>!$.subcircuit_id||w.has($.subcircuit_id)))R.subcircuit_connectivity_map_key&&(o.add(R.subcircuit_connectivity_map_key),n.set(R.subcircuit_connectivity_map_key,R));let k=new Map;for(let[R,$]of y){let j=t.source_port.get($);if(!j?.subcircuit_connectivity_map_key)continue;let H=j.subcircuit_connectivity_map_key;o.add(H),k.has(H)||k.set(H,[]),k.get(H).push(R)}for(let[R,$]of k){let j=n.get(R);if(j&&$.length>=2){let H=String(j.name||j.source_net_id||R);x.set(H,R),i.set(R,H);let G=.1*(.18/.18),tt=Number((String(H).length*G).toFixed(2));M.push({netId:H,pinIds:$.map(Q=>d.get(Q)),netLabelWidth:tt})}}let N=(()=>{let R={},$=new Set(M.map(j=>j.netId));for(let j of t.source_net.list().filter(H=>!H.subcircuit_id||w.has(H.subcircuit_id)))j.name&&$.has(j.name)&&(j.is_ground||j.name.toLowerCase().startsWith("gnd")?R[j.name]=["y-"]:j.is_power||j.name.toLowerCase().startsWith("v")?R[j.name]=["y+"]:R[j.name]=["x-","x+"]);return R})();return{inputProblem:{chips:u,directConnections:I,netConnections:M,availableNetLabelOrientations:N,maxMspPairDistance:e._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:h,pairKeyToSourceTraceId:E,sckToSourceNet:n,sckToUserNetId:i,userNetIdToSck:x,allSourceAndSchematicPortIdsInScope:_,schPortIdToSourcePortId:y,displayLabelTraces:s,allScks:o}}var no=1e-6;function fH(e){let t=Math.abs(e.to.x-e.from.x),n=Math.abs(e.to.y-e.from.y);return t>=n}function Lx(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function mH(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function _H(e,t,n){let i=Lx(e,t);if(i<no)return 0;let o=((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/((t.x-e.x)*(t.x-e.x)+(t.y-e.y)*(t.y-e.y));return Math.max(0,Math.min(1,o))*i}function Ex(e,t,n,i){return e*i-t*n}function aTt(e,t,n,i){let o={x:t.x-e.x,y:t.y-e.y},r={x:i.x-n.x,y:i.y-n.y},s=Ex(o.x,o.y,r.x,r.y),a={x:n.x-e.x,y:n.y-e.y},c=Ex(a.x,a.y,o.x,o.y);if(Math.abs(s)<no&&Math.abs(c)<no||Math.abs(s)<no&&Math.abs(c)>=no)return null;let l=Ex(a.x,a.y,r.x,r.y)/s,u=Ex(a.x,a.y,o.x,o.y)/s;return l<-no||l>1+no||u<-no||u>1+no?null:{x:e.x+l*o.x,y:e.y+l*o.y}}function cTt(e,t=no){if(e.length===0)return e;e.sort((o,r)=>o.start-r.start);let n=[],i={...e[0]};for(let o=1;o<e.length;o++){let r=e[o];r.start<=i.end+t?i.end=Math.max(i.end,r.end):(n.push(i),i={...r})}return n.push(i),n}function lTt(e,t,n){let i=Lx(e.from,e.to);if(i<no||t.length===0)return[e];let o=n/2,r=t.map(h=>({start:Math.max(0,h-o),end:Math.min(i,h+o)})).filter(h=>h.end-h.start>no),s=cTt(r),a=[],c=0,l={x:e.to.x-e.from.x,y:e.to.y-e.from.y},u=(h,d,_)=>{if(d-h<=no)return;let y=h/i,g=d/i;a.push({from:mH(e.from,e.to,y),to:mH(e.from,e.to,g),..._?{is_crossing:!0}:{}})};for(let h of s)h.start-c>no&&u(c,h.start,!1),u(h.start,h.end,!0),c=h.end;return i-c>no&&u(c,i,!1),a.length>0?a:[e]}function uTt(e,t={}){let n=t.crossSegmentLength??.075,i=t.tolerance??no,o=new Map,r=c=>`${c.traceIdx}:${c.edgeIdx}`,s=c=>e[c.traceIdx].edges[c.edgeIdx];for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=l.edges[u];for(let d=c;d<e.length;d++){let _=e[d];for(let y=d===c?u+1:0;y<_.edges.length;y++){let g=_.edges[y],x=aTt(h.from,h.to,g.from,g.to);if(!x)continue;let w=Lx(h.from,h.to),S=Lx(g.from,g.to);if(w<i||S<i)continue;let T=_H(h.from,h.to,x),I=_H(g.from,g.to,x),E=T<=i||Math.abs(w-T)<=i||Number.isNaN(T),M=I<=i||Math.abs(S-I)<=i||Number.isNaN(I);if(!E&&!M){let k=fH(h),N=fH(g),A;if(k!==N)A=k;else{let j=Math.abs(h.to.x-h.from.x),H=Math.abs(h.to.y-h.from.y),X=Math.abs(g.to.x-g.from.x),G=Math.abs(g.to.y-g.from.y),tt=j-H,Q=X-G;A=tt===Q?!0:tt>Q}let R=r({traceIdx:A?c:d,edgeIdx:A?u:y}),$=o.get(R)??[];$.push(A?T:I),o.set(R,$)}}}}}let a=e.map(c=>({source_trace_id:c.source_trace_id,edges:[]}));for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=r({traceIdx:c,edgeIdx:u}),d=o.get(h)??[];if(d.length===0){a[c].edges.push(l.edges[u]);continue}let _=Array.from(new Set(d.map(g=>Number(g.toFixed(6))))).sort((g,x)=>g-x),y=lTt(l.edges[u],_,n);a[c].edges.push(...y)}}return a}var fs=1e-6;function Fx(e,t,n=fs){return Math.abs(e-t)<=n}function Gh(e,t,n=fs){return Fx(e.x,t.x,n)&&Fx(e.y,t.y,n)}function yH(e,t,n,i=fs){let o=Math.min(t.x,n.x)-i,r=Math.max(t.x,n.x)+i,s=Math.min(t.y,n.y)-i,a=Math.max(t.y,n.y)+i;return e.x<o||e.x>r||e.y<s||e.y>a?!1:Math.abs((n.x-t.x)*(e.y-t.y)-(n.y-t.y)*(e.x-t.x))<=i}function gH(e,t=fs){let n=new Map;for(let i of e){let o=`${i.x.toFixed(6)},${i.y.toFixed(6)}`;n.has(o)||n.set(o,i)}return Array.from(n.values())}function bH(e){return{x:e.to.x-e.from.x,y:e.to.y-e.from.y}}function w4(e,t,n=fs){let i=bH(e),o=bH(t),r=Math.hypot(i.x,i.y),s=Math.hypot(o.x,o.y);if(r<n||s<n)return!0;let a=i.x*o.y-i.y*o.x;return Math.abs(a)<=n*r*s}function km(e,t,n=fs){return e.edges.filter(i=>Gh(i.from,t,n)||Gh(i.to,t,n))}function xH(e,t,n=fs){for(let i of e.edges){if(Gh(i.from,t,n))return i.from;if(Gh(i.to,t,n))return i.to}return null}function pTt(e,t,n=fs){let i=Gh(e.from,t,n)||Fx(e.from.x,t.x,n)&&Fx(e.from.y,t.y,n)?e.to:e.from,o=i.x-t.x,r=i.y-t.y;return Math.abs(o)<n&&Math.abs(r)<n?null:Math.abs(o)>=Math.abs(r)?o>=0?"right":"left":r>=0?"up":"down"}function $h(e,t,n=fs){let i=km(e,t,n);if(i.length<2)return null;let o=i.map(h=>pTt(h,t,n)),r=o.includes("up"),s=o.includes("down"),a=o.includes("left"),c=o.includes("right"),l=r?"up":s?"down":null,u=c?"right":a?"left":null;return l&&u?`${l}-${u}`:null}function hTt(e,t={}){let n=t.tolerance??fs,i={};for(let r of e)i[r.source_trace_id]=[];let o=e.map(r=>{let s=[];for(let a of r.edges)s.push(a.from,a.to);return gH(s,n)});for(let r=0;r<e.length;r++){let s=e[r],a=o[r];for(let c=r+1;c<e.length;c++){let l=e[c],u=o[c];for(let h of a)for(let d of u)if(Gh(h,d,n)){let _=km(s,h,n),y=km(l,d,n),g=_.some(T=>y.some(I=>!w4(T,I,n))),x=$h(s,h,n),w=$h(l,d,n);g&&!(x!==null&&w!==null&&x===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(d))}for(let h of a)for(let d of l.edges)if(yH(h,d.from,d.to,n)){let y=km(s,h,n).some(T=>!w4(T,d,n)),g=$h(s,h,n),x=xH(l,h,n*1e3),w=x?$h(l,x,n):null;y&&!(g!==null&&w!==null&&g===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(h))}for(let h of u)for(let d of s.edges)if(yH(h,d.from,d.to,n)){let y=km(l,h,n).some(T=>!w4(d,T,n)),g=$h(l,h,n),x=xH(s,h,n*1e3),w=x?$h(s,x,n):null;y&&!(w!==null&&g!==null&&w===g)&&(i[l.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[s.source_trace_id].push(h))}}}for(let r of Object.keys(i))i[r]=gH(i[r],n);return i}var P4=(0,ZH.default)("Group_doInitialSchematicTraceRender");function dTt(e){let{group:t,solver:n,pinIdToSchematicPortId:i,userNetIdToSck:o}=e,{db:r}=t.root,s=n.traceCleanupSolver?.getOutput().traces??n.traceLabelOverlapAvoidanceSolver?.getOutput().traces??n.schematicTraceLinesSolver?.solvedTracePaths,a=[];P4(`Traces inside SchematicTraceSolver output: ${(s??[]).length}`);for(let u of s??[]){let h=u?.tracePath;if(!Array.isArray(h)||h.length<2){P4(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let d=[];for(let g=0;g<h.length-1;g++)d.push({from:{x:h[g].x,y:h[g].y},to:{x:h[g+1].x,y:h[g+1].y}});let _=null,y;if(Array.isArray(u?.pins)&&u.pins.length===2){let g=i.get(u.pins[0]?.pinId),x=i.get(u.pins[1]?.pinId);if(g&&x){for(let w of[g,x])r.schematic_port.get(w)&&r.schematic_port.update(w,{is_connected:!0});y=o.get(String(u.userNetId))}}_||(_=`solver_${u?.mspPairId}`,y=o.get(String(u.userNetId))),a.push({source_trace_id:_,edges:d,subcircuit_connectivity_map_key:y})}P4(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=uTt(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=hTt(c);for(let u of c)r.schematic_trace.insert({source_trace_id:u.source_trace_id,edges:u.edges,junctions:l[u.source_trace_id]??[],subcircuit_connectivity_map_key:a.find(h=>h.source_trace_id===u.source_trace_id)?.subcircuit_connectivity_map_key})}var fTt=e=>{switch(e){case"x+":return"left";case"x-":return"right";case"y+":return"bottom";case"y-":return"top";case"left":return"right";case"top":return"bottom";case"right":return"left";case"bottom":return"top"}},mTt=e=>{for(let n of e){let i=n._getDirectlyConnectedTraces();for(let o of i){let r=o._parsedProps.schDisplayLabel;if(r)return{name:r,wasAssignedDisplayLabel:!0}}}return{name:e.map(n=>n._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},I4=(0,KH.default)("Group_doInitialSchematicTraceRender");function _Tt(e){let{group:t,solver:n,sckToSourceNet:i,allScks:o,allSourceAndSchematicPortIdsInScope:r,schPortIdToSourcePortId:s,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=e,{db:h}=t.root,d=n.netLabelPlacementSolver?.netLabelPlacements??n.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],_=n.mspConnectionPairSolver.globalConnMap;for(let y of d){I4(`processing placement: ${y.netId}`);let g=_.getIdsConnectedToNet(y.globalConnNetId).find(R=>a.get(R)),x=a.get(g),w=y.anchorPoint,S=y.orientation,T=fTt(S),I=x?i.get(x):void 0,E=y.pinIds.map(R=>c.get(R));if(E.some(R=>l.has(R))){I4(`skipping net label placement for "${y.netId}" REASON:schematic port has pre-existing net label`);continue}if(I){let R=I.name,$=Ic({anchor_position:w,anchor_side:T,text:R});h.schematic_net_label.insert({text:R,anchor_position:w,center:$,anchor_side:T,...I?.source_net_id?{source_net_id:I.source_net_id}:{}});continue}let M=t.selectAll("port").filter(R=>R._getSubcircuitConnectivityKey()===x),{name:k,wasAssignedDisplayLabel:N}=mTt(M);if(!N&&E.some(R=>u.has(R))){I4(`skipping net label placement for "${y.netId}" REASON:schematic port has routed traces and no display label`);continue}let A=Ic({anchor_position:w,anchor_side:T,text:k});h.schematic_net_label.insert({text:k,anchor_position:w,center:A,anchor_side:T})}}var yTt=({allSourceAndSchematicPortIdsInScope:e,group:t,schPortIdToSourcePortId:n,sckToSourceNet:i,pinIdToSchematicPortId:o,schematicPortIdsWithPreExistingNetLabels:r})=>{let{db:s}=t.root;for(let a of Array.from(e)){let c=s.schematic_port.get(a);if(!c||c.is_connected)continue;let l=n.get(a);if(!l)continue;let h=s.source_port.get(l)?.subcircuit_connectivity_map_key;if(!h)continue;let d=i.get(h);if(!d||s.schematic_net_label.list().some(w=>Math.abs(w.anchor_position.x-c.center.x)<.1&&Math.abs(w.anchor_position.y-c.center.y)<.1?d.source_net_id&&w.source_net_id?w.source_net_id===d.source_net_id:w.text===(d.name||h):!1))continue;let y=d.name||d.source_net_id||h,g=Lm(c.facing_direction||"right")||"right",x=Ic({anchor_position:c.center,anchor_side:g,text:y});s.schematic_net_label.insert({text:y,anchor_position:c.center,center:x,anchor_side:g,...d.source_net_id?{source_net_id:d.source_net_id}:{}})}},gTt=e=>{let t=new Set,n=e.selectAll("netlabel");for(let i of n){let o=i._getConnectedPorts();for(let r of o)r.schematic_port_id&&t.add(r.schematic_port_id)}return t},bTt=({solver:e,pinIdToSchematicPortId:t})=>{let n=e.schematicTraceLinesSolver.solvedTracePaths,i=new Set;for(let o of n)for(let r of o.pinIds){let s=t.get(r);s&&i.add(s)}return i},xTt=(0,WH.default)("Group_doInitialSchematicTraceRender"),vTt=e=>{if(!e.root?._featureMspSchematicTraceRouting||!e.isSubcircuit||e.root?.schematicDisabled)return;let{inputProblem:t,pinIdToSchematicPortId:n,pairKeyToSourceTraceId:i,sckToSourceNet:o,allSourceAndSchematicPortIdsInScope:r,schPortIdToSourcePortId:s,displayLabelTraces:a,allScks:c,userNetIdToSck:l}=sTt(e),u=gTt(e);xTt.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(t,null,2)});let h=new bX(t);h.solve();let d=bTt({solver:h,pinIdToSchematicPortId:n});dTt({group:e,solver:h,pinIdToSchematicPortId:n,userNetIdToSck:l}),_Tt({group:e,solver:h,sckToSourceNet:o,allSourceAndSchematicPortIdsInScope:r,schPortIdToSourcePortId:s,pinIdToSchematicPortId:n,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:d}),yTt({group:e,allSourceAndSchematicPortIdsInScope:r,schPortIdToSourcePortId:s,sckToSourceNet:o,pinIdToSchematicPortId:n,schematicPortIdsWithPreExistingNetLabels:u})},STt=()=>({async simulate(e){let t="spice-experiment-1",{circuit:n,tran:i}=SX(e);return{simulationResultCircuitJson:wX(i,n,t)}}}),sa=(0,JH.default)("tscircuit:core:Group_doInitialSimulationSpiceEngineRender");function wTt(e){if(!e.isSubcircuit)return;let{root:t}=e;if(!t)return;let n=e.selectAll("analogsimulation");if(n.length===0)return;let i={...t.platform?.spiceEngineMap};i.spicey||(i.spicey=STt());let o=t.db.toArray(),r;try{r=vX(o).toSpiceString(),sa(`Generated SPICE string:
|
|
250
250
|
${r}`)}catch(s){sa(`Failed to convert circuit JSON to SPICE: ${s}`);return}for(let s of n){let a=s._parsedProps.spiceEngine??"spicey",c=i[a];if(!c)throw new Error(`SPICE engine "${a}" not found in platform config. Available engines: ${JSON.stringify(Object.keys(i).filter(u=>u!=="spicey"))}`);let l=`spice-simulation-${a}-${s.source_component_id}`;sa(`Queueing simulation for spice engine: ${a} (id: ${l})`),e._queueAsyncEffect(l,async()=>{try{sa(`Running simulation with engine: ${a}`);let u=await c.simulate(r);sa(`Simulation completed, received ${u.simulationResultCircuitJson.length} elements`);let h=t.db.simulation_experiment.list()[0];if(!h){sa("No simulation experiment found, skipping result insertion");return}for(let d of u.simulationResultCircuitJson){d.type==="simulation_transient_voltage_graph"&&(d.simulation_experiment_id=h.simulation_experiment_id);let _=d.type;_&&t.db[_]?(t.db[_].insert(d),sa(`Inserted ${_} into database`)):(sa(`Warning: Unknown element type ${_}, adding to raw db`),t.db._addElement(d))}e._markDirty("SimulationSpiceEngineRender")}catch(u){sa(`Simulation failed for engine ${a}: ${u}`);let h=t.db.simulation_experiment.list()[0];t.db.simulation_unknown_experiment_error.insert({simulation_experiment_id:h?.simulation_experiment_id,error_type:"simulation_unknown_experiment_error",message:u instanceof Error?u.message:String(u)})}})}}function PTt(e){if(e.root?.pcbDisabled||!e.pcb_group_id)return;let t=e._parsedProps?.pcbPositionAnchor;if(!t)return;let n=e._getGlobalPcbPositionBeforeLayout(),{pcbX:i,pcbY:o}=e._parsedProps;if(i===void 0&&o===void 0)return;let{db:r}=e.root,s=r.pcb_group.get(e.pcb_group_id);if(!s)return;let a=s.width,c=s.height,{center:l}=s;if(s.outline&&s.outline.length>0){let g=ns(s.outline);g&&(a=g.maxX-g.minX,c=g.maxY-g.minY)}if(!a||!c)return;let u={left:l.x-a/2,right:l.x+a/2,top:l.y+c/2,bottom:l.y-c/2},h={...l},d=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(t))switch(t){case"center":d=h;break;case"top_left":d={x:u.left,y:u.top};break;case"top_center":d={x:h.x,y:u.top};break;case"top_right":d={x:u.right,y:u.top};break;case"center_left":d={x:u.left,y:h.y};break;case"center_right":d={x:u.right,y:h.y};break;case"bottom_left":d={x:u.left,y:u.bottom};break;case"bottom_center":d={x:h.x,y:u.bottom};break;case"bottom_right":d={x:u.right,y:u.bottom};break}if(!d)return;let y={...h};n.x!==void 0&&(y.x+=n.x-d.x),n.y!==void 0&&(y.y+=n.y-d.y),(Math.abs(y.x-h.x)>1e-6||Math.abs(y.y-h.y)>1e-6)&&(e._repositionOnPcb(y),r.pcb_group.update(e.pcb_group_id,{center:y})),r.pcb_group.update(e.pcb_group_id,{anchor_position:n,anchor_alignment:t})}var Tc=class extends On{constructor(){super(...arguments);P(this,"pcb_group_id",null);P(this,"schematic_group_id",null);P(this,"subcircuit_id",null);P(this,"_hasStartedAsyncAutorouting",!1);P(this,"_asyncAutoroutingResult",null);P(this,"unnamedElementCounter",{})}get config(){return{zodProps:mz,componentName:"Group"}}doInitialSourceGroupRender(){let{db:t}=this.root,n=typeof this._parsedProps.name=="string"&&this._parsedProps.name.length>0,i=t.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit,was_automatically_named:!n});this.source_group_id=i.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${i.source_group_id}`,t.source_group.update(i.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:t}=this.root;for(let n of this.children)t.source_component.update(n.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:t}=this.root,n=this.parent?.getGroup?.();if(n?.source_group_id&&t.source_group.update(this.source_group_id,{parent_source_group_id:n.source_group_id}),!this.isSubcircuit)return;let i=this.parent?.getSubcircuit?.()?.subcircuit_id;i&&t.source_group.update(this.source_group_id,{parent_subcircuit_id:i})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n,o=i.outline&&i.outline.length>0,r=o?i.outline.map(a=>({x:Y.parse(a.x),y:Y.parse(a.y)})):void 0,s=t.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),...o?{outline:r}:{width:0,height:0},pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:n.autorouter?{trace_clearance:n.autorouter.traceClearance}:void 0});this.pcb_group_id=s.pcb_group_id;for(let a of this.children)t.pcb_component.update(a.pcb_component_id,{pcb_group_id:s.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this._parsedProps,i=n.outline&&n.outline.length>0;if(this.pcb_group_id){let o=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0;if(i){let h=n.outline.map(x=>({x:Y.parse(x.x),y:Y.parse(x.y)})),d=ns(h);if(!d)return;let _=(d.minX+d.maxX)/2,y=(d.minY+d.maxY)/2,g=o?t.pcb_group.get(this.pcb_group_id)?.center??{x:_,y}:{x:_,y};t.pcb_group.update(this.pcb_group_id,{center:g});return}let r=$x(this.children),s=r.width,a=r.height,c=(r.minX+r.maxX)/2,l=(r.minY+r.maxY)/2;if(this.isSubcircuit){let{padLeft:h,padRight:d,padTop:_,padBottom:y}=this._resolvePcbPadding();s+=h+d,a+=_+y,c+=(d-h)/2,l+=(_-y)/2}let u=o?t.pcb_group.get(this.pcb_group_id)?.center??{x:c,y:l}:{x:c,y:l};t.pcb_group.update(this.pcb_group_id,{width:Number(n.width??s),height:Number(n.height??a),center:u})}}getNextAvailableName(t){var n,i;return(n=this.unnamedElementCounter)[i=t.lowercaseComponentName]??(n[i]=1),`unnamed_${t.lowercaseComponentName}${this.unnamedElementCounter[t.lowercaseComponentName]++}`}_resolvePcbPadding(){let t=this._parsedProps,n=t.pcbLayout,i=h=>{let d=n?.[h],_=t[h];if(typeof d=="number")return d;if(typeof _=="number")return _},o=i("padding")??0,r=i("paddingX"),s=i("paddingY"),a=i("paddingLeft")??r??o,c=i("paddingRight")??r??o,l=i("paddingTop")??s??o,u=i("paddingBottom")??s??o;return{padLeft:a,padRight:c,padTop:l,padBottom:u}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:t}=this,{db:n}=this.root,i=t;if(!this.isSubcircuit)return;let o=i.manualEdits?.manual_trace_hints;if(o)for(let r of o)this.add(new B4({for:r.pcb_port_selector,offsets:r.offsets}))}doInitialSourceAddConnectivityMapKey(){$It(this)}_areChildSubcircuitsRouted(){let t=this.selectAll("group").filter(n=>n.isSubcircuit);for(let n of t)if(n._shouldRouteAsync()&&!n._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let t=this._getAutorouterConfig();return t.groupMode==="sequential-trace"?!1:!!(t.local&&t.groupMode==="subcircuit"||!t.local)}_hasTracesToRoute(){let t=(0,jh.default)("tscircuit:core:_hasTracesToRoute"),n=this.selectAll("trace");return t(`[${this.getString()}] has ${n.length} traces to route`),n.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:t}=this.root,n=(0,jh.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),i=this._parsedProps,o=this._getAutorouterConfig(),r=o.serverUrl,s=o.serverMode,a=(u,h)=>(n("fetching",u),h.headers&&(h.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(u,h)),c=this.root.db.toArray().filter(u=>u.type.startsWith("source_")||u.type.startsWith("pcb_"));if(s==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:h}=await a(`${r}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:R4({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(d=>d.json());this._asyncAutoroutingResult=h,this._markDirty("PcbTraceRender");return}let{autorouting_result:u}=await a(`${r}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:c,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());this._asyncAutoroutingResult=u,this._markDirty("PcbTraceRender");return}let{autorouting_job:l}=await a(`${r}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:c,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:o.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(u=>u.json());for(;;){let{autorouting_job:u}=await a(`${r}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());if(u.is_finished){let{autorouting_job_output:h}=await a(`${r}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(d=>d.json());this._asyncAutoroutingResult={output_pcb_traces:h.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(u.has_error){let h=new Em(`Autorouting job failed: ${JSON.stringify(u.error)}`);throw t.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,error_type:"pcb_autorouting_error",message:h.message}),h}await new Promise(h=>setTimeout(h,100))}}async _runLocalAutorouting(){let{db:t}=this.root,n=this._parsedProps,i=(0,jh.default)("tscircuit:core:_runLocalAutorouting");i(`[${this.getString()}] starting local autorouting`);let o=this._getAutorouterConfig(),r=this._isLaserPrefabAutorouter(o),{simpleRouteJson:s}=R4({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(i.enabled&&global.debugOutputArray?.push({name:`simpleroutejson-${this.props.name}.json`,obj:s}),i.enabled){let l=zf(s);l.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(l)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:s});let a;o.algorithmFn?a=await o.algorithmFn(s):a=new NIt(s,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity,useAssignableViaSolver:r});let c=new Promise((l,u)=>{a.on("complete",h=>{i(`[${this.getString()}] local autorouting complete`),l(h.traces)}),a.on("error",h=>{i(`[${this.getString()}] local autorouting error: ${h.error.message}`),u(h.error)})});a.on("progress",l=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...l})}),a.start();try{let l=await c;this._asyncAutoroutingResult={output_pcb_traces:l},this._markDirty("PcbTraceRender")}catch(l){let{db:u}=this.root;throw u.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:l instanceof Error?l.message:String(l)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:l instanceof Error?l.message:String(l)},simpleRouteJson:s}),l}finally{a.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let t=(0,jh.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){t(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}t(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){vTt(this)}updatePcbTraceRender(){let t=(0,jh.default)("tscircuit:core:updatePcbTraceRender");if(t(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(t(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:n}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){t(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){t(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:t}=this.root,{traces:n}=this._asyncAutoroutingResult.output_simple_route_json;if(n)for(let i of n){let o=t.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:t}=this._asyncAutoroutingResult;if(!t)return;let{db:n}=this.root;for(let i of t)if(i.type==="pcb_trace"){if(i.subcircuit_id=this.subcircuit_id,i.connection_name){let o=i.connection_name;i.source_trace_id=o}n.pcb_trace.insert(i)}for(let i of t)if(i.type!=="pcb_via"&&i.type==="pcb_trace")for(let o of i.route)o.route_type==="via"&&n.pcb_via.insert({pcb_trace_id:i.pcb_trace_id,x:o.x,y:o.y,hole_diameter:.3,outer_diameter:.6,layers:[o.from_layer,o.to_layer],from_layer:o.from_layer,to_layer:o.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=i.schematic_group_id;for(let o of this.children)o.schematic_component_id&&t.schematic_component.update(o.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){let t=this._parsedProps;if(t.schLayout?.layoutMode==="none"||t.schLayout?.layoutMode==="relative")return"relative";if(t.schLayout?.matchAdapt)return"match-adapt";if(t.schLayout?.flex)return"flex";if(t.schLayout?.grid)return"grid";if(t.schMatchAdapt)return"match-adapt";if(t.schFlex)return"flex";if(t.schGrid)return"grid";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";if(t.relative||t.schRelative)return"relative";let n=this.children.some(o=>{let r=o._parsedProps;return r?.schX!==void 0||r?.schY!==void 0}),i=(t.manualEdits?.schematic_placements?.length??0)>0;return!n&&!i?"match-adapt":"relative"}doInitialSchematicLayout(){let t=this._getSchematicLayoutMode();t==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),t==="grid"&&this._doInitialSchematicLayoutGrid(),t==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){FIt(this)}_doInitialSchematicLayoutMatchpack(){DIt(this)}_doInitialSchematicLayoutGrid(){jIt(this)}_doInitialSchematicLayoutFlex(){BIt(this)}_getPcbLayoutMode(){let t=this._parsedProps;if(t.pcbRelative)return"none";if(t.pcbLayout?.matchAdapt)return"match-adapt";if(t.pcbLayout?.flex)return"flex";if(t.pcbLayout?.grid)return"grid";if(t.pcbLayout?.pack)return"pack";if(t.pcbFlex)return"flex";if(t.pcbGrid)return"grid";if(t.pcbPack||t.pack)return"pack";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";let n=t.pcbX!==void 0||t.pcbY!==void 0,i=(t.manualEdits?.pcb_placements?.length??0)>0,o=this.children.reduce((r,s)=>{if(!s.pcb_component_id&&!s.pcb_group_id)return r;let a=s._parsedProps,c=a?.pcbX!==void 0||a?.pcbY!==void 0;return r+(c?0:1)},0);return!n&&!i&&o>1?"pack":"none"}doInitialPcbLayout(){let t=this._getPcbLayoutMode();t==="grid"?this._doInitialPcbLayoutGrid():t==="pack"?this._doInitialPcbLayoutPack():t==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){YIt(this)}_doInitialPcbLayoutPack(){oTt(this)}_doInitialPcbLayoutFlex(){rTt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._parsedProps;if(!n.border)return;let i=typeof n.schWidth=="number"?n.schWidth:void 0,o=typeof n.schHeight=="number"?n.schHeight:void 0,r=typeof n.schPadding=="number"?n.schPadding:0,s=typeof n.schPaddingLeft=="number"?n.schPaddingLeft:r,a=typeof n.schPaddingRight=="number"?n.schPaddingRight:r,c=typeof n.schPaddingTop=="number"?n.schPaddingTop:r,l=typeof n.schPaddingBottom=="number"?n.schPaddingBottom:r,u=this.schematic_group_id?t.schematic_group.get(this.schematic_group_id):null;if(u&&(i===void 0&&typeof u.width=="number"&&(i=u.width),o===void 0&&typeof u.height=="number"&&(o=u.height)),i===void 0||o===void 0)return;let h=u?.center??this._getGlobalSchematicPositionBeforeLayout(),d=h.x-i/2-s,_=h.y-o/2-l,y=i+s+a,g=o+c+l;t.schematic_box.insert({width:y,height:g,x:d,y:_,is_dashed:n.border?.dashed??!1})}_determineSideFromPosition(t,n){if(!t.center||!n.center)return"left";let i=t.center.x-n.center.x,o=t.center.y-n.center.y;return Math.abs(i)>Math.abs(o)?i>0?"right":"left":o>0?"bottom":"top"}_calculateSchematicBounds(t){if(t.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let n=1/0,i=-1/0,o=1/0,r=-1/0;for(let a of t)n=Math.min(n,a.centerX),i=Math.max(i,a.centerX),o=Math.min(o,a.centerY),r=Math.max(r,a.centerY);let s=2;return{minX:n-s,maxX:i+s,minY:o-s,maxY:r+s}}_getAutorouterConfig(){let t=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return JIt(t)}_isLaserPrefabAutorouter(t=this._getAutorouterConfig()){let n=this.props.autorouter,i=o=>o?.replace(/-/g,"_")??o;return t.preset==="laser_prefab"?!0:typeof n=="string"?i(n)==="laser_prefab":typeof n=="object"&&n?i(n.preset)==="laser_prefab":!1}_getSubcircuitLayerCount(){let t=this.getInheritedProperty("layers");return typeof t=="number"?t:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(this.isSubcircuit){let n=new Map;for(let i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){let o=n.get(i._parsedProps.name)||[];o.push(i),n.set(i._parsedProps.name,o)}for(let[i,o]of n.entries())o.length>1&&t.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:o.map(r=>r.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:t}=this.root,n=t;for(let i of n.schematic_net_label.list()){let o=n.source_net.get(i.source_net_id),r=i.text||o?.name||"";if(i.anchor_side==="top"&&/^gnd/i.test(r)){n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_down"});continue}i.anchor_side==="bottom"&&/^v/i.test(r)&&n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_up"})}}doInitialSimulationSpiceEngineRender(){wTt(this)}doInitialPcbComponentAnchorAlignment(){PTt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(t){return super._repositionOnPcb(t)}},ITt=.01,vH=(e,t,n)=>{let i=e/2,o=t/2,r=Math.min(n,i,o);if(r<ITt)return[{x:-i,y:-o},{x:i,y:-o},{x:i,y:o},{x:-i,y:o}];let a=Math.max(1,Math.ceil(Math.PI/2*r/.1)),c=Math.PI/2/a,l=[];l.push({x:-i+r,y:-o}),l.push({x:i-r,y:-o});for(let u=1;u<=a;u++){let h=-Math.PI/2+u*c;l.push({x:i-r+r*Math.cos(h),y:-o+r+r*Math.sin(h)})}l.push({x:i,y:o-r});for(let u=1;u<=a;u++){let h=0+u*c;l.push({x:i-r+r*Math.cos(h),y:o-r+r*Math.sin(h)})}l.push({x:-i+r,y:o});for(let u=1;u<=a;u++){let h=Math.PI/2+u*c;l.push({x:-i+r+r*Math.cos(h),y:o-r+r*Math.sin(h)})}l.push({x:-i,y:-o+r});for(let u=1;u<=a;u++){let h=Math.PI+u*c;l.push({x:-i+r+r*Math.cos(h),y:-o+r+r*Math.sin(h)})}return l},QH=class extends Tc{constructor(){super(...arguments);P(this,"pcb_board_id",null);P(this,"source_board_id",null);P(this,"_drcChecksComplete",!1);P(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:LI}}get boardThickness(){let{_parsedProps:t}=this;return t.thickness??1.4}get allLayers(){return(this._parsedProps.layers??2)===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db:t}=this.root,{_parsedProps:n}=this;if(n.width&&n.height||n.outline)return;let i=1/0,o=1/0,r=-1/0,s=-1/0,a=HH(t,this.subcircuit_id),c=new Set([this.subcircuit_id,...a]),l=t.pcb_component.list().filter(E=>E.subcircuit_id&&c.has(E.subcircuit_id)),u=t.pcb_group.list().filter(E=>E.subcircuit_id&&c.has(E.subcircuit_id)),h=!1,d=(E,M,k)=>{M===0||k===0||(h=!0,i=Math.min(i,E.x-M/2),o=Math.min(o,E.y-k/2),r=Math.max(r,E.x+M/2),s=Math.max(s,E.y+k/2))};for(let E of l)d(E.center,E.width,E.height);for(let E of u){let M=E.width??0,k=E.height??0;if(E.outline&&E.outline.length>0){let N=ns(E.outline);N&&(M=N.maxX-N.minX,k=N.maxY-N.minY)}d(E.center,M,k)}if(n.boardAnchorPosition){let{x:E,y:M}=n.boardAnchorPosition;i=Math.min(i,E),o=Math.min(o,M),r=Math.max(r,E),s=Math.max(s,M)}let _=2,y=h?r-i+_*2:0,g=h?s-o+_*2:0,x={x:h?(i+r)/2+(n.outlineOffsetX??0):n.outlineOffsetX??0,y:h?(o+s)/2+(n.outlineOffsetY??0):n.outlineOffsetY??0},w=n.width??y,S=n.height??g,T=n.outline;!T&&n.borderRadius!=null&&w>0&&S>0&&(T=vH(w,S,n.borderRadius));let I={width:w,height:S,center:x};T&&(I.outline=T.map(E=>({x:E.x+(n.outlineOffsetX??0),y:E.y+(n.outlineOffsetY??0)}))),t.pcb_board.update(this.pcb_board_id,I)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let t=this.root?.platform;if(!t?.printBoardInformationToSilkscreen)return;let n=this.root.db.pcb_board.get(this.pcb_board_id);if(!n)return;let i=[];if(t.projectName&&i.push(t.projectName),t.version&&i.push(`v${t.version}`),t.url&&i.push(t.url),i.length===0)return;let o=i.join(`
|
|
251
|
-
`),a={x:n.center.x+n.width/2-.25,y:n.center.y-n.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:o,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:t}=this.root,n=t.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=n.source_board_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.width??0,o=n.height??0,r={x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)},{boardAnchorPosition:s,boardAnchorAlignment:a}=n;if(s&&(r=EIt({boardAnchorPosition:s,boardAnchorAlignment:a??"center",width:i,height:o})),n.outline){let u=n.outline.map(x=>x.x),h=n.outline.map(x=>x.y),d=Math.min(...u),_=Math.max(...u),y=Math.min(...h),g=Math.max(...h);i=_-d,o=g-y,r={x:(d+_)/2+(n.outlineOffsetX??0),y:(y+g)/2+(n.outlineOffsetY??0)}}let c=n.outline;!c&&n.borderRadius!=null&&i>0&&o>0&&(c=vH(i,o,n.borderRadius));let l=t.pcb_board.insert({center:r,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:o,outline:c?.map(u=>({x:u.x+(n.outlineOffsetX??0),y:u.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=l.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return zi()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let n=MX(t.toArray());for(let l of n)t.pcb_trace_error.insert(l);let i=TX(t.toArray());for(let l of i)t.pcb_port_not_connected_error.insert(l);let o=NX(t.toArray());for(let l of o)t.pcb_component_outside_board_error.insert(l);let r=RX(t.toArray());for(let l of r)t.pcb_trace_error.insert(l);let s=AX(t.toArray());for(let l of s)t.pcb_via_clearance_error.insert(l);let a=kX(t.toArray());for(let l of a)t.pcb_via_clearance_error.insert(l);let c=OX(t.toArray());for(let l of c)t.pcb_footprint_overlap_error.insert(l)}_emitRenderLifecycleEvent(t,n){super._emitRenderLifecycleEvent(t,n),n==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},tG=class extends Tc{get config(){return{componentName:"Panel",zodProps:_z}}get isGroup(){return!0}add(e){if(e.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(e)}runRenderCycle(){if(!this.children.some(e=>e.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}},TTt=new Proxy({},{get:(e,t)=>t}),la=TTt,jx="rgba(132, 0, 0)",Bx=.12,eG=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:Tz,sourceFtype:la.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let t=this.props.capacitance,n=typeof t=="string"?t:`${ni(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${ni(this._parsedProps.maxVoltageRating)}V`:n}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new $r({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new $r({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,capacitance:n.capacitance,max_voltage_rating:n.maxVoltageRating,max_decoupling_trace_length:n.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!n.polarized});this.source_component_id=i.source_component_id}},Fm=class extends On{constructor(t){super(t);P(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:Jp,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:n}=this;if(n.externallyConnectedPins){let i=new Set;for(let[o,r]of n.externallyConnectedPins)i.add(o),i.add(r);for(let o of i)if(!this.children.find(s=>s instanceof Ni&&s.isMatchingAnyOf([o]))){let s=o.match(/^pin(\d+)$/);if(s){let a=parseInt(s[1]);this.add(new Ni({pinNumber:a,aliases:[o]}))}else this.add(new Ni({name:o,aliases:[o]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.layer??"top";if(i!=="top"&&i!=="bottom"){let r=this.getSubcircuit(),s=Np.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${i}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:i,subcircuit_id:r.subcircuit_id??void 0});t.pcb_component_invalid_layer_error.insert(s)}let o=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:i==="top"||i==="bottom"?i:"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=o.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[n,i]of t.externallyConnectedPins)this.add(new $r({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:n}=this.props;if(!n)return;let i=null,o=null,r,s=this.selectAll("port");for(let h of s)for(let d of h.getNameAndAliases())if(n[d]){let _=n[d];_.providesPower&&(i=h,r=_.providesVoltage),_.providesGround&&(o=h)}if(!i||!o||r===void 0)return;let a=t.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=t.source_port.get(o.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=t.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=t.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||t.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:o.source_port_id,negative_source_net_id:u.source_net_id,voltage:r})}},nG=class extends Fm{constructor(e){super(e)}get config(){return{...super.config,componentName:"Pinout",zodProps:yz}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}},iG=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"anode",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},n=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"diode",componentName:"Diode",zodProps:Xz,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},oG=class extends On{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:bz,sourceFtype:la.simple_fuse}}_getSchematicSymbolDisplayValue(){let e=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,n=typeof e=="string"?parseFloat(e):e,i=typeof t=="string"?parseFloat(t):t;return`${ni(n)}A / ${ni(i)}V`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,i=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,o=e.source_component.insert({name:this.name,ftype:la.simple_fuse,current_rating_amps:n,voltage_rating_volts:i,display_current_rating:`${ni(n)}A`,display_voltage_rating:`${ni(i)}V`});this.source_component_id=o.source_component_id}},rG=class extends On{constructor(){super(...arguments);P(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:FI,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let o=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),r=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of o)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=r(a.start_pcb_port_id),a.end_pcb_port_id=r(a.end_pcb_port_id))}},sG=class extends On{constructor(){super(...arguments);P(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(t){return this.selectOne(`port.${t}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let t=this.children.filter(n=>n.componentName==="Port").map(n=>n.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,n=t.pinCount;if(t.pinCount==null&&!t.footprint&&(n=2),t.pinCount==null){let r=(t.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),s=r.length>0?Math.max(...r):0,a=t.pinLabels?Object.keys(t.pinLabels).length:0,c=Math.max(s,a);(c===2||c===3)&&(n=c),n==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(n=this.getPortsFromFootprint().length)}let i="";n?i+=`solderjumper${n}`:i="solderjumper";let o=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?o=Array.from(new Set(t.bridgedPins.flat().map(r=>this._getPinNumberFromBridgedPinName(r)).filter(r=>r!==null))).sort((r,s)=>r-s):t.bridged&&n&&(o=Array.from({length:n},(r,s)=>s+1)),o.length>0&&(i+=`_bridged${o.join("")}`),{schematicSymbolName:t.symbolName??i,componentName:"SolderJumper",zodProps:gz,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);n==null&&!this._parsedProps.footprint&&(n=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let o=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),r=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of o)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=r(a.start_pcb_port_id),a.end_pcb_port_id=r(a.end_pcb_port_id))}},aG=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"anode",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},n=this.props.laser?"laser":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"led",componentName:"Led",zodProps:Hz,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){let t=super.getFootprinterString();return t&&this.props.color?`${t}_color(${this.props.color})`:t}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:n.wavelength,color:n.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},cG=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"positive",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:rD,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Ni({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Ni({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},MTt=Dn.extend({voltage:ai.optional(),frequency:Wi.optional(),peakToPeakVoltage:ai.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Be.optional(),dutyCycle:p.number().optional()}),lG=class extends On{constructor(){super(...arguments);P(this,"terminal1",this.portMap.terminal1);P(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:MTt,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.portMap.terminal1,o=this.portMap.terminal2;t.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:o.source_port_id,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle})}},X4=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:vz,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${ni(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new $r({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new $r({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new $r({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new $r({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,resistance:n.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},CTt=["leftedge","rightedge","topedge","bottomedge","center"],uG=class extends xe{get config(){return{componentName:"Constraint",zodProps:Cz}}constructor(e){if(super(e),("xdist"in e||"ydist"in e)&&!("edgeToEdge"in e)&&!("centerToCenter"in e))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in e&&e.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let e=[],t=this.getPrimitiveContainer();function n(i){let o=i.split(" ").pop(),r=CTt.includes(o)?o:void 0,s=r?i.replace(` ${r}`,""):i,a=t.selectOne(s,{pcbPrimitive:!0});a&&e.push({selector:i,component:a,componentSelector:s,edge:r})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},pG=class extends xe{constructor(){super(...arguments);P(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:Wz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for FabricationNoteRect. Must be "top" or "bottom".`);let r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,s=this.getSubcircuit(),a=n.hasStroke??(n.strokeWidth!==void 0&&n.strokeWidth!==null),c=t.pcb_fabrication_note_rect.insert({pcb_component_id:r,layer:o,color:n.color,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,stroke_width:n.strokeWidth??1,is_filled:n.isFilled??!1,has_stroke:a,is_stroke_dashed:n.isStrokeDashed??!1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,corner_radius:n.cornerRadius??void 0});this.fabrication_note_rect_id=c.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},hG=class extends xe{constructor(){super(...arguments);P(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:Zz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this.getSubcircuit(),{_parsedProps:i}=this,o=i.layer??"top";if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenPath. Must be "top" or "bottom".`);let r=this._computePcbGlobalTransformBeforeLayout(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_fabrication_note_path.insert({pcb_component_id:s,layer:o,color:i.color,route:i.route.map(c=>{let l=Ne(r,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:n?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},dG=class extends xe{get config(){return{componentName:"FabricationNoteText",zodProps:qz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit();e.pcb_fabrication_note_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:t.pcbX??0,y:t.pcbY??0},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:"top",color:t.color,text:t.text??"",pcb_component_id:n.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},fG=class extends xe{constructor(){super(...arguments);P(this,"fabrication_note_dimension_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:Kz}}_resolvePoint(t,n){if(typeof t=="string"){let r=this.getSubcircuit().selectOne(t);return r?r._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${t}"`),Ne(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,o=typeof t.y=="string"?parseFloat(t.y):t.y;return Ne(n,{x:i,y:o})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this._resolvePoint(n.from,i),r=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(n.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for FabricationNoteDimension. Must be "top" or "bottom".`);let u=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,h=n.text??this._formatDistanceText({from:o,to:r,units:n.units??"mm"}),d=t.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:o,to:r,text:h,offset:n.offset,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.fabrication_note_dimension_id=d.pcb_fabrication_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}_formatDistanceText({from:t,to:n,units:i}){let o=n.x-t.x,r=n.y-t.y,s=Math.sqrt(o*o+r*r),a=i==="in"?s/25.4:s,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},mG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_line_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:ID}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),o=this.getGroup(),r=this._computePcbGlobalTransformBeforeLayout(),s=Ne(r,{x:n.x1,y:n.y1}),a=Ne(r,{x:n.x2,y:n.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,x1:s.x,y1:s.y,x2:a.x,y2:a.y,stroke_width:n.strokeWidth??.1,color:n.color,is_dashed:n.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:t}=this;return{width:Math.abs(t.x2-t.x1),height:Math.abs(t.y2-t.y1)}}},_G=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_rect_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:wD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=Ne(i,{x:0,y:0}),r=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,center:o,width:n.width,height:n.height,stroke_width:n.strokeWidth??.1,is_filled:n.isFilled??!1,has_stroke:n.hasStroke??!0,is_stroke_dashed:n.isStrokeDashed??!1,color:n.color,corner_radius:n.cornerRadius??void 0});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.width=="string"?parseFloat(t.width):t.width,i=typeof t.height=="string"?parseFloat(t.height):t.height;return{width:n,height:i}}},yG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_text_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:SD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=Ne(i,{x:0,y:0}),r=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_text.insert({pcb_component_id:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,font:n.font??"tscircuit2024",font_size:n.fontSize??1,text:n.text,anchor_position:o,anchor_alignment:n.anchorAlignment??"center",color:n.color});this.pcb_note_text_id=c.pcb_note_text_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.fontSize=="string"?parseFloat(t.fontSize):t.fontSize??1,i=n*.6;return{width:t.text.length*i,height:n}}},gG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_path_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:PD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this.getSubcircuit(),r=this.getGroup(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=typeof u=="string"?parseFloat(u):u,y=typeof h=="string"?parseFloat(h):h,g=Ne(i,{x:_,y});return{...d,x:g.x,y:g.y}}),c=t.pcb_note_path.insert({pcb_component_id:s,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,route:a,stroke_width:n.strokeWidth??.1,color:n.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:t}=this;if(t.route.length===0)return{width:0,height:0};let n=t.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=t.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),o=Math.min(...n),r=Math.max(...n),s=Math.min(...i),a=Math.max(...i);return{width:r-o,height:a-s}}},bG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_dimension_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:TD}}_resolvePoint(t,n){if(typeof t=="string"){let r=this.getSubcircuit().selectOne(`.${t}`);return r?r._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${t}"`),Ne(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,o=typeof t.y=="string"?parseFloat(t.y):t.y;return Ne(n,{x:i,y:o})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this._resolvePoint(n.from,i),r=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=n.text??this._formatDistanceText({from:o,to:r,units:n.units??"mm"}),u=t.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:o,to:r,text:l,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.pcb_note_dimension_id=u.pcb_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}_formatDistanceText({from:t,to:n,units:i}){let o=n.x-t.x,r=n.y-t.y,s=Math.sqrt(o*o+r*r),a=i==="in"?s/25.4:s,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},xG=(e,t)=>{let{injectionDb:n,normalComponent:i}=t;if(!i)return;let o=Vh({componentName:i.name,componentRotation:"0deg"},n.toArray().filter(r=>"pcb_component_id"in r&&r.pcb_component_id===e.pcb_component_id));i.addAll(o)};function ETt(e,t){let{injectionDb:n,subcircuit:i,groupsMap:o}=t,r=n.pcb_component.getWhere({source_component_id:e.source_component_id}),s=n.cad_component.getWhere({source_component_id:e.source_component_id}),a=new X4({name:e.name,resistance:e.resistance});r&&xG(r,{...t,normalComponent:a}),e.source_group_id&&o?.has(e.source_group_id)?o.get(e.source_group_id).add(a):i.add(a)}function NTt(e,t){let{injectionDb:n,subcircuit:i}=t;if(e.source_component_id!==null)return;let o=n.pcb_port.getWhere({source_port_id:e.source_port_id}),r=new Ni({name:e.name,pinNumber:e.pin_number});i.add(r),r.source_port_id=e.source_port_id;let s=i.root;if(s&&o){let{db:a}=s,c=a.pcb_port.insert({pcb_component_id:void 0,layers:o.layers,subcircuit_id:i.subcircuit_id??void 0,pcb_group_id:i.getGroup()?.pcb_group_id??void 0,x:o.x,y:o.y,source_port_id:e.source_port_id,is_board_pinout:!1});r.pcb_port_id=c.pcb_port_id}}function kTt(e,t){let{subcircuit:n,groupsMap:i}=t,o=new Tc({name:e.name});return o.source_group_id=e.source_group_id,n.add(o),i&&i.set(e.source_group_id,o),o}var ATt=(e,t)=>{if(!e||e.length===0)return;let{injectionDb:n}=t,i=e.map(o=>o.map(r=>{let s=n.source_port.get(r);return s?s.pin_number!==void 0&&s.pin_number!==null?`pin${s.pin_number}`:s.name:null}).filter(r=>r!==null)).filter(o=>o.length>0);return i.length>0?i:void 0},RTt=(e,t)=>{let{injectionDb:n,subcircuit:i,groupsMap:o}=t,r=n.pcb_component.getWhere({source_component_id:e.source_component_id}),s=n.schematic_component.getWhere({source_component_id:e.source_component_id}),a=n.cad_component.getWhere({source_component_id:e.source_component_id}),c=ATt(e.internally_connected_source_port_ids,t),l=new Fm({name:e.name,manufacturerPartNumber:e.manufacturer_part_number,supplierPartNumbers:e.supplier_part_numbers??void 0,pinLabels:s?.port_labels??void 0,schWidth:s?.size?.width,schHeight:s?.size?.height,schPinSpacing:s?.pin_spacing,schX:s?.center?.x,schY:s?.center?.y,layer:r?.layer,pcbX:r?.center?.x,pcbY:r?.center?.y,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds,internallyConnectedPins:c}),u=a?.footprinter_string??"soic8";u&&(Object.assign(l.props,{footprint:u}),Object.assign(l._parsedProps,{footprint:u}),a||l._addChildrenFromStringFootprint?.()),r&&xG(r,{...t,normalComponent:l}),e.source_group_id&&o?.has(e.source_group_id)?o.get(e.source_group_id).add(l):i.add(l)},vG=class extends Tc{constructor(e){super({...e,subcircuit:!0})}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:e,children:t}=this._parsedProps;if(!e)return;let n=Ge(e);if(e&&t?.length>0)throw new Error("Subcircuit cannot have both circuitJson and children");let o={injectionDb:n,subcircuit:this,groupsMap:new Map},r=n.source_group.list();for(let c of r)kTt(c,o);let s=n.source_component.list();for(let c of s)switch(c.ftype){case"simple_resistor":ETt(c,o);break;case"simple_chip":RTt(c,o);break;default:throw new Error(`No inflator implemented for source component ftype: "${c.ftype}"`)}let a=n.source_port.list();for(let c of a)NTt(c,o)}},SG=class extends Tc{constructor(e){super({...e,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let n=e.pcb_group.get(this.pcb_group_id),i=t.paddingLeft??t.padding??0,o=t.paddingRight??t.padding??0,r=t.paddingTop??t.padding??0,s=t.paddingBottom??t.padding??0;e.pcb_group.update(this.pcb_group_id,{width:(n.width??0)+i+o,height:(n.height??0)+r+s,center:{x:n.center.x+(o-i)/2,y:n.center.y+(r-s)/2}})}},wG=class extends xe{constructor(){super(...arguments);P(this,"pcb_breakout_point_id",null);P(this,"matchedPort",null);P(this,"matchedNet",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:tD}}_matchConnection(){let{connection:t}=this._parsedProps,n=this.getSubcircuit();n&&(this.matchedPort=n.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=n.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(o=>o.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(o=>o.connected_source_port_ids.includes(t.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;this._matchConnection();let{pcbX:n=0,pcbY:i=0}=this._parsedProps,o=this.parent?.getGroup(),r=this.getSubcircuit();if(!o||!o.pcb_group_id)return;let s=t.pcb_breakout_point.insert({pcb_group_id:o.pcb_group_id,subcircuit_id:r?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:n,y:i});this.pcb_breakout_point_id=s.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:n=0}=this._parsedProps;return{center:{x:t,y:n},bounds:{left:t,top:n,right:t,bottom:n},width:0,height:0}}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_breakout_point_id&&n.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},PG=class extends xe{constructor(){super(...arguments);P(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:zz}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),o=this._getConnectedPorts();if(o.length===0)return"right";let r=o[0]._getGlobalSchematicPositionBeforeLayout(),s=r.x-i.x,a=r.y-i.y;if(Math.abs(s)>Math.abs(a)){if(s>0)return"right";if(s<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let n=[];for(let i of t){let o=this.getSubcircuit().selectOne(i);o&&n.push(o)}return n}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let n=this._getConnectedPorts();if(n.length>0){let i=n[0]._getGlobalSchematicPositionBeforeLayout(),o=Ne(this.parent?.computeSchematicGlobalTransform?.()??zi(),{x:0,y:0});return vn(i.x-o.x,i.y-o.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),r=n.anchorSide??"right",s=Ic({anchor_position:i,anchor_side:r,text:n.net}),a=t.schematic_net_label.insert({text:n.net,source_net_id:o.source_net_id,anchor_position:i,center:s,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo??t.connection;if(Array.isArray(n))return n;if(typeof n=="string")return[n]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&zx(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let n of t)this.add(new $r({from:n,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._resolveConnectsTo();if(!n||n.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),o=this._getAnchorSide(),s={left:"x-",right:"x+",top:"y+",bottom:"y-"}[o],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of n){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id??""));if(w&&(u=t.schematic_trace.list().some(S=>S.source_trace_id===w.source_trace_id)),u)continue}let h=l._getGlobalSchematicPositionAfterLayout(),d=E4(l.facingDirection??"right")??"x+",_=oc({x:h.x,y:h.y,facingDirection:d},{x:i.x,y:i.y,facingDirection:s});if(!Array.isArray(_)||_.length<2)continue;let y=[];for(let w=0;w<_.length-1;w++)y.push({from:{x:_[w].x,y:_[w].y},to:{x:_[w+1].x,y:_[w+1].y}});let g,x;if(a?.source_net_id&&l.source_port_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id));g=w?.source_trace_id,x=w?.subcircuit_connectivity_map_key||t.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}t.schematic_trace.insert({source_trace_id:g,edges:y,junctions:[],subcircuit_connectivity_map_key:x}),t.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},IG=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_circle_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:xD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenCircle. Must be "top" or "bottom".`);let r=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:o,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},TG=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_rect_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:bD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenRect. Must be "top" or "bottom".`);let r=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_rect.insert({pcb_component_id:s,layer:o,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1,is_filled:n.filled??!1,corner_radius:n.cornerRadius??void 0});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},MG=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_line_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:gD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenLine. Must be "top" or "bottom".`);let r=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_line.insert({pcb_component_id:s,layer:o,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:r?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},CG=class extends xe{constructor(t){super(t);P(this,"pcb_via_id",null);P(this,"matchedPort",null);P(this,"isPcbPrimitive",!0);P(this,"source_manually_placed_via_id",null);let n=this._getLayers();this._parsedProps.layers=n,this.initPorts()}get config(){return{componentName:"Via",zodProps:Jz}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}_getLayers(){let{fromLayer:t="top",toLayer:n="bottom"}=this._parsedProps;return t===n?[t]:[t,n]}initPorts(){let t=this._parsedProps.layers;for(let i of t){let o=new Ni({name:i,layer:i});o.registerMatch(this),this.add(o)}let n=new Ni({name:"pin1"});n.registerMatch(this),this.add(n)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),o=this.getSubcircuit(),r=t.pcb_component.insert({center:i,width:n.outerDiameter,height:n.outerDiameter,layer:n.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:o?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=r.pcb_component_id}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getGroup(),o=this.getSubcircuit(),r=t.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:n.net??"",subcircuit_id:o?.subcircuit_id??void 0});this.source_component_id=r.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),o=this.getSubcircuit(),r=t.pcb_via.insert({x:i.x,y:i.y,hole_diameter:n.holeDiameter,outer_diameter:n.outerDiameter,layers:["bottom","top"],from_layer:n.fromLayer||"bottom",to_layer:n.toLayer||"top",subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,net_is_assignable:n.netIsAssignable??void 0});this.pcb_via_id=r.pcb_via_id}},EG=class extends xe{constructor(){super(...arguments);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:nD}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;zx(this,[t.connectsTo])}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit().selectOne(n.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${n.connectsTo}" not found for copper pour`);return}let o=this.getSubcircuit(),r=t.toArray().filter(h=>h.type==="source_net"&&h.name===i.name)[0]||"",s=n.clearance??.2,a=DX(t.toArray(),{layer:n.layer,pour_connectivity_key:r.subcircuit_connectivity_map_key||"",pad_margin:n.padMargin??s,trace_margin:n.traceMargin??s,board_edge_margin:n.boardEdgeMargin??s,cutout_margin:n.cutoutMargin??s}),c=new zX(a),{brep_shapes:l}=c.getOutput(),u=n.coveredWithSolderMask??!1;for(let h of l)t.pcb_copper_pour.insert({shape:"brep",layer:n.layer,brep_shape:h,source_net_id:i.source_net_id,subcircuit_id:o?.subcircuit_id??void 0,covered_with_solder_mask:u})})}},NG=class extends On{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:Lz,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:t.capacity,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},kG=class extends On{_getPcbRotationBeforeLayout(){let e=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+e}get config(){return{componentName:"PinHeader",zodProps:Fz,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,o=this._parsedProps.showSilkscreenPinLabels;if(e>0){let r;if(i)!t&&!n?r=`pinrow${e}_p${i}`:r=`pinrow${e}_p${i}_id${t}_od${n}`;else if(!t&&!n)r=`pinrow${e}`;else return null;return o!==!0&&(r+="_nopinlabels"),r}return null}initPorts(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let t=1;t<=e;t++){let n=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[t-1]:this._parsedProps.pinLabels?.[`pin${t}`];if(n){let i=Array.isArray(n)?n[0]:n,o=Array.isArray(n)?n.slice(1):[];this.add(new Ni({pinNumber:t,name:i,aliases:[`pin${t}`,...o]}))}else this.add(new Ni({pinNumber:t,name:`pin${t}`}))}}_getSchematicPortArrangement(){let e=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:n?.leftSide?.direction??"top-to-bottom",pins:n?.leftSide?.pins??Array.from({length:e},(i,o)=>`pin${o+1}`)}}:{rightSide:{direction:n?.rightSide?.direction??"top-to-bottom",pins:n?.rightSide?.pins??Array.from({length:e},(i,o)=>`pin${o+1}`)}}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:t.supplierPartNumbers,pin_count:t.pinCount,gender:t.gender,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function OTt(e){switch(e){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var AG=class extends On{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??OTt(this.props.pinVariant),zodProps:Iz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:n,are_pins_interchangeable:n==="no_ground"||n==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let e=`${ni(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ni(this._parsedProps.loadCapacitance)}F`:e}},RG=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:Yz,sourceFtype:la.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${ni(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({name:this.name,ftype:la.simple_inductor,inductance:n.inductance,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function LTt(e){switch(e){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var OG=class extends On{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??LTt(this.props.pinVariant),zodProps:wz,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${ni(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},LG=class extends On{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:Dz,sourceFtype:la.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let e=ti[this._getSchematicSymbolNameOrThrow()],t=e.ports.find(l=>l.labels.includes("1")),n=e.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),o=i.find(l=>l.props.pinNumber===1),r=i.find(l=>l.props.pinNumber===2),s=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;o.schematicSymbolPortDef=t,(!c||c.length===0)&&(r.schematicSymbolPortDef=n);for(let[l,u]of[[2,r],[3,s],[4,a]]){let h=c?.find(([_,y])=>_===`pin${l}`||y===`pin${l}`);if(!h){u.schematicSymbolPortDef=n;break}(h?.[0]===`pin${l}`?h[1]:h?.[0])!=="pin1"&&(u.schematicSymbolPortDef=n)}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:la.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},FG=class extends On{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:Pz,sourceFtype:"simple_crystal"}}initPorts(){let e=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:e})}_getSchematicSymbolDisplayValue(){let e=`${ni(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ni(this._parsedProps.loadCapacitance)}F`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:t.frequency,load_capacitance:t.loadCapacitance,pin_variant:t.pinVariant||"two_pin",are_pins_interchangeable:(t.pinVariant||"two_pin")==="two_pin"});this.source_component_id=n.source_component_id}},zG=class extends On{constructor(){super(...arguments);P(this,"emitter",this.portMap.pin1);P(this,"collector",this.portMap.pin2);P(this,"base",this.portMap.pin3)}get config(){let t=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??t,zodProps:jz,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},DG=class extends On{get config(){let e=this.props.mosfetMode==="depletion"?"d":"e",n=`${this.props.channelType}_channel_${e}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??n,zodProps:Bz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}};function FTt(e){return e.simSwitchFrequency!==void 0||e.simCloseAt!==void 0||e.simOpenAt!==void 0||e.simStartClosed!==void 0||e.simStartOpen!==void 0}var $G=class extends On{_getSwitchType(){let e=this._parsedProps;return e?e.dpdt?"dpdt":e.spst?"spst":e.spdt?"spdt":e.dpst?"dpst":e.type??"spst":"spst"}get config(){let e=this._getSwitchType(),t=this._parsedProps?.isNormallyClosed??!1,n={spst:t?"spst_normally_closed_switch":"spst_switch",spdt:t?"spdt_normally_closed_switch":"spdt_switch",dpst:t?"dpst_normally_closed_switch":"dpst_switch",dpdt:t?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??n[e],zodProps:Uz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,t=this._parsedProps??{},n=e.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=n.source_component_id}doInitialSimulationRender(){let{_parsedProps:e}=this;if(!FTt(e))return;let{db:t}=this.root,n={type:"simulation_switch",source_component_id:this.source_component_id||""};e.simSwitchFrequency!==void 0&&(n.switching_frequency=Wi.parse(e.simSwitchFrequency)),e.simCloseAt!==void 0&&(n.closes_at=qi.parse(e.simCloseAt)),e.simOpenAt!==void 0&&(n.opens_at=qi.parse(e.simOpenAt)),e.simStartOpen!==void 0&&(n.starts_closed=!e.simStartOpen),e.simStartClosed!==void 0&&(n.starts_closed=e.simStartClosed),t.simulation_switch.insert(n)}},T4={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},jG=class extends On{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:Qz,sourceFtype:la.simple_test_point}}_getPropsWithDefaults(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}=this._parsedProps;return!n&&t&&(n="through_hole"),n??(n="through_hole"),e??(e="circle"),n==="pad"?e==="circle"?i??(i=T4.SMT_CIRCLE_DIAMETER):e==="rect"&&(o??(o=T4.SMT_RECT_SIZE),r??(r=o)):n==="through_hole"&&(t??(t=T4.HOLE_DIAMETER)),{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}}_getImpliedFootprintString(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}=this._getPropsWithDefaults();if(n==="through_hole")return`platedhole_d${t}`;if(n==="pad"){if(e==="circle")return`smtpad_circle_d${i}`;if(e==="rect")return`smtpad_rect_w${o}_h${r}`}throw new Error(`Footprint variant "${n}" with pad shape "${e}" not implemented`)}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{padShape:n,holeDiameter:i,footprintVariant:o,padDiameter:r,width:s,height:a}=this._getPropsWithDefaults(),c=e.source_component.insert({ftype:la.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:o,pad_shape:n,pad_diameter:r,hole_diameter:i,width:s,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},BG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:hD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:i.x,y:i.y},rotation:n.schRotation??0})}},YG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:pD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_line.insert({schematic_component_id:o,x1:n.x1+i.x,y1:n.y1+i.y,x2:n.x2+i.x,y2:n.y2+i.y,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=r.schematic_line_id}},XG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:uD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_rect.insert({center:{x:i.x,y:i.y},width:n.width,height:n.height,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_filled:n.isFilled,schematic_component_id:o,is_dashed:n.isDashed,rotation:n.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=r.schematic_rect_id}},VG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:aD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_arc.insert({schematic_component_id:o,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,start_angle_degrees:n.startAngleDegrees,end_angle_degrees:n.endAngleDegrees,direction:n.direction,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=r.schematic_arc_id}},HG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:lD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_circle.insert({schematic_component_id:o,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_filled:n.isFilled,fill_color:n.fillColor,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=r.schematic_circle_id}};function zTt({anchor:e,x:t,y:n,width:i,height:o,isInside:r}){switch(e){case"top_left":return{x:t,y:n+o,textAnchor:r?"top_left":"bottom_left"};case"top_center":return{x:t+i/2,y:n+o,textAnchor:r?"top_center":"bottom_center"};case"top_right":return{x:t+i,y:n+o,textAnchor:r?"top_right":"bottom_right"};case"center_left":return{x:t,y:n+o/2,textAnchor:r?"center_left":"center_right"};case"center":return{x:t+i/2,y:n+o/2,textAnchor:"center"};case"center_right":return{x:t+i,y:n+o/2,textAnchor:r?"center_right":"center_left"};case"bottom_left":return{x:t,y:n,textAnchor:r?"bottom_left":"top_left"};case"bottom_center":return{x:t+i/2,y:n,textAnchor:r?"bottom_center":"top_center"};case"bottom_right":return{x:t+i,y:n,textAnchor:r?"bottom_right":"top_right"};default:return{x:t+i/2,y:n+o,textAnchor:"center"}}}var GG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:cD,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=.6,o=typeof n.padding=="number"?n.padding:0,r=typeof n.paddingTop=="number"?n.paddingTop:o,s=typeof n.paddingBottom=="number"?n.paddingBottom:o,a=typeof n.paddingLeft=="number"?n.paddingLeft:o,c=typeof n.paddingRight=="number"?n.paddingRight:o,l=n.overlay&&n.overlay.length>0,u=typeof n.width=="number"&&typeof n.height=="number",h,d,_,y,g,x;if(l){let S=n.overlay.map(J=>({selector:J,port:this.getSubcircuit().selectOne(J,{type:"port"})})).filter(({port:J})=>J!=null).map(({port:J})=>({position:J._getGlobalSchematicPositionAfterLayout()}));if(S.length===0)return;let T=S.map(J=>J.position.x),I=S.map(J=>J.position.y),E=Math.min(...T),M=Math.max(...T),k=Math.min(...I),N=Math.max(...I),A=M-E,R=N-k,$=A===0?i:0,j=R===0?i:0,H=a+$/2,X=c+$/2,G=r+j/2,tt=s+j/2,Q=E-H,V=M+X,rt=k-tt,et=N+G;h=V-Q,d=et-rt,_=Q+(n.schX??0),y=rt+(n.schY??0),g=_+h/2,x=y+d/2}else if(u){h=n.width,d=n.height;let w=this._getGlobalSchematicPositionBeforeLayout();g=w.x,x=w.y,_=g-h/2,y=x-d/2}else return;if(t.schematic_box.insert({height:d,width:h,x:_,y,is_dashed:n.strokeStyle==="dashed"}),n.title){let w=n.titleInside,S=.1,T=n.titleAlignment,I=zTt({anchor:T,x:_,y,width:h,height:d,isInside:w}),E,M,k=I.textAnchor;w?(E=T.includes("top")?-S:T.includes("bottom")?S:0,M=T.includes("left")?S:T.includes("right")?-S:0):(E=T.includes("top")?S:T.includes("bottom")?-S:0,M=T.includes("center_left")?-S:T.includes("center_right")?S:0);let N=I.x+M,A=I.y+E;t.schematic_text.insert({anchor:k,text:n.title,font_size:n.titleFontSize??.18,color:n.titleColor??"#000000",position:{x:N,y:A},rotation:0})}}},UG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:dD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.children.filter(d=>d.componentName==="SchematicRow");if(i.length===0)return;let o=[],r=0;for(let d of i){let _=d.children.filter(y=>y.componentName==="SchematicCell");r=Math.max(r,_.length)}for(let d=0;d<i.length;d++)o[d]=[];for(let d=0;d<i.length;d++){let y=i[d].children.filter(x=>x.componentName==="SchematicCell"),g=0;for(let x=0;x<y.length;x++){for(;o[d][g];)g++;let w=y[x],S=w._parsedProps.colSpan??1,T=w._parsedProps.rowSpan??1;for(let I=0;I<T;I++)for(let E=0;E<S;E++)o[d+I]||(o[d+I]=[]),o[d+I][g+E]=w;g+=S}}r=Math.max(0,...o.map(d=>d.length));let s=i.map((d,_)=>d._parsedProps.height??1),a=Array.from({length:r},(d,_)=>{let y=0;for(let g=0;g<i.length;g++){let x=o[g]?.[_];if(x){let w=x._parsedProps.text??x._parsedProps.children,S=x._parsedProps.width??(w?.length??2)*.5;S>y&&(y=S)}}return y||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=t.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:s,cell_padding:n.cellPadding,border_width:n.borderWidth,anchor:n.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,h=0;for(let d=0;d<i.length;d++){let _=0;for(let y=0;y<r;y++){let g=o[d]?.[y];if(g&&!u.has(g)){u.add(g);let x=g._parsedProps,w=x.rowSpan??1,S=x.colSpan??1,T=0;for(let E=0;E<S;E++)T+=a[y+E];let I=0;for(let E=0;E<w;E++)I+=s[d+E];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:d,end_row_index:d+w-1,start_column_index:y,end_column_index:y+S-1,text:x.text??x.children,center:{x:c.x+_+T/2,y:c.y-h-I/2},width:T,height:I,horizontal_align:x.horizontalAlign,vertical_align:x.verticalAlign,font_size:x.fontSize??n.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[y]&&(_+=a[y])}h+=s[d]}}},qG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:fD}}},WG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:mD}}},ZG=class extends xe{constructor(){super(...arguments);P(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:Oz}}},KG=class extends xe{get config(){return{componentName:"AnalogSimulation",zodProps:$z}}doInitialSimulationRender(){let{db:e}=this.root,{duration:t,timePerStep:n}=this._parsedProps,i=t||10,o=n||.01;e.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:o})}},JG=class extends xe{constructor(){super(...arguments);P(this,"simulation_voltage_probe_id",null)}get config(){return{componentName:"VoltageProbe",zodProps:sD}}doInitialSimulationRender(){let{db:t}=this.root,{connectsTo:n,name:i}=this._parsedProps,o=this.getSubcircuit();if(!o){this.renderError("VoltageProbe must be inside a subcircuit");return}let r=Array.isArray(n)?n:[n];if(r.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let s=r[0],a=o.selectOne(s,{type:"port"}),c=a?null:o.selectOne(s,{type:"net"});if(c&&c.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${s}" resolved to a non-net component "${c.componentName}".`);return}if(!a&&!c){this.renderError(`VoltageProbe could not find connection target "${s}"`);return}let{simulation_voltage_probe_id:l}=t.simulation_voltage_probe.insert({name:i??this.name,source_port_id:a?.source_port_id??void 0,source_net_id:c?.source_net_id??void 0,subcircuit_id:o.subcircuit_id||void 0});this.simulation_voltage_probe_id=l}},DTt={name:"@tscircuit/core",type:"module",version:"0.0.854",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"',"generate-test-plan":"bun run scripts/generate-test-plan.ts"},devDependencies:{"@biomejs/biome":"^1.8.3","@resvg/resvg-js":"^2.6.2","@tscircuit/capacity-autorouter":"^0.0.140","@tscircuit/checks":"^0.0.85","@tscircuit/circuit-json-util":"^0.0.72","@tscircuit/common":"^0.0.20","@tscircuit/copper-pour-solver":"^0.0.13","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.29","@tscircuit/miniflex":"^0.0.4","@tscircuit/ngspice-spice-engine":"^0.0.2","@tscircuit/props":"^0.0.397","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^v0.0.45","@tscircuit/solver-utils":"^0.0.3","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.304","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.16","circuit-to-svg":"^0.0.265",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6","eecircuit-engine":"^1.5.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.16",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.10","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.50","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Uh=class{constructor({platform:e,projectUrl:t}={}){P(this,"firstChild",null);P(this,"children");P(this,"db");P(this,"root",null);P(this,"isRoot",!0);P(this,"schematicDisabled",!1);P(this,"pcbDisabled",!1);P(this,"pcbRoutingDisabled",!1);P(this,"_featureMspSchematicTraceRouting",!0);P(this,"name");P(this,"platform");P(this,"projectUrl");P(this,"_hasRenderedAtleastOnce",!1);P(this,"_eventListeners",{});this.children=[],this.db=Le([]),this.root=this,this.platform=e,this.projectUrl=t,this.pcbDisabled=e?.pcbDisabled??!1}add(e){let t;(0,QG.isValidElement)(e)?t=CH(e):t=e,this.children.push(t)}setPlatform(e){this.platform={...this.platform,...e}}_getBoard(){let e=this.children.find(t=>t.componentName==="Board");if(e)return e}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");let e=this.children.filter(n=>n.lowercaseComponentName==="panel");if(e.length>1)throw new Error("Only one <panel> is allowed per circuit");if(e.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=e[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let t=new Tc({subcircuit:!0});t.parent=this,t.addAll(this.children),this.children=[t],this.firstChild=t}render(){this.firstChild||this._guessRootComponent();let{firstChild:e,db:t}=this;if(!e)throw new Error("RootCircuit has no root component");e.parent=this,e.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(t=>setTimeout(t,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(e=>e._hasIncompleteAsyncEffects()?!0:e.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(e){let t=await Promise.resolve().then(()=>(ZV(),WV)).catch(n=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
|
|
251
|
+
`),a={x:n.center.x+n.width/2-.25,y:n.center.y-n.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:o,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:t}=this.root,n=t.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=n.source_board_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.width??0,o=n.height??0,r={x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)},{boardAnchorPosition:s,boardAnchorAlignment:a}=n;if(s&&(r=EIt({boardAnchorPosition:s,boardAnchorAlignment:a??"center",width:i,height:o})),n.outline){let u=n.outline.map(x=>x.x),h=n.outline.map(x=>x.y),d=Math.min(...u),_=Math.max(...u),y=Math.min(...h),g=Math.max(...h);i=_-d,o=g-y,r={x:(d+_)/2+(n.outlineOffsetX??0),y:(y+g)/2+(n.outlineOffsetY??0)}}let c=n.outline;!c&&n.borderRadius!=null&&i>0&&o>0&&(c=vH(i,o,n.borderRadius));let l=t.pcb_board.insert({center:r,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:o,outline:c?.map(u=>({x:u.x+(n.outlineOffsetX??0),y:u.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=l.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return zi()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let n=MX(t.toArray());for(let l of n)t.pcb_trace_error.insert(l);let i=TX(t.toArray());for(let l of i)t.pcb_port_not_connected_error.insert(l);let o=NX(t.toArray());for(let l of o)t.pcb_component_outside_board_error.insert(l);let r=RX(t.toArray());for(let l of r)t.pcb_trace_error.insert(l);let s=AX(t.toArray());for(let l of s)t.pcb_via_clearance_error.insert(l);let a=kX(t.toArray());for(let l of a)t.pcb_via_clearance_error.insert(l);let c=OX(t.toArray());for(let l of c)t.pcb_footprint_overlap_error.insert(l)}_emitRenderLifecycleEvent(t,n){super._emitRenderLifecycleEvent(t,n),n==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},tG=class extends Tc{get config(){return{componentName:"Panel",zodProps:_z}}get isGroup(){return!0}add(e){if(e.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(e)}runRenderCycle(){if(!this.children.some(e=>e.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}},TTt=new Proxy({},{get:(e,t)=>t}),la=TTt,jx="rgba(132, 0, 0)",Bx=.12,eG=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:Tz,sourceFtype:la.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let t=this.props.capacitance,n=typeof t=="string"?t:`${ni(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${ni(this._parsedProps.maxVoltageRating)}V`:n}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new $r({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new $r({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,capacitance:n.capacitance,max_voltage_rating:n.maxVoltageRating,max_decoupling_trace_length:n.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!n.polarized});this.source_component_id=i.source_component_id}},Fm=class extends On{constructor(t){super(t);P(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:Jp,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:n}=this;if(n.externallyConnectedPins){let i=new Set;for(let[o,r]of n.externallyConnectedPins)i.add(o),i.add(r);for(let o of i)if(!this.children.find(s=>s instanceof Ni&&s.isMatchingAnyOf([o]))){let s=o.match(/^pin(\d+)$/);if(s){let a=parseInt(s[1]);this.add(new Ni({pinNumber:a,aliases:[o]}))}else this.add(new Ni({name:o,aliases:[o]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.layer??"top";if(i!=="top"&&i!=="bottom"){let r=this.getSubcircuit(),s=Np.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${i}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:i,subcircuit_id:r.subcircuit_id??void 0});t.pcb_component_invalid_layer_error.insert(s)}let o=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:i==="top"||i==="bottom"?i:"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=o.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[n,i]of t.externallyConnectedPins)this.add(new $r({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:n}=this.props;if(!n)return;let i=null,o=null,r,s=this.selectAll("port");for(let h of s)for(let d of h.getNameAndAliases())if(n[d]){let _=n[d];_.providesPower&&(i=h,r=_.providesVoltage),_.providesGround&&(o=h)}if(!i||!o||r===void 0)return;let a=t.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=t.source_port.get(o.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=t.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=t.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||t.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:o.source_port_id,negative_source_net_id:u.source_net_id,voltage:r})}},nG=class extends Fm{constructor(e){super(e)}get config(){return{...super.config,componentName:"Pinout",zodProps:yz}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}},iG=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"anode",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},n=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"diode",componentName:"Diode",zodProps:Xz,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},oG=class extends On{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:bz,sourceFtype:la.simple_fuse}}_getSchematicSymbolDisplayValue(){let e=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,n=typeof e=="string"?parseFloat(e):e,i=typeof t=="string"?parseFloat(t):t;return`${ni(n)}A / ${ni(i)}V`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,i=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,o=e.source_component.insert({name:this.name,ftype:la.simple_fuse,current_rating_amps:n,voltage_rating_volts:i,display_current_rating:`${ni(n)}A`,display_voltage_rating:`${ni(i)}V`});this.source_component_id=o.source_component_id}},rG=class extends On{constructor(){super(...arguments);P(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:FI,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let o=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),r=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of o)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=r(a.start_pcb_port_id),a.end_pcb_port_id=r(a.end_pcb_port_id))}},sG=class extends On{constructor(){super(...arguments);P(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(t){return this.selectOne(`port.${t}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let t=this.children.filter(n=>n.componentName==="Port").map(n=>n.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,n=t.pinCount;if(t.pinCount==null&&!t.footprint&&(n=2),t.pinCount==null){let r=(t.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),s=r.length>0?Math.max(...r):0,a=t.pinLabels?Object.keys(t.pinLabels).length:0,c=Math.max(s,a);(c===2||c===3)&&(n=c),n==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(n=this.getPortsFromFootprint().length)}let i="";n?i+=`solderjumper${n}`:i="solderjumper";let o=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?o=Array.from(new Set(t.bridgedPins.flat().map(r=>this._getPinNumberFromBridgedPinName(r)).filter(r=>r!==null))).sort((r,s)=>r-s):t.bridged&&n&&(o=Array.from({length:n},(r,s)=>s+1)),o.length>0&&(i+=`_bridged${o.join("")}`),{schematicSymbolName:t.symbolName??i,componentName:"SolderJumper",zodProps:gz,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);n==null&&!this._parsedProps.footprint&&(n=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let o=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),r=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of o)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=r(a.start_pcb_port_id),a.end_pcb_port_id=r(a.end_pcb_port_id))}},aG=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"anode",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},n=this.props.laser?"laser":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"led",componentName:"Led",zodProps:Hz,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){let t=super.getFootprinterString();return t&&this.props.color?`${t}_color(${this.props.color})`:t}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:n.wavelength,color:n.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},cG=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"positive",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:rD,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Ni({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Ni({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},MTt=Dn.extend({voltage:ai.optional(),frequency:Wi.optional(),peakToPeakVoltage:ai.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Be.optional(),dutyCycle:p.number().optional()}),lG=class extends On{constructor(){super(...arguments);P(this,"terminal1",this.portMap.terminal1);P(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:MTt,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.portMap.terminal1,o=this.portMap.terminal2;t.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:o.source_port_id,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle})}},X4=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:vz,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${ni(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new $r({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new $r({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new $r({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new $r({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,resistance:n.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},CTt=["leftedge","rightedge","topedge","bottomedge","center"],uG=class extends xe{get config(){return{componentName:"Constraint",zodProps:Cz}}constructor(e){if(super(e),("xdist"in e||"ydist"in e)&&!("edgeToEdge"in e)&&!("centerToCenter"in e))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in e&&e.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let e=[],t=this.getPrimitiveContainer();function n(i){let o=i.split(" ").pop(),r=CTt.includes(o)?o:void 0,s=r?i.replace(` ${r}`,""):i,a=t.selectOne(s,{pcbPrimitive:!0});a&&e.push({selector:i,component:a,componentSelector:s,edge:r})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},pG=class extends xe{constructor(){super(...arguments);P(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:Wz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for FabricationNoteRect. Must be "top" or "bottom".`);let r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,s=this.getSubcircuit(),a=n.hasStroke??(n.strokeWidth!==void 0&&n.strokeWidth!==null),c=t.pcb_fabrication_note_rect.insert({pcb_component_id:r,layer:o,color:n.color,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,stroke_width:n.strokeWidth??1,is_filled:n.isFilled??!1,has_stroke:a,is_stroke_dashed:n.isStrokeDashed??!1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,corner_radius:n.cornerRadius??void 0});this.fabrication_note_rect_id=c.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},hG=class extends xe{constructor(){super(...arguments);P(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:Zz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this.getSubcircuit(),{_parsedProps:i}=this,o=i.layer??"top";if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenPath. Must be "top" or "bottom".`);let r=this._computePcbGlobalTransformBeforeLayout(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_fabrication_note_path.insert({pcb_component_id:s,layer:o,color:i.color,route:i.route.map(c=>{let l=Ne(r,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:n?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},dG=class extends xe{get config(){return{componentName:"FabricationNoteText",zodProps:qz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit();e.pcb_fabrication_note_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:t.pcbX??0,y:t.pcbY??0},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:"top",color:t.color,text:t.text??"",pcb_component_id:n.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},fG=class extends xe{constructor(){super(...arguments);P(this,"fabrication_note_dimension_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:Kz}}_resolvePoint(t,n){if(typeof t=="string"){let r=this.getSubcircuit().selectOne(t);return r?r._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${t}"`),Ne(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,o=typeof t.y=="string"?parseFloat(t.y):t.y;return Ne(n,{x:i,y:o})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this._resolvePoint(n.from,i),r=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(n.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for FabricationNoteDimension. Must be "top" or "bottom".`);let u=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,h=n.text??this._formatDistanceText({from:o,to:r,units:n.units??"mm"}),d=t.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:o,to:r,text:h,offset:n.offset,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.fabrication_note_dimension_id=d.pcb_fabrication_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}_formatDistanceText({from:t,to:n,units:i}){let o=n.x-t.x,r=n.y-t.y,s=Math.sqrt(o*o+r*r),a=i==="in"?s/25.4:s,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},mG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_line_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:ID}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),o=this.getGroup(),r=this._computePcbGlobalTransformBeforeLayout(),s=Ne(r,{x:n.x1,y:n.y1}),a=Ne(r,{x:n.x2,y:n.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,x1:s.x,y1:s.y,x2:a.x,y2:a.y,stroke_width:n.strokeWidth??.1,color:n.color,is_dashed:n.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:t}=this;return{width:Math.abs(t.x2-t.x1),height:Math.abs(t.y2-t.y1)}}},_G=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_rect_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:wD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=Ne(i,{x:0,y:0}),r=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,center:o,width:n.width,height:n.height,stroke_width:n.strokeWidth??.1,is_filled:n.isFilled??!1,has_stroke:n.hasStroke??!0,is_stroke_dashed:n.isStrokeDashed??!1,color:n.color,corner_radius:n.cornerRadius??void 0});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.width=="string"?parseFloat(t.width):t.width,i=typeof t.height=="string"?parseFloat(t.height):t.height;return{width:n,height:i}}},yG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_text_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:SD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=Ne(i,{x:0,y:0}),r=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_text.insert({pcb_component_id:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,font:n.font??"tscircuit2024",font_size:n.fontSize??1,text:n.text,anchor_position:o,anchor_alignment:n.anchorAlignment??"center",color:n.color});this.pcb_note_text_id=c.pcb_note_text_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.fontSize=="string"?parseFloat(t.fontSize):t.fontSize??1,i=n*.6;return{width:t.text.length*i,height:n}}},gG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_path_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:PD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this.getSubcircuit(),r=this.getGroup(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=typeof u=="string"?parseFloat(u):u,y=typeof h=="string"?parseFloat(h):h,g=Ne(i,{x:_,y});return{...d,x:g.x,y:g.y}}),c=t.pcb_note_path.insert({pcb_component_id:s,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,route:a,stroke_width:n.strokeWidth??.1,color:n.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:t}=this;if(t.route.length===0)return{width:0,height:0};let n=t.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=t.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),o=Math.min(...n),r=Math.max(...n),s=Math.min(...i),a=Math.max(...i);return{width:r-o,height:a-s}}},bG=class extends xe{constructor(){super(...arguments);P(this,"pcb_note_dimension_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:TD}}_resolvePoint(t,n){if(typeof t=="string"){let r=this.getSubcircuit().selectOne(`.${t}`);return r?r._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${t}"`),Ne(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,o=typeof t.y=="string"?parseFloat(t.y):t.y;return Ne(n,{x:i,y:o})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this._resolvePoint(n.from,i),r=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=n.text??this._formatDistanceText({from:o,to:r,units:n.units??"mm"}),u=t.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:o,to:r,text:l,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.pcb_note_dimension_id=u.pcb_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}_formatDistanceText({from:t,to:n,units:i}){let o=n.x-t.x,r=n.y-t.y,s=Math.sqrt(o*o+r*r),a=i==="in"?s/25.4:s,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},xG=(e,t)=>{let{injectionDb:n,normalComponent:i}=t;if(!i)return;let o=Vh({componentName:i.name,componentRotation:"0deg"},n.toArray().filter(r=>"pcb_component_id"in r&&r.pcb_component_id===e.pcb_component_id));i.addAll(o)};function ETt(e,t){let{injectionDb:n,subcircuit:i,groupsMap:o}=t,r=n.pcb_component.getWhere({source_component_id:e.source_component_id}),s=n.cad_component.getWhere({source_component_id:e.source_component_id}),a=new X4({name:e.name,resistance:e.resistance});r&&xG(r,{...t,normalComponent:a}),e.source_group_id&&o?.has(e.source_group_id)?o.get(e.source_group_id).add(a):i.add(a)}function NTt(e,t){let{injectionDb:n,subcircuit:i}=t;if(e.source_component_id!==null)return;let o=n.pcb_port.getWhere({source_port_id:e.source_port_id}),r=new Ni({name:e.name,pinNumber:e.pin_number});i.add(r),r.source_port_id=e.source_port_id;let s=i.root;if(s&&o){let{db:a}=s,c=a.pcb_port.insert({pcb_component_id:void 0,layers:o.layers,subcircuit_id:i.subcircuit_id??void 0,pcb_group_id:i.getGroup()?.pcb_group_id??void 0,x:o.x,y:o.y,source_port_id:e.source_port_id,is_board_pinout:!1});r.pcb_port_id=c.pcb_port_id}}function kTt(e,t){let{subcircuit:n,groupsMap:i}=t,o=new Tc({name:e.name});return o.source_group_id=e.source_group_id,n.add(o),i&&i.set(e.source_group_id,o),o}var ATt=(e,t)=>{if(!e||e.length===0)return;let{injectionDb:n}=t,i=e.map(o=>o.map(r=>{let s=n.source_port.get(r);return s?s.pin_number!==void 0&&s.pin_number!==null?`pin${s.pin_number}`:s.name:null}).filter(r=>r!==null)).filter(o=>o.length>0);return i.length>0?i:void 0},RTt=(e,t)=>{let{injectionDb:n,subcircuit:i,groupsMap:o}=t,r=n.pcb_component.getWhere({source_component_id:e.source_component_id}),s=n.schematic_component.getWhere({source_component_id:e.source_component_id}),a=n.cad_component.getWhere({source_component_id:e.source_component_id}),c=ATt(e.internally_connected_source_port_ids,t),l=new Fm({name:e.name,manufacturerPartNumber:e.manufacturer_part_number,supplierPartNumbers:e.supplier_part_numbers??void 0,pinLabels:s?.port_labels??void 0,schWidth:s?.size?.width,schHeight:s?.size?.height,schPinSpacing:s?.pin_spacing,schX:s?.center?.x,schY:s?.center?.y,layer:r?.layer,pcbX:r?.center?.x,pcbY:r?.center?.y,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds,internallyConnectedPins:c}),u=a?.footprinter_string??"soic8";u&&(Object.assign(l.props,{footprint:u}),Object.assign(l._parsedProps,{footprint:u}),a||l._addChildrenFromStringFootprint?.()),r&&xG(r,{...t,normalComponent:l}),e.source_group_id&&o?.has(e.source_group_id)?o.get(e.source_group_id).add(l):i.add(l)},vG=class extends Tc{constructor(e){super({...e,subcircuit:!0})}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:e,children:t}=this._parsedProps;if(!e)return;let n=Ge(e);if(e&&t?.length>0)throw new Error("Subcircuit cannot have both circuitJson and children");let o={injectionDb:n,subcircuit:this,groupsMap:new Map},r=n.source_group.list();for(let c of r)kTt(c,o);let s=n.source_component.list();for(let c of s)switch(c.ftype){case"simple_resistor":ETt(c,o);break;case"simple_chip":RTt(c,o);break;default:throw new Error(`No inflator implemented for source component ftype: "${c.ftype}"`)}let a=n.source_port.list();for(let c of a)NTt(c,o)}},SG=class extends Tc{constructor(e){super({...e,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let n=e.pcb_group.get(this.pcb_group_id),i=t.paddingLeft??t.padding??0,o=t.paddingRight??t.padding??0,r=t.paddingTop??t.padding??0,s=t.paddingBottom??t.padding??0;e.pcb_group.update(this.pcb_group_id,{width:(n.width??0)+i+o,height:(n.height??0)+r+s,center:{x:n.center.x+(o-i)/2,y:n.center.y+(r-s)/2}})}},wG=class extends xe{constructor(){super(...arguments);P(this,"pcb_breakout_point_id",null);P(this,"matchedPort",null);P(this,"matchedNet",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:tD}}_matchConnection(){let{connection:t}=this._parsedProps,n=this.getSubcircuit();n&&(this.matchedPort=n.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=n.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(o=>o.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(o=>o.connected_source_port_ids.includes(t.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;this._matchConnection();let{pcbX:n=0,pcbY:i=0}=this._parsedProps,o=this.parent?.getGroup(),r=this.getSubcircuit();if(!o||!o.pcb_group_id)return;let s=t.pcb_breakout_point.insert({pcb_group_id:o.pcb_group_id,subcircuit_id:r?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:n,y:i});this.pcb_breakout_point_id=s.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:n=0}=this._parsedProps;return{center:{x:t,y:n},bounds:{left:t,top:n,right:t,bottom:n},width:0,height:0}}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_breakout_point_id&&n.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},PG=class extends xe{constructor(){super(...arguments);P(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:zz}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),o=this._getConnectedPorts();if(o.length===0)return"right";let r=o[0]._getGlobalSchematicPositionBeforeLayout(),s=r.x-i.x,a=r.y-i.y;if(Math.abs(s)>Math.abs(a)){if(s>0)return"right";if(s<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let n=[];for(let i of t){let o=this.getSubcircuit().selectOne(i);o&&n.push(o)}return n}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let n=this._getConnectedPorts();if(n.length>0){let i=n[0]._getGlobalSchematicPositionBeforeLayout(),o=Ne(this.parent?.computeSchematicGlobalTransform?.()??zi(),{x:0,y:0});return vn(i.x-o.x,i.y-o.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),r=n.anchorSide??"right",s=Ic({anchor_position:i,anchor_side:r,text:n.net}),a=t.schematic_net_label.insert({text:n.net,source_net_id:o.source_net_id,anchor_position:i,center:s,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo??t.connection;if(Array.isArray(n))return n;if(typeof n=="string")return[n]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&zx(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let n of t)this.add(new $r({from:n,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._resolveConnectsTo();if(!n||n.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),o=this._getAnchorSide(),s={left:"x-",right:"x+",top:"y+",bottom:"y-"}[o],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of n){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id??""));if(w&&(u=t.schematic_trace.list().some(S=>S.source_trace_id===w.source_trace_id)),u)continue}let h=l._getGlobalSchematicPositionAfterLayout(),d=E4(l.facingDirection??"right")??"x+",_=oc({x:h.x,y:h.y,facingDirection:d},{x:i.x,y:i.y,facingDirection:s});if(!Array.isArray(_)||_.length<2)continue;let y=[];for(let w=0;w<_.length-1;w++)y.push({from:{x:_[w].x,y:_[w].y},to:{x:_[w+1].x,y:_[w+1].y}});let g,x;if(a?.source_net_id&&l.source_port_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id));g=w?.source_trace_id,x=w?.subcircuit_connectivity_map_key||t.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}t.schematic_trace.insert({source_trace_id:g,edges:y,junctions:[],subcircuit_connectivity_map_key:x}),t.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},IG=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_circle_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:xD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenCircle. Must be "top" or "bottom".`);let r=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:o,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},TG=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_rect_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:bD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenRect. Must be "top" or "bottom".`);let r=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_rect.insert({pcb_component_id:s,layer:o,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1,is_filled:n.filled??!1,corner_radius:n.cornerRadius??void 0});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},MG=class extends xe{constructor(){super(...arguments);P(this,"pcb_silkscreen_line_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:gD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenLine. Must be "top" or "bottom".`);let r=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_line.insert({pcb_component_id:s,layer:o,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:r?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},CG=class extends xe{constructor(t){super(t);P(this,"pcb_via_id",null);P(this,"matchedPort",null);P(this,"isPcbPrimitive",!0);P(this,"source_manually_placed_via_id",null);P(this,"subcircuit_connectivity_map_key",null);let n=this._getLayers();this._parsedProps.layers=n,this.initPorts()}get config(){return{componentName:"Via",zodProps:Jz}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}_getLayers(){let{fromLayer:t="top",toLayer:n="bottom"}=this._parsedProps;return t===n?[t]:[t,n]}initPorts(){let t=this._parsedProps.layers;for(let i of t){let o=new Ni({name:i,layer:i});o.registerMatch(this),this.add(o)}let n=new Ni({name:"pin1"});n.registerMatch(this),this.add(n)}_getConnectedNetOrTrace(){let t=this._parsedProps.connectsTo;if(!t)return null;let n=this.getSubcircuit(),i=Array.isArray(t)?t:[t];for(let o of i)if(o.startsWith("net.")){let r=n.selectOne(o,{type:"net"});if(r)return r}return null}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),o=this.getSubcircuit(),r=t.pcb_component.insert({center:i,width:n.outerDiameter,height:n.outerDiameter,layer:n.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:o?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=r.pcb_component_id}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getGroup(),o=this.getSubcircuit(),r=t.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:n.net??"",subcircuit_id:o?.subcircuit_id??void 0});this.source_component_id=r.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),o=this.getSubcircuit(),r=t.pcb_via.insert({x:i.x,y:i.y,hole_diameter:n.holeDiameter,outer_diameter:n.outerDiameter,layers:["bottom","top"],from_layer:n.fromLayer||"bottom",to_layer:n.toLayer||"top",subcircuit_id:o?.subcircuit_id??void 0,subcircuit_connectivity_map_key:this.subcircuit_connectivity_map_key??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,net_is_assignable:n.netIsAssignable??void 0});this.pcb_via_id=r.pcb_via_id}},EG=class extends xe{constructor(){super(...arguments);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:nD}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;zx(this,[t.connectsTo])}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit().selectOne(n.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${n.connectsTo}" not found for copper pour`);return}let o=this.getSubcircuit(),r=t.toArray().filter(h=>h.type==="source_net"&&h.name===i.name)[0]||"",s=n.clearance??.2,a=DX(t.toArray(),{layer:n.layer,pour_connectivity_key:r.subcircuit_connectivity_map_key||"",pad_margin:n.padMargin??s,trace_margin:n.traceMargin??s,board_edge_margin:n.boardEdgeMargin??s,cutout_margin:n.cutoutMargin??s}),c=new zX(a),{brep_shapes:l}=c.getOutput(),u=n.coveredWithSolderMask??!1;for(let h of l)t.pcb_copper_pour.insert({shape:"brep",layer:n.layer,brep_shape:h,source_net_id:i.source_net_id,subcircuit_id:o?.subcircuit_id??void 0,covered_with_solder_mask:u})})}},NG=class extends On{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:Lz,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:t.capacity,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},kG=class extends On{_getPcbRotationBeforeLayout(){let e=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+e}get config(){return{componentName:"PinHeader",zodProps:Fz,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,o=this._parsedProps.showSilkscreenPinLabels;if(e>0){let r;if(i)!t&&!n?r=`pinrow${e}_p${i}`:r=`pinrow${e}_p${i}_id${t}_od${n}`;else if(!t&&!n)r=`pinrow${e}`;else return null;return o!==!0&&(r+="_nopinlabels"),r}return null}initPorts(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let t=1;t<=e;t++){let n=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[t-1]:this._parsedProps.pinLabels?.[`pin${t}`];if(n){let i=Array.isArray(n)?n[0]:n,o=Array.isArray(n)?n.slice(1):[];this.add(new Ni({pinNumber:t,name:i,aliases:[`pin${t}`,...o]}))}else this.add(new Ni({pinNumber:t,name:`pin${t}`}))}}_getSchematicPortArrangement(){let e=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:n?.leftSide?.direction??"top-to-bottom",pins:n?.leftSide?.pins??Array.from({length:e},(i,o)=>`pin${o+1}`)}}:{rightSide:{direction:n?.rightSide?.direction??"top-to-bottom",pins:n?.rightSide?.pins??Array.from({length:e},(i,o)=>`pin${o+1}`)}}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:t.supplierPartNumbers,pin_count:t.pinCount,gender:t.gender,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function OTt(e){switch(e){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var AG=class extends On{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??OTt(this.props.pinVariant),zodProps:Iz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:n,are_pins_interchangeable:n==="no_ground"||n==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let e=`${ni(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ni(this._parsedProps.loadCapacitance)}F`:e}},RG=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:Yz,sourceFtype:la.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${ni(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({name:this.name,ftype:la.simple_inductor,inductance:n.inductance,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function LTt(e){switch(e){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var OG=class extends On{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??LTt(this.props.pinVariant),zodProps:wz,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${ni(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},LG=class extends On{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:Dz,sourceFtype:la.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let e=ti[this._getSchematicSymbolNameOrThrow()],t=e.ports.find(l=>l.labels.includes("1")),n=e.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),o=i.find(l=>l.props.pinNumber===1),r=i.find(l=>l.props.pinNumber===2),s=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;o.schematicSymbolPortDef=t,(!c||c.length===0)&&(r.schematicSymbolPortDef=n);for(let[l,u]of[[2,r],[3,s],[4,a]]){let h=c?.find(([_,y])=>_===`pin${l}`||y===`pin${l}`);if(!h){u.schematicSymbolPortDef=n;break}(h?.[0]===`pin${l}`?h[1]:h?.[0])!=="pin1"&&(u.schematicSymbolPortDef=n)}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:la.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},FG=class extends On{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:Pz,sourceFtype:"simple_crystal"}}initPorts(){let e=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:e})}_getSchematicSymbolDisplayValue(){let e=`${ni(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ni(this._parsedProps.loadCapacitance)}F`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:t.frequency,load_capacitance:t.loadCapacitance,pin_variant:t.pinVariant||"two_pin",are_pins_interchangeable:(t.pinVariant||"two_pin")==="two_pin"});this.source_component_id=n.source_component_id}},zG=class extends On{constructor(){super(...arguments);P(this,"emitter",this.portMap.pin1);P(this,"collector",this.portMap.pin2);P(this,"base",this.portMap.pin3)}get config(){let t=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??t,zodProps:jz,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},DG=class extends On{get config(){let e=this.props.mosfetMode==="depletion"?"d":"e",n=`${this.props.channelType}_channel_${e}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??n,zodProps:Bz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}};function FTt(e){return e.simSwitchFrequency!==void 0||e.simCloseAt!==void 0||e.simOpenAt!==void 0||e.simStartClosed!==void 0||e.simStartOpen!==void 0}var $G=class extends On{_getSwitchType(){let e=this._parsedProps;return e?e.dpdt?"dpdt":e.spst?"spst":e.spdt?"spdt":e.dpst?"dpst":e.type??"spst":"spst"}get config(){let e=this._getSwitchType(),t=this._parsedProps?.isNormallyClosed??!1,n={spst:t?"spst_normally_closed_switch":"spst_switch",spdt:t?"spdt_normally_closed_switch":"spdt_switch",dpst:t?"dpst_normally_closed_switch":"dpst_switch",dpdt:t?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??n[e],zodProps:Uz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,t=this._parsedProps??{},n=e.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=n.source_component_id}doInitialSimulationRender(){let{_parsedProps:e}=this;if(!FTt(e))return;let{db:t}=this.root,n={type:"simulation_switch",source_component_id:this.source_component_id||""};e.simSwitchFrequency!==void 0&&(n.switching_frequency=Wi.parse(e.simSwitchFrequency)),e.simCloseAt!==void 0&&(n.closes_at=qi.parse(e.simCloseAt)),e.simOpenAt!==void 0&&(n.opens_at=qi.parse(e.simOpenAt)),e.simStartOpen!==void 0&&(n.starts_closed=!e.simStartOpen),e.simStartClosed!==void 0&&(n.starts_closed=e.simStartClosed),t.simulation_switch.insert(n)}},T4={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},jG=class extends On{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:Qz,sourceFtype:la.simple_test_point}}_getPropsWithDefaults(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}=this._parsedProps;return!n&&t&&(n="through_hole"),n??(n="through_hole"),e??(e="circle"),n==="pad"?e==="circle"?i??(i=T4.SMT_CIRCLE_DIAMETER):e==="rect"&&(o??(o=T4.SMT_RECT_SIZE),r??(r=o)):n==="through_hole"&&(t??(t=T4.HOLE_DIAMETER)),{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}}_getImpliedFootprintString(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}=this._getPropsWithDefaults();if(n==="through_hole")return`platedhole_d${t}`;if(n==="pad"){if(e==="circle")return`smtpad_circle_d${i}`;if(e==="rect")return`smtpad_rect_w${o}_h${r}`}throw new Error(`Footprint variant "${n}" with pad shape "${e}" not implemented`)}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{padShape:n,holeDiameter:i,footprintVariant:o,padDiameter:r,width:s,height:a}=this._getPropsWithDefaults(),c=e.source_component.insert({ftype:la.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:o,pad_shape:n,pad_diameter:r,hole_diameter:i,width:s,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},BG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:hD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:i.x,y:i.y},rotation:n.schRotation??0})}},YG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:pD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_line.insert({schematic_component_id:o,x1:n.x1+i.x,y1:n.y1+i.y,x2:n.x2+i.x,y2:n.y2+i.y,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=r.schematic_line_id}},XG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:uD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_rect.insert({center:{x:i.x,y:i.y},width:n.width,height:n.height,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_filled:n.isFilled,schematic_component_id:o,is_dashed:n.isDashed,rotation:n.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=r.schematic_rect_id}},VG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:aD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_arc.insert({schematic_component_id:o,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,start_angle_degrees:n.startAngleDegrees,end_angle_degrees:n.endAngleDegrees,direction:n.direction,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=r.schematic_arc_id}},HG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:lD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_circle.insert({schematic_component_id:o,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,stroke_width:n.strokeWidth??Bx,color:n.color??jx,is_filled:n.isFilled,fill_color:n.fillColor,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=r.schematic_circle_id}};function zTt({anchor:e,x:t,y:n,width:i,height:o,isInside:r}){switch(e){case"top_left":return{x:t,y:n+o,textAnchor:r?"top_left":"bottom_left"};case"top_center":return{x:t+i/2,y:n+o,textAnchor:r?"top_center":"bottom_center"};case"top_right":return{x:t+i,y:n+o,textAnchor:r?"top_right":"bottom_right"};case"center_left":return{x:t,y:n+o/2,textAnchor:r?"center_left":"center_right"};case"center":return{x:t+i/2,y:n+o/2,textAnchor:"center"};case"center_right":return{x:t+i,y:n+o/2,textAnchor:r?"center_right":"center_left"};case"bottom_left":return{x:t,y:n,textAnchor:r?"bottom_left":"top_left"};case"bottom_center":return{x:t+i/2,y:n,textAnchor:r?"bottom_center":"top_center"};case"bottom_right":return{x:t+i,y:n,textAnchor:r?"bottom_right":"top_right"};default:return{x:t+i/2,y:n+o,textAnchor:"center"}}}var GG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:cD,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=.6,o=typeof n.padding=="number"?n.padding:0,r=typeof n.paddingTop=="number"?n.paddingTop:o,s=typeof n.paddingBottom=="number"?n.paddingBottom:o,a=typeof n.paddingLeft=="number"?n.paddingLeft:o,c=typeof n.paddingRight=="number"?n.paddingRight:o,l=n.overlay&&n.overlay.length>0,u=typeof n.width=="number"&&typeof n.height=="number",h,d,_,y,g,x;if(l){let S=n.overlay.map(J=>({selector:J,port:this.getSubcircuit().selectOne(J,{type:"port"})})).filter(({port:J})=>J!=null).map(({port:J})=>({position:J._getGlobalSchematicPositionAfterLayout()}));if(S.length===0)return;let T=S.map(J=>J.position.x),I=S.map(J=>J.position.y),E=Math.min(...T),M=Math.max(...T),k=Math.min(...I),N=Math.max(...I),A=M-E,R=N-k,$=A===0?i:0,j=R===0?i:0,H=a+$/2,X=c+$/2,G=r+j/2,tt=s+j/2,Q=E-H,V=M+X,rt=k-tt,et=N+G;h=V-Q,d=et-rt,_=Q+(n.schX??0),y=rt+(n.schY??0),g=_+h/2,x=y+d/2}else if(u){h=n.width,d=n.height;let w=this._getGlobalSchematicPositionBeforeLayout();g=w.x,x=w.y,_=g-h/2,y=x-d/2}else return;if(t.schematic_box.insert({height:d,width:h,x:_,y,is_dashed:n.strokeStyle==="dashed"}),n.title){let w=n.titleInside,S=.1,T=n.titleAlignment,I=zTt({anchor:T,x:_,y,width:h,height:d,isInside:w}),E,M,k=I.textAnchor;w?(E=T.includes("top")?-S:T.includes("bottom")?S:0,M=T.includes("left")?S:T.includes("right")?-S:0):(E=T.includes("top")?S:T.includes("bottom")?-S:0,M=T.includes("center_left")?-S:T.includes("center_right")?S:0);let N=I.x+M,A=I.y+E;t.schematic_text.insert({anchor:k,text:n.title,font_size:n.titleFontSize??.18,color:n.titleColor??"#000000",position:{x:N,y:A},rotation:0})}}},UG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:dD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.children.filter(d=>d.componentName==="SchematicRow");if(i.length===0)return;let o=[],r=0;for(let d of i){let _=d.children.filter(y=>y.componentName==="SchematicCell");r=Math.max(r,_.length)}for(let d=0;d<i.length;d++)o[d]=[];for(let d=0;d<i.length;d++){let y=i[d].children.filter(x=>x.componentName==="SchematicCell"),g=0;for(let x=0;x<y.length;x++){for(;o[d][g];)g++;let w=y[x],S=w._parsedProps.colSpan??1,T=w._parsedProps.rowSpan??1;for(let I=0;I<T;I++)for(let E=0;E<S;E++)o[d+I]||(o[d+I]=[]),o[d+I][g+E]=w;g+=S}}r=Math.max(0,...o.map(d=>d.length));let s=i.map((d,_)=>d._parsedProps.height??1),a=Array.from({length:r},(d,_)=>{let y=0;for(let g=0;g<i.length;g++){let x=o[g]?.[_];if(x){let w=x._parsedProps.text??x._parsedProps.children,S=x._parsedProps.width??(w?.length??2)*.5;S>y&&(y=S)}}return y||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=t.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:s,cell_padding:n.cellPadding,border_width:n.borderWidth,anchor:n.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,h=0;for(let d=0;d<i.length;d++){let _=0;for(let y=0;y<r;y++){let g=o[d]?.[y];if(g&&!u.has(g)){u.add(g);let x=g._parsedProps,w=x.rowSpan??1,S=x.colSpan??1,T=0;for(let E=0;E<S;E++)T+=a[y+E];let I=0;for(let E=0;E<w;E++)I+=s[d+E];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:d,end_row_index:d+w-1,start_column_index:y,end_column_index:y+S-1,text:x.text??x.children,center:{x:c.x+_+T/2,y:c.y-h-I/2},width:T,height:I,horizontal_align:x.horizontalAlign,vertical_align:x.verticalAlign,font_size:x.fontSize??n.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[y]&&(_+=a[y])}h+=s[d]}}},qG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:fD}}},WG=class extends xe{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:mD}}},ZG=class extends xe{constructor(){super(...arguments);P(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:Oz}}},KG=class extends xe{get config(){return{componentName:"AnalogSimulation",zodProps:$z}}doInitialSimulationRender(){let{db:e}=this.root,{duration:t,timePerStep:n}=this._parsedProps,i=t||10,o=n||.01;e.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:o})}},JG=class extends xe{constructor(){super(...arguments);P(this,"simulation_voltage_probe_id",null)}get config(){return{componentName:"VoltageProbe",zodProps:sD}}doInitialSimulationRender(){let{db:t}=this.root,{connectsTo:n,name:i}=this._parsedProps,o=this.getSubcircuit();if(!o){this.renderError("VoltageProbe must be inside a subcircuit");return}let r=Array.isArray(n)?n:[n];if(r.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let s=r[0],a=o.selectOne(s,{type:"port"}),c=a?null:o.selectOne(s,{type:"net"});if(c&&c.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${s}" resolved to a non-net component "${c.componentName}".`);return}if(!a&&!c){this.renderError(`VoltageProbe could not find connection target "${s}"`);return}let{simulation_voltage_probe_id:l}=t.simulation_voltage_probe.insert({name:i??this.name,source_port_id:a?.source_port_id??void 0,source_net_id:c?.source_net_id??void 0,subcircuit_id:o.subcircuit_id||void 0});this.simulation_voltage_probe_id=l}},DTt={name:"@tscircuit/core",type:"module",version:"0.0.856",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"',"generate-test-plan":"bun run scripts/generate-test-plan.ts"},devDependencies:{"@biomejs/biome":"^1.8.3","@resvg/resvg-js":"^2.6.2","@tscircuit/capacity-autorouter":"^0.0.140","@tscircuit/checks":"^0.0.85","@tscircuit/circuit-json-util":"^0.0.72","@tscircuit/common":"^0.0.20","@tscircuit/copper-pour-solver":"^0.0.14","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.29","@tscircuit/miniflex":"^0.0.4","@tscircuit/ngspice-spice-engine":"^0.0.2","@tscircuit/props":"^0.0.398","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^v0.0.45","@tscircuit/solver-utils":"^0.0.3","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.306","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.16","circuit-to-svg":"^0.0.265",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6","eecircuit-engine":"^1.5.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.16",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.10","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.50","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Uh=class{constructor({platform:e,projectUrl:t}={}){P(this,"firstChild",null);P(this,"children");P(this,"db");P(this,"root",null);P(this,"isRoot",!0);P(this,"_schematicDisabledOverride");P(this,"pcbDisabled",!1);P(this,"pcbRoutingDisabled",!1);P(this,"_featureMspSchematicTraceRouting",!0);P(this,"name");P(this,"platform");P(this,"projectUrl");P(this,"_hasRenderedAtleastOnce",!1);P(this,"_eventListeners",{});this.children=[],this.db=Le([]),this.root=this,this.platform=e,this.projectUrl=t,this.pcbDisabled=e?.pcbDisabled??!1}get schematicDisabled(){return this._schematicDisabledOverride!==void 0?this._schematicDisabledOverride:this._getBoard()?._parsedProps?.schematicDisabled??!1}set schematicDisabled(e){this._schematicDisabledOverride=e}add(e){let t;(0,QG.isValidElement)(e)?t=CH(e):t=e,this.children.push(t)}setPlatform(e){this.platform={...this.platform,...e}}_getBoard(){let e=this.children.find(t=>t.componentName==="Board");if(e)return e}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");let e=this.children.filter(n=>n.lowercaseComponentName==="panel");if(e.length>1)throw new Error("Only one <panel> is allowed per circuit");if(e.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=e[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let t=new Tc({subcircuit:!0});t.parent=this,t.addAll(this.children),this.children=[t],this.firstChild=t}render(){this.firstChild||this._guessRootComponent();let{firstChild:e,db:t}=this;if(!e)throw new Error("RootCircuit has no root component");e.parent=this,e.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(t=>setTimeout(t,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(e=>e._hasIncompleteAsyncEffects()?!0:e.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(e){let t=await Promise.resolve().then(()=>(ZV(),WV)).catch(n=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
|
|
252
252
|
|
|
253
253
|
"${n.message}"`)});if(e.view==="pcb")return t.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(e.view==="schematic")return t.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${e.view}`)}getCoreVersion(){let[e,t,n]=DTt.version.split(".").map(Number);return`${e}.${t}.${n+1}`}async preview(e){let t=typeof e=="object"?e:{previewName:e};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return zi()}_computePcbGlobalTransformBeforeLayout(){return zi()}selectAll(e){return this._guessRootComponent(),this.firstChild?.selectAll(e)??[]}selectOne(e,t){return this._guessRootComponent(),this.firstChild?.selectOne(e,t)??null}emit(e,...t){if(this._eventListeners[e])for(let n of this._eventListeners[e])n(...t)}on(e,t){this._eventListeners[e]||(this._eventListeners[e]=[]),this._eventListeners[e].push(t)}removeListener(e,t){this._eventListeners[e]&&(this._eventListeners[e]=this._eventListeners[e].filter(n=>n!==t))}enableDebug(e){typeof e=="string"?O4.default.enable(e):(e===null||e===!1)&&O4.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},$Tt=Uh,jTt=Uh,BTt=e=>{let[t,n]=Bh.default.useState(!0),[i,o]=Bh.default.useState(null),[r,s]=Bh.default.useState(),[a,c]=Bh.default.useState();return Bh.default.useEffect(()=>{n(!0),o(null),e&&setTimeout(()=>{try{let l=new Uh;l.add(e),s(l),c(l.toJson())}catch(l){o(l)}n(!1)},1)},[e]),{isLoading:t,error:i,circuit:r,circuitJson:a}},qh=(e,t)=>(n,i)=>{let o=[];Array.isArray(t)?o.push(...t.flat()):typeof t=="object"&&o.push(...Object.values(t).flat(),...Object.keys(t));let r=s=>{if(s?.name&&s.name!==n)throw new Error(`Component name mismatch. Hook name: ${n}, Component prop name: ${s.name}`);let a={...i,...s,name:n},c=[];for(let l of o)if(a[l]){let u=`.${n} > .${l}`,h=a[l];c.push({from:u,to:h}),delete a[l]}return(0,mu.jsxs)(mu.Fragment,{children:[(0,mu.jsx)(e,{...a}),c.map((l,u)=>(0,mu.jsx)("trace",{...l},u))]})};for(let s of o)r[s]=`.${n} > .${s}`;return r},YTt=qh(e=>(0,tU.jsx)("capacitor",{...e}),Mz),XTt=e=>qh(t=>(0,eU.jsx)("chip",{pinLabels:e,...t}),e),VTt=qh(e=>(0,nU.jsx)("diode",{...e}),Vz),HTt=qh(e=>(0,iU.jsx)("led",{...e}),Gz),GTt=qh(e=>(0,oU.jsx)("resistor",{...e}),Sz),UTt=new Proxy(e=>new Proxy({},{get:(t,n)=>`.${e} > .${n}`}),{get:(e,t)=>{let n=(...i)=>{let o=i[0];return new Proxy({},{get:(r,s)=>`.${t} > .${s}`})};return new Proxy(n,{get:(i,o)=>t==="net"?`net.${o}`:t==="subcircuit"?new Proxy({},{get:(r,s)=>new Proxy({},{get:(a,c)=>`subcircuit.${o} > .${s} > .${c}`})}):`.${t} > .${o}`,apply:(i,o,r)=>t==="net"?new Proxy({},{get:(s,a)=>`net.${a}`}):new Proxy({},{get:(s,a)=>{let c=`.${t} > .${a}`;return["U","J","CN"].some(u=>t.startsWith(u))?c:new Proxy(new String(c),{get:(u,h)=>typeof h=="symbol"||h==="toString"?()=>c:`.${t} > .${a} > .${h}`})}})})}});MH(SH);MH({Bug:Fm});var PU=Xt(Mr(),1);var sU=e=>{let t=e.match(/:[RC]_(\d{4})_/);if(t||(t=e.match(/:(SOIC-\d+|SOT-\d+|SOD-\d+|SSOP-\d+|TSSOP-\d+|QFP-\d+|QFN-\d+)/),t))return t[1]};var V4=e=>e.includes("cap")?e.replace(/cap/g,""):e;var aU=e=>{if(e){if(e.startsWith("kicad:")){let t=sU(e);return t?V4(t):e}return V4(e)}};var H4=new Map,lo=async(e,t)=>{let n=new URLSearchParams({...t,json:"true"}).toString();if(H4.has(n))return H4.get(n);let o=await(await fetch(`https://jlcsearch.tscircuit.com/${e}/list?${n}`)).json();return H4.set(n,o),o},uo=e=>e?[...e].sort((t,n)=>Number(n.is_basic??!1)-Number(t.is_basic??!1)):[],cU={findPart:async({sourceComponent:e,footprinterString:t})=>{let n=aU(t);if(e.type==="source_component"&&e.ftype==="simple_resistor"){let{resistors:i}=await lo("resistors",{resistance:e.resistance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_capacitor"){let{capacitors:i}=await lo("capacitors",{capacitance:e.capacitance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_pin_header"){let i;t?.includes("_p")&&(i=Number(t.split("_p")[1]));let{headers:o}=await lo("headers",i?{pitch:i,num_pins:e.pin_count,gender:e.gender}:{num_pins:e.pin_count,gender:e.gender});return{jlcpcb:uo(o).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_potentiometer"){let{potentiometers:i}=await lo("potentiometers",{resistance:e.max_resistance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_diode"){let{diodes:i}=await lo("diodes",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_chip"){let{chips:i}=await lo("chips",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_transistor"){let{transistors:i}=await lo("transistors",{package:n,transistor_type:e.transistor_type});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_power_source"){let{power_sources:i}=await lo("power_sources",{voltage:e.voltage,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_inductor"){let{inductors:i}=await lo("inductors",{inductance:e.inductance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_crystal"){let{crystals:i}=await lo("crystals",{frequency:e.frequency,load_capacitance:e.load_capacitance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_mosfet"){let{mosfets:i}=await lo("mosfets",{package:n,mosfet_mode:e.mosfet_mode,channel_type:e.channel_type});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_resonator"){let{resonators:i}=await lo("resonators",{frequency:e.frequency,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_switch"){let{switches:i}=await lo("switches",{switch_type:e.type,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_led"){let{leds:i}=await lo("leds",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_fuse"){let{fuses:i}=await lo("fuses",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}return{}}};var hU=Xt(lU(),1);K();var yU=Xt(Sn(),1),gU=Xt(Sn(),1),ii=p.tuple([p.coerce.number(),p.coerce.number()]),iMt=p.tuple([p.number(),p.number(),p.number()]),Ux=p.union([ii,iMt]),oMt=p.object({kind:p.literal("arc"),start:ii,mid:ii,end:ii}),rMt=p.union([ii,oMt]),dU=p.object({at:Ux,size:ii,layer:p.string(),layers:p.array(p.string()),roundrect_rratio:p.number(),uuid:p.string()}).partial(),sMt=p.object({key:p.string(),val:p.string(),attributes:dU}),Vx=p.object({oval:p.boolean().default(!1),width:p.number().optional(),height:p.number().optional(),offset:ii.optional()}),fU=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:Ux,drill:p.union([p.number(),p.array(p.any()),Vx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:ii.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?ii.parse(e[3].slice(1)):void 0}:e).pipe(Vx),size:p.union([p.array(p.number()).length(2).transform(([e,t])=>({width:e,height:t})),p.object({width:p.number(),height:p.number()})]),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),uuid:p.string().optional()}),mU=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:Ux,size:ii,drill:p.union([p.number(),p.array(p.any()),Vx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:ii.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?ii.parse(e[3].slice(1)):void 0}:e).pipe(Vx).optional(),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),chamfer_ratio:p.number().optional(),solder_paste_margin:p.number().optional(),solder_paste_margin_ratio:p.number().optional(),clearance:p.number().optional(),zone_connection:p.union([p.literal(0).describe("Pad is not connect to zone"),p.literal(1).describe("Pad is connected to zone using thermal relief"),p.literal(2).describe("Pad is connected to zone using solid fill")]).optional(),thermal_width:p.number().optional(),thermal_gap:p.number().optional(),uuid:p.string().optional()}),_U=p.object({font:p.object({size:ii,thickness:p.number().optional()})}).partial(),aMt=p.object({fp_text_type:p.literal("user"),text:p.string(),at:Ux,layer:p.string(),uuid:p.string().optional(),effects:_U.partial()}),cMt=p.object({start:ii,mid:ii,end:ii,stroke:p.object({width:p.number(),type:p.string()}),layer:p.string(),uuid:p.string().optional()}),lMt=p.object({center:ii,end:ii,stroke:p.object({width:p.number(),type:p.string()}),fill:p.string().optional(),layer:p.string(),uuid:p.string().optional()}),uMt=p.object({pts:p.array(rMt),stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional(),fill:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),pMt=p.object({start:ii,end:ii,stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),uU=p.object({footprint_name:p.string(),version:p.string().optional(),generator:p.string().optional(),generator_version:p.string().optional(),layer:p.string(),descr:p.string().default(""),tags:p.array(p.string()).optional(),properties:p.array(sMt),fp_lines:p.array(pMt),fp_texts:p.array(aMt),fp_arcs:p.array(cMt),fp_circles:p.array(lMt).optional(),fp_polys:p.array(uMt).optional(),pads:p.array(mU),holes:p.array(fU).optional()}),Hx=(e,t)=>{if(t==="effects"&&Array.isArray(e)){let n={};for(let i of e)if(i[0]==="font"){let o={};for(let r of i.slice(1))r.length===2?o[r[0].valueOf()]=Number.parseFloat(r[1].valueOf()):o[r[0].valueOf()]=r.slice(1).map(s=>Number.parseFloat(s.valueOf()));n.font=o}return _U.parse(n)}if(t==="pts")return e.map(n=>{let i=n[0]?.valueOf?.()??n[0];if(i==="xy")return n.slice(1).map(o=>Number.parseFloat(o.valueOf()));if(i==="arc"){let o={kind:"arc"};for(let r of n.slice(1)){let s=r[0].valueOf();o[s]=r.slice(1).map(a=>Number.parseFloat(a.valueOf()))}return o}return n});if(t==="stroke"){let n={};for(let i of e){let o=i[0].valueOf();n[o]=Hx(i.slice(1),o)}return n}return t==="at"||t==="size"||t==="start"||t==="mid"||t==="end"?(Array.isArray(e)?e:[e]).map(i=>i?.valueOf?.()??i).filter(i=>typeof i=="number"||typeof i=="string"&&/^[-+]?\d*\.?\d+(e[-+]?\d+)?$/i.test(i)).map(i=>typeof i=="number"?i:Number.parseFloat(i)):t==="tags"?e.map(n=>n.valueOf()):t==="generator_version"||t==="version"?e[0].valueOf():e.length===2?e.valueOf():t==="uuid"?Array.isArray(e)?e[0].valueOf():e.valueOf():/^[\d\.]+$/.test(e)&&!Number.isNaN(Number.parseFloat(e))?Number.parseFloat(e):Array.isArray(e)&&e.length===1?e[0].valueOf():Array.isArray(e)?e.map(n=>n.valueOf()):e},Re=(e,t)=>{for(let n of e)if(Array.isArray(n)&&n[0]===t)return Hx(n.slice(1),t)},G4=(0,yU.default)("kicad-mod-converter"),hMt=e=>{let t=(0,hU.default)(e),n=t[1].valueOf(),i={},o=Object.entries(uU.shape).filter(([T,I])=>I._def.typeName==="ZodString"||T==="tags").map(([T])=>T);for(let T of t.slice(2)){if(!o.includes(T[0]))continue;let I=T[0].valueOf(),E=Hx(T.slice(1),I);i[I]=E}let r=t.slice(2).filter(T=>T[0]==="property").map(T=>{let I=T[1].valueOf(),E=T[2].valueOf(),M=dU.parse(T.slice(3).reduce((k,N)=>{let A=N[0].valueOf();return k[A]=Hx(N.slice(1),A),k},{}));return{key:I,val:E,attributes:M}}),s=t.slice(2).filter(T=>T[0]==="pad"),a=[];for(let T of s){let I=Re(T,"at"),E=Re(T,"size"),M=Re(T,"drill"),k=Re(T,"layers");if(Array.isArray(k)?k=k.map($=>$.valueOf()):typeof k=="string"?k=[k]:k||(k=[]),!k.includes("F.Cu")){G4(`Skipping pad without F.Cu layer: layers=${k.join(", ")}`);continue}let N=Re(T,"roundrect_rratio"),A=Re(T,"uuid"),R={name:T[1].valueOf(),pad_type:T[2].valueOf(),pad_shape:T[3].valueOf(),at:I,drill:M,size:E,layers:k,roundrect_rratio:N,uuid:A};G4(`attempting to parse pad: ${JSON.stringify(R,null," ")}`),a.push(mU.parse(R))}let c=t.slice(2).filter(T=>T[0]==="fp_text"),l=[];for(let T of c){let I=T[2].valueOf(),E=Re(T,"at"),M=Re(T,"layer"),k=Re(T,"uuid"),N=Re(T,"effects");l.push({fp_text_type:"user",text:I,at:E,layer:M,uuid:k,effects:N})}let u=[],h=t.slice(2).filter(T=>T[0]==="fp_line");for(let T of h){let I=Re(T,"start"),E=Re(T,"end"),M=Re(T,"stroke"),k=Re(T,"layer"),N=Re(T,"uuid");u.push({start:I,end:E,stroke:M,layer:k,uuid:N})}let d=[],_=t.slice(2).filter(T=>T[0]==="fp_arc");for(let T of _){let I=Re(T,"start"),E=Re(T,"mid"),M=Re(T,"end"),k=Re(T,"stroke"),N=Re(T,"layer"),A=Re(T,"uuid");!I||!M||!E||!k||!N||d.push({start:I,mid:E,end:M,stroke:k,layer:N,uuid:A})}let y=[],g=t.slice(2).filter(T=>T[0]==="fp_circle");for(let T of g){let I=Re(T,"center"),E=Re(T,"end"),M=Re(T,"stroke"),k=Re(T,"fill"),N=Re(T,"layer"),A=Re(T,"uuid");!I||!E||!M||!N||y.push({center:I,end:E,stroke:M,fill:k,layer:N,uuid:A})}let x=[],w=t.slice(2).filter(T=>T[0]==="fp_poly");for(let T of w){let I=Re(T,"pts"),E=Re(T,"stroke"),M=Re(T,"width"),k=Re(T,"layer"),N=Re(T,"uuid"),A=Re(T,"fill"),R=E;!R&&typeof M=="number"?R={width:M,type:"solid"}:R&&typeof R=="object"&&typeof M=="number"&&R.width===void 0&&(R={...R,width:M}),x.push({pts:I,stroke:R,layer:k,uuid:N,fill:A})}let S=[];for(let T of t.slice(2)){if(T[0]!=="pad"||T[2]?.valueOf?.()!=="thru_hole")continue;let I=T[1]?.valueOf?.(),E=T[2]?.valueOf?.(),M=T[3]?.valueOf?.(),k=Re(T,"at"),N=Re(T,"drill"),A=Re(T,"size");Array.isArray(A)&&(A[0]==="size"&&(A=A.slice(1)),A={width:Number(A[0]),height:Number(A[1])});let R=Re(T,"uuid"),$=Re(T,"roundrect_rratio"),j=Re(T,"layers");Array.isArray(j)?j=j.map(X=>X.valueOf()):typeof j=="string"?j=[j]:j||(j=[]);let H={name:I,pad_type:E,pad_shape:M,at:k,drill:N,size:A,layers:j,roundrect_rratio:$,uuid:R};G4(`attempting to parse holes: ${JSON.stringify(H,null,2)}`),S.push(fU.parse(H))}return uU.parse({footprint_name:n,...i,properties:r,fp_lines:u,fp_texts:l,fp_arcs:d,fp_circles:y,pads:a,holes:S,fp_polys:x})},zm=Math.PI*2,pU=e=>{let t=e%zm;return t<0&&(t+=zm),t},Gx=(e,t)=>{let n=pU(e),o=pU(t)-n;return o<0&&(o+=zm),o};function bU(e,t,n){let i={x:(e.x+t.x)/2,y:(e.y+t.y)/2},o={x:(t.x+n.x)/2,y:(t.y+n.y)/2},r=-(e.x-t.x)/(e.y-t.y),s=-(t.x-n.x)/(t.y-n.y),a=(i.y-o.y+s*o.x-r*i.x)/(s-r),c=i.y+r*(a-i.x);return{x:a,y:c}}function xU(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Zh(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var Z4=(e,t,n)=>{let i=bU(e,t,n),o=xU(i,e),r=Zh(i,e),s=Zh(i,t),a=Zh(i,n),c=Gx(r,s),l=Gx(r,a),u=l;return c>l&&(u=l-zm),Math.abs(o*u)};function K4(e,t,n,i){let o=bU(e,t,n),r=xU(o,e),s=Zh(o,e),a=Zh(o,t),c=Zh(o,n),l=Gx(s,a),u=Gx(s,c),h=u;l>u&&(h=u-zm);let d=[];for(let _=0;_<=i;_++){let y=s+_/i*h,g=o.x+r*Math.cos(y),x=o.y+r*Math.sin(y);d.push({x:g,y:x})}return d}var Mc=e=>Array.isArray(e)?{x:e[0],y:e[1]}:e,U4=(e,t,n=1e-4)=>Math.abs(e.x-t.x)<n&&Math.abs(e.y-t.y)<n,dMt=e=>{let t=[],n=new Set;for(let i=0;i<e.length;i++){if(n.has(i))continue;let o=[e[i]];n.add(i);let r=e[i].end,s=!0;for(;s;){if(s=!1,o.length>1&&U4(r,o[0].start)){t.push(o);break}for(let a=0;a<e.length;a++)if(!n.has(a)){if(U4(r,e[a].start)){o.push(e[a]),n.add(a),r=e[a].end,s=!0;break}else if(U4(r,e[a].end)){e[a].type==="arc"?o.push({...e[a],reversed:!0}):o.push({...e[a],start:e[a].end,end:e[a].start}),n.add(a),r=e[a].start,s=!0;break}}if(!s){for(let a=o.length-1;a>=0;a--){let c=e.indexOf(o[a]);c!==-1&&n.delete(c)}break}}}return t},fMt=e=>{let t=[];for(let n of e)if(n.type==="line")t.push(n.start);else if(n.type==="arc"&&n.mid){let i=Z4(n.start,n.mid,n.end),o=Math.max(3,Math.ceil(i)),r=K4(n.start,n.mid,n.end,o);n.reversed&&(r=r.reverse()),t.push(...r.slice(0,-1))}return t};function mMt(e){if(!Array.isArray(e))return null;let t=e.find(s=>s.layer?.toLowerCase()==="f.silks"&&(s.text?.includes("${REFERENCE}")||s.fp_text_type?.toLowerCase()==="reference"||s.text?.match(/^R\d+|C\d+|U\d+/))),n=t||e.find(s=>s.layer?.toLowerCase()==="f.fab"&&(s.text?.includes("${REFERENCE}")||s.fp_text_type?.toLowerCase()==="reference")),i=t||n;if(!i?.effects?.font?.size)return null;let[o,r]=i.effects.font.size;return r??o??1}var _Mt=e=>e*Math.PI/180,q4=(e,t,n)=>{let i=_Mt(n),o=Math.cos(i),r=Math.sin(i);return{x:e*o-t*r,y:e*r+t*o}},yMt=e=>{let t=[...new Map(e.map(u=>[`${u.x},${u.y}`,u])).values()];if(t.length!==4)return null;let n=t.map(u=>u.x),i=t.map(u=>u.y),o=[...new Set(n)],r=[...new Set(i)];if(o.length!==2||r.length!==2)return null;let[s,a]=o.sort((u,h)=>u-h),[c,l]=r.sort((u,h)=>u-h);return s===void 0||a===void 0||c===void 0||l===void 0?null:{x:(s+a)/2,y:(c+l)/2,width:a-s,height:l-c}},gMt=e=>{if(!e)return!1;let t=e.toLowerCase();return t!=="no"&&t!=="none"&&t!=="outline"},W4=e=>e&&Array.isArray(e)&&e.length>=3&&typeof e[2]=="number"?e[2]:0,Co=e=>{let t=(e%360+360)%360;return t===90||t===270},Wh=(0,gU.default)("kicad-mod-converter"),_r=e=>{switch(e.toLowerCase()){case"f.cu":case"f.fab":case"f.silks":case"edge.cuts":return"top";case"b.cu":case"b.fab":case"b.silks":return"bottom"}},bMt=async e=>{let{fp_lines:t,fp_texts:n,fp_arcs:i,fp_circles:o,pads:r,properties:s,holes:a,fp_polys:c}=e,l=[];l.push({type:"source_component",source_component_id:"source_component_0",supplier_part_numbers:{}}),l.push({type:"schematic_component",schematic_component_id:"schematic_component_0",source_component_id:"source_component_0",center:{x:0,y:0},rotation:0,size:{width:0,height:0}});let u=new Set;for(let V of r)V.name&&u.add(V.name);if(a)for(let V of a)V.name&&u.add(V.name);let h=0,d=new Map;for(let V of u){let rt=`source_port_${h++}`;d.set(V,rt),l.push({type:"source_port",source_port_id:rt,source_component_id:"source_component_0",name:V,port_hints:[V]}),l.push({type:"schematic_port",schematic_port_id:`schematic_port_${h++}`,source_port_id:rt,schematic_component_id:"schematic_component_0",center:{x:0,y:0}})}let _=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,g=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY;for(let V of r){let rt=V.at[0],et=-V.at[1],J=V.size[0],pt=V.size[1];_=Math.min(_,rt-J/2),y=Math.max(y,rt+J/2),g=Math.min(g,et-pt/2),x=Math.max(x,et+pt/2)}let w="pcb_component_0";l.push({type:"pcb_component",source_component_id:"source_component_0",pcb_component_id:w,layer:"top",center:{x:0,y:0},rotation:0,width:Number.isFinite(_)?y-_:0,height:Number.isFinite(g)?x-g:0});let S=0,T=new Map;for(let V of u){let rt=`pcb_port_${S++}`,et=d.get(V);T.set(V,rt);let J=0,pt=0,ht=["top","bottom"],St=r.find(wt=>wt.name===V);if(St)J=St.at[0],pt=-St.at[1],ht=St.layers?St.layers.map(wt=>_r(wt)).filter(Boolean):["top","bottom"];else if(a){let wt=a.find(lt=>lt.name===V);wt&&(J=wt.at[0],pt=-wt.at[1],ht=wt.layers?wt.layers.map(lt=>_r(lt)).filter(Boolean):["top","bottom"])}l.push({type:"pcb_port",pcb_port_id:rt,source_port_id:et,pcb_component_id:w,x:J,y:pt,layers:ht})}let I=0,E=0,M=0;for(let V of r)if(V.pad_type==="smd"){let rt=W4(V.at),et=Co(rt)?V.size[1]:V.size[0],J=Co(rt)?V.size[0]:V.size[1],pt=V.name?T.get(V.name):void 0;l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${I++}`,shape:"rect",x:V.at[0],y:-V.at[1],width:et,height:J,layer:_r(V.layers?.[0]??"F.Cu"),pcb_component_id:w,port_hints:[V.name],pcb_port_id:pt})}else if(V.pad_type==="thru_hole"){if(V.pad_shape==="rect"){let rt=W4(V.at),et=Co(rt)?V.size[1]:V.size[0],J=Co(rt)?V.size[0]:V.size[1],pt=V.drill?.offset?.[0]??0,ht=V.drill?.offset?.[1]??0,St=q4(pt,ht,rt),wt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:V.at[0],y:-V.at[1],hole_offset_x:St.x,hole_offset_y:-St.y,hole_diameter:V.drill?.width,rect_pad_width:et,rect_pad_height:J,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:wt})}else if(V.pad_shape==="circle"){let rt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circle",x:V.at[0],y:-V.at[1],outer_diameter:V.size[0],hole_diameter:V.drill?.width,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:rt})}else if(V.pad_shape==="oval"){let rt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"pill",x:V.at[0],y:-V.at[1],outer_width:V.size[0],outer_height:V.size[1],hole_width:V.drill?.width,hole_height:V.drill?.height,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:rt})}}else V.pad_type==="np_thru_hole"&&l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${M++}`,x:V.at[0],y:-V.at[1],hole_diameter:V.drill?.width,pcb_component_id:w});if(a)for(let V of a){let rt=V.layers?.some(ut=>ut.endsWith(".Cu")||ut==="*.Cu"),et=W4(V.at),J=V.drill?.offset?.[0]??0,pt=V.drill?.offset?.[1]??0,ht=q4(J,pt,et),St=V.at[0]+ht.x,wt=-(V.at[1]+ht.y),lt=V.drill?.width??0,B=V.size?.width??lt,q=V.roundrect_rratio??0,it=q>0?Math.min(Co(et)?V.size?.height??B:V.size?.width??B,Co(et)?V.size?.width??B:V.size?.height??B)/2*q:0;if(rt)if(V.pad_shape==="rect"){let ut=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:V.at[0],y:-V.at[1],hole_offset_x:ht.x,hole_offset_y:-ht.y,hole_diameter:lt,rect_pad_width:Co(et)?V.size?.height??B:V.size?.width??B,rect_pad_height:Co(et)?V.size?.width??B:V.size?.height??B,rect_border_radius:it,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ut})}else if(V.pad_shape==="oval"){let ut=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"pill",x:St,y:wt,outer_width:Co(et)?V.size?.height??B:V.size?.width??B,outer_height:Co(et)?V.size?.width??B:V.size?.height??B,hole_width:Co(et)?V.drill?.height??lt:V.drill?.width??lt,hole_height:Co(et)?V.drill?.width??lt:V.drill?.height??lt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ut})}else if(V.pad_shape==="roundrect"){let ut=V.name?T.get(V.name):void 0,_t=V.drill?.offset?.[0]??0,W=V.drill?.offset?.[1]??0,at=q4(_t,W,et),Mt=Co(et)?V.size?.height??B:V.size?.width??B,Ot=Co(et)?V.size?.width??B:V.size?.height??B;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:St,y:wt,hole_offset_x:at.x,hole_offset_y:-at.y,hole_diameter:lt,rect_pad_width:Mt,rect_pad_height:Ot,rect_border_radius:it,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ut})}else{let ut=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circle",x:St,y:wt,outer_diameter:B,hole_diameter:lt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ut})}else l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${M++}`,x:St,y:wt,hole_diameter:B,hole_shape:"circle",pcb_component_id:w})}let k=[];for(let V of t)V.layer.toLowerCase()==="edge.cuts"&&k.push({type:"line",start:{x:V.start[0],y:V.start[1]},end:{x:V.end[0],y:V.end[1]},strokeWidth:V.stroke.width});for(let V of i)V.layer.toLowerCase()==="edge.cuts"&&k.push({type:"arc",start:{x:V.start[0],y:V.start[1]},mid:{x:V.mid[0],y:V.mid[1]},end:{x:V.end[0],y:V.end[1]},strokeWidth:V.stroke.width});let N=dMt(k),A=0;for(let V of N){let rt=fMt(V);rt.length>=3&&l.push({type:"pcb_cutout",pcb_cutout_id:`pcb_cutout_${A++}`,shape:"polygon",points:rt.map(et=>({x:et.x,y:-et.y})),pcb_component_id:w})}let R=0,$=0,j=0,H=0;for(let V of t){let rt=[{x:V.start[0],y:-V.start[1]},{x:V.end[0],y:-V.end[1]}],et=V.layer.toLowerCase();et==="f.cu"?l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:w,layer:_r(V.layer),route:rt,thickness:V.stroke.width}):et==="f.silks"?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,pcb_component_id:w,layer:"top",route:rt,stroke_width:V.stroke.width}):et==="edge.cuts"?Wh("Skipping Edge.Cuts fp_line (converted to pcb_cutout)",V.layer):et==="f.fab"?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${j++}`,pcb_component_id:w,layer:"top",route:rt,stroke_width:V.stroke.width,port_hints:[]}):et.startsWith("user.")?l.push({type:"pcb_note_line",pcb_note_line_id:`pcb_note_line_${H++}`,pcb_component_id:w,x1:V.start[0],y1:-V.start[1],x2:V.end[0],y2:-V.end[1],stroke_width:V.stroke.width}):Wh("Unhandled layer for fp_line",V.layer)}if(c)for(let V of c){let rt=[],et=wt=>{!Number.isFinite(wt.x)||!Number.isFinite(wt.y)||rt.push(wt)};for(let wt of V.pts){if(Array.isArray(wt)){et({x:wt[0],y:-wt[1]});continue}if(wt&&typeof wt=="object"&&"kind"in wt){if(wt.kind==="arc"){let lt=Mc(wt.start),B=Mc(wt.mid),q=Mc(wt.end),it=Z4(lt,B,q),ut=Math.max(8,Math.ceil(it)),_t=Math.max(2,Math.ceil(it/.1)),W=K4(lt,B,q,_t).map(at=>({x:at.x,y:-at.y}));for(let at of W)et(at)}continue}}let J=rt,ht=J.length>2&&J[0].x===J[J.length-1].x&&J[0].y===J[J.length-1].y?J.slice(0,-1):J;if(J.length===0)continue;let St=V.stroke?.width??0;if(V.layer.endsWith(".Cu")){let wt=yMt(ht);wt?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${I++}`,shape:"rect",x:wt.x,y:wt.y,width:wt.width,height:wt.height,layer:_r(V.layer),pcb_component_id:w}):gMt(V.fill)?ht.length>=3?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${I++}`,shape:"polygon",points:ht,layer:_r(V.layer),pcb_component_id:w}):ht.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:w,layer:_r(V.layer),route:ht,thickness:St}):ht.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:w,layer:_r(V.layer),route:ht,thickness:St})}else V.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,pcb_component_id:w,layer:_r(V.layer),route:J,stroke_width:St}):V.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${j++}`,pcb_component_id:w,layer:_r(V.layer),route:ht,stroke_width:St,port_hints:[]}):Wh("Unhandled layer for fp_poly",V.layer)}let X=0;for(let V of i){let rt=V.layer.toLowerCase();if(rt==="edge.cuts"){Wh("Skipping Edge.Cuts fp_arc (converted to pcb_cutout)",V.layer);continue}let et=Mc(V.start),J=Mc(V.mid),pt=Mc(V.end),ht=Z4(et,J,pt),St=K4(et,J,pt,Math.ceil(ht));if(rt.startsWith("user.")){l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${X++}`,pcb_component_id:w,route:St.map(lt=>({x:lt.x,y:-lt.y})),stroke_width:V.stroke.width});continue}let wt=_r(V.layer);if(!wt){Wh("Unable to convert layer for fp_arc",V.layer);continue}l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,layer:wt,pcb_component_id:w,route:St.map(lt=>({x:lt.x,y:-lt.y})),stroke_width:V.stroke.width})}if(o)for(let V of o){let rt=V.layer.toLowerCase(),et=Mc(V.center),J=Mc(V.end),pt=Math.sqrt((J.x-et.x)**2+(J.y-et.y)**2),ht=Math.max(16,Math.ceil(2*Math.PI*pt)),St=[];for(let wt=0;wt<=ht;wt++){let lt=wt/ht*2*Math.PI;St.push({x:et.x+pt*Math.cos(lt),y:et.y+pt*Math.sin(lt)})}rt.startsWith("user.")&&l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${X++}`,pcb_component_id:w,route:St.map(wt=>({x:wt.x,y:-wt.y})),stroke_width:V.stroke.width})}for(let V of n){let rt=_r(V.layer);V.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_text",layer:rt,font:"tscircuit2024",font_size:V.effects?.font?.size[0]??1,pcb_component_id:w,anchor_position:{x:V.at[0],y:-V.at[1]},anchor_alignment:"center",text:V.text}):V.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_text",layer:rt,font:"tscircuit2024",font_size:V.effects?.font?.size[0]??1,pcb_component_id:w,anchor_position:{x:V.at[0],y:-V.at[1]},anchor_alignment:"center",text:V.text}):Wh("Unhandled layer for fp_text",V.layer)}let G=s.find(V=>V.key==="Reference"),tt=s.find(V=>V.key==="Value"),Q=[G,tt].filter(V=>V&&!!V.val);for(let V of Q){let rt=V.attributes.at;if(!rt)continue;let J=V.attributes.layer?.toLowerCase()?.endsWith(".fab"),pt=mMt(n);l.push({type:J?"pcb_fabrication_note_text":"pcb_silkscreen_text",layer:"top",font:"tscircuit2024",font_size:pt,pcb_component_id:w,anchor_position:{x:rt[0],y:-rt[1]},anchor_alignment:"center",text:V.val})}return l},vU=async e=>{let t=hMt(e);return await bMt(t)};var SU=async e=>{try{return(await import(e)).default}catch{console.log(`Failed to load ${e} locally, trying CDN fallback...`);try{let n=await fetch(`https://cdn.jsdelivr.net/npm/${e}/+esm`);if(!n.ok)throw new Error(`Failed to fetch ${e} from CDN: ${n.statusText}`);let i=await n.text(),o=new Blob([i],{type:"application/javascript"}),r=URL.createObjectURL(o);try{let{default:s}=await import(r);return s}finally{URL.revokeObjectURL(r)}}catch(n){throw console.error(`CDN fallback for ${e} also failed:`,n),n}}};var xMt="https://kicad-mod-cache.tscircuit.com",qx=null,wU=()=>({partsEngine:cU,spiceEngineMap:{ngspice:{simulate:async e=>{if(!qx){let t=await SU("@tscircuit/ngspice-spice-engine").catch(n=>{throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.",{cause:n})});t&&(qx=await t())}if(!qx)throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.");return qx.simulate(e)}}},footprintLibraryMap:{kicad:async e=>{let t=`${xMt}/${e}`,n=`${t}.circuit.json`,o=await(await fetch(n)).json(),r=Array.isArray(o)?o.filter(a=>a?.type==="pcb_silkscreen_text"?a?.text==="REF**":!0):o,s=`${t}.wrl`;return{footprintCircuitJson:r,cadModel:{wrlUrl:s,modelUnitToMmScale:2.54}}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async e=>{let t=await fetch(e).then(i=>i.text()),n=await vU(t);return{footprintCircuitJson:Array.isArray(n)?n:[n]}}}}});var J4=Xt(Sn(),1),Ooe=(0,J4.default)("tsci:eval:execution-context");function Wx(e,t={}){globalThis.React=PU;let n=t.platform||wU(),i=t.projectConfig?{...n,...t.projectConfig}:n;i.partsEngineDisabled&&(i.partsEngine=void 0);let o=new Uh({platform:i});t.name&&(o.name=t.name),t.debugNamespace&&o.enableDebug(t.debugNamespace);let r=[];return{fsMap:{},entrypoint:"",logger:{info:s=>{r.push({msg:s})},getLogs:()=>r,stringifyLogs:()=>r.map(s=>s.msg).join(`
|
|
254
254
|
`)},preSuppliedImports:{"@tscircuit/core":Yx,tscircuit:Yx,"@tscircuit/math-utils":YI,react:PU,debug:J4.default,"@tscircuit/props":{}},circuit:o,tsConfig:null,importStack:[],currentlyImporting:new Set,...e}}function Cc(e){let t=e;return t=t.replace(/\\/g,"/"),t=t.trim(),t.startsWith("./")&&(t=t.slice(2)),t.startsWith("/")&&(t=t.slice(1)),t}function IU(e){let t={};for(let[n,i]of Object.entries(e))t[Cc(n)]=i;return t}function jr(e){if(!e)return".";let n=e.replace(/\\/g,"/").replace(/\/+$/,"");return n.indexOf("/")===-1?".":n.substring(0,n.lastIndexOf("/"))||"/"}function Zx(e,t){if(e.startsWith("../")){let n=jr(t);return Zx(e.slice(3),n)}return e.startsWith("./")?Zx(e.slice(2),t):e.startsWith("/")?e.slice(1):`${t}/${e}`}function Dm(e){if(Array.isArray(e))return null;let t=e["tsconfig.json"];if(!t)return null;try{let n=t.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,"");return JSON.parse(n)}catch(n){throw new Error(`Failed to parse tsconfig.json: ${n.message}`)}}function TU(e){let{importPath:t,normalizedFilePathMap:n,extensions:i,tsConfig:o}=e,r=o?.compilerOptions?.paths;if(!r)return null;let s=o?.compilerOptions?.baseUrl||".",a=l=>{let u=Cc(l);if(n.has(u))return n.get(u);for(let h of i){let d=`${u}.${h}`;if(n.has(d))return n.get(d)}return null};for(let[l,u]of Object.entries(r))if(l.includes("*")){let[d,_]=l.split("*");if(!t.startsWith(d)||!t.endsWith(_||""))continue;let y=t.slice(d.length,t.length-(_?_.length:0));for(let g of u){let x=g.replace("*",y),w=s&&!x.startsWith("./")&&!x.startsWith("/")?`${s}/${x}`:x,S=a(w);if(S)return S}}else{if(t!==l)continue;for(let d of u){let _=s&&!d.startsWith("./")&&!d.startsWith("/")?`${s}/${d}`:d,y=a(_);if(y)return y}}let c=Q4({importPath:t,normalizedFilePathMap:n,extensions:i,tsConfig:o});return c||null}function Q4(e){let{importPath:t,normalizedFilePathMap:n,extensions:i,tsConfig:o}=e,r=o?.compilerOptions?.baseUrl;if(!r)return null;let s=`${r}/${t}`,a=Cc(s);if(n.has(a))return n.get(a);for(let c of i){let l=`${a}.${c}`;if(n.has(l))return n.get(l)}return null}function MU(e,t){let n=t?.compilerOptions?.paths;if(!n)return!1;for(let[i]of Object.entries(n))if(i.includes("*")){let[r,s]=i.split("*");if(e.startsWith(r)&&e.endsWith(s||""))return!0}else if(e===i)return!0;return!1}var $m=(e,t,n,i={})=>{let o=n?Zx(e,n):e,r=new Set(Array.isArray(t)?t:Object.keys(t));if(r.has(o))return o;let s=new Map;for(let u of r)s.set(Cc(u),u);let a=Cc(o);if(s.has(a))return s.get(a);let c=["tsx","ts","json","js","jsx","obj","gltf","glb"];for(let u of c){let h=`${a}.${u}`;if(s.has(h))return s.get(h)}let l=i.tsConfig??null;if(!e.startsWith("./")&&!e.startsWith("../")){let u=TU({importPath:e,normalizedFilePathMap:s,extensions:c,tsConfig:l});if(u)return u;let h=Q4({importPath:e,normalizedFilePathMap:s,extensions:c,tsConfig:l});if(h)return h}if(!e.startsWith("./")&&!e.startsWith("../")){let u=Cc(e);if(s.has(u))return s.get(u);for(let h of c){let d=`${u}.${h}`;if(s.has(d))return s.get(d)}}return null},Kx=(e,t,n,i={})=>{let o=$m(e,t,n,i);if(!o)throw new Error(`File not found "${e}", available paths:
|