@tscircuit/eval 0.0.306 → 0.0.308
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blob-url.js +1 -1
- package/dist/eval/index.js +2 -2
- package/dist/lib/index.js +2 -2
- package/dist/webworker/entrypoint.js +1 -1
- package/lib/getPlatformConfig.ts +1 -1
- package/package.json +1 -1
|
@@ -1038,7 +1038,7 @@ ${f._facingDirection??CF(f,x)}`,x:f.x,y:f.y,color:Z0(f.pinId,.8)})}for(let x of
|
|
|
1038
1038
|
${s.stack}`),a.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:n,componentDisplayName:this.getString(),phase:a.phase,error:s.toString()})})}_emitRenderLifecycleEvent(n,e){fUt(`${n}:${e} ${this.getString()}`);let a=`renderable:renderLifecycle:${n}:${e}`,s={renderId:this._renderId,componentDisplayName:this.getString(),type:a};"root"in this&&this.root&&(this.root.emit(a,s),this.root.emit("renderable:renderLifecycle:anyEvent",{...s,type:a}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(n=>!n.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(n){for(let e of this._asyncEffects)if(!e.complete&&e.phase===n)return!0;for(let e of this.children)if(e._hasIncompleteAsyncEffectsInSubtreeForPhase(n))return!0;return!1}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(n=>n.getRenderGraph())}}runRenderCycle(){for(let n of id)this.runRenderPhaseForChildren(n),this.runRenderPhase(n)}runRenderPhase(n){this._currentRenderPhase=n;let e=this.renderPhaseStates[n],a=e.initialized,s=e.dirty;if(!a&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&a){this._emitRenderLifecycleEvent(n,"start"),this?.[`remove${n}`]?.(),e.initialized=!1,e.dirty=!1,this._emitRenderLifecycleEvent(n,"end");return}let l=id.indexOf(n)-1;if(l>=0){let x=id[l];if(this._asyncEffects.filter(m=>m.phase===x).some(m=>!m.complete))return}let p=hUt[n]||[];for(let x of p)if(this._hasIncompleteAsyncEffectsInSubtreeForPhase(x))return;if(this._emitRenderLifecycleEvent(n,"start"),a){s&&(this?.[`update${n}`]?.(),e.dirty=!1),this._emitRenderLifecycleEvent(n,"end");return}e.dirty=!1,this?.[`doInitial${n}`]?.(),e.initialized=!0,this._emitRenderLifecycleEvent(n,"end")}runRenderPhaseForChildren(n){for(let e of this.children)e.runRenderPhaseForChildren(n),e.runRenderPhase(n)}renderError(n){throw typeof n=="string"?new Error(n):new Error(JSON.stringify(n,null,2))}},LS={},FBe=n=>{let e=Object.fromEntries(Object.entries(n).map(([a,s])=>[a.toLowerCase(),s]));Object.assign(LS,n),Object.assign(LS,e)},gUt=class extends Error{constructor(n,e,a){let s,l=Object.keys(a).filter(m=>m!=="_errors"),p=[],x=e.pinLabels;if(x)for(let[m,D]of Object.entries(x)){let b=Array.isArray(D)?D:[D];for(let E of b)typeof E=="string"&&(E.startsWith(" ")||E.endsWith(" "))&&p.push(`pinLabels.${m} ("${E}" has leading or trailing spaces)`)}let f=l.map(m=>m==="pinLabels"&&p.length>0?p.join(", "):a[m]._errors[0]?`${m} (${a[m]._errors[0]})`:`${m} (${JSON.stringify(a[m])})`).join(", ");"name"in e?s=`Invalid props for ${n} "${e.name}": ${f}`:"footprint"in e&&typeof e.footprint=="string"?s=`Invalid props for ${n} (unnamed ${e.footprint} component): ${f}`:s=`Invalid props for ${n} (unnamed): ${f}`,super(s),this.componentName=n,this.originalProps=e,this.formattedError=a}};function jW(n,e){let a=e.match(/^#(\w+)/);if(a)return n.props.id===a[1];let s=e.match(/^\.(\w+)/);if(s)return n.isMatchingNameOrAlias(s[1]);let[l,...p]=e.split(/(?=[#.[])/);return l==="pin"&&(l="port"),l&&l!=="*"&&n.lowercaseComponentName!==l.toLowerCase()?!1:p.every(x=>{if(x.startsWith("#"))return n.props.id===x.slice(1);if(x.startsWith("."))return n.isMatchingNameOrAlias(x.slice(1));let f=x.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!f)return!0;let[,m,D]=f;return n.props[m].toString()===D})}var KW={isTag:n=>!0,getParent:n=>n.parent,getChildren:n=>n.children,getName:n=>n.lowercaseComponentName,getAttributeValue:(n,e)=>{if(e==="class"&&"getNameAndAliases"in n)return n.getNameAndAliases().join(" ");if(e==="name"&&n._parsedProps?.name)return n._parsedProps.name;if(n._parsedProps&&e in n._parsedProps){let s=n._parsedProps[e];return typeof s=="string"?s:s!=null?String(s):null}if(e in n){let s=n[e];return typeof s=="string"?s:s!=null?String(s):null}let a=n._attributeLowerToCamelNameMap;if(a){let s=a[e];if(s&&s in n){let l=n[s];return typeof l=="string"?l:l!=null?String(l):null}}return null},hasAttrib:(n,e)=>{if(e==="class")return!!n._parsedProps?.name;if(n._parsedProps&&e in n._parsedProps||e in n)return!0;let a=n._attributeLowerToCamelNameMap;if(a){let s=a[e];if(s&&s in n)return!0}return!1},getSiblings:n=>n.parent?n.parent.children:[],prevElementSibling:n=>{if(!n.parent)return null;let e=n.parent.children,a=e.indexOf(n);return a>0?e[a-1]:null},getText:()=>"",removeSubsets:n=>n.filter((e,a)=>!n.some((s,l)=>a!==l&&s!==e&&s.getDescendants().includes(e))),existsOne:(n,e)=>e.some(n),findAll:(n,e)=>{let a=[],s=l=>{n(l)&&a.push(l);for(let p of l.children)s(p)};for(let l of e)s(l);return a},findOne:(n,e)=>{for(let a of e){if(n(a))return a;let s=a.children;if(s.length>0){let l=KW.findOne(n,s);if(l)return l}}return null},equals:(n,e)=>n._renderId===e._renderId,isHovered:n=>!1,isVisited:n=>!1,isActive:n=>!1},DUt={...KW,getChildren:n=>n.children.filter(e=>!e.isSubcircuit)},KSe={...KW,getChildren:n=>n.children.filter(e=>e.isSubcircuit)},JSe=n=>{if(/net\.[^\s>]*\./.test(n))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(n))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(n)){let e=n.match(/net\.([^ >]+)/),a=e?e[1]:"";throw new Error(`Net name "${a}" cannot start with a number, try using a prefix like "VBUS1"`)}return n.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(e,a,s,l)=>{let p=/^\d+$/.test(l)?`pin${l}`:l;return`${a}.${s} > .${p}`}).trim()},kW={adapter:DUt,cacheResults:!0},ma=class extends WW{constructor(e){super(e);q(this,"parent",null);q(this,"children");q(this,"childrenPendingRemoval");q(this,"props");q(this,"_parsedProps");q(this,"externallyAddedAliases");q(this,"isPrimitiveContainer",!1);q(this,"canHaveTextChildren",!1);q(this,"source_group_id",null);q(this,"source_component_id",null);q(this,"schematic_component_id",null);q(this,"pcb_component_id",null);q(this,"cad_component_id",null);q(this,"fallbackUnassignedName");q(this,"_cachedSelectAllQueries",new Map);q(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=e??{},this.externallyAddedAliases=[];let s=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(e??{});if(s.success)this._parsedProps=s.data;else throw new gUt(this.lowercaseComponentName,this.props,s.error.format())}get config(){return{componentName:"",zodProps:C.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(e){let a=this;for(;a;){if(a._parsedProps&&e in a._parsedProps)return a._parsedProps[e];a=a.parent}if(this.root?.platform&&e in this.root.platform)return this.root.platform[e]}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(e){let a=this.config.zodProps.parse({...this.props,...e}),s=this.props;this.props=a,this._parsedProps=this.config.zodProps.parse(e),this.onPropsChange({oldProps:s,newProps:a,changedProps:Object.keys(e)}),this.parent?.onChildChanged?.(this)}computePcbPropsTransform(){let{_parsedProps:e}=this;return Ts(ka(e.pcbX??0,e.pcbY??0),Xf((e.pcbRotation??0)*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let{_parsedProps:e}=this,a=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(a&&this.props.pcbX===void 0&&this.props.pcbY===void 0)return Ts(this.parent?._computePcbGlobalTransformBeforeLayout()??_i(),Ts(ka(a.x,a.y),Xf((e.pcbRotation??0)*Math.PI/180)));if(this.isPcbPrimitive){let s=this.getPrimitiveContainer();if(s){let l=s._parsedProps.layer==="bottom",p=s._getGlobalPcbPositionBeforeLayout();if(l){let x=Ts(ka(p.x,p.y),Yq(),ka(-p.x,-p.y));return Ts(this.parent?._computePcbGlobalTransformBeforeLayout()??_i(),Yq(),this.computePcbPropsTransform())}}}return Ts(this.parent?._computePcbGlobalTransformBeforeLayout()??_i(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let e=this.getPrimitiveContainer(),a=e?e._parsedProps.layer==="bottom":!1;return{isFlipped:a,maybeFlipLayer:l=>a?l==="top"?"bottom":"top":l}}_setPositionFromLayout(e){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:e}=this;return Ts(ka(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){let e=this._getSchematicGlobalManualPlacementTransform(this);return e||Ts(this.parent?.computeSchematicGlobalTransform?.()??_i(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:e}=this,a=this.config.schematicSymbolName,s={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},l=e.schOrientation!==void 0?s[e.schOrientation]:e.schRotation;if(l===void 0&&(l=0),l=l%360,l<0&&(l+=360),e.schRotation!==void 0&&l%90!==0)throw new Error(`Schematic rotation ${e.schRotation} is not supported for ${this.componentName}`);let p=`${a}_horz`,x=`${a}_vert`,f=`${a}_up`,m=`${a}_down`,D=`${a}_left`,b=`${a}_right`;if(b in Ps&&l===0)return b;if(f in Ps&&l===90)return f;if(D in Ps&&l===180)return D;if(m in Ps&&l===270)return m;if(p in Ps&&(l===0||l===180))return p;if(x in Ps&&(l===90||l===270))return x;if(a in Ps)return a}_getSchematicSymbolNameOrThrow(){let e=this._getSchematicSymbolName();if(!e)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return e}getSchematicSymbol(){let e=this._getSchematicSymbolName();return e?Ps[e]??null:null}_getPcbManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let a=this.props.manualEdits;if(!a)return null;let s=a?.pcb_placements;if(!s)return null;for(let l of s)if(jW(e,l.selector)||e.props.name===l.selector)return rs(this._computePcbGlobalTransformBeforeLayout(),l.center);return null}_getSchematicManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let a=this.props.manualEdits;if(!a)return null;let s=a.schematic_placements;if(!s)return null;for(let l of s)if(jW(e,l.selector)||e.props.name===l.selector)return rs(this.computeSchematicGlobalTransform(),l.center);return null}_getSchematicGlobalManualPlacementTransform(e){let a=this.getSubcircuit()?._parsedProps.manualEdits;if(!a)return null;for(let s of a.schematic_placements??[])if((jW(e,s.selector)||e.props.name===s.selector)&&s.relative_to==="group_center")return Ts(this.parent?._computePcbGlobalTransformBeforeLayout()??_i(),ka(s.center.x,s.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return rs(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return rs(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(e){this.parent=e}onPropsChange(e){}onChildChanged(e){this.parent?.onChildChanged?.(e)}add(e){let a=e.__text;if(typeof a=="string"){if(this.canHaveTextChildren||a.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${a}"`)}if(Object.keys(e).length!==0){if(this.lowercaseComponentName==="board"&&e.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(!e.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(e)}"`);e.onAddToParent(this),e.parent=this,this.children.push(e)}}addAll(e){for(let a of e)this.add(a)}remove(e){this.children=this.children.filter(a=>a!==e),this.childrenPendingRemoval.push(e),e.shouldBeRemoved=!0}getSubcircuitSelector(){let e=this.name,a=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?a:`${this.parent.getSubcircuitSelector()} > ${a}`}getFullPathSelector(){let e=this.name,a=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName,s=this.parent?.getFullPathSelector?.();return s?`${s} > ${a}`:a}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(e){return this.getNameAndAliases().includes(e)}isMatchingAnyOf(e){return this.getNameAndAliases().some(a=>e.map(s=>s.toString()).includes(a))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(e){let a=[this.componentName,this.lowercaseComponentName],s=[this.name].filter(Boolean),l=e.trim().split(/\> /)[0],p=l[0];return l.length>1?!1:!!(e==="*"||e[0]==="#"&&e.slice(1)===this.props.id||e[0]==="."&&s.includes(e.slice(1))||/^[a-zA-Z0-9_]/.test(p)&&a.includes(p))}getSubcircuit(){if(this.isSubcircuit)return this;let e=this.parent?.getSubcircuit?.();if(!e)throw new Error("Component is not inside an opaque group (no board?)");return e}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let e=this.selectAll("port");for(let a of e){let s=a.parent?.getNameAndAliases(),l=a.getNameAndAliases();if(s)for(let p of s)for(let x of l){let f=[`.${p} > .${x}`,`.${p} .${x}`];for(let m of f){let D=this._cachedSelectAllQueries.get(m);D?D.push(a):this._cachedSelectAllQueries.set(m,[a])}}}for(let[a,s]of this._cachedSelectAllQueries.entries())s.length===1&&this._cachedSelectOneQueries.set(a,s[0])}selectAll(e){if(this._cachedSelectAllQueries.has(e))return this._cachedSelectAllQueries.get(e);let a=JSe(e),s=aY(a,this,kW);if(s.length>0)return this._cachedSelectAllQueries.set(e,s),s;let[l,...p]=a.split(" "),x=GR(l,this,{adapter:KSe});if(!x)return[];let f=x.selectAll(p.join(" "));return this._cachedSelectAllQueries.set(e,f),f}selectOne(e,a){if(this._cachedSelectOneQueries.has(e))return this._cachedSelectOneQueries.get(e);let s=JSe(e);a?.port&&(a.type="port");let l=null;if(a?.type&&(l=aY(s,this,kW).find(D=>D.lowercaseComponentName===a.type)),l??(l=GR(s,this,kW)),l)return this._cachedSelectOneQueries.set(e,l),l;let[p,...x]=s.split(" "),f=GR(p,this,{adapter:KSe});return f?(l=f.selectOne(x.join(" "),a),this._cachedSelectOneQueries.set(e,l),l):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:e}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[e(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?this.root?._getBoard()?.allLayers??["top","bottom"]:[]}return[]}getDescendants(){let e=[];for(let a of this.children)e.push(a),e.push(...a.getDescendants());return e}getSelectableDescendants(){let e=[];for(let a of this.children)a.isSubcircuit?e.push(a):(e.push(a),e.push(...a.getSelectableDescendants()));return e}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this;return{schWidth:e.schWidth,schHeight:e.schHeight}}renderError(e){if(typeof e=="string")return super.renderError(e);this.root?.db.pcb_placement_error.insert(e)}getString(){let{lowercaseComponentName:e,_parsedProps:a,parent:s}=this;return a?.pinNumber!==void 0&&s?.props?.name&&a?.name?`<${e}#${this._renderId}(pin:${a.pinNumber} .${s?.props.name}>.${a.name}) />`:s?.props?.name&&a?.name?`<${e}#${this._renderId}(.${s?.props.name}>.${a?.name}) />`:a?.from&&a?.to?`<${e}#${this._renderId}(from:${a.from} to:${a?.to}) />`:a?.name?`<${e}#${this._renderId} name=".${a?.name}" />`:a?.portHints?`<${e}#${this._renderId}(${a.portHints.map(l=>`.${l}`).join(", ")}) />`:`<${e}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},yUt=class extends ma{constructor(n,e){super(n),this._parsedProps={...n,error:e,type:n.type||"unknown",component_name:n.name,error_type:"source_failed_to_create_component_error",message:e instanceof Error?e.message:String(e),pcbX:n.pcbX,pcbY:n.pcbY,schX:n.schX,schY:n.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:C.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let n=this._getGlobalPcbPositionBeforeLayout(),e=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:n,schematic_center:e})}}};function bUt(n,e){return new yUt(n,e)}function FUt(n,e){let a=n;return a.__tsci={...e},n}var EUt={supportsMutation:!0,createInstance(n,e){let a=LS[n];if(!a)throw Object.keys(LS).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type "${n}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return FUt(new a(e),{})}catch(s){return bUt({...e,componentType:n},s)}},createTextInstance(n){return{__text:n}},appendInitialChild(n,e){n.add(e)},appendChild(n,e){n.add(e)},appendChildToContainer(n,e){n.add(e)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(n){return n},preparePortalMount(n){throw new Error("Function not implemented.")},scheduleTimeout(n,e){throw new Error("Function not implemented.")},cancelTimeout(n){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(n){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(n,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:n=>{throw new Error("Function not implemented.")},detachDeletedInstance:n=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>MS.DefaultEventPriority,getCurrentUpdatePriority:()=>MS.DefaultEventPriority,resolveUpdatePriority:()=>MS.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},jS=(0,yBe.default)(EUt),EBe=n=>{let e={children:[],props:{name:"$root"},add(p){p.parent=this,this.children.push(p)},computePcbGlobalTransform(){return _i()}},a=[],s=jS.createContainer(e,0,null,!1,null,"tsci",p=>{console.log("Error in createContainer"),console.error(p),a.push(p)},null);if(jS.updateContainerSync(n,s,null,()=>{}),jS.flushSyncWork(),a.length>0)throw a[0];let l=jS.getPublicRootInstance(s);return l||e.children[0]},OF=(n,e)=>{if(typeof n=="number")return n;if(n.startsWith("pin"))return Number(n.slice(3));if(!e)throw new Error(`No pin labels provided and pin number or label is not a number: "${n}"`);for(let a in e)if((Array.isArray(e[a])?e[a]:[e[a]]).includes(n))return Number(a.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${n}"`)},vUt=(n,e)=>{if(!n)return;let a={},s={};for(let[l,p]of Object.entries(n)){let x=OF(l,e);s[x]={...s[x],...p}}for(let[l,p]of Object.entries(s)){let x=`pin${l}`;a[x]={bottom_margin:p.bottomMargin,left_margin:p.leftMargin,right_margin:p.rightMargin,top_margin:p.topMargin}}return a},CUt=n=>{if(n){if("leftSide"in n||"rightSide"in n||"topSide"in n||"bottomSide"in n)return{left_side:n.leftSide,right_side:n.rightSide,top_side:n.topSide,bottom_side:n.bottomSide};if("leftPinCount"in n||"rightPinCount"in n||"topPinCount"in n||"bottomPinCount"in n)return{left_size:n.leftPinCount,right_size:n.rightPinCount,top_size:n.topPinCount,bottom_size:n.bottomPinCount};if("leftSize"in n||"rightSize"in n||"topSize"in n||"bottomSize"in n)return{left_size:n.leftSize,right_size:n.rightSize,top_size:n.topSize,bottom_size:n.bottomSize}}};function vBe(n){let e=[];for(let a=0;a<n.length-1;a++)e.push([n[a],n[a+1]]);return e}var _Ut=C.object({name:C.string().refine(n=>!/[+-]/.test(n),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),JW=class extends ma{constructor(){super(...arguments);q(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:_Ut}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=a.name.startsWith("GND"),l=a.name.startsWith("V"),p=e.source_net.insert({name:a.name,member_source_group_ids:[],is_ground:s,is_power:l,is_positive_voltage_source:l});this.source_net_id=p.source_net_id}doInitialSourceParentAttachment(){let e=this.getSubcircuit();if(!e)return;let{db:a}=this.root;a.source_net.update(this.source_net_id,{subcircuit_id:e.subcircuit_id})}getAllConnectedPorts(){let e=this.getSubcircuit().selectAll("port"),a=[];for(let s of e){let l=s._getDirectlyConnectedTraces();for(let p of l)if(p._isExplicitlyConnectedToNet(this)){a.push(s);break}}return a}_getAllDirectlyConnectedTraces(){let e=this.getSubcircuit().selectAll("trace"),a=[];for(let s of e)s._isExplicitlyConnectedToNet(this)&&a.push(s);return a}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getAllDirectlyConnectedTraces().filter(x=>(x._portsRoutedOnPcb?.length??0)>0),l=[];for(let x of s){let f=x._portsRoutedOnPcb,m=l.find(D=>f.some(b=>D.ports.includes(b)));if(!m){l.push({ports:[...f],traces:[x]});continue}m.traces.push(x),m.ports.push(...f)}if(l.length===0)return;let p=vBe(l);for(let[x,f]of p){let m=x.ports.map(O=>O._getGlobalPcbPositionBeforeLayout()),D=f.ports.map(O=>O._getGlobalPcbPositionBeforeLayout()),b=1/0,E=[-1,-1];for(let O=0;O<m.length;O++){let $=m[O];for(let ee=0;ee<D.length;ee++){let X=D[ee],te=Math.sqrt(($.x-X.x)**2+($.y-X.y)**2);te<b&&(b=te,E=[O,ee])}}let A=x.ports[E[0]],B=f.ports[E[1]],w=e.toArray().filter(O=>O.type==="pcb_smtpad"||O.type==="pcb_trace"||O.type==="pcb_plated_hole"||O.type==="pcb_hole"||O.type==="source_port"||O.type==="pcb_port"),{solution:P}=T_e(w.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[A.source_port_id,B.source_port_id]}])),N=P[0];if(!N){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[A.pcb_component_id,B.pcb_component_id].filter(Boolean),pcb_port_ids:[A.pcb_port_id,B.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}e.pcb_trace.insert(N)}}renderError(e){if(typeof e=="string")return super.renderError(e);this.root?.db.pcb_trace_error.insert(e)}},ZW=(n,e)=>{for(let a of e)if(typeof a=="string"&&a.startsWith("net.")){if(/net\.[^\s>]*\./.test(a))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(a))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(a)){let l=a.split("net.")[1];throw new Error(`Net name "${l}" cannot start with a number, try using a prefix like "VBUS1"`)}let s=n.getSubcircuit();if(!s.selectOne(a)){let l=new JW({name:a.split("net.")[1]});s.add(l)}}},$S=class extends ma{constructor(){super(...arguments);q(this,"pcb_smtpad_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:tAe}}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="polygon"){let a=e.points,s=a.map(D=>D.x),l=a.map(D=>D.y),p=Math.min(...s),x=Math.max(...s),f=Math.min(...l),m=Math.max(...l);return{width:x-p,height:m-f}}throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let a of e)if(a.isMatchingAnyOf(this.props.portHints)){this.matchedPort=a,a.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this;if(!a.portHints)return;let s=this.getPrimitiveContainer(),l=this.getSubcircuit(),p=this._getGlobalPcbPositionBeforeLayout(),x=s?._getGlobalPcbPositionBeforeLayout(),f=QA(this._computePcbGlobalTransformBeforeLayout()),m=Math.abs(f.rotation.angle*(180/Math.PI)-90)%180<.01,{maybeFlipLayer:D}=this._getPcbPrimitiveFlippedHelpers(),b=s?._parsedProps.pcbRotation??0,E=null,A=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;a.shape==="circle"?(E=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"circle",radius:a.radius,port_hints:a.portHints.map(B=>B.toString()),x:p.x,y:p.y,subcircuit_id:l?.subcircuit_id??void 0}),e.pcb_solder_paste.insert({layer:E.layer,shape:"circle",radius:E.radius*.7,x:E.x,y:E.y,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):a.shape==="rect"?(E=b===0||m?e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"rect",width:m?a.height:a.width,height:m?a.width:a.height,port_hints:a.portHints.map(B=>B.toString()),x:p.x,y:p.y,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):e.pcb_smtpad.insert({pcb_component_id:A,layer:D(a.layer??"top"),shape:"rotated_rect",width:a.width,height:a.height,x:p.x,y:p.y,ccw_rotation:b,port_hints:a.portHints.map(B=>B.toString()),subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),E.shape==="rect"&&e.pcb_solder_paste.insert({layer:D(a.layer??"top"),shape:"rect",width:E.width*.7,height:E.height*.7,x:E.x,y:E.y,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),E.shape==="rotated_rect"&&e.pcb_solder_paste.insert({layer:D(a.layer??"top"),shape:"rotated_rect",width:E.width*.7,height:E.height*.7,x:E.x,y:E.y,ccw_rotation:b,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):a.shape==="polygon"&&(E=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"polygon",points:a.points.map(B=>({x:B.x+p.x,y:B.y+p.y})),port_hints:a.portHints.map(B=>B.toString()),subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})),E&&(this.pcb_smtpad_id=E.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_smtpad.get(this.pcb_smtpad_id);if(a.shape==="rect")return{center:{x:a.x,y:a.y},bounds:{left:a.x-a.width/2,top:a.y+a.height/2,right:a.x+a.width/2,bottom:a.y-a.height/2},width:a.width,height:a.height};if(a.shape==="rotated_rect"){let s=a.ccw_rotation*Math.PI/180,l=Math.cos(s),p=Math.sin(s),x=a.width/2,f=a.height/2,m=Math.abs(x*l)+Math.abs(f*p),D=Math.abs(x*p)+Math.abs(f*l);return{center:{x:a.x,y:a.y},bounds:{left:a.x-m,right:a.x+m,top:a.y-D,bottom:a.y+D},width:m*2,height:D*2}}if(a.shape==="circle")return{center:{x:a.x,y:a.y},bounds:{left:a.x-a.radius,top:a.y-a.radius,right:a.x+a.radius,bottom:a.y+a.radius},width:a.radius*2,height:a.radius*2};if(a.shape==="polygon"){let s=a.points,l=s.map(b=>b.x),p=s.map(b=>b.y),x=Math.min(...l),f=Math.max(...l),m=Math.min(...p),D=Math.max(...p);return{center:{x:(x+f)/2,y:(m+D)/2},bounds:{left:x,top:D,right:f,bottom:m},width:f-x,height:D-m}}throw new Error(`circuitJson bounds calculation not implemented for shape "${a.shape}"`)}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_smtpad.update(this.pcb_smtpad_id,{x:e.x,y:e.y});let s=a.pcb_solder_paste.list().find(l=>l.pcb_smtpad_id===this.pcb_smtpad_id);a.pcb_solder_paste.update(s?.pcb_solder_paste_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}},QW=class extends ma{constructor(){super(...arguments);q(this,"pcb_silkscreen_path_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:wAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenPath. Must be "top" or "bottom".`);let p=this._computePcbGlobalTransformBeforeLayout(),x=this.getSubcircuit(),f=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=e.pcb_silkscreen_path.insert({pcb_component_id:f,layer:l,route:a.route.map(D=>{let b=rs(p,{x:D.x,y:D.y});return{...D,x:b.x,y:b.y}}),stroke_width:a.strokeWidth??.1,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=m.pcb_silkscreen_path_id}_setPositionFromLayout(e){let{db:a}=this.root,{_parsedProps:s}=this,l=a.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!l)return;let p=0,x=0;for(let b of l.route)p+=b.x,x+=b.y;p/=l.route.length,x/=l.route.length;let f=e.x-p,m=e.y-x,D=l.route.map(b=>({...b,x:b.x+f,y:b.y+m}));a.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:D})}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let a=1/0,s=-1/0,l=1/0,p=-1/0;for(let x of e.route)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),p=Math.max(p,x.y);return{width:s-a,height:p-l}}},AUt=C.object({route:C.array(MA),source_trace_id:C.string().optional()}),eK=class extends ma{constructor(){super(...arguments);q(this,"pcb_trace_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:AUt}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer(),l=this.getSubcircuit(),{maybeFlipLayer:p}=this._getPcbPrimitiveFlippedHelpers(),x=this._computePcbGlobalTransformBeforeLayout(),f=a.route.map(D=>{let{x:b,y:E,...A}=D,B=rs(x,{x:b,y:E});return D.route_type==="wire"&&D.layer?{...B,...A,layer:p(D.layer)}:{...B,...A}}),m=e.pcb_trace.insert({pcb_component_id:s.pcb_component_id,source_trace_id:a.source_trace_id,route:f,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=m.pcb_trace_id}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let a=1/0,s=-1/0,l=1/0,p=-1/0;for(let x of e.route)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),p=Math.max(p,x.y),x.route_type==="wire"&&(a=Math.min(a,x.x-x.width/2),s=Math.max(s,x.x+x.width/2),l=Math.min(l,x.y-x.width/2),p=Math.max(p,x.y+x.width/2));return a===1/0||s===-1/0||l===1/0||p===-1/0?{width:0,height:0}:{width:s-a,height:p-l}}},zS=class extends ma{constructor(){super(...arguments);q(this,"pcb_plated_hole_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:G_e}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.outerDiameter,height:e.outerDiameter};if(e.shape==="oval"||e.shape==="pill")return{width:e.outerWidth,height:e.outerHeight};if(e.shape==="circular_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};if(e.shape==="pill_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_plated_hole.get(this.pcb_plated_hole_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y+s.height/2,right:a.x+s.width/2,bottom:a.y-s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let a of e)if(a.isMatchingAnyOf(this.props.portHints)){this.matchedPort=a,a.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,p=this.getSubcircuit();if(a.shape==="circle"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:a.outerDiameter,hole_diameter:a.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:a.outerDiameter/2,x:s.x,y:s.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:a.outerDiameter/2,x:s.x,y:s.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(a.shape==="pill"&&a.rectPad){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:a.outerWidth,outer_height:a.outerHeight,hole_width:a.holeWidth,hole_height:a.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:a.pcbRotation??0,rect_ccw_rotation:a.pcbRotation??0,rect_pad_width:a.outerWidth,rect_pad_height:a.outerHeight});this.pcb_plated_hole_id=x.pcb_plated_hole_id}else if(a.shape==="pill"||a.shape==="oval"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:a.outerWidth,outer_height:a.outerHeight,hole_width:a.holeWidth,hole_height:a.holeHeight,shape:a.shape,port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:a.shape,width:a.outerWidth,height:a.outerHeight,x:s.x,y:s.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:a.shape,width:a.outerWidth,height:a.outerHeight,x:s.x,y:s.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(a.shape==="circular_hole_with_rect_pad"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:a.holeDiameter,rect_pad_width:a.rectPadWidth,rect_pad_height:a.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id}else if(a.shape==="pill_hole_with_rect_pad"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:a.holeWidth,hole_height:a.holeHeight,rect_pad_width:a.rectPadWidth,rect_pad_height:a.rectPadHeight,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},qS=class extends ma{constructor(){super(...arguments);q(this,"pcb_keepout_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:EAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let e=this.getSubcircuit(),{db:a}=this.root,{_parsedProps:s}=this,l=this._getGlobalPcbPositionBeforeLayout(),p=QA(this._computePcbGlobalTransformBeforeLayout()),x=Math.abs(p.rotation.angle*(180/Math.PI)-90)%180<.01,f=null;s.shape==="circle"?f=a.pcb_keepout.insert({layers:["top"],shape:"circle",radius:s.radius,center:{x:l.x,y:l.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0}):s.shape==="rect"&&(f=a.pcb_keepout.insert({layers:["top"],shape:"rect",...x?{width:s.height,height:s.width}:{width:s.width,height:s.height},center:{x:l.x,y:l.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0})),f&&(this.pcb_keepout_id=f.pcb_keepout_id)}},tK=class extends ma{constructor(){super(...arguments);q(this,"pcb_hole_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:rAe}}getPcbSize(){let{_parsedProps:e}=this;return{width:e.diameter,height:e.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=this._getGlobalPcbPositionBeforeLayout(),p=e.pcb_hole.insert({hole_shape:"circle",hole_diameter:a.diameter,x:l.x,y:l.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:s?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=p.pcb_hole_id}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_hole.get(this.pcb_hole_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y-s.height/2,right:a.x+s.width/2,bottom:a.y+s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_hole.update(this.pcb_hole_id,{x:e.x,y:e.y})}},YS=class extends ma{constructor(){super(...arguments);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:BAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer(),l=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:p}=this._getPcbPrimitiveFlippedHelpers(),x=this.getSubcircuit(),f=new Set(a.layers);a.layer&&f.add(a.layer);let m=f.size>0?Array.from(f):["top"];for(let D of m)e.pcb_silkscreen_text.insert({anchor_alignment:a.anchorAlignment,anchor_position:{x:l.x,y:l.y},font:a.font??"tscircuit2024",font_size:a.fontSize??1,layer:p(D),text:a.text??"",ccw_rotation:a.pcbRotation,pcb_component_id:s.pcb_component_id,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:e}=this,a=e.fontSize??1,l=(e.text??"").length*a,p=a;return{width:l*a,height:p*a}}},MF=class extends ma{constructor(){super(...arguments);q(this,"pcb_cutout_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:eAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=this.getGroup()?.pcb_group_id??void 0,p=this._getGlobalPcbPositionBeforeLayout(),f=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,m;if(a.shape==="rect"){let D=typeof f=="string"?parseInt(f.replace("deg",""),10):f,b=Math.abs(D%180)===90,E={shape:"rect",center:p,width:b?a.height:a.width,height:b?a.width:a.height,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(E)}else if(a.shape==="circle"){let D={shape:"circle",center:p,radius:a.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(D)}else if(a.shape==="polygon"){let D=this._computePcbGlobalTransformBeforeLayout(),E={shape:"polygon",points:a.points.map(A=>rs(D,A)),subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(E)}m&&(this.pcb_cutout_id=m.pcb_cutout_id)}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="polygon"){if(e.points.length===0)return{width:0,height:0};let a=1/0,s=-1/0,l=1/0,p=-1/0;for(let x of e.points)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),p=Math.max(p,x.y);return{width:s-a,height:p-l}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,a=e.pcb_cutout.get(this.pcb_cutout_id);if(!a)return super._getPcbCircuitJsonBounds();if(a.shape==="rect")return{center:a.center,bounds:{left:a.center.x-a.width/2,top:a.center.y+a.height/2,right:a.center.x+a.width/2,bottom:a.center.y-a.height/2},width:a.width,height:a.height};if(a.shape==="circle")return{center:a.center,bounds:{left:a.center.x-a.radius,top:a.center.y+a.radius,right:a.center.x+a.radius,bottom:a.center.y-a.radius},width:a.radius*2,height:a.radius*2};if(a.shape==="polygon"){if(a.points.length===0)return super._getPcbCircuitJsonBounds();let s=1/0,l=-1/0,p=1/0,x=-1/0;for(let f of a.points)s=Math.min(s,f.x),l=Math.max(l,f.x),p=Math.min(p,f.y),x=Math.max(x,f.y);return{center:{x:(s+l)/2,y:(p+x)/2},bounds:{left:s,top:x,right:l,bottom:p},width:l-s,height:x-p}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(e){if(!this.pcb_cutout_id)return;let{db:a}=this.root,s=a.pcb_cutout.get(this.pcb_cutout_id);if(s){if(s.shape==="rect"||s.shape==="circle")a.pcb_cutout.update(this.pcb_cutout_id,{...s,center:e});else if(s.shape==="polygon"){let l=this._getPcbCircuitJsonBounds().center,p=e.x-l.x,x=e.y-l.y,f=s.points.map(m=>({x:m.x+p,y:m.y+x}));a.pcb_cutout.update(this.pcb_cutout_id,{...s,points:f})}}}},RUt=({elm:n,pinLabels:e,layer:a,readableRotation:s,anchorAlignment:l})=>{let p=n.text.replace(/[{}]/g,"").toLowerCase(),x=p;if(Array.isArray(e)){let f=parseInt(p.replace(/[^\d]/g,""),10)-1;x=String(e[f]??p)}else typeof e=="object"&&(x=String(e[p]??p));return new YS({anchorAlignment:l||"center",text:x??p,layer:a||"top",fontSize:n.font_size+.2,pcbX:isNaN(n.anchor_position.x)?0:n.anchor_position.x,pcbY:n.anchor_position.y,pcbRotation:s??0})},SUt=(n,e)=>((-parseInt(n||"0",10)+(e??0))%360+360)%360,zW=({componentName:n,componentRotation:e,footprint:a,pinLabels:s,pcbPinLabels:l},p)=>{let x=[];for(let f of p)if(f.type==="pcb_smtpad"&&f.shape==="rect")x.push(new $S({pcbX:f.x,pcbY:f.y,layer:f.layer,shape:"rect",height:f.height,width:f.width,portHints:f.port_hints}));else if(f.type==="pcb_smtpad"&&f.shape==="circle")x.push(new $S({pcbX:f.x,pcbY:f.y,layer:f.layer,shape:"circle",radius:f.radius,portHints:f.port_hints}));else if(f.type==="pcb_silkscreen_path")x.push(new QW({layer:f.layer,route:f.route,strokeWidth:f.stroke_width}));else if(f.type==="pcb_plated_hole")f.shape==="circle"?x.push(new zS({pcbX:f.x,pcbY:f.y,shape:"circle",holeDiameter:f.hole_diameter,outerDiameter:f.outer_diameter,portHints:f.port_hints})):f.shape==="circular_hole_with_rect_pad"&&x.push(new zS({pcbX:f.x,pcbY:f.y,shape:"circular_hole_with_rect_pad",holeDiameter:f.hole_diameter,rectPadHeight:f.rect_pad_height,rectPadWidth:f.rect_pad_width,portHints:f.port_hints}));else if(f.type==="pcb_keepout"&&f.shape==="circle")x.push(new qS({pcbX:f.center.x,pcbY:f.center.y,shape:"circle",radius:f.radius}));else if(f.type==="pcb_keepout"&&f.shape==="rect")x.push(new qS({pcbX:f.center.x,pcbY:f.center.y,shape:"rect",width:f.width,height:f.height}));else if(f.type==="pcb_hole"&&f.hole_shape==="circle")x.push(new tK({pcbX:f.x,pcbY:f.y,diameter:f.hole_diameter}));else if(f.type==="pcb_cutout")f.shape==="rect"?x.push(new MF({pcbX:f.center.x,pcbY:f.center.y,shape:"rect",width:f.width,height:f.height})):f.shape==="circle"?x.push(new MF({pcbX:f.center.x,pcbY:f.center.y,shape:"circle",radius:f.radius})):f.shape==="polygon"&&x.push(new MF({shape:"polygon",points:f.points}));else if(f.type==="pcb_silkscreen_text"){let m=SUt(e,f.ccw_rotation);a.includes("pinrow")&&f.text.includes("PIN")?x.push(RUt({elm:f,pinLabels:l??s,layer:f.layer,readableRotation:m,anchorAlignment:f.anchor_alignment})):x.push(new YS({anchorAlignment:f.anchor_alignment||"center",text:n,fontSize:f.font_size+.2,pcbX:Number.isNaN(f.anchor_position.x)?0:f.anchor_position.x,pcbY:f.anchor_position.y,pcbRotation:m??0}))}else f.type==="pcb_trace"&&x.push(new eK({route:f.route}));return x};function rK(n){let e=1/0,a=1/0,s=-1/0,l=-1/0,p=!1;for(let m of n)if(m.isPcbPrimitive&&!m.componentName.startsWith("Silkscreen")){let{x:D,y:b}=m._getGlobalPcbPositionBeforeLayout(),{width:E,height:A}=m.getPcbSize();e=Math.min(e,D-E/2),a=Math.min(a,b-A/2),s=Math.max(s,D+E/2),l=Math.max(l,b+A/2),p=!0}else if(m.children.length>0){let D=rK(m.children);(D.width>0||D.height>0)&&(e=Math.min(e,D.minX),a=Math.min(a,D.minY),s=Math.max(s,D.maxX),l=Math.max(l,D.maxY),p=!0)}if(!p)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let x=s-e,f=l-a;return x<0&&(x=0),f<0&&(f=0),{minX:e,minY:a,maxX:s,maxY:l,width:x,height:f}}function BUt(n,e){let a=e.x-n.x,s=e.y-n.y;return Math.abs(a)>Math.abs(s)?a>=0?"right":"left":s>=0?"up":"down"}var ZSe=n=>{if(n.length<=1)return!0;let e=n.map(p=>{let x=p._getPcbCircuitJsonBounds();return{left:x.bounds.left,right:x.bounds.right,top:x.bounds.top,bottom:x.bounds.bottom}}),a=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let p=0;p<e.length;p++)for(let x=p+1;x<e.length;x++){let f=e[p],m=e[x];a[p][x]=a[x][p]=!(f.right<m.left||f.left>m.right||f.bottom>m.top||f.top<m.bottom)}let s=new Set,l=p=>{s.add(p);for(let x=0;x<e.length;x++)a[p][x]&&!s.has(x)&&l(x)};return l(0),s.size===e.length},QSe=n=>{if(n.length===0)throw new Error("Cannot get center of empty PCB primitives array");let e=n.map(l=>l._getPcbCircuitJsonBounds().center).filter(Boolean),a=e.reduce((l,p)=>l+p.x,0),s=e.reduce((l,p)=>l+p.y,0);return{x:a/e.length,y:s/e.length}},wUt=C.object({name:C.string().optional(),pinNumber:C.number().optional(),aliases:C.array(C.string()).optional(),layer:C.string().optional(),layers:C.array(C.string()).optional()}),Ii=class extends ma{constructor(e,a={}){if(!e.name&&e.pinNumber!==void 0&&(e.name=`pin${e.pinNumber}`),!e.name)throw new Error("Port must have a name or a pinNumber");super(e);q(this,"source_port_id",null);q(this,"pcb_port_id",null);q(this,"schematic_port_id",null);q(this,"schematicSymbolPortDef",null);q(this,"matchedComponents");q(this,"facingDirection",null);q(this,"originDescription",null);a.originDescription&&(this.originDescription=a.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:wUt}}_getGlobalPcbPositionBeforeLayout(){let e=this.matchedComponents.find(s=>s.isPcbPrimitive),a=this.parent;if(a&&!a.props.footprint)throw new Error(`${a.componentName} "${a.props.name}" does not have a footprint. Add a footprint prop, e.g. <${a.componentName.toLowerCase()} footprint="..." />`);if(!e)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return e?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,a=e.pcb_port.get(this.pcb_port_id);return{center:{x:a.x,y:a.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let e=this.parent;if(!e||!e._getInternallyConnectedPins)return[];let a=e._getInternallyConnectedPins();for(let s of a)if(s.some(l=>l===this))return s;return[]}_hasSchematicPort(){if(this.parent?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(l=>l.schematicSymbolPortDef));let a=this?.parent?._getSchematicBoxDimensions();return!!(a&&this.props.pinNumber!==void 0&&a.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let e=this.parent?.getSchematicSymbol();if(e){let s=this.schematicSymbolPortDef;if(!s&&(s=this._getPortsInternallyConnectedToThisPort().find(p=>p.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!s))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let l=Ts(this.parent.computeSchematicGlobalTransform(),ka(-e.center.x,-e.center.y));return rs(l,s)}let a=this?.parent?._getSchematicBoxDimensions();if(a&&this.props.pinNumber!==void 0){let s=a.getPortPositionByPinNumber(this.props.pinNumber);if(!s)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return rs(this.parent.computeSchematicGlobalTransform(),s)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:e}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let a=e.schematic_port.get(this.schematic_port_id);if(!a)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return a.center}registerMatch(e){this.matchedComponents.push(e)}getNameAndAliases(){let{_parsedProps:e}=this;return Array.from(new Set([...e.name?[e.name]:[],...e.aliases??[],...typeof e.pinNumber=="number"?[`pin${e.pinNumber}`,e.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}isMatchingPort(e){return this.isMatchingAnyOf(e.getNameAndAliases())}getPortSelector(){return`.${this.parent?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:e,layers:a}=this._parsedProps;return a||(e?[e]:Array.from(new Set(this.matchedComponents.flatMap(s=>s.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(s=>!s._couldNotFindPort).filter(s=>s._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getNameAndAliases(),l=e.source_port.insert({name:a.name,pin_number:a.pinNumber,port_hints:s,source_component_id:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=l.source_port_id}doInitialSourceParentAttachment(){let{db:e}=this.root;if(!this.parent?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);e.source_port.update(this.source_port_id,{source_component_id:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=this.parent?.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{matchedComponents:a}=this;if(!this.parent?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()})`);let s=a.filter(p=>p.isPcbPrimitive);if(s.length===0)return;let l=null;if(s.length===1&&(l=s[0]._getPcbCircuitJsonBounds().center),s.length>1){if(!ZSe(s))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${s.map(p=>p.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);l=QSe(s)}if(l){let p=this.getSubcircuit(),x=e.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...l,source_port_id:this.source_port_id});this.pcb_port_id=x.pcb_port_id}else{let p=s[0];throw new Error(`${p.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;if(this.pcb_port_id)return;let a=this.matchedComponents.filter(x=>x.isPcbPrimitive);if(a.length===0)return;let s=null;if(a.length===1&&(s=a[0]._getPcbCircuitJsonBounds().center),a.length>1)try{ZSe(a)&&(s=QSe(a))}catch{}if(!s)return;let l=this.getSubcircuit(),p=e.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...s,source_port_id:this.source_port_id});this.pcb_port_id=p.pcb_port_id}doInitialSchematicPortRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer();if(!s||!this._hasSchematicPort())return;let l=s._getGlobalSchematicPositionBeforeLayout(),p=this._getGlobalSchematicPositionBeforeLayout(),x=null,f=s._getSchematicBoxDimensions();f&&a.pinNumber!==void 0&&(x=f.getPortPositionByPinNumber(a.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&e.schematic_debug_object.insert({shape:"rect",center:p,size:{width:.1,height:.1},label:"obstacle"}),x?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[x.side]:this.facingDirection=BUt(l,p);let m=e.source_port.get(this.source_port_id),D=[];for(let P of m?.port_hints??[])P.match(/^(pin)?\d+$/)||P.match(/^(left|right)/)&&!m?.name.match(/^(left|right)/)||D.push(P);let b;this.parent?.props?.showPinAliases&&D.length>0?b=D.join("/"):D.length>0&&(b=D[0]);let A=this.parent?._parsedProps?.pinAttributes,B={type:"schematic_port",schematic_component_id:this.parent?.schematic_component_id,center:p,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:x?.side,pin_number:a.pinNumber,true_ccw_index:x?.trueIndex,display_pin_label:b,is_connected:!1};if(A){for(let P of this.getNameAndAliases())if(A[P]){let N=A[P];N.requiresPower&&(B.has_input_arrow=!0),N.providesPower&&(B.has_output_arrow=!0)}}let w=e.schematic_port.insert(B);this.schematic_port_id=w.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(e){let{db:a}=this.root;this.pcb_port_id&&a.pcb_port.update(this.pcb_port_id,{x:e.x,y:e.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(e=>e.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},CBe=n=>{let e=n.find(a=>/^(pin)?\d+$/.test(a));return e?Number.parseInt(e.replace(/^pin/,"")):null};function IF(n,e){let a=CBe(n);if(!a)return null;let l=[...n.filter(p=>p.toString()!==a.toString()&&p!==`pin${a}`),...e?.additionalAliases?.[`pin${a}`]??[]];return new Ii({pinNumber:a,aliases:l})}var TUt=n=>{for(let e of["leftSide","rightSide","topSide","bottomSide"])if(e in n&&typeof n[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in n||"rightSide"in n||"topSide"in n||"bottomSide"in n},PUt=n=>{if(TUt(n))return{leftSize:n.leftSide?.pins.length??0,rightSize:n.rightSide?.pins.length??0,topSize:n.topSide?.pins.length??0,bottomSize:n.bottomSide?.pins.length??0};let{leftSize:e=0,rightSize:a=0,topSize:s=0,bottomSize:l=0}=n;return{leftSize:e,rightSize:a,topSize:s,bottomSize:l}};function _Be(n){let e=n;return e.leftSide!==void 0||e.rightSide!==void 0||e.topSide!==void 0||e.bottomSide!==void 0}var IUt=n=>{let e=n.portDistanceFromEdge??.4,a=n.schPortArrangement?PUt(n.schPortArrangement):null,s={left:0,right:0,top:0,bottom:0},l=n.pinCount??null;if(l===null)if(a)l=a.leftSize+a.rightSize+a.topSize;else throw new Error("Could not determine pin count for the schematic box");if(l&&!a){let w=Math.floor(l/2);a={leftSize:l-w,rightSize:w,topSize:0,bottomSize:0}}a||(a={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let p=({side:w,sideIndex:P,truePinIndex:N})=>{if(!n.schPortArrangement||!_Be(n.schPortArrangement))return N+1;let O={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[w],$=n.schPortArrangement?.[`${w}Side`]?.direction??O,ee=n.schPortArrangement?.[`${w}Side`]?.pins,X=P;return $!==O&&(X=ee.length-P-1),OF(ee[X],n.pinLabels)},x=[],f=0,m=0;for(let w=0;w<a.leftSize;w++){let P=p({side:"left",sideIndex:w,truePinIndex:m}),N=n.numericSchPinStyle?.[`pin${P}`]??n.numericSchPinStyle?.[P];N?.topMargin&&(f+=N.topMargin),x.push({trueIndex:m,pinNumber:P,side:"left",distanceFromOrthogonalEdge:f}),N?.bottomMargin&&(f+=N.bottomMargin),w===a.leftSize-1?s.left=f:f+=n.schPinSpacing,m++}f=0;for(let w=0;w<a.bottomSize;w++){let P=p({side:"bottom",sideIndex:w,truePinIndex:m}),N=n.numericSchPinStyle?.[`pin${P}`]??n.numericSchPinStyle?.[P];N?.leftMargin&&(f+=N.leftMargin),x.push({trueIndex:m,pinNumber:P,side:"bottom",distanceFromOrthogonalEdge:f}),N?.rightMargin&&(f+=N.rightMargin),w===a.bottomSize-1?s.bottom=f:f+=n.schPinSpacing,m++}f=0;for(let w=0;w<a.rightSize;w++){let P=p({side:"right",sideIndex:w,truePinIndex:m}),N=n.numericSchPinStyle?.[`pin${P}`]??n.numericSchPinStyle?.[P];N?.bottomMargin&&(f+=N.bottomMargin),x.push({trueIndex:m,pinNumber:P,side:"right",distanceFromOrthogonalEdge:f}),N?.topMargin&&(f+=N.topMargin),w===a.rightSize-1?s.right=f:f+=n.schPinSpacing,m++}f=0;for(let w=0;w<a.topSize;w++){let P=p({side:"top",sideIndex:w,truePinIndex:m}),N=n.numericSchPinStyle?.[`pin${P}`]??n.numericSchPinStyle?.[P];N?.rightMargin&&(f+=N.rightMargin),x.push({trueIndex:m,pinNumber:P,side:"top",distanceFromOrthogonalEdge:f}),N?.leftMargin&&(f+=N.leftMargin),w===a.topSize-1?s.top=f:f+=n.schPinSpacing,m++}let D=n.schWidth;if(D===void 0){D=Math.max(s.top+n.schPinSpacing*2,s.bottom+n.schPinSpacing*2);let w=n.pinLabels?Math.max(...Object.values(n.pinLabels).map(N=>N.length*.1)):0,P=w>0?1.1:0;D=Math.max(D,w+P)}let b=n.schHeight;b||(b=Math.max(s.left+n.schPinSpacing*2,s.right+n.schPinSpacing*2));let E={left:{x:-D/2-e,y:s.left/2},bottom:{x:-s.bottom/2,y:-b/2-e},right:{x:D/2+e,y:-s.right/2},top:{x:s.top/2,y:b/2+e}},A={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},B=x.map(w=>{let{distanceFromOrthogonalEdge:P,side:N}=w,O=E[N],$=A[N];return{x:O.x+P*$.x,y:O.y+P*$.y,...w}});return{getPortPositionByPinNumber(w){let P=B.find(N=>N.pinNumber.toString()===w.toString());return P||null},getSize(){return{width:D,height:b}},getSizeIncludingPins(){return{width:D+(a.leftSize||a.rightSize?.4:0),height:b+(a.topSize||a.bottomSize?.4:0)}},pinCount:l}},jUt=(0,ABe.default)("tscircuit:core:footprint"),RBe=class extends ma{get config(){return{componentName:"Footprint",zodProps:aAe}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let n=this.children.filter(E=>E.componentName==="Constraint");if(n.length===0)return;let{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),a=E=>e&&"left"in E&&"right"in E?{...E,left:E.right,right:E.left}:E,s=n.flatMap(E=>E._getAllReferencedComponents().componentsWithSelectors).map(({component:E,selector:A,componentSelector:B,edge:w})=>({component:E,selector:A,componentSelector:B,edge:w,bounds:E._getPcbCircuitJsonBounds()}));if(s.some(E=>E.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function l(E){return s.find(({selector:A})=>A===E)}let p=new o5,x={};function f(E){return E in x||(x[E]=new a1(E),p.addEditVariable(x[E],qs.weak)),x[E]}for(let{selector:E,bounds:A}of s){let B=f(`${E}_x`),w=f(`${E}_y`);p.suggestValue(B,A.center.x),p.suggestValue(w,A.center.y)}for(let E of n){let A=E._parsedProps;if("xDist"in A){let{xDist:B,left:w,right:P,edgeToEdge:N,centerToCenter:O}=a(A),$=f(`${w}_x`),ee=f(`${P}_x`),X=l(w)?.bounds,te=l(P)?.bounds;if(O){let L=new Is(ee,[-1,$]);p.addConstraint(new Zu(L,yo.Eq,A.xDist,qs.required))}else if(N){let L=new Is(ee,-te.width/2,[-1,$],-X.width/2);p.addConstraint(new Zu(L,yo.Eq,A.xDist,qs.required))}}else if("yDist"in A){let{yDist:B,top:w,bottom:P,edgeToEdge:N,centerToCenter:O}=A,$=f(`${w}_y`),ee=f(`${P}_y`),X=l(w)?.bounds,te=l(P)?.bounds;if(O){let L=new Is($,[-1,ee]);p.addConstraint(new Zu(L,yo.Eq,A.yDist,qs.required))}else if(N){let L=new Is($,X.height/2,[-1,ee],-te.height/2);p.addConstraint(new Zu(L,yo.Eq,A.yDist,qs.required))}}else if("sameY"in A){let{for:B}=A;if(B.length<2)continue;let w=B.map(N=>f(`${N}_y`)),P=new Is(...w.slice(1));p.addConstraint(new Zu(P,yo.Eq,w[0],qs.required))}else if("sameX"in A){let{for:B}=A;if(B.length<2)continue;let w=B.map(N=>f(`${N}_x`)),P=new Is(...w.slice(1));p.addConstraint(new Zu(P,yo.Eq,w[0],qs.required))}}p.updateVariables(),jUt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(x).map(([E,A])=>({var:E,val:A.value()}))));let m={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:E,bounds:{width:A,height:B}}of s){let w=f(`${E}_x`),P=f(`${E}_y`),N=w.value()-A/2,O=w.value()+A/2,$=P.value()+B/2,ee=P.value()-B/2;m.left=Math.min(m.left,N),m.right=Math.max(m.right,O),m.top=Math.max(m.top,$),m.bottom=Math.min(m.bottom,ee)}let D={x:-(m.right+m.left)/2,y:-(m.top+m.bottom)/2},b=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();D.x+=b.x,D.y+=b.y;for(let{component:E,selector:A}of s){let B=f(`${A}_x`),w=f(`${A}_y`);E._setPositionFromLayout({x:B.value()+D.x,y:w.value()+D.y})}}},kUt=(n,e)=>{if(!n)return;let a={};for(let[s,l]of Object.entries(n)){let p=OF(s,e),x={leftMargin:l.marginLeft??l.leftMargin,rightMargin:l.marginRight??l.rightMargin,topMargin:l.marginTop??l.topMargin,bottomMargin:l.marginBottom??l.bottomMargin};a[`pin${p}`]={...a[`pin${p}`],...x}}return a},eBe=class{constructor({input:n}){q(this,"input");this.input=n}solveAndMapToTraces(){let n=[];for(let e of this.input.connections){if(e.pointsToConnect.length!==2)continue;let[a,s]=e.pointsToConnect,l={type:"pcb_trace",pcb_trace_id:"",connection_name:e.name,route:[{route_type:"wire",x:a.x,y:a.y,layer:"top",width:.1},{route_type:"wire",x:s.x,y:s.y,layer:"top",width:.1}]};n.push(l)}return n}},NUt=n=>{let e=Math.min(...n.map(p=>p.center.x)),a=Math.max(...n.map(p=>p.center.x)),s=Math.min(...n.map(p=>p.center.y)),l=Math.max(...n.map(p=>p.center.y));return{minX:e,maxX:a,minY:s,maxY:l}},tBe=["top","bottom","inner1","inner2"],OS=(n,e=[])=>{let a=[];if(e.length===0){let f=n[0].layers;for(let m of f)a.push(...OS(n.slice(1),[m]));return a}if(n.length===0)return[];let s=n[0],l=s.via||s.optional_via,p=e[e.length-1];if(n.length===1){let f=s;return f.layers&&l?f.layers.map(m=>({layer_path:[...e,m]})):f.layers?.includes(p)?[{layer_path:[...e,p]}]:[]}if(!l)return s.layers&&!s.layers.includes(p)?[]:OS(n.slice(1),e.concat([p]));let x=(s.optional_via?tBe:tBe.filter(f=>f!==p)).filter(f=>!s.layers||s.layers?.includes(f));for(let f of x)a.push(...OS(n.slice(1),e.concat(f)));return a};function rBe(n){let e={x:n.to.x-n.from.x,y:n.to.y-n.from.y},a=Math.abs(e.x),s=Math.abs(e.y);return a>s?e.x>0?"right":"left":e.y>0?"down":"up"}function kg(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}var MUt=n=>{if(n.length===1)return n[0];if(n.some(m=>m.length===0))throw new Error("Cannot merge routes with zero length");let e=[],a=n[0][0],s=n[0][n[0].length-1],l=n[1][0],p=n[1][n[1].length-1],x=Math.min(kg(a,l),kg(a,p)),f=Math.min(kg(s,l),kg(s,p));x<f?e.push(...n[0].reverse()):e.push(...n[0]);for(let m=1;m<n.length;m++){let D=e[e.length-1],b=n[m],E=b[0],A=b[b.length-1],B=kg(D,E),w=kg(D,A);B<w?e.push(...b):e.push(...b.reverse())}for(let m=1;m<e.length-1;m++){let D=e[m-1],b=e[m];D.route_type==="wire"&&b.route_type==="wire"&&D.layer!==b.layer&&e.splice(m,0,{x:D.x,y:D.y,from_layer:D.layer,to_layer:b.layer,route_type:"via"})}return e},OUt=(n,e)=>{let a="_getGlobalPcbPositionBeforeLayout"in n?n._getGlobalPcbPositionBeforeLayout():n,s="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((a.x-s.x)**2+(a.y-s.y)**2)};function LUt(n,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let a=e[0],s=1/0;for(let l of e){let p=OUt(n,l);p<s&&(a=l,s=p)}return a}var $Ut=(n,e)=>{let a=0;a+=n.length??0,a+=e.filter(s=>s.is_crossing).length;for(let s=1;s<e.length;s++){let l=e[s-1],p=e[s],x=Math.abs(l.from.x-l.to.x)<.01,f=Math.abs(p.from.x-p.to.x)<.01;x!==f&&a++}return a},$F=n=>({up:"bottom",down:"top",left:"right",right:"left"})[n]??null,qW=({firstEdge:n,firstEdgePort:e,firstDominantDirection:a,lastEdge:s,lastEdgePort:l,lastDominantDirection:p})=>{if(n&&e)return qW({lastEdge:{from:n.to,to:n.from},lastEdgePort:e,lastDominantDirection:a}).reverse().map(f=>({from:f.to,to:f.from}));let x=[];if(s&&l){let f={x:s.to.x,y:s.to.y};p==="left"||p==="right"?(f.x=l.position.x,x.push({from:s.to,to:{...f}}),x.push({from:f,to:{...l.position}})):(f.y=l.position.y,x.push({from:s.to,to:{...f}}),x.push({from:f,to:{...l.position}}))}return x=x.filter(f=>Ri(f.from,f.to)>.01),x};function zUt(n){try{return[n(),null]}catch(e){return[null,e]}}var qUt=(n,{db:e})=>{let a=n.map(s=>{let l=e.source_port.get(s.source_port_id);if(!l?.source_component_id)return null;let p=e.source_component.get(l.source_component_id);return p?.ftype==="simple_capacitor"?p.max_decoupling_trace_length:null}).filter(s=>s!==null);if(a.length!==0)return Math.min(...a)};function UUt({ports:n,nets:e}){if(n.length>=2)return`${n[0]?.selector} to ${n[1]?.selector}`;if(n.length===1&&e.length===1)return`${n[0]?.selector} to net.${e[0]._parsedProps.name}`}var VUt=(n,{db:e})=>{let a=e.pcb_board.list()[0];if(a.outline){let m=a.outline,D=(b,E)=>{let A=!1;for(let B=0,w=E.length-1;B<E.length;w=B++){let P=E[B].x,N=E[B].y,O=E[w].x,$=E[w].y;N>b.y!=$>b.y&&b.x<(O-P)*(b.y-N)/($-N)+P&&(A=!A)}return A};return n.some(b=>!D(b,m))}let s=a.width,l=a.height,p=a.center.x,x=a.center.y;return n.some(m=>m.x<p-s/2||m.y<x-l/2||m.x>p+s/2||m.y>x+l/2)},nBe=(n,e)=>Math.abs(n-e)<1e-4,GUt=(n,e,{viaDiameter:a=.5}={})=>{let s=[];for(let l=0;l<n.length-1;l++){let[p,x]=[n[l],n[l+1]],f=l-1>=0?n[l-1]:null,m=nBe(p.y,x.y),D=nBe(p.x,x.x);if(!m&&!D)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${p.x}, ${p.y}), end: (${x.x}, ${x.y})`);let b={type:"rect",layers:[p.layer],center:{x:(p.x+x.x)/2,y:(p.y+x.y)/2},width:m?Math.abs(p.x-x.x):.1,height:D?Math.abs(p.y-x.y):.1,connectedTo:[e]};if(s.push(b),f&&f.layer===p.layer&&p.layer!==x.layer){let E={type:"rect",layers:[p.layer,x.layer],center:{x:p.x,y:p.y},connectedTo:[e],width:a,height:a};s.push(E)}}return s};function XUt(n,e=4){let{center:a,width:s,height:l,rotation:p}=n,x=[],f=p*Math.PI/180,m=Math.cos(f),D=Math.sin(f),b=(p%360+360)%360;if(l<=s?b>=45&&b<135||b>=225&&b<315:b>=135&&b<225||b>=315||b<45){let A=s/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*m,N=-w*D,O=A*1.1,$=Math.abs(l*m)+Math.abs(A*D);x.push({center:{x:a.x+P,y:a.y+N},width:O,height:$})}}else{let A=l/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*D,N=w*m,O=Math.abs(s*m)+Math.abs(A*D),$=A*1.1;x.push({center:{x:a.x+P,y:a.y+N},width:O,height:$})}}return x}function YUt(n,e={}){if(n.length<3)return[];let{rectHeight:a=.1}=e,s=[],l=n.map(f=>f.y),p=Math.min(...l),x=Math.max(...l);for(let f=p;f<x;f+=a){let m=f+a/2,D=[];for(let b=0;b<n.length;b++){let E=n[b],A=n[(b+1)%n.length];if(E.y<=m&&A.y>m||A.y<=m&&E.y>m){let B=(m-E.y)*(A.x-E.x)/(A.y-E.y)+E.x;D.push(B)}}D.sort((b,E)=>b-E);for(let b=0;b<D.length;b+=2)if(b+1<D.length){let E=D[b],B=D[b+1]-E;B>1e-6&&s.push({center:{x:E+B/2,y:m},width:B,height:a})}}return s}function HUt(n,e={}){let{center:a,radius:s}=n,{rectHeight:l=.1}=e,p=[],x=Math.ceil(s*2/l);for(let f=0;f<x;f++){let m=a.y-s+(f+.5)*l,D=m-a.y,b=Math.sqrt(s*s-D*D);b>0&&p.push({center:{x:a.x,y:m},width:b*2,height:l})}return p}var Zp=["top","inner1","inner2","bottom"],SBe=(n,e)=>{let a=l=>e?l.concat(l.map(p=>e?.getNetConnectedToId(p)).filter(Boolean)):l,s=[];for(let l of n)if(l.type==="pcb_smtpad"){if(l.shape==="circle")s.push({type:"oval",layers:[l.layer],center:{x:l.x,y:l.y},width:l.radius*2,height:l.radius*2,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rect")s.push({type:"rect",layers:[l.layer],center:{x:l.x,y:l.y},width:l.width,height:l.height,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rotated_rect"){let p={center:{x:l.x,y:l.y},width:l.width,height:l.height,rotation:l.ccw_rotation},x=XUt(p);for(let f of x)s.push({type:"rect",layers:[l.layer],center:f.center,width:f.width,height:f.height,connectedTo:a([l.pcb_smtpad_id])})}}else if(l.type==="pcb_keepout")l.shape==="circle"?s.push({type:"oval",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.radius*2,height:l.radius*2,connectedTo:[]}):l.shape==="rect"&&s.push({type:"rect",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.type==="pcb_cutout"){if(l.shape==="rect")s.push({type:"rect",layers:Zp,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.shape==="circle"){let p=HUt({center:l.center,radius:l.radius},{rectHeight:.6});for(let x of p)s.push({type:"rect",layers:Zp,center:x.center,width:x.width,height:x.height,connectedTo:[]})}else if(l.shape==="polygon"){let p=YUt(l.points,{rectHeight:.6});for(let x of p)s.push({type:"rect",layers:Zp,center:x.center,width:x.width,height:x.height,connectedTo:[]})}}else if(l.type==="pcb_hole")l.hole_shape==="oval"?s.push({type:"oval",center:{x:l.x,y:l.y},width:l.hole_width,height:l.hole_height,connectedTo:[]}):l.hole_shape==="square"?s.push({type:"rect",layers:Zp,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]}):(l.hole_shape==="round"||l.hole_shape==="circle")&&s.push({type:"rect",layers:Zp,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]});else if(l.type==="pcb_plated_hole")l.shape==="circle"?s.push({type:"oval",layers:Zp,center:{x:l.x,y:l.y},width:l.outer_diameter,height:l.outer_diameter,connectedTo:a([l.pcb_plated_hole_id])}):l.shape==="circular_hole_with_rect_pad"?s.push({type:"rect",layers:Zp,center:{x:l.x,y:l.y},width:l.rect_pad_width,height:l.rect_pad_height,connectedTo:a([l.pcb_plated_hole_id])}):(l.shape==="oval"||l.shape==="pill")&&s.push({type:"oval",layers:Zp,center:{x:l.x,y:l.y},width:l.outer_width,height:l.outer_height,connectedTo:a([l.pcb_plated_hole_id])});else if(l.type==="pcb_trace"){let p=GUt(l.route.map(x=>({x:x.x,y:x.y,layer:"layer"in x?x.layer:x.from_layer})),l.source_trace_id);s.push(...p)}else l.type==="pcb_via"&&s.push({type:"rect",layers:l.layers,center:{x:l.x,y:l.y},connectedTo:[],width:l.outer_diameter,height:l.outer_diameter});return s},Qp=({anchor_position:n,anchor_side:e,text:a,font_size:s=.18})=>{let l=.1*(s/.18),p=a.length*l,x=s,f={...n};switch(e){case"right":f.x-=p/2;break;case"left":f.x+=p/2;break;case"top":f.y-=x/2;break;case"bottom":f.y+=x/2;break}return f},nK=({db:n,source_trace_id:e,sameNetOnly:a,differentNetOnly:s})=>{!a&&!s&&(s=!0);let l=n.source_trace.get(e),p=[];for(let x of n.schematic_trace.list()){if(x.source_trace_id===e)continue;let m=n.source_trace.get(x.source_trace_id)?.subcircuit_connectivity_map_key===l.subcircuit_connectivity_map_key;s&&m||a&&!m||p.push(x)}return p},WUt=({edges:n,otherEdges:e})=>{let a=[...n];for(let s=0;s<a.length;s++){if(s>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let l=a[s],p=Math.abs(l.from.x-l.to.x)<.01?"vertical":l.from.y===l.to.y?"horizontal":"not-orthogonal";if(p==="not-orthogonal")continue;let x=[];for(let P of e){let N=P.from.x===P.to.x?"vertical":P.from.y===P.to.y?"horizontal":"not-orthogonal";if(N==="not-orthogonal"||p===N)continue;if(Np([l.from,l.to],[P.from,P.to],{lineThickness:.01})){let $=p==="vertical"?l.from.x:P.from.x,ee=p==="vertical"?P.from.y:l.from.y,X={x:$,y:ee};x.push({otherEdge:P,crossingPoint:X,distanceFromEdgeFrom:Ri(l.from,X)})}}if(x.length===0)continue;let f=x[0];for(let P of x)P.distanceFromEdgeFrom<f.distanceFromEdgeFrom&&(f=P);let m=f.crossingPoint,D=.075;if(m.x===l.from.x&&m.y===l.from.y)continue;let b=p5(l.from,m),E={x:m.x-b.x*D/2,y:m.y-b.y*D/2},A={x:m.x+b.x*D/2,y:m.y+b.y*D/2},B=Ri(A,l.to)<D,w=[{from:l.from,to:E},{from:E,to:A,is_crossing:!0},{from:A,to:l.to}];a.splice(s,1,...w),s+=w.length-2,B&&s++}return a},UW=.001,Ng=(n,e)=>{let a=Math.min(e.from.x,e.to.x),s=Math.max(e.from.x,e.to.x),l=Math.min(e.from.y,e.to.y),p=Math.max(e.from.y,e.to.y);return n.x>=a&&n.x<=s&&n.y>=l&&n.y<=p},aBe=n=>{let e=Math.abs(n.from.x-n.to.x)<UW,a=Math.abs(n.from.y-n.to.y)<UW;return e?"vertical":a?"horizontal":"diagonal"},KUt=(n,e)=>{let a=aBe(n),s=aBe(e);if(a===s)return null;if(a==="vertical"&&s==="horizontal"||a==="horizontal"&&s==="vertical"){let E=a==="vertical"?n:e,A=a==="horizontal"?n:e,B=E.from.x,w=A.from.y,P={x:B,y:w};return Ng(P,n)&&Ng(P,e)?P:null}if(a==="vertical"||s==="vertical"){let E=a==="vertical"?n:e,A=a==="vertical"?e:n,B=E.from.x,w=(A.to.y-A.from.y)/(A.to.x-A.from.x),P=A.from.y-w*A.from.x,N=w*B+P,O={x:B,y:N};return Ng(O,n)&&Ng(O,e)?O:null}let l=(n.to.y-n.from.y)/(n.to.x-n.from.x),p=n.from.y-l*n.from.x,x=(e.to.y-e.from.y)/(e.to.x-e.from.x),f=e.from.y-x*e.from.x;if(Math.abs(l-x)<UW)return null;let m=(f-p)/(l-x),D=l*m+p,b={x:m,y:D};return Ng(b,n)&&Ng(b,e)?b:null},JUt=({edges:n,db:e,source_trace_id:a})=>{let s=nK({db:e,source_trace_id:a,sameNetOnly:!0}).flatMap(p=>p.edges),l=new Map;for(let p of n)for(let x of s){let f=KUt(p,x);if(f){let m=`${f.x.toFixed(6)},${f.y.toFixed(6)}`;l.has(m)||l.set(m,f)}}return Array.from(l.values())};function ZUt(n){let e=1/0,a=1/0,s=-1/0,l=-1/0;for(let p of n){let x,f,m,D;p.type==="schematic_component"?(x=p.center?.x,f=p.center?.y,m=p.size?.width,D=p.size?.height):p.type==="schematic_box"?(x=p.x,f=p.y,m=p.width,D=p.height):p.type==="schematic_port"?(x=p.center?.x,f=p.center?.y,m=.2,D=.2):p.type==="schematic_text"&&(x=p.position?.x,f=p.position?.y,m=(p.text?.length??0)*.1,D=.2),typeof x=="number"&&typeof f=="number"&&typeof m=="number"&&typeof D=="number"&&(e=Math.min(e,x-m/2),s=Math.max(s,x+m/2),a=Math.min(a,f-D/2),l=Math.max(l,f+D/2))}return{minX:e,maxX:s,minY:a,maxY:l}}function QUt(n,e={}){let{minX:a,maxX:s,minY:l,maxY:p}=n,x=e.padding??1;if(!isFinite(a)||!isFinite(s)||!isFinite(l)||!isFinite(p))return[];let f=a-x,m=s+x,D=p+x,b=l-x,E=.01;return[{type:"rect",layers:["top"],center:{x:(f+m)/2,y:D},width:m-f,height:E,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(f+m)/2,y:b},width:m-f,height:E,connectedTo:[]},{type:"rect",layers:["top"],center:{x:f,y:(D+b)/2},width:E,height:D-b,connectedTo:[]},{type:"rect",layers:["top"],center:{x:m,y:(D+b)/2},width:E,height:D-b,connectedTo:[]}]}var eVt=n=>{let e=n.root.db,a=n._findConnectedPorts().ports??[],s=new Set(a.map(x=>x.schematic_port_id)),l=[];for(let x of e.toArray()){if(x.type==="schematic_component"){let f=!!x.symbol_name,m=x.size.width>x.size.height?"horz":"vert";l.push({type:"rect",layers:["top"],center:x.center,width:x.size.width+(f&&m==="horz"?-.5:0),height:x.size.height+(f&&m==="vert"?-.5:0),connectedTo:[]})}if(x.type==="schematic_port"){if(s.has(x.schematic_port_id))continue;let f=x.facing_direction?x5(x.facing_direction):{x:0,y:0};l.push({type:"rect",layers:["top"],center:{x:x.center.x-f.x*.1,y:x.center.y-f.y*.1},width:.1+Math.abs(f.x)*.3,height:.1+Math.abs(f.y)*.3,connectedTo:[]})}x.type==="schematic_text"&&l.push({type:"rect",layers:["top"],center:x.position,width:(x.text?.length??0)*.1,height:.2,connectedTo:[]}),x.type==="schematic_box"&&l.push({type:"rect",layers:["top"],center:{x:x.x,y:x.y},width:x.width,height:x.height,connectedTo:[]})}let p=ZUt(e.toArray());return l.push(...QUt(p,{padding:1})),l},tVt=({edges:n,db:e,source_trace_id:a})=>{let s=e.source_trace.get(a),l=nK({db:e,source_trace_id:a,differentNetOnly:!0}).flatMap(x=>x.edges),p=x=>{let{from:f,to:m}=x;return f.x===m.x?"vertical":"horizontal"};for(let x of n){let f=p(x),m=()=>l.find(b=>p(b)===f&&Np([x.from,x.to],[b.from,b.to],{lineThickness:.05})),D=m();for(;D;)f==="horizontal"?(x.from.y+=.1,x.to.y+=.1):(x.from.x+=.1,x.to.x+=.1),D=m()}},VW=n=>{switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},rVt=YAe.version??"unknown",jF=class extends Error{constructor(n){super(`${n} (capacity-autorouter@${rVt})`),this.name="AutorouterError"}},US=class extends Error{constructor(n){super(n.message),this.errorData=n,this.name="TraceConnectionError"}},nVt=n=>{if(n.root?._featureMspSchematicTraceRouting||n._couldNotFindPort||n.root?.schematicDisabled)return;let{db:e}=n.root,{_parsedProps:a,parent:s}=n;if(!s)throw new Error("Trace has no parent");let l,p;try{let Ne=n._findConnectedPorts();l=Ne.allPortsFound,p=Ne.portsWithSelectors??[]}catch(Ne){if(Ne instanceof US){e.source_trace_not_connected_error.insert({...Ne.errorData,error_type:"source_trace_not_connected_error"});return}throw Ne}let{netsWithSelectors:x}=n._findConnectedNets();if(!l)return;let m=p.map(Ne=>Ne.port.schematic_port_id).sort().join(","),D=n.root?._getBoard();if(D?._connectedSchematicPortPairs&&D._connectedSchematicPortPairs.has(m))return;let b={name:n.source_trace_id,pointsToConnect:[]},E=eVt(n),A=p.filter(({port:Ne})=>Ne.schematic_port_id!==null).map(({port:Ne})=>({port:Ne,position:Ne._getGlobalSchematicPositionAfterLayout(),schematic_port_id:Ne.schematic_port_id??void 0,facingDirection:Ne.facingDirection}));if(A.length===1&&x.length===1){let Ne=x[0].net,{port:Ve,position:et}=A[0],ct=n.getSubcircuit().selectAll("netlabel").find(ot=>{let it=ot._parsedProps.connection??ot._parsedProps.connectsTo;return it?Array.isArray(it)?it.some(It=>n.getSubcircuit().selectOne(It,{port:!0})===Ve):n.getSubcircuit().selectOne(it,{port:!0})===Ve:!1});if(!ct){let ot=e.schematic_net_label.getWhere({source_trace_id:n.source_trace_id});ot&&(ct=ot)}if(ct){let ot="_getGlobalSchematicPositionBeforeLayout"in ct?ct._getGlobalSchematicPositionBeforeLayout():ct.anchor_position,it=[];et.x===ot.x||et.y===ot.y?it.push({from:et,to:ot}):(it.push({from:et,to:{x:ot.x,y:et.y}}),it.push({from:{x:ot.x,y:et.y},to:ot}));let qt=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:it,junctions:[],subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=qt.schematic_trace_id;return}if(n.props.schDisplayLabel){let ot=$F(Ve.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel,source_net_id:Ne.source_net_id,anchor_position:et,center:Qp({anchor_position:et,anchor_side:ot,text:n.props.schDisplayLabel}),anchor_side:ot});return}let Mt=$F(Ve.facingDirection)??"bottom",Dt=e.schematic_net_label.insert({text:Ne._parsedProps.name,source_net_id:Ne.source_net_id,anchor_position:et,center:Qp({anchor_position:et,anchor_side:Mt,text:Ne._parsedProps.name}),anchor_side:Mt});return}if(n.props.schDisplayLabel&&("from"in n.props&&"to"in n.props||"path"in n.props)){n._doInitialSchematicTraceRenderWithDisplayLabel();return}if(A.length<2)return;let P=(()=>{let Ne=[];for(let et=0;et<A.length-1;et++){let ct=A[et],Mt=A[et+1],Dt=sg({x:ct.position.x,y:ct.position.y,facingDirection:VW(ct.facingDirection)},{x:Mt.position.x,y:Mt.position.y,facingDirection:VW(Mt.facingDirection)});for(let ot=0;ot<Dt.length-1;ot++)Ne.push({from:Dt[ot],to:Dt[ot+1]})}let Ve=(et,ct)=>{let Mt=ct.width/2,Dt=ct.height/2,ot=ct.center.x-Mt,it=ct.center.x+Mt,qt=ct.center.y-Dt,It=ct.center.y+Dt,tr=Et=>Et.x>=ot&&Et.x<=it&&Et.y>=qt&&Et.y<=It;return tr(et.from)||tr(et.to)?!0:[[{x:ot,y:qt},{x:it,y:qt}],[{x:it,y:qt},{x:it,y:It}],[{x:it,y:It},{x:ot,y:It}],[{x:ot,y:It},{x:ot,y:qt}]].some(Et=>Np([et.from,et.to],Et,{lineThickness:0}))};for(let et of Ne)for(let ct of E)if(Ve(et,ct))return null;return Ne})();P&&P.length===0&&(P=null),b.pointsToConnect=A.map(({position:Ne})=>({...Ne,layer:"top"}));let N=NUt(E),O=2,$={minTraceWidth:.1,obstacles:E,connections:[b],bounds:{minX:N.minX-O,maxX:N.maxX+O,minY:N.minY-O,maxY:N.maxY+O},layerCount:1},ee=JR,X=!1;if(n.getSubcircuit().props._schDirectLineRoutingEnabled&&(ee=eBe,X=!0),!P){let Ve=new ee({input:$,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(Ve.length===0){if(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection()){n._doInitialSchematicTraceRenderWithDisplayLabel();return}Ve=new eBe({input:$}).solveAndMapToTraces(),X=!0}let[{route:et}]=Ve;P=[];for(let ct=0;ct<et.length-1;ct++)P.push({from:et[ct],to:et[ct+1]})}let te=n.source_trace_id,L=[];if(!X){tVt({edges:P,db:e,source_trace_id:te});let Ne=nK({db:e,source_trace_id:te,differentNetOnly:!0}).flatMap(Ve=>Ve.edges);P=WUt({edges:P,otherEdges:Ne}),L=JUt({edges:P,db:e,source_trace_id:n.source_trace_id})}if(!P||P.length===0)return;let K=P[P.length-1],U=A[A.length-1],J=rBe(K);P.push(...qW({lastEdge:K,lastEdgePort:U,lastDominantDirection:J}));let Q=P[0],de=A[0],ce=rBe(Q);if(P.unshift(...qW({firstEdge:Q,firstEdgePort:de,firstDominantDirection:ce})),!n.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(n.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&$Ut(L,P)>=5&&(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection())){n._doInitialSchematicTraceRenderWithDisplayLabel();return}let Te=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:P,junctions:L,subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=Te.schematic_trace_id;for(let{port:Ne}of p)Ne.schematic_port_id&&e.schematic_port.update(Ne.schematic_port_id,{is_connected:!0});D?._connectedSchematicPortPairs&&D._connectedSchematicPortPairs.add(m)};function BBe(n){let e=0;for(let a=0;a<n.length;a++){let s=n[a];if(s.route_type==="wire"){let l=n[a+1];if(l){let p=l.x-s.x,x=l.y-s.y;e+=Math.sqrt(p*p+x*x)}}else s.route_type==="via"&&(e+=1.6)}return e}var kS=n=>({...n._getGlobalPcbPositionAfterLayout(),layers:n.getAvailablePcbLayers()}),aVt=!1;function sVt(n){if(n.root?.pcbDisabled)return;let{db:e}=n.root,{_parsedProps:a,parent:s}=n,l=n.getSubcircuit();if(!s)throw new Error("Trace has no parent");if(l._parsedProps.routingDisabled)return;let p=l._parsedProps.pcbRouteCache?.pcbTraces;if(p){let J=e.pcb_trace.insert({route:p.flatMap(Q=>Q.route),source_trace_id:n.source_trace_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0});n.pcb_trace_id=J.pcb_trace_id;return}if(a.pcbPath&&a.pcbPath.length>0||!l._shouldUseTraceByTraceRouting())return;let{allPortsFound:x,ports:f}=n._findConnectedPorts(),m=[];if(!x)return;let D=[];for(let J of f)J._hasMatchedPcbPrimitive()||D.push(J);if(D.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${n} wasn't routed. Missing ports: ${D.map(J=>J.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:D.map(J=>J.pcb_port_id).filter(Boolean)});return}let b=n._findConnectedNets().netsWithSelectors;if(f.length===0&&b.length===2){n.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(f.length===1&&b.length===1){let J=f[0],de=b[0].net.getAllConnectedPorts().filter(Te=>Te!==J);if(de.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let ce=LUt(J,de);m.push(ce),f.push(ce)}else if(f.length>1&&b.length>=1){n.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let E=f.flatMap(J=>J.matchedComponents.filter(Q=>Q.componentName==="TraceHint")),A=(n._parsedProps.pcbRouteHints??[]).concat(E.flatMap(J=>J.getPcbRouteHints()));if(f.length>2){n.renderError(`Trace has more than two ports (${f.map(J=>J.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(n.getSubcircuit().selectAll("trace").filter(J=>J.renderPhaseStates.PcbTraceRender.initialized).some(J=>J._portsRoutedOnPcb.length===f.length&&J._portsRoutedOnPcb.every(Q=>f.includes(Q))))return;let P=[];A.length===0?P=[kS(f[0]),kS(f[1])]:P=[kS(f[0]),...A,kS(f[1])];let N=OS(P);if(aVt&&N.length===0){n.renderError(`Could not find a common layer (using hints) for trace ${n.getString()}`);return}let O=Ku(n.root.db.toArray()),[$,ee]=zUt(()=>SBe(n.root.db.toArray()));if(ee){n.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:n.pcb_trace_id,message:`Error getting obstacles for autorouting: ${ee.message}`,source_trace_id:n.source_trace_id,center:{x:0,y:0},pcb_port_ids:f.map(J=>J.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[]});return}for(let J of $)if(J.connectedTo.length>0){let de=O.getNetConnectedToId(J.connectedTo[0]);de&&J.connectedTo.push(de)}let X=[];if(N.length===0)X=P;else{let J=N[0].layer_path;X=P.map((Q,de)=>Q.via?{...Q,via_to_layer:J[de]}:{...Q,layers:[J[de]]})}X[0].pcb_port_id=f[0].pcb_port_id,X[X.length-1].pcb_port_id=f[1].pcb_port_id;let te=[];for(let[J,Q]of vBe(X)){let de="via_to_layer"in J?J.via_to_layer:null,ce=2,Te="layers"in J&&J.layers.length===1?J.layers[0]:de??"top",Ne="layers"in Q&&Q.layers.length===1?Q.layers[0]:de??"top",Ve="pcb_port_id"in J?J.pcb_port_id:null,et="pcb_port_id"in Q?Q.pcb_port_id:null,ct=n.getSubcircuit()._parsedProps.minTraceWidth??.16,Mt=new JR({OBSTACLE_MARGIN:ct*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Ve&&et),connMap:O,input:{obstacles:$,minTraceWidth:ct,connections:[{name:n.source_trace_id,pointsToConnect:[{...J,layer:Te,pcb_port_id:Ve},{...Q,layer:Ne,pcb_port_id:et}]}],layerCount:n.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(J.x,Q.x)-ce,maxX:Math.max(J.x,Q.x)+ce,minY:Math.min(J.y,Q.y)-ce,maxY:Math.max(J.y,Q.y)+ce}}}),Dt=null;try{Dt=Mt.solveAndMapToTraces()}catch(qt){n.renderError({type:"pcb_trace_error",pcb_trace_error_id:n.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${qt.message}`,source_trace_id:n.pcb_trace_id,center:{x:(J.x+Q.x)/2,y:(J.y+Q.y)/2},pcb_port_ids:f.map(It=>It.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:f.map(It=>It.pcb_component_id)})}if(!Dt)return;if(Dt.length===0){n.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:n.pcb_trace_id,message:`Could not find a route for ${n}`,source_trace_id:n.source_trace_id,center:{x:(J.x+Q.x)/2,y:(J.y+Q.y)/2},pcb_port_ids:f.map(qt=>qt.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:f.map(qt=>qt.pcb_component_id)});return}let[ot]=Dt;de&&(ot.route=ot.route.map(qt=>(qt.route_type==="wire"&&!qt.layer&&(qt.layer=de),qt))),Ve&&ot.route[0].route_type==="wire"&&(ot.route[0].start_pcb_port_id=Ve);let it=ot.route[ot.route.length-1];et&&it.route_type==="wire"&&(it.end_pcb_port_id=et),te.push(ot.route)}let L=MUt(te),K=BBe(L),U=e.pcb_trace.insert({route:L,source_trace_id:n.source_trace_id,subcircuit_id:n.getSubcircuit()?.subcircuit_id,trace_length:K});n._portsRoutedOnPcb=f,n.pcb_trace_id=U.pcb_trace_id;for(let J of L)J.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:U.pcb_trace_id,x:J.x,y:J.y,hole_diameter:.3,outer_diameter:.6,layers:[J.from_layer,J.to_layer],from_layer:J.from_layer,to_layer:J.to_layer});n._insertErrorIfTraceIsOutsideBoard(L,f)}function iVt(n){if(n.root?.pcbDisabled)return;let{db:e}=n.root,{_parsedProps:a}=n,s=n.getSubcircuit();if(!a.pcbPath||a.pcbPath.length===0)return;let{allPortsFound:l,ports:p,portsWithSelectors:x}=n._findConnectedPorts();if(!l)return;let f=[];for(let $ of p)$._hasMatchedPcbPrimitive()||f.push($);if(f.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${n} wasn't routed. Missing ports: ${f.map($=>$.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:f.map($=>$.pcb_port_id).filter(Boolean)});return}let m;a.pcbPathRelativeTo&&(m=x.find($=>$.selector===a.pcbPathRelativeTo)?.port,m||(m=n.getSubcircuit().selectOne(a.pcbPathRelativeTo))),m||(m=p[0]);let D=p.find($=>$!==m)??p[1],b=m.getAvailablePcbLayers()[0]||"top",E=a.thickness??n.getSubcircuit()._parsedProps.minTraceWidth??.16,A=m._getGlobalPcbPositionAfterLayout(),B=D._getGlobalPcbPositionAfterLayout(),w=[];w.push({route_type:"wire",x:A.x,y:A.y,width:E,layer:b,start_pcb_port_id:m.pcb_port_id});let P=m?._computePcbGlobalTransformBeforeLayout?.()||_i();for(let $ of a.pcbPath){let ee=rs(P,{x:$.x,y:$.y});w.push({route_type:"wire",x:ee.x,y:ee.y,width:E,layer:b})}w.push({route_type:"wire",x:B.x,y:B.y,width:E,layer:b,end_pcb_port_id:D.pcb_port_id});let N=BBe(w),O=e.pcb_trace.insert({route:w,source_trace_id:n.source_trace_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,trace_length:N});n._portsRoutedOnPcb=p,n.pcb_trace_id=O.pcb_trace_id,n._insertErrorIfTraceIsOutsideBoard(w,p)}function oVt(n){if(n.root?.schematicDisabled)return;let{db:e}=n.root,{_parsedProps:a,parent:s}=n;if(!s)throw new Error("Trace has no parent");let{allPortsFound:l,portsWithSelectors:p}=n._findConnectedPorts();if(!l)return;let x=p.map(({port:X})=>({port:X,position:X._getGlobalSchematicPositionAfterLayout(),schematic_port_id:X.schematic_port_id,facingDirection:X.facingDirection}));if(x.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let f,m,D=x[0].position,b=x[0].port;if("path"in n.props){if(n.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[f,m]=n.props.path}else{if(!("from"in n.props&&"to"in n.props))throw new Error("Missing 'from' or 'to' properties in props.");f=n.props.from,m=n.props.to}if(!b.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${f}).`);let E=x[1].position,A=x[1].port;if(!A.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${m}).`);let B=e.schematic_net_label.list().find(X=>X.source_net_id===b.source_port_id),w=e.schematic_net_label.list().find(X=>X.source_net_id===A.source_port_id),[P,N]=p.map(({port:X})=>X),$=P.parent?.config.shouldRenderAsSchematicBox?`${P?.parent?.props.name}_${P?.props.name}`:`${N?.parent?.props.name}_${N?.props.name}`,ee=n.props.schDisplayLabel??$;if(B&&B.text!==ee&&(B.text=`${ee} / ${B.text}`),w&&w?.text!==ee&&(w.text=`${ee} / ${w.text}`),!w){let X=$F(A.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??$,source_net_id:A.source_port_id,anchor_position:E,center:Qp({anchor_position:E,anchor_side:X,text:n.props.schDisplayLabel??$}),anchor_side:X})}if(!B){let X=$F(b.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??$,source_net_id:b.source_port_id,anchor_position:D,center:Qp({anchor_position:D,anchor_side:X,text:n.props.schDisplayLabel??$}),anchor_side:X})}}function uVt(n){let{_parsedProps:e,parent:a}=n;if(!a)throw new Error("Trace has no parent");let l=n.getTracePortPathSelectors().map(p=>({selector:p,port:n.getSubcircuit().selectOne(p,{type:"port"})??null}));for(let{selector:p,port:x}of l)if(!x){let f,m,D=p.lastIndexOf(".");if(D!==-1&&D>p.lastIndexOf(" "))f=p.slice(0,D),m=p.slice(D+1);else{let X=p.match(/^(.*[ >])?([^ >]+)$/);f=X?.[1]?.trim()??"",m=X?.[2]??p}let b=f?n.getSubcircuit().selectOne(f):null;if(!b&&f&&!/[.#\[]/.test(f)&&(b=n.getSubcircuit().selectOne(`.${f}`)),!b){let X=f?`Could not find port for selector "${p}". Component "${f}" not found`:`Could not find port for selector "${p}"`,te=n.getSubcircuit(),L=te.getGroup();throw new US({error_type:"source_trace_not_connected_error",message:X,subcircuit_id:te.subcircuit_id??void 0,source_group_id:L?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[p]})}let E=b.children.filter(X=>X.componentName==="Port"),A=m.includes(".")?m.split(".").pop()??"":m,B=E.flatMap(X=>X.getNameAndAliases()),w=B.some(X=>!/^(pin\d+|\d+)$/.test(X)),P=Array.from(new Set(B)).join(", "),N;E.length===0?N="It has no ports":w?N=`It has [${P}]`:N=`It has ${E.length} pins and no pinLabels (consider adding pinLabels)`;let O=`Could not find port for selector "${p}". Component "${b.props.name??f}" found, but does not have pin "${A}". ${N}`,$=n.getSubcircuit(),ee=$.getGroup();throw new US({error_type:"source_trace_not_connected_error",message:O,subcircuit_id:$.subcircuit_id??void 0,source_group_id:ee?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[p]})}return l.some(p=>!p.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:l,ports:l.map(({port:p})=>p)}}var zc=class extends ma{constructor(e){super(e);q(this,"source_trace_id",null);q(this,"pcb_trace_id",null);q(this,"schematic_trace_id",null);q(this,"_portsRoutedOnPcb");q(this,"subcircuit_connectivity_map_key",null);q(this,"_traceConnectionHash",null);q(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}get config(){return{zodProps:nAe,componentName:"Trace"}}_getTracePortOrNetSelectorListFromProps(){return"from"in this.props&&"to"in this.props?[typeof this.props.from=="string"?this.props.from:this.props.from.getPortSelector(),typeof this.props.to=="string"?this.props.to:this.props.to.getPortSelector()]:"path"in this.props?this.props.path.map(e=>typeof e=="string"?e:e.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>!e.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>e.includes("net."))}_findConnectedPorts(){return uVt(this)}_resolveNet(e){let a=this.getSubcircuit().selectOne(e,{type:"net"});if(a)return a;let s=e.match(/^net\.(.+)$/),l=s?s[1]:null;return l&&this.root._getBoard().getDescendants().find(x=>x.componentName==="Net"&&x._parsedProps.name===l)||null}_findConnectedNets(){let e=this.getTracePathNetSelectors().map(s=>({selector:s,net:this._resolveNet(s)})),a=e.filter(s=>!s.net);return a.length>0&&this.renderError(`Could not find net for selector "${a[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(s=>s.net)}}_getAllTracesConnectedToSameNet(){let e=this.getSubcircuit().selectAll("trace"),a=this._findConnectedNets().nets,s=this._findConnectedPorts().ports??[];return e.filter(l=>{if(l===this)return!1;let p=l._findConnectedNets().nets,x=l._findConnectedPorts().ports??[];return p.some(f=>a.includes(f))||x.some(f=>s.includes(f))})}_isExplicitlyConnectedToPort(e){let{allPortsFound:a,portsWithSelectors:s}=this._findConnectedPorts();return a?s.map(p=>p.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){ZW(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();return!e||!a?null:[...a].sort((p,x)=>(p.pcb_port_id||"").localeCompare(x.pcb_port_id||"")).map(p=>p.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:e}=this.root,{_parsedProps:a,parent:s}=this;if(!s){this.renderError("Trace has no parent");return}let l,p;try{let E=this._findConnectedPorts();l=E.allPortsFound,p=E.portsWithSelectors??[]}catch(E){if(E instanceof US){e.source_trace_not_connected_error.insert({...E.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw E}if(!l)return;this._traceConnectionHash=this._computeTraceConnectionHash();let f=e.source_trace.list().find(E=>E.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&E.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(f){this.source_trace_id=f.source_trace_id;return}let m=this._findConnectedNets().nets,D=UUt({ports:p,nets:m}),b=e.source_trace.insert({connected_source_port_ids:p.map(E=>E.port.source_port_id),connected_source_net_ids:m.map(E=>E.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:qUt(p.map(E=>E.port),{db:e})??a.maxLength,display_name:D,min_trace_thickness:a.thickness});this.source_trace_id=b.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,a){let{db:s}=this.root;VUt(e,{db:s})&&s.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:a.map(p=>p.pcb_port_id)})}doInitialPcbManualTraceRender(){iVt(this)}doInitialPcbTraceRender(){sVt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){oVt(this)}_isSymbolToChipConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let p=s.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return p&&!x||!p&&x}_isSymbolToSymbolConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let p=!s.parent.config.shouldRenderAsSchematicBox,x=!l.parent.config.shouldRenderAsSchematicBox;return p&&x}_isChipToChipConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let p=s.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return p&&x}doInitialSchematicTraceRender(){nVt(this)}},cVt=n=>{let{db:e}=n.root;if(n.pcb_component_id){let a=e.pcb_component.get(n.pcb_component_id);return a?{width:a.width,height:a.height}:null}if(n.pcb_group_id){let a=e.pcb_group.get(n.pcb_group_id);return a?{width:a.width,height:a.height}:null}return null},lVt=(n,e)=>{let{db:a}=n.root,s=a.toArray();if(n.pcb_component_id){h5(s,n.pcb_component_id,e);return}if(n.source_group_id){m5(s,n.source_group_id,e);return}throw new Error(`Cannot reposition component ${n.getString()}: no pcb_component_id or source_group_id`)},dVt=n=>{let{db:e}=n.root;if(!n.source_component_id)return;let a=n.selectAll("port"),s=e.source_trace.list(),l=new Set;for(let x of s)for(let f of x.connected_source_port_ids)l.add(f);let p=n._getInternallyConnectedPins();for(let x of p)if(x.some(f=>f.source_port_id&&l.has(f.source_port_id)))for(let f of x)f.source_port_id&&l.add(f.source_port_id);for(let x of a)x.source_port_id&&pVt(n,x)&&(l.has(x.source_port_id)||e.source_pin_missing_trace_warning.insert({message:`Port ${x.getNameAndAliases()[0]} on ${n.props.name} is missing a trace`,source_component_id:n.source_component_id,source_port_id:x.source_port_id,subcircuit_id:n.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},pVt=(n,e)=>{if(n.config.componentName==="Chip"){let a=n.props.pinAttributes;if(!a)return!1;for(let s of e.getNameAndAliases()){let l=a[s];if(l?.requiresPower||l?.requiresGround||l?.requiresVoltage!==void 0)return!0}return!1}return!0};function xVt(n){let e=n.font_size,a=n.text.length*e*.6,s=e,l=n.anchor_alignment||"center",p=n.anchor_position.x,x=n.anchor_position.y;switch(l){case"top_left":p=n.anchor_position.x+a/2,x=n.anchor_position.y+s/2;break;case"top_center":p=n.anchor_position.x,x=n.anchor_position.y+s/2;break;case"top_right":p=n.anchor_position.x-a/2,x=n.anchor_position.y+s/2;break;case"center_left":p=n.anchor_position.x+a/2,x=n.anchor_position.y;break;case"center":p=n.anchor_position.x,x=n.anchor_position.y;break;case"center_right":p=n.anchor_position.x-a/2,x=n.anchor_position.y;break;case"bottom_left":p=n.anchor_position.x+a/2,x=n.anchor_position.y-s/2;break;case"bottom_center":p=n.anchor_position.x,x=n.anchor_position.y-s/2;break;case"bottom_right":p=n.anchor_position.x-a/2,x=n.anchor_position.y-s/2;break;default:p=n.anchor_position.x,x=n.anchor_position.y;break}return{x:p-a/2,y:x-s/2,width:a,height:s}}function fVt(n){if(!n._adjustSilkscreenTextAutomatically||n.root?.pcbDisabled||!n.pcb_component_id)return;let{db:e}=n.root,s=n._getPcbCircuitJsonBounds().center,l=e.pcb_silkscreen_text.list({pcb_component_id:n.pcb_component_id}).filter(m=>m.text===n.name);if(l.length===0)return;let f=n.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(m=>m!==n&&m.pcb_component_id).map(m=>{let D=m._getPcbCircuitJsonBounds(),b={center:D.center,width:D.width,height:D.height};return Ql(b)});for(let m of l){let D=m.anchor_position,b=xVt(m),E={center:{x:b.x+b.width/2,y:b.y+b.height/2},width:b.width,height:b.height},A=Ql(E);if(!f.some(ee=>Ob(A,ee)))continue;let w=2*s.x-D.x,P=2*s.y-D.y,N={center:{x:w,y:P},width:b.width,height:b.height},O=Ql(N);f.some(ee=>Ob(O,ee))||e.pcb_silkscreen_text.update(m.pcb_silkscreen_text_id,{anchor_position:{x:w,y:P}})}}function hVt(n){if(!n)return{validPinLabels:n,invalidPinLabelsMessages:[]};let e={},a=[];for(let[s,l]of Object.entries(n)){let p=Array.isArray(l)?l.slice():[l],x=[];for(let f of p)mVt(s,f)?x.push(f):a.push(`Invalid pin label: ${s} = '${f}' - excluding from component. Please use a valid pin label.`);x.length>0&&(e[s]=Array.isArray(l)?x:x[0])}return{validPinLabels:Object.keys(e).length>0?e:void 0,invalidPinLabelsMessages:a}}function mVt(n,e){try{let a={name:"test",footprint:"test",pinLabels:{[n]:e}};return rg.safeParse(a).success}catch{return!1}}var VS=n=>n.startsWith("http://")||n.startsWith("https://"),XW=n=>{if(VS(n))return null;let e=n.indexOf(":");if(e<=0)return null;let a=n.slice(0,e),s=n.slice(e+1);return!a||!s?null:{footprintLib:a,footprintName:s}};function gVt(n,e){let{footprint:a}=n.props;if(a??(a=n._getImpliedFootprintString?.()),!a)return;let{pcbRotation:s,pinLabels:l,pcbPinLabels:p}=n.props;if(typeof a=="string"&&VS(a)){if(n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let x=a;e("load-footprint-url",async()=>{let m=await(await fetch(x)).json(),D=zW({componentName:n.name,componentRotation:s,footprint:x,pinLabels:l,pcbPinLabels:p},m);n.addAll(D),n._markDirty("InitializePortsFromChildren")});return}if(typeof a=="string"){let x=XW(a);if(!x||n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let m=n.root?.platform?.footprintLibraryMap?.[x.footprintLib],D;if(typeof m=="function"&&(D=m),!D)return;e("load-lib-footprint",async()=>{let b=await D(x.footprintName),E=Array.isArray(b)?b:Array.isArray(b?.footprintCircuitJson)?b.footprintCircuitJson:null;if(!E)return;let A=zW({componentName:n.name,componentRotation:s,footprint:a,pinLabels:l,pcbPinLabels:p},E);n.addAll(A);for(let B of n.children)B.componentName==="Port"&&B._markDirty?.("PcbPortRender");n._markDirty("InitializePortsFromChildren")});return}if((0,GW.isValidElement)(a)){if(n.reactSubtrees.some(f=>f.element===a))return;let x=n._renderReactSubtree(a);n.reactSubtrees.push(x),n.add(x.component);return}!(0,GW.isValidElement)(a)&&a.componentName==="Footprint"&&n.add(a)}var DVt=(0,DBe.default)("tscircuit:core"),yVt=C.object({x:Ba,y:Ba,z:Ba}),Za=class extends ma{constructor(e){let a={...e},s=[];if(a.pinLabels&&!Array.isArray(a.pinLabels)){let{validPinLabels:l,invalidPinLabelsMessages:p}=hVt(a.pinLabels);a.pinLabels=l,s=p}super(a);q(this,"reactSubtrees",[]);q(this,"_impliedFootprint");q(this,"isPrimitiveContainer",!0);q(this,"_isNormalComponent",!0);q(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});q(this,"_asyncSupplierPartNumbers");q(this,"pcb_missing_footprint_error_id");q(this,"_hasStartedFootprintUrlLoad",!1);q(this,"_invalidPinLabelMessages",[]);q(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=s,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(a=>a.map(s=>typeof s=="number"?`pin${s}`:s))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let e=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(l=>l!==this&&l._isNormalComponent&&l.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let l=this._getGlobalPcbPositionBeforeLayout(),p=this._getGlobalSchematicPositionBeforeLayout();e.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:l,schematic_center:p}),this.shouldBeRemoved=!0;let x=[...this.children];for(let f of x)this.remove(f)}}initPorts(e={}){if(this.root?.schematicDisabled)return;let{config:a}=this,s=[],l=this._getSchematicPortArrangement();if(l&&!this._parsedProps.pinLabels){for(let D in l){let b=l[D].pins;if(Array.isArray(b))for(let E of b){let A=OF(E,this._parsedProps.pinLabels);s.push(new Ii({pinNumber:A,aliases:e.additionalAliases?.[`pin${A}`]??[]},{originDescription:`schPortArrangement:${D}`}))}}let f=["left","right","top","bottom"],m=1;for(let D of f){let b=l[`${D}Size`];for(let E=0;E<b;E++)s.push(new Ii({pinNumber:m++,aliases:e.additionalAliases?.[`pin${m}`]??[]},{originDescription:`schPortArrangement:${D}`}))}}let p=this._parsedProps.pinLabels;if(p)for(let[f,m]of Object.entries(p)){f=f.replace("pin","");let D=s.find(A=>A._parsedProps.pinNumber===Number(f)),b=Array.isArray(m)?m[0]:m,E=Array.isArray(m)?m.slice(1):[];D?(D.externallyAddedAliases.push(b,...E),D.props.name=b):(D=new Ii({pinNumber:parseInt(f),name:b,aliases:[...E,...e.additionalAliases?.[`pin${parseInt(f)}`]??[]]},{originDescription:`pinLabels:pin${f}`}),s.push(D))}if(a.schematicSymbolName&&!e.ignoreSymbolPorts){let f=Ps[this._getSchematicSymbolNameOrThrow()];if(!f)return;for(let m of f.ports){let D=CBe(m.labels);if(!D)continue;let b=s.find(E=>E._parsedProps.pinNumber===Number(D));if(b)b.schematicSymbolPortDef=m;else{let E=IF(m.labels.concat(e.additionalAliases?.[`pin${D}`]??[]));E&&(E.originDescription=`schematicSymbol:labels[0]:${m.labels[0]}`,E.schematicSymbolPortDef=m,s.push(E))}}this.addAll(s)}if(!this._getSchematicPortArrangement()){let f=this.getPortsFromFootprint(e);for(let m of f)s.some(D=>D.isMatchingAnyOf(m.getNameAndAliases()))||s.push(m)}let x=e.pinCount??this._getPinCount()??0;for(let f=1;f<=x;f++){if(s.find(D=>D._parsedProps.pinNumber===f))continue;if(!l){s.push(new Ii({pinNumber:f,aliases:e.additionalAliases?.[`pin${f}`]??[]}));continue}let m=[...l.leftSide?.pins??[],...l.rightSide?.pins??[],...l.topSide?.pins??[],...l.bottomSide?.pins??[]].map(D=>OF(D,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(D=>D in l)&&(m=Array.from({length:this._getPinCount()},(D,b)=>b+1)),m.includes(f)&&s.push(new Ii({pinNumber:f,aliases:e.additionalAliases?.[`pin${f}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${f}`}))}s.length>0&&this.addAll(s)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:e,pinLabels:a,pcbPinLabels:s}=this.props,{footprint:l}=this.props;if(l??(l=this._getImpliedFootprintString?.()),!!l&&typeof l=="string"){if(VS(l)||XW(l))return;let p=Mq.string(l).soup(),x=zW({componentName:this.name??this.componentName,componentRotation:e,footprint:l,pinLabels:a,pcbPinLabels:s},p);this.addAll(x)}}get portMap(){return new Proxy({},{get:(e,a)=>{let s=this.children.find(l=>l.componentName==="Port"&&l.isMatchingNameOrAlias(a));if(!s)throw new Error(`There was an issue finding the port "${a.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return s}})}getInstanceForReactElement(e){for(let a of this.reactSubtrees)if(a.element===e)return a.component;return null}doInitialSourceRender(){let e=this.config.sourceFtype;if(!e)return;let{db:a}=this.root,{_parsedProps:s}=this,l=a.source_component.insert({ftype:e,name:this.name,manufacturer_part_number:s.manufacturerPartNumber??s.mfn,supplier_part_numbers:s.supplierPartNumbers});this.source_component_id=l.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let l of this._invalidPinLabelMessages){let p="pinLabels",x=l.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);x&&(p=`pinLabels['${x[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:p,message:l,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:a}=this.config;a?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let s=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&s){if(!this.schematic_component_id)return;let l=NA.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});e.schematic_manual_edit_conflict_warning.insert(l)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let e=[];for(let a of this.internallyConnectedPinNames){let s=[];for(let l of a)s.push(this.portMap[l]);e.push(s)}return e}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getSchematicSymbolNameOrThrow(),l=Ps[s],p=this._getGlobalSchematicPositionBeforeLayout();if(l){let x=e.schematic_component.insert({center:p,size:l.size,source_component_id:this.source_component_id,symbol_name:s,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=x.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getSchematicBoxDimensions(),l={};if(Array.isArray(a.pinLabels))a.pinLabels.forEach((B,w)=>{l[String(w+1)]=B});else for(let[B,w]of Object.entries(a.pinLabels??{}))l[B]=Array.isArray(w)?w[0]:w;let p=this._getGlobalSchematicPositionBeforeLayout(),x=this._getSchematicPortArrangement(),f=e.schematic_component.insert({center:p,rotation:a.schRotation??0,size:s.getSize(),port_arrangement:CUt(x),pin_spacing:a.schPinSpacing??.2,pin_styles:vUt(a.schPinStyle,a.pinLabels),port_labels:l,source_component_id:this.source_component_id}),m=x?.topSide!==void 0||x?.bottomSide!==void 0,D=s?.getSize().width,b=s?.getSize().height,E=e.schematic_text.insert({text:a.manufacturerPartNumber??"",schematic_component_id:f.schematic_component_id,anchor:"left",rotation:0,position:{x:m?p.x+(D??0)/2+.1:p.x-(D??0)/2,y:m?p.y+(b??0)/2+.35:p.y-(b??0)/2-.13},color:"#006464",font_size:.18}),A=e.schematic_text.insert({text:a.name??"",schematic_component_id:f.schematic_component_id,anchor:"left",rotation:0,position:{x:m?p.x+(D??0)/2+.1:p.x-(D??0)/2,y:m?p.y+(b??0)/2+.55:p.y+(b??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=f.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:s.subcircuit_id??void 0});if(!(a.footprint??this._getImpliedFootprintString())&&!this.isGroup){let f=e.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=f.pcb_missing_footprint_error_id}this.pcb_component_id=l.pcb_component_id;let x=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&x){let f=OA.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:s.subcircuit_id??void 0});e.pcb_manual_edit_conflict_warning.insert(f)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:e}=this.root,{_parsedProps:a}=this,s=rK(this.children);if(s.width===0||s.height===0)return;let l={x:(s.minX+s.maxX)/2,y:(s.minY+s.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:l,width:s.width,height:s.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}_renderReactSubtree(e){return{element:e,component:EBe(e)}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){}doInitialPcbFootprintStringRender(){gVt(this,(e,a)=>this._queueAsyncEffect(e,a))}_hasExistingPortExactly(e){return this.children.filter(s=>s.componentName==="Port").some(s=>{let l=e.getNameAndAliases(),p=s.getNameAndAliases();return l.length===p.length&&l.every(x=>p.includes(x))})}add(e){let a;if((0,LF.isValidElement)(e)){let s=this._renderReactSubtree(e);this.reactSubtrees.push(s),a=s.component}else a=e;if(a.componentName==="Port"){if(this._hasExistingPortExactly(a))return;let l=this.children.filter(p=>p.componentName==="Port").find(p=>p.isMatchingAnyOf(a.getNameAndAliases()));l&&DVt(`Similar ports added. Port 1: ${l}, Port 2: ${a}`)}super.add(a)}getPortsFromFootprint(e){let{footprint:a}=this.props;if((!a||(0,LF.isValidElement)(a))&&(a=this.children.find(l=>l.componentName==="Footprint")),typeof a=="string"){if(VS(a))return[];if(XW(a))return[];let l=Mq.string(a).soup(),p=[];for(let x of l)if("port_hints"in x&&x.port_hints){let f=IF(x.port_hints,e);if(!f)continue;f.originDescription=`footprint:string:${a}:port_hints[0]:${x.port_hints[0]}`,p.push(f)}return p}if(!(0,LF.isValidElement)(a)&&a&&a.componentName==="Footprint"){let l=a,p=1,x=[];for(let f of l.children){if(!f.props.portHints)continue;let m=f.props.portHints;m.some(E=>E.startsWith("pin"))||(m=[...m,`pin${p}`]),p++;let b=IF(m);b&&(b.originDescription=`footprint:${a}`,x.push(b))}return x}let s=[];if(!a){for(let l of this.children)if(l.props.portHints&&l.isPcbPrimitive){let p=IF(l.props.portHints);p&&s.push(p)}}return s}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:e}=this;if(!e.schematicSymbolName)return[];let a=Ps[e.schematicSymbolName];if(!a)return[];let s=[];for(let l of a.ports){let p=IF(l.labels);p&&(p.schematicSymbolPortDef=l,s.push(p))}return s}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:e}=this,a=[];if(e.connections)for(let[s,l]of Object.entries(e.connections)){let p=Array.isArray(l)?l:[l];for(let x of p)a.push(x)}return a}_createNetsFromProps(e){ZW(this,e)}_getPcbCircuitJsonBounds(){let{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let a=e.pcb_component.get(this.pcb_component_id);return{center:{x:a.center.x,y:a.center.y},bounds:{left:a.center.x-a.width/2,top:a.center.y-a.height/2,right:a.center.x+a.width/2,bottom:a.center.y+a.height/2},width:a.width,height:a.height}}_getPinCountFromSchematicPortArrangement(){let e=this._getSchematicPortArrangement();if(!e)return 0;if(!_Be(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);let{leftSide:s,rightSide:l,topSide:p,bottomSide:x}=e;return Math.max(...s?.pins??[],...l?.pins??[],...p?.pins??[],...x?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let a=this.getPortsFromFootprint();if(a.length>0)return a.length;let{pinLabels:s}=this._parsedProps;if(s){if(Array.isArray(s))return s.length;let l=Object.keys(s).map(p=>p.startsWith("pin")?parseInt(p.slice(3)):parseInt(p)).filter(p=>!Number.isNaN(p));return l.length>0?Math.max(...l):Object.keys(s).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this,a=this._getPinCount(),s=e.schPinSpacing??.2;return IUt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:s,numericSchPinStyle:kUt(e.schPinStyle,e.pinLabels),pinCount:a,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:e.pinLabels})}doInitialCadModelRender(){let{db:e}=this.root,{boardThickness:a=0}=this.root?._getBoard()??{},s=this._parsedProps.cadModel,l=this.props.footprint??this._getImpliedFootprintString();if(!this.pcb_component_id||!s&&!l||s===null)return;let p=this._getPcbCircuitJsonBounds(),x=e.pcb_component.get(this.pcb_component_id);if(typeof s=="string")throw new Error("String cadModel not yet implemented");let f=yVt.parse({x:0,y:0,z:typeof s?.rotationOffset=="number"?s.rotationOffset:0,...typeof s?.rotationOffset=="object"?s.rotationOffset??{}:{}}),m=Lf.parse({x:0,y:0,z:0,...typeof s?.positionOffset=="object"?s.positionOffset:{}}),D=this.props.layer==="bottom"?"bottom":"top",b=e.cad_component.insert({position:{x:p.center.x+m.x,y:p.center.y+m.y,z:(D==="bottom"?-a/2:a/2)+m.z},rotation:{x:f.x,y:(D==="top"?0:180)+f.y,z:D==="bottom"?-((x?.rotation??0)+f.z)+180:(x?.rotation??0)+f.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(s??{})?this._addCachebustToModelUrl(s.stlUrl):void 0,model_obj_url:"objUrl"in(s??{})?this._addCachebustToModelUrl(s.objUrl):void 0,model_gltf_url:"gltfUrl"in(s??{})?this._addCachebustToModelUrl(s.gltfUrl):void 0,model_jscad:"jscad"in(s??{})?s.jscad:void 0,footprinter_string:typeof l=="string"&&!s?l:void 0})}_addCachebustToModelUrl(e){if(!e||!e.includes("modelcdn.tscircuit.com"))return e;let a=this.root?.getClientOrigin()??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(a)}`}_getPartsEngineCacheKey(e,a){return JSON.stringify({ftype:e.ftype,name:e.name,manufacturer_part_number:e.manufacturer_part_number,footprinterString:a})}async _getSupplierPartNumbers(e,a,s){if(this.props.doNotPlace)return{};let l=this.root?.platform?.localCacheEngine,p=this._getPartsEngineCacheKey(a,s);if(l){let m=await l.getItem(p);if(m)try{return JSON.parse(m)}catch{}}let x=await Promise.resolve(e.findPart({sourceComponent:a,footprinterString:s})),f=x==="Not found"?{}:x;if(l)try{await l.setItem(p,JSON.stringify(f))}catch{}return f}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let e=this.getInheritedProperty("partsEngine");if(!e)return;let{db:a}=this.root,s=a.source_component.get(this.source_component_id);if(!s||s.supplier_part_numbers)return;let l;this.props.footprint&&typeof this.props.footprint=="string"&&(l=this.props.footprint);let p=this._getSupplierPartNumbers(e,s,l);if(!(p instanceof Promise)){a.source_component.update(this.source_component_id,{supplier_part_numbers:p});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await p,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:e}=this.root,a=e.source_component.get(this.source_component_id);if(a&&!a.supplier_part_numbers&&this._asyncSupplierPartNumbers){e.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:e}=this;e.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:e}=this;if(e.connections)for(let[a,s]of Object.entries(e.connections)){let l=Array.isArray(s)?s:[s];for(let p of l)this.add(new zc({from:`${this.getSubcircuitSelector()} > port.${a}`,to:p}))}}doInitialSourceDesignRuleChecks(){dVt(this)}_getMinimumFlexContainerSize(){return cVt(this)}_repositionOnPcb(e){return lVt(this,e)}doInitialSilkscreenOverlapAdjustment(){return fVt(this)}},bVt=class{constructor(n,e={}){q(this,"input");q(this,"isRouting",!1);q(this,"solver");q(this,"eventHandlers",{complete:[],error:[],progress:[]});q(this,"cycleCount",0);q(this,"stepDelay");q(this,"timeoutId");this.input=n;let{capacityDepth:a,targetMinCapacity:s,stepDelay:l=0}=e;this.solver=new r6e(n,{capacityDepth:a,targetMinCapacity:s,cacheProvider:null}),this.stepDelay=l}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new jF(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let n=Date.now(),e=this.solver.iterations;for(;Date.now()-n<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let a=(this.solver.iterations-e)/(Date.now()-n)*1e3;this.cycleCount++;let s=this.solver?.preview()||void 0,l=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:a,progress:l,phase:this.solver.getCurrentPhase(),debugGraphics:s}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(n){this.emitEvent({type:"error",error:n instanceof Error?new jF(n.message):new jF(String(n))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(n,e){n==="complete"?this.eventHandlers.complete.push(e):n==="error"?this.eventHandlers.error.push(e):n==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(n){if(n.type==="complete")for(let e of this.eventHandlers.complete)e(n);else if(n.type==="error")for(let e of this.eventHandlers.error)e(n);else if(n.type==="progress")for(let e of this.eventHandlers.progress)e(n)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new jF(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},aK=class extends ma{constructor(){super(...arguments);q(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:jAe}}doInitialPortMatching(){let{db:e}=this.root,{_parsedProps:a,parent:s}=this;if(!s)return;if(s.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!s)throw new Error("TraceHint has no parent");if(!a.for){this.renderError(`TraceHint has no for property (${this})`);return}let l=s.selectOne(a.for,{type:"port"});l||this.renderError(`${this} could not find port for selector "${a.for}"`),this.matchedPort=l,l.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:e}=this,a=e.offset?[e.offset]:e.offsets;if(!a)return[];let s=this._computePcbGlobalTransformBeforeLayout();return a.map(l=>({...rs(s,l),via:l.via,to_layer:l.to_layer,trace_width:l.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this;e.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},wBe=({circuitJson:n,editEvents:e,manualEditsFile:a})=>{let s={...a,pcb_placements:[...a.pcb_placements??[]]};for(let l of e)if(l.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:p,new_center:x}=l,f=ia(n).pcb_component.get(p);if(!f)continue;let m=ia(n).source_component.get(f.source_component_id);if(!m)continue;let D=s.pcb_placements?.findIndex(E=>E.selector===m.name),b={selector:m.name,center:x,relative_to:"group_center"};D>=0?s.pcb_placements[D]=b:s.pcb_placements.push(b)}return s},TBe=({circuitJson:n,editEvents:e,manualEditsFile:a})=>{let s={...a,schematic_placements:[...a.schematic_placements??[]]};for(let l of e)if(l.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:p,new_center:x}=l,f=ia(n).schematic_component.get(p);if(!f)continue;let m=ia(n).source_component.get(f.source_component_id);if(!m)continue;let D=s.schematic_placements?.findIndex(E=>E.selector===m.name),b={selector:m.name,center:x,relative_to:"group_center"};D>=0?s.schematic_placements[D]=b:s.schematic_placements.push(b)}return s},FVt=({circuitJson:n,editEvents:e,manualEditsFile:a})=>{let s=e.filter(x=>x.edit_event_type==="edit_schematic_component_location"),l=e.filter(x=>x.edit_event_type==="edit_pcb_component_location"),p=a;return s.length>0&&(p=TBe({circuitJson:n,editEvents:s,manualEditsFile:p})),l.length>0&&(p=wBe({circuitJson:n,editEvents:l,manualEditsFile:p})),p},EVt=(n,e)=>{if(ia(n).pcb_trace_hint.get(e.pcb_trace_hint_id))n=n.map(s=>s.pcb_trace_hint_id===e.pcb_trace_hint_id?{...s,route:e.route}:s);else{let s=ia(n).pcb_port.get(e.pcb_port_id);n=n.filter(l=>!(l.type==="pcb_trace_hint"&&l.pcb_port_id===e.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:e.pcb_trace_hint_id,route:e.route,pcb_port_id:e.pcb_port_id,pcb_component_id:s?.pcb_component_id}])}return n},vVt=({circuitJson:n,editEvents:e})=>{n=JSON.parse(JSON.stringify(n));for(let a of e)if(a.edit_event_type==="edit_pcb_component_location"){let s=n.find(p=>p.type==="pcb_component"&&p.pcb_component_id===a.pcb_component_id);if((!s||s.center.x!==a.new_center.x||s.center.y!==a.new_center.y)&&a.original_center){let p=ka(a.new_center.x-a.original_center.x,a.new_center.y-a.original_center.y);n=n.map(x=>x.pcb_component_id!==a.pcb_component_id?x:RY(x,p))}}else a.edit_event_type==="edit_schematic_component_location"?n=n.map(s=>s.type==="schematic_component"&&s.schematic_component_id===a.schematic_component_id?{...s,center:a.new_center}:s):a.edit_event_type==="edit_pcb_trace_hint"&&(n=EVt(n,a));return n},PBe=(n,e)=>{let a=n.source_group.list(),s=[],l=p=>{let x=a.filter(f=>f.parent_subcircuit_id===p);for(let f of x)f.subcircuit_id&&(s.push(f.subcircuit_id),l(f.subcircuit_id))};return l(e),s},YW=({db:n,circuitJson:e,subcircuit_id:a,minTraceWidth:s=.1})=>{if(!n&&e&&(n=ia(e)),!n)throw new Error("db or circuitJson is required");let l=n.pcb_trace_hint.list(),p=a?new Set([a]):null;if(a){let K=PBe(n,a);for(let U of K)p.add(U)}let x=(e??n.toArray()).filter(K=>!a||"subcircuit_id"in K&&p.has(K.subcircuit_id)),f=n.pcb_board.list()[0];n=ia(x);let m=Ku(x),D=SBe([...n.pcb_component.list(),...n.pcb_smtpad.list(),...n.pcb_plated_hole.list(),...n.pcb_hole.list(),...n.pcb_via.list(),...n.pcb_cutout.list()].filter(K=>!a||p?.has(K.subcircuit_id)),m);for(let K of D){let U=K.connectedTo.flatMap(J=>m.getIdsConnectedToNet(J));K.connectedTo.push(...U)}let b=D.flatMap(K=>[{x:K.center.x-K.width/2,y:K.center.y-K.height/2},{x:K.center.x+K.width/2,y:K.center.y+K.height/2}]),E;if(f?E={minX:f.center.x-f.width/2,maxX:f.center.x+f.width/2,minY:f.center.y-f.height/2,maxY:f.center.y+f.height/2}:E={minX:Math.min(...b.map(K=>K.x))-1,maxX:Math.max(...b.map(K=>K.x))+1,minY:Math.min(...b.map(K=>K.y))-1,maxY:Math.max(...b.map(K=>K.y))+1},a){let K=n.pcb_group.getWhere({subcircuit_id:a});if(K){let U={minX:K.center.x-K.width/2,maxX:K.center.x+K.width/2,minY:K.center.y-K.height/2,maxY:K.center.y+K.height/2};E={minX:Math.min(E.minX,U.minX),maxX:Math.max(E.maxX,U.maxX),minY:Math.min(E.minY,U.minY),maxY:Math.max(E.maxY,U.maxY)}}}let A=new Set(n.pcb_trace.list().map(K=>K.source_trace_id).filter(K=>!!K)),B=n.source_trace.list().filter(K=>!A.has(K.source_trace_id)).map(K=>{let U=K.connected_source_port_ids.map(Ve=>{let et=n.source_port.get(Ve),ct=n.pcb_port.getWhere({source_port_id:Ve});return{...et,...ct}});if(U.length<2)return null;let[J,Q]=U,de=J.layers?.[0]??"top",ce=Q.layers?.[0]??"top",Te=l.filter(Ve=>Ve.pcb_port_id===J.pcb_port_id||Ve.pcb_port_id===Q.pcb_port_id),Ne=[];for(let Ve of Te){let ct=n.pcb_port.get(Ve.pcb_port_id)?.layers?.[0]??"top";for(let Mt of Ve.route)Ne.push({x:Mt.x,y:Mt.y,layer:ct})}return{name:K.source_trace_id??m.getNetConnectedToId(K.source_trace_id)??"",source_trace_id:K.source_trace_id,pointsToConnect:[{x:J.x,y:J.y,layer:de,pointId:J.pcb_port_id,pcb_port_id:J.pcb_port_id},...Ne,{x:Q.x,y:Q.y,layer:ce,pointId:Q.pcb_port_id,pcb_port_id:Q.pcb_port_id}]}}).filter(K=>K!==null),w=new Map(B.map(K=>[K.source_trace_id,K])),P=n.source_net.list().filter(K=>!a||p?.has(K.subcircuit_id)),N=[];for(let K of P){let U=n.source_trace.list().filter(J=>J.connected_source_net_ids?.includes(K.source_net_id));N.push({name:K.source_net_id??m.getNetConnectedToId(K.source_net_id),pointsToConnect:U.flatMap(J=>n.pcb_port.list().filter(de=>J.connected_source_port_ids.includes(de.source_port_id)).map(de=>({x:de.x,y:de.y,layer:de.layers?.[0]??"top",pointId:de.pcb_port_id,pcb_port_id:de.pcb_port_id})))})}let O=n.pcb_breakout_point.list().filter(K=>!a||p?.has(K.subcircuit_id)),$=[],ee=new Map;for(let K of O){let U={x:K.x,y:K.y,layer:"top"};if(K.source_trace_id){let J=w.get(K.source_trace_id)??ee.get(K.source_trace_id);if(J)J.pointsToConnect.push(U);else{let Q={name:K.source_trace_id,source_trace_id:K.source_trace_id,pointsToConnect:[U]};$.push(Q),ee.set(K.source_trace_id,Q)}}else if(K.source_net_id){let J=N.find(Q=>Q.name===K.source_net_id);J?J.pointsToConnect.push(U):$.push({name:K.source_net_id,pointsToConnect:[U]})}else if(K.source_port_id){let J=n.pcb_port.getWhere({source_port_id:K.source_port_id});J&&$.push({name:K.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:J.x,y:J.y,layer:J.layers?.[0]??"top",pointId:J.pcb_port_id,pcb_port_id:J.pcb_port_id},U]})}}let X=[...B,...N,...$],te=new Map;for(let K of X)for(let U of K.pointsToConnect)U.pointId&&te.set(U.pointId,K);let L=n.pcb_trace.list().filter(K=>!a||p?.has(K.subcircuit_id));for(let K of L){let U=new Set;for(let de of K.route)de.start_pcb_port_id&&U.add(de.start_pcb_port_id),de.end_pcb_port_id&&U.add(de.end_pcb_port_id);if(U.size<2)continue;let J=U.values().next().value;if(!J)continue;let Q=te.get(J);Q&&[...U].every(de=>te.get(de)===Q)&&(Q.externallyConnectedPointIds??(Q.externallyConnectedPointIds=[]),Q.externallyConnectedPointIds.push([...U]))}return{simpleRouteJson:{bounds:E,obstacles:D,connections:X,layerCount:f?.num_layers??2,minTraceWidth:s},connMap:m}},CVt=n=>{let e={};if(!n)return e;for(let s of id)e[s]=0;let a=new Map;for(let s of n){let[,,l,p]=s.type.split(":");if(p==="start"){a.set(`${l}:${s.renderId}`,s);continue}if(p==="end"){let x=a.get(`${l}:${s.renderId}`);if(x){let f=s.createdAt-x.createdAt;e[l]=(e[l]||0)+f}}}return e},_Vt=n=>{let e=n.map(m=>[...new Set(m)]),a=e.map(()=>[]),s=e.map(()=>null);for(let m=0;m<e.length;m++)for(let D of e[m])if(/^\d+$/.test(D)){s[m]=Number.parseInt(D);break}let l=0,p=new Set;for(let m=0;m<s.length;m++){let D=s[m];if(D===null||D<1)continue;if(!p.has(D)){p.add(D),a[m].push(`pin${D}`),l=Math.max(l,D);continue}let b=0;for(let E of a[m])E.startsWith(`pin${D}_alt`)&&b++;a[m].push(`pin${D}_alt${b+1}`)}for(let m=0;m<a.length;m++)a[m][0]?.includes("_alt")&&(l++,a[m].unshift(`pin${l}`));for(let m=0;m<a.length;m++)a[m].length===0&&(l++,a[m].push(`pin${l}`));let x={};for(let m of e)for(let D of m)/^\d+$/.test(D)||(x[D]=(x[D]??0)+1);let f={};for(let m=0;m<e.length;m++){let D=e[m];for(let b of D)/^\d+$/.test(b)||(x[b]===1?a[m].push(b):(f[b]=(f[b]??0)+1,a[m].push(`${b}${f[b]}`)))}return a},sBe=(0,IBe.default)("Group_doInitialSchematicLayoutMatchAdapt");function AVt(n){let{db:e}=n.root,a=Lb(e.toArray(),{source_group_id:n.source_group_id}),s=rH(a);sBe.enabled&&global.debugGraphics?.push(Vp(s,{title:`floatingBpcGraph-${n.name}`}));let l=rH(a),p={boxes:l.boxes,pins:l.pins.map(m=>({...m,color:m.color.replace("not_connected","normal")}))},{result:x}=TRe([{variantName:"default",floatingGraph:l},{variantName:"noNotConnected",floatingGraph:p}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(l.boxes.filter(m=>l.pins.filter(E=>E.boxId===m.boxId).filter(E=>!E.color.includes("center")).length<=2).map(m=>m.boxId)),corpus:{}});sBe.enabled&&global.debugGraphics?.push(Vp(x,{title:`laidOutBpcGraph-${n.name}`}));let f=n._getGlobalSchematicPositionBeforeLayout();for(let m of x.boxes){if(!m.center)continue;let D=e.schematic_component.get(m.boxId);if(D){let E={x:m.center.x+f.x,y:m.center.y+f.y},A=e.schematic_port.list({schematic_component_id:D.schematic_component_id}),B=e.schematic_text.list({schematic_component_id:D.schematic_component_id}),w={x:E.x-D.center.x,y:E.y-D.center.y};for(let P of A)P.center.x+=w.x,P.center.y+=w.y;for(let P of B)P.position.x+=w.x,P.position.y+=w.y;D.center=E;continue}let b=e.schematic_net_label.get(m.boxId);if(b){let E=x.pins.find(B=>B.boxId===m.boxId&&B.color==="netlabel_center");if(!E)throw new Error(`No pin found for net label: ${m.boxId}`);let A={x:m.center.x+f.x,y:m.center.y+f.y};b.center=A,b.anchor_position={x:A.x+E.offset.x,y:A.y+E.offset.y};continue}console.error(`No schematic element found for box: ${m.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var nn=(0,jBe.default)("Group_doInitialSchematicLayoutMatchpack");function iBe(n){switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function oBe(n,e){let a=["right","up","left","down"],s=a.indexOf(n);if(s===-1)return n;let l=Math.round(e/90),p=(s+l)%4;return a[p<0?p+4:p]}function RVt(n,e,a){let s={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};nn(`[${a.name}] Processing ${n.childNodes.length} child nodes for input problem`),n.childNodes.forEach((p,x)=>{if(nn(`[${a.name}] Processing child ${x}: nodeType=${p.nodeType}`),p.nodeType==="component"?nn(`[${a.name}] - Component: ${p.sourceComponent?.name}`):p.nodeType==="group"&&nn(`[${a.name}] - Group: ${p.sourceGroup?.name}`),p.nodeType==="component"&&p.sourceComponent){let f=p.sourceComponent.name||`chip_${x}`,m=e.schematic_component.getWhere({source_component_id:p.sourceComponent.source_component_id});if(!m)return;let D=a.children.find(A=>A.source_component_id===p.sourceComponent?.source_component_id),b=[0,90,180,270];D?._parsedProps?.schOrientation&&(b=[0]),D?._parsedProps?.schRotation!==void 0&&(b=[0]),s.chipMap[f]={chipId:f,pins:[],size:{x:m.size?.width||1,y:m.size?.height||1},availableRotations:b};let E=e.schematic_port.list({schematic_component_id:m.schematic_component_id});for(let A of E){let B=e.source_port.get(A.source_port_id);if(!B)continue;let w=`${f}.${B.pin_number||B.name||A.schematic_port_id}`;s.chipMap[f].pins.push(w);let P=iBe(A.facing_direction);s.chipPinMap[w]={pinId:w,offset:{x:(A.center?.x||0)-(m.center.x||0),y:(A.center?.y||0)-(m.center.y||0)},side:P}}}else if(p.nodeType==="group"&&p.sourceGroup){let f=p.sourceGroup.name||`group_${x}`;nn(`[${a.name}] Processing nested group: ${f}`);let m=e.schematic_group?.getWhere?.({source_group_id:p.sourceGroup.source_group_id});if(nn(`[${a.name}] Found schematic_group for ${f}:`,m),m){nn(`[${a.name}] Treating group ${f} as composite chip`);let D=e.schematic_component.list({schematic_group_id:m.schematic_group_id});nn(`[${a.name}] Group ${f} has ${D.length} components:`,D.map($=>$.source_component_id));let b=1/0,E=-1/0,A=1/0,B=-1/0,w=!1;for(let $ of D)if($.center&&$.size){w=!0;let ee=$.size.width/2,X=$.size.height/2;b=Math.min(b,$.center.x-ee),E=Math.max(E,$.center.x+ee),A=Math.min(A,$.center.y-X),B=Math.max(B,$.center.y+X)}let P=w?E-b:2,N=w?B-A:2;nn(`[${a.name}] Group ${f} computed size: ${P} x ${N}`);let O=[];for(let $ of D){let ee=e.schematic_port.list({schematic_component_id:$.schematic_component_id});for(let X of ee){let te=e.source_port.get(X.source_port_id);if(!te)continue;let L=`${f}.${te.pin_number||te.name||X.schematic_port_id}`;O.push(L);let K=m.center||{x:0,y:0},U=iBe(X.facing_direction);s.chipPinMap[L]={pinId:L,offset:{x:(X.center?.x||0)-K.x,y:(X.center?.y||0)-K.y},side:U}}}nn(`[${a.name}] Group ${f} has ${O.length} pins:`,O),s.chipMap[f]={chipId:f,pins:O,size:{x:P,y:N}},nn(`[${a.name}] Added group ${f} to chipMap`)}else nn(`[${a.name}] Warning: No schematic_group found for group ${f}`)}}),nn(`[${a.name}] Creating connections using connectivity keys`);let l=new Map;for(let[p,x]of Object.entries(s.chipMap))for(let f of x.pins){let m=f.split(".").pop(),D=n.childNodes.find(b=>b.nodeType==="component"&&b.sourceComponent?b.sourceComponent.name===p:b.nodeType==="group"&&b.sourceGroup?`group_${n.childNodes.indexOf(b)}`===p:!1);if(D?.nodeType==="group"&&D.sourceGroup){let b=e.schematic_group?.getWhere?.({source_group_id:D.sourceGroup.source_group_id});if(b){let E=e.schematic_component.list({schematic_group_id:b.schematic_group_id});for(let A of E){let B=e.source_port.list({source_component_id:A.source_component_id});for(let w of B){let P=w.pin_number||w.name;if(String(P)===String(m))if(w.subcircuit_connectivity_map_key){let N=w.subcircuit_connectivity_map_key;l.has(N)||l.set(N,[]),l.get(N).push(f),nn(`[${a.name}] \u2713 Pin ${f} has connectivity key: ${N}`)}else nn(`[${a.name}] Pin ${f} has no connectivity key`)}}}}else if(D?.nodeType==="component"&&D.sourceComponent){let b=e.source_port.list({source_component_id:D.sourceComponent.source_component_id});for(let E of b){let A=E.pin_number||E.name;if(String(A)===String(m)&&E.subcircuit_connectivity_map_key){let B=E.subcircuit_connectivity_map_key;l.has(B)||l.set(B,[]),l.get(B).push(f),nn(`[${a.name}] Pin ${f} has connectivity key: ${B}`)}}}}nn(`[${a.name}] Found ${l.size} connectivity groups:`,Array.from(l.entries()).map(([p,x])=>({key:p,pins:x})));for(let[p,x]of l)if(x.length>=2){let f=e.source_trace.list().filter(b=>b.subcircuit_connectivity_map_key===p),m=f.some(b=>b.connected_source_net_ids&&b.connected_source_net_ids.length>0),D=f.some(b=>b.connected_source_port_ids&&b.connected_source_port_ids.length>=2);if(nn(`[${a.name}] Connectivity ${p}: hasNetConnections=${m}, hasDirectConnections=${D}`),D){for(let b of f)if(b.connected_source_port_ids&&b.connected_source_port_ids.length>=2){let E=[];for(let A of b.connected_source_port_ids)for(let B of x){let w=B.split(".").pop(),P=e.source_port.get(A);if(P&&String(P.pin_number||P.name)===String(w)){let N=B.split(".")[0],O=n.childNodes.find($=>$.nodeType==="component"&&$.sourceComponent?$.sourceComponent.name===N:$.nodeType==="group"&&$.sourceGroup?`group_${n.childNodes.indexOf($)}`===N:!1);O?.nodeType==="component"&&O.sourceComponent&&e.source_port.list({source_component_id:O.sourceComponent.source_component_id}).some(ee=>ee.source_port_id===A)&&E.push(B)}}for(let A=0;A<E.length;A++)for(let B=A+1;B<E.length;B++){let w=E[A],P=E[B];s.pinStrongConnMap[`${w}-${P}`]=!0,s.pinStrongConnMap[`${P}-${w}`]=!0,nn(`[${a.name}] Created strong connection: ${w} <-> ${P}`)}}}if(m){let b=e.source_net.getWhere({subcircuit_connectivity_map_key:p}),E=b?.is_ground??!1,A=b?.is_power??!1;s.netMap[p]={netId:p,isGround:E,isPositiveVoltageSource:A};for(let B of x)s.netConnMap[`${B}-${p}`]=!0;nn(`[${a.name}] Created net ${p} with ${x.length} pins:`,x)}}return s}function SVt(n){let{db:e}=n.root,a=ig(e.toArray(),{source_group_id:n.source_group_id});if(nn(`[${n.name}] Starting matchpack layout with ${a.childNodes.length} children`),nn(`[${n.name}] Tree structure:`,JSON.stringify(a,null,2)),a.childNodes.length<=1){nn(`[${n.name}] Only ${a.childNodes.length} children, skipping layout`);return}nn("Converting circuit tree to InputProblem...");let s=RVt(a,e,n);nn.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${n.name}`,content:JSON.stringify(s,null,2)});let l=new L5e(s);if(nn("Starting LayoutPipelineSolver..."),nn.enabled&&global.debugGraphics){let m=l.visualize();global.debugGraphics.push({...m,title:`matchpack-initial-${n.name}`})}if(l.solve(),nn(`Solver completed in ${l.iterations} iterations`),nn(`Solved: ${l.solved}, Failed: ${l.failed}`),l.failed)throw nn(`Solver failed with error: ${l.error}`),new Error(`Matchpack layout solver failed: ${l.error}`);let p=l.getOutputLayout();if(nn("OutputLayout:",JSON.stringify(p,null,2)),nn("Solver completed successfully:",!l.failed),nn.enabled&&global.debugGraphics){let m=l.visualize();global.debugGraphics.push({...m,title:`matchpack-final-${n.name}`})}let x=l.checkForOverlaps(p);if(x.length>0){nn(`Warning: Found ${x.length} overlapping components:`);for(let m of x)nn(` ${m.chip1} overlaps ${m.chip2} (area: ${m.overlapArea})`)}let f=n._getGlobalSchematicPositionBeforeLayout();nn(`Group offset: x=${f.x}, y=${f.y}`),nn(`Applying layout results for ${Object.keys(p.chipPlacements).length} chip placements`);for(let[m,D]of Object.entries(p.chipPlacements)){nn(`Processing placement for chip: ${m} at (${D.x}, ${D.y})`);let b=a.childNodes.find(A=>{if(A.nodeType==="component"&&A.sourceComponent){let B=A.sourceComponent.name===m;return nn(` Checking component ${A.sourceComponent.name}: matches=${B}`),B}if(A.nodeType==="group"&&A.sourceGroup){let B=A.sourceGroup.name,w=`group_${a.childNodes.indexOf(A)}`,P=w===m;return nn(` Checking group ${B} (expected chipId: ${w}): matches=${P}`),P}return!1});if(!b){nn(`Warning: No tree node found for chip: ${m}`),nn("Available tree nodes:",a.childNodes.map((A,B)=>({type:A.nodeType,name:A.nodeType==="component"?A.sourceComponent?.name:A.sourceGroup?.name,expectedChipId:A.nodeType==="group"?`group_${B}`:A.sourceComponent?.name})));continue}let E={x:D.x+f.x,y:D.y+f.y};if(b.nodeType==="component"&&b.sourceComponent){let A=e.schematic_component.getWhere({source_component_id:b.sourceComponent.source_component_id});if(A){nn(`Moving component ${m} to (${E.x}, ${E.y})`);let B=e.schematic_port.list({schematic_component_id:A.schematic_component_id}),w=e.schematic_text.list({schematic_component_id:A.schematic_component_id}),P={x:E.x-A.center.x,y:E.y-A.center.y};for(let N of B)N.center.x+=P.x,N.center.y+=P.y;for(let N of w)N.position.x+=P.x,N.position.y+=P.y;if(A.center=E,D.ccwRotationDegrees!==0){nn(`Component ${m} has rotation: ${D.ccwRotationDegrees}\xB0`);let N=D.ccwRotationDegrees*Math.PI/180,O=Math.cos(N),$=Math.sin(N);for(let ee of B){let X=ee.center.x-E.x,te=ee.center.y-E.y,L=X*O-te*$,K=X*$+te*O;ee.center.x=E.x+L,ee.center.y=E.y+K;let U=ee.facing_direction||"right";ee.facing_direction=oBe(U,D.ccwRotationDegrees)}for(let ee of w){let X=ee.position.x-E.x,te=ee.position.y-E.y,L=X*O-te*$,K=X*$+te*O;ee.position.x=E.x+L,ee.position.y=E.y+K}if(A.symbol_name){let ee=A.symbol_name.match(/_(right|left|up|down)$/);ee&&(A.symbol_name=A.symbol_name.replace(ee[0],`_${oBe(ee[1],D.ccwRotationDegrees)}`))}}}}else if(b.nodeType==="group"&&b.sourceGroup){let A=e.schematic_group?.getWhere?.({source_group_id:b.sourceGroup.source_group_id});if(A){nn(`Moving group ${m} to (${E.x}, ${E.y}) from (${A.center?.x}, ${A.center?.y})`);let B=e.schematic_component.list({schematic_group_id:A.schematic_group_id});nn(`Group ${m} has ${B.length} components to move`);let w=A.center||{x:0,y:0},P={x:E.x-w.x,y:E.y-w.y};nn(`Position delta for group ${m}: (${P.x}, ${P.y})`);for(let N of B)if(N.center){let O={...N.center};N.center.x+=P.x,N.center.y+=P.y,nn(`Moved component ${N.source_component_id} from (${O.x}, ${O.y}) to (${N.center.x}, ${N.center.y})`);let $=e.schematic_port.list({schematic_component_id:N.schematic_component_id}),ee=e.schematic_text.list({schematic_component_id:N.schematic_component_id});for(let X of $)X.center&&(X.center.x+=P.x,X.center.y+=P.y);for(let X of ee)X.position&&(X.position.x+=P.x,X.position.y+=P.y)}A.center=E,nn(`Updated group ${m} center to (${E.x}, ${E.y})`)}}}nn("Matchpack layout completed successfully")}function BVt(n){if(!n.isSubcircuit)return;let{db:e}=n.root,a=n.selectAll("trace"),s=new Pb({});s.addConnections(a.map(f=>{let m=e.source_trace.get(f.source_trace_id);return m?[m.source_trace_id,...m.connected_source_port_ids,...m.connected_source_net_ids]:null}).filter(f=>f!==null));let{name:l}=n._parsedProps;for(let f of a){if(!f.source_trace_id)continue;let m=s.getNetConnectedToId(f.source_trace_id);m&&(f.subcircuit_connectivity_map_key=`${l??`unnamedsubcircuit${n._renderId}`}_${m}`,e.source_trace.update(f.source_trace_id,{subcircuit_connectivity_map_key:f.subcircuit_connectivity_map_key}))}let p=new Set;for(let f of a){if(!f.source_trace_id)continue;let m=e.source_trace.get(f.source_trace_id);if(m)for(let D of m.connected_source_port_ids)p.add(D)}for(let f of p){let m=s.getNetConnectedToId(f);if(!m)continue;let D=`${l??`unnamedsubcircuit${n._renderId}`}_${m}`;e.source_port.update(f,{subcircuit_connectivity_map_key:D})}let x=new Set;for(let f of a){if(!f.source_trace_id)continue;let m=e.source_trace.get(f.source_trace_id);if(m)for(let D of m.connected_source_net_ids)x.add(D)}for(let f of x){let m=s.getNetConnectedToId(f);if(!m)continue;let D=`${l??`unnamedsubcircuit${n._renderId}`}_${m}`;e.source_net.update(f,{subcircuit_connectivity_map_key:D})}}function wVt(n){let{db:e}=n.root,a=n._parsedProps,s=n.children.filter(te=>{let L=te._parsedProps?.schX!==void 0||te._parsedProps?.schY!==void 0;return te.schematic_component_id&&!L});if(s.length===0)return;let l=0,p=0;for(let te of s){let L=e.schematic_component.get(te.schematic_component_id);L?.size&&(l=Math.max(l,L.size.width),p=Math.max(p,L.size.height))}l===0&&s.length>0&&(l=1),p===0&&s.length>0&&(p=1);let x=a.gridCols,f,m=a.gridGap,D=a.gridRowGap,b=a.gridColumnGap;a.schLayout?.grid&&(x=a.schLayout.grid.cols??x,f=a.schLayout.grid.rows,m=a.schLayout.gridGap??m,D=a.schLayout.gridRowGap??D,b=a.schLayout.gridColumnGap??b);let E,A;x!==void 0&&f!==void 0?(E=x,A=f):x!==void 0?(E=x,A=Math.ceil(s.length/E)):f!==void 0?(A=f,E=Math.ceil(s.length/A)):(E=Math.ceil(Math.sqrt(s.length)),A=Math.ceil(s.length/E)),E===0&&s.length>0&&(E=1),A===0&&s.length>0&&(A=s.length);let B,w,P=te=>{if(te!==void 0)return typeof te=="number"?te:xe.parse(te)};if(D!==void 0||b!==void 0){let te=typeof m=="object"&&m!==null?m.x:m,L=typeof m=="object"&&m!==null?m.y:m;B=P(b??te)??1,w=P(D??L)??1}else if(typeof m=="number")B=m,w=m;else if(typeof m=="string"){let te=xe.parse(m);B=te,w=te}else if(typeof m=="object"&&m!==null){let te=m.x,L=m.y;B=typeof te=="number"?te:xe.parse(te??"0mm"),w=typeof L=="number"?L:xe.parse(L??"0mm")}else B=1,w=1;let N=E*l+Math.max(0,E-1)*B,O=A*p+Math.max(0,A-1)*w,$=n._getGlobalSchematicPositionBeforeLayout(),ee=$.x-N/2+l/2,X=$.y+O/2-p/2;for(let te=0;te<s.length;te++){let L=s[te];if(!L.schematic_component_id)continue;let K=Math.floor(te/E),U=te%E;if(K>=A||U>=E){console.warn(`Schematic grid layout: Child ${L.getString()} at index ${te} (row ${K}, col ${U}) exceeds specified grid dimensions (${A}x${E}). Skipping placement.`);continue}let J=ee+U*(l+B),Q=X-K*(p+w),de=e.schematic_component.get(L.schematic_component_id);if(de){let ce=de.center,Te={x:J,y:Q};e.schematic_component.update(L.schematic_component_id,{center:Te});let Ne=Te.x-ce.x,Ve=Te.y-ce.y,et=e.schematic_port.list({schematic_component_id:L.schematic_component_id});for(let Mt of et)e.schematic_port.update(Mt.schematic_port_id,{center:{x:Mt.center.x+Ne,y:Mt.center.y+Ve}});let ct=e.schematic_text.list({schematic_component_id:L.schematic_component_id});for(let Mt of ct)e.schematic_text.update(Mt.schematic_text_id,{position:{x:Mt.position.x+Ne,y:Mt.position.y+Ve}})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:N,height:O,center:$})}var uBe=(n,e)=>{let{sourceComponent:a,sourceGroup:s}=e;if(e.nodeType==="component"){let l=n.schematic_component.getWhere({source_component_id:a?.source_component_id});return l?.size?{width:l.size.width,height:l.size.height}:null}if(e.nodeType==="group"){let l=n.schematic_group.getWhere({source_group_id:s?.source_group_id});if(l?.width&&l?.height)return{width:l.width,height:l.height};let p=n.schematic_component.list({schematic_group_id:l?.schematic_group_id}),x=1/0,f=-1/0,m=1/0,D=-1/0;for(let A of p)if(A.center&&A.size){let B=A.size.width/2,w=A.size.height/2;x=Math.min(x,A.center.x-B),f=Math.max(f,A.center.x+B),m=Math.min(m,A.center.y-w),D=Math.max(D,A.center.y+w)}let b=f-x,E=D-m;return{width:b,height:E}}return null},TVt=n=>{let{db:e}=n.root,a=n._parsedProps,s=ig(e.toArray(),{source_group_id:n.source_group_id}),l=a.schJustifyContent??a.justifyContent,p=a.schAlignItems??a.alignItems,x=a.schFlexGap??a.schGap??a.gap,f=a.schFlexDirection??"row",m={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[l??"space-between"],D={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[p??"center"];if(!m)throw new Error(`Invalid justifyContent value: "${l}"`);if(!D)throw new Error(`Invalid alignItems value: "${p}"`);let b=0,E=0;typeof x=="object"?(b=x.y??0,E=x.x??0):typeof x=="number"?(b=x,E=x):typeof x=="string"&&(b=xe.parse(x),E=xe.parse(x));let A,B=a.width??a.schWidth??void 0,w=a.height??a.schHeight??void 0;(B===void 0||w===void 0)&&(A=g5(s.childNodes.map(X=>uBe(e,X)).filter(X=>X!==null),{alignItems:D,justifyContent:m,direction:f,rowGap:b,columnGap:E}),B=A.width,w=A.height);let N=new FS(B,w,{alignItems:D,justifyContent:m,direction:f,rowGap:b,columnGap:E});for(let X of s.childNodes){let te=uBe(e,X);N.addChild({metadata:X,width:te?.width??0,height:te?.height??0,flexBasis:te?f==="row"?te.width:te.height:void 0})}N.build();let O={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let X of N.children)O.minX=Math.min(O.minX,X.position.x),O.minY=Math.min(O.minY,X.position.y),O.maxX=Math.max(O.maxX,X.position.x+X.size.width),O.maxY=Math.max(O.maxY,X.position.y+X.size.height);O.width=O.maxX-O.minX,O.height=O.maxY-O.minY;let $={x:-(O.maxX+O.minX)/2,y:-(O.maxY+O.minY)/2},ee=e.toArray();for(let X of N.children){let{sourceComponent:te,sourceGroup:L}=X.metadata;if(te){let K=e.schematic_component.getWhere({source_component_id:te.source_component_id});if(!K)continue;n4e(ee,K.schematic_component_id,{x:X.position.x+X.size.width/2+$.x,y:X.position.y+X.size.height/2+$.y})}if(L){if(!e.schematic_group.getWhere({source_group_id:L.source_group_id}))continue;s4e(ee,L.source_group_id,{x:X.position.x+X.size.width/2+$.x,y:X.position.y+X.size.height/2+$.y})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:O.width,height:O.height})},NW=1;function PVt(n){let{db:e}=n.root,a=n._parsedProps,s=IVt(n);if(s.length===0)return;let l=jVt({db:e,pcbChildren:s}),p=kVt(a),x=NVt({props:a,pcbChildren:s,childDimensions:l,gridConfig:p}),f=LVt({pcbChildren:s,childDimensions:l,gridLayout:x,gridConfig:p}),{itemCoordinates:m}=f.layout();$Vt({db:e,group:n,pcbChildren:s,itemCoordinates:m,gridLayout:x}),zVt({db:e,group:n,props:a,gridLayout:x})}function IVt(n){return n.children.filter(e=>e.pcb_component_id||e.pcb_group_id)}function jVt(n){let{db:e,pcbChildren:a}=n,s=0,l=0;for(let p of a){let x=0,f=0;if(p.pcb_group_id){let m=e.pcb_group.get(p.pcb_group_id);x=m?.width??0,f=m?.height??0}else if(p.pcb_component_id){let m=e.pcb_component.get(p.pcb_component_id);x=m?.width??0,f=m?.height??0}s=Math.max(s,x),l=Math.max(l,f)}return{width:s,height:l}}function kVt(n){let e=n.pcbGridCols??n.gridCols??n.pcbLayout?.grid?.cols,a=n.pcbGridRows??n.pcbLayout?.grid?.rows,s=n.pcbGridTemplateColumns,l=n.pcbGridTemplateRows,p=E=>E===void 0?NW:typeof E=="number"?E:xe.parse(E),x=n.pcbGridGap??n.gridGap??n.pcbLayout?.gridGap,f=n.pcbGridRowGap??n.gridRowGap??n.pcbLayout?.gridRowGap,m=n.pcbGridColumnGap??n.gridColumnGap??n.pcbLayout?.gridColumnGap,D=NW,b=NW;if(f!==void 0||m!==void 0){let E=typeof x=="object"?x?.x:x,A=typeof x=="object"?x?.y:x;D=p(m??E),b=p(f??A)}else if(typeof x=="object"&&x!==null)D=p(x.x),b=p(x.y);else{let E=p(x);D=E,b=E}return{cols:e,rows:a,gapX:D,gapY:b,templateColumns:s,templateRows:l}}function NVt(n){let{props:e,pcbChildren:a,childDimensions:s,gridConfig:l}=n;return e.pcbGridTemplateColumns||e.pcbGridTemplateRows?MVt({props:e,gridConfig:l,pcbChildren:a,childDimensions:s}):OVt({gridConfig:l,pcbChildren:a,childDimensions:s})}function MVt(n){let{props:e,gridConfig:a,pcbChildren:s,childDimensions:l}=n,p=e.pcbGridTemplateColumns??"",x=e.pcbGridTemplateRows??"",f=A=>{let B=A.match(/repeat\((\d+),/);return B?parseInt(B[1]):Math.ceil(Math.sqrt(s.length))},m=e.pcbGridTemplateColumns?f(p):Math.ceil(Math.sqrt(s.length)),D=e.pcbGridTemplateRows?f(x):Math.ceil(s.length/m),b=m*l.width+Math.max(0,m-1)*a.gapX,E=D*l.height+Math.max(0,D-1)*a.gapY;return{gridTemplateColumns:p,gridTemplateRows:x,containerWidth:b,containerHeight:E}}function OVt(n){let{gridConfig:e,pcbChildren:a,childDimensions:s}=n,l,p;e.cols!==void 0&&e.rows!==void 0?(l=e.cols,p=e.rows):e.cols!==void 0?(l=e.cols,p=Math.ceil(a.length/l)):e.rows!==void 0?(p=e.rows,l=Math.ceil(a.length/p)):(l=Math.ceil(Math.sqrt(a.length)),p=Math.ceil(a.length/l)),l=Math.max(1,l),p=Math.max(1,p);let x=l*s.width+Math.max(0,l-1)*e.gapX,f=p*s.height+Math.max(0,p-1)*e.gapY,m=`repeat(${l}, ${s.width}px)`,D=`repeat(${p}, ${s.height}px)`;return{gridTemplateColumns:m,gridTemplateRows:D,containerWidth:x,containerHeight:f}}function LVt(n){let{pcbChildren:e,childDimensions:a,gridLayout:s,gridConfig:l}=n,p=e.map((x,f)=>({key:x.getString()||`child-${f}`,contentWidth:a.width,contentHeight:a.height}));return new H5e({containerWidth:s.containerWidth,containerHeight:s.containerHeight,gridTemplateColumns:s.gridTemplateColumns,gridTemplateRows:s.gridTemplateRows,gap:[l.gapY,l.gapX],children:p})}function $Vt(n){let{db:e,group:a,pcbChildren:s,itemCoordinates:l,gridLayout:p}=n,x=a._getGlobalPcbPositionBeforeLayout(),f=e.toArray();for(let m=0;m<s.length;m++){let D=s[m],b=D.getString()||`child-${m}`,E=l[b];if(!E){console.warn(`PCB grid layout: No coordinates found for child ${b}`);continue}let A=x.x-p.containerWidth/2+E.x+E.width/2,B=x.y+p.containerHeight/2-E.y-E.height/2;if(D.pcb_component_id)h5(f,D.pcb_component_id,{x:A,y:B});else{let w=D;w.pcb_group_id&&w.source_group_id&&m5(f,w.source_group_id,{x:A,y:B})}}}function zVt(n){let{db:e,group:a,props:s,gridLayout:l}=n;if(a.pcb_group_id){let p=a._getGlobalPcbPositionBeforeLayout();e.pcb_group.update(a.pcb_group_id,{width:s.width??l.containerWidth,height:s.height??l.containerHeight,center:p})}}function qVt(n){let e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof n=="object"&&!n.preset)return{local:!(n.serverUrl||n.serverMode||n.serverCacheEnabled),...e,...n};let a=typeof n=="object"?n.preset:n,s=typeof n=="object"?n:{};switch(a){case"auto-local":return{local:!0,groupMode:"subcircuit"};case"sequential-trace":return{local:!0,groupMode:"sequential-trace"};case"subcircuit":return{local:!0,groupMode:"subcircuit"};case"auto-cloud":{let{preset:l,local:p,groupMode:x,...f}=s;return{local:!1,groupMode:"subcircuit",...e,...f}}default:return{local:!0,groupMode:"subcircuit"}}}var UVt="1mm",cBe=(0,kBe.default)("Group_doInitialPcbLayoutPack"),kF=(n,e,a)=>{if(e===a)return!0;let s=n.source_group.get(e);return!s||!s.parent_source_group_id?!1:kF(n,s.parent_source_group_id,a)},VVt=n=>{let{db:e}=n.root,{_parsedProps:a}=n,{packOrderStrategy:s,packPlacementStrategy:l,gap:p,pcbGap:x,pcbPackGap:f}=a,m=f??x??p,D=xe.parse(m??UVt),b={...M5e(N5e(e.toArray(),{source_group_id:n.source_group_id,shouldAddInnerObstacles:!0})),orderStrategy:s??"largest_to_smallest",placementStrategy:l??"minimum_sum_squared_distance_to_network",minGap:D};cBe.enabled&&(n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${n.name}`,content:JSON.stringify(e.toArray())}),n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${n.name}`,content:b}));let E=gS(b);if(cBe.enabled){let A=mS(E);A.title=`packOutput-${n.name}`,global.debugGraphics?.push(A)}for(let A of E.components){let{center:B,componentId:w,ccwRotationOffset:P,ccwRotationDegrees:N}=A,O=e.pcb_component.get(w);if(O){let K=n.source_group_id,J=e.source_component.get(O.source_component_id)?.source_group_id;if(J!==void 0&&!kF(e,J,K))continue;let Q=O.center,de=N??P??0,ce=Ts(n._computePcbGlobalTransformBeforeLayout(),ka(B.x,B.y),Xf(de*Math.PI/180),ka(-Q.x,-Q.y)),Te=e.toArray().filter(Ne=>"pcb_component_id"in Ne&&Ne.pcb_component_id===w);$b(Te,ce);continue}let $=e.pcb_group.list().find(K=>K.source_group_id===w);if(!$)continue;let ee=$.center,X=N??P??0,te=Ts(n._computePcbGlobalTransformBeforeLayout(),ka(B.x,B.y),Xf(X*Math.PI/180),ka(-ee.x,-ee.y)),L=e.toArray().filter(K=>{if("source_group_id"in K&&K.source_group_id&&(K.source_group_id===w||kF(e,K.source_group_id,w)))return!0;if("source_component_id"in K&&K.source_component_id){let U=e.source_component.get(K.source_component_id);if(U?.source_group_id&&(U.source_group_id===w||kF(e,U.source_group_id,w)))return!0}if("pcb_component_id"in K&&K.pcb_component_id){let U=e.pcb_component.get(K.pcb_component_id);if(U?.source_component_id){let J=e.source_component.get(U.source_component_id);if(J?.source_group_id&&(J.source_group_id===w||kF(e,J.source_group_id,w)))return!0}}return!1});$b(L,te),e.pcb_group.update($.pcb_group_id,{center:B})}},GVt=n=>{let{db:e}=n.root,{_parsedProps:a}=n,s=n.children.filter(te=>te.pcb_component_id||te.pcb_group_id);if(s.some(te=>{let L=te._parsedProps;return L?.pcbX!==void 0||L?.pcbY!==void 0}))return;let p=a.pcbJustifyContent??a.justifyContent,x=a.pcbAlignItems??a.alignItems,f=a.pcbFlexGap??a.pcbGap??a.gap,m=a.pcbFlexDirection??"row",D={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[p??"space-between"],b={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[x??"center"];if(!D)throw new Error(`Invalid justifyContent value: "${p}"`);if(!b)throw new Error(`Invalid alignItems value: "${x}"`);let E=0,A=0;typeof f=="object"?(E=f.y??0,A=f.x??0):typeof f=="number"?(E=f,A=f):typeof f=="string"&&(E=xe.parse(f),A=xe.parse(f));let B,w=a.width??a.pcbWidth??void 0,P=a.height??a.pcbHeight??void 0;(w===void 0||P===void 0)&&(B=g5(s.map(te=>te._getMinimumFlexContainerSize()).filter(te=>te!==null),{alignItems:b,justifyContent:D,direction:m,rowGap:E,columnGap:A}),w=B.width,P=B.height);let O=new FS(w,P,{alignItems:b,justifyContent:D,direction:m,rowGap:E,columnGap:A});for(let te of s){let L=te._getMinimumFlexContainerSize();O.addChild({metadata:te,width:L?.width??0,height:L?.height??0,flexBasis:L?m==="row"?L.width:L.height:void 0})}O.build();let $={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let te of O.children)$.minX=Math.min($.minX,te.position.x),$.minY=Math.min($.minY,te.position.y),$.maxX=Math.max($.maxX,te.position.x+te.size.width),$.maxY=Math.max($.maxY,te.position.y+te.size.height);$.width=$.maxX-$.minX,$.height=$.maxY-$.minY;let ee=n._getGlobalPcbPositionBeforeLayout(),X={x:ee.x-($.maxX+$.minX)/2,y:ee.y-($.maxY+$.minY)/2};for(let te of O.children)te.metadata._repositionOnPcb({x:te.position.x+te.size.width/2+X.x,y:te.position.y+te.size.height/2+X.y});e.pcb_group.update(n.pcb_group_id,{width:$.width,height:$.height,center:ee})};function XVt(n){let{db:e}=n.root,a=new Map,s=new Map,l=new Set,x=n.selectAll("trace").filter(Q=>Q._parsedProps?.schDisplayLabel),f=n.selectAll("group"),m=[n.schematic_group_id,...f.map(Q=>Q.schematic_group_id)],D=e.schematic_component.list().filter(Q=>m.includes(Q.schematic_group_id)),b=[],E=new Map,A=new Map;for(let Q of D){let de=Q.schematic_component_id,ce=[],Te=e.source_component.getWhere({source_component_id:Q.source_component_id}),Ne=e.schematic_port.list({schematic_component_id:Q.schematic_component_id});for(let Ve of Ne){let et=`${Te?.name??Q.schematic_component_id}.${Ve.pin_number}`;E.set(et,Ve.schematic_port_id),A.set(Ve.schematic_port_id,et)}for(let Ve of Ne){let et=A.get(Ve.schematic_port_id);ce.push({pinId:et,x:Ve.center.x,y:Ve.center.y})}b.push({chipId:de,center:Q.center,width:Q.size.width,height:Q.size.height,pins:ce})}let B=new Set,w=new Map,P=new Map,N=new Map;for(let Q of D){let de=e.schematic_port.list({schematic_component_id:Q.schematic_component_id});for(let ce of de)B.add(ce.schematic_port_id),ce.source_port_id&&(w.set(ce.schematic_port_id,ce.source_port_id),P.set(ce.source_port_id,ce.schematic_port_id))}let O=new Set;n.subcircuit_id&&O.add(n.subcircuit_id);for(let Q of f)Q.subcircuit_id&&O.add(Q.subcircuit_id);let ee=e.source_trace.list().filter(Q=>{if(Q.subcircuit_id===n.subcircuit_id)return!0;for(let de of Q.connected_source_port_ids)if(P.has(de))return!0;return!1}).flatMap(Q=>Q.connected_source_net_ids);for(let Q of ee){let de=e.source_net.get(Q);de?.subcircuit_id&&O.add(de.subcircuit_id)}let X=[],te=new Map;for(let Q of e.source_trace.list()){if(Q.subcircuit_id&&!O.has(Q.subcircuit_id))continue;let de=(Q.connected_source_port_ids??[]).map(ce=>P.get(ce)).filter(ce=>!!ce&&B.has(ce));if(de.length>=2){let[ce,Te]=de.slice(0,2),Ne=[ce,Te].sort().join("::");if(!te.has(Ne)){te.set(Ne,Q.source_trace_id);let Ve=Q.display_name??Q.source_trace_id;Q.subcircuit_connectivity_map_key&&(l.add(Q.subcircuit_connectivity_map_key),N.set(Ve,Q.subcircuit_connectivity_map_key),s.set(Q.subcircuit_connectivity_map_key,Ve)),X.push({pinIds:[ce,Te].map(et=>A.get(et)),netId:Ve})}}}let L=[];for(let Q of e.source_net.list().filter(de=>!de.subcircuit_id||O.has(de.subcircuit_id)))Q.subcircuit_connectivity_map_key&&(l.add(Q.subcircuit_connectivity_map_key),a.set(Q.subcircuit_connectivity_map_key,Q));let K=new Map;for(let[Q,de]of w){let ce=e.source_port.get(de);if(!ce?.subcircuit_connectivity_map_key)continue;let Te=ce.subcircuit_connectivity_map_key;l.add(Te),K.has(Te)||K.set(Te,[]),K.get(Te).push(Q)}for(let[Q,de]of K){let ce=a.get(Q);if(ce&&de.length>=2){let Te=String(ce.name||ce.source_net_id||Q);N.set(Te,Q),s.set(Q,Te),L.push({netId:Te,pinIds:de.map(Ne=>A.get(Ne))})}}let U=(()=>{let Q={},de=new Set(L.map(ce=>ce.netId));for(let ce of e.source_net.list().filter(Te=>!Te.subcircuit_id||O.has(Te.subcircuit_id)))ce.name&&de.has(ce.name)&&(ce.is_ground||ce.name.toLowerCase().startsWith("gnd")?Q[ce.name]=["y-"]:ce.is_power||ce.name.toLowerCase().startsWith("v")?Q[ce.name]=["y+"]:Q[ce.name]=["x-","x+"]);return Q})();return{inputProblem:{chips:b,directConnections:X,netConnections:L,availableNetLabelOrientations:U,maxMspPairDistance:n._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:E,pairKeyToSourceTraceId:te,sckToSourceNet:a,sckToUserNetId:s,userNetIdToSck:N,allSourceAndSchematicPortIdsInScope:B,schPortIdToSourcePortId:w,displayLabelTraces:x,allScks:l}}var Ji=1e-6;function lBe(n){let e=Math.abs(n.to.x-n.from.x),a=Math.abs(n.to.y-n.from.y);return e>=a}function GS(n,e){return Math.hypot(e.x-n.x,e.y-n.y)}function dBe(n,e,a){return{x:n.x+(e.x-n.x)*a,y:n.y+(e.y-n.y)*a}}function pBe(n,e,a){let s=GS(n,e);if(s<Ji)return 0;let l=((a.x-n.x)*(e.x-n.x)+(a.y-n.y)*(e.y-n.y))/((e.x-n.x)*(e.x-n.x)+(e.y-n.y)*(e.y-n.y));return Math.max(0,Math.min(1,l))*s}function NS(n,e,a,s){return n*s-e*a}function YVt(n,e,a,s){let l={x:e.x-n.x,y:e.y-n.y},p={x:s.x-a.x,y:s.y-a.y},x=NS(l.x,l.y,p.x,p.y),f={x:a.x-n.x,y:a.y-n.y},m=NS(f.x,f.y,l.x,l.y);if(Math.abs(x)<Ji&&Math.abs(m)<Ji||Math.abs(x)<Ji&&Math.abs(m)>=Ji)return null;let D=NS(f.x,f.y,p.x,p.y)/x,b=NS(f.x,f.y,l.x,l.y)/x;return D<-Ji||D>1+Ji||b<-Ji||b>1+Ji?null:{x:n.x+D*l.x,y:n.y+D*l.y}}function HVt(n,e=Ji){if(n.length===0)return n;n.sort((l,p)=>l.start-p.start);let a=[],s={...n[0]};for(let l=1;l<n.length;l++){let p=n[l];p.start<=s.end+e?s.end=Math.max(s.end,p.end):(a.push(s),s={...p})}return a.push(s),a}function WVt(n,e,a){let s=GS(n.from,n.to);if(s<Ji||e.length===0)return[n];let l=a/2,p=e.map(E=>({start:Math.max(0,E-l),end:Math.min(s,E+l)})).filter(E=>E.end-E.start>Ji),x=HVt(p),f=[],m=0,D={x:n.to.x-n.from.x,y:n.to.y-n.from.y},b=(E,A,B)=>{if(A-E<=Ji)return;let w=E/s,P=A/s;f.push({from:dBe(n.from,n.to,w),to:dBe(n.from,n.to,P),...B?{is_crossing:!0}:{}})};for(let E of x)E.start-m>Ji&&b(m,E.start,!1),b(E.start,E.end,!0),m=E.end;return s-m>Ji&&b(m,s,!1),f.length>0?f:[n]}function KVt(n,e={}){let a=e.crossSegmentLength??.075,s=e.tolerance??Ji,l=new Map,p=m=>`${m.traceIdx}:${m.edgeIdx}`,x=m=>n[m.traceIdx].edges[m.edgeIdx];for(let m=0;m<n.length;m++){let D=n[m];for(let b=0;b<D.edges.length;b++){let E=D.edges[b];for(let A=m;A<n.length;A++){let B=n[A];for(let w=A===m?b+1:0;w<B.edges.length;w++){let P=B.edges[w],N=YVt(E.from,E.to,P.from,P.to);if(!N)continue;let O=GS(E.from,E.to),$=GS(P.from,P.to);if(O<s||$<s)continue;let ee=pBe(E.from,E.to,N),X=pBe(P.from,P.to,N),te=ee<=s||Math.abs(O-ee)<=s||Number.isNaN(ee),L=X<=s||Math.abs($-X)<=s||Number.isNaN(X);if(!te&&!L){let K=lBe(E),U=lBe(P),J;if(K!==U)J=K;else{let ce=Math.abs(E.to.x-E.from.x),Te=Math.abs(E.to.y-E.from.y),Ne=Math.abs(P.to.x-P.from.x),Ve=Math.abs(P.to.y-P.from.y),et=ce-Te,ct=Ne-Ve;J=et===ct?!0:et>ct}let Q=p({traceIdx:J?m:A,edgeIdx:J?b:w}),de=l.get(Q)??[];de.push(J?ee:X),l.set(Q,de)}}}}}let f=n.map(m=>({source_trace_id:m.source_trace_id,edges:[]}));for(let m=0;m<n.length;m++){let D=n[m];for(let b=0;b<D.edges.length;b++){let E=p({traceIdx:m,edgeIdx:b}),A=l.get(E)??[];if(A.length===0){f[m].edges.push(D.edges[b]);continue}let B=Array.from(new Set(A.map(P=>Number(P.toFixed(6))))).sort((P,N)=>P-N),w=WVt(D.edges[b],B,a);f[m].edges.push(...w)}}return f}var tl=1e-6;function XS(n,e,a=tl){return Math.abs(n-e)<=a}function $g(n,e,a=tl){return XS(n.x,e.x,a)&&XS(n.y,e.y,a)}function xBe(n,e,a,s=tl){let l=Math.min(e.x,a.x)-s,p=Math.max(e.x,a.x)+s,x=Math.min(e.y,a.y)-s,f=Math.max(e.y,a.y)+s;return n.x<l||n.x>p||n.y<x||n.y>f?!1:Math.abs((a.x-e.x)*(n.y-e.y)-(a.y-e.y)*(n.x-e.x))<=s}function fBe(n,e=tl){let a=new Map;for(let s of n){let l=`${s.x.toFixed(6)},${s.y.toFixed(6)}`;a.has(l)||a.set(l,s)}return Array.from(a.values())}function hBe(n){return{x:n.to.x-n.from.x,y:n.to.y-n.from.y}}function MW(n,e,a=tl){let s=hBe(n),l=hBe(e),p=Math.hypot(s.x,s.y),x=Math.hypot(l.x,l.y);if(p<a||x<a)return!0;let f=s.x*l.y-s.y*l.x;return Math.abs(f)<=a*p*x}function NF(n,e,a=tl){return n.edges.filter(s=>$g(s.from,e,a)||$g(s.to,e,a))}function mBe(n,e,a=tl){for(let s of n.edges){if($g(s.from,e,a))return s.from;if($g(s.to,e,a))return s.to}return null}function JVt(n,e,a=tl){let s=$g(n.from,e,a)||XS(n.from.x,e.x,a)&&XS(n.from.y,e.y,a)?n.to:n.from,l=s.x-e.x,p=s.y-e.y;return Math.abs(l)<a&&Math.abs(p)<a?null:Math.abs(l)>=Math.abs(p)?l>=0?"right":"left":p>=0?"up":"down"}function Mg(n,e,a=tl){let s=NF(n,e,a);if(s.length<2)return null;let l=s.map(E=>JVt(E,e,a)),p=l.includes("up"),x=l.includes("down"),f=l.includes("left"),m=l.includes("right"),D=p?"up":x?"down":null,b=m?"right":f?"left":null;return D&&b?`${D}-${b}`:null}function ZVt(n,e={}){let a=e.tolerance??tl,s={};for(let p of n)s[p.source_trace_id]=[];let l=n.map(p=>{let x=[];for(let f of p.edges)x.push(f.from,f.to);return fBe(x,a)});for(let p=0;p<n.length;p++){let x=n[p],f=l[p];for(let m=p+1;m<n.length;m++){let D=n[m],b=l[m];for(let E of f)for(let A of b)if($g(E,A,a)){let B=NF(x,E,a),w=NF(D,A,a),P=B.some(ee=>w.some(X=>!MW(ee,X,a))),N=Mg(x,E,a),O=Mg(D,A,a);P&&!(N!==null&&O!==null&&N===O)&&(s[x.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[D.source_trace_id].push(A))}for(let E of f)for(let A of D.edges)if(xBe(E,A.from,A.to,a)){let w=NF(x,E,a).some(ee=>!MW(ee,A,a)),P=Mg(x,E,a),N=mBe(D,E,a*1e3),O=N?Mg(D,N,a):null;w&&!(P!==null&&O!==null&&P===O)&&(s[x.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[D.source_trace_id].push(E))}for(let E of b)for(let A of x.edges)if(xBe(E,A.from,A.to,a)){let w=NF(D,E,a).some(ee=>!MW(A,ee,a)),P=Mg(D,E,a),N=mBe(x,E,a*1e3),O=N?Mg(x,N,a):null;w&&!(O!==null&&P!==null&&O===P)&&(s[D.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[x.source_trace_id].push(E))}}}for(let p of Object.keys(s))s[p]=fBe(s[p],a);return s}var OW=(0,MBe.default)("Group_doInitialSchematicTraceRender");function QVt(n){let{group:e,solver:a,pinIdToSchematicPortId:s,userNetIdToSck:l}=n,{db:p}=e.root,x=a.traceOverlapShiftSolver?.correctedTraceMap,f=[];OW(`Traces inside SchematicTraceSolver output: ${Object.values(x??{}).length}`);for(let b of Object.values(x??{})){let E=b?.tracePath;if(!Array.isArray(E)||E.length<2){OW(`Skipping trace ${b?.pinIds.join(",")} because it has less than 2 points`);continue}let A=[];for(let P=0;P<E.length-1;P++)A.push({from:{x:E[P].x,y:E[P].y},to:{x:E[P+1].x,y:E[P+1].y}});let B=null,w;if(Array.isArray(b?.pins)&&b.pins.length===2){let P=s.get(b.pins[0]?.pinId),N=s.get(b.pins[1]?.pinId);if(P&&N){for(let O of[P,N])p.schematic_port.get(O)&&p.schematic_port.update(O,{is_connected:!0});w=l.get(String(b.userNetId))}}B||(B=`solver_${b?.mspPairId}`,w=l.get(String(b.userNetId))),f.push({source_trace_id:B,edges:A,subcircuit_connectivity_map_key:w})}OW(`Applying ${f.length} traces from SchematicTraceSolver output`);let m=KVt(f.map(b=>({source_trace_id:b.source_trace_id,edges:b.edges}))),D=ZVt(m);for(let b of m)p.schematic_trace.insert({source_trace_id:b.source_trace_id,edges:b.edges,junctions:D[b.source_trace_id]??[],subcircuit_connectivity_map_key:f.find(E=>E.source_trace_id===b.source_trace_id)?.subcircuit_connectivity_map_key})}var eGt=n=>{switch(n){case"x+":return"left";case"x-":return"right";case"y+":return"bottom";case"y-":return"top";case"left":return"right";case"top":return"bottom";case"right":return"left";case"bottom":return"top"}},tGt=n=>{for(let a of n){let s=a._getDirectlyConnectedTraces();for(let l of s){let p=l._parsedProps.schDisplayLabel;if(p)return{name:p,wasAssignedDisplayLabel:!0}}}return{name:n.map(a=>a._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},LW=(0,OBe.default)("Group_doInitialSchematicTraceRender");function rGt(n){let{group:e,solver:a,sckToSourceNet:s,allScks:l,allSourceAndSchematicPortIdsInScope:p,schPortIdToSourcePortId:x,userNetIdToSck:f,pinIdToSchematicPortId:m,schematicPortIdsWithPreExistingNetLabels:D,schematicPortIdsWithRoutedTraces:b}=n,{db:E}=e.root,A=a.netLabelPlacementSolver?.netLabelPlacements??[],B=a.mspConnectionPairSolver.globalConnMap;for(let w of A){LW(`processing placement: ${w.netId}`);let P=B.getIdsConnectedToNet(w.globalConnNetId).find(Q=>f.get(Q)),N=f.get(P),O=w.anchorPoint,$=w.orientation,ee=eGt($),X=N?s.get(N):void 0,te=w.pinIds.map(Q=>m.get(Q));if(te.some(Q=>D.has(Q))){LW(`skipping net label placement for "${w.netId}" REASON:schematic port has pre-existing net label`);continue}if(X){let Q=X.name,de=Qp({anchor_position:O,anchor_side:ee,text:Q});E.schematic_net_label.insert({text:Q,anchor_position:O,center:de,anchor_side:ee,...X?.source_net_id?{source_net_id:X.source_net_id}:{}});continue}let L=e.selectAll("port").filter(Q=>Q._getSubcircuitConnectivityKey()===N),{name:K,wasAssignedDisplayLabel:U}=tGt(L);if(!U&&te.some(Q=>b.has(Q))){LW(`skipping net label placement for "${w.netId}" REASON:schematic port has routed traces and no display label`);continue}let J=Qp({anchor_position:O,anchor_side:ee,text:K});E.schematic_net_label.insert({text:K,anchor_position:O,center:J,anchor_side:ee})}}var nGt=({allSourceAndSchematicPortIdsInScope:n,group:e,schPortIdToSourcePortId:a,sckToSourceNet:s,pinIdToSchematicPortId:l,schematicPortIdsWithPreExistingNetLabels:p})=>{let{db:x}=e.root;for(let f of Array.from(n)){let m=x.schematic_port.get(f);if(!m||m.is_connected)continue;let D=a.get(f);if(!D)continue;let E=x.source_port.get(D)?.subcircuit_connectivity_map_key;if(!E)continue;let A=s.get(E);if(!A||x.schematic_net_label.list().some(O=>Math.abs(O.anchor_position.x-m.center.x)<.1&&Math.abs(O.anchor_position.y-m.center.y)<.1?A.source_net_id&&O.source_net_id?O.source_net_id===A.source_net_id:O.text===(A.name||E):!1))continue;let w=A.name||A.source_net_id||E,P=$F(m.facing_direction||"right")||"right",N=Qp({anchor_position:m.center,anchor_side:P,text:w});x.schematic_net_label.insert({text:w,anchor_position:m.center,center:N,anchor_side:P,...A.source_net_id?{source_net_id:A.source_net_id}:{}})}},aGt=n=>{let e=new Set,a=n.selectAll("netlabel");for(let s of a){let l=s._getConnectedPorts();for(let p of l)p.schematic_port_id&&e.add(p.schematic_port_id)}return e},sGt=({solver:n,pinIdToSchematicPortId:e})=>{let a=n.schematicTraceLinesSolver.solvedTracePaths,s=new Set;for(let l of a)for(let p of l.pinIds){let x=e.get(p);x&&s.add(x)}return s},iGt=(0,NBe.default)("Group_doInitialSchematicTraceRender"),oGt=n=>{if(!n.root?._featureMspSchematicTraceRouting||!n.isSubcircuit||n.root?.schematicDisabled)return;let{inputProblem:e,pinIdToSchematicPortId:a,pairKeyToSourceTraceId:s,sckToSourceNet:l,allSourceAndSchematicPortIdsInScope:p,schPortIdToSourcePortId:x,displayLabelTraces:f,allScks:m,userNetIdToSck:D}=XVt(n),b=aGt(n);iGt.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(e,null,2)});let E=new uSe(e);E.solve();let A=sGt({solver:E,pinIdToSchematicPortId:a});QVt({group:n,solver:E,pinIdToSchematicPortId:a,userNetIdToSck:D}),rGt({group:n,solver:E,sckToSourceNet:l,allSourceAndSchematicPortIdsInScope:p,schPortIdToSourcePortId:x,pinIdToSchematicPortId:a,allScks:m,userNetIdToSck:D,schematicPortIdsWithPreExistingNetLabels:b,schematicPortIdsWithRoutedTraces:A}),nGt({group:n,allSourceAndSchematicPortIdsInScope:p,schPortIdToSourcePortId:x,sckToSourceNet:l,pinIdToSchematicPortId:a,schematicPortIdsWithPreExistingNetLabels:b})},zg=class extends Za{constructor(){super(...arguments);q(this,"pcb_group_id",null);q(this,"schematic_group_id",null);q(this,"subcircuit_id",null);q(this,"_hasStartedAsyncAutorouting",!1);q(this,"_asyncAutoroutingResult",null);q(this,"unnamedElementCounter",{})}get config(){return{zodProps:z_e,componentName:"Group"}}doInitialSourceGroupRender(){let{db:e}=this.root,a=e.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit});this.source_group_id=a.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${a.source_group_id}`,e.source_group.update(a.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:e}=this.root;for(let a of this.children)e.source_component.update(a.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:e}=this.root,a=this.parent?.getGroup?.();if(a?.source_group_id&&e.source_group.update(this.source_group_id,{parent_source_group_id:a.source_group_id}),!this.isSubcircuit)return;let s=this.parent?.getSubcircuit?.()?.subcircuit_id;s&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:s})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:a.autorouter?{trace_clearance:a.autorouter.traceClearance}:void 0});this.pcb_group_id=s.pcb_group_id;for(let l of this.children)e.pcb_component.update(l.pcb_component_id,{pcb_group_id:s.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,a=this._parsedProps,s=rK(this.children);if(this.pcb_group_id){let l=s.width,p=s.height,x=(s.minX+s.maxX)/2,f=(s.minY+s.maxY)/2;if(this.isSubcircuit){let{padLeft:b,padRight:E,padTop:A,padBottom:B}=this._resolvePcbPadding();l+=b+E,p+=A+B,x+=(E-b)/2,f+=(A-B)/2}let D=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0?e.pcb_group.get(this.pcb_group_id)?.center??{x,y:f}:{x,y:f};e.pcb_group.update(this.pcb_group_id,{width:Number(a.width??l),height:Number(a.height??p),center:D})}}getNextAvailableName(e){var a,s;return(a=this.unnamedElementCounter)[s=e.lowercaseComponentName]??(a[s]=1),`unnamed_${e.lowercaseComponentName}${this.unnamedElementCounter[e.lowercaseComponentName]++}`}_resolvePcbPadding(){let e=this._parsedProps,a=e.pcbLayout,s=E=>{let A=a?.[E],B=e[E];if(typeof A=="number")return A;if(typeof B=="number")return B},l=s("padding")??0,p=s("paddingX"),x=s("paddingY"),f=s("paddingLeft")??p??l,m=s("paddingRight")??p??l,D=s("paddingTop")??x??l,b=s("paddingBottom")??x??l;return{padLeft:f,padRight:m,padTop:D,padBottom:b}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:e}=this,{db:a}=this.root,s=e;if(!this.isSubcircuit)return;let l=s.manualEdits?.manual_trace_hints;if(l)for(let p of l)this.add(new aK({for:p.pcb_port_selector,offsets:p.offsets}))}doInitialSourceAddConnectivityMapKey(){BVt(this)}_areChildSubcircuitsRouted(){let e=this.selectAll("group").filter(a=>a.isSubcircuit);for(let a of e)if(a._shouldRouteAsync()&&!a._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let e=this._getAutorouterConfig();return e.groupMode==="sequential-trace"?!1:!!(e.local&&e.groupMode==="subcircuit"||!e.local)}_hasTracesToRoute(){let e=(0,Og.default)("tscircuit:core:_hasTracesToRoute"),a=this.selectAll("trace");return e(`[${this.getString()}] has ${a.length} traces to route`),a.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:e}=this.root,a=(0,Og.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),s=this._parsedProps,l=this._getAutorouterConfig(),p=l.serverUrl,x=l.serverMode,f=(b,E)=>(a("fetching",b),E.headers&&(E.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(b,E)),m=this.root.db.toArray().filter(b=>b.type.startsWith("source_")||b.type.startsWith("pcb_"));if(x==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:E}=await f(`${p}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:YW({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(A=>A.json());this._asyncAutoroutingResult=E,this._markDirty("PcbTraceRender");return}let{autorouting_result:b}=await f(`${p}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:m,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(E=>E.json());this._asyncAutoroutingResult=b,this._markDirty("PcbTraceRender");return}let{autorouting_job:D}=await f(`${p}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:m,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:l.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(b=>b.json());for(;;){let{autorouting_job:b}=await f(`${p}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:D.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(E=>E.json());if(b.is_finished){let{autorouting_job_output:E}=await f(`${p}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:D.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(A=>A.json());this._asyncAutoroutingResult={output_pcb_traces:E.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(b.has_error){let E=new jF(`Autorouting job failed: ${JSON.stringify(b.error)}`);throw e.pcb_autorouting_error.insert({pcb_error_id:D.autorouting_job_id,error_type:"pcb_autorouting_error",message:E.message}),E}await new Promise(E=>setTimeout(E,100))}}async _runLocalAutorouting(){let{db:e}=this.root,a=this._parsedProps,s=(0,Og.default)("tscircuit:core:_runLocalAutorouting");s(`[${this.getString()}] starting local autorouting`);let l=this._getAutorouterConfig(),{simpleRouteJson:p}=YW({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(s.enabled){let m=ZY(p);m.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(m)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:p});let x;l.algorithmFn?x=await l.algorithmFn(p):x=new bVt(p,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity});let f=new Promise((m,D)=>{x.on("complete",b=>{s(`[${this.getString()}] local autorouting complete`),m(b.traces)}),x.on("error",b=>{s(`[${this.getString()}] local autorouting error: ${b.error.message}`),D(b.error)})});x.on("progress",m=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...m})}),x.start();try{let m=await f;this._asyncAutoroutingResult={output_pcb_traces:m},this._markDirty("PcbTraceRender")}catch(m){let{db:D}=this.root;throw D.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:m instanceof Error?m.message:String(m)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:m instanceof Error?m.message:String(m)},simpleRouteJson:p}),m}finally{x.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let e=(0,Og.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){e(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}e(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){oGt(this)}updatePcbTraceRender(){let e=(0,Og.default)("tscircuit:core:updatePcbTraceRender");if(e(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(e(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:a}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){e(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){e(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:e}=this.root,{traces:a}=this._asyncAutoroutingResult.output_simple_route_json;if(a)for(let s of a){let l=e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:s.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;let{db:a}=this.root;for(let s of e)if(s.type==="pcb_trace"){if(s.subcircuit_id=this.subcircuit_id,s.connection_name){let l=s.connection_name;s.source_trace_id=l}a.pcb_trace.insert(s)}for(let s of e)if(s.type!=="pcb_via"&&s.type==="pcb_trace")for(let l of s.route)l.route_type==="via"&&a.pcb_via.insert({pcb_trace_id:s.pcb_trace_id,x:l.x,y:l.y,hole_diameter:.3,outer_diameter:.6,layers:[l.from_layer,l.to_layer],from_layer:l.from_layer,to_layer:l.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=s.schematic_group_id;for(let l of this.children)l.schematic_component_id&&e.schematic_component.update(l.schematic_component_id,{schematic_group_id:s.schematic_group_id})}_getSchematicLayoutMode(){let e=this._parsedProps;if(e.schLayout?.layoutMode==="none"||e.schLayout?.layoutMode==="relative")return"relative";if(e.schLayout?.matchAdapt)return"match-adapt";if(e.schLayout?.flex)return"flex";if(e.schLayout?.grid)return"grid";if(e.schMatchAdapt)return"match-adapt";if(e.schFlex)return"flex";if(e.schGrid)return"grid";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";if(e.relative||e.schRelative)return"relative";let a=this.children.some(l=>{let p=l._parsedProps;return p?.schX!==void 0||p?.schY!==void 0}),s=(e.manualEdits?.schematic_placements?.length??0)>0;return!a&&!s?"match-adapt":"relative"}doInitialSchematicLayout(){let e=this._getSchematicLayoutMode();e==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),e==="grid"&&this._doInitialSchematicLayoutGrid(),e==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){AVt(this)}_doInitialSchematicLayoutMatchpack(){SVt(this)}_doInitialSchematicLayoutGrid(){wVt(this)}_doInitialSchematicLayoutFlex(){TVt(this)}_getPcbLayoutMode(){let e=this._parsedProps;if(e.pcbRelative)return"none";if(e.pcbLayout?.matchAdapt)return"match-adapt";if(e.pcbLayout?.flex)return"flex";if(e.pcbLayout?.grid)return"grid";if(e.pcbLayout?.pack)return"pack";if(e.pcbFlex)return"flex";if(e.pcbGrid)return"grid";if(e.pcbPack||e.pack)return"pack";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";let a=e.pcbX!==void 0||e.pcbY!==void 0,s=(e.manualEdits?.pcb_placements?.length??0)>0;if(this.children.some(x=>{let f=x._parsedProps;return f?.pcbX!==void 0||f?.pcbY!==void 0}))return"none";let p=this.children.reduce((x,f)=>{let m=f._parsedProps,D=m?.pcbX!==void 0||m?.pcbY!==void 0;return x+(D?0:1)},0);return!a&&!s&&p>1?"pack":"none"}doInitialPcbLayout(){let e=this._getPcbLayoutMode();e==="grid"?this._doInitialPcbLayoutGrid():e==="pack"?this._doInitialPcbLayoutPack():e==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){PVt(this)}_doInitialPcbLayoutPack(){VVt(this)}_doInitialPcbLayoutFlex(){GVt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,a=this._parsedProps;if(!a.border)return;let s=typeof a.schWidth=="number"?a.schWidth:void 0,l=typeof a.schHeight=="number"?a.schHeight:void 0,p=typeof a.schPadding=="number"?a.schPadding:0,x=typeof a.schPaddingLeft=="number"?a.schPaddingLeft:p,f=typeof a.schPaddingRight=="number"?a.schPaddingRight:p,m=typeof a.schPaddingTop=="number"?a.schPaddingTop:p,D=typeof a.schPaddingBottom=="number"?a.schPaddingBottom:p,b=this.schematic_group_id?e.schematic_group.get(this.schematic_group_id):null;if(b&&(s===void 0&&typeof b.width=="number"&&(s=b.width),l===void 0&&typeof b.height=="number"&&(l=b.height)),s===void 0||l===void 0)return;let E=b?.center??this._getGlobalSchematicPositionBeforeLayout(),A=E.x-s/2-x,B=E.y-l/2-D,w=s+x+f,P=l+m+D;e.schematic_box.insert({width:w,height:P,x:A,y:B,is_dashed:a.border?.dashed??!1})}_determineSideFromPosition(e,a){if(!e.center||!a.center)return"left";let s=e.center.x-a.center.x,l=e.center.y-a.center.y;return Math.abs(s)>Math.abs(l)?s>0?"right":"left":l>0?"bottom":"top"}_calculateSchematicBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let a=1/0,s=-1/0,l=1/0,p=-1/0;for(let f of e)a=Math.min(a,f.centerX),s=Math.max(s,f.centerX),l=Math.min(l,f.centerY),p=Math.max(p,f.centerY);let x=2;return{minX:a-x,maxX:s+x,minY:l-x,maxY:p+x}}_getAutorouterConfig(){let e=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return qVt(e)}_getSubcircuitLayerCount(){let e=this.getInheritedProperty("layers");return typeof e=="number"?e:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(this.isSubcircuit){let a=new Map;for(let s of this.children)if(!s.isSubcircuit&&s._parsedProps.name){let l=a.get(s._parsedProps.name)||[];l.push(s),a.set(s._parsedProps.name,l)}for(let[s,l]of a.entries())l.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${s}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:l.map(p=>p.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:e}=this.root,a=e;for(let s of a.schematic_net_label.list()){let l=a.source_net.get(s.source_net_id),p=s.text||l?.name||"";if(s.anchor_side==="top"&&/^gnd/i.test(p)){a.schematic_net_label.update(s.schematic_net_label_id,{symbol_name:"ground_down"});continue}s.anchor_side==="bottom"&&/^v/i.test(p)&&a.schematic_net_label.update(s.schematic_net_label_id,{symbol_name:"vcc_up"})}}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(e){return super._repositionOnPcb(e)}},LBe=class extends zg{constructor(){super(...arguments);q(this,"pcb_board_id",null);q(this,"_drcChecksComplete",!1);q(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:FY}}get boardThickness(){let{_parsedProps:e}=this;return 1.4}get allLayers(){return(this._parsedProps.layers??2)===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db:e}=this.root,{_parsedProps:a}=this;if(a.width&&a.height)return;let s=1/0,l=1/0,p=-1/0,x=-1/0,f=PBe(e,this.subcircuit_id),m=new Set([this.subcircuit_id,...f]),D=e.pcb_component.list().filter(ee=>ee.subcircuit_id&&m.has(ee.subcircuit_id)),b=e.pcb_group.list().filter(ee=>ee.subcircuit_id&&m.has(ee.subcircuit_id)),E=!1,A=(ee,X,te)=>{X===0||te===0||(E=!0,s=Math.min(s,ee.x-X/2),l=Math.min(l,ee.y-te/2),p=Math.max(p,ee.x+X/2),x=Math.max(x,ee.y+te/2))};for(let ee of D)A(ee.center,ee.width,ee.height);for(let ee of b)A(ee.center,ee.width,ee.height);let B=2,w=E?p-s+B*2:0,P=E?x-l+B*2:0,N={x:E?(s+p)/2+(a.outlineOffsetX??0):a.outlineOffsetX??0,y:E?(l+x)/2+(a.outlineOffsetY??0):a.outlineOffsetY??0},O=a.width??w,$=a.height??P;e.pcb_board.update(this.pcb_board_id,{width:O,height:$,center:N})}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let e=this.root?.platform;if(!e?.printBoardInformationToSilkscreen)return;let a=this.root.db.pcb_board.get(this.pcb_board_id);if(!a)return;let s=[];if(e.projectName&&s.push(e.projectName),e.version&&s.push(`v${e.version}`),e.url&&s.push(e.url),s.length===0)return;let l=s.join(`
|
|
1039
1039
|
`),f={x:a.center.x+a.width/2-.25,y:a.center.y-a.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:l,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:f})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=a.width??0,l=a.height??0,p={x:(a.pcbX??0)+(a.outlineOffsetX??0),y:(a.pcbY??0)+(a.outlineOffsetY??0)};if(a.outline){let f=a.outline.map(B=>B.x),m=a.outline.map(B=>B.y),D=Math.min(...f),b=Math.max(...f),E=Math.min(...m),A=Math.max(...m);s=b-D,l=A-E,p={x:(D+b)/2+(a.outlineOffsetX??0),y:(E+A)/2+(a.outlineOffsetY??0)}}let x=e.pcb_board.insert({center:p,thickness:this.boardThickness,num_layers:this.allLayers.length,width:s,height:l,outline:a.outline?.map(f=>({x:f.x+(a.outlineOffsetX??0),y:f.y+(a.outlineOffsetY??0)})),material:a.material});this.pcb_board_id=x.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return _i()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let a=pSe(e.toArray());for(let l of a)e.pcb_trace_error.insert(l);let s=dSe(e.toArray());for(let l of s)e.pcb_port_not_connected_error.insert(l)}_emitRenderLifecycleEvent(e,a){super._emitRenderLifecycleEvent(e,a),a==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e})}},uGt=new Proxy({},{get:(n,e)=>e}),od=uGt,$Be=class extends Za{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:J_e,sourceFtype:od.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let e=this.props.capacitance,a=typeof e=="string"?e:`${js(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${a}/${js(this._parsedProps.maxVoltageRating)}V`:a}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new zc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new zc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,capacitance:a.capacitance,max_voltage_rating:a.maxVoltageRating,max_decoupling_trace_length:a.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!a.polarized});this.source_component_id=s.source_component_id}},HS=class extends Za{constructor(e){super(e);q(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:rg,shouldRenderAsSchematicBox:!0}}initPorts(e={}){super.initPorts(e);let{_parsedProps:a}=this;if(a.externallyConnectedPins){let s=new Set;for(let[l,p]of a.externallyConnectedPins)s.add(l),s.add(p);for(let l of s)if(!this.children.find(x=>x instanceof Ii&&x.isMatchingAnyOf([l]))){let x=l.match(/^pin(\d+)$/);if(x){let f=parseInt(x[1]);this.add(new Ii({pinNumber:f,aliases:[l]}))}else this.add(new Ii({name:l,aliases:[l]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:e}=this;e?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:e}=this;if(e.externallyConnectedPins)for(let[a,s]of e.externallyConnectedPins)this.add(new zc({from:`${this.getSubcircuitSelector()} > port.${a}`,to:`${this.getSubcircuitSelector()} > port.${s}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:e}=this.root,{pinAttributes:a}=this.props;if(!a)return;let s=null,l=null,p,x=this.selectAll("port");for(let E of x)for(let A of E.getNameAndAliases())if(a[A]){let B=a[A];B.providesPower&&(s=E,p=B.providesVoltage),B.providesGround&&(l=E)}if(!s||!l||p===void 0)return;let f=e.source_port.get(s.source_port_id);if(!f?.subcircuit_connectivity_map_key)return;let m=e.source_port.get(l.source_port_id);if(!m?.subcircuit_connectivity_map_key)return;let D=e.source_net.getWhere({subcircuit_connectivity_map_key:f.subcircuit_connectivity_map_key}),b=e.source_net.getWhere({subcircuit_connectivity_map_key:m.subcircuit_connectivity_map_key});!D||!b||e.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:s.source_port_id,positive_source_net_id:D.source_net_id,negative_source_port_id:l.source_port_id,negative_source_net_id:b.source_net_id,voltage:p})}},zBe=class extends HS{constructor(n){super(n)}get config(){return{...super.config,componentName:"Pinout",zodProps:q_e}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=a.source_component_id}},qBe=class extends Za{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"anode",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"cathode",this.portMap.pin2)}get config(){let e={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},a=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:a?e[a]:this.props.symbolName??"diode",componentName:"Diode",zodProps:pAe,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},UBe=class extends Za{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:V_e,sourceFtype:od.simple_fuse}}_getSchematicSymbolDisplayValue(){let n=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,a=typeof n=="string"?parseFloat(n):n,s=typeof e=="string"?parseFloat(e):e;return`${js(a)}A / ${js(s)}V`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=typeof e.currentRating=="string"?parseFloat(e.currentRating):e.currentRating,s=typeof e.voltageRating=="string"?parseFloat(e.voltageRating):e.voltageRating,l=n.source_component.insert({name:this.name,ftype:od.simple_fuse,current_rating_amps:a,voltage_rating_volts:s,display_current_rating:`${js(a)}A`,display_voltage_rating:`${js(s)}V`});this.source_component_id=l.source_component_id}},VBe=class extends Za{constructor(){super(...arguments);q(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:vY,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let a=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),s=this._parsedProps.schDirection??"right";return{leftSize:s==="left"?a:0,rightSize:s==="right"?a:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,a=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),s={};for(let x=0;x<a.length;x++){let f=a[x],m=e.source_port.get(f.source_port_id),D="";if(typeof m?.pin_number=="number")D=m.pin_number.toString();else if(Array.isArray(m?.port_hints)){let b=m.port_hints.find(E=>/^(pin)?\d+$/.test(E));b&&(/^pin\d+$/.test(b)?D=b.replace(/^pin/,""):D=b)}s[D]=f.pcb_port_id}let l=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),p=x=>{if(x&&typeof x=="string"&&x.startsWith("{PIN")){let f=x.replace("{PIN","").replace("}","");return s[f]||x}return x};for(let x of l)if(x.route)for(let f of x.route)f.route_type==="wire"&&(f.start_pcb_port_id=p(f.start_pcb_port_id),f.end_pcb_port_id=p(f.end_pcb_port_id))}},GBe=class extends Za{constructor(){super(...arguments);q(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(e){return this.selectOne(`port.${e}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let e=this.children.filter(a=>a.componentName==="Port").map(a=>a.name);return e.length>0?[e]:[]}return this._parsedProps.bridgedPins??[]}get config(){let e=this._parsedProps??this.props,a=e.pinCount;if(e.pinCount==null&&!e.footprint&&(a=2),e.pinCount==null){let p=(e.bridgedPins??[]).flat().map(D=>this._getPinNumberFromBridgedPinName(D)).filter(D=>D!==null),x=p.length>0?Math.max(...p):0,f=e.pinLabels?Object.keys(e.pinLabels).length:0,m=Math.max(x,f);(m===2||m===3)&&(a=m),a==null&&e.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(a=this.getPortsFromFootprint().length)}let s="";a?s+=`solderjumper${a}`:s="solderjumper";let l=[];return Array.isArray(e.bridgedPins)&&e.bridgedPins.length>0?l=Array.from(new Set(e.bridgedPins.flat().map(p=>this._getPinNumberFromBridgedPinName(p)).filter(p=>p!==null))).sort((p,x)=>p-x):e.bridged&&a&&(l=Array.from({length:a},(p,x)=>x+1)),l.length>0&&(s+=`_bridged${l.join("")}`),{schematicSymbolName:e.symbolName??s,componentName:"SolderJumper",zodProps:U_e,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let a=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);a==null&&!this._parsedProps.footprint&&(a=2);let s=this._parsedProps.schDirection??"right";return{leftSize:s==="left"?a:0,rightSize:s==="right"?a:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,a=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),s={};for(let x=0;x<a.length;x++){let f=a[x],m=e.source_port.get(f.source_port_id),D="";if(typeof m?.pin_number=="number")D=m.pin_number.toString();else if(Array.isArray(m?.port_hints)){let b=m.port_hints.find(E=>/^(pin)?\d+$/.test(E));b&&(/^pin\d+$/.test(b)?D=b.replace(/^pin/,""):D=b)}s[D]=f.pcb_port_id}let l=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),p=x=>{if(x&&typeof x=="string"&&x.startsWith("{PIN")){let f=x.replace("{PIN","").replace("}","");return s[f]||x}return x};for(let x of l)if(x.route)for(let f of x.route)f.route_type==="wire"&&(f.start_pcb_port_id=p(f.start_pcb_port_id),f.end_pcb_port_id=p(f.end_pcb_port_id))}},XBe=class extends Za{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"anode",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"cathode",this.portMap.pin2)}get config(){let e={laser:"laser_diode"},a=this.props.laser?"laser":null;return{schematicSymbolName:a?e[a]:this.props.symbolName??"led",componentName:"Led",zodProps:fAe,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_led",name:this.name,wave_length:a.wavelength,color:a.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},YBe=class extends Za{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"positive",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:vAe,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Ii({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Ii({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:a.voltage,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},cGt=fs.extend({voltage:zs.optional(),frequency:Nc.optional(),peakToPeakVoltage:zs.optional(),waveShape:C.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Ba.optional(),dutyCycle:C.number().optional()}),HBe=class extends Za{constructor(){super(...arguments);q(this,"terminal1",this.portMap.terminal1);q(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:cGt,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(e){if(!e.startsWith("Pcb"))for(let a of this.children)a.runRenderPhaseForChildren(e),a.runRenderPhase(e)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:a.voltage,frequency:a.frequency,peak_to_peak_voltage:a.peakToPeakVoltage,wave_shape:a.waveShape,phase:a.phase,duty_cycle:a.dutyCycle,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialSimulationRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.portMap.terminal1,l=this.portMap.terminal2;e.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:s.source_port_id,terminal2_source_port_id:l.source_port_id,voltage:a.voltage,frequency:a.frequency,peak_to_peak_voltage:a.peakToPeakVoltage,wave_shape:a.waveShape,phase:a.phase,duty_cycle:a.dutyCycle})}},WBe=class extends Za{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:X_e,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${js(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new zc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new zc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new zc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new zc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,resistance:a.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}},lGt=["leftedge","rightedge","topedge","bottomedge","center"],KBe=class extends ma{get config(){return{componentName:"Constraint",zodProps:Q_e}}constructor(n){if(super(n),("xdist"in n||"ydist"in n)&&!("edgeToEdge"in n)&&!("centerToCenter"in n))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in n&&n.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let n=[],e=this.getPrimitiveContainer();function a(s){let l=s.split(" ").pop(),p=lGt.includes(l)?l:void 0,x=p?s.replace(` ${p}`,""):s,f=e.selectOne(x,{pcbPrimitive:!0});f&&n.push({selector:s,component:f,componentSelector:x,edge:p})}for(let s of["left","right","top","bottom"])s in this._parsedProps&&a(this._parsedProps[s]);if("for"in this._parsedProps)for(let s of this._parsedProps.for)a(s);return{componentsWithSelectors:n}}},JBe=class extends ma{constructor(){super(...arguments);q(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:DAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,a=this.getSubcircuit(),{_parsedProps:s}=this,l=s.layer??"top";if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenPath. Must be "top" or "bottom".`);let p=this._computePcbGlobalTransformBeforeLayout(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_fabrication_note_path.insert({pcb_component_id:x,layer:l,color:s.color,route:s.route.map(m=>{let D=rs(p,{x:m.x,y:m.y});return{...m,x:D.x,y:D.y}}),stroke_width:s.strokeWidth??.1,subcircuit_id:a?.subcircuit_id??void 0});this.fabrication_note_path_id=f.pcb_fabrication_note_path_id}},ZBe=class extends ma{get config(){return{componentName:"FabricationNoteText",zodProps:gAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:n}=this.root,{_parsedProps:e}=this,a=this.getPrimitiveContainer(),s=this.getSubcircuit();n.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:e.pcbX??0,y:e.pcbY??0},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:e.text??"",pcb_component_id:a.pcb_component_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},QBe=class extends zg{constructor(n){super({...n,subcircuit:!0})}},e9e=class extends zg{constructor(n){super({...n,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:n}=this.root,e=this._parsedProps;if(!this.pcb_group_id)return;let a=n.pcb_group.get(this.pcb_group_id),s=e.paddingLeft??e.padding??0,l=e.paddingRight??e.padding??0,p=e.paddingTop??e.padding??0,x=e.paddingBottom??e.padding??0;n.pcb_group.update(this.pcb_group_id,{width:a.width+s+l,height:a.height+p+x,center:{x:a.center.x+(l-s)/2,y:a.center.y+(p-x)/2}})}},t9e=class extends ma{constructor(){super(...arguments);q(this,"pcb_breakout_point_id",null);q(this,"matchedPort",null);q(this,"matchedNet",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:FAe}}_matchConnection(){let{connection:e}=this._parsedProps,a=this.getSubcircuit();a&&(this.matchedPort=a.selectOne(e,{type:"port"}),this.matchedPort||(this.matchedNet=a.selectOne(e,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${e}"`))}_getSourceTraceIdForPort(e){let{db:a}=this.root;return a.source_trace.list().find(l=>l.connected_source_port_ids.includes(e.source_port_id))?.source_trace_id}_getSourceNetIdForPort(e){let{db:a}=this.root;return a.source_trace.list().find(l=>l.connected_source_port_ids.includes(e.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;this._matchConnection();let{pcbX:a=0,pcbY:s=0}=this._parsedProps,l=this.parent?.getGroup(),p=this.getSubcircuit();if(!l||!l.pcb_group_id)return;let x=e.pcb_breakout_point.insert({pcb_group_id:l.pcb_group_id,subcircuit_id:p?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:a,y:s});this.pcb_breakout_point_id=x.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:e=0,pcbY:a=0}=this._parsedProps;return{center:{x:e,y:a},bounds:{left:e,top:a,right:e,bottom:a},width:0,height:0}}_setPositionFromLayout(e){let{db:a}=this.root;this.pcb_breakout_point_id&&a.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:e.x,y:e.y})}getPcbSize(){return{width:0,height:0}}},r9e=class extends ma{constructor(){super(...arguments);q(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:oAe}}_getAnchorSide(){let{_parsedProps:e}=this;if(e.anchorSide)return e.anchorSide;if(!this._resolveConnectsTo())return"right";let s=this._getGlobalSchematicPositionBeforeLayout(),l=this._getConnectedPorts();if(l.length===0)return"right";let p=l[0]._getGlobalSchematicPositionBeforeLayout(),x=p.x-s.x,f=p.y-s.y;if(Math.abs(x)>Math.abs(f)){if(x>0)return"right";if(x<0)return"left"}else{if(f>0)return"top";if(f<0)return"bottom"}return"right"}_getConnectedPorts(){let e=this._resolveConnectsTo();if(!e)return[];let a=[];for(let s of e){let l=this.getSubcircuit().selectOne(s);l&&a.push(l)}return a}computeSchematicPropsTransform(){let{_parsedProps:e}=this;if(e.schX===void 0&&e.schY===void 0){let a=this._getConnectedPorts();if(a.length>0){let s=a[0]._getGlobalSchematicPositionBeforeLayout(),l=rs(this.parent?.computeSchematicGlobalTransform?.()??_i(),{x:0,y:0});return ka(s.x-l.x,s.y-l.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalSchematicPositionBeforeLayout(),l=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),p=a.anchorSide??"right",x=Qp({anchor_position:s,anchor_side:p,text:a.net}),f=e.schematic_net_label.insert({text:a.net,source_net_id:l.source_net_id,anchor_position:s,center:x,anchor_side:this._getAnchorSide()});this.source_net_label_id=f.source_net_id}_resolveConnectsTo(){let{_parsedProps:e}=this,a=e.connectsTo??e.connection;if(Array.isArray(a))return a;if(typeof a=="string")return[a]}_getNetName(){let{_parsedProps:e}=this;return e.net}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;e.net&&ZW(this,[`net.${e.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let e=this._resolveConnectsTo();if(e)for(let a of e)this.add(new zc({from:a,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:e}=this.root,a=this._resolveConnectsTo();if(!a||a.length===0)return;let s=this._getGlobalSchematicPositionBeforeLayout(),l=this._getAnchorSide(),x={left:"x-",right:"x+",top:"y+",bottom:"y-"}[l],f=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let m of a){let D=this.getSubcircuit().selectOne(m,{type:"port"});if(!D||!D.schematic_port_id)continue;let b=!1;if(f?.source_net_id){let O=e.source_trace.list().find($=>$.connected_source_net_ids?.includes(f.source_net_id)&&$.connected_source_port_ids?.includes(D.source_port_id??""));if(O&&(b=e.schematic_trace.list().some($=>$.source_trace_id===O.source_trace_id)),b)continue}let E=D._getGlobalSchematicPositionAfterLayout(),A=VW(D.facingDirection??"right")??"x+",B=sg({x:E.x,y:E.y,facingDirection:A},{x:s.x,y:s.y,facingDirection:x});if(!Array.isArray(B)||B.length<2)continue;let w=[];for(let O=0;O<B.length-1;O++)w.push({from:{x:B[O].x,y:B[O].y},to:{x:B[O+1].x,y:B[O+1].y}});let P,N;if(f?.source_net_id&&D.source_port_id){let O=e.source_trace.list().find($=>$.connected_source_net_ids?.includes(f.source_net_id)&&$.connected_source_port_ids?.includes(D.source_port_id));P=O?.source_trace_id,N=O?.subcircuit_connectivity_map_key||e.source_net.get(f.source_net_id)?.subcircuit_connectivity_map_key}e.schematic_trace.insert({source_trace_id:P,edges:w,junctions:[],subcircuit_connectivity_map_key:N}),e.schematic_port.update(D.schematic_port_id,{is_connected:!0})}}},n9e=class extends ma{constructor(){super(...arguments);q(this,"pcb_silkscreen_circle_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:IAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenCircle. Must be "top" or "bottom".`);let p=this._computePcbGlobalTransformBeforeLayout(),x=this.getSubcircuit(),f=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=e.pcb_silkscreen_circle.insert({pcb_component_id:f,layer:l,center:{x:a.pcbX??0,y:a.pcbY??0},radius:a.radius,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:a.strokeWidth??.1});this.pcb_silkscreen_circle_id=m.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:e}=this,a=e.radius*2;return{width:a,height:a}}},a9e=class extends ma{constructor(){super(...arguments);q(this,"pcb_silkscreen_rect_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:PAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenRect. Must be "top" or "bottom".`);let p=this.getSubcircuit(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_silkscreen_rect.insert({pcb_component_id:x,layer:l,center:{x:a.pcbX??0,y:a.pcbY??0},width:a.width,height:a.height,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:a.strokeWidth??.1});this.pcb_silkscreen_rect_id=f.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},s9e=class extends ma{constructor(){super(...arguments);q(this,"pcb_silkscreen_line_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:TAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenLine. Must be "top" or "bottom".`);let p=this.getSubcircuit(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_silkscreen_line.insert({pcb_component_id:x,layer:l,x1:a.x1,y1:a.y1,x2:a.x2,y2:a.y2,stroke_width:a.strokeWidth??.1,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:p?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=f.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:e}=this,a=Math.abs(e.x2-e.x1),s=Math.abs(e.y2-e.y1);return{width:a,height:s}}},i9e=class extends ma{constructor(e){super(e);q(this,"pcb_via_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0);q(this,"source_manually_placed_via_id",null);let a=this._getLayers();this._parsedProps.layers=a,this.initPorts()}get config(){return{componentName:"Via",zodProps:yAe}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:e}=this;return{width:e.outerDiameter,height:e.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_via.get(this.pcb_via_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y-s.height/2,right:a.x+s.width/2,bottom:a.y+s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}_getLayers(){let{fromLayer:e="top",toLayer:a="bottom"}=this._parsedProps;return e===a?[e]:[e,a]}initPorts(){let e=this._parsedProps.layers;for(let s of e){let l=new Ii({name:s,layer:s});l.registerMatch(this),this.add(l)}let a=new Ii({name:"pin1"});a.registerMatch(this),this.add(a)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.getSubcircuit(),p=e.pcb_component.insert({center:s,width:a.outerDiameter,height:a.outerDiameter,layer:a.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:l?.subcircuit_id??void 0});this.pcb_component_id=p.pcb_component_id}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getGroup(),l=this.getSubcircuit(),p=e.source_manually_placed_via.insert({source_group_id:s?.source_group_id,source_net_id:a.net??"",subcircuit_id:l?.subcircuit_id??void 0});this.source_component_id=p.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.getSubcircuit(),p=e.pcb_via.insert({x:s.x,y:s.y,hole_diameter:a.holeDiameter,outer_diameter:a.outerDiameter,layers:["bottom","top"],from_layer:a.fromLayer||"bottom",to_layer:a.toLayer||"top",subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=p.pcb_via_id}},o9e=class extends Za{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:sAe,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=a.source_component_id}},u9e=class extends Za{get config(){return{componentName:"PinHeader",zodProps:iAe,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),e=this._parsedProps.holeDiameter,a=this._parsedProps.platedDiameter,s=this._parsedProps.pitch,l=this._parsedProps.showSilkscreenPinLabels;if(n>0){let p;if(s)!e&&!a?p=`pinrow${n}_p${s}`:p=`pinrow${n}_p${s}_id${e}_od${a}`;else if(!e&&!a)p=`pinrow${n}`;else return null;return l!==!0&&(p+="_nopinlabels"),p}return null}initPorts(){let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let e=1;e<=n;e++){let a=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[e-1]:this._parsedProps.pinLabels?.[`pin${e}`];if(a){let s=Array.isArray(a)?a[0]:a,l=Array.isArray(a)?a.slice(1):[];this.add(new Ii({pinNumber:e,name:s,aliases:[`pin${e}`,...l]}))}else this.add(new Ii({pinNumber:e,name:`pin${e}`}))}}_getSchematicPortArrangement(){let n=this._parsedProps.pinCount??1,e=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",a=this._parsedProps.schPinArrangement;return e==="left"?{leftSide:{direction:a?.leftSide?.direction??"top-to-bottom",pins:a?.leftSide?.pins??Array.from({length:n},(s,l)=>`pin${l+1}`)}}:{rightSide:{direction:a?.rightSide?.direction??"top-to-bottom",pins:a?.rightSide?.pins??Array.from({length:n},(s,l)=>`pin${l+1}`)}}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender,are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}};function dGt(n){switch(n){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var c9e=class extends Za{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??dGt(this.props.pinVariant),zodProps:K_e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=e.pinVariant||"no_ground",s=n.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:a,are_pins_interchangeable:a==="no_ground"||a==="ground_pin"});this.source_component_id=s.source_component_id}_getSchematicSymbolDisplayValue(){let n=`${js(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${js(this._parsedProps.loadCapacitance)}F`:n}},l9e=class extends Za{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:dAe,sourceFtype:od.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${js(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({name:this.name,ftype:od.simple_inductor,inductance:a.inductance,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}};function pGt(n){switch(n){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var d9e=class extends Za{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??pGt(this.props.pinVariant),zodProps:H_e,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${js(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=e.pinVariant||"two_pin",s=n.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:e.maxResistance,pin_variant:a,are_pins_interchangeable:a==="two_pin"});this.source_component_id=s.source_component_id}},p9e=class extends Za{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:uAe,sourceFtype:od.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let n=Ps[this._getSchematicSymbolNameOrThrow()],e=n.ports.find(D=>D.labels.includes("1")),a=n.ports.find(D=>D.labels.includes("2")),s=this.selectAll("port"),l=s.find(D=>D.props.pinNumber===1),p=s.find(D=>D.props.pinNumber===2),x=s.find(D=>D.props.pinNumber===3),f=s.find(D=>D.props.pinNumber===4),{internallyConnectedPins:m}=this._parsedProps;l.schematicSymbolPortDef=e,(!m||m.length===0)&&(p.schematicSymbolPortDef=a);for(let[D,b]of[[2,p],[3,x],[4,f]]){let E=m?.find(([B,w])=>B===`pin${D}`||w===`pin${D}`);if(!E){b.schematicSymbolPortDef=a;break}(E?.[0]===`pin${D}`?E[1]:E?.[0])!=="pin1"&&(b.schematicSymbolPortDef=a)}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({name:this.name,ftype:od.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}},x9e=class extends Za{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:W_e,sourceFtype:"simple_crystal"}}initPorts(){let n=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:n})}_getSchematicSymbolDisplayValue(){let n=`${js(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${js(this._parsedProps.loadCapacitance)}F`:n}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin",are_pins_interchangeable:(e.pinVariant||"two_pin")==="two_pin"});this.source_component_id=a.source_component_id}},f9e=class extends Za{constructor(){super(...arguments);q(this,"emitter",this.portMap.pin1);q(this,"collector",this.portMap.pin2);q(this,"base",this.portMap.pin3)}get config(){let e=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??e,zodProps:cAe,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let e={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:e})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:a.type});this.source_component_id=s.source_component_id}},h9e=class extends Za{get config(){let n=this.props.mosfetMode==="depletion"?"d":"e",a=`${this.props.channelType}_channel_${n}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??a,zodProps:lAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=a.source_component_id}},m9e=class extends Za{_getSwitchType(){let{spst:n,spdt:e,dpst:a,dpdt:s,type:l}=this._parsedProps??{};return s?"dpdt":n?"spst":e?"spdt":a?"dpst":l??"spst"}get config(){let n=this._getSwitchType(),{isNormallyClosed:e}=this._parsedProps??{},s={spst:e?"spst_normally_closed_switch":"spst_switch",spdt:e?"spdt_normally_closed_switch":"spdt_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"}[n]??"spst_switch";return{componentName:"Switch",schematicSymbolName:this.props.symbolName??s,zodProps:mAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,a=n.source_component.insert({ftype:"simple_switch",name:this.name,switch_type:e.type,is_normally_closed:e.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=a.source_component_id}},$W={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},g9e=class extends Za{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:bAe,sourceFtype:od.simple_test_point}}_getPropsWithDefaults(){let{padShape:n,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:p}=this._parsedProps;return!a&&e&&(a="through_hole"),a??(a="through_hole"),n??(n="circle"),a==="pad"?n==="circle"?s??(s=$W.SMT_CIRCLE_DIAMETER):n==="rect"&&(l??(l=$W.SMT_RECT_SIZE),p??(p=l)):a==="through_hole"&&(e??(e=$W.HOLE_DIAMETER)),{padShape:n,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:p}}_getImpliedFootprintString(){let{padShape:n,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:p}=this._getPropsWithDefaults();if(a==="through_hole")return`platedhole_d${e}`;if(a==="pad"){if(n==="circle")return`smtpad_circle_d${s}`;if(n==="rect")return`smtpad_rect_w${l}_h${p}`}throw new Error(`Footprint variant "${a}" with pad shape "${n}" not implemented`)}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,{padShape:a,holeDiameter:s,footprintVariant:l,padDiameter:p,width:x,height:f}=this._getPropsWithDefaults(),m=n.source_component.insert({ftype:od.simple_test_point,name:this.name,supplier_part_numbers:e.supplierPartNumbers,footprint_variant:l,pad_shape:a,pad_diameter:p,hole_diameter:s,width:x,height:f,are_pins_interchangeable:!0});this.source_component_id=m.source_component_id}},D9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:_Ae}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalSchematicPositionBeforeLayout();e.schematic_text.insert({anchor:a.anchor??"center",text:a.text,font_size:a.fontSize,color:a.color||"#000000",position:{x:s.x,y:s.y},rotation:a.schRotation??0})}};function xGt({anchor:n,x:e,y:a,width:s,height:l,isInside:p}){switch(n){case"top_left":return{x:e,y:a+l,textAnchor:p?"top_left":"bottom_left"};case"top_center":return{x:e+s/2,y:a+l,textAnchor:p?"top_center":"bottom_center"};case"top_right":return{x:e+s,y:a+l,textAnchor:p?"top_right":"bottom_right"};case"center_left":return{x:e,y:a+l/2,textAnchor:p?"center_left":"center_right"};case"center":return{x:e+s/2,y:a+l/2,textAnchor:"center"};case"center_right":return{x:e+s,y:a+l/2,textAnchor:p?"center_right":"center_left"};case"bottom_left":return{x:e,y:a,textAnchor:p?"bottom_left":"top_left"};case"bottom_center":return{x:e+s/2,y:a,textAnchor:p?"bottom_center":"top_center"};case"bottom_right":return{x:e+s,y:a,textAnchor:p?"bottom_right":"top_right"};default:return{x:e+s/2,y:a+l,textAnchor:"center"}}}var y9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:CAe,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=.6,l=typeof a.padding=="number"?a.padding:0,p=typeof a.paddingTop=="number"?a.paddingTop:l,x=typeof a.paddingBottom=="number"?a.paddingBottom:l,f=typeof a.paddingLeft=="number"?a.paddingLeft:l,m=typeof a.paddingRight=="number"?a.paddingRight:l,D=a.overlay&&a.overlay.length>0,b=typeof a.width=="number"&&typeof a.height=="number",E,A,B,w,P,N;if(D){let $=a.overlay.map(it=>({selector:it,port:this.getSubcircuit().selectOne(it,{type:"port"})})).filter(({port:it})=>it!=null).map(({port:it})=>({position:it._getGlobalSchematicPositionAfterLayout()}));if($.length===0)return;let ee=$.map(it=>it.position.x),X=$.map(it=>it.position.y),te=Math.min(...ee),L=Math.max(...ee),K=Math.min(...X),U=Math.max(...X),J=L-te,Q=U-K,de=J===0?s:0,ce=Q===0?s:0,Te=f+de/2,Ne=m+de/2,Ve=p+ce/2,et=x+ce/2,ct=te-Te,Mt=L+Ne,Dt=K-et,ot=U+Ve;E=Mt-ct,A=ot-Dt,B=ct+(a.schX??0),w=Dt+(a.schY??0),P=B+E/2,N=w+A/2}else if(b){E=a.width,A=a.height;let O=this._getGlobalSchematicPositionBeforeLayout();P=O.x,N=O.y,B=P-E/2,w=N-A/2}else return;if(e.schematic_box.insert({height:A,width:E,x:B,y:w,is_dashed:a.strokeStyle==="dashed"}),a.title){let O=a.titleInside,$=.1,ee=a.titleAlignment,X=xGt({anchor:ee,x:B,y:w,width:E,height:A,isInside:O}),te,L,K=X.textAnchor;O?(te=ee.includes("top")?-$:ee.includes("bottom")?$:0,L=ee.includes("left")?$:ee.includes("right")?-$:0):(te=ee.includes("top")?$:ee.includes("bottom")?-$:0,L=ee.includes("center_left")?-$:ee.includes("center_right")?$:0);let U=X.x+L,J=X.y+te;e.schematic_text.insert({anchor:K,text:a.title,font_size:a.titleFontSize??.18,color:a.titleColor??"#000000",position:{x:U,y:J},rotation:0})}}},b9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0);q(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:AAe}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.children.filter(A=>A.componentName==="SchematicRow");if(s.length===0)return;let l=[],p=0;for(let A of s){let B=A.children.filter(w=>w.componentName==="SchematicCell");p=Math.max(p,B.length)}for(let A=0;A<s.length;A++)l[A]=[];for(let A=0;A<s.length;A++){let w=s[A].children.filter(N=>N.componentName==="SchematicCell"),P=0;for(let N=0;N<w.length;N++){for(;l[A][P];)P++;let O=w[N],$=O._parsedProps.colSpan??1,ee=O._parsedProps.rowSpan??1;for(let X=0;X<ee;X++)for(let te=0;te<$;te++)l[A+X]||(l[A+X]=[]),l[A+X][P+te]=O;P+=$}}p=Math.max(0,...l.map(A=>A.length));let x=s.map((A,B)=>A._parsedProps.height??1),f=Array.from({length:p},(A,B)=>{let w=0;for(let P=0;P<s.length;P++){let N=l[P]?.[B];if(N){let O=N._parsedProps.text??N._parsedProps.children,$=N._parsedProps.width??(O?.length??2)*.5;$>w&&(w=$)}}return w||10}),m=this._getGlobalSchematicPositionBeforeLayout(),D=e.schematic_table.insert({anchor_position:m,column_widths:f,row_heights:x,cell_padding:a.cellPadding,border_width:a.borderWidth,anchor:a.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=D.schematic_table_id;let b=new Set,E=0;for(let A=0;A<s.length;A++){let B=0;for(let w=0;w<p;w++){let P=l[A]?.[w];if(P&&!b.has(P)){b.add(P);let N=P._parsedProps,O=N.rowSpan??1,$=N.colSpan??1,ee=0;for(let te=0;te<$;te++)ee+=f[w+te];let X=0;for(let te=0;te<O;te++)X+=x[A+te];e.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:A,end_row_index:A+O-1,start_column_index:w,end_column_index:w+$-1,text:N.text??N.children,center:{x:m.x+B+ee/2,y:m.y-E-X/2},width:ee,height:X,horizontal_align:N.horizontalAlign,vertical_align:N.verticalAlign,font_size:N.fontSize??a.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}f[w]&&(B+=f[w])}E+=x[A]}}},F9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:RAe}}},E9e=class extends ma{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0);q(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:SAe}}},fGt={name:"@tscircuit/core",type:"module",version:"0.0.705",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"'},devDependencies:{"@biomejs/biome":"^1.8.3","@tscircuit/capacity-autorouter":"^0.0.107","@tscircuit/checks":"^0.0.71","@tscircuit/circuit-json-util":"^0.0.67","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.21","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.305","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.35","@tscircuit/simple-3d-svg":"^0.0.38","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.245","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-simple-3d":"^0.0.6","circuit-to-svg":"^0.0.185",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.195","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.33","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},qg=class{constructor({platform:n,projectUrl:e}={}){q(this,"firstChild",null);q(this,"children");q(this,"db");q(this,"root",null);q(this,"isRoot",!0);q(this,"schematicDisabled",!1);q(this,"pcbDisabled",!1);q(this,"pcbRoutingDisabled",!1);q(this,"_featureMspSchematicTraceRouting",!0);q(this,"name");q(this,"platform");q(this,"projectUrl");q(this,"_hasRenderedAtleastOnce",!1);q(this,"_eventListeners",{});this.children=[],this.db=ia([]),this.root=this,this.platform=n,this.projectUrl=e,this.pcbDisabled=n?.pcbDisabled??!1}add(n){let e;(0,v9e.isValidElement)(n)?e=EBe(n):e=n,this.children.push(e)}_getBoard(){return this.children.find(n=>n.componentName==="Board")}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let n=new zg({subcircuit:!0});n.parent=this,n.addAll(this.children),this.children=[n],this.firstChild=n}render(){this.firstChild||this._guessRootComponent();let{firstChild:n,db:e}=this;if(!n)throw new Error("RootCircuit has no root component");n.parent=this,n.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(e=>setTimeout(e,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(n=>n._hasIncompleteAsyncEffects()?!0:n.children.some(e=>e._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(n){let e=await Promise.resolve().then(()=>(WSe(),HSe)).catch(a=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
|
|
1040
1040
|
|
|
1041
|
-
"${a.message}"`)});if(n.view==="pcb")return e.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(n.view==="schematic")return e.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${n.view}`)}getCoreVersion(){let[n,e,a]=fGt.version.split(".").map(Number);return`${n}.${e}.${a+1}`}async preview(n){let e=typeof n=="object"?n:{previewName:n};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return _i()}_computePcbGlobalTransformBeforeLayout(){return _i()}selectAll(n){return this._guessRootComponent(),this.firstChild?.selectAll(n)??[]}selectOne(n,e){return this._guessRootComponent(),this.firstChild?.selectOne(n,e)??null}emit(n,...e){if(this._eventListeners[n])for(let a of this._eventListeners[n])a(...e)}on(n,e){this._eventListeners[n]||(this._eventListeners[n]=[]),this._eventListeners[n].push(e)}removeListener(n,e){this._eventListeners[n]&&(this._eventListeners[n]=this._eventListeners[n].filter(a=>a!==e))}enableDebug(n){typeof n=="string"?HW.default.enable(n):(n===null||n===!1)&&HW.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},hGt=qg,mGt=qg,gGt=n=>{let[e,a]=Lg.default.useState(!0),[s,l]=Lg.default.useState(null),[p,x]=Lg.default.useState(),[f,m]=Lg.default.useState();return Lg.default.useEffect(()=>{a(!0),l(null),n&&setTimeout(()=>{try{let D=new qg;D.add(n),x(D),m(D.toJson())}catch(D){l(D)}a(!1)},1)},[n]),{isLoading:e,error:s,circuit:p,circuitJson:f}},Ug=(n,e)=>(a,s)=>{let l=[];Array.isArray(e)?l.push(...e.flat()):typeof e=="object"&&l.push(...Object.values(e).flat(),...Object.keys(e));let p=x=>{if(x?.name&&x.name!==a)throw new Error(`Component name mismatch. Hook name: ${a}, Component prop name: ${x.name}`);let f={...s,...x,name:a},m=[];for(let D of l)if(f[D]){let b=`.${a} > .${D}`,E=f[D];m.push({from:b,to:E}),delete f[D]}return(0,A1.jsxs)(A1.Fragment,{children:[(0,A1.jsx)(n,{...f}),m.map((D,b)=>(0,A1.jsx)("trace",{...D},b))]})};for(let x of l)p[x]=`.${a} > .${x}`;return p},DGt=Ug(n=>(0,C9e.jsx)("capacitor",{...n}),Z_e),yGt=n=>Ug(e=>(0,_9e.jsx)("chip",{pinLabels:n,...e}),n),bGt=Ug(n=>(0,A9e.jsx)("diode",{...n}),xAe),FGt=Ug(n=>(0,R9e.jsx)("led",{...n}),hAe),EGt=Ug(n=>(0,S9e.jsx)("resistor",{...n}),Y_e),vGt=new Proxy(n=>new Proxy({},{get:(e,a)=>`.${n} > .${a}`}),{get:(n,e)=>{let a=(...s)=>{let l=s[0];return new Proxy({},{get:(p,x)=>`.${e} > .${x}`})};return new Proxy(a,{get:(s,l)=>e==="net"?`net.${l}`:e==="subcircuit"?new Proxy({},{get:(p,x)=>new Proxy({},{get:(f,m)=>`subcircuit.${l} > .${x} > .${m}`})}):`.${e} > .${l}`,apply:(s,l,p)=>e==="net"?new Proxy({},{get:(x,f)=>`net.${f}`}):new Proxy({},{get:(x,f)=>{let m=`.${e} > .${f}`;return["U","J","CN"].some(b=>e.startsWith(b))?m:new Proxy(new String(m),{get:(b,E)=>typeof E=="symbol"||E==="toString"?()=>m:`.${e} > .${f} > .${E}`})}})})}});FBe(gBe);FBe({Bug:HS});var P9e=qr(Ic(),1);var sK=new Map,Eo=async(n,e)=>{let a=new URLSearchParams({...e,json:"true"}).toString();if(sK.has(a))return sK.get(a);let l=await(await fetch(`https://jlcsearch.tscircuit.com/${n}/list?${a}`)).json();return sK.set(a,l),l},w9e={findPart:async({sourceComponent:n,footprinterString:e})=>{if(n.type==="source_component"&&n.ftype==="simple_resistor"){let{resistors:a}=await Eo("resistors",{resistance:n.display_resistance??n.resistance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_capacitor"){e?.includes("cap")&&(e=e.replace("cap",""));let{capacitors:a}=await Eo("capacitors",{capacitance:n.display_capacitance??n.capacitance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_pin_header"){let a;e?.includes("_p")&&(a=Number(e.split("_p")[1]));let{headers:s}=await Eo("headers",a?{pitch:a,num_pins:n.pin_count,gender:n.gender}:{num_pins:n.pin_count,gender:n.gender});return{jlcpcb:(s??[]).map(l=>`C${l.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_potentiometer"){let{potentiometers:a}=await Eo("potentiometers",{resistance:n.max_resistance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_diode"){let{diodes:a}=await Eo("diodes",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_chip"){let{chips:a}=await Eo("chips",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_transistor"){let{transistors:a}=await Eo("transistors",{package:e,transistor_type:n.transistor_type});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_power_source"){let{power_sources:a}=await Eo("power_sources",{voltage:n.voltage,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_inductor"){let{inductors:a}=await Eo("inductors",{inductance:n.inductance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_crystal"){let{crystals:a}=await Eo("crystals",{frequency:n.frequency,load_capacitance:n.load_capacitance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_mosfet"){let{mosfets:a}=await Eo("mosfets",{package:e,mosfet_mode:n.mosfet_mode,channel_type:n.channel_type});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_resonator"){let{resonators:a}=await Eo("resonators",{frequency:n.frequency,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_switch"){let{switches:a}=await Eo("switches",{switch_type:n.type,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_led"){let{leds:a}=await Eo("leds",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_fuse"){let{fuses:a}=await Eo("fuses",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}return{}}};var CGt="https://kicad-mod-cache.tscircuit.com",T9e=()=>({partsEngine:w9e,footprintLibraryMap:{kicad:async n=>{let e=`${CGt}/${n}`,a=`${e}.circuit.json`,l=await(await fetch(a)).json(),p=Array.isArray(l)?l.filter(f=>f?.type==="pcb_silkscreen_text"?f?.text==="REF**":!0):l,x=`${e}.wrl`;return{footprintCircuitJson:p,cadModel:{
|
|
1041
|
+
"${a.message}"`)});if(n.view==="pcb")return e.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(n.view==="schematic")return e.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${n.view}`)}getCoreVersion(){let[n,e,a]=fGt.version.split(".").map(Number);return`${n}.${e}.${a+1}`}async preview(n){let e=typeof n=="object"?n:{previewName:n};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return _i()}_computePcbGlobalTransformBeforeLayout(){return _i()}selectAll(n){return this._guessRootComponent(),this.firstChild?.selectAll(n)??[]}selectOne(n,e){return this._guessRootComponent(),this.firstChild?.selectOne(n,e)??null}emit(n,...e){if(this._eventListeners[n])for(let a of this._eventListeners[n])a(...e)}on(n,e){this._eventListeners[n]||(this._eventListeners[n]=[]),this._eventListeners[n].push(e)}removeListener(n,e){this._eventListeners[n]&&(this._eventListeners[n]=this._eventListeners[n].filter(a=>a!==e))}enableDebug(n){typeof n=="string"?HW.default.enable(n):(n===null||n===!1)&&HW.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},hGt=qg,mGt=qg,gGt=n=>{let[e,a]=Lg.default.useState(!0),[s,l]=Lg.default.useState(null),[p,x]=Lg.default.useState(),[f,m]=Lg.default.useState();return Lg.default.useEffect(()=>{a(!0),l(null),n&&setTimeout(()=>{try{let D=new qg;D.add(n),x(D),m(D.toJson())}catch(D){l(D)}a(!1)},1)},[n]),{isLoading:e,error:s,circuit:p,circuitJson:f}},Ug=(n,e)=>(a,s)=>{let l=[];Array.isArray(e)?l.push(...e.flat()):typeof e=="object"&&l.push(...Object.values(e).flat(),...Object.keys(e));let p=x=>{if(x?.name&&x.name!==a)throw new Error(`Component name mismatch. Hook name: ${a}, Component prop name: ${x.name}`);let f={...s,...x,name:a},m=[];for(let D of l)if(f[D]){let b=`.${a} > .${D}`,E=f[D];m.push({from:b,to:E}),delete f[D]}return(0,A1.jsxs)(A1.Fragment,{children:[(0,A1.jsx)(n,{...f}),m.map((D,b)=>(0,A1.jsx)("trace",{...D},b))]})};for(let x of l)p[x]=`.${a} > .${x}`;return p},DGt=Ug(n=>(0,C9e.jsx)("capacitor",{...n}),Z_e),yGt=n=>Ug(e=>(0,_9e.jsx)("chip",{pinLabels:n,...e}),n),bGt=Ug(n=>(0,A9e.jsx)("diode",{...n}),xAe),FGt=Ug(n=>(0,R9e.jsx)("led",{...n}),hAe),EGt=Ug(n=>(0,S9e.jsx)("resistor",{...n}),Y_e),vGt=new Proxy(n=>new Proxy({},{get:(e,a)=>`.${n} > .${a}`}),{get:(n,e)=>{let a=(...s)=>{let l=s[0];return new Proxy({},{get:(p,x)=>`.${e} > .${x}`})};return new Proxy(a,{get:(s,l)=>e==="net"?`net.${l}`:e==="subcircuit"?new Proxy({},{get:(p,x)=>new Proxy({},{get:(f,m)=>`subcircuit.${l} > .${x} > .${m}`})}):`.${e} > .${l}`,apply:(s,l,p)=>e==="net"?new Proxy({},{get:(x,f)=>`net.${f}`}):new Proxy({},{get:(x,f)=>{let m=`.${e} > .${f}`;return["U","J","CN"].some(b=>e.startsWith(b))?m:new Proxy(new String(m),{get:(b,E)=>typeof E=="symbol"||E==="toString"?()=>m:`.${e} > .${f} > .${E}`})}})})}});FBe(gBe);FBe({Bug:HS});var P9e=qr(Ic(),1);var sK=new Map,Eo=async(n,e)=>{let a=new URLSearchParams({...e,json:"true"}).toString();if(sK.has(a))return sK.get(a);let l=await(await fetch(`https://jlcsearch.tscircuit.com/${n}/list?${a}`)).json();return sK.set(a,l),l},w9e={findPart:async({sourceComponent:n,footprinterString:e})=>{if(n.type==="source_component"&&n.ftype==="simple_resistor"){let{resistors:a}=await Eo("resistors",{resistance:n.display_resistance??n.resistance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_capacitor"){e?.includes("cap")&&(e=e.replace("cap",""));let{capacitors:a}=await Eo("capacitors",{capacitance:n.display_capacitance??n.capacitance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_pin_header"){let a;e?.includes("_p")&&(a=Number(e.split("_p")[1]));let{headers:s}=await Eo("headers",a?{pitch:a,num_pins:n.pin_count,gender:n.gender}:{num_pins:n.pin_count,gender:n.gender});return{jlcpcb:(s??[]).map(l=>`C${l.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_potentiometer"){let{potentiometers:a}=await Eo("potentiometers",{resistance:n.max_resistance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_diode"){let{diodes:a}=await Eo("diodes",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_chip"){let{chips:a}=await Eo("chips",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_transistor"){let{transistors:a}=await Eo("transistors",{package:e,transistor_type:n.transistor_type});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_power_source"){let{power_sources:a}=await Eo("power_sources",{voltage:n.voltage,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_inductor"){let{inductors:a}=await Eo("inductors",{inductance:n.inductance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_crystal"){let{crystals:a}=await Eo("crystals",{frequency:n.frequency,load_capacitance:n.load_capacitance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_mosfet"){let{mosfets:a}=await Eo("mosfets",{package:e,mosfet_mode:n.mosfet_mode,channel_type:n.channel_type});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_resonator"){let{resonators:a}=await Eo("resonators",{frequency:n.frequency,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_switch"){let{switches:a}=await Eo("switches",{switch_type:n.type,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_led"){let{leds:a}=await Eo("leds",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_fuse"){let{fuses:a}=await Eo("fuses",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}return{}}};var CGt="https://kicad-mod-cache.tscircuit.com",T9e=()=>({partsEngine:w9e,footprintLibraryMap:{kicad:async n=>{let e=`${CGt}/${n}`,a=`${e}.circuit.json`,l=await(await fetch(a)).json(),p=Array.isArray(l)?l.filter(f=>f?.type==="pcb_silkscreen_text"?f?.text==="REF**":!0):l,x=`${e}.wrl`;return{footprintCircuitJson:p,cadModel:{wrlUrl:x}}}}});var iK=qr(vs(),1),wgr=(0,iK.default)("tsci:eval:execution-context");function KS(n,e={}){globalThis.React=P9e;let a=new qg({platform:e.platform||T9e()});return e.name&&(a.name=e.name),e.debugNamespace&&a.enableDebug(e.debugNamespace),{fsMap:{},entrypoint:"",preSuppliedImports:{"@tscircuit/core":WS,tscircuit:WS,"@tscircuit/math-utils":_Y,react:P9e,debug:iK.default,"@tscircuit/props":{}},circuit:a,...n}}function zF(n){let e=n;return e=e.replace(/\\/g,"/"),e=e.trim(),e.startsWith("./")&&(e=e.slice(2)),e.startsWith("/")&&(e=e.slice(1)),e}function I9e(n){let e={};for(let[a,s]of Object.entries(n))e[zF(a)]=s;return e}function ud(n){if(!n)return".";let a=n.replace(/\\/g,"/").replace(/\/+$/,"");return a.indexOf("/")===-1?".":a.substring(0,a.lastIndexOf("/"))||"/"}function oK(n,e){if(n.startsWith("../")){let a=ud(e);return oK(n.slice(3),a)}return n.startsWith("./")?oK(n.slice(2),e):n.startsWith("/")?n.slice(1):`${e}/${n}`}var qF=(n,e,a)=>{let s=a?oK(n,a):n,l=new Set(Array.isArray(e)?e:Object.keys(e));if(l.has(s))return s;let p=new Map;for(let m of l)p.set(zF(m),m);let x=zF(s);if(p.has(x))return p.get(x);let f=["tsx","ts","json","js","jsx","obj"];for(let m of f){let D=`${x}.${m}`;if(p.has(D))return p.get(D)}if(!n.startsWith("./")&&!n.startsWith("../")){let m=zF(n);if(p.has(m))return p.get(m);for(let D of f){let b=`${m}.${D}`;if(p.has(b))return p.get(b)}}return null},JS=(n,e)=>{let a=qF(n,e);if(!a)throw new Error(`File not found "${n}", available paths:
|
|
1042
1042
|
|
|
1043
1043
|
${Object.keys(e).join(", ")}`);return a};function UF(n,e,a){globalThis.__tscircuit_require=l=>{let p=qF(l,e,a),x=p&&e[p];if(!e[l]&&!x)throw new Error(`Import "${l}" not found ${a?`in "${a}"`:""}`);let f=e[l]||e[p];return new Proxy(f,{get(m,D){if(!(D in m)){if(D==="default")return m.default!==void 0?m.default:m.__esModule?void 0:typeof m=="function"||typeof m=="object"?m:void 0;if(D==="__esModule")return!0;throw new Error(`Component "${String(D)}" is not exported by "${l}"`)}return m[D]}})};let s=`
|
|
1044
1044
|
var exports = {};
|