astra/am3352-sbc

A 4-layer AM3352 single-board computer with 128‑MiB DDR3, PMIC power regulation, USB‑C 5‑V PD input, dual USB host ports, HDMI output with ESD protection, microSD/UART/JTAG interfaces, addressable RGB indicators, and a PWM-driven buzzer.

Version
0.1.19
License
unset
Stars
0

dist/viewer-part-06.txt

as,allowSameNetMerges:this.config.allowSameNetMerges,staticClearanceCache:this.routeStaticClearanceCache},A);for(const O of F)y.push({assignment:{...E.assignment,[C.busId]:R},plans:[...E.plans,...O]})}}if(y.length===0)return null;y.sort((E,B)=>{const S=this.getCoordinatedAdditionalViaCount(E.plans)-this.getCoordinatedAdditionalViaCount(B.plans);if(S!==0)return S;const Q=l(E)-l(B);return Math.abs(Q)>1e-9?Q:JSON.stringify(E.assignment).localeCompare(JSON.stringify(B.assignment))});const x=new Map;c=[];for(const E of y){const B=JSON.stringify(E.assignment),S=x.get(B)??0;if(!(S>=2)&&(x.set(B,S+1),c.push(E),c.length>=a))break}this.setInProgressPlans({phase:"route-grouped-beam",plans:c[0]?.plans??[],strategy:"grouped-beam",unitIndex:u,unitCount:i.length,busId:C.busId}),yield}let g,h,d=Number.POSITIVE_INFINITY,p=Number.POSITIVE_INFINITY;const m=C=>C.plans.reduce((y,x)=>y+x.length,0)+bue(C.plans)*.1+Eue(C.assignment,this.preparedBuses,this.config.balanceLayerLoadByConnectionCount)*Bue(this.config),_=this.preparedBuses.some(C=>C.maxLengthSkew!==void 0);for(const C of c){if(C.plans.length!==this.inputSrj.connections.length){yield;continue}const y=this.matchCompletePlanLengths(C.plans);if(!y.plans){yield;continue}const x=this.normalizeCompletePlanCorners(y.plans);if(!x){yield;continue}const E=aR({inputSrj:this.inputSrj,plans:x,layerNames:this.config.layerNames});if(!this.validateCompletePlans(x,E).valid){yield;continue}const B={...C,plans:x},S=this.getCoordinatedAdditionalViaCount(x),Q=m(B);if((!g||S<p||S===p&&Q<d)&&(g=B,h=E,d=Q,p=S),!_)break;this.setInProgressPlans({phase:"validate-grouped-beam",plans:x,strategy:"grouped-beam"}),yield}if(!g||!h)return null;const f=d;return Number.isFinite(f)?{summary:{assignmentIndex:t,busLayerAssignments:g.assignment,routedBusCount:this.preparedBuses.length,routedConnectionCount:g.plans.length,failedBusIds:[],score:f},plans:g.plans,blockingBusIds:[],outputSrj:h}:null}*evaluateGroupedBeamAlternativesSteps(t){const e=yield*this.evaluateGroupedBeamSteps(t);return e||(yield*this.evaluateGroupedBeamSteps(t,!0))}prioritizeFailedBusRepairs(t,e,n){const o=JSON.stringify(t),i=this.assignmentRepairDepthByKey.get(o)??0;if(i>=2)return;const r=8,s=[],a=new Set,A=l=>{const u=JSON.stringify(l);a.has(u)||this.evaluatedAssignmentKeys.has(u)||this.queuedAssignmentKeys.has(u)||(a.add(u),this.queuedAssignmentKeys.add(u),this.assignmentRepairDepthByKey.set(u,i+1),s.push(l))},c=[];for(let l=0;l<Math.max(e.length,n.length);l++){const u=e[l],g=n[l];u&&!c.includes(u)&&c.push(u),g&&!c.includes(g)&&c.push(g)}for(const l of e){const u=t[l],g=this.escapeLayersByBusId[l];if(!(!u||!g)){for(const h of n.slice(0,4)){const d=t[h],p=this.escapeLayersByBusId[h];if(!(!d||!p||!g.includes(d)||!p.includes(u))&&(A({...t,[l]:d,[h]:u}),s.length>=r))break}if(s.length>=r)break}}for(const l of c){const u=t[l],g=this.escapeLayersByBusId[l];if(!u||!g)continue;const h=g.indexOf(u);for(let d=1;d<g.length;d++){const p=g[(Math.max(h,0)+d)%g.length];if(p!==u&&(A({...t,[l]:p}),s.length>=r))break}if(s.length>=r)break}this.pendingRepairAssignments.push(...s)}hasCompleteBestAttempt(){return this.bestAttempt?.summary.routedConnectionCount===this.inputSrj.connections.length}getCoordinatedAdditionalViaCount(t){const e=new Set(this.preparedBuses.filter(a6).map(n=>n.busId));return t.reduce((n,o)=>n+(e.has(o.busId)?o.additionalVias?.length??0:0),0)}isAttemptBetter(t,e){if(t.summary.routedConnectionCount!==e.summary.routedConnectionCount)return t.summary.routedConnectionCount>e.summary.routedConnectionCount;if(t.summary.routedBusCount!==e.summary.routedBusCount)return t.summary.routedBusCount>e.summary.routedBusCount;const n=this.getCoordinatedAdditionalViaCount(t.plans),o=this.getCoordinatedAdditionalViaCount(e.plans);return n!==o?n<o:t.summary.score<e.summary.score}hasGloballyViaMinimalBestAttempt(){return!this.hasCompleteBestAttempt()||!this.bestAttempt||this.preparedBuses.length===0||!this.preparedBuses.every(a6)?!1:this.bestAttempt.plans.every(t=>t.via!==void 0&&(t.additionalVias?.length??0)===0)}shouldEvaluateGroupedBeam(){return this.groupedBeamEvaluated||this.nextAssignmentIndex===0?!1:this.hasCompleteBestAttempt()||this.pendingRepairAssignments.length===0||this.nextAssignmentIndex>=this.config.maxLayerCombinations}commitGroupedBeamAttempt(t){if(!t){this.hasCompleteBestAttempt()&&this.bestAttempt&&this.getCoordinatedAdditionalViaCount(this.bestAttempt.plans)===0&&(this.completeBestAttemptEndpoints(),this.solved=!0);return}this.attempts.push(t.summary),(!this.bestAttempt||this.isAttemptBetter(t,this.bestAttempt))&&(this.bestAttempt=t);const e=this.bestAttempt.summary;this.stats={phase:"complete-grouped-beam",assignment:e.assignmentIndex<0?0:e.assignmentIndex+1,assignmentCount:this.config.maxLayerCombinations,routedBuses:`${e.routedBusCount}/${this.preparedBuses.length}`,routedConnections:`${e.routedConnectionCount}/${this.inputSrj.connections.length}`,failedBuses:"none",bestScore:e.score},this.getCoordinatedAdditionalViaCount(this.bestAttempt.plans)===0&&(this.completeBestAttemptEndpoints(),this.solved=!0)}commitAssignmentAttempt(t,e){this.nextAssignmentIndex++,this.evaluatedAssignmentKeys.add(JSON.stringify(t)),(!this.bestAttempt||e.summary.routedConnectionCount>=this.bestAttempt.summary.routedConnectionCount)&&this.prioritizeFailedBusRepairs(t,e.summary.failedBusIds,e.blockingBusIds),this.attempts.push(e.summary),(!this.bestAttempt||this.isAttemptBetter(e,this.bestAttempt))&&(this.bestAttempt=e),this.stats={phase:"complete-assignment",assignment:e.summary.assignmentIndex+1,assignmentCount:this.config.maxLayerCombinations,routedBuses:`${e.summary.routedBusCount}/${this.preparedBuses.length}`,routedConnections:`${e.summary.routedConnectionCount}/${this.inputSrj.connections.length}`,failedBuses:e.summary.failedBusIds.join(", ")||"none",bestScore:this.bestAttempt.summary.score},(e.stopAfterCompleteValidation&&this.hasCompleteBestAttempt()||this.groupedBeamEvaluated&&e.summary.routedConnectionCount===this.inputSrj.connections.length&&this.getCoordinatedAdditionalViaCount(this.bestAttempt.plans)===0)&&(this.completeBestAttemptEndpoints(),this.solved=!0)}getNextAssignment(){let t;for(;!t&&this.nextAssignmentIndex<this.config.maxLayerCombinations;){const e=this.nextAssignmentIndex%3===0;let n,o=!1;if(!this.groupedBeamEvaluated&&this.nextAssignmentIndex>0?(n=this.pendingRepairAssignments.pop(),o=n!==void 0):e?n=this.layerAssignments[this.nextGeneratedAssignmentIndex++]:(n=this.pendingRepairAssignments.pop(),o=n!==void 0),!n&&(this.groupedBeamEvaluated||this.nextAssignmentIndex===0)&&(n=e?this.pendingRepairAssignments.pop():this.layerAssignments[this.nextGeneratedAssignmentIndex++],o=e&&n!==void 0),!n)break;const i=JSON.stringify(n);o&&this.queuedAssignmentKeys.delete(i),!this.evaluatedAssignmentKeys.has(i)&&(t=n)}return t}finishWithoutAnotherAssignment(){if(this.hasCompleteBestAttempt()){this.completeBestAttemptEndpoints(),this.solved=!0;return}this.failed=!0;const t=this.lengthMatchingFailure?.message??this.bestAttempt?.summary.validationIssues?.[0]?.message;this.error=t?`FanoutSolver: ${t}`:this.bestAttempt?`FanoutSolver: best layer assignment routed ${this.bestAttempt.summary.routedConnectionCount}/${this.inputSrj.connections.length} connections`:"FanoutSolver: no layer assignment could be evaluated"}_step(){if(this.activeOperation){this.stepActiveOperation();return}if(!this.layerReservedRoutingEvaluated){this.layerReservedRoutingEvaluated=!0;const e=vSo(this.preparedBuses,this.config.allowBlindAndBuriedVias),n=!e&&KPe({...this.config,srj:this.routingSrj,buses:this.preparedBuses})!==null;if(n||e||this.shouldTryLayerReservedRouting()){this.startOperation({name:"FanoutLayerReservedSolver",generator:this.evaluateLayerReservedRoutingSteps(e,n),onSolved:o=>{if(!o){this.inProgressPlans=[],this.stats={phase:"layer-reserved-fallback"};return}const i=o.summary.busLayerAssignments;this.layerAssignments.push(i),this.routingInitialized=!0,this.commitAssignmentAttempt(i,o)},getProgress:()=>Number(this.stats.workUnit??0)/Math.max(1,this.inputSrj.connections.length)}),this.stats={phase:"prepare-layer-reserved-routing"};return}}if(!this.routingInitialized){this.startOperation({name:"FanoutCandidateLayerSolver",generator:this.initializeRoutingSteps(),onSolved:()=>{},getProgress:()=>this.nextCandidateLayerBusIndex/Math.max(1,this.boundaryBuses.length+1)});return}if(this.nextAssignmentIndex>0&&this.hasGloballyViaMinimalBestAttempt()){this.completeBestAttemptEndpoints(),this.solved=!0;return}if(this.shouldEvaluateGroupedBeam()){this.groupedBeamEvaluated=!0,this.startOperation({name:"FanoutGroupedBeamSolver",generator:this.evaluateGroupedBeamAlternativesSteps(-1),onSolved:e=>this.commitGroupedBeamAttempt(e),getProgress:()=>{const e=Number(this.stats.workUnit??0),n=Number(this.stats.workUnitCount??0);return n>0?e/n:0}}),this.stats={...this.stats,phase:"prepare-grouped-beam"};return}const t=this.getNextAssignment();if(!(!t&&!this.groupedBeamEvaluated)){if(!t){this.finishWithoutAnotherAssignment();return}this.startOperation({name:"FanoutAssignmentSolver",generator:this.evaluateAssignmentSteps(this.nextAssignmentIndex,t),onSolved:e=>this.commitAssignmentAttempt(t,e),getProgress:()=>{const e=this.stats.routingStrategy==="group-by-layer"?1:this.stats.routingStrategy==="deep-first"?2:0,n=Number(this.stats.workUnit??0),o=Number(this.stats.workUnitCount??0),i=o>0?Math.min(1,n/o):0;return(e+i)/3}}),this.stats={...this.stats,phase:"prepare-assignment",assignment:this.nextAssignmentIndex+1,assignmentCount:this.config.maxLayerCombinations,routedConnections:`0/${this.inputSrj.connections.length}`}}}computeProgress(){if(this.solved||this.failed)return 1;if(this.activeSubSolver?.getSolverName()==="FanoutLayerReservedSolver")return Math.min(.99,Number(this.stats.workUnit??0)/Math.max(1,this.inputSrj.connections.length));if(!this.routingInitialized)return .05*(this.nextCandidateLayerBusIndex/Math.max(1,this.boundaryBuses.length+1));let t=0;if(this.activeSubSolver?.getSolverName()==="FanoutAssignmentSolver"){const e=this.stats.routingStrategy==="group-by-layer"?1:this.stats.routingStrategy==="deep-first"?2:0,n=Number(this.stats.workUnit??0),o=Number(this.stats.workUnitCount??0),i=o>0?Math.min(1,n/o):0;t=(e+i)/3}return Math.min(.99,.05+.95*((this.nextAssignmentIndex+t)/this.config.maxLayerCombinations))}getConstructorParams(){return[this.inputSrj,this.options]}getOutput(){if(!this.solved||!this.bestAttempt)throw new Error("FanoutSolver: getOutput() called before a complete fanout was solved");const t=this.validateCompletePlans(this.bestAttempt.plans,this.bestAttempt.outputSrj);if(!t.valid)throw new Error(`FanoutSolver: completed output failed validation: ${t.issues[0]?.message??"unknown validation error"}`);const e=OSo({srj:this.endpointCompletion?.simpleRouteJson??this.bestAttempt.outputSrj,layerNames:this.config.layerNames,allowBlindAndBuriedVias:this.config.allowBlindAndBuriedVias}),n=new Map((e.traces??[]).map(o=>[o.pcb_trace_id,o]));return{simpleRouteJson:e,fanoutTraces:this.bestAttempt.plans.flatMap(o=>[n.get(o.trace.pcb_trace_id)??o.trace,...o.planeEndpointTrace?[n.get(o.planeEndpointTrace.pcb_trace_id)??o.planeEndpointTrace]:[]]),completionTraces:(this.endpointCompletion?.traces??[]).map(o=>n.get(o.pcb_trace_id)??o),...this.endpointCompletion?{endpointCompletion:this.endpointCompletion.report}:{},planeTerminations:this.bestAttempt.plans.flatMap(o=>o.termination.type==="plane"&&o.via?[{busId:o.busId,connectionName:o.connectionName,layer:o.termination.layer,via:o.via}]:[]),busLayerAssignments:this.bestAttempt.summary.busLayerAssignments,busDirections:Object.fromEntries(this.preparedBuses.map(o=>[o.busId,o.direction])),attempts:[...this.attempts],validation:t}}getOutputSimpleRouteJson(){return this.getOutput().simpleRouteJson}visualize(){return this.activeSubSolver?.visualize()??this.visualizeCurrentState()}},$vo=t=>{if(typeof t!="object"){const e=lt.parse(t);return{top:e,right:e,bottom:e,left:e}}return{top:t.top===void 0?0:lt.parse(t.top),right:t.right===void 0?0:lt.parse(t.right),bottom:t.bottom===void 0?0:lt.parse(t.bottom),left:t.left===void 0?0:lt.parse(t.left)}},qvo=t=>{const e=(t.ccwRotationDegrees??0)*Math.PI/180,n=Math.abs(Math.cos(e)),o=Math.abs(Math.sin(e));return{x:(n*t.width+o*t.height)/2,y:(o*t.width+n*t.height)/2}},Xvo=({preparedBuses:t,padding:e})=>{if(e===void 0)return;const n=new Map;for(const a of t)n.has(a.componentId)||n.set(a.componentId,a.componentObstacles.filter(A=>A.connectedTo.length>0));const o=[...n.values()].flat();if(o.length===0)throw new Error("Cannot apply fanout boundary padding without source pad obstacles");const i=o.map(a=>{const A=qvo(a);return{minX:a.center.x-A.x,maxX:a.center.x+A.x,minY:a.center.y-A.y,maxY:a.center.y+A.y}}),r=$vo(e),s={minX:Math.min(...i.map(a=>a.minX))-r.left,maxX:Math.max(...i.map(a=>a.maxX))+r.right,minY:Math.min(...i.map(a=>a.minY))-r.bottom,maxY:Math.max(...i.map(a=>a.maxY))+r.top};for(const a of t)if(a.termination.type==="boundary")for(const A of a.connections)a.direction==="left"||a.direction==="right"?(s.minY=Math.min(s.minY,A.targetPoint.y),s.maxY=Math.max(s.maxY,A.targetPoint.y)):(s.minX=Math.min(s.minX,A.targetPoint.x),s.maxX=Math.max(s.maxX,A.targetPoint.x));return s},Zvo=t=>Math.round(t*1e3)/1e3,ewo=(t,e)=>{let n;for(const o of t.obstacles){if(!o.componentId||!e.has(o.componentId))continue;const i=o.center.x-o.width/2,r=o.center.x+o.width/2,s=o.center.y-o.height/2,a=o.center.y+o.height/2;n=n?{minX:Math.min(n.minX,i),maxX:Math.max(n.maxX,r),minY:Math.min(n.minY,s),maxY:Math.max(n.maxY,a)}:{minX:i,maxX:r,minY:s,maxY:a}}return n},two=(t,e)=>Math.min(t.minX-e.minX,e.maxX-t.maxX,t.minY-e.minY,e.maxY-t.maxY),nwo=({input:t,solverError:e,componentIds:n,sharedBoundary:o,componentNamesById:i})=>{const r=e?.match(/routed (\d+)\/(\d+) connections/),s=r?Number(r[1]):void 0,a=r?Number(r[2]):t.connections.length,A=[...n].map(g=>i?.get(g)??g).sort(),c=A.length>0?` for ${A.join(", ")}`:"",l=[s===void 0?`Fanout failed${c}: ${e??"the fanout solver did not report a reason"}.`:`Fanout failed${c}: only ${s} of ${a} connections could escape to the breakout boundary.`],u=ewo(t,n);if(u&&o){const g=two(u,o);l.push(`The breakout boundary is ${Zvo(g)}mm from the pads at its narrowest point, which all ${a} escapes have to share.`)}return l.push("Give the fanout more room by increasing the breakout's padding, or by extending the breakout to include the parts crowding it (decoupling capacitors, series resistors) so their pads sit inside the boundary instead of against it."),l.join(" ")},owo=(t,e)=>Math.abs(t.minX-e.minX)>1e-6||Math.abs(t.maxX-e.maxX)>1e-6||Math.abs(t.minY-e.minY)>1e-6||Math.abs(t.maxY-e.maxY)>1e-6,iwo=(t,e)=>{if(!(!t&&e.length===0))return{minX:Math.min(t?.minX??Number.POSITIVE_INFINITY,...e.map(n=>n.x)),maxX:Math.max(t?.maxX??Number.NEGATIVE_INFINITY,...e.map(n=>n.x)),minY:Math.min(t?.minY??Number.POSITIVE_INFINITY,...e.map(n=>n.y)),maxY:Math.max(t?.maxY??Number.NEGATIVE_INFINITY,...e.map(n=>n.y))}},rwo=(t,e)=>t?.map(n=>{const{preferredLayer:o,preferredLayers:i,...r}=n,s=e?.[n.busId],a=s===void 0?void 0:rMe(s),A=a&&a!=="center"&&sMe(a)?a:void 0,c={...r,...n.termination?.type==="plane"?{}:A?{exitPosition:A}:{}},l=[...o===void 0?[]:[o],...i??[]].filter((h,d,p)=>p.indexOf(h)===d);if(l.length===0)return c;const u=n.allowedLayers,g=u===void 0?l:l.filter(h=>u.includes(h));return{...c,allowedLayers:g}}),rMe=t=>typeof t=="string"?t:t.direction,swo=new Set(rlt),sMe=t=>swo.has(t),awo=t=>{switch(t){case"top_left":return"top-left";case"top_center":return"top";case"top_right":return"top-right";case"center_left":return"left";case"center":return;case"center_right":return"right";case"bottom_left":return"bottom-left";case"bottom_center":return"bottom";case"bottom_right":return"bottom-right"}},Awo=t=>{switch(t){case"top_left":case"top_center":case"top_right":return"up";case"center_left":return"left";case"center":return;case"center_right":return"right";case"bottom_left":case"bottom_center":case"bottom_right":return"down"}},cwo=t=>{const e=rMe(t);return sMe(e)?XDt(e).direction:Awo(e)},lwo=(t,e)=>t.obstacles.find(o=>o.componentId&&o.layers.includes(e.layer)&&(e.pointId&&o.connectedTo.includes(e.pointId)||e.x>=o.center.x-o.width/2&&e.x<=o.center.x+o.width/2&&e.y>=o.center.y-o.height/2&&e.y<=o.center.y+o.height/2))?.componentId,uwo=(t,e)=>{const n=new Set(e.connectionNames),o=new Map;for(const f of t.connections)if(n.has(f.name))for(const I of f.pointsToConnect){const C=lwo(t,I);if(!C)continue;const y=o.get(C)??[];y.push(I),o.set(C,y)}const i=[...o.entries()].sort(([f,I],[C,y])=>y.length-I.length||f.localeCompare(C))[0];if(!i)return;const[r,s]=i,a=t.obstacles.filter(f=>f.componentId===r);if(a.length===0)return;const A=a.map(f=>f.center.x),c=a.map(f=>f.center.y),l=Math.min(...A),u=Math.max(...A),g=Math.min(...c),h=Math.max(...c),d={x:(l+u)/2,y:(g+h)/2},p={x:Math.max((u-l)/2,1e-6),y:Math.max((h-g)/2,1e-6)},m={x:s.reduce((f,I)=>f+I.x,0)/s.length,y:s.reduce((f,I)=>f+I.y,0)/s.length},_={x:(m.x-d.x)/p.x,y:(m.y-d.y)/p.y};return Math.abs(_.x)>Math.abs(_.y)?_.x>=0?"right":"left":Math.abs(_.y)>1e-9?_.y>=0?"up":"down":"right"},gwo=({fanoutSimpleRouteJson:t,sourceComponentIds:e})=>{const n=new Map;for(const i of t.obstacles){if(!i.componentId||!e.has(i.componentId))continue;const r=n.get(i.componentId)??[];r.push(i),n.set(i.componentId,r)}const o=[];for(const[i,r]of n){const s=Math.min(...r.map(l=>l.center.x-l.width/2)),a=Math.max(...r.map(l=>l.center.x+l.width/2)),A=Math.min(...r.map(l=>l.center.y-l.height/2)),c=Math.max(...r.map(l=>l.center.y+l.height/2));o.push({obstacleId:`fanout-source-keepout:${i}`,componentId:i,isFanoutSourceKeepout:!0,type:"rect",layers:WN(t.layerCount),center:{x:(s+a)/2,y:(A+c)/2},width:a-s,height:c-A,connectedTo:[]})}return{...t,obstacles:[...t.obstacles.filter(i=>!i.componentId||!e.has(i.componentId)),...o]}},aMe=class xit{constructor(e,n){this.input=e,this.options=n}input;options;isRouting=!1;outputSimpleRouteJson;startTimeoutId;eventHandlers={complete:[],error:[],progress:[]};getLegacyBusExitPreferences(){if(!this.options.busFanoutDirections)return;const e=new Set(this.input.buses?.map(i=>i.busId)??[]),n=new Set(this.input.buses?.filter(i=>i.termination?.type==="plane").map(i=>i.busId)??[]),o={};for(const[i,r]of Object.entries(this.options.busFanoutDirections)){if(!e.has(i))throw new Error(`Fanout direction references unknown bus "${i}" in this autorouting phase`);if(n.has(i))continue;const s=rMe(r);if(sMe(s))continue;const a=awo(s);a&&(o[i]=a)}return Object.keys(o).length>0?o:void 0}getPlaneBusDirections(){const e=this.input.buses?.filter(i=>i.termination?.type==="plane")??[],n=new Set(e.map(i=>i.busId)),o={};for(const[i,r]of Object.entries(this.options.busFanoutDirections??{})){if(!n.has(i))continue;const s=cwo(r);s&&(o[i]=s)}for(const i of e){if(o[i.busId])continue;const r=uwo(this.input,i);r&&(o[i.busId]=r)}return Object.keys(o).length>0?o:void 0}getFanoutSolverOptions(){const e={buses:rwo(this.input.buses,this.options.busFanoutDirections),borderDistribution:"even",compactBusTracks:!0,busDirections:this.getPlaneBusDirections(),busExitPreferences:this.getLegacyBusExitPreferences(),escapeLayers:this.options.fanoutRoutingLayers,allowBlindAndBuriedVias:this.options.allowBlindAndBuriedVias??this.input.allowBlindAndBuriedVias};return this.options.mode==="single_layer_fanout"?{...e,escapeLayers:["top"],singleLayerPushAndShove:!0}:e}static resolveFanoutBounds(e,n){let o,i;if(n.fanoutBoundaryPadding!==void 0){const r=new xit(e,n),s=new Sue(e,r.getFanoutSolverOptions());o=Xvo({preparedBuses:s.preparedBuses,padding:n.fanoutBoundaryPadding})}else if(n.fanoutBounds===void 0){const r=new xit(e,n);i=new Sue(e,r.getFanoutSolverOptions()).preparedBuses[0]?.sharedBoundary}return n.fanoutBounds&&o&&owo(n.fanoutBounds,o)&&n.onFanoutBoundsConflict?.(),iwo(n.fanoutBounds??o??i,n.breakoutPoints??[])}solveFanout(){const e=this.getFanoutSolverOptions(),n=new Sue(this.input,{...e,...this.options.fanoutBounds?{sharedBoundary:this.options.fanoutBounds}:{}}),o=n.getConstructorParams();if(this.options.onSolverStarted?.({solverName:"FanoutSolver",solverParams:o[0],solverConstructorArgs:o}),n.solve(),n.failed)throw new Error(nwo({input:this.input,solverError:n.error,componentIds:new Set(n.preparedBuses.map(a=>a.componentId)),sharedBoundary:this.options.fanoutBounds??e.sharedBoundary,componentNamesById:this.options.componentNamesById}));const i=n.getOutput(),r=i.simpleRouteJson,s=i.fanoutTraces;return{downstreamSimpleRouteJson:gwo({fanoutSimpleRouteJson:r,sourceComponentIds:new Set(n.preparedBuses.map(a=>a.componentId))}),fanoutTraces:s,debugGraphics:n.visualize()}}startFanout(){try{const{downstreamSimpleRouteJson:e,fanoutTraces:n,debugGraphics:o}=this.solveFanout();if(!this.isRouting)return;this.outputSimpleRouteJson=e,this.emitEvent({type:"progress",steps:1,progress:1,phase:this.options.mode,debugGraphics:o}),this.isRouting=!1,this.emitEvent({type:"complete",traces:n})}catch(e){this.isRouting=!1,this.emitEvent({type:"error",error:e instanceof Error?e:new Error(String(e))})}}start(){this.isRouting||(this.isRouting=!0,this.startTimeoutId=setTimeout(()=>{this.startTimeoutId=void 0,this.startFanout()},0))}stop(){this.startTimeoutId!==void 0&&(clearTimeout(this.startTimeoutId),this.startTimeoutId=void 0),this.isRouting=!1}on(e,n){e==="complete"?this.eventHandlers.complete.push(n):e==="error"?this.eventHandlers.error.push(n):this.eventHandlers.progress.push(n)}emitEvent(e){if(e.type==="complete")for(const n of this.eventHandlers.complete)n(e);else if(e.type==="error")for(const n of this.eventHandlers.error)n(e);else for(const n of this.eventHandlers.progress)n(e)}solveSync(){const{downstreamSimpleRouteJson:e,fanoutTraces:n}=this.solveFanout();return this.outputSimpleRouteJson=e,n}getOutputSimpleRouteJson(){return this.outputSimpleRouteJson}},Que=1e-6;function dwo(t,e){if(!t.subcircuit_connectivity_map_key||t.subcircuit_connectivity_map_key!==e.subcircuit_connectivity_map_key||t.subcircuit_id!==e.subcircuit_id)return!1;const n=t.layers.toSorted(),o=e.layers.toSorted();return Math.abs(t.x-e.x)<=Que&&Math.abs(t.y-e.y)<=Que&&Math.abs(t.hole_diameter-e.hole_diameter)<=Que&&Math.abs(t.outer_diameter-e.outer_diameter)<=Que&&n.length===o.length&&n.every((i,r)=>i===o[r])}var hwo=({db:t,connectedOffboardObstacles:e,simpleRouteJson:n,subcircuit_id:o})=>{if(Object.keys(e).length===0)return;const i=new Map;for(const a of t.pcb_port.list())if(a.source_port_id){const A=t.pcb_smtpad.getWhere({pcb_port_id:a.pcb_port_id});A&&i.set(A.pcb_smtpad_id,a.source_port_id);const c=t.pcb_plated_hole.getWhere({pcb_port_id:a.pcb_port_id});c&&i.set(c.pcb_plated_hole_id,a.source_port_id)}const r=new Map;for(const a of n.obstacles)a.obstacleId&&r.set(a.obstacleId,a);const s=new Map;for(const[a,A]of Object.entries(e))s.has(A)||s.set(A,[]),s.get(A).push(a);for(const[a,A]of s){const c=new Set;for(const h of A){const d=r.get(h);if(d)for(const p of d.connectedTo){const m=i.get(p);m&&c.add(m)}}if(c.size<2)continue;const l=Array.from(c);t.source_trace.list().some(h=>{const d=new Set(h.connected_source_port_ids);return l.every(p=>d.has(p))})||t.source_trace.insert({connected_source_port_ids:l,connected_source_net_ids:[],subcircuit_id:o??void 0,display_name:`offboard_${a}`})}},gRt=({traceWidth:t,traceToPadClearance:e,viaPadDiameter:n})=>(n??Math.max(t*2,.3))+2*(t+e),pwo=t=>{const e=new Map;for(const n of t.pcb_component.list()){const o=t.source_component.get(n.source_component_id);o?.name&&e.set(n.pcb_component_id,o.name)}return e},AMe=t=>t?.replace(/-/g,"_");function dRt(t){if(!t)return null;if(typeof t=="string"){const n=AMe(t);return n==="sequential_trace"||n==="auto_cloud"?n:null}const e=AMe(t.preset);return e==="sequential_trace"||e==="auto_cloud"?e:AMe(t.groupMode)==="sequential_trace"?"sequential_trace":null}function h$(t,e){const n={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof t=="object"&&!t.preset)return{local:!(t.serverUrl||t.serverMode||t.serverCacheEnabled),...n,...t};const o=typeof t=="object"?t.preset:t,i=typeof t=="object"?t:{},r=typeof o=="string"?o.replace(/_/g,"-"):o,s=r&&typeof r=="string"?e?.autorouterMap?.[r]:void 0;if(s)return{local:!0,groupMode:"subcircuit",algorithmFn:async a=>s.createAutorouter(a)};switch(r){case"default":case"auto":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"beta-pipeline9":return{local:!0,groupMode:"subcircuit",autorouterVersion:"beta_pipeline9"};case"single-layer-fanout":return{local:!0,groupMode:"subcircuit",preset:"single_layer_fanout"};case"fanout":return{local:!0,groupMode:"subcircuit",preset:"fanout"};case"simplify":return{local:!0,groupMode:"subcircuit",preset:"simplify"};case"auto-cloud":{const{preset:a,local:A,groupMode:c,...l}=i;return{local:!1,groupMode:"subcircuit",...n,...l}}case"laser-prefab":{const{preset:a,local:A,groupMode:c,...l}=i;return{local:!0,groupMode:"subcircuit",preset:"laser_prefab",...l}}case"auto-jumper":{const{preset:a,local:A,groupMode:c,...l}=i;return{local:!0,groupMode:"subcircuit",preset:"auto_jumper",...l}}default:return{local:!0,groupMode:"subcircuit"}}}var hRt=new WeakMap,pRt=t=>{const e=hRt.get(t);if(e)return e;const n={toLocal:D0(l3e(-t.rotation),M0(-t.x,-t.y)),toWorld:D0(M0(t.x,t.y),l3e(t.rotation))};return hRt.set(t,n),n},mwo=(t,e)=>{if(nD(t,e))return 0;let n=Number.POSITIVE_INFINITY;for(let o=0;o<e.length;o++){const i=e[o],r=e[(o+1)%e.length];n=Math.min(n,Zd(t,i,r))}return n},mRt=(t,e,n)=>{const o={x:e,y:n};if(t.kind==="circle")return Math.max(ad(o,t)-t.radius,0);if(t.kind==="segment")return Math.max(Zd(o,{x:t.x1,y:t.y1},{x:t.x2,y:t.y2})-t.halfWidth,0);if(t.kind==="polygon")return mwo(o,t.points);const{toLocal:i}=pRt(t);return EQn(ts(i,o),{center:{x:0,y:0},width:t.halfWidth*2,height:t.halfHeight*2})},_wo=(t,e)=>{if(mRt(t,e.x,e.y)===0)return e;if(t.kind==="circle"){const r={x:t.x,y:t.y},s=Bxe(r,e);return{x:t.x+s.x*t.radius,y:t.y+s.y*t.radius}}if(t.kind==="segment"){const r=SQ(e,{x:t.x1,y:t.y1},{x:t.x2,y:t.y2}),s=Bxe(r,e);return{x:r.x+s.x*t.halfWidth,y:r.y+s.y*t.halfWidth}}if(t.kind==="polygon"){let r=t.points[0],s=Number.POSITIVE_INFINITY;for(let a=0;a<t.points.length;a++){const A=t.points[a],c=t.points[(a+1)%t.points.length],l=SQ(e,A,c),u=ad(e,l);u<s&&(s=u,r=l)}return r}const{toLocal:n,toWorld:o}=pRt(t),i=ts(n,e);return ts(o,{x:fp(i.x,-t.halfWidth,t.halfWidth),y:fp(i.y,-t.halfHeight,t.halfHeight)})},_Rt=({start:t,end:e,trace:n,clearance:o=0})=>{const i=n.halfWidth+o,r=Oh([t,e]),s={minX:r.minX-i,minY:r.minY-i,maxX:r.maxX+i,maxY:r.maxY+i},a={x:n.x1,y:n.y1},A={x:n.x2,y:n.y2},c=Oh([a,A]);return z4(c,s)?xV(t,e,a,A)<=i:!1},fRt=(t,e)=>{const n=new Set(t),o=new Map,i=(s,a,A,c)=>{const l=`${s},${a}`,u=o.get(l)??[];u.push([A,c]),o.set(l,u)};for(const s of t){const a=s%e,A=Math.floor(s/e);(A===0||!n.has(s-e))&&i(a,A,a+1,A),(a===e-1||!n.has(s+1))&&i(a+1,A,a+1,A+1),n.has(s+e)||i(a+1,A+1,a,A+1),(a===0||!n.has(s-1))&&i(a,A+1,a,A)}const r=[];for(const[s,a]of o)for(;a.length>0;){const[A,c]=s.split(",").map(Number),l=[[A,c]];let u=a.pop();for(;u[0]!==A||u[1]!==c;){l.push(u);const h=o.get(`${u[0]},${u[1]}`);if(!h||h.length===0)break;u=h.pop()}const g=l.filter((h,d)=>{const p=l[(d+l.length-1)%l.length],m=l[(d+1)%l.length],_=p[0]===h[0]&&h[0]===m[0],f=p[1]===h[1]&&h[1]===m[1];return!_&&!f});g.length>=3&&r.push(g)}return r},fwo=2,cMe=9,lMe=(t,{nx:e,ny:n})=>{const o=t%e,i=Math.floor(t/e),r=[];return o>0&&r.push(t-1),o<e-1&&r.push(t+1),i>0&&r.push(t-e),i<n-1&&r.push(t+e),r},Iwo=(t,e)=>{const n=new Uint8Array(e.labels.length*2);return(o,i)=>{const r=Math.min(o,i)*2+(Math.abs(o-i)===e.nx?1:0),s=n[r];if(s!==0)return s===1;const a=e.gridCells[o].center,A=e.gridCells[i].center,c=zne(a,A),l=a.y===A.y,u=l?{minX:c.x,minY:c.y-e.gridPitch/2,maxX:c.x,maxY:c.y+e.gridPitch/2}:{minX:c.x-e.gridPitch/2,minY:c.y,maxX:c.x+e.gridPitch/2,maxY:c.y};let g=0;const h=(1<<cMe)-1;for(const d of e.traceBarriers)if(!(d.netIndex===t||d.maxX<u.minX||d.minX>u.maxX||d.maxY<u.minY||d.minY>u.maxY)){for(let p=0;p<cMe;p++){const m=1<<p;if((g&m)!==0)continue;const _=-e.gridPitch/2+e.gridPitch*p/(cMe-1),f=l?{x:c.x,y:c.y+_}:{x:c.x+_,y:c.y},I=SQ(f,d.start,d.end);bxe(f,I)<=d.radiusSquared&&(g|=m)}if(g===h)return n[r]=2,!1}return n[r]=1,!0}},uMe=(t,e)=>{let n=e.canCrossGridEdgeByNetIndex.get(t);return n||(n=Iwo(t,e),e.canCrossGridEdgeByNetIndex.set(t,n)),n},Cwo=({labeledLayer:t,insideCells:e,connectivitySeedNetIndices:n,traceBarriers:o,gridCells:i,traceClearance:r,gridPitch:s})=>{if(r===0)return;const{labels:a,nx:A,ny:c}=t,l=o.map(_=>{const f=_.halfWidth+r,I={x:_.x1,y:_.y1},C={x:_.x2,y:_.y2},y=Oh([I,C]);return{netIndex:_.netIndex,start:I,end:C,radiusSquared:f**2,minX:y.minX-f,minY:y.minY-f,maxX:y.maxX+f,maxY:y.maxY+f}}),u={labels:a,nx:A,traceBarriers:l,gridCells:i,gridPitch:s,canCrossGridEdgeByNetIndex:new Map},g=new Uint8Array(a.length),h=[];for(let _=0;_<a.length;_++)e[_]!==1||n[_]!==a[_]||(g[_]=1,h.push(_));let d=0;for(;d<h.length;){const _=h[d++],f=a[_];for(const I of lMe(_,t))e[I]!==1||g[I]===1||a[I]!==f||!uMe(f,u)(_,I)||(g[I]=1,h.push(I))}const p=new Uint8Array(a.length),m=[];for(let _=0;_<a.length;_++){if(e[_]!==1||a[_]<0||g[_]===1||p[_]===1)continue;const f=a[_],I=[],C=[_];for(p[_]=1;C.length>0;){const E=C.pop();I.push(E);for(const B of lMe(E,t))e[B]!==1||p[B]===1||g[B]===1||a[B]!==f||!uMe(f,u)(E,B)||(p[B]=1,C.push(B))}const y=new Map;for(const E of I)for(const B of lMe(E,t)){const S=a[B];g[B]!==1||S<0||S===f||!uMe(S,u)(E,B)||y.set(S,(y.get(S)??0)+1)}const x=[...y.entries()].sort((E,B)=>B[1]-E[1])[0]?.[0];x!==void 0?m.push({cells:I,netIndex:x}):m.push({cells:I,netIndex:-1})}for(const _ of m)for(const f of _.cells)a[f]=_.netIndex},ywo=({labeledLayer:t,insideCells:e,visibleCells:n,traceBarriers:o,gridCells:i,traceClearance:r})=>{const{labels:s,nx:a,ny:A}=t,c=new Set;for(let g=0;g<s.length;g++)n[g]===1&&s[g]>=0&&c.add(s[g]);const l=new Map;for(const g of c){const h=new Int8Array(s.length).fill(-1),d=[];for(let m=0;m<s.length;m++)n[m]!==1||s[m]!==g||(h[m]=0,d.push(m));let p=0;for(;p<d.length;){const m=d[p++];if(h[m]>=fwo)continue;const _=m%a,f=Math.floor(m/a),I=[];_>0&&I.push(m-1),_<a-1&&I.push(m+1),f>0&&I.push(m-a),f<A-1&&I.push(m+a);const C=i[m].center;for(const y of I){if(e[y]!==1||h[y]>=0||n[y]===1&&s[y]!==g)continue;const x=i[y].center;o.some(B=>B.netIndex!==g&&_Rt({start:C,end:x,trace:B,clearance:r}))||(h[y]=h[m]+1,d.push(y))}}l.set(g,h)}const u=[];for(let g=0;g<s.length;g++){const h=s[g];if(e[g]!==1||h<0||n[g]===1)continue;const d=l.get(h)?.[g]??-1,p=Array.from(l.entries()).map(([m,_])=>({netIndex:m,distance:_[g]})).filter(m=>m.netIndex!==h&&m.distance>=0&&(d<0||m.distance<d)).sort((m,_)=>m.distance-_.distance)[0];p&&u.push({cell:g,netIndex:p.netIndex})}for(const g of u)s[g.cell]=g.netIndex},xwo=t=>{const{bounds:e,boardOutline:n,gridPitch:o,regionNormalizationArea:i,traceClearance:r}=t,s=Math.max(1,Math.round((e.maxX-e.minX)/o)),a=Math.max(1,Math.round((e.maxY-e.minY)/o)),A=Math.max(1,Math.round(i/o**2)),c=xQn({rows:a,cols:s,xSpacing:o,ySpacing:o,offsetX:e.minX,offsetY:e.minY,yDirection:"up-is-negative",centered:!1}),l=[];for(const u of t.layers){const g=t.primitives.filter(y=>y.layers.includes(u)&&t.nets[y.netIndex]?.isPower),h=t.primitives.filter(y=>y.kind==="segment"&&y.isTrace===!0&&y.layers.includes(u)),d=new Int32Array(s*a).fill(-1),p=new Uint8Array(s*a),m=new Uint8Array(s*a),_=new Uint8Array(s*a),f=new Int32Array(s*a).fill(-1),I=o*Math.SQRT2/2;for(const{index:y,center:x}of c){if(!nD(x,n))continue;m[y]=1;const E=g.map(M=>({primitive:M,distance:mRt(M,x.x,x.y)})).sort((M,k)=>M.distance-k.distance);let B=E[0]?.primitive.netIndex??-1,S=E[0]?.distance??Number.POSITIVE_INFINITY,Q=!1,w=!1;for(const M of E){if(M.distance===0){B=M.primitive.netIndex,S=M.distance,Q=!0,w=!0;break}const k=_wo(M.primitive,x);if(!h.some(F=>F.netIndex!==M.primitive.netIndex&&_Rt({start:x,end:k,trace:F,clearance:r}))){B=M.primitive.netIndex,S=M.distance,w=!0;break}}d[y]=B,Q&&(p[y]=1),w&&(_[y]=1),w&&S<=I&&(f[y]=B)}const C={layer:u,labels:d,nx:s,ny:a};ywo({labeledLayer:C,insideCells:m,visibleCells:_,traceBarriers:h,gridCells:c,traceClearance:r}),Cwo({labeledLayer:C,insideCells:m,connectivitySeedNetIndices:f,traceBarriers:h,gridCells:c,traceClearance:r,gridPitch:o}),Bwo(C,p,A),l.push(C)}return{...t,labeledLayers:l}},IRt=t=>{const{labels:e,nx:n,ny:o}=t,i=new Int32Array(n*o).fill(-1),r=[],s=[];for(let a=0;a<n*o;a++){if(i[a]!==-1||e[a]<0)continue;const A=e[a],c=[];for(i[a]=r.length,s.push(a);s.length>0;){const l=s.pop();c.push(l);const u=l%n,g=Math.floor(l/n),h=[];u>0&&h.push(l-1),u<n-1&&h.push(l+1),g>0&&h.push(l-n),g<o-1&&h.push(l+n);for(const d of h)i[d]===-1&&e[d]===A&&(i[d]=r.length,s.push(d))}r.push({netIndex:A,cells:c})}return{component:i,regions:r}},Ewo=t=>IRt(t).regions,Bwo=(t,e,n)=>{if(!(n<=1))for(;;){const{component:o,regions:i}=IRt(t),r=[];for(const s of i){if(s.cells.length>=n||s.cells.some(c=>e[c]===1))continue;const a=new Map;for(const c of s.cells){const l=c%t.nx,u=Math.floor(c/t.nx),g=[];l>0&&g.push(c-1),l<t.nx-1&&g.push(c+1),u>0&&g.push(c-t.nx),u<t.ny-1&&g.push(c+t.nx);for(const h of g){const d=o[h];d<0||i[d]===s||a.set(d,(a.get(d)??0)+1)}}const A=[...a.entries()].map(([c,l])=>({region:i[c],sharedEdges:l})).filter(c=>c.region.cells.length>s.cells.length).sort((c,l)=>l.sharedEdges-c.sharedEdges||l.region.cells.length-c.region.cells.length)[0]?.region;A&&r.push({cells:s.cells,netIndex:A.netIndex})}if(r.length===0)return;for(const s of r)for(const a of s.cells)t.labels[a]=s.netIndex}},bwo=(t,e)=>{const n=new Set(t),o=[],i=[];for(;n.size>0;){const r=n.values().next().value,s=[];for(n.delete(r),i.push(r);i.length>0;){const a=i.pop();s.push(a);const A=a%e,c=[a-e,a+e];A>0&&c.push(a-1),A<e-1&&c.push(a+1);for(const l of c)n.has(l)&&(n.delete(l),i.push(l))}o.push(s)}return o},CRt=t=>Math.abs(t.reduce((e,n,o)=>{const i=t[(o+1)%t.length];return e+n[0]*i[1]-i[0]*n[1]},0)/2),Swo=(t,e)=>{const n=[t],o=[];for(;n.length>0;){const i=n.pop(),r=fRt(i,e);if(r.length<=1){o.push(i);continue}const s=r.reduce((h,d,p)=>CRt(d)>CRt(r[h])?p:h,0),A=r.find((h,d)=>d!==s).map(h=>h[1]),c=Math.round((Math.min(...A)+Math.max(...A))/2),l=i.filter(h=>Math.floor(h/e)<c),u=i.filter(h=>Math.floor(h/e)>=c),g=[l,u].filter(h=>h.length>0).flatMap(h=>bwo(h,e));if(g.length<2||g.some(h=>h.length===i.length))throw new Error("Unable to split an implicit copper region around a hole");n.push(...g)}return o},yRt=t=>t.replace(/[^a-zA-Z0-9_]+/g,"_"),Qwo=t=>{const e=[],n=Math.max(1,Math.round(t.minRegionArea/t.gridPitch**2)),o=D0(M0(t.bounds.minX,t.bounds.minY),FV(t.gridPitch));for(const i of t.labeledLayers){const r=Ewo(i);for(const[s,a]of r.entries()){const A=t.nets[a.netIndex];if(!A?.isPower||a.cells.length<n)continue;const c=Swo(a.cells,i.nx);for(const[l,u]of c.entries()){const g=fRt(u,i.nx);if(g.length!==1)throw new Error("Implicit copper region part must have one outline");const d=g[0].map(([p,m])=>{const _=ts(o,{x:p,y:m});return{x:fp(_.x,t.bounds.minX,t.bounds.maxX),y:fp(_.y,t.bounds.minY,t.bounds.maxY)}});e.push({type:"pcb_copper_pour",pcb_copper_pour_id:`pcb_copper_pour_${yRt(i.layer)}_${yRt(A.sourceNet.source_net_id)}_${s}_${l}`,shape:"polygon",layer:i.layer,source_net_id:A.sourceNet.source_net_id,covered_with_solder_mask:t.coveredWithSolderMask,subcircuit_id:A.sourceNet.subcircuit_id,points:d})}}}return e},xRt=t=>t==="top"?"#c2453a":t==="bottom"?"#5b7fd8":"#c58b43",vwo=.25,wwo=.2,Pwo=0,Mwo=.5,Dwo=t=>{if(t.outline&&t.outline.length>=3)return t.outline;if(t.width===void 0||t.height===void 0)throw new Error("pcb_board must provide an outline or width and height");const e=Ey({center:t.center,width:t.width,height:t.height});return[{x:e.minX,y:e.minY},{x:e.maxX,y:e.minY},{x:e.maxX,y:e.maxY},{x:e.minX,y:e.maxY}]},ERt=(t,e)=>{const{layers:n,netIndex:o,x:i,y:r,width:s,height:a,rotation:A}=e,c=Math.min(s,a)/2,u=(Math.max(s,a)-c*2)/2,g=D0(M0(i,r),l3e(A+(a>s?90:0))),[h,d]=IRn(g,[{x:-u,y:0},{x:u,y:0}]);t.push({kind:"segment",layers:n,netIndex:o,x1:h.x,y1:h.y,x2:d.x,y2:d.y,halfWidth:c})},Nwo=(t,e,n)=>{const o=[e.layer];e.shape==="circle"?t.push({kind:"circle",layers:o,netIndex:n,x:e.x,y:e.y,radius:e.radius}):e.shape==="rect"||e.shape==="rotated_rect"?t.push({kind:"rect",layers:o,netIndex:n,x:e.x,y:e.y,halfWidth:e.width/2,halfHeight:e.height/2,rotation:e.shape==="rotated_rect"?e.ccw_rotation:0}):e.shape==="polygon"?t.push({kind:"polygon",layers:o,netIndex:n,points:e.points}):ERt(t,{layers:o,netIndex:n,x:e.x,y:e.y,width:e.width,height:e.height,rotation:e.shape==="rotated_pill"?e.ccw_rotation:0})},Rwo=(t,e,n)=>{const o=e.layers;if(e.shape==="circle")t.push({kind:"circle",layers:o,netIndex:n,x:e.x,y:e.y,radius:e.outer_diameter/2});else if(e.shape==="oval"||e.shape==="pill")ERt(t,{layers:o,netIndex:n,x:e.x,y:e.y,width:e.outer_width,height:e.outer_height,rotation:e.ccw_rotation});else if(e.shape==="hole_with_polygon_pad")t.push({kind:"polygon",layers:o,netIndex:n,points:e.pad_outline});else if("rect_pad_width"in e&&"rect_pad_height"in e){const i=e.shape==="circular_hole_with_rect_pad"?e.rect_ccw_rotation??0:e.shape==="rotated_pill_hole_with_rect_pad"?e.rect_ccw_rotation:0;t.push({kind:"rect",layers:o,netIndex:n,x:e.x,y:e.y,halfWidth:e.rect_pad_width/2,halfHeight:e.rect_pad_height/2,rotation:i})}},Two=(t,e,n)=>{let o=null;for(const i of e.route){if(i.route_type!=="wire"){o=null,i.route_type==="via"&&t.push({kind:"circle",layers:[i.from_layer,i.to_layer],netIndex:n,x:i.x,y:i.y,radius:.3});continue}o&&o.layer===i.layer&&t.push({kind:"segment",layers:[i.layer],netIndex:n,isTrace:!0,x1:o.x,y1:o.y,x2:i.x,y2:i.y,halfWidth:i.width/2}),o=i}},BRt=t=>{const e=t.gridPitch??vwo,n=t.traceClearance??wwo,o=t.edgeSimplificationTolerance??e,i=t.minRegionArea??Pwo,r=t.regionNormalizationArea??Mwo;if(!(e>0))throw new Error("gridPitch must be greater than zero");if(!Number.isFinite(n)||n<0)throw new Error("traceClearance must be zero or greater");if(!Number.isFinite(o)||o<0)throw new Error("edgeSimplificationTolerance must be zero or greater");if(!(i>=0))throw new Error("minRegionArea must be zero or greater");if(!(r>=0))throw new Error("regionNormalizationArea must be zero or greater");const s=t.circuitJson.find(E=>E.type==="pcb_board");if(!s)throw new Error("No pcb_board found in Circuit JSON");const a=Dwo(s),A=Oh(a),c=t.circuitJson.filter(E=>E.type==="source_net"),l=c.map(E=>({sourceNet:E,isPower:!!(E.is_power||E.is_ground||E.is_positive_voltage_source)})),u=new Map,g=new Map;for(const[E,B]of c.entries())u.set(B.source_net_id,E),B.subcircuit_connectivity_map_key&&g.set(B.subcircuit_connectivity_map_key,E);const h=new Map,d=(E,B=E)=>{const S=h.get(E);if(S!==void 0)return S;const Q=`source_net_implicit_${E.replace(/[^a-zA-Z0-9_]+/g,"_")}`;let w=Q,M=1;for(;u.has(w);)w=`${Q}_${M++}`;const k={type:"source_net",source_net_id:w,name:B,member_source_group_ids:[],is_ground:!1,is_power:!1,is_positive_voltage_source:!1},R=l.length;return l.push({sourceNet:k,isPower:!1}),u.set(w,R),h.set(E,R),R},p=E=>{const B=E.subcircuit_connectivity_map_key;if(!B)return;const S=g.get(B);if(S!==void 0)return S;const Q=d(`connectivity:${B}`,B);return g.set(B,Q),Q},m=Mxe(t.circuitJson),_=Object.values(m.netMap);for(const E of t.circuitJson){if(E.type==="source_trace"){_.push([E.source_trace_id,...E.connected_source_port_ids,...E.connected_source_net_ids]);continue}if(E.type==="pcb_port"){_.push([E.pcb_port_id,E.source_port_id]);continue}if(E.type==="pcb_smtpad"&&E.pcb_port_id){_.push([E.pcb_smtpad_id,E.pcb_port_id]);continue}if(E.type==="pcb_plated_hole"&&E.pcb_port_id){_.push([E.pcb_plated_hole_id,E.pcb_port_id]);continue}if(E.type==="pcb_trace"){const B=Array.from(new Set(E.route.flatMap(w=>w.route_type==="wire"?[w.start_pcb_port_id,w.end_pcb_port_id].filter(M=>!!M):[]))),S=E.source_net_id,Q=[...S?[S]:[],...B.length>0?B:E.source_trace_id?[E.source_trace_id]:[]];Q.length>0&&_.push([E.pcb_trace_id,...Q]);continue}if(E.type==="pcb_via"){const B=E,S=B.source_net_id??B.pcb_trace_id??B.source_trace_id;S&&_.push([B.pcb_via_id,S])}}const f=new wQ($ne(_)),I=new Map,C=E=>{const B=hz(E),S=f.getNetConnectedToId(B);if(S){const Q=c.flatMap((k,R)=>f.areIdsConnected(B,k.source_net_id)?[R]:[]);if(Q.length>1){const k=Q.map(R=>c[R].source_net_id);throw new Error(`Circuit JSON connectivity assigns ${B} to multiple source nets: ${k.join(", ")}`)}if(Q[0]!==void 0)return I.set(S,Q[0]),Q[0];const w=I.get(S);if(w!==void 0)return w;const M=p(E)??d(`connectivity-network:${S}`,S);return I.set(S,M),M}return p(E)},y=E=>{const B=E.source_net_id;if(B)return u.get(B)??d(`source-net-id:${B}`,B);const S=C(E);if(S!==void 0)return S;const Q=hz(E);return d(`${E.type}:${Q}`,Q)},x=[];for(const E of t.circuitJson){if(E.type!=="pcb_smtpad"&&E.type!=="pcb_plated_hole"&&E.type!=="pcb_via"&&E.type!=="pcb_trace")continue;const B=y(E);if(B!==void 0)if(E.type==="pcb_smtpad")Nwo(x,E,B);else if(E.type==="pcb_plated_hole")Rwo(x,E,B);else if(E.type==="pcb_via"){const S=E;x.push({kind:"circle",layers:S.layers,netIndex:B,x:S.x,y:S.y,radius:S.outer_diameter/2})}else E.type==="pcb_trace"&&Two(x,E,B)}return{bounds:A,boardOutline:a,layers:t.layers??["top","bottom"],nets:l,primitives:x,gridPitch:e,traceClearance:n,minRegionArea:i,regionNormalizationArea:r,coveredWithSolderMask:t.coveredWithSolderMask??!0}},xw=(t,e)=>t.x===e.x&&t.y===e.y,kwo=(t,e)=>{if(t.length<=2)return[...t];const n=new Uint8Array(t.length);n[0]=1,n[t.length-1]=1;const o=[[0,t.length-1]];for(;o.length>0;){const[i,r]=o.pop(),s=t[i],a=t[r];let A=-1,c=e;for(let l=i+1;l<r;l++){const u=Zd(t[l],s,a);u>c&&(c=u,A=l)}A!==-1&&(n[A]=1,o.push([i,A],[A,r]))}return t.filter((i,r)=>n[r]===1)},bRt=t=>{let e=0;for(let n=0;n<t.length;n++){const o=t[n],i=t[(n+1)%t.length];e+=o.x*i.y-i.x*o.y}return e/2},SRt=(t,e,n)=>(e.x-t.x)*(n.y-t.y)-(e.y-t.y)*(n.x-t.x),gMe=(t,e)=>{if(t.length<=2)return[...t];const n=t.map((r,s)=>s===0||s===t.length-1?0:Math.sign(SRt(t[s-1],t[s],t[s+1]))),o=[0];for(let r=1;r<t.length-1;r++){const s=n[r];if(s===0)continue;const a=s===n[r-1]||s===n[r+1],A=t[r-1],c=t[r],l=t[r+1],u=Math.min(ad(c,A),ad(l,c));(a||u>e)&&o.push(r)}o.push(t.length-1);const i=[];for(let r=0;r<o.length-1;r++){const s=o[r],a=o[r+1],A=kwo(t.slice(s,a+1),e);i.push(...r===0?A:A.slice(1))}return i},Fwo=t=>{for(let e=0;e<t.length;e++){const n=(e+1)%t.length;for(let o=e+1;o<t.length;o++){const i=(o+1)%t.length;if(!(e===o||e===i||n===o||n===i)&&X1(t[e],t[n],t[o],t[i]))return!1}}return!0},QRt=t=>{const e=t.filter((n,o)=>o===0||!xw(n,t[o-1]));return e.length>1&&xw(e[0],e[e.length-1])&&e.pop(),e},Lwo=(t,e,n)=>{if(xw(t,e)||xw(t,n))return!1;const o=SRt(e,n,t);return Math.abs(o)>1e-9?!1:CV(e,t,n)},Hwo=(t,e)=>{const n=[];for(let o=0;o<t.length;o++){const i=t[o],r=t[(o+1)%t.length],s=r.x-i.x,a=r.y-i.y,A=e.filter(c=>Lwo(c,i,r)).map(c=>({point:c,position:Math.abs(s)>=Math.abs(a)?(c.x-i.x)/s:(c.y-i.y)/a})).sort((c,l)=>c.position-l.position);n.push(i);for(const{point:c}of A)xw(n[n.length-1],c)||n.push(c)}return n},vRt=(t,e)=>{if(e.length<3)return!1;const n=bRt(t),o=bRt(e);return n!==0&&o!==0&&Math.sign(n)===Math.sign(o)&&Fwo(e)},Owo=(t,e)=>{const n=QRt(t);if(n.length<4||e<=0)return n;const o=[...n,n[0]],i=gMe(o,e);return xw(i[0],i[i.length-1])&&i.pop(),vRt(n,i)?i:n},dMe=t=>`${t.x},${t.y}`,Gwo=(t,e)=>{const n=dMe(t),o=dMe(e);return n<o?`${n}|${o}`:`${o}|${n}`},wRt=t=>t.map(dMe).join("|"),Ywo=t=>{const e=wRt(t),n=[...t].reverse(),o=wRt(n);return e<=o?{points:[...t],reversed:!1,key:e}:{points:n,reversed:!0,key:o}},Uwo=t=>{const e=new Map;for(const[o,i]of t.entries())for(let r=0;r<i.length;r++){const s=Gwo(i[r],i[(r+1)%i.length]),a=e.get(s)??[];a.push({polygonIndex:o,edgeIndex:r}),e.set(s,a)}const n=t.map((o,i)=>o.map(()=>`outer:${i}`));for(const o of e.values()){if(o.length!==2||o[0].polygonIndex===o[1].polygonIndex)continue;const i=o[0].polygonIndex,r=o[1].polygonIndex,s=i<r?`${i}:${r}`:`${r}:${i}`;for(const a of o)n[a.polygonIndex][a.edgeIndex]=`shared:${s}`}return n},Kwo=(t,e,n)=>{const o=[t[e]];let i=e;for(;i!==n;)o.push(t[(i+1)%t.length]),i=(i+1)%t.length;return o},Vwo=(t,e)=>{const n=[];for(const o of t.chains){const i=e.get(o.arcKey),r=i.disabled?i.original:i.simplified,s=o.reversed?[...r].reverse():r;if(n.length===0)n.push(...s);else if(xw(n[n.length-1],s[0]))n.push(...s.slice(1));else return[]}return n.length>1&&xw(n[0],n[n.length-1])&&n.pop(),n},zwo=(t,e)=>{const n=t.map(QRt),o=n.flat(),i=n.map(c=>Hwo(c,o));if(e<=0||i.length===0)return i;const r=Uwo(i),s=new Map,a=[];for(const[c,l]of i.entries()){if(l.length<4){a.push({original:l,mode:"fixed"});continue}const u=r[c],g=u.flatMap((d,p)=>u[(p+l.length-1)%l.length]===d?[]:[p]);if(g.length===0){u[0]?.startsWith("shared:")?a.push({original:l,mode:"fixed"}):a.push({original:l,mode:"standalone",simplified:Owo(l,e)});continue}const h=[];for(let d=0;d<g.length;d++){const p=g[d],m=g[(d+1)%g.length],_=Kwo(l,p,m),f=u[p];if(f.startsWith("shared:")){const I=Ywo(_),C=`${f}:${I.key}`;s.has(C)||s.set(C,{original:I.points,simplified:gMe(I.points,e),disabled:!1}),h.push({arcKey:C,reversed:I.reversed})}else{const I=`outer:${c}:${d}`;s.set(I,{original:_,simplified:gMe(_,e),disabled:!1}),h.push({arcKey:I,reversed:!1})}}a.push({original:l,mode:"chains",chains:h})}let A=i;for(let c=0;c<=s.size;c++){A=a.map(g=>g.mode==="fixed"?g.original:g.mode==="standalone"?g.simplified:Vwo(g,s));const l=A.flatMap((g,h)=>vRt(a[h].original,g)?[]:[h]);if(l.length===0)return A;let u=!1;for(const g of l){const h=a[g];if(h.mode==="chains")for(const d of h.chains){const p=s.get(d.arcKey);p.disabled||(p.disabled=!0,u=!0)}}if(!u)return A.map((g,h)=>l.includes(h)?a[h].original:g)}return i},Jwo="#555a66",Wwo="red",PRt="blue",jwo="rgba(255, 0, 0, 0.5)",$wo="rgba(0, 0, 255, 0.5)",qwo=.35,MRt=["#ed9148","#d93bd0","#b6df38","#438bd9","#e5485f","#43d16d","#8b48df","#e6b93f","#43ced2","#cf3d99"],Xwo=(t,e)=>{const n=Number.parseInt(t.slice(1,3),16),o=Number.parseInt(t.slice(3,5),16),i=Number.parseInt(t.slice(5,7),16);return`rgba(${n}, ${o}, ${i}, ${e})`},DRt=t=>{const e=t.map(n=>n==="top"?0:n==="bottom"?1:null).filter(n=>n!==null);return`z${Array.from(new Set(e)).join(",")}`},Zwo=t=>t.includes("top")?Wwo:PRt,ePo=t=>t.includes("top")?jwo:$wo,tPo=(t,e,n)=>{const o=t.nets[e]?.sourceNet;return`${o?.name??o?.source_net_id??"unknown net"} ${n}`},nPo=t=>{const e={coordinateSystem:"cartesian",title:"Circuit JSON copper obstacles",points:[],rects:[],circles:[],lines:[{points:[...t.boardOutline,t.boardOutline[0]],strokeColor:Jwo,strokeWidth:.08,label:"PCB outline"}],polygons:[],texts:[]};for(const n of t.primitives){const o=Zwo(n.layers),i=ePo(n.layers),r=DRt(n.layers),s=tPo(t,n.netIndex,n.kind);if(n.kind==="rect"){e.rects.push({center:{x:n.x,y:n.y},width:n.halfWidth*2,height:n.halfHeight*2,ccwRotationDegrees:n.rotation,fill:i,layer:r,label:s});continue}if(n.kind==="segment"){const A=n.layers.includes("top");e.lines.push({points:[{x:n.x1,y:n.y1},{x:n.x2,y:n.y2}],strokeColor:A?o:"rgba(0, 0, 255, 0.5)",strokeWidth:n.halfWidth*2,...A?{}:{strokeDash:[.2,.2]},layer:r,label:s});continue}if(n.kind==="polygon"){e.polygons.push({points:n.points,fill:i,stroke:o,strokeWidth:.04,layer:r,label:s});continue}const a=n.layers.includes("top")&&n.layers.includes("bottom");e.circles.push({center:{x:n.x,y:n.y},radius:n.radius,fill:a?PRt:i,stroke:"none",layer:r,label:s})}return e},oPo=(t,e)=>({coordinateSystem:"cartesian",title:"Power-net copper pour polygons",points:[],rects:[],circles:[],lines:[],polygons:e.flatMap(n=>{if(n.shape!=="polygon")return[];const o=t.nets.findIndex(({sourceNet:s})=>s.source_net_id===n.source_net_id),i=MRt[Math.max(0,o)%MRt.length],r=t.nets[o]?.sourceNet;return[{points:n.points,fill:Xwo(i,qwo),stroke:i,strokeWidth:.06,layer:DRt([n.layer]),label:`${r?.name??n.source_net_id??"power net"} ${n.layer} pour`}]}),texts:[]}),iPo=(t,e)=>({coordinateSystem:"cartesian",title:e.polygons?.length?e.title:t.title,polygons:[...e.polygons??[],...t.polygons??[]],rects:[...t.rects??[],...e.rects??[]],lines:[...t.lines??[],...e.lines??[]],circles:[...t.circles??[],...e.circles??[]],points:[...t.points??[],...e.points??[]],texts:[...t.texts??[],...e.texts??[]]}),rPo=class extends fC{constructor(t){super(),this.input=t}input;output;_step(){this.output=BRt(this.input),this.solved=!0}getOutput(){if(!this.output)throw new Error("Circuit JSON has not been prepared");return this.output}},sPo=class extends fC{constructor(t){super(),this.input=t}input;output;_step(){this.output=xwo(this.input),this.stats={layers:this.output.labeledLayers.length,samples:this.output.labeledLayers.reduce((t,e)=>t+e.nx*e.ny,0)},this.solved=!0}getOutput(){if(!this.output)throw new Error("Grid cells have not been assigned");return this.output}},aPo=class extends fC{constructor(t){super(),this.input=t}input;output;_step(){this.output=Qwo(this.input),this.stats={polygons:this.output.length},this.solved=!0}getOutput(){if(!this.output)throw new Error("Power polygons have not been traced");return this.output}visualize(){return{points:[],rects:[],circles:[],texts:[],lines:(this.output??[]).flatMap(t=>t.shape!=="polygon"?[]:[{points:[...t.points,t.points[0]],strokeColor:xRt(t.layer),strokeWidth:.08,label:t.source_net_id}])}}},APo=class extends fC{constructor(t){super(),this.input=t}input;output;_step(){let t=0,e=0;const n=[...this.input.pours],o=new Map;for(const[i,r]of this.input.pours.entries()){if(r.shape!=="polygon")continue;t+=r.points.length;const s=o.get(r.layer)??[];s.push(i),o.set(r.layer,s)}for(const i of o.values()){const r=zwo(i.map(s=>{const a=this.input.pours[s];return a.shape!=="polygon"?[]:a.points}),this.input.tolerance);for(const[s,a]of r.entries()){const A=i[s],c=this.input.pours[A];c.shape==="polygon"&&(n[A]={...c,points:a},e+=a.length)}}this.output=n,this.stats={polygons:this.output.length,inputPoints:t,outputPoints:e,pointsRemoved:t-e},this.solved=!0}getOutput(){if(!this.output)throw new Error("Polygon edges have not been simplified");return this.output}visualize(){return{points:[],rects:[],circles:[],texts:[],lines:(this.output??[]).flatMap(t=>t.shape!=="polygon"?[]:[{points:[...t.points,t.points[0]],strokeColor:xRt(t.layer),strokeWidth:.08,label:t.source_net_id}])}}},NRt=class extends eve{initialPreparedProblem;pipelineDef=[TH("prepareCircuitJson",rPo,t=>[t.inputProblem]),TH("assignGridCells",sPo,t=>[t.getStageOutput("prepareCircuitJson")]),TH("tracePowerPolygons",aPo,t=>[t.getStageOutput("assignGridCells")]),TH("simplifyPolygonEdges",APo,t=>{const e=t.getStageOutput("prepareCircuitJson");return[{pours:t.getStageOutput("tracePowerPolygons"),tolerance:t.inputProblem.edgeSimplificationTolerance??e.gridPitch}]})];getSolverName(){return"ImplicitCopperPourPipelineSolver"}getConstructorParams(){return[this.inputProblem]}getOutput(){return this.getStageOutput("simplifyPolygonEdges")??[]}visualize(){const t=this.getStageOutput("prepareCircuitJson")??(this.initialPreparedProblem??=BRt(this.inputProblem)),e=nPo(t),n=this.getStageOutput("simplifyPolygonEdges")??this.getStageOutput("tracePowerPolygons")??[];return iPo(e,oPo(t,n))}},hMe=1e-8,cPo=(t,e,n)=>{const o=(t.y-e.y)*(n.x-e.x)-(t.x-e.x)*(n.y-e.y);if(Math.abs(o)>hMe)return!1;const i=(t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y);if(i<-hMe)return!1;const r=(n.x-e.x)**2+(n.y-e.y)**2;return i<=r+hMe},RRt=(t,e)=>{let n=!1;for(let o=0,i=e.vertices.length-1;o<e.vertices.length;i=o++){const r=e.vertices[o],s=e.vertices[i];if(cPo(t,s,r))return!0;r.y>t.y!=s.y>t.y&&t.x<(s.x-r.x)*(t.y-r.y)/(s.y-r.y)+r.x&&(n=!n)}return n},lPo=(t,e)=>RRt(t,e.outer_ring)&&!e.inner_rings.some(n=>RRt(t,n)),uPo=(t,e)=>e.some(n=>lPo(t,n)),TRt=t=>{const e=t.flatMap(n=>n.outer_ring.vertices);if(e.length!==0)return{minX:Math.min(...e.map(n=>n.x)),maxX:Math.max(...e.map(n=>n.x)),minY:Math.min(...e.map(n=>n.y)),maxY:Math.max(...e.map(n=>n.y))}},kRt=({center:t,radius:e,shapes:n})=>{const o=[t];for(let i=0;i<32;i++){const r=i/32*Math.PI*2;o.push({x:t.x+Math.cos(r)*e,y:t.y+Math.sin(r)*e})}return o.every(i=>uPo(i,n))},pMe=(t,e)=>e.some(n=>String(n)===String(t)),gPo=t=>{if(!(t.do_not_place||!t.obstructs_within_bounds))return{kind:"rect",center:t.center,width:t.width,height:t.height,ccwRotation:t.rotation}},dPo=t=>t.shape==="circle"?{kind:"circle",center:{x:t.x,y:t.y},radius:t.radius}:t.shape==="polygon"?{kind:"polygon",points:t.points}:{kind:"rect",center:{x:t.x,y:t.y},width:t.width,height:t.height,ccwRotation:t.shape==="rotated_rect"||t.shape==="rotated_pill"?t.ccw_rotation:0},hPo=t=>{if(t.shape==="circle")return{kind:"circle",center:{x:t.x,y:t.y},radius:t.outer_diameter/2};if("outer_width"in t)return{kind:"rect",center:{x:t.x,y:t.y},width:t.outer_width,height:t.outer_height,ccwRotation:t.ccw_rotation};if(t.shape==="hole_with_polygon_pad"){const e=(t.ccw_rotation??0)*Math.PI/180,n=Math.cos(e),o=Math.sin(e);return{kind:"polygon",points:t.pad_outline.map(i=>({x:t.x+i.x*n-i.y*o,y:t.y+i.x*o+i.y*n}))}}return{kind:"rect",center:{x:t.x,y:t.y},width:t.rect_pad_width,height:t.rect_pad_height,ccwRotation:"rect_ccw_rotation"in t?t.rect_ccw_rotation??0:0}},pPo=t=>"hole_diameter"in t?t.hole_shape==="circle"?{kind:"circle",center:{x:t.x,y:t.y},radius:t.hole_diameter/2}:{kind:"rect",center:{x:t.x,y:t.y},width:t.hole_diameter,height:t.hole_diameter,ccwRotation:0}:{kind:"rect",center:{x:t.x,y:t.y},width:t.hole_width,height:t.hole_height,ccwRotation:t.hole_shape==="rotated_pill"?t.ccw_rotation:0},mPo=(t,e,n)=>{const o=n.x-e.x,i=n.y-e.y,r=o**2+i**2;if(r===0)return Math.hypot(t.x-e.x,t.y-e.y);const s=Math.max(0,Math.min(1,((t.x-e.x)*o+(t.y-e.y)*i)/r));return Math.hypot(t.x-(e.x+s*o),t.y-(e.y+s*i))},_Po=(t,e)=>{let n=!1;for(let o=0,i=e.length-1;o<e.length;i=o++){const r=e[o],s=e[i];r.y>t.y!=s.y>t.y&&t.x<(s.x-r.x)*(t.y-r.y)/(s.y-r.y)+r.x&&(n=!n)}return n},fPo=(t,e,n)=>{if(n.kind==="circle")return Math.hypot(t.x-n.center.x,t.y-n.center.y)<e+n.radius;if(n.kind==="polygon")return _Po(t,n.points)?!0:n.points.some((l,u)=>mPo(t,l,n.points[(u+1)%n.points.length])<e);const o=-n.ccwRotation*Math.PI/180,i=t.x-n.center.x,r=t.y-n.center.y,s=i*Math.cos(o)-r*Math.sin(o),a=i*Math.sin(o)+r*Math.cos(o),A=Math.max(Math.abs(s)-n.width/2,0),c=Math.max(Math.abs(a)-n.height/2,0);return Math.hypot(A,c)<e},IPo=(t,e)=>t.flatMap(n=>{if(n.type==="pcb_component"&&pMe(n.layer,e)){const o=gPo(n);return o?[o]:[]}return n.type==="pcb_smtpad"&&pMe(n.layer,e)?[dPo(n)]:n.type==="pcb_plated_hole"&&n.layers.some(o=>pMe(o,e))?[hPo(n)]:n.type==="pcb_hole"?[pPo(n)]:[]}),CPo=({center:t,radius:e,obstacles:n})=>n.some(o=>fPo(t,e,o)),yPo=(t={})=>{const e={sourceNetIds:t.sourceNetIds?new Set(t.sourceNetIds):void 0,layers:t.layers??["top","bottom"],viaStitchPitch:t.viaStitchPitch??1,viaHoleDiameter:t.viaHoleDiameter??.3,viaOuterDiameter:t.viaOuterDiameter??.6,pourEdgeClearance:t.pourEdgeClearance??.2,obstacleClearance:t.obstacleClearance??.2,minimumViaSeparation:t.minimumViaSeparation??Math.max(t.viaOuterDiameter??.6,.8),gridOrigin:t.gridOrigin??{x:0,y:0},isTented:t.isTented??!0};for(const[n,o]of[["viaStitchPitch",e.viaStitchPitch],["viaHoleDiameter",e.viaHoleDiameter],["viaOuterDiameter",e.viaOuterDiameter],["minimumViaSeparation",e.minimumViaSeparation]])if(!Number.isFinite(o)||o<=0)throw new Error(`${n} must be a finite number greater than zero`);if(!Number.isFinite(e.pourEdgeClearance)||e.pourEdgeClearance<0)throw new Error("pourEdgeClearance must be a finite non-negative number");if(!Number.isFinite(e.obstacleClearance)||e.obstacleClearance<0)throw new Error("obstacleClearance must be a finite non-negative number");if(!Number.isFinite(e.gridOrigin.x)||!Number.isFinite(e.gridOrigin.y))throw new Error("gridOrigin coordinates must be finite numbers");if(e.viaHoleDiameter>=e.viaOuterDiameter)throw new Error("viaHoleDiameter must be smaller than viaOuterDiameter");if(String(e.layers[0])===String(e.layers[1]))throw new Error("layers must contain two distinct PCB layers");return e},xPo=t=>t.type==="pcb_copper_pour"&&t.shape==="brep",EPo=(t,e)=>{const n=new Map(t.circuitJson.filter(a=>a.type==="source_net").map(a=>[a.source_net_id,a])),o=new Map;for(const a of t.circuitJson){if(!xPo(a)||!a.source_net_id||e.sourceNetIds&&!e.sourceNetIds.has(a.source_net_id))continue;const A=o.get(a.source_net_id)??[];A.push(a),o.set(a.source_net_id,A)}const[i,r]=e.layers,s=[];for(const[a,A]of o){const c=A.filter(u=>String(u.layer)===String(i)),l=A.filter(u=>String(u.layer)===String(r));c.length===0||l.length===0||s.push({sourceNetId:a,sourceNet:n.get(a),fromLayerPours:c,toLayerPours:l})}return s},BPo=(t,e)=>(t.outer_diameter??e*2)/2,bPo=({center:t,radius:e,occupiedVias:n,minimumViaSeparation:o})=>n.some(i=>Math.hypot(t.x-i.center.x,t.y-i.center.y)<Math.max(o,e+i.radius)),FRt=({minimum:t,maximum:e,origin:n,pitch:o})=>{const i=[],r=Math.ceil((t-n)/o),s=Math.floor((e-n)/o);for(let a=r;a<=s;a++)i.push(n+a*o);return i},LRt=class extends fC{constructor(t){super(),this.input=t,this.options=yPo(t.options),this.copperPourPairContexts=EPo(t,this.options),this.stitchingObstacles=IPo(t.circuitJson,this.options.layers);const e=this.options.viaOuterDiameter/2;for(const n of t.circuitJson)if(n.type==="pcb_via"){const o=n;this.existingPcbViaIds.add(o.pcb_via_id),this.occupiedVias.push({center:{x:o.x,y:o.y},radius:o.outer_diameter/2})}else if(n.type==="pcb_trace")for(const o of n.route)o.route_type==="via"&&this.occupiedVias.push({center:{x:o.x,y:o.y},radius:BPo(o,e)})}input;options;copperPourPairContexts;pcbVias=[];occupiedVias=[];existingPcbViaIds=new Set;stitchingObstacles;nextCopperPourPairIndex=0;nextViaId=0;_step(){const t=this.copperPourPairContexts[this.nextCopperPourPairIndex];if(!t){this.solved=!0,this.progress=1;return}this.processCopperPourPair(t),this.nextCopperPourPairIndex+=1,this.progress=this.copperPourPairContexts.length===0?1:this.nextCopperPourPairIndex/this.copperPourPairContexts.length,this.solved=this.nextCopperPourPairIndex===this.copperPourPairContexts.length}processCopperPourPair(t){const[e,n]=this.options.layers,o=t.fromLayerPours.map(h=>h.brep_shape),i=t.toLayerPours.map(h=>h.brep_shape),r=TRt(o),s=TRt(i);if(!r||!s)return;const a={minX:Math.max(r.minX,s.minX),maxX:Math.min(r.maxX,s.maxX),minY:Math.max(r.minY,s.minY),maxY:Math.min(r.maxY,s.maxY)};if(a.minX>a.maxX||a.minY>a.maxY)return;const A=this.options.viaOuterDiameter/2,c=A+this.options.pourEdgeClearance,l=A+this.options.obstacleClearance,u=FRt({minimum:a.minX+c,maximum:a.maxX-c,origin:this.options.gridOrigin.x,pitch:this.options.viaStitchPitch}),g=FRt({minimum:a.minY+c,maximum:a.maxY-c,origin:this.options.gridOrigin.y,pitch:this.options.viaStitchPitch});for(const h of g)for(const d of u){const p={x:d,y:h};if(bPo({center:p,radius:A,occupiedVias:this.occupiedVias,minimumViaSeparation:this.options.minimumViaSeparation})||CPo({center:p,radius:l,obstacles:this.stitchingObstacles})||!kRt({center:p,radius:c,shapes:o})||!kRt({center:p,radius:c,shapes:i}))continue;let m=`via_stitch_via_${this.nextViaId++}`;for(;this.existingPcbViaIds.has(m);)m=`via_stitch_via_${this.nextViaId++}`;const _=t.fromLayerPours[0],f={type:"pcb_via",pcb_via_id:m,x:d,y:h,hole_diameter:this.options.viaHoleDiameter,outer_diameter:this.options.viaOuterDiameter,layers:[e,n],from_layer:e,to_layer:n,source_net_id:t.sourceNetId,subcircuit_id:_.subcircuit_id,pcb_group_id:_.pcb_group_id,subcircuit_connectivity_map_key:t.sourceNet?.subcircuit_connectivity_map_key,is_tented:this.options.isTented};this.pcbVias.push(f),this.existingPcbViaIds.add(m),this.occupiedVias.push({center:p,radius:A})}}getOutput(){return{processedCopperPourPairCount:this.copperPourPairContexts.length,pcbVias:this.pcbVias}}},mMe={PackSolver2:rj,LayoutPipelineSolver:ZSt,AutoroutingPipelineSolver:F7t,AssignableAutoroutingPipeline2:ieo,AssignableAutoroutingPipeline3:Bno,AutoroutingPipeline1_OriginalUnravel:zZn,AutoroutingPipelineSolver3_HgPortPointPathing:Rno,AutoroutingPipelineSolver4:s9t,AutoroutingPipelineSolver5:$0o,AutoroutingPipelineSolver7_MultiGraph:F7t,AutoroutingPipelineSolver8:xgo,AutoroutingPipelineSolver9_PreloadedTraceGraph:X6t,AutoroutingPipelineSolver9_Networked:s8t,AutoroutingPipelineSolver11_Simplification:hho,CopperPourPipelineSolver:Rbt,CreateFdmEnclosureSolver:Vbt,FanoutSolver:Sue,ImplicitCopperPourPipelineSolver:NRt,SchematicTracePipelineSolver:Ewt,ViaStitchSolver:LRt},SPo="capacity-autorouter:",HRt=new WeakMap;function _Me(t){return typeof t=="object"&&t!==null&&"then"in t&&typeof t.then=="function"}function ORt(t){return t.constructor.name==="AsyncFunction"}var QPo=class{constructor(t){this.localCacheEngine=t,this.isSyncCache=!ORt(t.getItem)&&!ORt(t.setItem)}localCacheEngine;isSyncCache;cacheHits=0;cacheMisses=0;cacheHitsByPrefix={};cacheMissesByPrefix={};knownCacheKeys=new Set;getCachedSolutionSync(t){if(this.isSyncCache){this.knownCacheKeys.add(t);try{const e=this.localCacheEngine.getItem(this.getLocalCacheEngineKey(t));if(_Me(e)){this.isSyncCache=!1,Promise.resolve(e).catch(()=>{}),this.recordCacheMiss(t);return}return this.parseCachedItem(t,e)}catch{this.recordCacheMiss(t);return}}}async getCachedSolution(t){this.knownCacheKeys.add(t);try{const e=await this.localCacheEngine.getItem(this.getLocalCacheEngineKey(t));return this.parseCachedItem(t,e)}catch{this.recordCacheMiss(t);return}}setCachedSolutionSync(t,e){if(this.isSyncCache){this.knownCacheKeys.add(t);try{const n=JSON.stringify(e);if(n===void 0)return;const o=this.localCacheEngine.setItem(this.getLocalCacheEngineKey(t),n);_Me(o)&&(this.isSyncCache=!1,Promise.resolve(o).catch(()=>{}))}catch{}}}async setCachedSolution(t,e){this.knownCacheKeys.add(t);try{const n=JSON.stringify(e);if(n===void 0)return;await this.localCacheEngine.setItem(this.getLocalCacheEngineKey(t),n)}catch{}}getAllCacheKeys(){return[...this.knownCacheKeys]}clearCache(){for(const t of this.knownCacheKeys){const e=this.getLocalCacheEngineKey(t);try{const n=this.localCacheEngine.removeItem?this.localCacheEngine.removeItem(e):this.localCacheEngine.setItem(e,"null");_Me(n)&&Promise.resolve(n).catch(()=>{})}catch{}}this.knownCacheKeys.clear(),this.cacheHits=0,this.cacheMisses=0,this.cacheHitsByPrefix={},this.cacheMissesByPrefix={}}getLocalCacheEngineKey(t){return`${SPo}${t}`}parseCachedItem(t,e){if(e===null){this.recordCacheMiss(t);return}try{const n=JSON.parse(e);if(n===null){this.recordCacheMiss(t);return}return this.recordCacheHit(t),n}catch{this.recordCacheMiss(t);return}}recordCacheHit(t){this.cacheHits++;const e=t.split(":")[0];this.cacheHitsByPrefix[e]=(this.cacheHitsByPrefix[e]??0)+1}recordCacheMiss(t){this.cacheMisses++;const e=t.split(":")[0];this.cacheMissesByPrefix[e]=(this.cacheMissesByPrefix[e]??0)+1}};function vPo(t){let e=HRt.get(t);return e||(e=new QPo(t),HRt.set(t,e)),e}var GRt=({useAssignableSolver:t=!1,useAutoJumperSolver:e=!1,autorouterVersion:n,useLaserPrefabSolver:o=!1,useTraceSimplificationSolver:i=!1,platformConfig:r,effort:s})=>{const a=r?.useCloudAutorouter&&(s===void 0||s===1)?"AutoroutingPipelineSolver9_Networked":"AutoroutingPipelineSolver9_PreloadedTraceGraph";return i?"AutoroutingPipelineSolver11_Simplification":n==="beta_pipeline1"?"AutoroutingPipeline1_OriginalUnravel":n==="beta_pipeline3"?"AutoroutingPipelineSolver3_HgPortPointPathing":n==="beta_pipeline4"?"AutoroutingPipelineSolver4":n==="beta_pipeline5"?"AutoroutingPipelineSolver5":n==="beta_pipeline7"?"AutoroutingPipelineSolver7_MultiGraph":n==="beta_pipeline9"||n==="latest"?a:o?"AutoroutingPipelineSolver8":e?"AssignableAutoroutingPipeline3":t?"AssignableAutoroutingPipeline2":a};function wPo(t){return t?.localCacheEngine?vPo(t.localCacheEngine):null}var PPo=class{input;isRouting=!1;solver;eventHandlers={complete:[],error:[],progress:[]};cycleCount=0;stepDelay;timeoutId;constructor(t,e={}){this.input=t;const{capacityDepth:n,targetMinCapacity:o,stepDelay:i=0,useAssignableSolver:r=!1,useAutoJumperSolver:s=!1,autorouterVersion:a,useLaserPrefabSolver:A=!1,useTraceSimplificationSolver:c=!1,effort:l,platformConfig:u,onSolverStarted:g}=e,h=GRt({useAssignableSolver:r,useAutoJumperSolver:s,autorouterVersion:a,useLaserPrefabSolver:A,useTraceSimplificationSolver:c,platformConfig:u,effort:l}),d=wPo(u),p={capacityDepth:n,targetMinCapacity:o,cacheProvider:d,effort:l};this.solver=h==="AutoroutingPipelineSolver9_Networked"?new s8t(t,{...p,effort:1}):new mMe[h](t,p),g?.({solverName:h,solverParams:{input:t,options:{capacityDepth:n,targetMinCapacity:o,cacheProvider:d,effort:l}}}),this.stepDelay=i}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}async stepSolver(){if("stepAsync"in this.solver&&typeof this.solver.stepAsync=="function"){await this.solver.stepAsync();return}this.solver.step()}async runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new Oj(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimplifiedPcbTraces()}),this.isRouting=!1;return}const t=Date.now(),e=this.solver.iterations;for(;Date.now()-t<250&&!this.solver.failed&&!this.solver.solved;)await this.stepSolver();const n=(this.solver.iterations-e)/(Date.now()-t)*1e3;this.cycleCount++;const o=this.solver?.preview()||void 0,i=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:i,phase:"getCurrentPhase"in this.solver?this.solver.getCurrentPhase():this.solver.activeSubSolver?.getSolverName()??this.solver.getSolverName(),debugGraphics:o}),this.stepDelay>0?this.timeoutId=setTimeout(()=>{this.runCycleAndQueueNextCycle()},this.stepDelay):this.timeoutId=setTimeout(()=>{this.runCycleAndQueueNextCycle()},0)}catch(t){this.emitEvent({type:"error",error:t instanceof Error?new Oj(t.message):new Oj(String(t))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(t,e){t==="complete"?this.eventHandlers.complete.push(e):t==="error"?this.eventHandlers.error.push(e):t==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(t){if(t.type==="complete")for(const e of this.eventHandlers.complete)e(t);else if(t.type==="error")for(const e of this.eventHandlers.error)e(t);else if(t.type==="progress")for(const e of this.eventHandlers.progress)e(t)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Oj(this.solver.error||"Routing failed");return this.solver.getOutputSimplifiedPcbTraces()}getConnectedOffboardObstacles(){return"getConnectedOffboardObstacles"in this.solver?this.solver.getConnectedOffboardObstacles():{}}},YRt=(t,e)=>({name:t,cacheable:!0,getSolverName:n=>GRt({...n,...e}),create:({simpleRouteJson:n,commonAutorouterOptions:o,onSolverStarted:i})=>new PPo(n,{...o,...e,onSolverStarted:r=>i?.({...r,solverConstructorArgs:[r.solverParams]})})}),MPo=YRt("tscircuit",{}),DPo=YRt("tscircuit_simplify",{useTraceSimplificationSolver:!0}),URt=t=>({name:t,cacheable:!1,followUpAutorouter:"default",getSolverName:()=>"FanoutSolver",create:({simpleRouteJson:e,busFanoutDirections:n,fanoutBounds:o,fanoutRoutingLayers:i,allowBlindAndBuriedVias:r,componentNamesById:s,onSolverStarted:a})=>new aMe(e,{mode:t,busFanoutDirections:n,fanoutBounds:o,fanoutRoutingLayers:i,allowBlindAndBuriedVias:r,componentNamesById:s,onSolverStarted:a})}),NPo=new Map([["single_layer_fanout",URt("single_layer_fanout")],["fanout",URt("fanout")],["simplify",DPo]]),KRt=t=>NPo.get(t??"")??MPo,RPo=(t,e)=>{const n=KRt(t.preset),o=[{autorouterConfig:t,strategy:n,usesPreviousStageOutput:!1}];if(n.followUpAutorouter){const i=h$(n.followUpAutorouter,e);o.push({autorouterConfig:i,strategy:KRt(i.preset),usesPreviousStageOutput:!0})}return o},TPo=({circuitJson:t,editEvents:e,manualEditsFile:n})=>{const o={...n,pcb_placements:[...n.pcb_placements??[]]};for(const i of e)if(i.edit_event_type==="edit_pcb_component_location"){const{pcb_component_id:r,new_center:s}=i,a=Mr(t).pcb_component.get(r);if(!a)continue;const A=Mr(t).source_component.get(a.source_component_id);if(!A)continue;const c=o.pcb_placements?.findIndex(u=>u.selector===A.name),l={selector:A.name,center:s,relative_to:"group_center"};c>=0?o.pcb_placements[c]=l:o.pcb_placements.push(l)}return o},kPo=({circuitJson:t,editEvents:e,manualEditsFile:n})=>{const o={...n,schematic_placements:[...n.schematic_placements??[]]};for(const i of e)if(i.edit_event_type==="edit_schematic_component_location"){const{schematic_component_id:r,new_center:s}=i,a=Mr(t).schematic_component.get(r);if(!a||!a.source_component_id)continue;const A=Mr(t).source_component.get(a.source_component_id);if(!A)continue;const c=o.schematic_placements?.findIndex(u=>u.selector===A.name),l={selector:A.name,center:s,relative_to:"group_center"};c>=0?o.schematic_placements[c]=l:o.schematic_placements.push(l)}return o},VRt=({circuitJson:t,editEvents:e,manualEditsFile:n})=>{const o=e.filter(s=>s.edit_event_type==="edit_schematic_component_location"),i=e.filter(s=>s.edit_event_type==="edit_pcb_component_location");let r=n;return o.length>0&&(r=kPo({circuitJson:t,editEvents:o,manualEditsFile:r})),i.length>0&&(r=TPo({circuitJson:t,editEvents:i,manualEditsFile:r})),r},FPo=class extends Ir{get config(){return{componentName:"Bus",zodProps:wPn}}},LPo=(t,e)=>{const{db:n}=t.root,o=t.getSubcircuit(),r=n.source_trace.list().filter(c=>c.subcircuit_id===o.subcircuit_id).filter(c=>c.name===e),s=new Set;if(r.length>0)for(const c of r)c.subcircuit_connectivity_map_key&&s.add(c.subcircuit_connectivity_map_key);else{const c=o.selectOne(e,{type:"port"});if(c?.source_port_id){const l=n.source_port.get(c.source_port_id);l?.subcircuit_connectivity_map_key&&s.add(l.subcircuit_connectivity_map_key)}}if(s.size!==1)return;const a=s.values().next().value;return a?{sourcePorts:n.source_port.list().filter(c=>c.subcircuit_connectivity_map_key===a),sourceTraceName:r.length>0?e:void 0}:void 0},HPo=t=>t.length<=1?t.join(""):t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t.at(-1)}`,OPo=(t,e)=>{let n;if(t.source_component_id&&(n=e.get(t.source_component_id)),!n?.name)return t.source_port_id;const o=t.most_frequently_referenced_by_name??t.name;return`.${n.name} > .${o}`},GPo=({differentialPairName:t,connectionPolarity:e,connectionSelector:n,sourceTraceName:o,terminalPinSelectors:i})=>{const r=HPo(i),s=r?`: ${r}`:"";return o&&i.length>2?`Differential pair "${t}" ${e}Connection uses the ambiguous trace name "${o}": its connection has more than 2 terminal pins${s}.`:`Differential pair "${t}" ${e}Connection="${n}" is not point-to-point: expected exactly 2 terminal pins, found ${i.length}${s}.`},YPo=t=>{const{db:e}=t.root,n=new Map;for(const o of e.source_component.list())n.set(o.source_component_id,{name:o.name});for(const o of["positive","negative"]){let i=t._parsedProps.negativeConnection;o==="positive"&&(i=t._parsedProps.positiveConnection);const r=LPo(t,i);if(!r)continue;const s=r.sourcePorts;if(s.length===2)continue;let a="";const A=s[0];if(A){if(!A.source_component_id)throw new Error(`Differential pair "${t.name}" resolved terminal port "${A.source_port_id}" without a source_component_id`);a=A.source_component_id}const c=s.map(l=>OPo(l,n)).sort((l,u)=>l.localeCompare(u));e.source_property_ignored_warning.insert({source_component_id:a,property_name:`${o}Connection`,error_type:"source_property_ignored_warning",message:GPo({differentialPairName:t.name,connectionPolarity:o,connectionSelector:i,sourceTraceName:r.sourceTraceName,terminalPinSelectors:c}),subcircuit_id:t.getSubcircuit().subcircuit_id??void 0})}},UPo=class extends Ir{get config(){return{componentName:"DifferentialPair",zodProps:PPn}}doInitialSourceDesignRuleChecks(){YPo(this)}},zRt=t=>{const e={...t.bounds};for(const n of t.connections)if(!n.isOffBoard)for(const o of n.pointsToConnect)e.minX=Math.min(e.minX,o.x),e.maxX=Math.max(e.maxX,o.x),e.minY=Math.min(e.minY,o.y),e.maxY=Math.max(e.maxY,o.y);return e},KPo=({bus:t,busSourceTraces:e,traceNameOrPortSelector:n})=>{const o=e.filter(A=>A.name===n),r=(o.length===0?t.getSubcircuit().selectOne(n,{type:"port"}):null)?.source_port_id??void 0,s=r?e.filter(A=>A.connected_source_port_ids.includes(r)):o;if(s.length===0)throw new Error(`Could not find source trace for trace name or port selector "${n}" in bus "${t.name}"`);if(s.length>1)throw new Error(`Trace name or port selector "${n}" matches multiple source traces in bus "${t.name}"`);return s[0].source_trace_id},VPo=({srjConnections:t,bus:e,sourceTraceId:n,traceNameOrPortSelector:o})=>{const i=t.filter(r=>r.source_trace_id===n);if(i.length===0)throw new Error(`Could not find an SRJ connection for "${o}" in bus "${e.name}"`);return i.map(r=>r.name)},zPo=t=>t.trim().replace(/^net\./,"").replace(/^\./,""),JPo=({fanoutPourNetMap:t,sourceNets:e,sourceTraces:n,subcircuitId:o})=>{const i=new Map;if(!t)return i;const r=new Map;for(const[s,a]of Object.entries(t)){const A=Array.isArray(a)?a:[a];for(const c of A){const l=zPo(c);for(const u of e){if(u.name!==l)continue;const g=r.get(u.source_net_id);if(g&&g!==s)throw new Error(`Fanout plane net "${l}" maps to multiple layers ("${g}" and "${s}"); use fanoutPourNetMap to select one`);r.set(u.source_net_id,s)}}}for(const s of n){if(o&&s.subcircuit_id!==o||s.connected_source_port_ids.length!==1)continue;const a=new Set((s.connected_source_net_ids??[]).map(c=>r.get(c)).filter(c=>c!==void 0));if(a.size>1)throw new Error(`Source trace "${s.name??s.source_trace_id}" connects to fanout planes on multiple layers`);const A=a.values().next().value;A&&i.set(s.source_trace_id,A)}return i},WPo=({srjConnections:t,buses:e,sourceTraces:n,subcircuitId:o,planeTerminatedSourceTraceLayers:i})=>{const r=[];for(const A of e){const c=A.getSubcircuit().subcircuit_id;if(o&&c!==o)continue;const l=n.filter(g=>g.subcircuit_id===c),u=A._parsedProps.connections.flatMap(g=>{const h=KPo({bus:A,busSourceTraces:l,traceNameOrPortSelector:g});return VPo({srjConnections:t,bus:A,sourceTraceId:h,traceNameOrPortSelector:g})});if(new Set(u).size!==u.length)throw new Error(`Bus "${A.name}" resolves multiple entries to one trace`);r.push({busId:A.name,name:A.name,connectionNames:u,...A._parsedProps.maxLengthSkew!==void 0?{maxLengthSkew:A._parsedProps.maxLengthSkew}:{},...A._parsedProps.pcbTraceWidth!==void 0?{traceWidth:A._parsedProps.pcbTraceWidth}:{},...A._parsedProps.pcbAllowedLayers!==void 0?{allowedLayers:A._parsedProps.pcbAllowedLayers}:{},...A._parsedProps.preferredLayer!==void 0?{preferredLayer:A._parsedProps.preferredLayer}:{},...A._parsedProps.preferredLayers!==void 0?{preferredLayers:A._parsedProps.preferredLayers}:{}})}const s=[];for(const[A,c]of i??[]){const l=n.find(h=>h.source_trace_id===A),u=t.find(h=>h.source_trace_id===A);if(!l||!u)continue;const g=l.name??l.source_trace_id;if([...r,...s].some(h=>h.busId===g))throw new Error(`Fanout plane trace "${g}" conflicts with an existing bus name`);s.push({busId:g,name:g,connectionNames:[u.name],termination:{type:"plane",layer:c}})}const a=[...s,...r];return a.length>0?a:void 0},jPo=(t,e)=>t.filter(n=>n.name===e),$Po=(t,e)=>t.filter(n=>n.connected_source_port_ids.includes(e)),JRt=({differentialPair:t,differentialPairSourceTraces:e,traceNameOrPortSelector:n})=>{const o=t.getSubcircuit(),i=jPo(e,n),s=(i.length===0?o.selectOne(n,{type:"port"}):null)?.source_port_id??void 0,a=s?$Po(e,s):i;if(a.length===0)throw new Error(`Could not find source trace for trace name or port selector "${n}" in differential pair "${t.name}"`);if(a.length>1)throw new Error(`Trace name or port selector "${n}" matches multiple source traces for differential pair "${t.name}"`);const A=a[0];if(!A)throw new Error(`Expected one source trace for trace name or port selector "${n}" in differential pair "${t.name}"`);const c=A.subcircuit_connectivity_map_key;if(!c)throw new Error(`Source trace "${A.source_trace_id}" does not have a subcircuit connectivity map key for differential pair "${t.name}"`);return c},WRt=({srjConnections:t,differentialPairName:e,differentialPairSourceTraces:n,traceSubcircuitConnectivityMapKey:o,traceNameOrPortSelector:i})=>{const r=[],s=new Set;for(const c of n)if(c.subcircuit_connectivity_map_key===o){r.push(c.source_trace_id);for(const l of c.connected_source_net_ids??[])s.add(l)}const a=[];for(const c of t)(s.has(c.name)||c.source_trace_id&&r.includes(c.source_trace_id))&&a.push(c);if(a.length===0)throw new Error(`Could not find an SRJ connection for trace name or port selector "${i}" in differential pair "${e}"`);const A=new Map;for(const c of a){const l=c.routingPcbGroupId;if(A.has(l)){const u=l===void 0?"the global routing cohort":`routing PCB group "${l}"`;throw new Error(`Subcircuit connectivity map key "${o}" matches multiple SRJ connections in ${u} for differential pair "${e}"`)}A.set(l,c.name)}return A},jRt=t=>t===void 0?"the global routing cohort":`routing PCB group "${t}"`,qPo=({srjConnections:t,differentialPairs:e,sourceTraces:n,subcircuitId:o})=>{const i=[];for(const r of e){const s=r.getSubcircuit().subcircuit_id;if(o&&s!==o)continue;const a=n.filter(p=>p.subcircuit_id===s),A=r._parsedProps.positiveConnection,c=r._parsedProps.negativeConnection,l=JRt({differentialPair:r,differentialPairSourceTraces:a,traceNameOrPortSelector:A}),u=JRt({differentialPair:r,differentialPairSourceTraces:a,traceNameOrPortSelector:c}),g=WRt({srjConnections:t,differentialPairName:r.name,differentialPairSourceTraces:a,traceSubcircuitConnectivityMapKey:l,traceNameOrPortSelector:A}),h=WRt({srjConnections:t,differentialPairName:r.name,differentialPairSourceTraces:a,traceSubcircuitConnectivityMapKey:u,traceNameOrPortSelector:c}),d=r._parsedProps.maxLengthSkew??.1;for(const p of g.keys())if(!h.has(p))throw new Error(`Differential pair "${r.name}" has a positive SRJ connection in ${jRt(p)} without a matching negative SRJ connection`);for(const p of h.keys())if(!g.has(p))throw new Error(`Differential pair "${r.name}" has a negative SRJ connection in ${jRt(p)} without a matching positive SRJ connection`);for(const[p,m]of g){const _=h.get(p);i.push({connectionNames:[m,_],lengthTolerance:d,...r._parsedProps.pcbTraceGap!==void 0?{traceGap:r._parsedProps.pcbTraceGap}:{},...r._parsedProps.maxUncoupledLength!==void 0?{maxUncoupledLength:r._parsedProps.maxUncoupledLength}:{}})}}return i.length>0?i:void 0},p$=t=>typeof t=="string"?t:t.name,XPo=t=>t.source_trace_id??t.connection_name??t.pcb_trace_id,ZPo=t=>{const e=new Set(t.connectsTo??[]);for(const n of t.route)if(n.route_type==="wire")for(const o of[n.start_pcb_port_id,n.end_pcb_port_id])o&&e.add(o);return Array.from(e)},eMo=t=>t.route.map(e=>{if(e.route_type==="wire")return{route_type:"wire",x:e.x,y:e.y,width:e.width,layer:p$(e.layer)};if(e.route_type==="via"){const n=e,o=n.outer_diameter??n.via_diameter,i=n.hole_diameter??n.via_hole_diameter;return{route_type:"via",x:e.x,y:e.y,from_layer:p$(e.from_layer),to_layer:p$(e.to_layer),...o!==void 0?{via_diameter:o}:{},...i!==void 0?{via_hole_diameter:i}:{}}}return{route_type:"through_obstacle",start:e.start,end:e.end,from_layer:p$(e.start_layer),to_layer:p$(e.end_layer),width:e.width}}),tMo=({scopedDb:t,relevantSubcircuitIds:e})=>t.pcb_trace.list().filter(n=>!n.subcircuit_id||n.pcb_component_id&&!n.source_trace_id?!1:e===null||e.has(n.subcircuit_id)).map(n=>{const o=n,i=XPo(o);return{type:"pcb_trace",pcb_trace_id:n.pcb_trace_id,source_trace_id:n.source_trace_id,connection_name:i,connectsTo:ZPo(o),route:eMo(o)}}).filter(n=>n.route.length>=2),nMo=.5,oMo=t=>Array.from(new Set(t.filter(e=>!!e))),iMo=t=>typeof t=="string"?t:t.name,$Rt=({layer:t,connectedTo:e,center:n,width:o,height:i})=>({type:"rect",layers:[t],center:n,width:o,height:i,connectedTo:e,isCopperPour:!0}),rMo=({outline:t,group:e,board:n})=>t&&t.length>=3?t:e?.outline&&e.outline.length>=3?e.outline:n?.outline&&n.outline.length>=3?n.outline:null,sMo=({group:t,board:e})=>t?.width&&t.height?{center:t.center,width:t.width,height:t.height}:e?.width&&e.height?{center:e.center,width:e.width,height:e.height}:null,aMo=(t,e)=>oMo([t.source_net_id,t.subcircuit_connectivity_map_key,t.source_net_id?e.getNetConnectedToId(t.source_net_id):null]),AMo=({connMap:t,subcircuitComponent:e,board:n,group:o})=>{if(!e)return[];const i=[],r=e.selectAll("copperpour");for(const s of r){const a=s._parsedProps;if(!a.unbroken)continue;const A=s.getSubcircuit().selectOne(a.connectsTo);if(!A?.source_net_id)continue;const c=iMo(a.layer),l=aMo(A,t);if(l.length===0)continue;const u=rMo({outline:a.outline,group:o,board:n});if(u){const h=Gwe(u,{rectHeight:nMo});if(h.length>0){i.push(...h.map(d=>$Rt({layer:c,connectedTo:l,center:d.center,width:d.width,height:d.height})));continue}}const g=sMo({group:o,board:n});g&&i.push($Rt({layer:c,connectedTo:l,center:g.center,width:g.width,height:g.height}))}return i},cMo=(t,e)=>{const n=new Set;let o=e,i=!0;for(;o&&!n.has(o);){n.add(o);const r=t.source_group.getWhere({subcircuit_id:o}),s=r?t.source_board.getWhere({source_group_id:r.source_group_id}):void 0;if(s)return{board:t.pcb_board.getWhere({source_board_id:s.source_board_id})??null,subcircuitIsBoard:i};o=r?.parent_subcircuit_id??null,i=!1}return{board:null,subcircuitIsBoard:!1}},fMe=({db:t,circuitJson:e,subcircuit_id:n,minTraceWidth:o,minTraceToPadEdgeClearance:i,minViaEdgeToPadEdgeClearance:r,minViaHoleEdgeToViaHoleEdgeClearance:s,minPlatedHoleDrillEdgeToDrillEdgeClearance:a,minPadEdgeToPadEdgeClearance:A,minBoardEdgeClearance:c,minViaHoleDiameter:l,minViaPadDiameter:u,nominalTraceWidth:g,subcircuitComponent:h,routingPcbGroupId:d,fanoutPourNetMap:p,ignoreExistingTopLevelPcbRouteState:m=!1})=>{if(!t&&e&&(t=Mr(e)),!t)throw new Error("db or circuitJson is required");const _=t.pcb_trace_hint.list(),f=n?new Set([n]):null;if(n){const it=uPe(t,n);for(const Yt of it)f.add(Yt)}const I=(e??t.toArray()).filter(it=>!n||"subcircuit_id"in it&&f.has(it.subcircuit_id));let C=null,y=!1;if(n){const it=cMo(t,n);C=it.board,y=it.subcircuitIsBoard&&C!==null}C||(C=t.pcb_board.list()[0]),t=Mr(I);const x=it=>{if(!it?.source_component_id)return;const Yt=t.source_component.get(it.source_component_id);if(Yt?.name)return`${Yt.name}.${it.name}`},E=d?t.pcb_group.get(d):n?t.pcb_group.getWhere({subcircuit_id:n}):void 0;let B=h?.pcb_group_id;B==null&&!y&&(B=E?.pcb_group_id);const S=Vf(I),Q=t.pcb_breakout_point.list().filter(it=>!n||f?.has(it.subcircuit_id)),w=it=>it.subcircuit_id===n&&(B?it.pcb_group_id===B:!y),M=tMo({scopedDb:t,relevantSubcircuitIds:f}),k=new Map(M.map(it=>[it.pcb_trace_id,it])),R=it=>{if(!it.pcb_trace_id)return!1;const Yt=k.get(it.pcb_trace_id);if(!Yt)return!1;const pn=new Set(it.layers);return Yt.route.some(be=>{if(be.route_type!=="via"||be.x!==it.x||be.y!==it.y)return!1;const et=new Set(lw({fromLayer:be.from_layer,toLayer:be.to_layer,layerCount:C?.num_layers??2}));return et.size===pn.size&&[...et].every(It=>pn.has(It))})},F=_Mt([...C?[C]:[],...t.source_component.list(),...t.source_port.list(),...t.pcb_port.list(),...t.pcb_component.list(),...t.pcb_smtpad.list(),...t.pcb_plated_hole.list(),...t.pcb_hole.list(),...t.pcb_trace.list().filter(it=>!it.source_trace_id),...t.pcb_via.list().filter(it=>(!m||!!it.subcircuit_id)&&!R(it)),...t.pcb_keepout.list(),...t.pcb_cutout.list()].filter(it=>it.type==="pcb_board"||!n||f?.has(it.subcircuit_id)),S);F.push(...AMo({connMap:S,subcircuitComponent:h,board:C,group:E}));for(const it of F){const Yt=it.connectedTo.flatMap(pn=>S.getIdsConnectedToNet(pn));it.connectedTo=[...new Set([...it.connectedTo,...Yt])]}const O=t.source_component_internal_connection.list(),U=new Map;for(const it of O)for(const Yt of it.source_port_ids)U.set(Yt,it.source_component_internal_connection_id);const Y=new Map;for(const it of t.pcb_port.list())if(it.source_port_id){const Yt=t.pcb_smtpad.getWhere({pcb_port_id:it.pcb_port_id});Yt&&Y.set(Yt.pcb_smtpad_id,it.source_port_id);const pn=t.pcb_plated_hole.getWhere({pcb_port_id:it.pcb_port_id});pn&&Y.set(pn.pcb_plated_hole_id,it.source_port_id)}for(const it of F)for(const Yt of it.connectedTo){const pn=Y.get(Yt);if(pn){const be=U.get(pn);if(be){it.offBoardConnectsTo=[be],it.netIsAssignable=!0;break}}}const W=F.flatMap(it=>[{x:it.center.x-it.width/2,y:it.center.y-it.height/2},{x:it.center.x+it.width/2,y:it.center.y+it.height/2}]).concat(C?.outline??[]);let te;const j=!!(E?.width&&E.height&&n&&!y);if(j?te={minX:E.center.x-E.width/2,maxX:E.center.x+E.width/2,minY:E.center.y-E.height/2,maxY:E.center.y+E.height/2}:C&&!C.outline?te={minX:C.center.x-C.width/2,maxX:C.center.x+C.width/2,minY:C.center.y-C.height/2,maxY:C.center.y+C.height/2}:te={minX:Math.min(...W.map(it=>it.x))-1,maxX:Math.max(...W.map(it=>it.x))+1,minY:Math.min(...W.map(it=>it.y))-1,maxY:Math.max(...W.map(it=>it.y))+1},E?.width&&E.height&&!j){const it={minX:E.center.x-E.width/2,maxX:E.center.x+E.width/2,minY:E.center.y-E.height/2,maxY:E.center.y+E.height/2};te={minX:Math.min(te.minX,it.minX),maxX:Math.max(te.maxX,it.maxX),minY:Math.min(te.minY,it.minY),maxY:Math.max(te.maxY,it.maxY)}}const J=new Set(t.pcb_trace.list().filter(it=>it.source_trace_id?n?it.subcircuit_id===n:it.subcircuit_id?t.source_trace.get(it.source_trace_id)?.subcircuit_id===it.subcircuit_id:!1:!1).map(it=>it.source_trace_id).filter(it=>!!it)),oe=new Map;for(const it of Q){const Yt=it.source_port_id;Yt&&oe.set(Yt,it)}const ie=it=>{const Yt=it.layers?.[0]??"top",pn=oe.get(it.source_port_id),be=x(t.source_port.get(it.source_port_id));return pn&&!w(pn)?{x:pn.x,y:pn.y,layer:pn.layer??Yt,pointId:pn.pcb_breakout_point_id,port_selector:be}:{x:it.x,y:it.y,layer:Yt,pointId:it.pcb_port_id,pcb_port_id:it.pcb_port_id,port_selector:be}},ne=t.source_trace.list(),le=JPo({fanoutPourNetMap:p,sourceNets:t.source_net.list(),sourceTraces:ne,subcircuitId:n}),ge=ne.filter(it=>!J.has(it.source_trace_id)).filter(it=>!n||it.subcircuit_id===n).map(it=>{const Yt=it.connected_source_port_ids.map(xt=>t.pcb_port.getWhere({source_port_id:xt})).filter(xt=>xt!==null),pn=le.has(it.source_trace_id);if(Yt.length<2&&!(pn&&Yt.length===1))return null;for(const xt of Yt)if(xt.x===void 0||xt.y===void 0)return console.error(`(source_port_id: ${xt.source_port_id}) for trace ${it.source_trace_id} does not have x/y coordinates. Skipping this trace.`),null;const be=new Set(Yt.map(xt=>xt.pcb_port_id)),et=_.filter(xt=>be.has(xt.pcb_port_id)),It=[];for(const xt of et){const Ze=t.pcb_port.get(xt.pcb_port_id)?.layers?.[0]??"top";for(const dt of xt.route)It.push({x:dt.x,y:dt.y,layer:Ze})}const Bt=Yt.map(xt=>ie(xt)),[mt,...st]=Bt;return{name:it.source_trace_id??S.getNetConnectedToId(it.source_trace_id)??"",source_trace_id:it.source_trace_id,nominalTraceWidth:it.min_trace_thickness,width:it.min_trace_thickness,pointsToConnect:[mt,...It,...st]}}).filter(it=>it!==null),_e=t.source_net.list().filter(it=>!n||it.subcircuit_id===n),ue=[],fe=new Map,pe=new Set,ye=new Set(_e.map(it=>it.source_net_id)),Me=t.source_trace.list().filter(it=>!n||it.subcircuit_id===n),ve=new Set((h?.selectAll("trace")??[]).flatMap(it=>{const Yt=it;return Yt._exposesSubcircuitConnection&&Yt.source_trace_id?[Yt.source_trace_id]:[]})),he=new Set;for(const it of Me)if(ve.has(it.source_trace_id))for(const Yt of it.connected_source_net_ids??[])ye.has(Yt)||he.add(Yt);const Qe=new Set(n?t.pcb_trace.list().filter(it=>it.subcircuit_id&&it.subcircuit_id!==n&&f?.has(it.subcircuit_id)).map(it=>it.source_trace_id).filter(it=>!!it):[]),Pe=t.source_trace.list().filter(it=>!le.has(it.source_trace_id)).filter(it=>!J.has(it.source_trace_id)||n!=null&&it.subcircuit_id===n).filter(it=>!n||it.subcircuit_id===n||(it.connected_source_net_ids?.some(Yt=>ye.has(Yt))??!1)||(it.connected_source_net_ids?.some(Yt=>he.has(Yt))??!1)&&!Qe.has(it.source_trace_id)),we=it=>it?S.getNetConnectedToId(it)??it:null;for(const it of _e){const Yt=we(it.source_net_id);if(!Yt||pe.has(Yt))continue;pe.add(Yt);const pn=_e.filter(st=>we(st.source_net_id)===Yt).map(st=>st.source_net_id),be=Pe.filter(st=>[st.source_trace_id,...st.connected_source_net_ids??[]].some(xt=>we(xt)===Yt));let et;for(const st of be)st.min_trace_thickness!==void 0&&(et=Math.max(et??0,st.min_trace_thickness));const It=[],Bt=new Set;for(const st of be){const xt=t.pcb_port.list().filter(Xe=>st.connected_source_port_ids.includes(Xe.source_port_id));for(const Xe of xt){const Ze=ie(Xe);Bt.has(Ze.pointId)||(Bt.add(Ze.pointId),It.push(Ze))}}const mt={name:it.source_net_id??S.getNetConnectedToId(it.source_net_id),nominalTraceWidth:et,width:et,pointsToConnect:It};if(It.length!==0){ue.push(mt);for(const st of pn)fe.set(st,mt)}}const Te=[];for(const it of Q){const Yt=it.source_port_id,pn={x:it.x,y:it.y,layer:it.layer??"top",pointId:it.pcb_breakout_point_id};if(Yt){const be=t.pcb_port.getWhere({source_port_id:Yt});if(!be)continue;const et={x:be.x,y:be.y,layer:be.layers?.[0]??"top",pointId:be.pcb_port_id,pcb_port_id:be.pcb_port_id,port_selector:x(t.source_port.get(be.source_port_id))},It=w(it),Bt=!It&&it.subcircuit_id===n;if(It||Bt){Te.push({name:Bt?`breakout:${it.pcb_breakout_point_id}`:Yt,source_trace_id:it.source_trace_id,routingPcbGroupId:Bt?it.pcb_group_id:void 0,pointsToConnect:[et,pn]});continue}it.source_trace_id||Te.push({name:Yt,pointsToConnect:[et,pn]});continue}if(it.source_net_id){const be=fe.get(it.source_net_id);be?be.pointsToConnect.push(pn):Te.push({name:it.source_net_id,pointsToConnect:[pn]})}}const Re=ue.filter(it=>it.pointsToConnect.length>=2),Ee=[...ge,...Re,...Te],ke=o??C?.min_trace_width??.1;for(const it of Ee)it.nominalTraceWidth??=g??ke,it.width??=g??ke;te=zRt({bounds:te,connections:Ee});const Ce=h?.selectAll("differentialpair")??[],Le=h?.selectAll("bus")??[],Ye=qPo({srjConnections:Ee,differentialPairs:Ce,sourceTraces:t.source_trace.list(),subcircuitId:n}),tt=WPo({srjConnections:Ee,buses:Le,sourceTraces:t.source_trace.list(),subcircuitId:n,planeTerminatedSourceTraceLayers:le});if(n){const it=new Map;for(const pn of Ee)for(const be of pn.pointsToConnect)be.pointId&&it.set(be.pointId,pn);const Yt=t.pcb_trace.list().filter(pn=>f?.has(pn.subcircuit_id));for(const pn of Yt){const be=new Set;for(const Bt of pn.route)Bt.start_pcb_port_id&&be.add(Bt.start_pcb_port_id),Bt.end_pcb_port_id&&be.add(Bt.end_pcb_port_id);if(be.size<2)continue;const et=be.values().next().value;if(!et)continue;const It=it.get(et);It&&[...be].every(Bt=>it.get(Bt)===It)&&(It.externallyConnectedPointIds??=[],It.externallyConnectedPointIds.push([...be]))}}const At=l??C?.min_via_hole_diameter,at=u??C?.min_via_pad_diameter,nt=i??C?.min_trace_to_pad_edge_clearance,gt=r??C?.min_via_edge_to_pad_edge_clearance,bt=s??C?.min_via_hole_edge_to_via_hole_edge_clearance,Ct=a??C?.min_plated_hole_drill_edge_to_drill_edge_clearance,Dt=A??C?.min_pad_edge_to_pad_edge_clearance,kt=c??C?.min_board_edge_clearance;return{simpleRouteJson:{bounds:te,obstacles:F,connections:Ee,differentialPairs:Ye,...tt?{buses:tt}:{},traces:M.length>0?M:void 0,layerCount:C?.num_layers??2,allowBlindAndBuriedVias:C?.allow_blind_and_buried_vias??!1,minTraceWidth:Math.min(ke,...Ee.map(it=>it.width)),minViaDiameter:at,minViaHoleDiameter:At,minViaPadDiameter:at,min_via_hole_diameter:At,min_via_pad_diameter:at,minTraceToPadEdgeClearance:nt,minViaEdgeToPadEdgeClearance:gt,minViaHoleEdgeToViaHoleEdgeClearance:bt,minPlatedHoleDrillEdgeToDrillEdgeClearance:Ct,minPadEdgeToPadEdgeClearance:Dt,minBoardEdgeClearance:kt,nominalTraceWidth:g,outline:C?.outline?.map(it=>({...it}))},connMap:S}},qRt=class extends Ir{matchedPort=null;get config(){return{componentName:"TraceHint",zodProps:yDn}}doInitialPortMatching(){const{db:t}=this.root,{_parsedProps:e,parent:n}=this;if(!n)return;if(n.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!n)throw new Error("TraceHint has no parent");if(!e.for){this.renderError(`TraceHint has no for property (${this})`);return}const o=n.selectOne(e.for,{type:"port"});o||this.renderError(`${this} could not find port for selector "${e.for}"`),this.matchedPort=o,o.registerMatch(this)}getPcbRouteHints(){const{_parsedProps:t}=this,e=t.offset?[t.offset]:t.offsets;if(!e)return[];const n=this._computePcbGlobalTransformBeforeLayout();return e.map(o=>({...ts(n,o),via:o.via,to_layer:o.to_layer,trace_width:o.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this;t.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}};function lMo({anchor:t,x:e,y:n,width:o,height:i,isInside:r}){switch(t){case"top_left":return{x:e,y:n+i,textAnchor:r?"top_left":"bottom_left"};case"top_center":return{x:e+o/2,y:n+i,textAnchor:r?"top_center":"bottom_center"};case"top_right":return{x:e+o,y:n+i,textAnchor:r?"top_right":"bottom_right"};case"center_left":return{x:e,y:n+i/2,textAnchor:r?"center_left":"center_right"};case"center":return{x:e+o/2,y:n+i/2,textAnchor:"center"};case"center_right":return{x:e+o,y:n+i/2,textAnchor:r?"center_right":"center_left"};case"bottom_left":return{x:e,y:n,textAnchor:r?"bottom_left":"top_left"};case"bottom_center":return{x:e+o/2,y:n,textAnchor:r?"bottom_center":"top_center"};case"bottom_right":return{x:e+o,y:n,textAnchor:r?"bottom_right":"top_right"};default:return{x:e+o/2,y:n+i,textAnchor:"center"}}}var XRt=t=>t?Object.entries(t).map(([e,n])=>{const o=uw(e);if(o===null)throw new Error(`Invalid schematicbox pinLabels key "${e}". Expected pin<number>.`);const i=typeof n=="string"?[n]:[...n];return{pinNumber:o,displayPinLabel:i[0]??e,pinAliases:i}}):[],uMo=({referencedChip:t,schematicBoxPins:e})=>{const n=Kj(t._parsedProps.schPinStyle,t._parsedProps.pinLabels);if(!n)return;const o={};for(const{pinNumber:i,referencedSourcePort:r}of e){if(r.pin_number===void 0)continue;const s=n[`pin${r.pin_number}`];s&&(o[`pin${i}`]=s)}return Object.keys(o).length>0?o:void 0},gMo=({inheritedPinStyle:t,overridePinStyle:e})=>{if(!t&&!e)return;const n={...t};for(const[o,i]of Object.entries(e??{}))n[o]={...n[o],...i};return Object.keys(n).length>0?n:void 0},dMo=t=>{if(t.root?.schematicDisabled)return;const{db:e}=t.root,n=t._parsedProps;if(!n.chipRef)return;const o=t.getSubcircuit().selectOne(n.chipRef);if(!o?.source_component_id)throw new Error(`Could not resolve chipRef "${n.chipRef}" for ${t.getString()}`);const i=XRt(n.pinLabels),r=Object.fromEntries(i.map(({pinNumber:f,displayPinLabel:I})=>[`pin${f}`,I])),s=e.source_port.list({source_component_id:o.source_component_id}),a=i.map(f=>{const I=s.find(C=>f.pinAliases.some(y=>C.name===y||C.port_hints?.includes(y)));if(!I)throw new Error(`Could not find pin "${f.displayPinLabel}" on chipRef "${n.chipRef}"`);return{...f,referencedSourcePort:I}}),A=uMo({referencedChip:o,schematicBoxPins:a}),c=gMo({inheritedPinStyle:A,overridePinStyle:Kj(n.schPinStyle,n.pinLabels)}),l=sPe({schWidth:n.width,schHeight:n.height,schPinSpacing:.2,pinCount:i.length,schPortArrangement:n.schPinArrangement,numericSchPinStyle:Kj(c),pinLabels:r}),u=t._getGlobalSchematicPositionBeforeLayout(),g=l.getSize(),h=t._resolveSchematicSheetId(),d=Object.fromEntries(i.map(({pinNumber:f,displayPinLabel:I})=>[String(f),I])),p=e.schematic_component.insert({center:u,size:g,source_component_id:o.source_component_id,is_box_with_pins:!0,port_arrangement:ePe(n.schPinArrangement),port_labels:d,pin_spacing:.2,pin_styles:Zwe(c),schematic_sheet_id:h});t.schematic_component_id=p.schematic_component_id;for(const{pinNumber:f,displayPinLabel:I,referencedSourcePort:C}of a){const y=l.getPortPositionByPinNumber(f);if(!y)throw new Error(`Could not determine schematic position for ${t.getString()} pin${f}`);const x={left:"left",right:"right",top:"up",bottom:"down"}[y.side];e.schematic_port.insert({schematic_component_id:p.schematic_component_id,center:{x:u.x+y.x,y:u.y+y.y},source_port_id:C.source_port_id,facing_direction:x,distance_from_component_edge:.4,side_of_component:y.side,pin_number:f,true_ccw_index:y.trueIndex,display_pin_label:I,is_connected:!1,schematic_sheet_id:h})}const m=n.name??n.chipRef;e.schematic_text.insert({text:m,schematic_component_id:p.schematic_component_id,anchor:"left",rotation:0,position:{x:u.x-g.width/2,y:u.y+g.height/2+.13},color:"#006464",font_size:.18,schematic_sheet_id:h});const _=e.source_component.get(o.source_component_id);e.schematic_text.insert({text:_?.manufacturer_part_number??"",schematic_component_id:p.schematic_component_id,anchor:"left",rotation:0,position:{x:u.x-g.width/2,y:u.y-g.height/2-.13},color:"#006464",font_size:.18,schematic_sheet_id:h})},ZRt=class extends Ir{isSchematicPrimitive=!0;get config(){return{componentName:"SchematicBox",zodProps:XMn,shouldRenderAsSchematicBox:!0}}doInitialSchematicComponentRender(){dMo(this)}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled||this.getCollapsedSchematicBoxAncestor())return;const{db:t}=this.root,{_parsedProps:e}=this;if(e.chipRef)return;const n=.6,o=typeof e.padding=="number"?e.padding:0,i=typeof e.paddingTop=="number"?e.paddingTop:o,r=typeof e.paddingBottom=="number"?e.paddingBottom:o,s=typeof e.paddingLeft=="number"?e.paddingLeft:o,a=typeof e.paddingRight=="number"?e.paddingRight:o,A=e.overlay&&e.overlay.length>0,c=typeof e.width=="number"&&typeof e.height=="number";let l,u,g,h,d,p;if(A){const _=e.overlay.map(te=>({selector:te,port:this.getSubcircuit().selectOne(te,{type:"port"})})).filter(({port:te})=>te!=null).map(({port:te})=>({position:te._getGlobalSchematicPositionAfterLayout()}));if(_.length===0)return;const f=_.map(te=>te.position.x),I=_.map(te=>te.position.y),C=Math.min(...f),y=Math.max(...f),x=Math.min(...I),E=Math.max(...I),B=y-C,S=E-x,Q=B===0?n:0,w=S===0?n:0,M=s+Q/2,k=a+Q/2,R=i+w/2,F=r+w/2,O=C-M,U=y+k,Y=x-F,W=E+R;l=U-O,u=W-Y,g=O+(e.schX??0),h=Y+(e.schY??0),d=g+l/2,p=h+u/2}else if(c){l=e.width,u=e.height;const m=this._getGlobalSchematicPositionBeforeLayout();d=m.x,p=m.y,g=d-l/2,h=p-u/2}else return;if(t.schematic_box.insert({height:u,width:l,x:g,y:h,is_dashed:e.strokeStyle==="dashed",schematic_sheet_id:this._resolveSchematicSheetId()}),e.title){const m=e.titleInside,_=.1,f=e.titleAlignment,I=lMo({anchor:f,x:g,y:h,width:l,height:u,isInside:m});let C,y;const x=I.textAnchor;m?(C=f.includes("top")?-_:f.includes("bottom")?_:0,y=f.includes("left")?_:f.includes("right")?-_:0):(C=f.includes("top")?_:f.includes("bottom")?-_:0,y=f.includes("center_left")?-_:f.includes("center_right")?_:0);const E=I.x+y,B=I.y+C;t.schematic_text.insert({anchor:x,text:e.title,font_size:e.titleFontSize??.18,color:e.titleColor??"#000000",position:{x:E,y:B},rotation:0,schematic_sheet_id:this._resolveSchematicSheetId()})}}},hMo=t=>{if(!t.isSubcircuit||t.root?.schematicDisabled)return;const{db:e}=t.root,n=new Map,o=new Set,i=t.getDescendants().filter(s=>s instanceof ZRt&&s.getSubcircuit()===t);for(const s of i){const{chipRef:a,pinLabels:A}=s._parsedProps,c=s._resolveSchematicSheetId();if(!a||!c)continue;const l=s.getSubcircuit().selectOne(a);if(!(l instanceof g0)||!l.source_component_id)continue;o.add(l.source_component_id);const u=e.source_port.list({source_component_id:l.source_component_id});for(const{pinAliases:g}of XRt(A)){const d=u.find(m=>g.some(_=>m.name===_||m.port_hints?.includes(_)))?.subcircuit_connectivity_map_key;if(!d)continue;const p=n.get(d)??new Set;p.add(c),n.set(d,p)}}const r=t.getDescendants().filter(s=>s instanceof g0&&s.getSubcircuit()===t);for(const s of r){if(!s.source_component_id||o.has(s.source_component_id)||s._resolveSchematicSheetId())continue;const a=new Set,A=e.source_port.list({source_component_id:s.source_component_id});for(const l of A){const u=l.subcircuit_connectivity_map_key;if(!u)continue;const g=n.get(u);if(g)for(const h of g)a.add(h)}if(a.size!==1)continue;const[c]=a;c&&(s.schematic_sheet_id=c)}},pMo=new Set(["x","y","minx","maxx","miny","maxy","width","height"]);function mMo(t){if(t.root?.pcbDisabled||!t.isSubcircuit)return;const{db:e}=t.root,n=t.getNormalComponentNameMap?.()??new Map,o=fMo(t),i={};for(const u of o)eTt(u,i);const r=new Map,s=new Map,a=new Map;for(const u of o){if(!_Mo(u))continue;const g=IMo(u);if(!u.name)throw new Error(`Invalid pcb position expression for ${u.getString()}: component-relative calc requires the component to have a name`);r.set(u.name,{component:u,refs:g}),s.set(u.name,0)}for(const[u,g]of r.entries()){const h=new Set;for(const d of g.refs){const{referencePath:p,field:m}=CMo(d);if(!pMo.has(m))throw new Error(`Invalid pcb position expression for ${g.component.getString()}: unsupported component field "${m}" in "${d}"`);const _=yMo({token:d,referencePath:p,candidate:g,normalComponentNameMap:n});r.has(_)&&_!==u&&h.add(_)}for(const d of h)s.set(u,(s.get(u)??0)+1),a.has(d)||a.set(d,new Set),a.get(d).add(u)}const A=[...s.entries()].filter(([,u])=>u===0).map(([u])=>u);let c=0;for(;A.length>0;){const u=A.shift(),g=r.get(u);if(g){l(g.component,i),c++;for(const h of a.get(u)??[]){const d=(s.get(h)??0)-1;s.set(h,d),d===0&&A.push(h)}}}if(c<r.size){const u=[...r.keys()].filter(g=>(s.get(g)??0)>0);throw new Error(`Circular pcb position calc references detected among: ${u.join(", ")}`)}function l(u,g){if(!u.pcb_component_id)return;const h=e.pcb_component.get(u.pcb_component_id);if(!h)return;const d=u._parsedProps.pcbX,p=u._parsedProps.pcbY,m=u.props,_=u._parsedProps.pcbLeftEdgeX??m.pcbLeftEdgeX,f=u._parsedProps.pcbRightEdgeX??m.pcbRightEdgeX,I=u._parsedProps.pcbTopEdgeY??m.pcbTopEdgeY,C=u._parsedProps.pcbBottomEdgeY??m.pcbBottomEdgeY;if(_!==void 0&&f!==void 0)throw new Error(`${u.componentName} cannot set both pcbLeftEdgeX and pcbRightEdgeX`);if(I!==void 0&&C!==void 0)throw new Error(`${u.componentName} cannot set both pcbTopEdgeY and pcbBottomEdgeY`);const y=h.width??0,x=h.height??0,E={x:h.center.x,y:h.center.y};if(d!==void 0){const B=u.resolvePcbCoordinate({rawValue:d,axis:"pcbX",allowComponentVariables:!0,componentVariables:g});u._resolvedPcbCalcOffsetX=B,E.x=B}else if(_!==void 0){const S=u.resolvePcbCoordinate({rawValue:_,axis:"pcbX",allowComponentVariables:!0,componentVariables:g,propertyName:"pcbLeftEdgeX"})+y/2;u._resolvedPcbCalcOffsetX=S,E.x=S}else if(f!==void 0){const S=u.resolvePcbCoordinate({rawValue:f,axis:"pcbX",allowComponentVariables:!0,componentVariables:g,propertyName:"pcbRightEdgeX"})-y/2;u._resolvedPcbCalcOffsetX=S,E.x=S}if(p!==void 0){const B=u.resolvePcbCoordinate({rawValue:p,axis:"pcbY",allowComponentVariables:!0,componentVariables:g});u._resolvedPcbCalcOffsetY=B,E.y=B}else if(I!==void 0){const S=u.resolvePcbCoordinate({rawValue:I,axis:"pcbY",allowComponentVariables:!0,componentVariables:g,propertyName:"pcbTopEdgeY"})-x/2;u._resolvedPcbCalcOffsetY=S,E.y=S}else if(C!==void 0){const S=u.resolvePcbCoordinate({rawValue:C,axis:"pcbY",allowComponentVariables:!0,componentVariables:g,propertyName:"pcbBottomEdgeY"})+x/2;u._resolvedPcbCalcOffsetY=S,E.y=S}u._repositionOnPcb(E),eTt(u,g)}}function _Mo(t){const e=t._parsedProps,n=t.props,o=e.pcbX,i=e.pcbY,r=e.pcbLeftEdgeX??n.pcbLeftEdgeX,s=e.pcbRightEdgeX??n.pcbRightEdgeX,a=e.pcbTopEdgeY??n.pcbTopEdgeY,A=e.pcbBottomEdgeY??n.pcbBottomEdgeY;return r!==void 0||s!==void 0||a!==void 0||A!==void 0?!0:typeof o=="string"||typeof i=="string"}function fMo(t){const e=[],n=o=>{o._isNormalComponent&&e.push(o);for(const i of o.children)i.isSubcircuit||n(i)};for(const o of t.children)o.isSubcircuit||n(o);return e}function IMo(t){const e=new Set,n=t._parsedProps.pcbX,o=t._parsedProps.pcbY,i=t.props,r=t._parsedProps.pcbLeftEdgeX??i.pcbLeftEdgeX,s=t._parsedProps.pcbRightEdgeX??i.pcbRightEdgeX,a=t._parsedProps.pcbTopEdgeY??i.pcbTopEdgeY,A=t._parsedProps.pcbBottomEdgeY??i.pcbBottomEdgeY,c=l=>{if(typeof l!="string")return;const u=Nwe(l);for(const g of u)g.startsWith("board.")||e.add(g)};return c(n),c(o),c(r),c(s),c(a),c(A),e}function CMo(t){const e=t.lastIndexOf(".");if(e<=0||e===t.length-1)throw new Error(`Invalid component reference token: "${t}"`);return{referencePath:t.slice(0,e),field:t.slice(e+1).toLowerCase()}}function yMo(t){const{token:e,referencePath:n,candidate:o,normalComponentNameMap:i}=t,r=i.get(n);if(r&&r.length>0){if(r.length>1)throw new Error(`Invalid pcb position expression for ${o.component.getString()}: ambiguous component reference "${n}" in "${e}"`);return n}let s=null;for(const a of i.keys())n.startsWith(`${a}.`)&&(!s||a.length>s.length)&&(s=a);if(!s)throw new Error(`Invalid pcb position expression for ${o.component.getString()}: unknown component reference "${n}" in "${e}"`);return s}function eTt(t,e){if(!t.name||!t.pcb_component_id||!t.root)return;const n=t.root.db.pcb_component.get(t.pcb_component_id);if(!n)return;const o=n.width??0,i=n.height??0,r=n.center.x,s=n.center.y;aMt({vars:e,componentName:t.name,position:{x:r,y:s},size:{width:o,height:i}});const a=xMo(t);for(const[A,c]of a.entries()){const l=H8(c),u=l.minX,g=l.maxX,h=l.minY,d=l.maxY;e[`${A}.x`]=(u+g)/2,e[`${A}.y`]=(h+d)/2,e[`${A}.width`]=g-u,e[`${A}.height`]=d-h,e[`${A}.minX`]=u,e[`${A}.maxX`]=g,e[`${A}.minY`]=h,e[`${A}.maxY`]=d}}function xMo(t){const e=new Map;if(!t.name||!t.pcb_component_id||!t.root)return e;const{db:n}=t.root,o=[...n.pcb_smtpad.list({pcb_component_id:t.pcb_component_id}),...n.pcb_plated_hole.list({pcb_component_id:t.pcb_component_id})];for(const i of o){const r=new Set;for(const a of i.port_hints??[])typeof a=="string"&&a.length>0&&r.add(a);const s=i.pcb_port_id;if(s){const a=n.pcb_port.get(s),A=a?.source_port_id?n.source_port.get(a.source_port_id):null;A?.name&&r.add(A.name),A?.pin_number!=null&&r.add(`pin${A.pin_number}`)}for(const a of r){const A=`${t.name}.${a}`;e.has(A)||e.set(A,[]),e.get(A).push(i)}}return e}function EMo(t){if(t.root?.pcbDisabled||!t.pcb_group_id)return;const e=t._parsedProps?.pcbPositionAnchor;if(!e)return;const n=t._getGlobalPcbPositionBeforeLayout(),{pcbX:o,pcbY:i}=t._parsedProps;if(o===void 0&&i===void 0)return;const{db:r}=t.root,s=r.pcb_group.get(t.pcb_group_id);if(!s)return;let a=s.width,A=s.height;const{center:c}=s;if(s.outline&&s.outline.length>0){const p=Oh(s.outline);p&&(a=p.maxX-p.minX,A=p.maxY-p.minY)}if(!a||!A)return;const l={left:c.x-a/2,right:c.x+a/2,top:c.y+A/2,bottom:c.y-A/2},u={...c};let g=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(e))switch(e){case"center":g=u;break;case"top_left":g={x:l.left,y:l.top};break;case"top_center":g={x:u.x,y:l.top};break;case"top_right":g={x:l.right,y:l.top};break;case"center_left":g={x:l.left,y:u.y};break;case"center_right":g={x:l.right,y:u.y};break;case"bottom_left":g={x:l.left,y:l.bottom};break;case"bottom_center":g={x:u.x,y:l.bottom};break;case"bottom_right":g={x:l.right,y:l.bottom};break}if(!g)return;const d={...u};n.x!==void 0&&(d.x+=n.x-g.x),n.y!==void 0&&(d.y+=n.y-g.y),(Math.abs(d.x-u.x)>1e-6||Math.abs(d.y-u.y)>1e-6)&&(t._repositionOnPcb(d),r.pcb_group.update(t.pcb_group_id,{center:d})),r.pcb_group.update(t.pcb_group_id,{anchor_position:n,anchor_alignment:e,display_offset_x:o,display_offset_y:i})}var BMo=t=>{const{db:e}=t.root,{_parsedProps:n}=t,o=t.children.filter(y=>y.pcb_component_id||y.pcb_group_id);if(o.some(y=>{const x=y._parsedProps;return x?.pcbX!==void 0||x?.pcbY!==void 0}))return;const r=n.pcbJustifyContent??n.justifyContent,s=n.pcbAlignItems??n.alignItems,a=n.pcbFlexGap??n.pcbGap??n.gap,A=n.pcbFlexDirection??"row",c={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[r??"space-between"],l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[s??"center"];if(!c)throw new Error(`Invalid justifyContent value: "${r}"`);if(!l)throw new Error(`Invalid alignItems value: "${s}"`);let u=0,g=0;typeof a=="object"?(u=a.y??0,g=a.x??0):typeof a=="number"?(u=a,g=a):typeof a=="string"&&(u=ce.parse(a),g=ce.parse(a));let h,d=n.width??n.pcbWidth??void 0,p=n.height??n.pcbHeight??void 0;(d===void 0||p===void 0)&&(h=lmt(o.map(y=>y._getMinimumFlexContainerSize()).filter(y=>y!==null),{direction:A,rowGap:u,columnGap:g}),d=h.width,p=h.height);const _=new Qwt(d,p,{alignItems:l,justifyContent:c,direction:A,rowGap:u,columnGap:g});for(const y of o){const x=y._getMinimumFlexContainerSize();_.addChild({metadata:y,width:x?.width??0,height:x?.height??0,flexBasis:x?A==="row"?x.width:x.height:void 0})}_.build();const f={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(const y of _.children)f.minX=Math.min(f.minX,y.position.x),f.minY=Math.min(f.minY,y.position.y),f.maxX=Math.max(f.maxX,y.position.x+y.size.width),f.maxY=Math.max(f.maxY,y.position.y+y.size.height);f.width=f.maxX-f.minX,f.height=f.maxY-f.minY;const I=t._getGlobalPcbPositionBeforeLayout(),C={x:I.x-(f.maxX+f.minX)/2,y:I.y-(f.maxY+f.minY)/2};for(const y of _.children)y.metadata._repositionOnPcb({x:y.position.x+y.size.width/2+C.x,y:y.position.y+y.size.height/2+C.y});e.pcb_group.update(t.pcb_group_id,{width:f.width,height:f.height,center:I})},IMe=1;function bMo(t){const{db:e}=t.root,n=t._parsedProps,o=SMo(t);if(o.length===0)return;const i=QMo({db:e,pcbChildren:o}),r=vMo(n),s=wMo({props:n,pcbChildren:o,childDimensions:i,gridConfig:r}),a=DMo({pcbChildren:o,childDimensions:i,gridLayout:s,gridConfig:r}),{itemCoordinates:A}=a.layout();NMo({db:e,group:t,pcbChildren:o,itemCoordinates:A,gridLayout:s}),RMo({db:e,group:t,props:n,gridLayout:s})}function SMo(t){return t.children.filter(e=>e.pcb_component_id||e.pcb_group_id)}function QMo(t){const{db:e,pcbChildren:n}=t;let o=0,i=0;for(const r of n){let s=0,a=0;if(r.pcb_group_id){const A=e.pcb_group.get(r.pcb_group_id);s=A?.width??0,a=A?.height??0}else if(r.pcb_component_id){const A=e.pcb_component.get(r.pcb_component_id);s=A?.width??0,a=A?.height??0}o=Math.max(o,s),i=Math.max(i,a)}return{width:o,height:i}}function vMo(t){const e=t.pcbGridCols??t.gridCols??t.pcbLayout?.grid?.cols,n=t.pcbGridRows??t.pcbLayout?.grid?.rows,o=t.pcbGridTemplateColumns,i=t.pcbGridTemplateRows,r=u=>u===void 0?IMe:typeof u=="number"?u:ce.parse(u),s=t.pcbGridGap??t.gridGap??t.pcbLayout?.gridGap,a=t.pcbGridRowGap??t.gridRowGap??t.pcbLayout?.gridRowGap,A=t.pcbGridColumnGap??t.gridColumnGap??t.pcbLayout?.gridColumnGap;let c=IMe,l=IMe;if(a!==void 0||A!==void 0){const u=typeof s=="object"?s?.x:s,g=typeof s=="object"?s?.y:s;c=r(A??u),l=r(a??g)}else if(typeof s=="object"&&s!==null)c=r(s.x),l=r(s.y);else{const u=r(s);c=u,l=u}return{cols:e,rows:n,gapX:c,gapY:l,templateColumns:o,templateRows:i}}function wMo(t){const{props:e,pcbChildren:n,childDimensions:o,gridConfig:i}=t;return e.pcbGridTemplateColumns||e.pcbGridTemplateRows?PMo({props:e,gridConfig:i,pcbChildren:n,childDimensions:o}):MMo({gridConfig:i,pcbChildren:n,childDimensions:o})}function PMo(t){const{props:e,gridConfig:n,pcbChildren:o,childDimensions:i}=t,r=e.pcbGridTemplateColumns??"",s=e.pcbGridTemplateRows??"",a=g=>{const h=g.match(/repeat\((\d+),/);return h?parseInt(h[1]):Math.ceil(Math.sqrt(o.length))},A=e.pcbGridTemplateColumns?a(r):Math.ceil(Math.sqrt(o.length)),c=e.pcbGridTemplateRows?a(s):Math.ceil(o.length/A),l=A*i.width+Math.max(0,A-1)*n.gapX,u=c*i.height+Math.max(0,c-1)*n.gapY;return{gridTemplateColumns:r,gridTemplateRows:s,containerWidth:l,containerHeight:u}}function MMo(t){const{gridConfig:e,pcbChildren:n,childDimensions:o}=t;let i,r;e.cols!==void 0&&e.rows!==void 0?(i=e.cols,r=e.rows):e.cols!==void 0?(i=e.cols,r=Math.ceil(n.length/i)):e.rows!==void 0?(r=e.rows,i=Math.ceil(n.length/r)):(i=Math.ceil(Math.sqrt(n.length)),r=Math.ceil(n.length/i)),i=Math.max(1,i),r=Math.max(1,r);const s=i*o.width+Math.max(0,i-1)*e.gapX,a=r*o.height+Math.max(0,r-1)*e.gapY,A=`repeat(${i}, ${o.width}px)`,c=`repeat(${r}, ${o.height}px)`;return{gridTemplateColumns:A,gridTemplateRows:c,containerWidth:s,containerHeight:a}}function DMo(t){const{pcbChildren:e,childDimensions:n,gridLayout:o,gridConfig:i}=t,r=e.map((s,a)=>({key:s.getString()||`child-${a}`,contentWidth:n.width,contentHeight:n.height}));return new oEo({containerWidth:o.containerWidth,containerHeight:o.containerHeight,gridTemplateColumns:o.gridTemplateColumns,gridTemplateRows:o.gridTemplateRows,gap:[i.gapY,i.gapX],children:r})}function NMo(t){const{db:e,group:n,pcbChildren:o,itemCoordinates:i,gridLayout:r}=t,s=n._getGlobalPcbPositionBeforeLayout(),a=e.toArray();for(let A=0;A<o.length;A++){const c=o[A],l=c.getString()||`child-${A}`,u=i[l];if(!u){console.warn(`PCB grid layout: No coordinates found for child ${l}`);continue}const g=s.x-r.containerWidth/2+u.x+u.width/2,h=s.y+r.containerHeight/2-u.y-u.height/2;if(c.pcb_component_id)smt(a,c.pcb_component_id,{x:g,y:h});else{const d=c;d.pcb_group_id&&d.source_group_id&&Amt(a,d.source_group_id,{x:g,y:h})}}}function RMo(t){const{db:e,group:n,props:o,gridLayout:i}=t;if(n.pcb_group_id){const r=n._getGlobalPcbPositionBeforeLayout();e.pcb_group.update(n.pcb_group_id,{width:o.width??i.containerWidth,height:o.height??i.containerHeight,center:r})}}var TMo=(t,e,n=()=>performance.now())=>{if(e===void 0||!Number.isFinite(e)||e<=0)return t.solve(),{elapsedMs:0,timedOut:!1};const o=n();let i=0;for(;!t.solved&&!t.failed&&(t.step(),!(t.solved||t.failed));)if(i=n()-o,i>=e)return{elapsedMs:i,timedOut:!0};return{elapsedMs:i,timedOut:!1}},kMo=(t,e)=>{const n=t.children.filter(u=>u.componentName==="Constraint"&&u._parsedProps.pcb),o=new Map,i={},r=u=>(i[u]!==u&&(i[u]=r(i[u])),i[u]),s=(u,g)=>{const h=r(u),d=r(g);h!==d&&(i[d]=h)},a=u=>{u in i||(i[u]=u)},A=u=>{const g=u.startsWith(".")?u.slice(1):u;return t.children.find(d=>d.name===g)?.pcb_component_id??void 0};for(const u of n){const g=u._parsedProps;if("left"in g&&"right"in g){const h=A(g.left),d=A(g.right);h&&d&&(a(h),a(d),s(h,d))}else if("top"in g&&"bottom"in g){const h=A(g.top),d=A(g.bottom);h&&d&&(a(h),a(d),s(h,d))}else if("for"in g&&Array.isArray(g.for)){const h=g.for.map(d=>A(d)).filter(d=>!!d);for(const d of h)a(d);for(let d=1;d<h.length;d++)s(h[0],h[d])}}for(const u of Object.keys(i)){const g=r(u);o.has(g)||o.set(g,{componentIds:[],constraints:[]}),o.get(g).componentIds.push(u)}for(const u of n){const g=u._parsedProps;let h;if("left"in g?h=A(g.left):"top"in g?h=A(g.top):"for"in g&&(h=A(g.for[0])),!h)continue;const d=r(h);o.get(d)?.constraints.push(u)}const c={},l=Object.fromEntries(e.components.map(u=>[u.componentId,u]));for(const[u,g]of o.entries()){if(g.componentIds.length<=1)continue;const h=new qpt,d={},p=(S,Q)=>{const w=`${S}_${Q}`;return d[w]||(d[w]=new gse(w)),d[w]},m=g.componentIds[0];h.addConstraint(new ux(p(m,"x"),V_.Eq,0,wg.required)),h.addConstraint(new ux(p(m,"y"),V_.Eq,0,wg.required));for(const S of g.constraints){const Q=S._parsedProps;if("xDist"in Q){const w=A(Q.left),M=A(Q.right);w&&M&&h.addConstraint(new ux(new Gh(p(M,"x"),[-1,p(w,"x")]),V_.Eq,Q.xDist,wg.required))}else if("yDist"in Q){const w=A(Q.top),M=A(Q.bottom);w&&M&&h.addConstraint(new ux(new Gh(p(w,"y"),[-1,p(M,"y")]),V_.Eq,Q.yDist,wg.required))}else if("sameX"in Q&&Array.isArray(Q.for)){const w=Q.for.map(M=>A(M)).filter(M=>!!M);if(w.length>1){const M=p(w[0],"x");for(let k=1;k<w.length;k++)h.addConstraint(new ux(new Gh(p(w[k],"x"),[-1,M]),V_.Eq,0,wg.required))}}else if("sameY"in Q&&Array.isArray(Q.for)){const w=Q.for.map(M=>A(M)).filter(M=>!!M);if(w.length>1){const M=p(w[0],"y");for(let k=1;k<w.length;k++)h.addConstraint(new ux(new Gh(p(w[k],"y"),[-1,M]),V_.Eq,0,wg.required))}}}h.updateVariables();const _={};for(const S of g.componentIds)_[S]={x:p(S,"x").value(),y:p(S,"y").value()};let f=1/0,I=1/0,C=-1/0,y=-1/0;for(const S of g.componentIds){const Q=l[S],w=_[S];if(Q)for(const M of Q.pads){const k=w.x+M.offset.x,R=w.y+M.offset.y;f=Math.min(f,k-M.size.x/2),C=Math.max(C,k+M.size.x/2),I=Math.min(I,R-M.size.y/2),y=Math.max(y,R+M.size.y/2)}}const x={x:(f+C)/2,y:(I+y)/2},E=[],B={};for(const S of g.componentIds){const Q=l[S],w=_[S];if(Q){B[S]={x:w.x-x.x,y:w.y-x.y};for(const M of Q.pads)E.push({padId:M.padId,networkId:M.networkId,type:M.type,size:M.size,offset:{x:w.x+M.offset.x-x.x,y:w.y+M.offset.y-x.y}})}}e.components=e.components.filter(S=>!g.componentIds.includes(S.componentId)),e.components.push({componentId:g.componentIds[0],pads:E,availableRotationDegrees:[0]}),g.relativeCenters=B,c[g.componentIds[0]]=g}return c},tTt=({db:t,pcbComponentId:e,rotationDegrees:n,layer:o})=>{if(n==null||!t?.cad_component?.list)return;const i=t.cad_component.getWhere({pcb_component_id:e});if(!i)return;const r=o?.toLowerCase?.()==="bottom"?-n:n,s=i.rotation?.z??0,a={...i.rotation??{x:0,y:0,z:0},z:k9(s+r)};t.cad_component.update(i.cad_component_id,{rotation:a}),i.rotation=a},m$=(t,e,n)=>{if(e===n)return!0;const o=t.source_group.get(e);return!o||!o.parent_source_group_id?!1:m$(t,o.parent_source_group_id,n)},FMo=(t,e,n,o)=>{const{db:i}=t.root;for(const r of e.components){if(r.isStatic)continue;const{center:s,componentId:a,ccwRotationOffset:A,ccwRotationDegrees:c}=r,l=n[a];if(l){const f=c??A??0,I=f*Math.PI/180;for(const C of l.componentIds){const y=l.relativeCenters[C];if(!y)continue;i.pcb_component.update(C,{position_mode:"packed"});const x={x:y.x*Math.cos(I)-y.y*Math.sin(I),y:y.x*Math.sin(I)+y.y*Math.cos(I)},E=i.pcb_component.get(C);if(!E)continue;const B=E.center,S=D0(t._computePcbGlobalTransformBeforeLayout(),M0(s.x+x.x,s.y+x.y),W4(I),M0(-B.x,-B.y)),Q=i.toArray().filter(w=>"pcb_component_id"in w&&w.pcb_component_id===C);FF(Q,S),tTt({db:i,pcbComponentId:C,rotationDegrees:f,layer:E.layer})}continue}const u=i.pcb_component.get(a);if(u){i.pcb_component.update(a,{position_mode:"packed"});const f=t.source_group_id,C=i.source_component.get(u.source_component_id)?.source_group_id;if(C!==void 0&&!m$(i,C,f))continue;const y=u.center,x=c??A??0,E=D0(t._computePcbGlobalTransformBeforeLayout(),M0(s.x,s.y),W4(x*Math.PI/180),M0(-y.x,-y.y)),B=i.toArray().filter(S=>"pcb_component_id"in S&&S.pcb_component_id===a);FF(B,E),tTt({db:i,pcbComponentId:a,rotationDegrees:x,layer:u.layer});continue}const g=i.pcb_group.list().find(f=>f.source_group_id===a);if(!g)continue;const d=o.components.find(f=>f.componentId===a)?.center??g.center,p=c??A??0,m=D0(t._computePcbGlobalTransformBeforeLayout(),M0(s.x,s.y),W4(p*Math.PI/180),M0(-d.x,-d.y)),_=i.toArray().filter(f=>{if("source_group_id"in f&&f.source_group_id&&(f.source_group_id===a||m$(i,f.source_group_id,a)))return!0;if("source_component_id"in f&&f.source_component_id){const I=i.source_component.get(f.source_component_id);if(I?.source_group_id&&(I.source_group_id===a||m$(i,I.source_group_id,a)))return!0}if("pcb_component_id"in f&&f.pcb_component_id){const I=i.pcb_component.get(f.pcb_component_id);if(I?.source_component_id){const C=i.source_component.get(I.source_component_id);if(C?.source_group_id&&(C.source_group_id===a||m$(i,C.source_group_id,a)))return!0}}return!1});for(const f of _)f.type==="pcb_component"&&i.pcb_component.update(f.pcb_component_id,{position_mode:"packed"});FF(_,m),i.pcb_group.update(g.pcb_group_id,{center:s})}if(t.pcb_group_id){const r=i.pcb_component.list({pcb_group_id:t.pcb_group_id});t.calculatePcbGroupBounds(N9e(r))}},nTt=t=>(t??"top").toLowerCase(),LMo=(t,e)=>{const n=new Set,o=e.pcb_component.get(t.componentId);o&&n.add(nTt(o.layer));for(const i of t.pads){const r=e.pcb_via.get(i.padId),s=e.pcb_smtpad.get(i.padId)?.pcb_component_id??e.pcb_plated_hole.get(i.padId)?.pcb_component_id??r?.pcb_component_id;if(!s)continue;const a=e.pcb_component.get(s);a&&n.add(nTt(a.layer))}return n.size===1?n.values().next().value:void 0},HMo=(t,e)=>{const n=new Map;for(const i of t.components){const r=LMo(i,e);if(!r)return[t];const s=n.get(r)??[];s.push(i),n.set(r,s)}if(n.size<=1)return[t];const o=i=>i==="top"?0:i==="bottom"?1:2;return Array.from(n.entries()).sort(([i],[r])=>o(i)-o(r)||i.localeCompare(r)).map(([,i])=>({...t,components:i}))},OMo="1mm",oTt=vc("Group_doInitialPcbLayoutPack"),iTt=t=>{if(t.courtyard&&t.center)return{obstacleId:t.componentId,absoluteCenter:{x:t.center.x+t.courtyard.offsetFromCenter.x,y:t.center.y+t.courtyard.offsetFromCenter.y},width:t.courtyard.width,height:t.courtyard.height};if(t.pads.length===0)return;let e=1/0,n=1/0,o=-1/0,i=-1/0;for(const r of t.pads){const s=r.absoluteCenter??(t.center?{x:t.center.x+r.offset.x,y:t.center.y+r.offset.y}:r.offset);e=Math.min(e,s.x-r.size.x/2),n=Math.min(n,s.y-r.size.y/2),o=Math.max(o,s.x+r.size.x/2),i=Math.max(i,s.y+r.size.y/2)}return{obstacleId:t.componentId,absoluteCenter:{x:(e+o)/2,y:(n+i)/2},width:o-e,height:i-n}},GMo=t=>{const{db:e}=t.root,{_parsedProps:n}=t;t.root?.emit("packing:start",{subcircuit_id:t.subcircuit_id,componentDisplayName:t.getString()});const{packOrderStrategy:o,packPlacementStrategy:i,gap:r,pcbGap:s,pcbPackGap:a}=n,A=a??s??r,c=ce.parse(A??OMo),l={},u=new Set,g=B=>{if(B?.pcb_component_id&&B?._parsedProps){const S=B._parsedProps,Q=ce.parse(S.pcbMarginLeft??S.pcbMarginX??0),w=ce.parse(S.pcbMarginRight??S.pcbMarginX??0),M=ce.parse(S.pcbMarginTop??S.pcbMarginY??0),k=ce.parse(S.pcbMarginBottom??S.pcbMarginY??0);(Q||w||M||k)&&(l[B.pcb_component_id]={left:Q,right:w,top:M,bottom:k})}B?.children&&B.children.forEach(g)};g(t);const h=new Set;for(const B of t.children){const S=B;S._isNormalComponent&&S.isRelativelyPositioned?.()&&(S.pcb_component_id&&u.add(S.pcb_component_id),S.pcb_group_id&&h.add(S.pcb_group_id))}const d=(B,S,Q)=>{if(S===Q)return!0;const w=B.source_group.get(S);return!w||!w.parent_source_group_id?!1:d(B,w.parent_source_group_id,Q)};if(h.size>0)for(const B of e.toArray()){if(B.type!=="pcb_component")continue;const S=e.source_component.get(B.source_component_id);if(S?.source_group_id)for(const Q of h)d(e,S.source_group_id,Q)&&u.add(B.pcb_component_id)}const p=e.toArray();let m;if(n.width!==void 0&&n.height!==void 0){const B=ce.parse(n.width),S=ce.parse(n.height);m={minX:-B/2,maxX:B/2,minY:-S/2,maxY:S/2}}const _=xfo(p,{source_group_id:t.source_group_id,chipMarginsMap:l,staticPcbComponentIds:Array.from(u)}),f={...Efo(_),packOrderStrategy:o??"largest_to_smallest",packPlacementStrategy:i??"minimum_sum_squared_distance_to_network",minGap:c,bounds:m},I=kMo(t,f);oTt.enabled&&(t.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${t.name}`,content:JSON.stringify(e.toArray())}),t.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${t.name}`,content:f}));const C=HMo(f,e),y={...f,components:[]};let x=!1;const E=B=>{const S=`Unable to pack all PCB components within the layout bounds: ${B}`;e.pcb_packing_error.insert({error_type:"pcb_packing_error",message:S,pcb_group_id:t.pcb_group_id??void 0,subcircuit_id:t.subcircuit_id??void 0}),t.root?.emit("packing:error",{subcircuit_id:t.subcircuit_id,componentDisplayName:t.getString(),error:{message:S}})};try{for(const B of C){const S=new Set(B.components.map(J=>J.componentId)),Q=B.components.flatMap(J=>{if(!J.isStatic)return[];const oe=iTt(J);return oe?[oe]:[]}),w=B.components.every(J=>!!e.pcb_component.get(J.componentId)&&!I[J.componentId]),M=f.components.filter(J=>J.isStatic&&!S.has(J.componentId)),k=w?[]:M.flatMap(J=>{const oe=iTt(J);return oe?[oe]:[]}),R=new Set([...B.components.filter(J=>J.isStatic),...w?[]:M].flatMap(J=>J.pads.map(oe=>oe.padId))),F=new Map([...y.components.map(J=>[J.componentId,{component:J,courtyardSize:Number.EPSILON}]),...w?M.map(J=>[J.componentId,{component:J,courtyardSize:1e-6}]):[]]),O=Array.from(F.values(),({component:J,courtyardSize:oe})=>({...J,componentId:`network_reference_${J.componentId}`,isStatic:!0,courtyard:{offsetFromCenter:{x:0,y:0},width:oe,height:oe}})),U={...B,weightedConnections:B.weightedConnections?.filter(J=>J.padIds.every(oe=>!R.has(oe))),obstacles:[...B.obstacles??[],...Q,...k],components:[...O,...B.components.filter(J=>!J.isStatic)]},Y=new rj(U),W=Y.getConstructorParams();t.root?.emit("solver:started",{type:"solver:started",solverName:"PackSolver2",solverParams:W,solverConstructorArgs:[W],componentName:t.getString()});const te=t.root?.platform?.pcbPackSolverTimeoutMs,{timedOut:j}=TMo(Y,te);if(j&&(x=!0,E(`PackSolver2 timed out after ${te}ms`)),Y.failed){x=!0;const J=Y.error??Y.activeSubSolver?.error??"No valid packing solution found";E(J)}if(y.components.push(...Y.packedComponents.filter(J=>S.has(J.componentId))),j)break}}catch(B){throw E(B instanceof Error?B.message:String(B)),B}if(oTt.enabled&&global?.debugGraphics){const B=Zbt(y);B.title=`packOutput-${t.name}`,global.debugGraphics?.push(B)}FMo(t,y,I,_),!x&&t.root?.emit("packing:end",{subcircuit_id:t.subcircuit_id,componentDisplayName:t.getString()})},YMo=t=>{if(!t)return null;const e=t.match(/^pin(\d+)$/i)??t.match(/^(\d+)$/);if(!e)return null;const n=Number(e[1]);return Number.isFinite(n)&&n>0?n:null},rTt=t=>t.children.filter(e=>e.componentName==="Port"),UMo=t=>{const{db:e}=t.root,n=rTt(t);for(const r of n){if(r._parsedProps.pinNumber!==void 0)continue;const s=YMo(r._parsedProps.name);s!==null&&(r._parsedProps.pinNumber=s)}const o=new Set(n.map(r=>r._parsedProps.pinNumber).filter(r=>r!==void 0));let i=1;for(const r of n){if(r._parsedProps.pinNumber===void 0){for(;o.has(i);)i++;r._parsedProps.pinNumber=i,o.add(i)}r.source_port_id&&e.source_port.update(r.source_port_id,{pin_number:r._parsedProps.pinNumber,port_hints:r.getNameAndAliases()})}},KMo=t=>{const e={};for(const n of rTt(t)){const o=n._parsedProps.pinNumber,i=n._parsedProps.name;o===void 0||!i||i===`pin${o}`||i===String(o)||(e[`pin${o}`]=i)}return e},VMo=t=>{if(t.root?.schematicDisabled)return;const{db:e}=t.root,n=t._parsedProps;n.schPinSpacing!==void 0&&e.source_property_ignored_warning.insert({source_component_id:t.source_group_id??"",property_name:"schPinSpacing",error_type:"source_property_ignored_warning",message:"schPinSpacing is deprecated and will be ignored. Pin spacing is always 0.2."}),UMo(t);const o=t._getSchematicBoxDimensions();if(!o)return;const i=t._getGlobalSchematicPositionBeforeLayout(),r=o.getSize(),s=t._getPinLabelsFromPorts(),a=t._getSchematicPortArrangement(),A=e.schematic_component.insert({center:i,size:r,source_group_id:t.source_group_id,schematic_group_id:t.schematic_group_id??void 0,subcircuit_id:t.subcircuit_id??t.getSubcircuit()?.subcircuit_id??void 0,is_schematic_group:!0,is_box_with_pins:!0,port_arrangement:ePe(a),pin_spacing:.2,pin_styles:Zwe(n.schPinStyle,s),port_labels:s,schematic_sheet_id:t._resolveSchematicSheetId()});t.schematic_component_id=A.schematic_component_id,t.schematic_group_id&&e.schematic_group.update(t.schematic_group_id,{center:i,width:r.width,height:r.height,schematic_component_ids:[A.schematic_component_id]});const c=n.schTitle??n.name;c&&e.schematic_text.insert({text:c,schematic_component_id:A.schematic_component_id,anchor:"left",rotation:0,position:{x:i.x-r.width/2,y:i.y+r.height/2+.13},color:"#006464",font_size:.18,schematic_sheet_id:t._resolveSchematicSheetId()})},sTt=(t,e)=>{const{sourceComponent:n,sourceGroup:o}=e;if(e.nodeType==="component"){const i=t.schematic_component.getWhere({source_component_id:n?.source_component_id});return i?.size?{width:i.size.width,height:i.size.height}:null}if(e.nodeType==="group"){const i=t.schematic_group.getWhere({source_group_id:o?.source_group_id});if(i?.width&&i?.height)return{width:i.width,height:i.height};const r=t.schematic_component.list({schematic_group_id:i?.schematic_group_id});let s=1/0,a=-1/0,A=1/0,c=-1/0;for(const g of r)if(g.center&&g.size){const h=g.size.width/2,d=g.size.height/2;s=Math.min(s,g.center.x-h),a=Math.max(a,g.center.x+h),A=Math.min(A,g.center.y-d),c=Math.max(c,g.center.y+d)}const l=a-s,u=c-A;return{width:l,height:u}}return null},zMo=t=>{const{db:e}=t.root,n=t._parsedProps,o=mz(e.toArray(),{source_group_id:t.source_group_id}),i=n.schJustifyContent??n.justifyContent,r=n.schAlignItems??n.alignItems,s=n.schFlexGap??n.schGap??n.gap,a=n.schFlexDirection??"row",A={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"}[i??"space-between"],c={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[r??"center"];if(!A)throw new Error(`Invalid justifyContent value: "${i}"`);if(!c)throw new Error(`Invalid alignItems value: "${r}"`);let l=0,u=0;typeof s=="object"?(l=s.y??0,u=s.x??0):typeof s=="number"?(l=s,u=s):typeof s=="string"&&(l=ce.parse(s),u=ce.parse(s));let g,h=n.width??n.schWidth??void 0,d=n.height??n.schHeight??void 0;(h===void 0||d===void 0)&&(g=lmt(o.childNodes.map(C=>sTt(e,C)).filter(C=>C!==null),{direction:a,rowGap:l,columnGap:u}),h=g.width,d=g.height);const m=new Qwt(h,d,{alignItems:c,justifyContent:A,direction:a,rowGap:l,columnGap:u});for(const C of o.childNodes){const y=sTt(e,C);m.addChild({metadata:C,width:y?.width??0,height:y?.height??0,flexBasis:y?a==="row"?y.width:y.height:void 0})}m.build();const _={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(const C of m.children)_.minX=Math.min(_.minX,C.position.x),_.minY=Math.min(_.minY,C.position.y),_.maxX=Math.max(_.maxX,C.position.x+C.size.width),_.maxY=Math.max(_.maxY,C.position.y+C.size.height);_.width=_.maxX-_.minX,_.height=_.maxY-_.minY;const f={x:-(_.maxX+_.minX)/2,y:-(_.maxY+_.minY)/2},I=e.toArray();for(const C of m.children){const{sourceComponent:y,sourceGroup:x}=C.metadata;if(y){const E=e.schematic_component.getWhere({source_component_id:y.source_component_id});if(!E)continue;DWn(I,E.schematic_component_id,{x:C.position.x+C.size.width/2+f.x,y:C.position.y+C.size.height/2+f.y})}if(x){if(!e.schematic_group.getWhere({source_group_id:x.source_group_id}))continue;NWn(I,x.source_group_id,{x:C.position.x+C.size.width/2+f.x,y:C.position.y+C.size.height/2+f.y})}}t.schematic_group_id&&e.schematic_group.update(t.schematic_group_id,{width:_.width,height:_.height})};function MO({db:t,schematicComponentId:e,deltaX:n,deltaY:o}){const i=t.schematic_rect.list({schematic_component_id:e});for(const c of i)c.center.x+=n,c.center.y+=o;const r=t.schematic_line.list({schematic_component_id:e});for(const c of r)c.x1+=n,c.y1+=o,c.x2+=n,c.y2+=o;const s=t.schematic_circle.list({schematic_component_id:e});for(const c of s)c.center.x+=n,c.center.y+=o;const a=t.schematic_arc.list({schematic_component_id:e});for(const c of a)c.center.x+=n,c.center.y+=o;const A=t.schematic_path.list({schematic_component_id:e});for(const c of A)for(const l of c.points)l.x+=n,l.y+=o}function JMo(t){const{db:e}=t.root,n=t._parsedProps,o=t.children.filter(y=>{const x=y._parsedProps?.schX!==void 0||y._parsedProps?.schY!==void 0;return y.schematic_component_id&&!x});if(o.length===0)return;let i=0,r=0;for(const y of o){const x=e.schematic_component.get(y.schematic_component_id);x?.size&&(i=Math.max(i,x.size.width),r=Math.max(r,x.size.height))}i===0&&o.length>0&&(i=1),r===0&&o.length>0&&(r=1);let s=n.gridCols,a,A=n.gridGap,c=n.gridRowGap,l=n.gridColumnGap;n.schLayout?.grid&&(s=n.schLayout.grid.cols??s,a=n.schLayout.grid.rows,A=n.schLayout.gridGap??A,c=n.schLayout.gridRowGap??c,l=n.schLayout.gridColumnGap??l);let u,g;s!==void 0&&a!==void 0?(u=s,g=a):s!==void 0?(u=s,g=Math.ceil(o.length/u)):a!==void 0?(g=a,u=Math.ceil(o.length/g)):(u=Math.ceil(Math.sqrt(o.length)),g=Math.ceil(o.length/u)),u===0&&o.length>0&&(u=1),g===0&&o.length>0&&(g=o.length);let h,d;const p=y=>{if(y!==void 0)return typeof y=="number"?y:ce.parse(y)};if(c!==void 0||l!==void 0){const y=typeof A=="object"&&A!==null?A.x:A,x=typeof A=="object"&&A!==null?A.y:A;h=p(l??y)??1,d=p(c??x)??1}else if(typeof A=="number")h=A,d=A;else if(typeof A=="string"){const y=ce.parse(A);h=y,d=y}else if(typeof A=="object"&&A!==null){const y=A.x,x=A.y;h=typeof y=="number"?y:ce.parse(y??"0mm"),d=typeof x=="number"?x:ce.parse(x??"0mm")}else h=1,d=1;const m=u*i+Math.max(0,u-1)*h,_=g*r+Math.max(0,g-1)*d,f=t._getGlobalSchematicPositionBeforeLayout(),I=f.x-m/2+i/2,C=f.y+_/2-r/2;for(let y=0;y<o.length;y++){const x=o[y];if(!x.schematic_component_id)continue;const E=Math.floor(y/u),B=y%u;if(E>=g||B>=u){console.warn(`Schematic grid layout: Child ${x.getString()} at index ${y} (row ${E}, col ${B}) exceeds specified grid dimensions (${g}x${u}). Skipping placement.`);continue}const S=I+B*(i+h),Q=C-E*(r+d),w=e.schematic_component.get(x.schematic_component_id);if(w){const M=w.center,k={x:S,y:Q};e.schematic_component.update(x.schematic_component_id,{center:k});const R=k.x-M.x,F=k.y-M.y,O=e.schematic_port.list({schematic_component_id:x.schematic_component_id});for(const Y of O)e.schematic_port.update(Y.schematic_port_id,{center:{x:Y.center.x+R,y:Y.center.y+F}});const U=e.schematic_text.list({schematic_component_id:x.schematic_component_id});for(const Y of U)e.schematic_text.update(Y.schematic_text_id,{position:{x:Y.position.x+R,y:Y.position.y+F}});MO({db:e,schematicComponentId:x.schematic_component_id,deltaX:R,deltaY:F})}}t.schematic_group_id&&e.schematic_group.update(t.schematic_group_id,{width:m,height:_,center:f})}var aTt=vc("Group_doInitialSchematicLayoutMatchAdapt");function WMo(t){const{db:e}=t.root,n=dz(e.toArray(),{source_group_id:t.source_group_id});if(n.filter(A=>A.type==="source_component").length<=1)return;const i=lEo(n);aTt.enabled&&global?.debugGraphics&&global.debugGraphics?.push(zN(i,{title:`floatingBpcGraph-${t.name}`}));const r={boxes:i.boxes,pins:i.pins.map(A=>({...A,color:A.color.replace("not_connected","normal")}))},{result:s}=HEo([{variantName:"default",floatingGraph:i},{variantName:"noNotConnected",floatingGraph:r}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(i.boxes.filter(A=>i.pins.filter(u=>u.boxId===A.boxId).filter(u=>!u.color.includes("center")).length<=2).map(A=>A.boxId)),corpus:{}});aTt.enabled&&global?.debugGraphics&&global.debugGraphics?.push(zN(s,{title:`laidOutBpcGraph-${t.name}`}));const a=t._getGlobalSchematicPositionBeforeLayout();for(const A of s.boxes){if(!A.center)continue;const c=e.schematic_component.get(A.boxId);if(c){const u={x:A.center.x+a.x,y:A.center.y+a.y},g=e.schematic_port.list({schematic_component_id:c.schematic_component_id}),h=e.schematic_text.list({schematic_component_id:c.schematic_component_id}),d={x:u.x-c.center.x,y:u.y-c.center.y};for(const p of g)p.center.x+=d.x,p.center.y+=d.y;for(const p of h)p.position.x+=d.x,p.position.y+=d.y;MO({db:e,schematicComponentId:c.schematic_component_id,deltaX:d.x,deltaY:d.y}),c.center=u;continue}const l=e.schematic_net_label.get(A.boxId);if(l){const u=s.pins.find(h=>h.boxId===A.boxId&&h.color==="netlabel_center");if(!u)throw new Error(`No pin found for net label: ${A.boxId}`);const g={x:A.center.x+a.x,y:A.center.y+a.y};l.center=g,l.anchor_position={x:g.x+u.offset.x,y:g.y+u.offset.y};continue}console.error(`No schematic element found for box: ${A.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}function ATt({text:t,fontSize:e}){const o=.12*(e/.18);return t.length*o}var jMo=.18,$Mo=new Set(["simple_resistor","simple_capacitor","simple_inductor","simple_crystal","simple_resonator","simple_potentiometer","simple_fuse","simple_diode","simple_led","simple_transistor","simple_mosfet","simple_op_amp","simple_voltage_source","simple_test_point"]);function cTt({text:t,position:e,anchor:n,fontSize:o}){const i=ATt({text:t,fontSize:o}),r=o;let s,a;n.includes("left")?(s=0,a=i):n.includes("right")?(s=-i,a=0):(s=-i/2,a=i/2);let A,c;return n.includes("top")?(A=-r,c=0):n.includes("bottom")?(A=0,c=r):(A=-r/2,c=r/2),{minX:e.x+s,maxX:e.x+a,minY:e.y+A,maxY:e.y+c}}function qMo({schematicComponent:t,sourceComponent:e}){if(!t.symbol_name)return[];const n=Su[t.symbol_name];if(!n?.primitives||!n.center)return[];const o=[];for(const i of n.primitives){if(i.type!=="text")continue;let r;i.text==="{REF}"?r=e?.display_name??e?.name??"":i.text==="{VAL}"?r=t.symbol_display_value??"":r=i.text??"",r&&o.push(cTt({text:r,position:{x:i.x-n.center.x+t.center.x,y:i.y-n.center.y+t.center.y},anchor:i.anchor??"center",fontSize:jMo}))}return o}function lTt(t){return Ey({center:t.center,width:t.size.width,height:t.size.height})}function XMo(t,e){if(!e.center||!e.size)return null;const n=e.source_component_id?t.source_component.get(e.source_component_id):void 0;if(!n||!$Mo.has(n.ftype))return null;const o=qMo({schematicComponent:e,sourceComponent:n});if(o.length===0)return null;const i=lTt(e),r={...i};for(const s of o)r.minX=Math.min(r.minX,s.minX),r.maxX=Math.max(r.maxX,s.maxX),r.minY=Math.min(r.minY,s.minY),r.maxY=Math.max(r.maxY,s.maxY);return r.minX===i.minX&&r.maxX===i.maxX&&r.minY===i.minY&&r.maxY===i.maxY?null:r}function ZMo(t,e){let n=t.size;return n&&(n=kwe(n,e)),{...t,symbol_name:Rwe(t.symbol_name,e),size:n}}function vue({db:t,schematicComponent:e,ccwRotationDegrees:n=0}){const o=ZMo(e,n),i=XMo(t,o);if(!i)return null;const r=lTt(o);if(o.size.height>o.size.width)return i;const a=Math.max(0,r.minX-i.minX),A=Math.max(0,i.maxX-r.maxX),c=Math.max(0,i.maxY-r.maxY),l=Math.max(0,r.minY-i.minY);let u=a,g=A;a>0&&A>0&&(u=Math.max(a,A),g=u);let h=c,d=l;return c>0&&l>0&&(h=Math.max(c,l),d=h),{minX:r.minX-u,maxX:r.maxX+g,minY:r.minY-d,maxY:r.maxY+h}}var js=vc("Group_doInitialSchematicLayoutMatchpack"),uTt=[0,90,180,270],eDo={"y+":0,"x+":90,"y-":180,"x-":270};function CMe(t){switch(t){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function tDo(t,e){if(e.length!==2)return null;const n=new Set;for(const o of e){const r=t.source_port.get(o.source_port_id)?.subcircuit_connectivity_map_key;if(!r)continue;const s=t.source_net.getWhere({subcircuit_connectivity_map_key:r});if(!s)continue;const a=s.is_ground??!1,A=s.is_power===!0||s.is_positive_voltage_source===!0;if(A===a)continue;const c=eDo[CMe(o.facing_direction)],l=A?c:(c+180)%360;n.add(l)}return n.size===1?n.values().next().value:null}function gTt({db:t,schematicComponent:e,component:n,ccwRotationDegrees:o}){let i=e.size;i&&(i=kwe(i,o));const r=vue({db:t,schematicComponent:e,ccwRotationDegrees:o});let s=0,a=0,A=0,c=0;if(r&&e.center){const m=(i?.width??0)/2,_=(i?.height??0)/2;s=e.center.x-m-r.minX,a=r.maxX-(e.center.x+m),A=r.maxY-(e.center.y+_),c=e.center.y-_-r.minY}const l=(n?._parsedProps?.schMarginLeft??n?._parsedProps?.schMarginX??0)+s,u=(n?._parsedProps?.schMarginRight??n?._parsedProps?.schMarginX??0)+a;let g=(n?._parsedProps?.schMarginTop??n?._parsedProps?.schMarginY??0)+A,h=(n?._parsedProps?.schMarginBottom??n?._parsedProps?.schMarginY??0)+c;n?.config.shouldRenderAsSchematicBox&&(g+=.4,h+=.4);const d={width:(i?.width||1)+l+u,height:(i?.height||1)+g+h},p=kwe(d,o);return{x:p.width,y:p.height}}function nDo({db:t,schematicComponent:e,component:n,ccwRotationDegrees:o,chipGap:i}){const r=gTt({db:t,schematicComponent:e,component:n,ccwRotationDegrees:0});if(!Twe(o))return r;const s=gTt({db:t,schematicComponent:e,component:n,ccwRotationDegrees:o});return s.x-r.x>=i||s.y-r.y>=i?s:r}function oDo({db:t,schematicGroup:e,groupComponents:n,groupInstance:o}){let i=1/0,r=-1/0,s=1/0,a=-1/0,A=!1;for(const d of n){if(!d.center||!d.size)continue;A=!0;const p=vue({db:t,schematicComponent:d})??Ey({center:d.center,width:d.size.width,height:d.size.height});i=Math.min(i,p.minX),r=Math.max(r,p.maxX),s=Math.min(s,p.minY),a=Math.max(a,p.maxY)}const c=o?._parsedProps?.schMarginLeft??o?._parsedProps?.schMarginX??0,l=o?._parsedProps?.schMarginRight??o?._parsedProps?.schMarginX??0,u=o?._parsedProps?.schMarginTop??o?._parsedProps?.schMarginY??0,g=o?._parsedProps?.schMarginBottom??o?._parsedProps?.schMarginY??0,h=A?{x:(i+r)/2,y:(s+a)/2}:e.center??{x:0,y:0};return{center:{x:h.x+(l-c)/2,y:h.y+(u-g)/2},size:{x:(A?r-i:2)+c+l,y:(A?a-s:2)+u+g}}}function iDo(t,e){if(t.nodeType==="component"&&t.sourceComponent){const n=e.children.find(o=>o.source_component_id===t.sourceComponent?.source_component_id);return n?._parsedProps?.schX!==void 0||n?._parsedProps?.schY!==void 0}if(t.nodeType==="group"&&t.sourceGroup){const n=e.children.find(o=>o.source_group_id===t.sourceGroup?.source_group_id);return n?._parsedProps?.schX!==void 0||n?._parsedProps?.schY!==void 0}return!1}function DO(t,e){return t.nodeType==="component"&&t.sourceComponent?t.sourceComponent.name||`chip_${e}`:t.nodeType==="group"&&t.sourceGroup?t.sourceGroup.name||`group_${e}`:null}var dTt=({db:t,sourceComponentId:e,schematicSheetId:n})=>t.schematic_component.getWhere({source_component_id:e,...n?{schematic_sheet_id:n}:{}});function rDo(t,e,n,o={}){const i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2},r={},s=n._getGlobalSchematicPositionBeforeLayout();js(`[${n.name}] Processing ${t.childNodes.length} child nodes for input problem`),t.childNodes.forEach((A,c)=>{const l=iDo(A,n);if(js(l?`[${n.name}] Child ${c} explicitly positioned, including as fixed chip`:`[${n.name}] Processing child ${c}: nodeType=${A.nodeType}`),A.nodeType==="component"?js(`[${n.name}] - Component: ${A.sourceComponent?.name}`):A.nodeType==="group"&&js(`[${n.name}] - Group: ${A.sourceGroup?.name}`),A.nodeType==="component"&&A.sourceComponent){const u=DO(A,c),g=dTt({db:e,sourceComponentId:A.sourceComponent.source_component_id,schematicSheetId:o.schematicSheetId});if(!g)return;const h=n.children.find(_=>_.source_component_id===A.sourceComponent?.source_component_id),d=e.schematic_port.list({schematic_component_id:g.schematic_component_id});let p=[...uTt];if(h?._parsedProps?.schOrientation&&(p=[0]),h?._parsedProps?.schRotation!==void 0&&(p=[0]),h?._parsedProps?.facingDirection&&(p=[0]),h?._parsedProps?.schFacingDirection&&(p=[0]),h?.componentName==="Chip"&&(p=[0]),p.length===uTt.length){const _=tDo(e,d);_!==null&&(p=[_])}const m=p.length===1?p[0]:0;i.chipMap[u]={chipId:u,pins:[],size:nDo({db:e,schematicComponent:g,component:h,ccwRotationDegrees:m,chipGap:i.chipGap}),isCapacitor:A.sourceComponent.ftype==="simple_capacitor",isCrystal:A.sourceComponent.ftype==="simple_crystal",isResistor:A.sourceComponent.ftype==="simple_resistor",isTestPoint:A.sourceComponent.ftype==="simple_test_point",availableRotations:p,...l&&{fixedPosition:{x:g.center.x-s.x,y:g.center.y-s.y}}};for(const _ of d){const f=e.source_port.get(_.source_port_id);if(!f)continue;const I=`${u}.${f.pin_number||f.name||_.schematic_port_id}`;i.chipMap[u].pins.push(I);const C=CMe(_.facing_direction);i.chipPinMap[I]={pinId:I,offset:{x:(_.center?.x||0)-(g.center.x||0),y:(_.center?.y||0)-(g.center.y||0)},side:C}}}else if(A.nodeType==="group"&&A.sourceGroup){const u=DO(A,c);js(`[${n.name}] Processing nested group: ${u}`);const g=e.schematic_group?.getWhere?.({source_group_id:A.sourceGroup.source_group_id}),h=n.children.find(d=>d.source_group_id===A.sourceGroup?.source_group_id);if(js(`[${n.name}] Found schematic_group for ${u}:`,g),g){js(`[${n.name}] Treating group ${u} as composite chip`);const d=e.schematic_component.list({schematic_group_id:g.schematic_group_id});js(`[${n.name}] Group ${u} has ${d.length} components:`,d.map(_=>_.source_component_id));const p=oDo({db:e,schematicGroup:g,groupComponents:d,groupInstance:h});r[u]=p,js(`[${n.name}] Group ${u} computed proxy: ${p.size.x} x ${p.size.y} centered at (${p.center.x}, ${p.center.y})`);const m=[];for(const _ of d){const f=e.schematic_port.list({schematic_component_id:_.schematic_component_id});for(const I of f){const C=e.source_port.get(I.source_port_id);if(!C)continue;const y=`${u}.${C.pin_number||C.name||I.schematic_port_id}`;m.push(y);const x=CMe(I.facing_direction);i.chipPinMap[y]={pinId:y,offset:{x:(I.center?.x||0)-p.center.x,y:(I.center?.y||0)-p.center.y},side:x}}}js(`[${n.name}] Group ${u} has ${m.length} pins:`,m),i.chipMap[u]={chipId:u,pins:m,size:p.size},js(`[${n.name}] Added group ${u} to chipMap`)}else js(`[${n.name}] Warning: No schematic_group found for group ${u}`)}}),js(`[${n.name}] Creating connections using connectivity keys`);const a=new Map;for(const[A,c]of Object.entries(i.chipMap))for(const l of c.pins){const u=l.split(".").pop(),g=t.childNodes.find(h=>DO(h,t.childNodes.indexOf(h))===A);if(g?.nodeType==="group"&&g.sourceGroup){const h=e.schematic_group?.getWhere?.({source_group_id:g.sourceGroup.source_group_id});if(h){const d=e.schematic_component.list({schematic_group_id:h.schematic_group_id});for(const p of d){const m=e.source_port.list({source_component_id:p.source_component_id});for(const _ of m){const f=_.pin_number||_.name;if(String(f)===String(u))if(_.subcircuit_connectivity_map_key){const I=_.subcircuit_connectivity_map_key;a.has(I)||a.set(I,[]),a.get(I).push(l),js(`[${n.name}] ✓ Pin ${l} has connectivity key: ${I}`)}else js(`[${n.name}] Pin ${l} has no connectivity key`)}}}}else if(g?.nodeType==="component"&&g.sourceComponent){const h=e.source_port.list({source_component_id:g.sourceComponent.source_component_id});for(const d of h){const p=d.pin_number||d.name;if(String(p)===String(u)&&d.subcircuit_connectivity_map_key){const m=d.subcircuit_connectivity_map_key;a.has(m)||a.set(m,[]),a.get(m).push(l),js(`[${n.name}] Pin ${l} has connectivity key: ${m}`)}}}}js(`[${n.name}] Found ${a.size} connectivity groups:`,Array.from(a.entries()).map(([A,c])=>({key:A,pins:c})));for(const[A,c]of a){const l=e.source_trace.list().filter(h=>h.subcircuit_connectivity_map_key===A),u=l.some(h=>h.connected_source_net_ids&&h.connected_source_net_ids.length>0),g=l.some(h=>h.connected_source_port_ids&&h.connected_source_port_ids.length>=2);if(js(`[${n.name}] Connectivity ${A}: hasNetConnections=${u}, hasDirectConnections=${g}`),c.length>=2&&g){for(const h of l)if(h.connected_source_port_ids&&h.connected_source_port_ids.length>=2){const d=[];for(const p of h.connected_source_port_ids)for(const m of c){const _=m.split(".").pop(),f=e.source_port.get(p);if(f&&String(f.pin_number||f.name)===String(_)){const I=m.split(".")[0],C=t.childNodes.find(y=>DO(y,t.childNodes.indexOf(y))===I);C?.nodeType==="component"&&C.sourceComponent&&e.source_port.list({source_component_id:C.sourceComponent.source_component_id}).some(x=>x.source_port_id===p)&&d.push(m)}}for(let p=0;p<d.length;p++)for(let m=p+1;m<d.length;m++){const _=d[p],f=d[m];i.pinStrongConnMap[`${_}-${f}`]=!0,i.pinStrongConnMap[`${f}-${_}`]=!0,js(`[${n.name}] Created strong connection: ${_} <-> ${f}`)}}}if(u){const h=e.source_net.getWhere({subcircuit_connectivity_map_key:A}),d=h?.is_ground??!1,p=h?.is_power===!0||h?.is_positive_voltage_source===!0;i.netMap[A]={netId:A,isGround:d,isPositiveVoltageSource:p};for(const m of c)i.netConnMap[`${m}-${A}`]=!0;js(`[${n.name}] Created net ${A} with ${c.length} pins:`,c)}}return{inputProblem:i,nestedGroupMatchpackProxyMap:r}}function hTt(t,e,n={}){const{db:o}=t.root;if(js(`[${t.name}] Starting matchpack layout with ${e.childNodes.length} children`),js(`[${t.name}] Tree structure:`,JSON.stringify(e,null,2)),e.childNodes.length<=1){js(`[${t.name}] Only ${e.childNodes.length} children, skipping layout`);return}js("Converting circuit tree to InputProblem...");const{inputProblem:i,nestedGroupMatchpackProxyMap:r}=rDo(e,o,t,n);js.enabled&&t.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${t.name}`,content:JSON.stringify(i,null,2)});const s=new ZSt(i);if(t.root?.emit("solver:started",{type:"solver:started",solverName:"LayoutPipelineSolver",solverParams:i,solverConstructorArgs:[i],componentName:t.getString()}),js("Starting LayoutPipelineSolver..."),js.enabled&&global?.debugGraphics){const l=s.visualize();global.debugGraphics.push({...l,title:`matchpack-initial-${t.name}`})}if(s.solve(),t.root?.emit("solver:ended",{type:"solver:ended",solverName:"LayoutPipelineSolver",componentName:t.getString(),solved:s.solved,failed:s.failed,iterations:s.iterations,error:s.error}),js(`Solver completed in ${s.iterations} iterations`),js(`Solved: ${s.solved}, Failed: ${s.failed}`),s.failed){const l=s.error??"Unknown Matchpack failure";js(`Solver failed with error: ${l}`),o.schematic_layout_error.insert({error_type:"schematic_layout_error",message:`Matchpack layout solver failed: ${l}`,is_fatal:!1,source_group_id:t.source_group_id,schematic_group_id:t.schematic_group_id,subcircuit_id:t.subcircuit_id??void 0});return}const a=s.getOutputLayout();if(js("OutputLayout:",JSON.stringify(a,null,2)),js("Solver completed successfully:",!s.failed),js.enabled&&global?.debugGraphics){const l=s.visualize();global.debugGraphics.push({...l,title:`matchpack-final-${t.name}`})}const A=s.checkForOverlaps(a);if(A.length>0){js(`Warning: Found ${A.length} overlapping components:`);for(const l of A)js(`  ${l.chip1} overlaps ${l.chip2} (area: ${l.overlapArea})`)}const c=t._getGlobalSchematicPositionBeforeLayout();js(`Group offset: x=${c.x}, y=${c.y}`),js(`Applying layout results for ${Object.keys(a.chipPlacements).length} chip placements`);for(const[l,u]of Object.entries(a.chipPlacements)){js(`Processing placement for chip: ${l} at (${u.x}, ${u.y})`);const g=e.childNodes.find(d=>{const p=DO(d,e.childNodes.indexOf(d)),m=p===l;return js(`  Checking child ${p}: matches=${m}`),m});if(!g){js(`Warning: No tree node found for chip: ${l}`),js("Available tree nodes:",e.childNodes.map((d,p)=>({type:d.nodeType,name:d.nodeType==="component"?d.sourceComponent?.name:d.sourceGroup?.name,expectedChipId:DO(d,p)})));continue}const h={x:u.x+c.x,y:u.y+c.y};if(g.nodeType==="component"&&g.sourceComponent){const d=t.children.find(m=>m.source_component_id===g.sourceComponent?.source_component_id);if(d?._parsedProps?.schX!==void 0||d?._parsedProps?.schY!==void 0){js(`Skipping position update for fixed chip ${l}`);continue}const p=dTt({db:o,sourceComponentId:g.sourceComponent.source_component_id,schematicSheetId:n.schematicSheetId});if(p){js(`Moving component ${l} to (${h.x}, ${h.y})`);const m=o.schematic_port.list({schematic_component_id:p.schematic_component_id}),_=o.schematic_text.list({schematic_component_id:p.schematic_component_id}),f={x:h.x-p.center.x,y:h.y-p.center.y};for(const I of m)I.center.x+=f.x,I.center.y+=f.y;for(const I of _)I.position.x+=f.x,I.position.y+=f.y;if(MO({db:o,schematicComponentId:p.schematic_component_id,deltaX:f.x,deltaY:f.y}),p.center=h,u.ccwRotationDegrees!==0){js(`Component ${l} has rotation: ${u.ccwRotationDegrees}°`);const I=(Math.round(u.ccwRotationDegrees)%360+360)%360;if((I===90||I===270)&&p.size){const E=p.size.width;p.size.width=p.size.height,p.size.height=E}const C=u.ccwRotationDegrees*Math.PI/180,y=Math.cos(C),x=Math.sin(C);for(const E of m){const B=E.center.x-h.x,S=E.center.y-h.y,Q=B*y-S*x,w=B*x+S*y;E.center.x=h.x+Q,E.center.y=h.y+w;const M=E.facing_direction||"right";E.facing_direction=cMt(M,u.ccwRotationDegrees),E.side_of_component=(E.facing_direction==="up"?"top":E.facing_direction==="down"?"bottom":E.facing_direction)||E.side_of_component}for(const E of _){const B=E.position.x-h.x,S=E.position.y-h.y,Q=B*y-S*x,w=B*x+S*y;E.position.x=h.x+Q,E.position.y=h.y+w}p.symbol_name&&(p.symbol_name=Rwe(p.symbol_name,u.ccwRotationDegrees))}}}else if(g.nodeType==="group"&&g.sourceGroup){const d=o.schematic_group?.getWhere?.({source_group_id:g.sourceGroup.source_group_id});if(d){js(`Moving group ${l} to (${h.x}, ${h.y}) from (${d.center?.x}, ${d.center?.y})`);const p=o.schematic_component.list({schematic_group_id:d.schematic_group_id});js(`Group ${l} has ${p.length} components to move`);const m=r[l],_=m?.center??d.center??{x:0,y:0},f={x:h.x-_.x,y:h.y-_.y};js(`Position delta for group ${l}: (${f.x}, ${f.y})`);for(const I of p)if(I.center){const C={...I.center};I.center.x+=f.x,I.center.y+=f.y,js(`Moved component ${I.source_component_id} from (${C.x}, ${C.y}) to (${I.center.x}, ${I.center.y})`);const y=o.schematic_port.list({schematic_component_id:I.schematic_component_id}),x=o.schematic_text.list({schematic_component_id:I.schematic_component_id});for(const E of y)E.center&&(E.center.x+=f.x,E.center.y+=f.y);for(const E of x)E.position&&(E.position.x+=f.x,E.position.y+=f.y);MO({db:o,schematicComponentId:I.schematic_component_id,deltaX:f.x,deltaY:f.y})}d.center=h,m&&(d.width=m.size.x,d.height=m.size.y),js(`Updated group ${l} center to (${h.x}, ${h.y})`)}}}js("Matchpack layout completed successfully")}function sDo({circuitJson:t,schematicSheetIdsBySourceComponentId:e}){const n=new Map;for(const i of t)i.type==="source_group"&&n.set(i.source_group_id,i.parent_source_group_id);const o=new Map;for(const i of t){if(i.type!=="source_component"||!i.source_group_id)continue;const r=e.get(i.source_component_id);if(r!==void 0)for(const s of r){let a=i.source_group_id;const A=new Set;for(;a&&!A.has(a);){A.add(a);const c=o.get(a)??new Set;c.add(s),o.set(a,c),a=n.get(a)}}}return o}function aDo({circuitJson:t,schematicSheetId:e,rootSourceGroupId:n,schematicSheetIdsBySourceComponentId:o,schematicSheetIdsBySourceGroupId:i}){const r=s=>s===n||i.get(s)?.has(e)===!0;return t.filter(s=>s.type==="source_group"?r(s.source_group_id):s.type==="source_component"?o.get(s.source_component_id)?.has(e)!==!0?!1:s.source_group_id?r(s.source_group_id):!0:!0)}function ADo(t,e){const{source_group_id:n}=e,o=new Map;for(const s of t){if(s.type!=="schematic_component"||!s.source_component_id||!s.schematic_sheet_id)continue;const a=o.get(s.source_component_id)??new Set;a.add(s.schematic_sheet_id),o.set(s.source_component_id,a)}const i=new Set;for(const s of o.values())for(const a of s)i.add(a);if(i.size<=1)return[{tree:mz(t,{source_group_id:n}),schematicSheetId:i.values().next().value}];const r=sDo({circuitJson:t,schematicSheetIdsBySourceComponentId:o});return Array.from(i).map(s=>({tree:mz(aDo({circuitJson:t,schematicSheetId:s,rootSourceGroupId:n,schematicSheetIdsBySourceComponentId:o,schematicSheetIdsBySourceGroupId:r}),{source_group_id:n}),schematicSheetId:s}))}function cDo(t){const{db:e}=t.root,n=ADo(e.toArray(),{source_group_id:t.source_group_id});for(const{tree:o,schematicSheetId:i}of n)hTt(t,o,{schematicSheetId:i})}var yMe=1,wue=1.5;function lDo({sectionBlocks:t,groupSchPositionBeforeLayout:e}){const n=t.reduce((c,l)=>{const u=Math.max(l.size.x,.5)+wue*2,g=Math.max(l.size.y,.5)+wue*2;return c+u*g},0),o=Math.sqrt(n)*2,i=[];let r=[],s=0;for(const c of t){const l=Math.max(c.size.x,.5)+wue*2,u=Math.max(c.size.y,.5)+wue*2,g=s>0?s+yMe+l:l;r.length>0&&g>o&&(i.push(r),r=[],s=0);const h=s>0?s+yMe:0;r.push({sectionName:c.sectionName,rowOffset:h,width:l,height:u}),s=h+l}r.length>0&&i.push(r);const a=new Map;let A=0;for(const c of i){const l=Math.max(...c.map(h=>h.height)),g=-(c[c.length-1].rowOffset+c[c.length-1].width)/2;for(const h of c)a.set(h.sectionName,{x:g+h.rowOffset+h.width/2+e.x,y:A-l/2+e.y});A-=l+yMe}return a}var uDo=vc("Group_doInitialSchematicLayoutSections");function gDo(t){const{db:e}=t.root,n=new Set;let o=!1;for(const c of t.children){if(!c.source_component_id)continue;const l=c.getSchematicSectionName();l!==null?n.add(l):o=!0}const i=Array.from(n);if(o&&i.push(null),i.length===0)return;for(const c of i){const l=mz(e.toArray(),{source_group_id:t.source_group_id});l.childNodes=l.childNodes.filter(u=>u.nodeType!=="component"||!u.sourceComponent?!1:(t.children.find(d=>d.source_component_id===u.sourceComponent?.source_component_id)?.getSchematicSectionName()??null)===c),hTt(t,l)}if(i.length<=1)return;const r=new Map;for(const c of i){let l=1/0,u=-1/0,g=1/0,h=-1/0;const d=new Set;for(const p of t.children){const m=p.source_component_id;if(!m||p.getSchematicSectionName()!==c)continue;const f=e.schematic_component.getWhere({source_component_id:m});if(!f)continue;d.add(m);const I=f.size.width/2,C=f.size.height/2;l=Math.min(l,f.center.x-I),u=Math.max(u,f.center.x+I),g=Math.min(g,f.center.y-C),h=Math.max(h,f.center.y+C)}!Number.isFinite(l)||d.size===0||r.set(c,{sectionName:c,center:{x:(l+u)/2,y:(g+h)/2},size:{x:u-l,y:h-g},sourceCompIds:d})}if(r.size<=1)return;const s=new Set;for(const c of t.children){if(!c.source_component_id)continue;const l=c._parsedProps;(l?.schX!==void 0||l?.schY!==void 0)&&s.add(c.getSchematicSectionName())}const a=t._getGlobalSchematicPositionBeforeLayout(),A=lDo({sectionBlocks:Array.from(r.values()).map(c=>({sectionName:c.sectionName,size:c.size})),groupSchPositionBeforeLayout:a});for(const[c,l]of A){const u=r.get(c);if(!u)continue;if(s.has(c)){uDo(`[${t.name}] Section "${c}" anchored by manual position, skipping shift`);continue}const g={x:l.x-u.center.x,y:l.y-u.center.y};for(const h of u.sourceCompIds){const d=e.schematic_component.getWhere({source_component_id:h});if(!d)continue;const p=e.schematic_port.list({schematic_component_id:d.schematic_component_id}),m=e.schematic_text.list({schematic_component_id:d.schematic_component_id});for(const _ of p)_.center.x+=g.x,_.center.y+=g.y;for(const _ of m)_.position.x+=g.x,_.position.y+=g.y;MO({db:e,schematicComponentId:d.schematic_component_id,deltaX:g.x,deltaY:g.y}),d.center={x:d.center.x+g.x,y:d.center.y+g.y}}}}var dDo=({db:t,schematicDisabled:e})=>{const n=t.schematic_missing_sheet_warning.list()[0],o=t.schematic_component.list().length>0;if(!(!e&&o&&t.schematic_sheet.list().length===0)){n&&t.schematic_missing_sheet_warning.delete(n.schematic_missing_sheet_warning_id);return}n||t.schematic_missing_sheet_warning.insert({warning_type:"schematic_missing_sheet_warning",message:"No <schematicsheet> was found. Add a <schematicsheet> to define the schematic drawing area."})},pTt=t=>{const e=t.root;if(!e?.isRootCircuit)return;const n=e.firstChild===t,o=U0e(e.firstChild)&&t.parent===e.firstChild;!n&&!o||dDo({db:e.db,schematicDisabled:e.schematicDisabled})},hDo=t=>{pTt(t)},pDo=class extends Ir{source_net_label_id;schematic_net_label_id;get config(){return{componentName:"NetLabel",zodProps:HPn}}_getAnchorSide(){const{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";const n=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);let o;if(n?.source_net_id&&(o=this.root?.db.source_net.get(n.source_net_id)),o?.is_ground)return"top";if(o?.is_power)return"bottom";const i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";const s=r[0];if(s.facingDirection)return gO(s.facingDirection);const a=s._getGlobalSchematicPositionBeforeLayout(),A=a.x-i.x,c=a.y-i.y;if(Math.abs(A)>Math.abs(c)){if(A>0)return"right";if(A<0)return"left"}else{if(c>0)return"top";if(c<0)return"bottom"}return"right"}_getConnectedPorts(){const t=this._resolveConnectsTo();if(!t)return[];const e=[];for(const n of t){const o=this.getSubcircuit().selectOne(n);o&&e.push(o)}return e}computeSchematicPropsTransform(){const{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){const e=this._getConnectedPorts();if(e.length>0){const n=e[0]._getGlobalSchematicPositionBeforeLayout(),o=ts(this.parent?.computeSchematicGlobalTransform?.()??hC(),{x:0,y:0});return M0(n.x-o.x,n.y-o.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled||this.getCollapsedSchematicBoxAncestor())return;const{db:t}=this.root,{_parsedProps:e}=this;if(e.inline&&this.root?._featureMspSchematicTraceRouting&&this._getConnectedPorts().length>0)return;const n=this._getGlobalSchematicPositionBeforeLayout(),o=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),i=this._getAnchorSide(),r=j7({anchor_position:n,anchor_side:i,text:e.net}),s=t.schematic_net_label.insert({text:e.net,source_net_id:o.source_net_id,anchor_position:n,center:r,anchor_side:i,schematic_sheet_id:this._resolveSchematicSheetId()});this.source_net_label_id=s.source_net_id,this.schematic_net_label_id=s.schematic_net_label_id}_resolveConnectsTo(){const{_parsedProps:t}=this,e=t.connectsTo??t.connection;if(Array.isArray(e))return e;if(typeof e=="string")return[e]}_getNetName(){const{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){const{_parsedProps:t}=this;t.net&&Hj(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){const t=this._resolveConnectsTo();if(t)for(const e of t)this.add(new t1({from:e,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled||this.getCollapsedSchematicBoxAncestor()||this._parsedProps.inline)return;const{schX:t,schY:e}=this._parsedProps;if(t===void 0&&e===void 0)return;const{db:n}=this.root,o=this._resolveConnectsTo();if(!o||o.length===0)return;const i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),a={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],A=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(const c of o){const l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(A?.source_net_id){const f=n.source_trace.list().find(I=>I.connected_source_net_ids?.includes(A.source_net_id)&&I.connected_source_port_ids?.includes(l.source_port_id??""));if(f&&(u=n.schematic_trace.list().some(I=>I.source_trace_id===f.source_trace_id)),u)continue}const g=l._getGlobalSchematicPositionAfterLayout(),h=D0e(l.facingDirection??"right")??"x+",d=wF({x:g.x,y:g.y,facingDirection:h},{x:i.x,y:i.y,facingDirection:a});if(!Array.isArray(d)||d.length<2)continue;const p=[];for(let f=0;f<d.length-1;f++)p.push({from:{x:d[f].x,y:d[f].y},to:{x:d[f+1].x,y:d[f+1].y}});let m,_;if(A?.source_net_id&&l.source_port_id){const f=n.source_trace.list().find(I=>I.connected_source_net_ids?.includes(A.source_net_id)&&I.connected_source_port_ids?.includes(l.source_port_id));m=f?.source_trace_id,_=f?.subcircuit_connectivity_map_key||n.source_net.get(A.source_net_id)?.subcircuit_connectivity_map_key}n.schematic_trace.insert({source_trace_id:m,edges:p,junctions:[],subcircuit_connectivity_map_key:_,schematic_sheet_id:this._resolveSchematicSheetId()}),n.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},xMe=t=>{const e=[...new Set(t.flatMap(s=>s._getDirectlyConnectedTraces()))],n=e.find(s=>s._parsedProps.schDisplayLabel)?._parsedProps.schDisplayLabel??e.find(s=>s._parsedProps.displayName)?._parsedProps.displayName??e.find(s=>s._parsedProps.name)?._parsedProps.name;if(n)return{name:n,wasAssignedDisplayLabel:!0};const o=t.find(s=>s.root)?.root?.db,i=t.map(s=>s.source_port_id).filter(s=>!!s);return{name:(o?Vwe(o,i):t.map(s=>s._getNetLabelText()).filter(s=>!!s).sort((s,a)=>s.localeCompare(a,void 0,{numeric:!0,sensitivity:"base"}))[0])??"",wasAssignedDisplayLabel:!1}},mTt=(t,e,n)=>{const o=t.get(e);o?o.push(n):t.set(e,[n])},EMe=t=>{const{db:e}=t.root,n=new Map,o=new Map,i=new Map,r=new Map;for(const s of e.source_net.list())s.subcircuit_connectivity_map_key&&n.set(s.subcircuit_connectivity_map_key,s);for(const s of t.selectAll("port")){const a=s._getSubcircuitConnectivityKey();a&&mTt(o,a,s)}for(const s of e.source_port.list())s.subcircuit_connectivity_map_key&&mTt(i,s.subcircuit_connectivity_map_key,s.source_port_id);return({subcircuitConnectivityMapKey:s})=>{const a=r.get(s);if(a)return a;const A=n.get(s);if(A?.name){const u={name:A.name,wasAssignedDisplayLabel:!0};return r.set(s,u),u}const c=xMe(o.get(s)??[]);if(c.name)return r.set(s,c),c;const l={name:Vwe(e,i.get(s)??[])??"",wasAssignedDisplayLabel:!1};return r.set(s,l),l}},Am=t=>t,NO=t=>t,mDo=vc("Group_doInitialSchematicTraceRender"),_Do="rgb(132, 0, 0)",fDo=-90;function IDo(t){const{group:e,solver:n,userNetIdToConnKey:o,sourceTraceIdByPinPairKey:i,crossScopeSourceTraceIdBySchematicPortIdAndNetId:r}=t,{db:s}=e.root,a=n.inlineNetLabelSolver?.getOutput().inlineNetLabelPlacements??[];if(a.length===0)return;const A=EMe(e),c=n.mspConnectionPairSolver.globalConnMap;for(const l of a){const u=l.pinIds.map(Am),g=c.getIdsConnectedToNet(l.globalConnNetId).find(S=>o.has(S)),h=u.length===1?r.get(u[0])?.get(l.netId??l.globalConnNetId):void 0,d=(h?s.source_trace.get(h)?.subcircuit_connectivity_map_key:void 0)??(g?o.get(g):void 0),p=l.netLabelText??(d?A({subcircuitConnectivityMapKey:d}).name:l.netId??l.globalConnNetId);if(!p){mDo(`skipping inline net label for "${l.netId}" REASON:no resolvable text`);continue}let m=h??i.get([...u].sort().join("::"));if(!m&&d){const S=u.flatMap(Q=>{const w=s.schematic_port.get(Q)?.source_port_id;return w?[w]:[]});m=s.source_trace.list().find(Q=>Q.subcircuit_connectivity_map_key===d&&S.some(w=>Q.connected_source_port_ids.includes(w)))?.source_trace_id}let _=e._resolveSchematicSheetId();const f=s.schematic_port.get(u[0]);f?.schematic_sheet_id&&(_=f.schematic_sheet_id);let I={x:0,y:0},C=l.stubTracePath?.map(S=>({...S}));if(C&&u.length===1){const S=s.schematic_port.get(u[0])?.center;S&&(I={x:S.x-C[0].x,y:S.y-C[0].y},C=C.map(Q=>({x:Q.x+I.x,y:Q.y+I.y})))}const y={x:l.anchorPoint.x+I.x,y:l.anchorPoint.y+I.y},x={x:l.center.x+I.x,y:l.center.y+I.y};let E="center";const B=l.height/2;switch(l.side){case"y+":x.y=y.y+B;break;case"y-":x.y=y.y-B;break;case"x+":x.x=y.x+B;break;case"x-":x.x=y.x-B;break}if(C&&C.length===2){const[S,Q]=C;if(l.axis==="x"){const w=Q.x>S.x;E=w?"left":"right",x.x+=w?-l.width/2:l.width/2}else{const w=Q.y>S.y;E=w?"left":"right",x.y+=w?-l.width/2:l.width/2}}C&&C.length===2&&(s.schematic_trace.insert({source_trace_id:m,edges:[{from:C[0],to:C[1]}],junctions:[],subcircuit_connectivity_map_key:d,schematic_sheet_id:_}),s.schematic_port.update(u[0],{is_connected:!0})),s.schematic_text.insert({text:p,source_trace_id:m,anchor:E,position:x,rotation:l.axis==="y"?fDo:0,font_size:l.height,color:_Do,schematic_sheet_id:_})}}var CDo=.18,_Tt=({center:t,text:e})=>{const o=vb({text:e})/2,i=CDo/2;return{minX:t.x-o,maxX:t.x+o,minY:t.y-i,maxY:t.y+i}},yDo=t=>{switch(t){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"}},_$=vc("Group_doInitialSchematicTraceRender"),fTt=(t,e)=>t.schematicNetLabel.source_net_id!=null&&t.schematicNetLabel.source_net_id===e.source_net_id,xDo=(t,e)=>fTt(t,e.sourceNet)?t.schematicPortIds.some(n=>e.schematicPortIds.has(n))?!0:t.schematicNetLabel.center?z4(_Tt({center:t.schematicNetLabel.center,text:t.schematicNetLabel.text}),e.bounds):!1:!1;function EDo(t){const{group:e,routedSchematicPortIdBySchematicPortId:n,solver:o,connKeyToSourceNet:i,userNetIdToConnKey:r,crossScopeSourceTraceIdBySchematicPortIdAndNetId:s,sourceTraceIdByPortOnlyLabelSchematicPortId:a,connKeysWithExplicitPortNetTraces:A,schematicPortIdsWithPreExistingNetLabels:c,schematicPortIdsWithRoutedTraces:l,netLabels:u}=t,{db:g}=e.root,h=EMe(e),d=o.inlineNetLabelSolver?.getOutput().netLabelPlacements??o.netLabelNetLabelCollisionSolver?.getOutput().netLabelPlacements??o.netLabelTraceCollisionSolver?.getOutput().netLabelPlacements??o.netLabelPlacementSolver?.netLabelPlacements??o.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],p=[],m=new Set;for(const x of d){const E=[...x.pinIds??[]].sort(),B=`${x.globalConnNetId}|${E.join("::")}|${x.netId??""}`;if(m.has(B)){_$(`skipping duplicate placement for "${x.netId}" REASON:identical net label placement`);continue}m.add(B),p.push(x)}const _=new Map,f=new Map,I=new Set;for(const x of p)_.set(x.globalConnNetId,(_.get(x.globalConnNetId)??0)+1),(x.pinIds?.length??0)>1&&(f.has(x.globalConnNetId)||f.set(x.globalConnNetId,new Set),f.get(x.globalConnNetId).add(x.pinIds.slice().sort().join("::"))),(x.pinIds?.length??0)<=1&&I.add(x.globalConnNetId);const C=o.mspConnectionPairSolver.globalConnMap,y=u.map(x=>{if(!x.schematic_net_label_id)return null;const E=g.schematic_net_label.get(x.schematic_net_label_id);return E?{schematicNetLabel:E,schematicPortIds:x._getConnectedPorts().map(B=>B.schematic_port_id).filter(B=>!!B).map(B=>n.get(B)??B),shouldUseSchematicTraceSolver:x._parsedProps.schX===void 0&&x._parsedProps.schY===void 0}:null}).filter(x=>x!==null);for(const x of p){_$(`processing placement: ${x.netId}`);const E=x.pinIds.map(Am),S=(E.length===1?s.get(E[0])?.get(x.netId??x.globalConnNetId):void 0)??(E.length===1?a.get(E[0]):void 0),Q=S?g.source_trace.get(S):void 0,w=C.getIdsConnectedToNet(x.globalConnNetId).find(ge=>r.get(ge)),M=Q?.subcircuit_connectivity_map_key??r.get(w),k=x.orientation,R=yDo(k);let F;M&&(F=i.get(M));const O=M?h({subcircuitConnectivityMapKey:M}):{name:x.netId??x.globalConnNetId,wasAssignedDisplayLabel:!1},U=x.netLabelText?{name:x.netLabelText,wasAssignedDisplayLabel:!0}:O;let Y=e._resolveSchematicSheetId();const W=g.schematic_port.get(E[0]);W?.schematic_sheet_id&&(Y=W.schematic_sheet_id);let te=x.anchorPoint;if(E.length===1&&E[0]){const ge=g.schematic_port.get(E[0]);ge?.center&&!ge.is_connected&&(te=ge.center)}if(E.some(ge=>c.has(ge))){_$(`skipping net label placement for "${x.netId}" REASON:schematic port has pre-existing net label`);continue}if(F){const ge=F.is_ground||F.is_power,_e=A.has(M),ue=E.some(Qe=>l.has(Qe)),fe=(_.get(x.globalConnNetId)??0)<=1;if(!_e&&!ge&&ue&&fe){_$(`skipping net label placement for "${x.netId}" REASON:schematic port has routed trace`);continue}const ye=U.name,Me=j7({anchor_position:te,anchor_side:R,text:ye}),ve=y.find(Qe=>Qe.shouldUseSchematicTraceSolver&&fTt(Qe,F)&&Qe.schematicPortIds.some(Pe=>E.includes(Pe)));if(ve){g.schematic_net_label.update(ve.schematicNetLabel.schematic_net_label_id,{anchor_position:te,center:Me,anchor_side:R,schematic_sheet_id:Y,source_trace_id:S});continue}if(!ge){const Qe={sourceNet:F,schematicPortIds:new Set(E),bounds:_Tt({center:Me,text:ye})};if(y.some(Pe=>xDo(Pe,Qe)))continue}const he={text:ye,source_net_id:F.source_net_id,anchor_position:te,center:Me,anchor_side:R,schematic_sheet_id:Y,source_trace_id:S};g.schematic_net_label.insert(he);continue}const{name:j,wasAssignedDisplayLabel:J}=U,ie=(x.pinIds?.length??0)>1&&(I.has(x.globalConnNetId)||(f.get(x.globalConnNetId)?.size??0)>1);if(!J&&!ie&&E.some(ge=>l.has(ge))){_$(`skipping net label placement for "${x.netId}" REASON:schematic port has routed traces and no display label`);continue}const ne=j7({anchor_position:te,anchor_side:R,text:j}),le={text:j,source_net_id:M??x.netId??x.globalConnNetId,anchor_position:te,center:ne,anchor_side:R,schematic_sheet_id:Y,source_trace_id:S};g.schematic_net_label.insert(le)}}var Pue=(t,e,n,o)=>t*o-e*n;function ITt(t,e,n,o,i){const r={x:e.x-t.x,y:e.y-t.y},s={x:o.x-n.x,y:o.y-n.y},a=Pue(r.x,r.y,s.x,s.y),A={x:n.x-t.x,y:n.y-t.y},c=Pue(A.x,A.y,r.x,r.y);if(Math.abs(a)<i&&Math.abs(c)<i||Math.abs(a)<i&&Math.abs(c)>=i)return null;const l=Pue(A.x,A.y,s.x,s.y)/a,u=Pue(A.x,A.y,r.x,r.y)/a;return l<-i||l>1+i||u<-i||u>1+i?null:{x:t.x+l*r.x,y:t.y+l*r.y}}var Ew=1e-6;function CTt(t){const e=Math.abs(t.to.x-t.from.x),n=Math.abs(t.to.y-t.from.y);return e>=n}function uR(t,e){return Math.hypot(e.x-t.x,e.y-t.y)}function gR(t,e,n){return{x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n}}function RO(t,e,n){const o=uR(t,e);if(o<Ew)return 0;const i=((n.x-t.x)*(e.x-t.x)+(n.y-t.y)*(e.y-t.y))/((e.x-t.x)*(e.x-t.x)+(e.y-t.y)*(e.y-t.y));return Math.max(0,Math.min(1,i))*o}function yTt(t,e=Ew){if(t.length===0)return t;t.sort((i,r)=>i.start-r.start);const n=[];let o={...t[0]};for(let i=1;i<t.length;i++){const r=t[i];r.start<=o.end+e?o.end=Math.max(o.end,r.end):(n.push(o),o={...r})}return n.push(o),n}function BDo(t,e,n){const o=uR(t.from,t.to);if(o<Ew||e.length===0)return[t];const i=n/2,r=e.map(l=>({start:Math.max(0,l-i),end:Math.min(o,l+i)})).filter(l=>l.end-l.start>Ew),s=yTt(r),a=[];let A=0;t.to.x-t.from.x,t.to.y-t.from.y;const c=(l,u,g)=>{if(u-l<=Ew)return;const h=l/o,d=u/o;a.push({from:gR(t.from,t.to,h),to:gR(t.from,t.to,d),...g?{is_crossing:!0}:{}})};for(const l of s)l.start-A>Ew&&c(A,l.start,!1),c(l.start,l.end,!0),A=l.end;return o-A>Ew&&c(A,o,!1),a.length>0?a:[t]}function bDo(t,e={}){const n=e.crossSegmentLength??.075,o=e.tolerance??Ew,i=new Map,r=a=>`${a.traceIdx}:${a.edgeIdx}`;for(let a=0;a<t.length;a++){const A=t[a];for(let c=0;c<A.edges.length;c++){const l=A.edges[c];for(let u=a;u<t.length;u++){const g=t[u];for(let h=u===a?c+1:0;h<g.edges.length;h++){const d=g.edges[h];if(A.connectivity_key!==void 0&&A.connectivity_key===g.connectivity_key)continue;const p=ITt(l.from,l.to,d.from,d.to,o);if(!p)continue;const m=uR(l.from,l.to),_=uR(d.from,d.to);if(m<o||_<o)continue;const f=RO(l.from,l.to,p),I=RO(d.from,d.to,p),C=f<=o||Math.abs(m-f)<=o||Number.isNaN(f),y=I<=o||Math.abs(_-I)<=o||Number.isNaN(I);if(!C&&!y){const x=CTt(l),E=CTt(d);let B;if(x!==E)B=x;else{const w=Math.abs(l.to.x-l.from.x),M=Math.abs(l.to.y-l.from.y),k=Math.abs(d.to.x-d.from.x),R=Math.abs(d.to.y-d.from.y),F=w-M,O=k-R;B=F===O?!0:F>O}const S=r({traceIdx:B?a:u,edgeIdx:B?c:h}),Q=i.get(S)??[];Q.push(B?f:I),i.set(S,Q)}}}}}const s=t.map(a=>({source_trace_id:a.source_trace_id,connectivity_key:a.connectivity_key,edges:[]}));for(let a=0;a<t.length;a++){const A=t[a];for(let c=0;c<A.edges.length;c++){const l=r({traceIdx:a,edgeIdx:c}),u=i.get(l)??[];if(u.length===0){s[a].edges.push(A.edges[c]);continue}const g=Array.from(new Set(u.map(d=>Number(d.toFixed(6))))).sort((d,p)=>d-p),h=BDo(A.edges[c],g,n);s[a].edges.push(...h)}}return s}var QB=1e-6;function Mue(t,e,n=QB){return Math.abs(t-e)<=n}function Bw(t,e,n=QB){return Mue(t.x,e.x,n)&&Mue(t.y,e.y,n)}function xTt(t,e,n,o=QB){const i=Math.min(e.x,n.x)-o,r=Math.max(e.x,n.x)+o,s=Math.min(e.y,n.y)-o,a=Math.max(e.y,n.y)+o;return t.x<i||t.x>r||t.y<s||t.y>a?!1:Math.abs((n.x-e.x)*(t.y-e.y)-(n.y-e.y)*(t.x-e.x))<=o}function ETt(t,e=QB){const n=new Map;for(const o of t){const i=`${o.x.toFixed(6)},${o.y.toFixed(6)}`;n.has(i)||n.set(i,o)}return Array.from(n.values())}function BTt(t){return{x:t.to.x-t.from.x,y:t.to.y-t.from.y}}function bTt(t,e,n=QB){return Bw(t,e.from,n)||Bw(t,e.to,n)}function BMe(t,e,n=QB){const o=BTt(t),i=BTt(e),r=Math.hypot(o.x,o.y),s=Math.hypot(i.x,i.y);if(r<n||s<n)return!0;const a=o.x*i.y-o.y*i.x;return Math.abs(a)<=n*r*s}function f$(t,e,n=QB){return t.edges.filter(o=>Bw(o.from,e,n)||Bw(o.to,e,n))}function STt(t,e,n=QB){for(const o of t.edges){if(Bw(o.from,e,n))return o.from;if(Bw(o.to,e,n))return o.to}return null}function SDo(t,e,n=QB){const o=Bw(t.from,e,n)||Mue(t.from.x,e.x,n)&&Mue(t.from.y,e.y,n)?t.to:t.from,i=o.x-e.x,r=o.y-e.y;return Math.abs(i)<n&&Math.abs(r)<n?null:Math.abs(i)>=Math.abs(r)?i>=0?"right":"left":r>=0?"up":"down"}function TO(t,e,n=QB){const o=f$(t,e,n);if(o.length<2)return null;const i=o.map(u=>SDo(u,e,n)),r=i.includes("up"),s=i.includes("down"),a=i.includes("left"),A=i.includes("right"),c=r?"up":s?"down":null,l=A?"right":a?"left":null;return c&&l?`${c}-${l}`:null}function QDo(t,e={}){const n=e.tolerance??QB,o={};for(const r of t)o[r.source_trace_id]=[];const i=t.map(r=>{const s=[];for(const a of r.edges)s.push(a.from,a.to);return ETt(s,n)});for(let r=0;r<t.length;r++){const s=t[r],a=i[r];for(let A=r+1;A<t.length;A++){const c=t[A],l=i[A];if(s.connectivity_key!==void 0&&s.connectivity_key===c.connectivity_key){for(const g of s.edges)for(const h of c.edges){const d=ITt(g.from,g.to,h.from,h.to,n);d&&(bTt(d,g,n)||bTt(d,h,n)||(o[s.source_trace_id].push(d),s.source_trace_id!==c.source_trace_id&&o[c.source_trace_id].push(d)))}for(const g of a)for(const h of l)if(Bw(g,h,n)){const d=f$(s,g,n),p=f$(c,h,n),m=d.some(C=>p.some(y=>!BMe(C,y,n))),_=TO(s,g,n),f=TO(c,h,n);m&&!(_!==null&&f!==null&&_===f)&&(o[s.source_trace_id].push(g),s.source_trace_id!==c.source_trace_id&&o[c.source_trace_id].push(h))}for(const g of a)for(const h of c.edges)if(xTt(g,h.from,h.to,n)){const p=f$(s,g,n).some(C=>!BMe(C,h,n)),m=TO(s,g,n),_=STt(c,g,n*1e3),f=_?TO(c,_,n):null;p&&!(m!==null&&f!==null&&m===f)&&(o[s.source_trace_id].push(g),s.source_trace_id!==c.source_trace_id&&o[c.source_trace_id].push(g))}for(const g of l)for(const h of s.edges)if(xTt(g,h.from,h.to,n)){const p=f$(c,g,n).some(C=>!BMe(h,C,n)),m=TO(c,g,n),_=STt(s,g,n*1e3),f=_?TO(s,_,n):null;p&&!(f!==null&&m!==null&&f===m)&&(o[c.source_trace_id].push(g),s.source_trace_id!==c.source_trace_id&&o[s.source_trace_id].push(g))}}}}for(const r of Object.keys(o))o[r]=ETt(o[r],n);return o}var bw=1e-6;function vDo(t,e,n=bw){const o=t.to.x-t.from.x,i=t.to.y-t.from.y,r=e.to.x-e.from.x,s=e.to.y-e.from.y,a=Math.hypot(o,i),A=Math.hypot(r,s);if(a<=n||A<=n)return!1;const c=o*s-i*r;if(Math.abs(c)>n*a*A)return!1;const l=o*(e.from.y-t.from.y)-i*(e.from.x-t.from.x);return Math.abs(l)<=n*a}function wDo(t,e){const n=yTt(e);if(n.length===0)return[t];const o=uR(t.from,t.to);if(o<=bw)return[t];const i=[];let r=0;for(const s of n)s.start-r>bw&&i.push({from:gR(t.from,t.to,r/o),to:gR(t.from,t.to,s.start/o)}),s.end-s.start>bw&&i.push({from:gR(t.from,t.to,s.start/o),to:gR(t.from,t.to,s.end/o),is_crossing:!0}),r=Math.max(r,s.end);return o-r>bw&&i.push({from:gR(t.from,t.to,r/o),to:t.to}),i}function PDo(t){const e=new Map;for(let n=0;n<t.length;n++){const o=t[n];if(o.connectivity_key){for(const i of o.edges)if(!(!i.is_crossing||uR(i.from,i.to)<=bw))for(let r=0;r<t.length;r++){const s=t[r];if(!(r===n||s.connectivity_key!==o.connectivity_key))for(let a=0;a<s.edges.length;a++){const A=s.edges[a],c=uR(A.from,A.to);if(A.is_crossing||c<=bw||!vDo(A,i))continue;const l=Math.max(0,Math.min(RO(A.from,A.to,i.from),RO(A.from,A.to,i.to))),u=Math.min(c,Math.max(RO(A.from,A.to,i.from),RO(A.from,A.to,i.to)));if(u-l<=bw)continue;const g=`${r}:${a}`,h=e.get(g)??[];h.push({start:l,end:u}),e.set(g,h)}}}}return e.size===0?t:t.map((n,o)=>({...n,edges:n.edges.flatMap((i,r)=>{const s=e.get(`${o}:${r}`);return s?wDo(i,s):[i]})}))}var Due=vc("Group_doInitialSchematicTraceRender"),MDo=1.5;function DDo(t,e){const{points:n,schematicPortIds:o,componentBoundsByPortId:i}=t,r=o.map(h=>{const d=e.schematic_port.get(h)?.center,p=i.get(h);return!d||!p?null:{center:d,bounds:p}}).filter(h=>!!h);if(r.length===0)return n;const s=n.map(h=>({x:h.x,y:h.y})),a=(h,d)=>(h.x-d.x)**2+(h.y-d.y)**2,A=new Set;for(let h=0;h<r.length;h++)s.some(d=>a(r[h].center,d)<=1e-12)&&A.add(h);const c=.001,l=["start","end"],u=[];for(const h of l){const d=h==="start"?s[0]:s[s.length-1];for(let p=0;p<r.length;p++){if(A.has(p))continue;const{center:m,bounds:_}=r[p],f=a(m,d);Math.abs(m.x-d.x)>c&&Math.abs(m.y-d.y)>c||f>MDo**2&&BQn(d,_)>c||u.push({endpoint:h,centerIndex:p,dist:f})}}u.sort((h,d)=>h.dist-d.dist);const g=new Set;for(const{endpoint:h,centerIndex:d,dist:p}of u){if(g.has(h)||A.has(d)||(A.add(d),g.add(h),p<=1e-12))continue;const m=r[d].center;h==="start"?s.unshift({x:m.x,y:m.y}):s.push({x:m.x,y:m.y})}return s}function NDo(t){const{group:e,solver:n,userNetIdToConnKey:o,schematicPortIdsWithPreExistingNetLabels:i}=t,{db:r}=e.root,s=new Set(e.selectAll("port").filter(_=>{if(!_._getSymbolAncestor())return!1;const f=_.getParentNormalComponent()?._parsedProps.symbol;return ee.isValidElement(f)||aPe(f)}).map(_=>_.schematic_port_id).filter(_=>_!=null).map(Am)),a=new Map;for(const _ of r.schematic_component.list()){const f=vue({db:r,schematicComponent:_}),I=Ey({center:_.center,width:_.size.width,height:_.size.height});for(const C of r.schematic_port.list({schematic_component_id:_.schematic_component_id})){const y=C.center.x>I.minX&&C.center.x<I.maxX&&C.center.y>I.minY&&C.center.y<I.maxY,x=Am(C.schematic_port_id);!f&&!s.has(x)||!f&&y||a.set(x,f??I)}}const A=n.inlineNetLabelSolver?.getOutput().traces??n.sameNetJunctionAlignmentSolver?.getOutput().traces??n.netLabelTraceCollisionSolver?.getOutput().traces??n.traceCleanupSolver?.getOutput().traces??n.traceLabelOverlapAvoidanceSolver?.getOutput().traces??n.schematicTraceLinesSolver?.solvedTracePaths,c=[];Due(`Traces inside SchematicTraceSolver output: ${(A??[]).length}`);for(const _ of A??[]){const I=Array.from(new Set(_.pinIds??[])).map(Am);if(I.length>0&&I.every(M=>i.has(M))){Due(`Skipping solver netlabel-covered trace ${_?.mspPairId} because all schematic ports already have netlabels`);continue}const y=_?.tracePath;if(!Array.isArray(y)||y.length<2){Due(`Skipping trace ${_?.pinIds.join(",")} because it has less than 2 points`);continue}const x=DDo({points:y,schematicPortIds:I,componentBoundsByPortId:a},r),E=[];for(let M=0;M<x.length-1;M++)E.push({from:{x:x[M].x,y:x[M].y},to:{x:x[M+1].x,y:x[M+1].y}});const B=String(_?.mspPairId);let S;if(Array.isArray(_?.pins)&&_.pins.length===2){const M=_.pins[0]?.pinId,k=_.pins[1]?.pinId,R=M?Am(M):void 0,F=k?Am(k):void 0;if(R&&F){const O=new Set([R,F]);for(const U of O)r.schematic_port.update(U,{is_connected:!0});S=o.get(String(_.userNetId))}}if(S||(S=o.get(String(_.userNetId))),!S){const M=I.map(R=>{const O=r.schematic_port.get(R)?.source_port_id;if(O)return r.source_port.get(O)?.subcircuit_connectivity_map_key}).filter(R=>!!R);new Set(M).size===1&&(S=M[0])}const Q=new Set(I.map(M=>r.schematic_port.get(M)?.schematic_sheet_id).filter(M=>!!M));let w;Q.size===1?w=Q.values().next().value:Q.size===0&&(w=e._resolveSchematicSheetId()),c.push({source_trace_id:B,edges:E,subcircuit_connectivity_map_key:S,schematic_sheet_id:w})}Due(`Applying ${c.length} traces from SchematicTraceSolver output`);const l=bDo(c.map(_=>({source_trace_id:_.source_trace_id,edges:_.edges,connectivity_key:_.subcircuit_connectivity_map_key}))),u=[],g=e._resolveSchematicSheetId();for(const _ of r.schematic_trace.list()){if(_.edges.length===0||_.schematic_sheet_id!==g)continue;const f=_.source_trace_id?r.source_trace.get(_.source_trace_id):void 0;u.push({schematic_trace_id:_.schematic_trace_id,source_trace_id:_.source_trace_id??_.schematic_trace_id,edges:_.edges,connectivity_key:_.subcircuit_connectivity_map_key??f?.subcircuit_connectivity_map_key})}const h=PDo([...l,...u]),d=h.slice(0,l.length),p=h.slice(l.length);for(const _ of p)_.schematic_trace_id&&r.schematic_trace.update(_.schematic_trace_id,{edges:_.edges});const m=QDo([...d,...p]);for(const _ of d){const f=c.find(C=>C.source_trace_id===_.source_trace_id);let I=g;f?.schematic_sheet_id&&(I=f.schematic_sheet_id),r.schematic_trace.insert({source_trace_id:_.source_trace_id,edges:_.edges,junctions:m[_.source_trace_id]??[],subcircuit_connectivity_map_key:f?.subcircuit_connectivity_map_key,schematic_sheet_id:I})}}var QTt=.12,vTt=(t,e)=>{t.anchoredNetLabelWidth??=Number(vb({text:e}).toFixed(2)),t.allowInlineNetLabel=!0,t.inlineNetLabelHeight=QTt,t.inlineNetLabelWidth=Number(vb({text:e,font_size:QTt}).toFixed(2))},RDo=({directConnections:t,netConnections:e,connKeyToSchematicPortIds:n,connKeyToSourceNet:o,connKeysWithExplicitPortNetTraces:i,schematicPortIdsWithExplicitNetLabels:r,schematicPortIdsWithInlineNetLabels:s,areSchematicPortsOnDifferentComponents:a,resolveCanonicalNetLabelText:A})=>{for(const c of t){const{connKey:l}=c;if(!l||n.get(l)?.length!==2)continue;const g=o.get(l);if(g?.is_power||g?.is_ground)continue;const{name:h,wasAssignedDisplayLabel:d}=A({subcircuitConnectivityMapKey:l});!h||!d||vTt(c,h)}for(const c of e){const{schematicPortIds:l}=c,{isSameSheetCrossSectionConnection:u}=c,g=l.some(C=>s.has(C)),h=l.length===1,d=l[0],p=d!==void 0&&l.slice(1).some(C=>a([d,C]));if(!g&&!u&&!h&&!p||!g&&l.some(C=>r.has(C)))continue;const{connKey:m}=c;if(!m&&!u||m&&!u&&!i.has(m))continue;const _=m?o.get(m):void 0;if(!g&&(c.isPowerOrGroundConnection||_?.is_power||_?.is_ground))continue;let f=c.netLabelText??"",I=!!f;if(!u){if(!m)continue;const C=A({subcircuitConnectivityMapKey:m});f=C.name,I=C.wasAssignedDisplayLabel}!f||!g&&!I||vTt(c,f)}},TDo=t=>{const{schX:e,schY:n}=t._parsedProps;if(e!==void 0&&n!==void 0||!t.getParentNormalComponent()?.getSchematicSymbol())return t;const o=t._getPortsInternallyConnectedToThisPort(),i=t.schematicSymbolPortDef??o.find(r=>r.schematicSymbolPortDef)?.schematicSymbolPortDef;return i?o.find(r=>r.schematicSymbolPortDef===i)??t:t};function kDo(t){const{db:e}=t.root,n=new Map;for(const o of t.selectAll("port")){if(!o.schematic_port_id)continue;const i=e.schematic_port.get(o.schematic_port_id),r=TDo(o),s=r.schematic_port_id?e.schematic_port.get(r.schematic_port_id):void 0;!i||!s||i.schematic_component_id!==s.schematic_component_id||i.schematic_sheet_id!==s.schematic_sheet_id||n.set(Am(i.schematic_port_id),Am(s.schematic_port_id))}return n}var wTt=({db:t,sourcePortId:e,otherSourcePortId:n,sourcePortIdsInSchematicScope:o,schematicSheetId:i})=>{if(o.has(n))return!1;const r=t.source_port.get(e),s=t.source_port.get(n);if(!r||!s)return!1;if(r.subcircuit_id!==s.subcircuit_id)return!0;if(!i)return!1;const a=t.schematic_port.list({source_port_id:n});return a.some(c=>c.schematic_sheet_id===i)?!1:a.some(c=>c.schematic_sheet_id!==void 0)},PTt=({db:t,sourcePortId:e,sourcePortIdsInSchematicScope:n,schematicSheetId:o})=>{if(t.source_port.get(e))for(const i of t.source_trace.list()){const r=(i.connected_source_port_ids??[]).map(NO);if(r.length!==2||(i.connected_source_net_ids??[]).length>0||!r.includes(e))continue;const s=r.find(a=>a!==e);if(s&&wTt({db:t,sourcePortId:e,otherSourcePortId:s,sourcePortIdsInSchematicScope:n,schematicSheetId:o}))return s}},MTt=({group:t,sourcePortId:e,connectedSourcePortIdsForKey:n,sourcePortIdsInSchematicScope:o,schematicSheetId:i,connKey:r,sourceNet:s})=>{const{db:a}=t.root,A=t.selectAll("port").filter(m=>m._getSubcircuitConnectivityKey()===r),{name:c,wasAssignedDisplayLabel:l}=xMe(A),u=l?c:void 0,g=l?void 0:c||void 0,h=Vwe(a,n),d=PTt({db:a,sourcePortId:e,sourcePortIdsInSchematicScope:o,schematicSheetId:i}),p=d?xMt(a,d):void 0;return{text:s?.name||s?.source_net_id||u||p||g||h||r,wasAssignedDisplayLabel:l,directConnectionOutsideSchematicScopeSourcePortId:d}},FDo=.18;function LDo(t){const e=t.font_size??FDo,n=ATt({text:t.text??"",fontSize:e}),o=e,i=t.anchor??"center";let r,s;i.includes("left")?(r=0,s=n):i.includes("right")?(r=-n,s=0):(r=-n/2,s=n/2);let a,A;i.includes("top")?(a=-o,A=0):i.includes("bottom")?(a=0,A=o):(a=-o/2,A=o/2);const c=(t.rotation??0)*Math.PI/180,l=Math.cos(c),u=Math.sin(c),g=[{x:r,y:a},{x:r,y:A},{x:s,y:a},{x:s,y:A}].map(h=>({x:t.position.x+h.x*l-h.y*u,y:t.position.y+h.x*u+h.y*l}));return Oh(g)}var HDo=.01,bMe=.06;function ODo(t,e){return e?t.text===e.display_name||t.text===e.name:!1}function GDo(t,e={}){if(!t.text)return null;const n=LDo(t);if(ODo(t,e.sourceComponent)&&e.schematicComponent?.center&&e.schematicComponent?.size){const o=Ey({center:e.schematicComponent.center,width:e.schematicComponent.size.width,height:e.schematicComponent.size.height}),i=n.maxY-n.minY;n.minY>o.maxY&&(n.minX-=bMe,n.maxX+=bMe,n.minY=o.maxY-HDo,n.maxY=o.maxY+i+bMe)}return{chipId:t.schematic_component_id,center:oD(n),width:n.maxX-n.minX,height:n.maxY-n.minY,text:t.text}}var DTt=2.4,YDo=.42;function UDo(t,e={}){const{db:n}=t.root,o=kDo(t),i=Qe=>o.get(Qe)??Qe,r=Mxe(n.toArray()),s=Qe=>{const Pe=[...r.getIdsConnectedToNet(Qe)].sort()[0];return Pe?`source_connectivity_${Pe}`:`source_${Qe}`},a=Qe=>{const Pe=[...Qe.connected_source_port_ids,...Qe.connected_source_net_ids].map(we=>r.getNetConnectedToId(we)).find(we=>!!we);return Pe?s(Pe):Qe.subcircuit_connectivity_map_key??Qe.source_trace_id},A=new Set;for(const Qe of n.source_net.list()){if(!Qe.is_power&&!Qe.is_ground)continue;const Pe=r.getNetConnectedToId(Qe.source_net_id);Pe&&A.add(s(Pe))}const c=new Map,l=[],u=[...t.children].reverse();for(;u.length>0;){const Qe=u.pop();if(Qe instanceof A6){if(Qe.isSubcircuit){Qe._parsedProps.showAsSchematicBox&&l.push(Qe);continue}l.push(Qe)}u.push(...[...Qe.children].reverse())}const g=[t.schematic_group_id,...l.map(Qe=>Qe.schematic_group_id)],h=n.schematic_component.list().filter(Qe=>g.includes(Qe.schematic_group_id)).filter(Qe=>e.schematicSheetId===void 0||Qe.schematic_sheet_id===e.schematicSheetId),d=new Set(h.map(Qe=>Qe.schematic_component_id)),p=new Map(h.map(Qe=>[Qe.schematic_component_id,Qe])),m=n.schematic_text.list().filter(Qe=>Qe.schematic_component_id&&d.has(Qe.schematic_component_id)).map(Qe=>{const Pe=p.get(Qe.schematic_component_id);if(!Pe)return;const we=n.source_component.get(Pe.source_component_id);return GDo(Qe,{schematicComponent:Pe,sourceComponent:we})}).filter(Qe=>!!Qe),_=new Map,f=t._getBoard()?.getDescendants()??[];for(const Qe of f){const Pe=Qe.schematic_component_id,we=Qe.getSchematicSectionName();Pe&&we&&_.set(Pe,we)}const I=[];for(const Qe of h){const Pe=Qe.schematic_component_id,Te=n.schematic_port.list({schematic_component_id:Qe.schematic_component_id}).filter(ke=>{const Ce=Am(ke.schematic_port_id);return i(Ce)===Ce}).map(ke=>{const Ce=Am(ke.schematic_port_id),Le=ke.source_port_id?n.source_port.get(ke.source_port_id):void 0;return{pinId:Ce,displayName:ke.display_pin_label??ke.pin_number?.toString()??Le?.name,x:ke.center.x,y:ke.center.y,_facingDirection:D0e(ke.facing_direction??null)}}),Re=_.get(Qe.schematic_component_id),Ee=vue({db:n,schematicComponent:Qe})??Ey({center:Qe.center,width:Qe.size.width,height:Qe.size.height});I.push({chipId:Pe,center:oD(Ee),width:Ee.maxX-Ee.minX,height:Ee.maxY-Ee.minY,pins:Te,sectionId:Re})}const C=new Set,y=new Map,x=new Map,E=new Map,B=new Map(t.selectAll("port").filter(Qe=>Qe.schematic_port_id).map(Qe=>[Am(Qe.schematic_port_id),Qe])),S=EMe(t);for(const Qe of h){const Pe=n.schematic_port.list({schematic_component_id:Qe.schematic_component_id});for(const we of Pe){const Te=Am(we.schematic_port_id);if(C.add(Te),we.source_port_id){const Re=NO(we.source_port_id);y.set(Te,Re),x.set(Re,Te)}}}const Q=new Set(x.keys()),w=(e.netLabels??[]).filter(Qe=>Qe._getConnectedPorts().some(Pe=>Pe.schematic_port_id?C.has(Am(Pe.schematic_port_id)):!1)),M=new Set(w.filter(Qe=>!Qe._parsedProps.inline).flatMap(Qe=>Qe._getConnectedPorts()).map(Qe=>Qe.schematic_port_id).filter(Qe=>Qe!=null).map(Am).map(i)),k=new Set(w.filter(Qe=>Qe._parsedProps.inline||Qe._parsedProps.schX===void 0&&Qe._parsedProps.schY===void 0).flatMap(Qe=>Qe._getConnectedPorts()).map(Qe=>Qe.schematic_port_id).filter(Qe=>Qe!=null).map(Am).map(i)),R=new Set(w.filter(Qe=>Qe._parsedProps.inline).flatMap(Qe=>Qe._getConnectedPorts()).map(Qe=>Qe.schematic_port_id).filter(Qe=>Qe!=null).map(Am).map(i)),F=new Set;t.subcircuit_id&&F.add(t.subcircuit_id);for(const Qe of l)Qe.subcircuit_id&&F.add(Qe.subcircuit_id);const O=n.source_trace.list().filter(Qe=>{if(Qe.subcircuit_id===t.subcircuit_id)return!0;for(const Pe of Qe.connected_source_port_ids)if(x.has(NO(Pe)))return!0;return!1}),U=new Set;for(const Qe of O)if(Qe.subcircuit_id!==t.subcircuit_id&&Qe.connected_source_net_ids.length!==0)for(const Pe of Qe.connected_source_port_ids){const we=NO(Pe),Te=x.get(we);!Te||k.has(Te)||!n.schematic_port.list({source_port_id:Pe}).some(Ee=>Ee.schematic_port_id===Te?!1:(Ee.schematic_component_id?n.schematic_component.get(Ee.schematic_component_id):void 0)?.schematic_sheet_id===e.schematicSheetId)||U.add(Te)}const Y=O.flatMap(Qe=>Qe.connected_source_net_ids);for(const Qe of Y){const Pe=n.source_net.get(Qe);Pe?.subcircuit_id&&F.add(Pe.subcircuit_id)}for(const Qe of n.source_net.list().filter(Pe=>!Pe.subcircuit_id||F.has(Pe.subcircuit_id)))Qe.subcircuit_connectivity_map_key&&c.set(Qe.subcircuit_connectivity_map_key,Qe);const W=[],te=[],j=new Set,J=new Map,oe=new Map,ie=({schematicPortId:Qe,netId:Pe,sourceTraceId:we,replaceExisting:Te=!1})=>{const Re=J.get(Qe)??new Map;return Re.has(Pe)&&!Te?!1:(Re.set(Pe,we),J.set(Qe,Re),!0)},ne=({sourceConnectivityNetId:Qe,schematicPortId:Pe,text:we,sourceTraceId:Te,connKey:Re,preferInScopeTraceMetadata:Ee=!1})=>{const ke=Qe;if(ie({schematicPortId:Pe,netId:ke,sourceTraceId:Te,replaceExisting:Ee}),M.has(Pe))return;let Ce=oe.get(Qe);Ce?Ee&&(Ce.netLabelText=we,Ce.netLabelWidth=Number(vb({text:we}).toFixed(2)),Ce.connKey=Re??Ce.connKey):(Ce={netId:ke,netLabelText:we,schematicPortIds:[],netLabelWidth:Number(vb({text:we}).toFixed(2)),connKey:Re,isSameSheetCrossSectionConnection:!0,isPowerOrGroundConnection:A.has(ke)},oe.set(Qe,Ce),te.push(Ce)),Ce.schematicPortIds.includes(Pe)||Ce.schematicPortIds.push(Pe)},le=new Map,ge=new Map,_e=new Set;for(const Qe of O)Qe?.subcircuit_connectivity_map_key&&(Qe.connected_source_port_ids?.length??0)>0&&(Qe.connected_source_net_ids?.length??0)>0&&_e.add(Qe.subcircuit_connectivity_map_key);const ue=(Qe,Pe)=>{const we=n.schematic_port.get(Qe),Te=n.schematic_port.get(Pe);if(!we||!Te||!(we.schematic_sheet_id===Te.schematic_sheet_id))return!1;const Ee=we.schematic_component_id?_.get(we.schematic_component_id):void 0,ke=Te.schematic_component_id?_.get(Te.schematic_component_id):void 0;return Ee!==ke&&(Ee!==void 0||ke!==void 0)},fe=({schematicPortId:Qe,otherSourcePortId:Pe})=>n.schematic_port.list({source_port_id:Pe}).some(we=>ue(Qe,Am(we.schematic_port_id)));for(const Qe of O){const Pe=Array.from(new Set((Qe.connected_source_port_ids??[]).map(ke=>x.get(NO(ke))).filter(ke=>!!ke&&C.has(ke)).map(i))),we=Pe.length===1?y.get(Pe[0]):void 0,Te=we?Qe.connected_source_port_ids.map(NO).find(ke=>ke!==we):void 0,Re=!!(we&&Te&&wTt({db:n,sourcePortId:we,otherSourcePortId:Te,sourcePortIdsInSchematicScope:Q,schematicSheetId:e.schematicSheetId})),Ee=!!(Pe.length===1&&Te&&fe({schematicPortId:Pe[0],otherSourcePortId:Te}));if(Pe.length===1&&Qe.connected_source_port_ids.length===2&&Re&&Qe.connected_source_net_ids.length===0&&Qe.subcircuit_connectivity_map_key){const ke=Pe[0],Ce=y.get(ke);if(Ce){const Le=Qe.subcircuit_connectivity_map_key,Ye=n.source_port.get(Ce)?.subcircuit_connectivity_map_key,tt=n.source_net.list().find(gt=>gt.subcircuit_id===t.subcircuit_id&&r.areIdsConnected(gt.source_net_id,Ce)),At=c.get(Le)??(Ye?c.get(Ye):void 0)??tt,at=Array.from(C).map(gt=>y.get(gt)).filter(gt=>gt?n.source_port.get(gt)?.subcircuit_connectivity_map_key===Le:!1),{text:nt}=MTt({group:t,sourcePortId:Ce,connectedSourcePortIdsForKey:at,sourcePortIdsInSchematicScope:Q,schematicSheetId:e.schematicSheetId,connKey:Le,sourceNet:At});if(nt){const gt=a(Qe);E.has(gt)||E.set(gt,Le),Ee?ne({sourceConnectivityNetId:gt,schematicPortId:ke,text:nt,sourceTraceId:Qe.source_trace_id,connKey:Le}):ie({schematicPortId:ke,netId:gt,sourceTraceId:Qe.source_trace_id})&&te.push({netId:gt,netLabelText:nt,schematicPortIds:[ke],netLabelWidth:Number(vb({text:nt}).toFixed(2)),connKey:Le})}}}else if(Pe.length>=2){for(const gt of Pe){const bt=le.get(gt)??new Set;bt.add(Qe.source_trace_id),le.set(gt,bt)}const ke=Qe.name??Qe.display_name,Ce=ke??Qe.source_trace_id;Qe.subcircuit_connectivity_map_key&&E.set(Ce,Qe.subcircuit_connectivity_map_key);const Le=t._parsedProps.schMaxTraceDistance??DTt,Ye=Pe.map(gt=>B.get(gt)).filter(gt=>!!gt),tt=Qe.subcircuit_connectivity_map_key?S({subcircuitConnectivityMapKey:Qe.subcircuit_connectivity_map_key}).name:xMe(Ye).name||ke,At=Pe.slice(1).some((gt,bt)=>{const Ct=Pe[bt],Dt=n.schematic_port.get(Ct),kt=n.schematic_port.get(gt);return!Dt||!kt?!1:Math.sqrt((Dt.center.x-kt.center.x)**2+(Dt.center.y-kt.center.y)**2)>Le}),at=tt&&At?Number(vb({text:tt}).toFixed(2)):void 0,nt=tt;for(let gt=0;gt<Pe.length-1;gt++){const bt=Pe[gt],Ct=Pe[gt+1],Dt=[bt,Ct].sort().join("::");if(!j.has(Dt)){if(j.add(Dt),nt&&ue(bt,Ct)){const kt=a(Qe);Qe.subcircuit_connectivity_map_key&&E.set(kt,Qe.subcircuit_connectivity_map_key),ne({sourceConnectivityNetId:kt,schematicPortId:bt,text:nt,sourceTraceId:Qe.source_trace_id,connKey:Qe.subcircuit_connectivity_map_key,preferInScopeTraceMetadata:!0}),ne({sourceConnectivityNetId:kt,schematicPortId:Ct,text:nt,sourceTraceId:Qe.source_trace_id,connKey:Qe.subcircuit_connectivity_map_key,preferInScopeTraceMetadata:!0});continue}ge.set(Dt,Qe.source_trace_id),W.push({schematicPortIds:[bt,Ct],netId:Ce,netLabelWidth:at,connKey:Qe.subcircuit_connectivity_map_key})}}}}const pe=[...te],ye=new Map;for(const[Qe,Pe]of y){if(U.has(Qe))continue;const we=n.source_port.get(Pe);if(!we?.subcircuit_connectivity_map_key)continue;const Te=we.subcircuit_connectivity_map_key;ye.has(Te)||ye.set(Te,[]);const Re=i(Qe),Ee=ye.get(Te);Ee.includes(Re)||Ee.push(Re)}for(const[Qe,Pe]of ye){const we=c.get(Qe);if(we&&Pe.length>=1){const Te=String(we.name||we.source_net_id||Qe);E.set(Te,Qe);const Re=Number(vb({text:String(Te)}).toFixed(2));let Ee=Re,ke;(we.is_ground||we.is_power)&&(Ee=YDo,ke=Re),pe.push({netId:Te,schematicPortIds:Pe,isGround:we.is_ground,netLabelWidth:Ee,netLabelHeight:ke,connKey:Qe})}}RDo({directConnections:W,netConnections:pe,connKeyToSchematicPortIds:ye,connKeyToSourceNet:c,connKeysWithExplicitPortNetTraces:_e,schematicPortIdsWithExplicitNetLabels:M,schematicPortIdsWithInlineNetLabels:R,areSchematicPortsOnDifferentComponents:Qe=>{const Pe=Qe.map(we=>n.schematic_port.get(we)?.schematic_component_id);return Pe.every(we=>!!we)&&Pe[0]!==Pe[1]},resolveCanonicalNetLabelText:S});const Me=(()=>{const Qe={},Pe=new Set(pe.map(we=>we.netId));for(const we of n.source_net.list().filter(Te=>!Te.subcircuit_id||F.has(Te.subcircuit_id)))we.name&&Pe.has(we.name)&&(we.is_ground?Qe[we.name]=["y-"]:we.is_power?Qe[we.name]=["y+"]:Qe[we.name]=["x-","x+"]);for(const{netId:we}of te)Qe[we]??=["x-","x+"];return Qe})(),ve={chips:I,directConnections:W.map(({schematicPortIds:Qe,connKey:Pe,...we})=>({...we,pinIds:Qe})),netConnections:pe.map(({schematicPortIds:Qe,connKey:Pe,isSameSheetCrossSectionConnection:we,isPowerOrGroundConnection:Te,...Re})=>({...Re,pinIds:Qe})),textBoxes:m,availableNetLabelOrientations:Me,maxMspPairDistance:t._parsedProps.schMaxTraceDistance??DTt},he=new Map(Array.from(le).flatMap(([Qe,Pe])=>Pe.size!==1?[]:[[Qe,Pe.values().next().value]]));return{inputProblem:ve,routedSchematicPortIdBySchematicPortId:o,connKeyToSourceNet:c,userNetIdToConnKey:E,crossScopeSourceTraceIdBySchematicPortIdAndNetId:J,sourceTraceIdByPortOnlyLabelSchematicPortId:he,connKeysWithExplicitPortNetTraces:_e,schematicPortIdsInScope:C,schematicPortIdsWithExternallyRoutedRepresentations:U,schPortIdToSourcePortId:y,netLabelsInScope:w,sourceTraceIdByPinPairKey:ge}}var KDo=(t,e)=>{const n=new Set;for(const o of t){const{inline:i,schX:r,schY:s}=o._parsedProps;if(i||r===void 0&&s===void 0)continue;const a=o._getConnectedPorts();for(const A of a)A.schematic_port_id&&n.add(e.get(Am(A.schematic_port_id))??Am(A.schematic_port_id))}return n},VDo=({solver:t})=>{const e=t.traceCleanupSolver?.getOutput().traces??t.traceLabelOverlapAvoidanceSolver?.getOutput().traces??t.schematicTraceLinesSolver?.solvedTracePaths??[],n=new Set;for(const o of e){const i=o?.tracePath;if(!Array.isArray(i)||i.length<2)continue;const r=Array.isArray(o.pins)?o.pins.map(s=>s.pinId):o.pinIds;for(const s of r){const a=Am(s);a&&n.add(a)}}return n},NTt=.5,Nue=.1,RTt=t=>{const{nl:e,connKey:n,sourceNet:o,text:i}=t;return o?.source_net_id&&e.source_net_id?e.source_net_id===o.source_net_id:e.source_net_id?e.source_net_id===n:e.text===i},TTt=({schematicPortIdsInScope:t,schematicPortIdsWithExternallyRoutedRepresentations:e,group:n,schPortIdToSourcePortId:o,connKeyToSourceNet:i})=>{const{db:r}=n.root,s=new Set(Array.from(t).map(a=>o.get(a)).filter(a=>a!==void 0));for(const a of t){if(e.has(a))continue;const A=r.schematic_port.get(a);if(!A||A.is_connected)continue;const c=o.get(a);if(!c)continue;const l=r.source_port.get(c);if(n._parsedProps.showAsSchematicBox&&l?.subcircuit_id===n.subcircuit_id&&!l.source_component_id&&PTt({db:r,sourcePortId:c,sourcePortIdsInSchematicScope:s,schematicSheetId:A.schematic_sheet_id}))continue;const u=l?.subcircuit_connectivity_map_key;if(!u)continue;const g=i.get(u),h=A.schematic_component_id?r.schematic_component.get(A.schematic_component_id):void 0,d=h?.schematic_sheet_id??n._resolveSchematicSheetId(),p=Array.from(t).map(F=>o.get(F)).filter(F=>F?r.source_port.get(F)?.subcircuit_connectivity_map_key===u:!1),{text:m,wasAssignedDisplayLabel:_,directConnectionOutsideSchematicScopeSourcePortId:f}=MTt({group:n,sourcePortId:c,connectedSourcePortIdsForKey:p,sourcePortIdsInSchematicScope:s,schematicSheetId:A.schematic_sheet_id,connKey:u,sourceNet:g}),C=f?r.schematic_port.list({source_port_id:f}).some(F=>!F.is_connected):!1,y=h?.is_box_with_pins&&l&&!l.source_component_id,x=r.source_trace.list().some(F=>F.connected_source_port_ids.includes(c)&&F.subcircuit_id!==l?.subcircuit_id);if(y&&!x&&!!!(g||_))continue;const B=Array.from(t).filter(F=>{const O=o.get(F);return O?r.source_port.get(O)?.subcircuit_connectivity_map_key===u:!1}).length,S=g?.is_ground??!1,Q=!S&&(g?.is_power??!1);let w;S?w="top":Q?w="bottom":w=gO(A.facing_direction||"right")||"right";const M=j7({anchor_position:A.center,anchor_side:w,text:m}),k=r.schematic_net_label.list().find(F=>F.schematic_sheet_id!==d?!1:RTt({nl:F,connKey:u,sourceNet:g,text:m}));if(k&&B<=1&&!C){r.schematic_net_label.update(k.schematic_net_label_id,{text:m,anchor_position:A.center,center:M,anchor_side:w});continue}if(k){const F=k.anchor_position.x-A.center.x,O=k.anchor_position.y-A.center.y;if(F*F+O*O<NTt*NTt){if(S){const W=k.anchor_side??w;r.schematic_net_label.update(k.schematic_net_label_id,{text:m,anchor_position:A.center,center:j7({anchor_position:A.center,anchor_side:W,text:m}),anchor_side:W})}else if(!Q&&k.text===m){const W=k.anchor_side??w;r.schematic_net_label.update(k.schematic_net_label_id,{text:m,anchor_position:A.center,center:j7({anchor_position:A.center,anchor_side:W,text:m}),anchor_side:W})}continue}if(r.schematic_net_label.list().some(W=>{if(W.schematic_sheet_id!==d)return!1;const te=W.anchor_position.x-A.center.x,j=W.anchor_position.y-A.center.y;return te*te+j*j>=Nue*Nue?!1:RTt({nl:W,connKey:u,sourceNet:g,text:m})}))continue}if(!g&&!C)for(const F of r.schematic_net_label.list()){if(F.source_net_id!==u||F.schematic_sheet_id!==d)continue;p.some(U=>{const Y=Array.from(o.entries()).find(([,J])=>J===U)?.[0];let W;if(Y&&(W=r.schematic_port.get(Y)),!W?.center||!F.anchor_position)return!1;const te=F.anchor_position.x-W.center.x,j=F.anchor_position.y-W.center.y;return te*te+j*j<Nue*Nue})||r.schematic_net_label.delete(F.schematic_net_label_id)}const R={text:m,source_net_id:g?.source_net_id??u,anchor_position:A.center,center:M,anchor_side:w,schematic_sheet_id:d};r.schematic_net_label.insert(R)}},zDo=vc("Group_doInitialSchematicTraceRender"),kTt=({group:t,schematicSheetId:e,netLabels:n})=>{const{inputProblem:o,routedSchematicPortIdBySchematicPortId:i,connKeyToSourceNet:r,schematicPortIdsInScope:s,schematicPortIdsWithExternallyRoutedRepresentations:a,schPortIdToSourcePortId:A,userNetIdToConnKey:c,crossScopeSourceTraceIdBySchematicPortIdAndNetId:l,sourceTraceIdByPortOnlyLabelSchematicPortId:u,connKeysWithExplicitPortNetTraces:g,netLabelsInScope:h,sourceTraceIdByPinPairKey:d}=UDo(t,{schematicSheetId:e,netLabels:n});if(o.chips.length===0)return;const p=KDo(h,i);if(!(o.directConnections.length>0||o.netConnections.length>0)){TTt({group:t,schematicPortIdsInScope:s,schematicPortIdsWithExternallyRoutedRepresentations:a,schPortIdToSourcePortId:A,connKeyToSourceNet:r});return}zDo.enabled&&t.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(o,null,2)});const _=new Ewt(o),f=_.getConstructorParams();t.root?.emit("solver:started",{type:"solver:started",solverName:"SchematicTracePipelineSolver",solverParams:f[0],solverConstructorArgs:f,componentName:t.getString()}),_.solve();const I=VDo({solver:_});NDo({group:t,solver:_,userNetIdToConnKey:c,schematicPortIdsWithPreExistingNetLabels:p}),EDo({group:t,routedSchematicPortIdBySchematicPortId:i,solver:_,connKeyToSourceNet:r,userNetIdToConnKey:c,crossScopeSourceTraceIdBySchematicPortIdAndNetId:l,sourceTraceIdByPortOnlyLabelSchematicPortId:u,connKeysWithExplicitPortNetTraces:g,schematicPortIdsWithPreExistingNetLabels:p,schematicPortIdsWithRoutedTraces:I,netLabels:h}),IDo({group:t,solver:_,userNetIdToConnKey:c,sourceTraceIdByPinPairKey:d,crossScopeSourceTraceIdBySchematicPortIdAndNetId:l});const{db:C}=t.root;for(const[y,x]of i)C.schematic_port.get(x)?.is_connected&&C.schematic_port.update(y,{is_connected:!0});TTt({group:t,schematicPortIdsInScope:s,schematicPortIdsWithExternallyRoutedRepresentations:a,schPortIdToSourcePortId:A,connKeyToSourceNet:r})},JDo=t=>{if(!t.root?._featureMspSchematicTraceRouting||!t.isSubcircuit||t.root?.schematicDisabled)return;const e=new Set,n=t._getBoard();let o=t;for(;o;){if(o instanceof A6)for(const a of o.selectAll("netlabel"))e.add(a);if(o===n)break;o=o.parent}const i=[...e],r=new Set([t,...t.getDescendants().filter(a=>a instanceof A6)].map(a=>a.schematic_group_id).filter(a=>!!a)),s=new Set(t.root.db.schematic_component.list().filter(a=>r.has(a.schematic_group_id)).map(a=>a.schematic_sheet_id).filter(a=>!!a));if(s.size===0){kTt({group:t,netLabels:i});return}for(const a of s)kTt({group:t,schematicSheetId:a,netLabels:i})};function WDo(t){const e=[];for(const n of t.printStatements){const o=n.match(/^\.PRINT\s+TRAN\s+(.+)$/i);if(o)for(const i of o[1].match(/V\(([^)]+)\)/g)??[]){const r=i.slice(2,-1);e.push(r.replace(",","-"))}}return e}var FTt=["rgb(0, 150, 0)","rgb(0, 0, 220)","rgb(220, 0, 0)","rgb(0, 160, 160)","rgb(180, 0, 180)","rgb(170, 140, 0)","rgb(220, 120, 0)","rgb(128, 128, 128)","rgb(100, 0, 180)","rgb(140, 70, 0)","rgb(220, 80, 120)","rgb(0, 120, 220)","rgb(0, 120, 120)","rgb(120, 0, 0)","rgb(0, 0, 132)","rgb(80, 80, 80)"],Rue=new Map,Tue=0;function jDo(t){if(Rue.has(t))return Rue.get(t);const e=FTt[Tue];return Tue=(Tue+1)%FTt.length,Rue.set(t,e),e}function $Do(){Rue.clear(),Tue=0}var qDo=()=>({async simulate(t){const e="spice-experiment-1",{circuit:n,tran:o}=r5o(t);return{simulationResultCircuitJson:s5o(o,n,e)}}}),SMe=t=>t.type==="simulation_transient_current_graph",LTt=t=>t.type==="simulation_dc_operating_point_current"||t.type==="simulation_dc_sweep_current_graph"||t.type==="simulation_ac_sweep_current_graph",HTt=t=>t.type==="simulation_dc_operating_point_voltage"||t.type==="simulation_dc_sweep_voltage_graph"||t.type==="simulation_ac_sweep_voltage_graph",QMe=t=>t.type==="simulation_transient_voltage_graph",XDo=t=>QMe(t)||SMe(t)||HTt(t)||LTt(t),ZDo=({simulationResult:t,simulationParameterSweepCoordinate:e})=>{if(!e||!XDo(t))return t;const n={...t},o=`${n.type}_id`;return Reflect.deleteProperty(n,o),n.simulation_parameter_sweep_coordinate=e,n},vMe=({circuitJson:t,sourceComponentId:e,isMatchingSourceComponent:n})=>{const o=t.find(i=>n(i)&&i.source_component_id===e);if(!o)throw new Error(`Parameter sweep target ${e} was not found`);return o},eNo=({circuitJson:t,parameterSweep:e,simulationParameterSweepCoordinate:n})=>{const o=structuredClone(t),i=n.parameter_value;if(e.parameter_type==="resistance"){const r=vMe({circuitJson:o,sourceComponentId:e.resistor_source_component_id,isMatchingSourceComponent:s=>s.type==="source_component"&&s.ftype==="simple_resistor"});return r.resistance=i,o}if(e.parameter_type==="capacitance"){const r=vMe({circuitJson:o,sourceComponentId:e.capacitor_source_component_id,isMatchingSourceComponent:s=>s.type==="source_component"&&s.ftype==="simple_capacitor"});return r.capacitance=i,o}if(e.parameter_type==="inductance"){const r=vMe({circuitJson:o,sourceComponentId:e.inductor_source_component_id,isMatchingSourceComponent:s=>s.type==="source_component"&&s.ftype==="simple_inductor"});return r.inductance=i,o}if(e.parameter_type==="voltage"){const r=o.find(a=>a.type==="source_net"&&a.name.toUpperCase()==="GND");if(!r||r.type!=="source_net")throw new Error("A voltage parameter sweep requires a GND net");const s={type:"simulation_voltage_source",simulation_voltage_source_id:`simulation_voltage_source_${n.simulation_parameter_sweep_id}_${n.sweep_index}`,is_dc_source:!0,positive_source_net_id:e.source_net_id,negative_source_net_id:r.source_net_id,voltage:i};return o.push(s),o}if(e.parameter_type==="current"){const r=new Set(o.filter(a=>a.type==="source_port"&&a.source_component_id===e.current_source_component_id).map(a=>a.source_port_id)),s=o.find(a=>a.type==="simulation_current_source"&&(a.is_dc_source?!!(a.positive_source_port_id&&r.has(a.positive_source_port_id)):!!(a.terminal1_source_port_id&&r.has(a.terminal1_source_port_id))));if(!s)throw new Error(`Current sweep target ${e.current_source_component_id} has no simulation source`);return s.current=i,o}throw new Error("Parameter sweep target is incomplete")},OTt=({circuitJson:t,simulationParameterSweepCoordinate:e})=>{const n=T4o(t);return{spiceNetlist:n,spiceString:n.toSpiceString(),simulationParameterSweepCoordinate:e}},tNo=({circuitJson:t,simulationExperimentId:e})=>{const n=t.find(o=>o.type==="simulation_parameter_sweep"&&o.simulation_experiment_id===e);return n?n.parameter_values.map((o,i)=>{const r={simulation_parameter_sweep_id:n.simulation_parameter_sweep_id,sweep_index:i,parameter_value:o,parameter_unit:n.parameter_unit};return OTt({circuitJson:eNo({circuitJson:t,parameterSweep:n,simulationParameterSweepCoordinate:r}),simulationParameterSweepCoordinate:r})}):[OTt({circuitJson:t})]},nNo={p:1e-12,n:1e-9,u:1e-6,µ:1e-6,m:.001,"":1,k:1e3,K:1e3,M:1e6,G:1e9},Sw=t=>{if(t===void 0)return;if(typeof t=="number")return t;const n=t.trim().match(/^([+-]?(?:\d+(?:\.\d*)?|\.\d+))\s*([pnumµkKMG]?)/);if(!n)return;const o=Number(n[1]);if(Number.isFinite(o))return o*(nNo[n[2]??""]??1)},oNo=t=>{const{graphDisplayName:e,graphCenter:n,graphVerticalOffset:o,graphVoltagePerDiv:i}=t._parsedProps;return{displayName:e,color:t.color??void 0,center:n,verticalOffset:Sw(o),valuePerDiv:Sw(i)}},iNo=t=>{const{color:e,graphDisplayName:n,graphCenter:o,graphVerticalOffset:i,graphCurrentPerDiv:r}=t._parsedProps;return{displayName:n,color:e,center:o,verticalOffset:Sw(i),valuePerDiv:Sw(r)}},rNo=t=>{let e=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(const o of t)Number.isFinite(o)&&(e=Math.min(e,o),n=Math.max(n,o));return e===Number.POSITIVE_INFINITY||n===Number.NEGATIVE_INFINITY?null:{min:e,max:n}},sNo=t=>t.type==="simulation_transient_current_graph"?t.current_levels:t.voltage_levels,GTt=2,aNo=.8,ANo=({graph:t,index:e,graphCount:n})=>{const o=rNo(sNo(t));if(!o)return null;const i=(o.min+o.max)/2,r=o.max-o.min,s=r>0?r/(GTt*aNo):Math.max(Math.abs(i)/10,Number.EPSILON);return{display_center_value:i,display_center_offset_divs:((n-1)/2-e)*GTt,value_per_div:s}},cNo=t=>t!==void 0,lNo=t=>{const e=new Map;for(const n of t)n.simulation_voltage_probe_id&&e.set(n.simulation_voltage_probe_id,n);return e},uNo=t=>{const e=new Map;for(const n of t)n.simulation_current_probe_id&&e.set(n.simulation_current_probe_id,n);return e},gNo=({db:t,graphs:e,graphDisplayOverridesByProbeId:n})=>{if(e.length===0)return;const o=t.simulation_oscilloscope_trace.list(),i=lNo(o),r=uNo(o),s=new Set(o.flatMap(a=>[a.simulation_transient_voltage_graph_id,a.simulation_transient_current_graph_id]).filter(cNo));for(const[a,{type:A,graph:c}]of e.entries()){const l=ANo({graph:c,index:a,graphCount:e.length});if(!l)continue;const u=A==="voltage"?c.simulation_transient_voltage_graph_id:c.simulation_transient_current_graph_id;if(s.has(u))continue;const g=c.source_probe_id??void 0,h=g===void 0?void 0:A==="voltage"?i.get(g):r.get(g),d=g===void 0?void 0:n?.get(g),p=d?.valuePerDiv??l.value_per_div,m=d?.center??l.display_center_value,_=d?.verticalOffset!==void 0&&p!==0?d.verticalOffset/p:h?.display_center_offset_divs??l.display_center_offset_divs;t.simulation_oscilloscope_trace.insert({...A==="voltage"?{simulation_transient_voltage_graph_id:c.simulation_transient_voltage_graph_id,volts_per_div:p}:{simulation_transient_current_graph_id:c.simulation_transient_current_graph_id,amps_per_div:p},display_name:d?.displayName??h?.display_name,color:d?.color??h?.color??c.color,display_center_value:m,display_center_offset_divs:_})}},dNo=t=>!!(t&&typeof t=="object"&&"type"in t),vB=vc("tscircuit:core:Group_doInitialSimulationSpiceEngineRender"),hNo=({circuitJson:t,simulationExperimentId:e,voltageProbes:n,ammeters:o})=>{const i=new Set(n.map(s=>s.simulation_voltage_probe_id).filter(s=>!!s)),r=new Set(o.map(s=>s.simulation_current_probe_id).filter(s=>!!s));return t.filter(s=>{if(s.type==="simulation_experiment")return s.simulation_experiment_id===e;if(s.type==="simulation_voltage_probe")return i.has(s.simulation_voltage_probe_id);if(s.type==="simulation_current_probe")return r.has(s.simulation_current_probe_id);if(s.type==="simulation_parameter_sweep")return s.simulation_experiment_id===e;if(s.type==="simulation_oscilloscope_trace"){if(s.simulation_voltage_probe_id)return i.has(s.simulation_voltage_probe_id);if(s.simulation_current_probe_id)return r.has(s.simulation_current_probe_id)}return!(s.type==="simulation_transient_voltage_graph"||s.type==="simulation_transient_current_graph"||s.type==="simulation_dc_operating_point_voltage"||s.type==="simulation_dc_operating_point_current"||s.type==="simulation_dc_sweep_voltage_graph"||s.type==="simulation_dc_sweep_current_graph"||s.type==="simulation_ac_sweep_voltage_graph"||s.type==="simulation_ac_sweep_current_graph"||s.type==="simulation_unknown_experiment_error")})};function pNo(t){if(t.getInheritedProperty("analogSimulationDisabled")||!t.isSubcircuit)return;const{root:e}=t;if(!e)return;const n=[...t.selectAll("analogsimulation"),...t.selectAll("analogtransientsimulation"),...t.selectAll("analogdcoperatingpointsimulation"),...t.selectAll("analogdcsweepsimulation"),...t.selectAll("analogacsweepsimulation")];if(n.length===0)return;$Do();const o={...e.platform?.spiceEngineMap};o.spicey||(o.spicey=qDo());for(const i of n){const r=i.simulation_experiment_id;if(!r){vB("No simulation experiment id found, skipping simulation");continue}const s=e.db.simulation_experiment.get(r);if(!s){vB("No simulation experiment found, skipping simulation");continue}const a=i.getGroup()??t,A=a.selectAll("voltageprobe"),c=a.selectAll("ammeter"),l=hNo({circuitJson:e.db.toArray(),simulationExperimentId:r,voltageProbes:A,ammeters:c});let u;try{u=tNo({circuitJson:l,simulationExperimentId:r}),vB(`Generated ${u.length} SPICE run(s):
${u.map(B=>B.spiceString).join(`
`)}`)}catch(B){vB(`Failed to convert circuit JSON to SPICE: ${B}`),e.db.simulation_unknown_experiment_error.insert({simulation_experiment_id:r,error_type:"simulation_unknown_experiment_error",message:B instanceof Error?B.message:String(B)});continue}const g=new Map,h=new Map,d=new Map;for(const B of A)B.finalProbeName&&g.set(B.finalProbeName,B),B.simulation_voltage_probe_id&&(h.set(B.simulation_voltage_probe_id,B),d.set(B.simulation_voltage_probe_id,oNo(B)));for(const B of c)B.simulation_current_probe_id&&d.set(B.simulation_current_probe_id,iNo(B));const p=new Set(c.map(B=>B.simulation_current_probe_id).filter(B=>!!B)),m=new Map,_=new Map;for(const B of e.db.simulation_current_probe.list().filter(S=>p.has(S.simulation_current_probe_id)))m.set(B.simulation_current_probe_id,B),B.name!==void 0&&_.set(B.name,B);const f=e.db.simulation_voltage_probe.list().filter(B=>h.has(B.simulation_voltage_probe_id)),I=u[0]?.spiceNetlist,C=I?WDo(I):[];if(C.length===f.length)for(const[B,S]of f.entries()){const Q=h.get(S.simulation_voltage_probe_id),w=C[B];Q&&w&&g.set(w,Q)}else vB(`Skipping probe-to-graph order mapping because counts differ: probes=${f.length} graphNames=${C.length}`);const y=i.getSpiceEngineName()??"spicey",x=o[y];if(!x)throw new Error(`SPICE engine "${y}" not found in platform config. Available engines: ${JSON.stringify(Object.keys(o).filter(B=>B!=="spicey"))}`);const E=`spice-simulation-${y}-${r}`;vB(`Queueing simulation for spice engine: ${y} (id: ${E})`),t._queueAsyncEffect(E,async()=>{try{const B=[],S=[];for(const Q of u){vB(`Running simulation with engine: ${y}`);const w=await x.simulate(Q.spiceString);vB(`Simulation completed, received ${w.simulationResultCircuitJson.length} elements`);for(const M of w.simulationResultCircuitJson){if(!dNo(M)){vB("Skipping invalid simulation result element");continue}const k=ZDo({simulationResult:M,simulationParameterSweepCoordinate:Q.simulationParameterSweepCoordinate});if(QMe(k)){k.simulation_experiment_id=s.simulation_experiment_id;const F=k.name?g.get(k.name):void 0;F&&(k.color=F.color??void 0,k.source_probe_id=F.simulation_voltage_probe_id??void 0)}else if(HTt(k)){k.simulation_experiment_id=s.simulation_experiment_id;const F=h.get(k.simulation_voltage_probe_id)??(k.name?g.get(k.name):void 0);F?.simulation_voltage_probe_id&&(k.color=F.color??void 0,k.simulation_voltage_probe_id=F.simulation_voltage_probe_id)}if(SMe(k)){k.simulation_experiment_id=s.simulation_experiment_id;const F=(k.source_probe_id?m.get(k.source_probe_id):void 0)??(k.name?_.get(k.name):void 0);F&&(k.color=F.color,k.source_probe_id=F.simulation_current_probe_id)}else if(LTt(k)){k.simulation_experiment_id=s.simulation_experiment_id;const F=m.get(k.simulation_current_probe_id)??(k.name?_.get(k.name):void 0);F&&(k.color=F.color,k.simulation_current_probe_id=F.simulation_current_probe_id)}const R=e.db.insert(k);QMe(R)&&B.push({type:"voltage",graph:R}),SMe(R)&&S.push({type:"current",graph:R}),vB(`Inserted ${k.type} into database`)}}i.usesIndependentGraphAxes()&&gNo({db:e.db,graphs:[...B,...S],graphDisplayOverridesByProbeId:d}),t._markDirty("SimulationSpiceEngineRender")}catch(B){vB(`Simulation failed for engine ${y}: ${B}`),e.db.simulation_unknown_experiment_error.insert({simulation_experiment_id:r,error_type:"simulation_unknown_experiment_error",message:B instanceof Error?B.message:String(B)})}})}}function mNo(t){if(!t.isSubcircuit)return;const{db:e}=t.root,n=t.selectAll("trace"),o=t.selectAll("via"),i=t.selectAll("net"),r=new wQ({});r.addConnections(n.map(l=>{const u=e.source_trace.get(l.source_trace_id);return u?[u.source_trace_id,...u.connected_source_port_ids,...u.connected_source_net_ids]:null}).filter(l=>l!==null));const s=e.source_net.list().filter(l=>l.subcircuit_id===t.subcircuit_id);for(const l of s)r.addConnections([[l.source_net_id]]);const{name:a}=t._parsedProps;for(const l of n){if(!l.source_trace_id)continue;const u=r.getNetConnectedToId(l.source_trace_id);u&&(l.subcircuit_connectivity_map_key=`${a??`unnamedsubcircuit${t.subcircuit_id??t.source_group_id??t._renderId}`}_${u}`,e.source_trace.update(l.source_trace_id,{subcircuit_connectivity_map_key:l.subcircuit_connectivity_map_key}))}const A=new Set;for(const l of n){if(!l.source_trace_id)continue;const u=e.source_trace.get(l.source_trace_id);if(u)for(const g of u.connected_source_port_ids)A.add(g)}for(const l of A){const u=r.getNetConnectedToId(l);if(!u)continue;const g=`${a??`unnamedsubcircuit${t.subcircuit_id??t.source_group_id??t._renderId}`}_${u}`;e.source_port.update(l,{subcircuit_connectivity_map_key:g})}const c=new Set;for(const l of n){if(!l.source_trace_id)continue;const u=e.source_trace.get(l.source_trace_id);if(u)for(const g of u.connected_source_net_ids)c.add(g)}for(const l of s)c.add(l.source_net_id);for(const l of c){const u=r.getNetConnectedToId(l);if(!u)continue;const g=`${a??`unnamedsubcircuit${t.subcircuit_id??t.source_group_id??t._renderId}`}_${u}`;e.source_net.update(l,{subcircuit_connectivity_map_key:g});const h=i.find(d=>d.source_net_id===l);h&&(h.subcircuit_connectivity_map_key=g)}for(const l of o){const u=l._getConnectedNetOrTrace();u&&u.subcircuit_connectivity_map_key&&(l.subcircuit_connectivity_map_key=u.subcircuit_connectivity_map_key)}}var _No=t=>{const e=t.root?.firstChild===t;if(!t.isSubcircuit||!e||t._getBoard())return;const n=t.root?.pcbRoutingDisabled||t.getInheritedProperty("routingDisabled"),o=t.root?.platform?.drcChecksDisabled??t.getInheritedProperty("drcChecksDisabled"),i=t.root?.platform?.routingDrcChecksDisabled??t.getInheritedProperty("routingDrcChecksDisabled");if(t.root?.pcbDisabled||n||o||i||t._hasIncompleteAsyncEffectsInSubtreeForPhase("PcbTraceRender")||t._hasTracesToRoute()&&!t._areChildSubcircuitsRouted()||t._standaloneSubcircuitDrcChecksComplete||t._standaloneSubcircuitDrcChecksInProgress)return;const{db:r}=t.root,s=r.subtree({subcircuit_id:t.subcircuit_id}).toArray();t._standaloneSubcircuitDrcChecksInProgress=!0,t._queueAsyncEffect("standalone-subcircuit:routing-drc-checks",async()=>{try{const a=await jmt(s);r.insertAll(Ymt(a)),t._standaloneSubcircuitDrcChecksComplete=!0}finally{t._standaloneSubcircuitDrcChecksInProgress=!1}})},YTt=(t,e)=>{for(const[n,o]of Object.entries(e)){if(!o)continue;const i=Array.isArray(o)?o:[o],r=t.get(n)??new Set;for(const s of i)r.add(s);t.set(n,r)}},UTt=t=>Object.fromEntries(Array.from(t,([e,n])=>[e,n.size===1?Array.from(n)[0]:Array.from(n)])),fNo=(t,e)=>{const n=e.map(r=>r.fanoutPourNetMap).filter(r=>r!==void 0),o=new Map;if(n.length>0){for(const r of n)YTt(o,r);return UTt(o)}let i=t;for(;i;){if(i.isSubcircuit){const r=i,s=r.selectAll("copperpour");for(const a of s){if(a.getSubcircuit()!==r)continue;const{layer:A,connectsTo:c}=a._parsedProps;YTt(o,{[A]:c})}}i=i.parent}return o.size>0?UTt(o):void 0},KTt=(t,e)=>Math.hypot(t.x-e.x,t.y-e.y)<1e-4&&t.layer===e.layer;function INo(t,e,n){const o=t.getGroup(),i=o._computePcbGlobalTransformBeforeLayout(),r=WN(e.layerCount),s=new Map(e.connections.map(g=>[g,[...g.pointsToConnect]])),a=new Set,A=new Set,c=[];for(const[g,h]of(t._parsedProps.pcbTracePaths??[]).entries()){const d=t.getSubcircuit().selectOne(h.connection,{type:"port"});if(!d)throw new Error(`Saved phase path "${h.connection}" must select a PCB port`);if(A.has(d))throw new Error(`Duplicate saved phase path for "${h.connection}"`);A.add(d);const p=e.connections.filter(F=>F.pointsToConnect.some(O=>O.pcb_port_id===d.pcb_port_id));if(p.length!==1)throw new Error(`Saved phase path "${h.connection}" must select exactly one connection in this phase`);const m=p[0],_=s.get(m),f=_.findIndex(F=>F.pcb_port_id===d.pcb_port_id);if(f<0)throw new Error(`Saved phase path "${h.connection}" starts at an endpoint already joined by another path`);const I=d._getGlobalPcbPositionBeforeLayout(),C=d._getGlobalPcbPositionAfterLayout(),y=D0(M0(C.x-I.x,C.y-I.y),i),x=h.route.map(F=>({...F,...ts(y,F)}));for(const F of x)if((F.route_type==="wire"?[F.layer]:[F.from_layer,F.to_layer]).some(U=>!r.includes(U)))throw new Error(`Saved phase path "${h.connection}" uses a layer unavailable on this board`);const E=x[0],B=x.at(-1),S=E.route_type==="wire"?E.layer:E.from_layer,Q=B.route_type==="wire"?B.layer:B.to_layer;if(!KTt(_[f],{...E,layer:S}))throw new Error(`Saved phase path "${h.connection}" must start at its PCB port on an available layer`);const w=_.findIndex((F,O)=>O!==f&&KTt(F,{...B,layer:Q}));if(!e.allowViaInPad&&(E.route_type==="via"||B.route_type==="via"&&w>=0))throw new Error(`Saved phase path "${h.connection}" has a via at a pad; enable allowViaInPad`);const M=`saved_phase_${o.pcb_group_id}_${t._parsedProps.phaseIndex??"default"}_${g}`;if(w<0&&!n)throw new Error(`Saved phase path "${h.connection}" must end at another connection endpoint; use autorouter="fanout" for saved escapes`);w>=0?_.splice(f,1):_[f]={x:B.x,y:B.y,layer:Q,pointId:`${M}_exit`};const k=x.find(F=>F.route_type==="wire")?.width??e.minTraceWidth,R=x.flatMap(F=>F.route_type==="via"?[{route_type:"wire",x:F.x,y:F.y,layer:F.from_layer,width:k},F,{route_type:"wire",x:F.x,y:F.y,layer:F.to_layer,width:k}]:[F]);B.route_type==="via"&&R.push({route_type:"wire",x:B.x,y:B.y,layer:B.to_layer,width:k}),a.add(m),c.push({type:"pcb_trace",pcb_trace_id:M,connection_name:m.name,connectsTo:[m.source_trace_id,...m.pointsToConnect.map(F=>F.pointId)].filter(F=>!!F),route:R})}for(const g of e.connections){if(!a.has(g))throw new Error(`pcbTracePaths must cover every connection in the phase; missing: ${g.name}`);if(!n&&s.get(g).length>1)throw new Error(`Saved phase paths for "${g.name}" must connect every endpoint; use autorouter="fanout" for saved escapes`)}const l=e.connections.flatMap(g=>{const h=s.get(g);return h.length>1?[{...g,pointsToConnect:h}]:[]}),u=new Set(l.map(g=>g.name));return{traces:c,outputSimpleRouteJson:n?{...e,connections:l,buses:e.buses?.map(g=>({...g,connectionNames:g.connectionNames.filter(h=>u.has(h))})).filter(g=>g.connectionNames.length>0),differentialPairs:e.differentialPairs?.filter(g=>g.connectionNames.every(h=>u.has(h))),traces:[...e.traces??[],...c]}:void 0}}var CNo=qa.omit({pcbRotation:!0,layer:!0}),VTt=class extends Ir{pcb_breakout_point_id=null;matchedPort=null;matchedNet=null;matchedSourceTraceId=null;isPcbPrimitive=!0;_getSourceTraceIdForPort(t){const{db:e}=this.root;return e.source_trace.list().find(o=>o.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){const{db:e}=this.root;return e.source_trace.list().find(o=>o.connected_source_port_ids.includes(t.source_port_id))?.connected_source_net_ids[0]}_renderPcbBreakoutPoint({layer:t}={}){if(this.pcb_breakout_point_id||this.root?.pcbDisabled)return;const{db:e}=this.root,n=this._getGlobalPcbPositionBeforeLayout(),o=this.parent?.getGroup(),i=this.getSubcircuit();if(!o||!o.pcb_group_id)return;const r=e.pcb_breakout_point.insert({pcb_group_id:o.pcb_group_id,subcircuit_id:i?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this.matchedSourceTraceId??this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,layer:t,x:n.x,y:n.y});this.pcb_breakout_point_id=r.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){const t=this._getGlobalPcbPositionBeforeLayout();return{center:{x:t.x,y:t.y},bounds:{left:t.x,top:t.y,right:t.x,bottom:t.y},width:0,height:0}}_setPositionFromLayout(t){const{db:e}=this.root;if(!this.pcb_breakout_point_id)return;const n={x:t.x,y:t.y};this.matchedSourceTraceId&&(n.source_trace_id=this.matchedSourceTraceId),e.pcb_breakout_point.update(this.pcb_breakout_point_id,n)}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_breakout_point_id)return;const o=n.pcb_breakout_point.get(this.pcb_breakout_point_id);o&&n.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:o.x+t,y:o.y+e})}getPcbSize(){return{width:0,height:0}}},dR=class extends VTt{get config(){return{componentName:"BreakoutPoint",zodProps:wMn}}_matchConnection(){if(this.matchedPort)return;const{connection:t}=this._parsedProps,e=this.getSubcircuit();e&&(this.matchedPort=e.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=e.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}doInitialPcbPrimitiveRender(){this._matchConnection(),this._renderPcbBreakoutPoint()}},zTt=class extends dR{exitLayer="top";doInitialPcbPrimitiveRender(){this._matchConnection(),this._renderPcbBreakoutPoint({layer:this.exitLayer})}};function yNo(t,e){const{db:n}=t.root,o=WN(e.layerCount),i=new Set,r=t.children.filter(A=>A instanceof zTt),s=(t._parsedProps.pcbTracePaths??[]).map((A,c)=>{for(const S of A.route)if((S.route_type==="wire"?[S.layer]:[S.from_layer,S.to_layer]).some(w=>!o.includes(w)))throw new Error(`Saved fanout path "${A.connection}" uses a layer unavailable on this board`);const l=r[c],u=l.matchedPort,g=e.connections.find(S=>S.pointsToConnect.some(Q=>Q.pcb_port_id===u.pcb_port_id));if(!g)throw new Error(`No fanout connection for saved path "${A.connection}"`);const h=n.pcb_breakout_point.get(l.pcb_breakout_point_id),d=A.route.at(-1),p=D0(l._computePcbGlobalTransformBeforeLayout(),M0(-d.x,-d.y)),m=ts(p,d),_=A.route.map(S=>{const Q=ts(p,S);return{...S,x:Q.x+h.x-m.x,y:Q.y+h.y-m.y}}),f=_[0],I=f.route_type==="wire"?f.layer:f.from_layer,C=u._getGlobalPcbPositionAfterLayout();if(Math.hypot(f.x-C.x,f.y-C.y)>1e-4||!u.getAvailablePcbLayers().includes(I))throw new Error(`Saved fanout path "${A.connection}" must start at its PCB port on an available layer`);if(f.route_type==="via"&&!e.allowViaInPad)throw new Error(`Saved fanout path "${A.connection}" starts with a via at a pad; enable allowViaInPad`);const y=_.at(-1),x=y.route_type==="wire"?y.layer:y.to_layer,E=[{...f,layer:I},{...y,layer:x}];if(g.pointsToConnect.some(S=>!E.some(Q=>Math.hypot(S.x-Q.x,S.y-Q.y)<1e-4&&S.layer===Q.layer)))throw new Error(`Saved fanout path "${A.connection}" does not cover its connection endpoints`);const B=_.find(S=>S.route_type==="wire")?.width??e.minTraceWidth;return f.route_type==="via"&&(_.splice(1,0,{route_type:"wire",x:f.x,y:f.y,layer:f.to_layer,width:B}),_.unshift({route_type:"wire",x:f.x,y:f.y,layer:f.from_layer,width:B})),y.route_type==="via"&&(_.splice(_.length-1,0,{route_type:"wire",x:y.x,y:y.y,layer:y.from_layer,width:B}),_.push({route_type:"wire",x:y.x,y:y.y,layer:y.to_layer,width:B})),y.route_type==="via"&&_.push({route_type:"wire",x:y.x,y:y.y,layer:y.to_layer,width:B}),i.add(g),{type:"pcb_trace",pcb_trace_id:`saved_fanout_${t.pcb_group_id}_${c}`,connection_name:g.name,source_trace_id:g.source_trace_id,connectsTo:[g.source_trace_id,...g.pointsToConnect.map(S=>S.pointId)].filter(S=>!!S),route:_}}),a=e.connections.filter(A=>!i.has(A));if(a.length)throw new Error(`pcbTracePaths must cover every fanout connection; missing: ${a.map(A=>A.name).join(", ")}`);return s}function JTt(t){return t===null?Number.POSITIVE_INFINITY:t}function xNo(t,e){return JTt(t.routingPhaseIndex)-JTt(e.routingPhaseIndex)}function kue(t,e){let n=t.get(e);return n||(n={routingPhaseIndex:e,nets:[],traces:[]},t.set(e,n)),n}function WTt(t){return t.props.routingPhaseIndex??null}function ENo(t,e=[]){const n=new Set;for(const a of e){if(a._parsedProps.routingPhaseIndex===void 0)continue;a._parsedProps.connections.some(c=>c===t.name||PMe(t,Fue(c)))&&n.add(a._parsedProps.routingPhaseIndex)}if(n.size>1)throw new Error(`Trace "${t.name}" belongs to buses with different routing phases`);const o=n.values().next().value;if(o!==void 0)return o;const i=t.props.routingPhaseIndex;if(i!==void 0)return i;let r=null;const s=t._findConnectedNets().nets;for(const a of s){const A=WTt(a);typeof A=="number"&&(r===null||A<r)&&(r=A)}return r}function Fue(t){return t.trim().replace(/\s*>\s*/g,".").replace(/\s+/g,".").replace(/^\./,"").replace(/\.\./g,".")}function wMe(t){return t.connection===void 0&&t.connections===void 0?t.pcbTracePaths?.map(e=>e.connection)??[]:[...t.connection?[t.connection]:[],...t.connections??[]]}function PMe(t,e){if(t.getTracePortPathSelectors().some(o=>Fue(o)===e))return!0;const n=t.getSubcircuit().selectOne(e,{type:"port"});return n!==null&&(t._findConnectedPorts().ports?.includes(n)??!1)}function BNo(t){const e=t.selectAll("autoroutingphase"),n=new Map;for(const o of e){const{phaseIndex:i,autorouter:r}=o._parsedProps;r!==void 0&&n.set(i??null,r)}return n}function bNo(t){const e=t.selectAll("autoroutingphase"),n=new Map;for(const o of e){const i=o._parsedProps;n.set(i.phaseIndex??null,i)}return n}function Fb(t){if(t!==void 0)return Number(t)}function SNo(t){const{minTraceWidth:e,minViaHoleEdgeToViaHoleEdgeClearance:n,minPlatedHoleDrillEdgeToDrillEdgeClearance:o,minTraceToPadEdgeClearance:i,minPadEdgeToPadEdgeClearance:r,minBoardEdgeClearance:s,minViaEdgeToPadEdgeClearance:a,minViaHoleDiameter:A,minViaPadDiameter:c}=t;if(!(e===void 0&&n===void 0&&o===void 0&&i===void 0&&r===void 0&&s===void 0&&a===void 0&&A===void 0&&c===void 0))return{minTraceWidth:Fb(e),minViaHoleEdgeToViaHoleEdgeClearance:Fb(n),minPlatedHoleDrillEdgeToDrillEdgeClearance:Fb(o),minTraceToPadEdgeClearance:Fb(i),minPadEdgeToPadEdgeClearance:Fb(r),minBoardEdgeClearance:Fb(s),minViaEdgeToPadEdgeClearance:Fb(a),minViaHoleDiameter:Fb(A),minViaPadDiameter:Fb(c)}}function QNo(t){const e=t.selectAll("trace"),n=t.selectAll("net"),o=t.selectAll("bus"),i=t.selectAll("group").filter(_=>_.isRoutingDirective),r=new Map,s=new Map;for(const _ of e){let f=_.parent;for(;f&&f!==t;){if(f.isRoutingDirective){r.set(_,f);break}f=f.parent}}for(const _ of n)_.parent?.isRoutingDirective&&i.includes(_.parent)&&s.set(_,_.parent);const a=new Map,A=BNo(t),c=bNo(t),l=t._parsedProps,u=e.length>0||n.length>0,g=Array.from(c.values()).some(_=>_.reroute),h=Array.from(c.values()).some(_=>wMe(_).length>0);if(!u&&!g&&!h&&i.length===0)return[];for(const _ of n){if(s.has(_))continue;const f=WTt(_);kue(a,f).nets.push(_)}for(const _ of e){if(r.has(_))continue;const f=ENo(_,o);kue(a,f).traces.push(_)}for(const[_,f]of c){const I=wMe(f);if(I.length>0){const C=kue(a,_),y=I.map(Fue);C.connectionSelectors=I;for(const x of e)if(!r.has(x)&&y.some(E=>PMe(x,E))){if(!f.reroute)for(const E of a.values())E!==C&&(E.traces=E.traces.filter(B=>B!==x));if(C.traces.includes(x))continue;C.traces.push(x)}}(f.reroute||f.pcbTracePaths!==void 0)&&kue(a,_)}const d=Array.from(a.values()).sort(xNo);for(const _ of d){_.autorouter=A.get(_.routingPhaseIndex);const f=c.get(_.routingPhaseIndex);_.phaseName=f?.name,_.reroute=f?.reroute,_.region=f?.region,_.connectionSelectors=f?wMe(f):void 0,_.busFanoutDirections=f?.busFanoutDirections??l.busFanoutDirections,_.fanoutBoundaryPadding=f?.fanoutBoundaryPadding??l.fanoutBoundaryPadding;const I=f?.fanoutRoutingLayers??l.fanoutRoutingLayers;_.fanoutRoutingLayers=I?.map(C=>typeof C=="string"?C:C.name),_.fanoutPourNetMap=f?.fanoutPourNetMap??l.fanoutPourNetMap,_.drcTolerances=f?SNo(f):void 0}for(const _ of t.selectAll("autoroutingphase")){if(_._parsedProps.pcbTracePaths===void 0)continue;const f=a.get(_._parsedProps.phaseIndex??null);if(!f)continue;const I=f.autorouter!==void 0?h$(f.autorouter,t.root?.platform):t._getAutorouterConfig(),C=["fanout","single_layer_fanout"].includes(I.preset??"");f.getPrecomputedRoutingResult=y=>INo(_,y,C)}const p=[];for(const _ of i){const f=_._parsedProps,C=_.children.some(O=>O instanceof dR)&&_.props.autorouter===void 0,y=e.filter(O=>r.get(O)===_),x=y.filter(O=>!O.pcb_trace_id),E=_.pcb_group_id?_.root?.db.pcb_group.get(_.pcb_group_id):null,B=E?.outline?Oh(E.outline):null,S=E?.width??(B?B.maxX-B.minX:void 0),Q=E?.height??(B?B.maxY-B.minY:void 0),w=E&&S&&Q?{minX:E.center.x-S/2,maxX:E.center.x+S/2,minY:E.center.y-Q/2,maxY:E.center.y+Q/2}:void 0,M=_.props,k=M.width!==void 0||M.height!==void 0||!!M.outline?.length,R=M.fanoutBoundaryPadding!==void 0,F={routingPhaseIndex:null,routingPcbGroupId:_.pcb_group_id??void 0,fanoutRegionPcbGroupId:_.pcb_group_id??void 0,routingBounds:w,fanoutBounds:k?w:R?void 0:w,autorouter:f.autorouter??"fanout",busFanoutDirections:f.busFanoutDirections,fanoutBoundaryPadding:f.fanoutBoundaryPadding,fanoutRoutingLayers:f.fanoutRoutingLayers?.map(O=>typeof O=="string"?O:O.name),fanoutPourNetMap:f.fanoutPourNetMap,nets:n.filter(O=>s.get(O)===_),traces:y};if(_._parsedProps.pcbTracePaths!==void 0){p.push({...F,autorouter:{local:!0,groupMode:"subcircuit",allowViaInPad:(typeof f.autorouter=="object"?f.autorouter.allowViaInPad:void 0)??t._getAutorouterConfig().allowViaInPad},getPrecomputedRoutingResult:O=>({traces:yNo(_,O)})});continue}if(!C){p.push(F);continue}if(p.push({...F,autorouter:"default",traces:[]}),x.length>0){const O=new Set(o.filter(Y=>x.some(W=>Y._parsedProps.connections.some(te=>te===W.name||PMe(W,Fue(te))))).map(Y=>Y.name));for(const Y of x)Y.name&&O.add(Y.name);const U=f.busFanoutDirections?Object.fromEntries(Object.entries(f.busFanoutDirections).filter(([Y])=>O.has(Y))):void 0;p.push({...F,routingPcbGroupId:void 0,busFanoutDirections:U,traces:x})}}const m=c.get(null);if(u&&c.size===1&&m?.reroute&&d.length===1&&d[0]?.routingPhaseIndex===null){const _=d[0];return[...p,{routingPhaseIndex:null,nets:[..._.nets],traces:[..._.traces]},_]}return[...p,...d]}var jTt={version:"0.0.1910"},$Tt=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return e>>>0},qTt=t=>{const e=JSON.stringify(t),n=$Tt(e),o=$Tt(`${e}${n}`);return`${n.toString(16).padStart(8,"0")}${o.toString(16).padStart(8,"0")}`},vNo=(t,e)=>`routes:core@${jTt.version}:solver:${qTt(e)}:srj:${qTt(t)}`,wNo=async({cacheEngine:t,cacheKey:e})=>{if(!t)return null;try{const n=await t.getItem(e);if(!n)return null;const o=JSON.parse(n);return!o||!Array.isArray(o.traces)?null:o}catch{return null}},PNo=async({cacheEngine:t,cacheKey:e,result:n})=>{if(t)try{await t.setItem(e,JSON.stringify(n))}catch{}},XTt=1e-6,ZTt=(t,e)=>t.pointId!==void 0&&e.pointId!==void 0&&t.pointId===e.pointId,ekt=(t,e)=>Math.abs(t.x-e.x)<=XTt&&Math.abs(t.y-e.y)<=XTt&&t.layer===e.layer,I$=(t,e)=>t.pointId!==void 0&&e.pointId!==void 0?ZTt(t,e):ekt(t,e),MNo=(t,e)=>{const n=t.connections.find(i=>i.routingPcbGroupId!==e.routingPcbGroupId&&i.source_trace_id===e.source_trace_id&&i.pointsToConnect.some(r=>e.pointsToConnect.some(s=>I$(r,s))));if(!n)return;const o=n.pointsToConnect.filter(i=>!e.pointsToConnect.some(r=>I$(i,r)));return o.length===1?o[0]:void 0},DNo=(t,e)=>{if(!e.routingPcbGroupId||!e.source_trace_id)return;const n=MNo(t,e);if(!(!n||!t.connections.some(i=>i.routingPcbGroupId!==void 0&&i.routingPcbGroupId!==e.routingPcbGroupId&&i.source_trace_id===e.source_trace_id&&i.pointsToConnect.some(r=>I$(r,n)))))return{x:n.x,y:n.y,layer:n.layer}};function tkt(t,e){if(t.routingPcbGroupId)return t.routingPcbGroupId===e.routingPcbGroupId;for(const n of e.traces)if(n.source_trace_id&&(t.source_trace_id===n.source_trace_id||t.name===n.source_trace_id||t.rootConnectionName===n.source_trace_id||t.mergedConnectionNames?.includes(n.source_trace_id)))return!0;for(const n of e.nets)if(n.source_net_id&&t.name===n.source_net_id)return!0;return!1}function NNo(t){for(const e of t)if(e.routingPcbGroupId||e.routingPhaseIndex!==null)return!0;return!1}function Lue(t,e){const n=[];for(const A of t.connections)tkt(A,e)&&n.push(A);const o=new Set;for(const A of n)o.add(A.name);const i=[];for(const A of t.differentialPairs??[]){const c=o.has(A.connectionNames[0]),l=o.has(A.connectionNames[1]);if(c!==l)throw new Error(`Differential pair "${A.connectionNames.join("/")}" cannot be split across autorouting phases`);c&&i.push(A)}const r=new Map(n.map(A=>[A.name,A])),s=(t.buses??[]).map(A=>{const c=A.connectionNames.filter(u=>o.has(u)),l=Object.fromEntries(c.flatMap(u=>{const g=r.get(u);if(!g)return[];const h=DNo(t,g);return h?[[u,h]]:[]}));return{...A,connectionNames:c,...Object.keys(l).length>0?{connectionExitTargets:l}:{}}}).filter(A=>A.connectionNames.length>0),a=zRt({bounds:e.routingBounds??t.bounds,connections:n});return{...t,bounds:a,connections:n,differentialPairs:i.length>0?i:void 0,buses:s.length>0?s:void 0}}function RNo(t){return t?Object.values(t).some(e=>e!==void 0):!1}function TNo(t,e){return e===void 0?t:t.map(n=>({...n,nominalTraceWidth:Math.max(n.nominalTraceWidth??e,e),width:Math.max(n.width??e,e)}))}function nkt(t,e){if(!RNo(e))return t;const n=e.minTraceWidth??t.minTraceWidth,o=e.minViaHoleDiameter??t.minViaHoleDiameter,i=e.minViaPadDiameter??t.minViaPadDiameter,r=e.minTraceToPadEdgeClearance??t.minTraceToPadEdgeClearance,s=e.minViaEdgeToPadEdgeClearance??t.minViaEdgeToPadEdgeClearance,a=e.minViaHoleEdgeToViaHoleEdgeClearance??t.minViaHoleEdgeToViaHoleEdgeClearance,A=e.minPlatedHoleDrillEdgeToDrillEdgeClearance??t.minPlatedHoleDrillEdgeToDrillEdgeClearance,c=e.minPadEdgeToPadEdgeClearance??t.minPadEdgeToPadEdgeClearance,l=e.minBoardEdgeClearance??t.minBoardEdgeClearance;return{...t,connections:TNo(t.connections,e.minTraceWidth),minTraceWidth:n,minViaDiameter:i,minViaHoleDiameter:o,minViaPadDiameter:i,min_via_hole_diameter:o,min_via_pad_diameter:i,minTraceToPadEdgeClearance:r,minViaEdgeToPadEdgeClearance:s,minViaHoleEdgeToViaHoleEdgeClearance:a,minPlatedHoleDrillEdgeToDrillEdgeClearance:A,minPadEdgeToPadEdgeClearance:c,minBoardEdgeClearance:l}}var kNo=(t,e)=>{const n=t.connections.filter(s=>s.routingPcbGroupId!==e),o=new Set(n.map(s=>s.name)),i=[];for(const s of t.differentialPairs??[]){const a=o.has(s.connectionNames[0]),A=o.has(s.connectionNames[1]);if(a!==A)throw new Error(`Differential pair "${s.connectionNames.join("/")}" cannot be split at a breakout boundary`);a&&i.push(s)}const r=(t.buses??[]).map(s=>({...s,connectionNames:s.connectionNames.filter(a=>o.has(a))})).filter(s=>s.connectionNames.length>0);return{...t,connections:n,differentialPairs:i.length>0?i:void 0,buses:r.length>0?r:void 0}},FNo=(t,e)=>({...t,traces:t.traces?.map(n=>{const o=e.get(n.connection_name??"");return o?{...n,connectsTo:[...new Set([...n.connectsTo??[],o])]}:n})});function LNo({fanoutInputSimpleRouteJson:t,fanoutOutputSimpleRouteJson:e,baseSimpleRouteJson:n,routingPhasePlan:o}){const i=o.routingPcbGroupId;if(!i)return{downstreamSimpleRouteJson:e,baseSimpleRouteJson:n,synchronizedBreakoutPoints:[]};const r=new Map(e.connections.map(g=>[g.name,g])),s=n.connections.map(g=>({...g,pointsToConnect:g.pointsToConnect.map(h=>({...h}))})),a=[],A=new Map;for(const g of t.connections){if(g.routingPcbGroupId!==i||!g.source_trace_id)continue;const h=r.get(g.name);if(!h)continue;const p=s.filter(f=>{if(f.routingPcbGroupId===i)return!1;const I=f.source_trace_id===g.source_trace_id,C=f.pointsToConnect.some(y=>g.pointsToConnect.some(x=>ZTt(y,x)));return!I&&!C?!1:f.pointsToConnect.some(y=>g.pointsToConnect.some(x=>I$(y,x)))}).flatMap(f=>f.pointsToConnect.flatMap((I,C)=>g.pointsToConnect.some(y=>I$(I,y))?[{globalConnection:f,pointIndex:C,previousPoint:I}]:[]));if(p.length===0)continue;const m=h.pointsToConnect.findIndex((f,I)=>{const C=g.pointsToConnect[I];return C!==void 0&&!ekt(f,C)});if(m<0)continue;const _=h.pointsToConnect[m];for(const{globalConnection:f,pointIndex:I,previousPoint:C}of p){const{terminalVia:y,...x}=C,E={...x,x:_.x,y:_.y,layer:_.layer,..._.terminalVia?{terminalVia:{..._.terminalVia}}:{}};f.pointsToConnect[I]=E,C.pointId&&A.set(g.name,C.pointId),a.push({sourceTraceId:g.source_trace_id,routingPcbGroupId:i,previousPoint:C,fanoutExitPoint:_})}}const c=e.obstacles.filter(g=>g.isFanoutSourceKeepout===!0&&g.componentId!==void 0),l=new Set(c.flatMap(g=>g.componentId===void 0?[]:[g.componentId])),u=n.obstacles.filter(g=>!g.componentId||!l.has(g.componentId));return{downstreamSimpleRouteJson:kNo(FNo(e,A),i),baseSimpleRouteJson:{...n,connections:s,obstacles:[...u,...c]},synchronizedBreakoutPoints:a}}function HNo(t){const e=[],o=t.pcb_smtpad.list().filter(i=>{const r=t.pcb_component.get(i.pcb_component_id);return r?t.source_component.get(r.source_component_id)?.name?.startsWith("__autoplaced_jumper"):!1});for(const i of o)if(i.shape!=="polygon"&&i.pcb_port_id){if(i.shape==="rect"||i.shape==="rotated_rect"){const r=i.width/2,s=i.height/2;e.push({pcb_port_id:i.pcb_port_id,x:i.x,y:i.y,minX:i.x-r,maxX:i.x+r,minY:i.y-s,maxY:i.y+s})}else if(i.shape==="circle"){const r=i.radius;e.push({pcb_port_id:i.pcb_port_id,x:i.x,y:i.y,minX:i.x-r,maxX:i.x+r,minY:i.y-r,maxY:i.y+r})}}return e}function okt(t,e,n,o=.01){for(const i of t)if(Math.abs(i.x-e)<o&&Math.abs(i.y-n)<o)return i.pcb_port_id}function ONo(t,e,n){for(const o of t)if(e>=o.minX&&e<=o.maxX&&n>=o.minY&&n<=o.maxY)return o}function GNo(t,e){if(t.length===0||e.length===0)return[t];const n=[];let o=[];for(let i=0;i<t.length;i++){const r=t[i];if(o.push(r),r.route_type==="wire"&&i>0&&i<t.length-1){const s=ONo(e,r.x,r.y);if(s){r.end_pcb_port_id||(r.end_pcb_port_id=s.pcb_port_id),n.push(o);const a={...r};delete a.end_pcb_port_id,a.start_pcb_port_id||(a.start_pcb_port_id=s.pcb_port_id),o=[a]}}}return o.length>0&&n.push(o),n}function YNo(t,e){const n=HNo(e);if(n.length===0)return t;const o=[];for(const i of t){const r=GNo(i,n);for(const s of r)if(s.length>0){const a=s[0],A=s[s.length-1];if(a.route_type==="wire"&&!a.start_pcb_port_id){const c=okt(n,a.x,a.y);c&&(a.start_pcb_port_id=c)}if(A.route_type==="wire"&&!A.end_pcb_port_id){const c=okt(n,A.x,A.y);c&&(A.end_pcb_port_id=c)}o.push(s)}}return o}var ikt=({db:t,pcbTrace:e,routeWithSrjMetadata:n})=>{for(const o of n){if(o.route_type!=="through_pad")continue;const i=o.circuitJsonMetadata?.pcb_via_id;if(!i)continue;const r=t.pcb_via.get(i);!r?.net_is_assignable||r.net_assigned&&r.pcb_trace_id!==e.pcb_trace_id||t.pcb_via.update(r.pcb_via_id,{pcb_trace_id:e.pcb_trace_id,net_assigned:!0})}},rkt=(t,e,n,o)=>Math.max(n-e,t-o),UNo=t=>{for(let e=0;e<t.length;e++){const n=t[e];for(let o=e+1;o<t.length;o++){const i=t[o];if(n.regionId&&n.regionId===i.regionId)continue;const r=rkt(n.bounds.minX,n.bounds.maxX,i.bounds.minX,i.bounds.maxX),s=rkt(n.bounds.minY,n.bounds.maxY,i.bounds.minY,i.bounds.maxY),a=Math.max(r,s),A=n.boundaryKeepaway+i.boundaryKeepaway;if(a+1e-6<A)return{firstRegion:n,secondRegion:i,availableGap:a,requiredGap:A}}}};function kO({accumulatedPcbTraces:t,stageOutputPcbTraces:e}){const n=new Set(e.flatMap(o=>[o.pcb_trace_id,...o.__replaces_pcb_trace_id?[o.__replaces_pcb_trace_id]:[]]));return[...t.filter(o=>!n.has(o.pcb_trace_id)),...e]}var KNo=1e-6;function VNo({point:t,segmentStart:e,segmentEnd:n}){return t.layer&&(e.layer!==t.layer||n.layer!==t.layer)?!1:Zd(t,e,n)<=KNo}function zNo({point:t,pad:e,traceWidth:n=0}){return e.shape==="rect"||e.shape==="rotated_rect"?Math.abs(t.x-e.x)<=e.width/2+n/2&&Math.abs(t.y-e.y)<=e.height/2+n/2:e.shape==="circle"?ad(t,e)<=e.radius+n/2:!1}function JNo({point:t,hole:e,traceWidth:n=0}){return ad(t,e)<=(e.outer_diameter??e.hole_diameter??0)/2+n/2}function WNo(t,e){const n=new Set,o=e.route,i=[o[0],o[o.length-1]].filter(r=>!!r&&r.route_type==="wire"&&r.x!==void 0&&r.y!==void 0);for(const r of i){for(const s of t.pcb_port.list())s.source_port_id&&(r.layer&&s.layers&&!s.layers.includes(r.layer)||ad(r,s)<=.01&&n.add(s.source_port_id));for(const s of t.pcb_smtpad.list()){if(!s.pcb_port_id||r.layer&&s.layer!==r.layer||!zNo({point:r,pad:s,traceWidth:r.width}))continue;const a=t.pcb_port.get(s.pcb_port_id)?.source_port_id;a&&n.add(a)}for(const s of t.pcb_plated_hole.list()){if(!s.pcb_port_id||!JNo({point:r,hole:s,traceWidth:r.width}))continue;const a=t.pcb_port.get(s.pcb_port_id)?.source_port_id;a&&n.add(a)}}return[...n]}function jNo(t){const e=t.route.filter(n=>n.route_type==="wire"&&n.x!==void 0&&n.y!==void 0);return[e[0],e[e.length-1]].filter(n=>!!n)}function $No(t,e){const n=new Set,o=jNo(e);if(o.length===0)return[];for(const i of t.pcb_trace.list()){if(!i.source_trace_id||i.pcb_trace_id===e.pcb_trace_id||!t.source_trace.get(i.source_trace_id)&&!t.source_net.get(i.source_trace_id))continue;const r=i.route.filter(s=>s.route_type==="wire");for(let s=0;s<r.length-1;s++){const a=r[s],A=r[s+1];if(!(!a||!A))for(const c of o)VNo({point:c,segmentStart:a,segmentEnd:A})&&n.add(i.source_trace_id)}}return[...n]}function qNo(t,e){const n=new Set;for(const o of e.route)for(const i of[o.start_pcb_port_id,o.end_pcb_port_id]){if(!i)continue;const r=t.pcb_port.get(i)?.source_port_id;r&&n.add(r)}return n.size>0?[...n]:WNo(t,e)}function XNo(t){const e=new wQ({});return e.addConnections(t.map(n=>[n.source_trace_id,...n.connected_source_port_ids,...n.connected_source_net_ids])),e}function MMe({db:t,trace:e,subcircuit_id:n}){if(e.source_trace_id&&(t.source_trace.get(e.source_trace_id)??t.source_net.get(e.source_trace_id)))return e.source_trace_id;const o=qNo(t,e);if(o.length===0)return $No(t,e)[0];const i=t.source_trace.list(),r=XNo(i),s=o.map(u=>r.getNetConnectedToId(u)).filter(u=>!!u),a=o.length>=2?i.find(u=>o.every(g=>u.connected_source_port_ids.includes(g))):void 0;if(a)return a.source_trace_id;const A=i.filter(u=>{const g=r.getNetConnectedToId(u.source_trace_id);return s.some(h=>h===g)}),c=A.filter(u=>u.connected_source_port_ids.some(g=>o.includes(g))),l=c.length>0?c:A;if(l.length!==0)return(l.find(u=>u.subcircuit_id===n)??l[0])?.source_trace_id}function ZNo(t,e){const o=[];for(const i of t){const r=e==="vertical"?i.center.y:i.center.x;let s=!1;for(const a of o){const A=e==="vertical"?a[0].center.y:a[0].center.x;if(Math.abs(r-A)<.01){a.push(i),s=!0;break}}s||o.push([i])}return o.filter(i=>i.length>=2)}function eRo(t){const{db:e,output_jumpers:n,subcircuit_id:o}=t;for(let i=0;i<n.length;i++){const r=n[i],s=e.source_component.insert({ftype:"simple_chip",name:`__autoplaced_jumper_${i}`,supplier_part_numbers:{}}),a=r.orientation==="horizontal"?0:90,A=r.pads[0]?.layer||r.pads[0]?.layers?.[0]||"top",c=e.pcb_component.insert({source_component_id:s.source_component_id,center:r.center,rotation:a,layer:A,width:r.width||0,height:r.height||0,obstructs_within_bounds:!1}),l=[];for(let g=0;g<r.pads.length;g++){const h=r.pads[g],d=g+1,p=e.source_port.insert({source_component_id:s.source_component_id,name:`pin${d}`,pin_number:d}),m=h.layer||h.layers?.[0]||"top",_=e.pcb_port.insert({pcb_component_id:c.pcb_component_id,source_port_id:p.source_port_id,x:h.center.x,y:h.center.y,layers:[m]}),f=e.pcb_smtpad.insert({pcb_component_id:c.pcb_component_id,pcb_port_id:_.pcb_port_id,shape:"rect",x:h.center.x,y:h.center.y,width:h.width,height:h.height,layer:m});l.push({pad:h,sourcePortId:p.source_port_id,pcbSmtpadId:f.pcb_smtpad_id})}const u=ZNo(r.pads,r.orientation);for(const g of u){const h=[];for(const d of g){const p=l.find(m=>Math.abs(m.pad.center.x-d.center.x)<.01&&Math.abs(m.pad.center.y-d.center.y)<.01);p&&h.push(p.sourcePortId)}h.length>=2&&e.source_component_internal_connection.insert({source_component_id:s.source_component_id,subcircuit_id:o??void 0,source_port_ids:h})}}}function tRo(t){return{...t,type:"pcb_trace",pcb_trace_id:t.pcb_trace_id,connection_name:t.connection_name??t.source_trace_id??t.pcb_trace_id,route:t.route.map(e=>({...e}))}}function nRo(t){const e=new Set;if(!t.subcircuit_id)return e;e.add(t.subcircuit_id);const n=t.root?.db;if(!n)return e;for(const o of uPe(n,t.subcircuit_id))e.add(o);return e}function DMe(t){const e=t.root?.db;if(!e)return[];const n=nRo(t);return e.pcb_trace.list().filter(o=>!o.route||o.route.length<2?!1:t.subcircuit_id?!!(o.subcircuit_id&&n.has(o.subcircuit_id)):!0)}function NMe(t){return typeof t!="string"||t.length===0?[]:t.split("__").flatMap(e=>{if(e.length===0)return[];const n=[e],o=e.indexOf("_reroute_");return o>0&&n.push(e.slice(0,o)),n})}function RMe(t,e){if(!(typeof e!="string"||e.length===0)){t.add(e);for(const n of NMe(e))t.add(n)}}function oRo({group:t,outputPcbTraces:e,pcbTraceIdsToReplace:n=[]}){const o=t.root?.db;if(!o)return;const i=new Set(n),r=new Set;for(const A of e){if(A.type!=="pcb_trace")continue;const c=A;i.add(c.pcb_trace_id),RMe(r,c.source_trace_id),RMe(r,c.connection_name),RMe(r,c.rootConnectionName)}if(i.size===0&&r.size===0)return;const s=DMe(t).filter(A=>i.has(A.pcb_trace_id)||!!(A.source_trace_id&&A.subcircuit_id===t.subcircuit_id&&r.has(A.source_trace_id)));if(s.length===0)return;const a=new Set(s.map(A=>A.pcb_trace_id));for(const A of o.pcb_via.list())A.pcb_trace_id&&a.has(A.pcb_trace_id)&&o.pcb_via.delete(A.pcb_via_id);for(const A of s)o.pcb_trace.delete(A.pcb_trace_id)}function iRo(t){return DMe(t).map(tRo)}function rRo(t){const e=t.filter(s=>s.route_type==="jumper"),n=t.filter(s=>s.route_type!=="jumper");if(e.length===0)return null;const o=[];for(const s of e){const a=s.start,A=s.end;let c=-1,l=-1,u=1/0,g=1/0;for(let h=0;h<n.length;h++){const d=n[h];if(d.route_type!=="wire")continue;const p=Math.hypot(d.x-a.x,d.y-a.y),m=Math.hypot(d.x-A.x,d.y-A.y);p<u&&(u=p,c=h),m<g&&(g=m,l=h)}c>l&&([c,l]=[l,c]),c>=0&&l>=0&&c!==l&&o.push({startIdx:c,endIdx:l})}o.sort((s,a)=>s.startIdx-a.startIdx);const i=[];let r=0;for(const s of o)r<s.startIdx&&i.push(n.slice(r,s.startIdx+1)),r=s.endIdx;return r<n.length&&i.push(n.slice(r)),i}function skt(t,e){const{width:n,height:o,pcbAnchorAlignment:i}=e;if(!i)return t;const r=i;if(typeof n!="number"||typeof o!="number")return t;const s=t.x,a=t.y;switch(r){case"top_left":return{x:s+n/2,y:a-o/2};case"top_center":return{x:s,y:a-o/2};case"top_right":return{x:s-n/2,y:a-o/2};case"center_left":return{x:s+n/2,y:a};case"center_right":return{x:s-n/2,y:a};case"bottom_left":return{x:s+n/2,y:a+o/2};case"bottom_center":return{x:s,y:a+o/2};case"bottom_right":return{x:s-n/2,y:a+o/2};default:return t}}var akt=(t,e)=>{const n=W7(t);return Math.hypot(n.x-e.x,n.y-e.y)},Akt=t=>{const e=t.root?.platform;return e!==void 0&&"allowLegacyAutorouters"in e&&e.allowLegacyAutorouters===!0},ckt=t=>{if(Akt(t))return null;const e=t._parsedProps.autorouter??t.getInheritedProperty("autorouter");return dRt(e)},lkt=t=>{if(Akt(t))return null;const e=ckt(t);if(e)return e;const n=t.selectAll("autoroutingphase").map(o=>o._parsedProps.autorouter);for(const o of n){const i=dRt(o);if(i)return i}return null},sRo=({db:t,route:e,routeThicknessMode:n,sourceTraceId:o})=>{if(!o||e.length<2)return e;const r=t.source_trace.get(o)?.connected_source_port_ids[0];if(!r)return e;const s=t.pcb_port.list().find(c=>c.source_port_id===r);if(!s)return e;const a=e[0],A=e[e.length-1];return akt(A,s)<akt(a,s)?B0e(e,n):e},A6=class extends g0{pcb_group_id=null;schematic_group_id=null;subcircuit_id=null;_hasStartedAsyncAutorouting=!1;_pcbPlacementDrcErrorCount=null;_pcbPlacementDrcCheckError=null;_pcbPlacementDrcChecksPending=!1;_standaloneSubcircuitDrcChecksComplete=!1;_standaloneSubcircuitDrcChecksInProgress=!1;_isInflatedFromCircuitJson=!1;_isolatedCircuitJson=null;get _isIsolatedSubcircuit(){return!!this.getInheritedProperty("_subcircuitCachingEnabled")}_normalComponentNameMap=null;getNormalComponentNameMap(){if(this._normalComponentNameMap)return this._normalComponentNameMap;const t=new Map,e=n=>{if(n._isNormalComponent&&n.name){const o=t.get(n.name);o?o.push(n):t.set(n.name,[n])}for(const o of n.children)o.isSubcircuit||e(o)};for(const n of this.children)n.isSubcircuit||e(n);return this._normalComponentNameMap=t,t}_asyncAutoroutingResult=null;get config(){return{zodProps:mwn,componentName:"Group"}}initPorts(t={}){const e=this._getSchematicPortArrangement();this._parsedProps?.showAsSchematicBox&&!this._parsedProps.pinLabels&&e&&rPe(e).some(o=>typeof o=="string")||super.initPorts(t)}_getSchematicPortArrangementFromPortDirections(){if(!this._parsedProps?.showAsSchematicBox)return null;const t={leftSide:[],rightSide:[],topSide:[],bottomSide:[]};for(const n of this.children){if(n.componentName!=="Port")continue;const o=n._parsedProps.direction;if(!o)continue;const i=n._parsedProps.pinNumber??n._parsedProps.name??void 0;if(i===void 0)continue;t[o==="left"?"leftSide":o==="right"?"rightSide":o==="up"?"topSide":"bottomSide"].push(i)}if(t.leftSide.length===0&&t.rightSide.length===0&&t.topSide.length===0&&t.bottomSide.length===0)return null;const e={};return t.leftSide.length>0&&(e.leftSide={pins:t.leftSide,direction:"top-to-bottom"}),t.rightSide.length>0&&(e.rightSide={pins:t.rightSide,direction:"top-to-bottom"}),t.topSide.length>0&&(e.topSide={pins:t.topSide,direction:"left-to-right"}),t.bottomSide.length>0&&(e.bottomSide={pins:t.bottomSide,direction:"left-to-right"}),e}_getSchematicPortArrangement(){return super._getSchematicPortArrangement()??this._getSchematicPortArrangementFromPortDirections()}_ensureSchematicBoxPortsFromConnections(){if(this._parsedProps?.showAsSchematicBox&&this._parsedProps?.connections)for(const[t,e]of Object.entries(this._parsedProps.connections)){if(this.children.find(r=>r.componentName==="Port"&&r.isMatchingAnyOf([t])))continue;const o=t.match(/^pin(\d+)$/i)??t.match(/^(\d+)$/),i=o?Number(o[1]):void 0;this.add(new Pu({name:t,pinNumber:i,connectsTo:e}))}}doInitialInitializePortsFromChildren(){super.doInitialInitializePortsFromChildren(),this._ensureSchematicBoxPortsFromConnections()}updateInitializePortsFromChildren(){super.updateInitializePortsFromChildren(),this._ensureSchematicBoxPortsFromConnections()}_getPrimaryPinCount(){const t=super._getPrimaryPinCount();if(!this._parsedProps?.showAsSchematicBox)return t;const e=this.children.filter(n=>n.componentName==="Port").map(n=>n._parsedProps.pinNumber).filter(n=>n!==void 0);return e.length===0?t:Math.max(t,...e)}_getPinLabelsFromPorts(){return this._parsedProps?.showAsSchematicBox?KMo(this):super._getPinLabelsFromPorts()}doInitialSourceGroupRender(){const{db:t}=this.root,e=typeof this._parsedProps.name=="string"&&this._parsedProps.name.length>0,n=t.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit,was_automatically_named:!e});this.source_group_id=n.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${n.source_group_id}`,t.source_group.update(n.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){const{db:t}=this.root;for(const n of this.getDescendants())n.getGroup()?.source_group_id===this.source_group_id&&t.source_component.update(n.source_component_id,{source_group_id:this.source_group_id});if(!this.isSubcircuit)return;const e=lkt(this);e&&t.source_property_ignored_warning.insert({source_component_id:this.source_component_id??"",property_name:"autorouter",subcircuit_id:this.subcircuit_id??void 0,error_type:"source_property_ignored_warning",message:`The "${e}" autorouter is deprecated, so autorouting has been disabled for this subcircuit. Use the default autorouter and introduce <autoroutingphase /> or <fanout /> elements as needed.`})}doInitialSourceParentAttachment(){const{db:t}=this.root,e=this.parent?.getGroup?.();if(e?.source_group_id&&t.source_group.update(this.source_group_id,{parent_source_group_id:e.source_group_id}),!this.isSubcircuit||U0e(this.parent))return;const n=this.parent?.getSubcircuit?.()?.subcircuit_id;n&&t.source_group.update(this.source_group_id,{parent_subcircuit_id:n})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=e,o=n.outline&&n.outline.length>0,i=o?n.outline.map(c=>({x:lt.parse(c.x),y:lt.parse(c.y)})):void 0,r=this.props,s=this._getGlobalPcbPositionBeforeLayout(),a=skt(s,r),A=t.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,anchor_position:s,center:a,...o?{outline:i}:{width:0,height:0},pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:e.autorouter?{trace_clearance:e.autorouter.traceClearance}:void 0,anchor_alignment:e.pcbAnchorAlignment??null});this.pcb_group_id=A.pcb_group_id;for(const c of this.children)t.pcb_component.update(c.pcb_component_id,{pcb_group_id:A.pcb_group_id})}doInitialPcbPrimitiveRender(){this.calculatePcbGroupBounds()}calculatePcbGroupBounds(t){if(!this.pcb_group_id||this.root?.pcbDisabled)return;const{db:e}=this.root,n=this._parsedProps,o=n.outline&&n.outline.length>0,i=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0;if(o){const m=n.outline.map(y=>({x:lt.parse(y.x),y:lt.parse(y.y)})),_=Oh(m);if(!_)return;const f=(_.minX+_.maxX)/2,I=(_.minY+_.maxY)/2,C=i?e.pcb_group.get(this.pcb_group_id)?.center??{x:f,y:I}:{x:f,y:I};e.pcb_group.update(this.pcb_group_id,{center:C});return}let r=t;if(!r){const m=L0e(this.children);r={center:{x:(m.minX+m.maxX)/2,y:(m.minY+m.maxY)/2},width:m.width,height:m.height}}let{width:s,height:a}=r,{x:A,y:c}=r.center;if(this.isSubcircuit||this.isRoutingDirective){const{padLeft:m,padRight:_,padTop:f,padBottom:I}=this._resolvePcbPadding();s+=m+_,a+=f+I,A+=(_-m)/2,c+=(f-I)/2}const l=Number(n.width??s),u=Number(n.height??a),h=e.pcb_group.get(this.pcb_group_id)?.center??{x:A,y:c},d=this.isSubcircuit||t!==void 0;let p=i?d?{x:n.width===void 0?A:h.x,y:n.height===void 0?c:h.y}:h:{x:A,y:c};if(i&&n.pcbAnchorAlignment){const m=this._getGlobalPcbPositionBeforeLayout(),_=skt(m,{...this.props,width:l,height:u});(Math.abs(_.x-p.x)>1e-6||Math.abs(_.y-p.y)>1e-6)&&this._repositionOnPcb(_),p=_}e.pcb_group.update(this.pcb_group_id,{width:l,height:u,center:p})}updatePcbPrimitiveRender(){this.calculatePcbGroupBounds()}unnamedElementCounter={};getNextAvailableName(t){return this.unnamedElementCounter[t.lowercaseComponentName]??=1,`unnamed_${t.lowercaseComponentName}${this.unnamedElementCounter[t.lowercaseComponentName]++}`}_resolvePcbPadding(){const t=this._parsedProps,e=t.pcbLayout,n=l=>{const u=e?.[l],g=t[l];if(typeof u=="number")return u;if(typeof g=="number")return g},o=n("padding")??0,i=n("paddingX"),r=n("paddingY"),s=n("paddingLeft")??i??o,a=n("paddingRight")??i??o,A=n("paddingTop")??r??o,c=n("paddingBottom")??r??o;return{padLeft:s,padRight:a,padTop:A,padBottom:c}}doInitialCreateTraceHintsFromProps(){const{_parsedProps:t}=this,{db:e}=this.root,n=t;if(!this.isSubcircuit)return;const o=n.manualEdits?.manual_trace_hints;if(o)for(const i of o)this.add(new qRt({for:i.pcb_port_selector,offsets:i.offsets}))}doInitialSourceAddConnectivityMapKey(){mNo(this),hMo(this)}_areChildSubcircuitsRouted(){const t=this._findDirectChildSubcircuits();for(const e of t)if(!e._isInflatedFromCircuitJson&&e._hasTracesToRoute()&&e._shouldRouteAsync()&&!e._asyncAutoroutingResult)return!1;return!0}_findDirectChildSubcircuits(){const t=[],e=n=>{for(const o of n)o.isSubcircuit&&o!==this?t.push(o):e(o.children)};return e(this.children),t}_shouldRouteAsync(){if(this._isLegacyAutorouterDisabled())return!1;const t=this._getAutorouterConfig();return t.groupMode==="sequential-trace"?!1:!!(t.local&&t.groupMode==="subcircuit"||!t.local)}_getRoutingPhasePlans(){return QNo(this)}_hasTracesToRoute(){const t=vc("tscircuit:core:_hasTracesToRoute"),e=this._getRoutingPhasePlans();let n=0,o=!1;for(const i of e){n+=i.traces.length;const r=i.autorouter?h$(i.autorouter,this.root?.platform):void 0;o||=!!(i.reroute&&(i.region||r?.preset==="simplify"))}if(t(`[${this.getString()}] has ${n} traces to route`),n>0)return!0;if(o){const i=DMe(this).length;return t(`[${this.getString()}] has ${i} existing pcb traces available for reroute`),i>0}return!1}async _runEffectMakeHttpAutoroutingRequest(){const{db:t}=this.root,e=vc("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),n=this._parsedProps,o=this._getAutorouterConfig(),i=o.serverUrl,r=o.serverMode,s=(c,l)=>(e("fetching",c),l.headers&&(l.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(c,l)),a=this.root.db.toArray().filter(c=>c.type.startsWith("source_")||c.type.startsWith("pcb_"));if(r==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){const l=n.defaultTraceWidth??n.nominalTraceWidth,{simpleRouteJson:u}=fMe({db:t,minTraceWidth:Number(n.minTraceWidth??.15),nominalTraceWidth:l!=null?Number(l):void 0,subcircuit_id:this.subcircuit_id,subcircuitComponent:this});u.allowViaInPad=o.allowViaInPad;const{autorouting_result:g}=await s(`${i}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:u,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());this._asyncAutoroutingResult=g,this._markDirty("PcbTraceRender");return}const{autorouting_result:c}=await s(`${i}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:a,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(l=>l.json());this._asyncAutoroutingResult=c,this._markDirty("PcbTraceRender");return}const{autorouting_job:A}=await s(`${i}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:a,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:o.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(c=>c.json());for(;;){const{autorouting_job:c}=await s(`${i}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:A.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(l=>l.json());if(c.is_finished){const{autorouting_job_output:l}=await s(`${i}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:A.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(u=>u.json());this._asyncAutoroutingResult={output_pcb_traces:l.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(c.has_error){const l=new Oj(`Autorouting job failed: ${JSON.stringify(c.error)}`);throw t.pcb_autorouting_error.insert({pcb_error_id:A.autorouting_job_id,error_type:"pcb_autorouting_error",message:l.message}),l}await new Promise(l=>setTimeout(l,100))}}async _runLocalAutorouting(){const{db:t}=this.root,e=this._parsedProps,n=vc("tscircuit:core:_runLocalAutorouting");n(`[${this.getString()}] starting local autorouting`);const o=this._getAutorouterConfig(),i=this._isLaserPrefabAutorouter(o),r=this._isAutoJumperAutorouter(o),s=this._getSubcircuitLayerCount()===1,a=Number(e.minTraceWidth??.15),A=Number(e.defaultTraceWidth??e.nominalTraceWidth??a),c=this._getRoutingPhasePlans(),l=NNo(c),u=c.length>1,g=new Map(c.map((k,R)=>[k,R]));if(u)for(const k of t.pcb_debug_object.list())k.subcircuit_id===this.subcircuit_id&&(k.label?.startsWith("Autorouting phase: ")||/^autorouting phase \d+(?: |$)/.test(k.label??""))&&t.pcb_debug_object.delete(k.pcb_debug_object_id);const h=(k,R)=>{if(!u)return;const F=g.get(k);if(F===void 0)return;const O=k.phaseName?.trim();t.pcb_debug_object.insert({shape:"rect",center:{x:(R.minX+R.maxX)/2,y:(R.minY+R.maxY)/2},size:{width:R.maxX-R.minX,height:R.maxY-R.minY},label:`autorouting phase ${F}${O?` ${O}`:""}`,subcircuit_id:this.subcircuit_id??void 0})},d=c.flatMap(k=>{const R=k.autorouter?h$(k.autorouter,this.root?.platform):o,F=k.getPrecomputedRoutingResult?{...R,allowViaInPad:(typeof k.autorouter=="object"?k.autorouter.allowViaInPad:void 0)??o.allowViaInPad}:R,O=RPo(F,this.root?.platform);return O.map((U,Y)=>({...U,routingPhasePlan:k,phaseStageIndex:Y,phaseStageCount:O.length}))}),m=d.some(({autorouterConfig:k})=>["fanout","single_layer_fanout"].includes(k.preset??""))?fNo(this,c):void 0;let{simpleRouteJson:_}=fMe({db:t,minTraceWidth:a,nominalTraceWidth:A,subcircuit_id:this.subcircuit_id,subcircuitComponent:this,fanoutPourNetMap:m});const f=k=>{const R=k.fanoutRegionPcbGroupId;if(!R)return;const F=t.pcb_group.get(R),O=t.pcb_component.list().find(W=>W.pcb_group_id===R)?.source_component_id;if(!O)return;const U=`${F?.name??"Breakout"} defines conflicting fanout bounds with explicit breakout geometry and fanoutBoundaryPadding. Explicit breakout geometry takes precedence, so fanoutBoundaryPadding is ignored.`;t.source_property_ignored_warning.list().some(W=>W.source_component_id===O&&W.property_name==="fanoutBoundaryPadding"&&W.message===U)||t.source_property_ignored_warning.insert({source_component_id:O,property_name:"fanoutBoundaryPadding",message:U,error_type:"source_property_ignored_warning",subcircuit_id:F?.subcircuit_id})},I=new Map;for(const k of d){const R=k.autorouterConfig.preset;(R==="fanout"||R==="single_layer_fanout")&&!I.has(k.routingPhasePlan)&&I.set(k.routingPhasePlan,k.autorouterConfig)}const C=[];for(const[k,R]of I){const F=k.fanoutRegionPcbGroupId;if(!F)continue;let O=Lue(_,k);if(O.connections.length===0)continue;O=nkt(O,k.drcTolerances);const U=t.pcb_breakout_point.list().filter(ie=>ie.pcb_group_id===F).map(ie=>({x:ie.x,y:ie.y})),Y=R.preset,W=aMe.resolveFanoutBounds(O,{mode:Y,busFanoutDirections:k.busFanoutDirections,fanoutBounds:k.fanoutBounds,fanoutBoundaryPadding:k.fanoutBoundaryPadding,fanoutRoutingLayers:k.fanoutRoutingLayers,allowBlindAndBuriedVias:O.allowBlindAndBuriedVias,breakoutPoints:U,onFanoutBoundsConflict:()=>f(k)});if(k.fanoutBounds=W,!W)continue;const te=t.pcb_group.get(F),j=Math.max(O.minTraceWidth,...O.connections.map(ie=>ie.nominalTraceWidth??ie.width??O.minTraceWidth)),J=O.minViaPadDiameter??O.min_via_pad_diameter??O.minViaDiameter,oe=O.minTraceToPadEdgeClearance??O.defaultObstacleMargin??j;C.push({regionId:F,name:te?.name??k.phaseName??F,bounds:W,boundaryKeepaway:gRt({traceWidth:j,traceToPadClearance:oe,viaPadDiameter:J})/2})}const y=UNo(C);if(y){const{firstRegion:k,secondRegion:R,availableGap:F,requiredGap:O}=y,U=F<0?`overlap by ${Math.abs(F).toFixed(3)}mm`:`are only ${F.toFixed(3)}mm apart`,Y=`Fanout regions "${k.name}" and "${R.name}" ${U}, but at least ${O.toFixed(3)}mm of separation is required for a via-safe routing channel. Move the components farther apart or reduce their facing fanout padding.`;throw t.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:Y}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:Y},simpleRouteJson:_}),new Error(Y)}for(const{regionId:k,bounds:R}of C)t.pcb_group.update(k,{center:{x:(R.minX+R.maxX)/2,y:(R.minY+R.maxY)/2},width:R.maxX-R.minX,height:R.maxY-R.minY});const x=[],E=[],B=new Set,S=iRo(this),Q=(k,R)=>{const F=k.connection_name??k.pcb_trace_id,O=new Set([F,k.pcb_trace_id,...NMe(F),...NMe(k.pcb_trace_id)]);return _.connections.some(U=>tkt(U,R)?O.has(U.name)||(U.source_trace_id?O.has(U.source_trace_id):!1)||(U.rootConnectionName?O.has(U.rootConnectionName):!1)||U.mergedConnectionNames?.some(Y=>O.has(Y)):!1)},w=new Set;let M;for(const[k,{routingPhasePlan:R,autorouterConfig:F,strategy:O,usesPreviousStageOutput:U,phaseStageIndex:Y,phaseStageCount:W}]of d.entries()){if(U||(M=void 0),U&&M===void 0)throw new Error("Autorouting follow-up stage is missing the preceding stage output");let te=M??_;const j=!!(R.reroute&&F.preset==="simplify"),J=!!(R.reroute&&R.region&&!j),oe=!!(R.reroute&&!j&&!R.region&&R.traces.length>0),ie=J||oe||j,ne=J?{..._,traces:[...S,...x]}:null;if(!U&&j)te={...Lue(_,R),traces:kO({accumulatedPcbTraces:S,stageOutputPcbTraces:x})};else if(!U&&J&&ne)te=Iho(ne,{...R.region});else if(!U&&oe){const Le=Lue(_,R);te={...Le,traces:[...Le.traces??[],...x.filter(Ye=>!Q(Ye,R))]}}else if(!U&&l){const Le=Lue(_,R),Ye=R.routingPcbGroupId;if(Ye){const At=fMe({db:t,minTraceWidth:a,nominalTraceWidth:A,subcircuit_id:this.subcircuit_id,subcircuitComponent:this,routingPcbGroupId:Ye,fanoutPourNetMap:m}).simpleRouteJson.obstacles.filter(nt=>nt.isCopperPour),at=Le.obstacles.filter(nt=>!nt.isCopperPour);Le.obstacles=at.concat(At)}te={...Le,traces:kO({accumulatedPcbTraces:Le.traces??[],stageOutputPcbTraces:x})}}te=U8o(te,w),te=nkt(te,R.drcTolerances),te.allowViaInPad=F.allowViaInPad;const le=U?void 0:R.getPrecomputedRoutingResult,ge=!!(j&&te.traces?.length===0);if((l||ie||U)&&(te.connections.length===0&&!j&&!le||ge)){Y===0&&h(R,te.bounds),M=te;continue}const _e=R.autorouter!==void 0?this._isAutoJumperAutorouter(F):r,ue=R.autorouter!==void 0?this._isLaserPrefabAutorouter(F):i;_e&&(te.allowJumpers=!0,F.availableJumperTypes&&(te.availableJumperTypes=F.availableJumperTypes));const fe=F.preset;if((fe==="fanout"||fe==="single_layer_fanout")&&!R.fanoutRegionPcbGroupId&&!le&&(R.fanoutBounds=aMe.resolveFanoutBounds(te,{mode:fe,busFanoutDirections:R.busFanoutDirections,fanoutBounds:R.fanoutBounds,fanoutBoundaryPadding:R.fanoutBoundaryPadding,fanoutRoutingLayers:R.fanoutRoutingLayers,allowBlindAndBuriedVias:te.allowBlindAndBuriedVias})),Y===0&&h(R,R.fanoutBounds??te.bounds),n.enabled&&global.debugOutputArray?.push({name:`simpleroutejson-${this.props.name}.json`,obj:te}),n.enabled){const Le=mx(te);Le.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(Le)}const pe=F.autorouterVersion??this.props.autorouterVersion,ye=this.props.autorouterEffortLevel,Me=ye?Number.parseInt(ye.replace("x",""),10):void 0,ve={capacityDepth:F.capacityDepth,targetMinCapacity:F.targetMinCapacity,platformConfig:this.root?.platform,useAssignableSolver:ue||s,useAutoJumperSolver:_e,useLaserPrefabSolver:ue,autorouterVersion:pe,effort:Me},he=le?"precomputed":F.algorithmFn?"custom":O.name,Qe=le||F.algorithmFn?void 0:O.getSolverName(ve),Pe={autorouterName:he,solverName:Qe,capacityDepth:ve.capacityDepth,targetMinCapacity:ve.targetMinCapacity,useAssignableSolver:ve.useAssignableSolver,useAutoJumperSolver:ve.useAutoJumperSolver,useLaserPrefabSolver:ve.useLaserPrefabSolver,useTraceSimplificationSolver:F.preset==="simplify",autorouterVersion:ve.autorouterVersion,effort:ve.effort},we=le||F.algorithmFn||!O.cacheable?void 0:this.root?.platform?.localCacheEngine,Te=we?vNo(te,Pe):void 0,Re=Te?await wNo({cacheEngine:we,cacheKey:Te}):null,Ee=le?"precomputed":F.algorithmFn?"custom_algorithm":O.cacheable?we?void 0:"no_cache_engine":"strategy_not_cacheable",ke={routingPhaseIndex:k,phaseOrdinal:k+1,phaseCount:d.length,connectionCount:te.connections.length,obstacleCount:te.obstacles.length,previousTraceCount:te.traces?.length??0,isReroutePhase:ie,autorouterName:he,autorouterVersion:pe,solverName:Qe,effort:Me,cacheStatus:we?Re?"hit":"miss":"disabled",cacheKey:Te,cacheDisabledReason:Ee};this.root?.emit("autorouting:start",{type:"autorouting:start",subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...R.phaseName!==void 0?{phaseName:R.phaseName,phaseStageIndex:Y,phaseStageCount:W}:{},...ke,simpleRouteJson:te});let Ce;try{let Le,Ye;if(le){const bt=le(te);Le=bt.traces,Ye=bt.outputSimpleRouteJson;for(const Ct of Le)w.add(Ct.pcb_trace_id)}else if(Re)n(`[${this.getString()}] using cached local autorouting result`),Le=Re.traces;else{if(F.algorithmFn?Ce=await F.algorithmFn(te):Ce=O.create({simpleRouteJson:te,commonAutorouterOptions:ve,busFanoutDirections:R.busFanoutDirections,fanoutBounds:R.fanoutBounds,fanoutRoutingLayers:R.fanoutRoutingLayers,allowBlindAndBuriedVias:te.allowBlindAndBuriedVias,componentNamesById:pwo(t),onSolverStarted:({solverName:Dt,solverParams:kt,solverConstructorArgs:it})=>this.root?.emit("solver:started",{type:"solver:started",solverName:Dt,solverParams:kt,solverConstructorArgs:it,componentName:this.getString()})}),!Ce)throw new Error("Failed to create local autorouter");const bt=Ce,Ct=new Promise((Dt,kt)=>{bt.on("complete",it=>{n(`[${this.getString()}] local autorouting complete`),Dt(it.traces)}),bt.on("error",it=>{n(`[${this.getString()}] local autorouting error: ${it.error.message}`),kt(it.error)})});bt.on("progress",Dt=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...R.phaseName!==void 0?{phaseName:R.phaseName,phaseStageIndex:Y,phaseStageCount:W}:{},...ke,...Dt,type:"autorouting:progress"})}),bt.start(),Le=await Ct}let tt=Ye??Ce?.getOutputSimpleRouteJson?.();if(tt&&!U&&["fanout","single_layer_fanout"].includes(F.preset??"")&&R.routingPcbGroupId){const bt=LNo({fanoutInputSimpleRouteJson:te,fanoutOutputSimpleRouteJson:tt,baseSimpleRouteJson:_,routingPhasePlan:R});_=bt.baseSimpleRouteJson,tt=bt.downstreamSimpleRouteJson;for(const Ct of bt.synchronizedBreakoutPoints){const Dt=t.pcb_breakout_point.list().find(kt=>kt.pcb_group_id===Ct.routingPcbGroupId&&kt.source_trace_id===Ct.sourceTraceId&&Math.abs(kt.x-Ct.previousPoint.x)<=1e-6&&Math.abs(kt.y-Ct.previousPoint.y)<=1e-6);Dt&&t.pcb_breakout_point.update(Dt.pcb_breakout_point_id,{x:Ct.fanoutExitPoint.x,y:Ct.fanoutExitPoint.y})}}let At=Le;tt?.traces?At=tt.traces:U&&(At=kO({accumulatedPcbTraces:te.traces??[],stageOutputPcbTraces:Le}));let at=At;!tt&&!U&&R.routingPhaseIndex!==null&&(at=kO({accumulatedPcbTraces:te.traces??[],stageOutputPcbTraces:Le}));const nt={...tt??te,traces:at};if(M=tt?nt:void 0,!Re&&Te&&await PNo({cacheEngine:we,cacheKey:Te,result:{...te,traces:Le}}),this.root?.emit("autorouting:end",{type:"autorouting:end",subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...R.phaseName!==void 0?{phaseName:R.phaseName,phaseStageIndex:Y,phaseStageCount:W}:{},...ke,simpleRouteJson:nt}),Ce?.getConnectedOffboardObstacles){const bt=Ce.getConnectedOffboardObstacles();hwo({db:t,connectedOffboardObstacles:bt,simpleRouteJson:te,subcircuit_id:this.subcircuit_id})}const gt=Ce?.solver;if(gt?.getOutputJumpers&&E.push(...gt.getOutputJumpers()||[]),J&&ne){for(const Ct of ne.traces??[])Ct.type==="pcb_trace"&&B.add(Ct.pcb_trace_id);const bt=Cho(ne,{...te,traces:[...te.traces??[],...Le]});x.splice(0,x.length,...bt.traces??[])}else if(oe){const bt=x.filter(Ct=>!Q(Ct,R));x.splice(0,x.length,...kO({accumulatedPcbTraces:bt,stageOutputPcbTraces:At}))}else{if(j)for(const bt of S)B.add(bt.pcb_trace_id);x.splice(0,x.length,...kO({accumulatedPcbTraces:x,stageOutputPcbTraces:At}))}}catch(Le){const{db:Ye}=this.root;throw Ye.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:Le instanceof Error?Le.message:String(Le)}),this.root?.emit("autorouting:error",{type:"autorouting:error",subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...R.phaseName!==void 0?{phaseName:R.phaseName,phaseStageIndex:Y,phaseStageCount:W}:{},...ke,error:{message:Le instanceof Error?Le.message:String(Le)},simpleRouteJson:te}),Le}finally{Ce?.stop()}}this._asyncAutoroutingResult={output_pcb_traces:x,output_jumpers:E,pcb_trace_ids_to_be_replaced:[...B]},this._markDirty("PcbTraceRender")}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){const t=vc("tscircuit:core:doInitialPcbTraceRender");if(!this.isSubcircuit||this.root?.pcbDisabled||this.root?.pcbRoutingDisabled||this.getInheritedProperty("routingDisabled")||this._isInflatedFromCircuitJson||this._isLegacyAutorouterDisabled()||this._shouldUseTraceByTraceRouting())return;if(!this._areChildSubcircuitsRouted()){t(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}if(t(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),!this._hasTracesToRoute())return;const e=jwe({component:this,subcircuit:this}),n=$we({component:this,subcircuit:this});e||n||this._startAsyncAutorouting()}doInitialSchematicTraceRender(){this._parsedProps.showAsSchematicBox||JDo(this)}doInitialSchematicSheetRender(){pTt(this)}updateSchematicSheetRender(){hDo(this)}updatePcbTraceRender(){const t=vc("tscircuit:core:updatePcbTraceRender");if(t(`[${this.getString()}] updating...`),!this.isSubcircuit||this._isInflatedFromCircuitJson||this._isLegacyAutorouterDisabled())return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){if(this._areChildSubcircuitsRouted()){const n=jwe({component:this,subcircuit:this}),o=$we({component:this,subcircuit:this});if(n||o)return;t(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting()}return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;const{db:e}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){t(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){t(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){const{db:t}=this.root,{traces:e}=this._asyncAutoroutingResult.output_simple_route_json;if(e)for(const n of e){const o=n.route.map(r=>r.route_type!=="through_obstacle"?r:{route_type:"through_pad",start:r.start,end:r.end,start_layer:r.from_layer,end_layer:r.to_layer,width:r.width,circuitJsonMetadata:r.circuitJsonMetadata}),i=t.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:Wwe(o)});ikt({db:t,pcbTrace:i,routeWithSrjMetadata:o})}}_updatePcbTraceRenderFromPcbTraces(){const{output_pcb_traces:t,output_jumpers:e,pcb_trace_ids_to_be_replaced:n}=this._asyncAutoroutingResult;if(!t)return;const{db:o}=this.root,i=this.getInheritedMergedProperty("pcbStyle"),{holeDiameter:r,padDiameter:s}=$N(i),a=this._getBoard(),A=a?.pcb_board_id?o.pcb_board.get(a.pcb_board_id):o.pcb_board.list()[0],c=A?.min_via_hole_diameter??r,l=A?.min_via_pad_diameter??s;e&&e.length>0&&eRo({db:o,output_jumpers:e,subcircuit_id:this.subcircuit_id}),oRo({group:this,outputPcbTraces:t,pcbTraceIdsToReplace:n});const u=o.pcb_via.list();for(const g of t){if(g.type!=="pcb_trace")continue;g.subcircuit_id??=this.subcircuit_id;let h=g.route.map(_=>_.route_type!=="through_obstacle"?_:{route_type:"through_pad",start:_.start,end:_.end,start_layer:_.from_layer,end_layer:_.to_layer,width:_.width,circuitJsonMetadata:_.circuitJsonMetadata});const d=MMe({db:o,trace:{...g,route:h},subcircuit_id:this.subcircuit_id});h=sRo({db:o,route:h,routeThicknessMode:g.route_thickness_mode,sourceTraceId:d}),g.route=h;let p=rRo(h);p===null&&(p=[h]);const m=YNo(p,o);for(const _ of m)if(_.length>0){const f=Wwe(_),I=MMe({db:o,trace:{...g,route:f},subcircuit_id:this.subcircuit_id}),C=o.pcb_trace.insert({...g,source_trace_id:I,route:f});ikt({db:o,pcbTrace:C,routeWithSrjMetadata:_})}}for(const g of t)if(g.type!=="pcb_via"&&g.type==="pcb_trace"){const h=MMe({db:o,trace:g,subcircuit_id:this.subcircuit_id}),{connection_name:d}=g;let p;if(h&&(p=o.source_trace.get(h)?.subcircuit_connectivity_map_key),!p&&d){const m=o.source_net.get(d);m&&(p=m.subcircuit_connectivity_map_key)}for(const m of g.route)if(m.route_type==="via"){const _=m,f=m.from_layer,I=m.to_layer,C={pcb_trace_id:g.pcb_trace_id,x:m.x,y:m.y,hole_diameter:_.via_hole_diameter??_.hole_diameter??c,outer_diameter:_.via_diameter??_.outer_diameter??l,layers:hMt({fromLayer:f,toLayer:I,layerCount:this._getSubcircuitLayerCount(),allowBlindAndBuriedVias:A?.allow_blind_and_buried_vias??!1,physicalLayers:_.layers}),from_layer:f,to_layer:I,subcircuit_id:this.subcircuit_id,pcb_group_id:this.pcb_group_id??void 0,subcircuit_connectivity_map_key:p};if(u.some(y=>dwo(y,C)))continue;u.push(o.pcb_via.insert(C))}}}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=t.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id,show_as_schematic_box:e.showAsSchematicBox??!1});this.schematic_group_id=n.schematic_group_id,e.showAsSchematicBox&&VMo(this);for(const o of this.getDescendants())o.getGroup()?.source_group_id===this.source_group_id&&(o._parsedProps?.showAsSchematicBox||o.schematic_component_id&&t.schematic_component.update(o.schematic_component_id,{schematic_group_id:n.schematic_group_id}))}_getSchematicLayoutMode(){const t=this._parsedProps,e=t.schAutoLayoutEnabled??!1;if(t.schLayout?.layoutMode==="none"||t.schLayout?.layoutMode==="relative")return"relative";if(t.schLayout?.matchAdapt)return"match-adapt";if(t.schLayout?.flex)return"flex";if(t.schLayout?.grid)return"grid";if(t.schMatchAdapt)return"match-adapt";if(t.schFlex)return"flex";if(t.schGrid)return"grid";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";if(t.relative||t.schRelative)return"relative";const n=this.children.some(i=>{const r=i._parsedProps;return(i.source_component_id!==null||i.source_group_id!==null)&&(r?.schX!==void 0||r?.schY!==void 0)}),o=(t.manualEdits?.schematic_placements?.length??0)>0;return e&&!o||!n&&!o?"match-adapt":"relative"}doInitialSchematicLayout(){if(this._parsedProps.showAsSchematicBox){this._insertSchematicBorder();return}if(this.children.some(o=>o.source_component_id!==null&&o._parsedProps?.schSectionName!==void 0)){this._doInitialSchematicLayoutSections(),this._insertSchematicBorder();return}const n=this._getSchematicLayoutMode();n==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),n==="grid"&&this._doInitialSchematicLayoutGrid(),n==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutSections(){gDo(this)}_doInitialSchematicLayoutMatchAdapt(){WMo(this)}_doInitialSchematicLayoutMatchpack(){cDo(this)}_doInitialSchematicLayoutGrid(){JMo(this)}_doInitialSchematicLayoutFlex(){zMo(this)}_getPcbLayoutMode(){const t=this._parsedProps,e=this.props;if(this._isInflatedFromCircuitJson||t.pcbRelative)return"none";if(t.pcbLayout?.matchAdapt)return"match-adapt";if(t.pcbLayout?.flex)return"flex";if(t.pcbLayout?.grid)return"grid";if(t.pcbLayout?.pack)return"pack";if(t.pcbFlex)return"flex";if(t.pcbGrid)return"grid";if(t.pcbPack||t.pack)return"pack";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";t.pcbX!==void 0||t.pcbY!==void 0||t.pcbLeftEdgeX!==void 0||t.pcbRightEdgeX!==void 0||t.pcbTopEdgeY!==void 0||t.pcbBottomEdgeY!==void 0||e.pcbLeftEdgeX!==void 0||e.pcbRightEdgeX!==void 0||e.pcbTopEdgeY!==void 0||e.pcbBottomEdgeY;const n=(t.manualEdits?.pcb_placements?.length??0)>0,o=this.children.reduce((i,r)=>{if(!r.pcb_component_id&&!r.pcb_group_id)return i;const s=r._parsedProps,a=r.props,A=s?.pcbX!==void 0||s?.pcbY!==void 0||s?.pcbLeftEdgeX!==void 0||s?.pcbRightEdgeX!==void 0||s?.pcbTopEdgeY!==void 0||s?.pcbBottomEdgeY!==void 0||a?.pcbLeftEdgeX!==void 0||a?.pcbRightEdgeX!==void 0||a?.pcbTopEdgeY!==void 0||a?.pcbBottomEdgeY!==void 0;return i+(A?0:1)},0);return!n&&o>1?"pack":"none"}doInitialPcbLayout(){if(this.root?.pcbDisabled)return;if(this.pcb_group_id){const{db:e}=this.root,n=this._parsedProps;if(n.pcbX!==void 0||n.pcbY!==void 0){const i=this.parent?.getGroup?.(),r=i?.pcb_group_id?e.pcb_group.get(i.pcb_group_id)?.pcb_group_id:void 0,s=r?void 0:this._getBoard()?.pcb_board_id??void 0;e.pcb_group.update(this.pcb_group_id,{position_mode:"relative_to_group_anchor",positioned_relative_to_pcb_group_id:r,positioned_relative_to_pcb_board_id:s,display_offset_x:n.pcbX,display_offset_y:n.pcbY})}}const t=this._getPcbLayoutMode();t==="grid"?this._doInitialPcbLayoutGrid():t==="pack"?this._doInitialPcbLayoutPack():t==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){bMo(this)}_doInitialPcbLayoutPack(){GMo(this)}_doInitialPcbLayoutFlex(){BMo(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;const{db:t}=this.root,e=this._parsedProps;if(!e.border)return;let n=typeof e.schWidth=="number"?e.schWidth:void 0,o=typeof e.schHeight=="number"?e.schHeight:void 0;const i=typeof e.schPadding=="number"?e.schPadding:0,r=typeof e.schPaddingLeft=="number"?e.schPaddingLeft:i,s=typeof e.schPaddingRight=="number"?e.schPaddingRight:i,a=typeof e.schPaddingTop=="number"?e.schPaddingTop:i,A=typeof e.schPaddingBottom=="number"?e.schPaddingBottom:i,c=this.schematic_group_id?t.schematic_group.get(this.schematic_group_id):null;if(c&&(n===void 0&&typeof c.width=="number"&&(n=c.width),o===void 0&&typeof c.height=="number"&&(o=c.height)),n===void 0||o===void 0)return;const l=c?.center??this._getGlobalSchematicPositionBeforeLayout(),u=l.x-n/2-r,g=l.y-o/2-A,h=n+r+s,d=o+a+A;t.schematic_box.insert({width:h,height:d,x:u,y:g,is_dashed:e.border?.dashed??!1})}_determineSideFromPosition(t,e){if(!t.center||!e.center)return"left";const n=t.center.x-e.center.x,o=t.center.y-e.center.y;return Math.abs(n)>Math.abs(o)?n>0?"right":"left":o>0?"bottom":"top"}_calculateSchematicBounds(t){if(t.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let e=1/0,n=-1/0,o=1/0,i=-1/0;for(const s of t)e=Math.min(e,s.centerX),n=Math.max(n,s.centerX),o=Math.min(o,s.centerY),i=Math.max(i,s.centerY);const r=2;return{minX:e-r,maxX:n+r,minY:o-r,maxY:i+r}}_getAutorouterConfig(){const t=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return h$(t,this.root?.platform)}_isLegacyAutorouterDisabled(){return lkt(this)!==null}_isLaserPrefabAutorouter(t=this._getAutorouterConfig()){const e=this.props.autorouter,n=o=>o?.replace(/-/g,"_")??o;return t.preset==="laser_prefab"?!0:typeof e=="string"?n(e)==="laser_prefab":typeof e=="object"&&e?n(e.preset)==="laser_prefab":!1}_isAutoJumperAutorouter(t=this._getAutorouterConfig()){const e=this.props.autorouter,n=o=>o?.replace(/-/g,"_")??o;return t.preset==="auto_jumper"?!0:typeof e=="string"?n(e)==="auto_jumper":typeof e=="object"&&e?n(e.preset)==="auto_jumper":!1}_getSubcircuitLayerCount(){const t=this.getInheritedProperty("layers");return typeof t=="number"?t:2}_shouldUseTraceByTraceRouting(){return ckt(this)?!1:this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this._isLegacyAutorouterDisabled()||this.root?.pcbRoutingDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:t}=this.root;if(this.isSubcircuit){const e=new Map;for(const n of this.children)if(!n.isSubcircuit&&n._parsedProps.name){const o=e.get(n._parsedProps.name)||[];o.push(n),e.set(n._parsedProps.name,o)}for(const[n,o]of e.entries()){if(o.length<=1)continue;const i=o.filter(A=>A instanceof t1),r=i.length===o.length,s=i.map(A=>A.subcircuit_connectivity_map_key),a=r&&s.every(Boolean)&&new Set(s).size===1;if(!r||!a){const A=this.name||"unnamed",c=r?`Trace "${n}" in subcircuit "${A}" shares a name with another trace, but the traces are not mutually connected. Same-named traces must have the same subcircuit connectivity map key.`:`Multiple immediate children found with name "${n}" in subcircuit "${A}". Names must be unique.`;t.pcb_trace_error.insert({error_type:"pcb_trace_error",message:c,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:o.map(l=>l.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}}_No(this)}doInitialSchematicLabelNetsWithConflictingNames(){this.root?.schematicDisabled||this.getTopLevelRenderable()===this&&K8o(this.root.db)}updateSchematicLabelNetsWithConflictingNames(){this.doInitialSchematicLabelNetsWithConflictingNames()}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;const{db:t}=this.root,e=t;for(const n of e.schematic_net_label.list()){const o=e.source_net.get(n.source_net_id),i=n.text||o?.name||"",r=o?.is_ground||Q0e.test(i),s=o?.is_power||Hwe.test(i);if(n.anchor_side==="top"&&r){e.schematic_net_label.update(n.schematic_net_label_id,{symbol_name:"rail_down"});continue}n.anchor_side==="bottom"&&s&&e.schematic_net_label.update(n.schematic_net_label_id,{symbol_name:"rail_up"})}}doInitialSimulationSpiceEngineRender(){pNo(this)}doInitialPcbComponentAnchorAlignment(){EMo(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}doInitialPcbCalcPlacementResolution(){mMo(this)}updatePcbCalcPlacementResolution(){this.doInitialPcbCalcPlacementResolution()}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(t){return super._repositionOnPcb(t)}};function aRo(t,e){const{injectionDb:n,subcircuit:o,groupsMap:i}=e,r=n.pcb_group.getWhere({source_group_id:t.source_group_id}),s={name:t.name??`inflated_group_${t.source_group_id}`};if(r?.position_mode==="relative_to_group_anchor"&&r.anchor_position){let A={x:0,y:0};if(t.parent_source_group_id){const c=n.pcb_group.getWhere({source_group_id:t.parent_source_group_id});c?.anchor_position&&(A=c.anchor_position)}s.pcbX=r.anchor_position.x-A.x,s.pcbY=r.anchor_position.y-A.y}r?.anchor_alignment&&(s.pcbAnchorAlignment=r.anchor_alignment);const a=new A6(s);return a._isInflatedFromCircuitJson=!0,a.source_group_id=t.source_group_id,i&&i.set(t.source_group_id,a),t.parent_source_group_id&&i?.has(t.parent_source_group_id)?i.get(t.parent_source_group_id).add(a):o.add(a),a}var ukt=class extends g0{_adjustSilkscreenTextAutomatically=!0;get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:dMn,sourceFtype:$7.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${H_(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({name:this.name,ftype:$7.simple_inductor,inductance:this.props.inductance,max_current_rating:e.maxCurrentRating===void 0?void 0:q1(e.maxCurrentRating,"A").value,display_inductance:this._getSchematicSymbolDisplayValue(),supplier_part_numbers:e.supplierPartNumbers,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,are_pins_interchangeable:!0,display_name:e.displayName});this.source_component_id=n.source_component_id}};function ARo(t,e){const{injectionDb:n,subcircuit:o,groupsMap:i}=e,r=n.pcb_component.getWhere({source_component_id:t.source_component_id});n.cad_component.getWhere({source_component_id:t.source_component_id});const{pcbX:s,pcbY:a}=t4({pcbComponent:r,sourceGroupId:t.source_group_id,inflatorContext:e}),A=new ukt({name:t.name,inductance:t.inductance,layer:r?.layer,pcbX:s,pcbY:a,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds});if(r){const c=e4(r,{...e,normalComponent:A});c&&A.add(c)}t.source_group_id&&i?.has(t.source_group_id)?i.get(t.source_group_id).add(A):o.add(A)}var TMe=new WeakMap,gkt=t=>{const e=[t.name,...t.port_hints??[]].map(i=>i.toLowerCase().replace(/[^a-z0-9+-]/g,"")),n=e.some(i=>["a","anode","pos","positive","+"].includes(i)),o=e.some(i=>["k","c","cathode","neg","negative","-"].includes(i));return n===o?null:n?"anode":"cathode"},cRo=t=>{const e=t.root;if(!e)return;const{db:n}=e,o=TMe.get(t);for(const y of o??[])n.pcb_fabrication_note_path.delete(y.pcb_fabrication_note_path_id);if(TMe.delete(t),e.pcbDisabled||!t.pcb_component_id)return;const i=n.pcb_component.get(t.pcb_component_id);if(!i||i.layer!=="top"&&i.layer!=="bottom")return;const r=n.source_port.list({source_component_id:t.source_component_id}),s=r.filter(y=>gkt(y)==="anode"),a=r.filter(y=>gkt(y)==="cathode");if(s.length!==1||a.length!==1)return;const A=s[0],c=a[0],l=n.pcb_port.getWhere({source_port_id:A.source_port_id}),u=n.pcb_port.getWhere({source_port_id:c.source_port_id});if(!l||!u)return;const g=Math.hypot(u.x-l.x,u.y-l.y);if(g<1e-6)return;const h=Math.atan2(u.y-l.y,u.x-l.x),d=D0(M0((l.x+u.x)/2,(l.y+u.y)/2),W4(h)),p=(y,x)=>ts(d,{x:y,y:x}),m={pcb_component_id:i.pcb_component_id,subcircuit_id:t.getSubcircuit()?.subcircuit_id??void 0,layer:i.layer},_=[];TMe.set(t,_);const f=Math.min(g*.2,.4),I=f*.75,C=[[p(-g/2,0),p(-f,0)],[p(-f,-I),p(f,0),p(-f,I),p(-f,-I)],[p(f,-I),p(f,I)],[p(f,0),p(g/2,0)]];for(const y of C)_.push(n.pcb_fabrication_note_path.insert({...m,route:y,stroke_width:.08}))},dkt=class extends g0{get config(){const t={laser:"laser_diode"},e=this.props.laser?"laser":null;return{schematicSymbolName:e?t[e]:this.props.symbolName??"led",componentName:"Led",zodProps:yMn,sourceFtype:"simple_led"}}initPorts(){const t=this.children.some(i=>i.componentName==="Footprint"),e=this.resolveFootprint(),n=!!this._resolvePinLabels(),o=!n&&!t&&(!e||HDt(e));super.initPorts({pinCount:2,ignoreSymbolPorts:!n&&!o,additionalAliases:{pin1:o?["anode","pos","left"]:[],pin2:o?["cathode","neg","right"]:[]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){const t=super.getFootprinterString();return t&&this.props.color?`${t}_color(${this.props.color})`:t}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:e.wavelength,color:e.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1,display_name:e.displayName});this.source_component_id=n.source_component_id}get pos(){return this.portMap.pos}doInitialPcbComponentSizeCalculation(){super.doInitialPcbComponentSizeCalculation(),cRo(this)}get anode(){return this.portMap.anode}get neg(){return this.portMap.neg}get cathode(){return this.portMap.cathode}};function lRo(t,e){const{injectionDb:n,subcircuit:o,groupsMap:i}=e,r=n.pcb_component.getWhere({source_component_id:t.source_component_id});n.cad_component.getWhere({source_component_id:t.source_component_id});const{pcbX:s,pcbY:a}=t4({pcbComponent:r,sourceGroupId:t.source_group_id,inflatorContext:e}),A=new dkt({name:t.name,color:t.color,wavelength:t.wavelength??t.wave_length,layer:r?.layer,pcbX:s,pcbY:a,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds});if(r){const c=e4(r,{...e,normalComponent:A});c&&A.add(c)}t.source_group_id&&i?.has(t.source_group_id)?i.get(t.source_group_id).add(A):o.add(A)}var uRo=[{gate:"left",drain:"top",source:"bottom"},{gate:"left",drain:"bottom",source:"top"},{gate:"right",drain:"top",source:"bottom"},{gate:"right",drain:"bottom",source:"top"},{gate:"top",drain:"left",source:"right"},{gate:"top",drain:"right",source:"left"},{gate:"bottom",drain:"left",source:"right"},{gate:"bottom",drain:"right",source:"left"}],gRo=t=>{const e=(t%360+360)%360;if(e%90!==0)throw new Error(`Schematic rotation ${t} is not supported for Mosfet`);return[{gate:"left",drain:"top",source:"bottom"},{gate:"top",drain:"right",source:"left"},{gate:"right",drain:"bottom",source:"top"},{gate:"bottom",drain:"left",source:"right"}][e/90]},dRo=t=>{const e={drain:t.symbolDrainSide,source:t.symbolSourceSide,gate:t.symbolGateSide},n=gRo(Number(t.schRotation??0)),o=uRo.filter(i=>Object.keys(e).every(r=>e[r]===void 0||e[r]===i[r]));if(o.length===0){const i=Object.entries(e).filter(([,r])=>r!==void 0).map(([r,s])=>`${r}=${s}`).join(", ");throw new Error(`Invalid MOSFET symbol port side combination (${i}). The gate must be perpendicular to the drain and source, and the drain and source must be opposite.`)}return o.sort((i,r)=>{const s=a=>Object.keys(n).filter(A=>a[A]!==n[A]).length;return s(i)-s(r)})[0]},hRo=t=>{const e=t.mosfetMode==="depletion"?"d":"e",n=`${t.channelType}_channel_${e}_mosfet_transistor`;if(!(t.symbolDrainSide!==void 0||t.symbolSourceSide!==void 0||t.symbolGateSide!==void 0))return n;const{gate:i,drain:r}=dRo(t);return`${n}_gate_${i}_drain_${r}`},hkt=class extends g0{get config(){return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??hRo(this.props),zodProps:cMn,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({ftype:"simple_mosfet",name:this.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,mosfet_mode:e.mosfetMode,channel_type:e.channelType,display_name:e.displayName});this.source_component_id=n.source_component_id}};function pRo(t,e){const{injectionDb:n,subcircuit:o,groupsMap:i}=e,r=n.pcb_component.getWhere({source_component_id:t.source_component_id}),{pcbX:s,pcbY:a}=t4({pcbComponent:r,sourceGroupId:t.source_group_id,inflatorContext:e}),A=new hkt({name:t.name,channelType:t.channel_type,mosfetMode:t.mosfet_mode,manufacturerPartNumber:t.manufacturer_part_number,supplierPartNumbers:t.supplier_part_numbers??void 0,displayName:t.display_name,layer:r?.layer,pcbX:s,pcbY:a,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds});if(r){const c=e4(r,{...e,normalComponent:A});c&&A.add(c)}t.source_group_id&&i?.has(t.source_group_id)?i.get(t.source_group_id).add(A):o.add(A)}function mRo(t,e){const{injectionDb:n,subcircuit:o}=e;if(t.source_component_id!==null)return;const i=n.pcb_port.getWhere({source_port_id:t.source_port_id}),r=new Pu({name:t.name,pinNumber:t.pin_number});o.add(r),r.source_port_id=t.source_port_id;const s=o.root;if(s&&i){const{db:a}=s,A=a.pcb_port.insert({pcb_component_id:void 0,layers:i.layers,subcircuit_id:o.subcircuit_id??void 0,pcb_group_id:o.getGroup()?.pcb_group_id??void 0,x:i.x,y:i.y,source_port_id:t.source_port_id,is_board_pinout:!1});r.pcb_port_id=A.pcb_port_id}}var pkt=class extends g0{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:OPn,sourceFtype:$7.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});const e=Su[this._getSchematicSymbolNameOrThrow()],n=e.ports.find(A=>A.labels.includes("1")),o=e.ports.find(A=>A.labels.includes("2")),i=this.selectAll("port"),r=i.find(A=>A.props.pinNumber===1);r.schematicSymbolPortDef=n;const s=new Set(r._getPortsInternallyConnectedToThisPort()),a=i.filter(A=>A!==r&&!s.has(A)).sort((A,c)=>(A.props.pinNumber??0)-(c.props.pinNumber??0))[0];a&&(a.schematicSymbolPortDef=o)}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:n}=this,o=e.source_component.insert({name:this.name,ftype:$7.simple_push_button,supplier_part_numbers:n.supplierPartNumbers,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,are_pins_interchangeable:!0,display_name:n.displayName});this.source_component_id=o.source_component_id}};function _Ro(t,e){const{injectionDb:n,subcircuit:o,groupsMap:i}=e,r=n.pcb_component.getWhere({source_component_id:t.source_component_id});n.cad_component.getWhere({source_component_id:t.source_component_id});const{pcbX:s,pcbY:a}=t4({pcbComponent:r,sourceGroupId:t.source_group_id,inflatorContext:e}),A=new pkt({name:t.name,layer:r?.layer,pcbX:s,pcbY:a,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds});if(r){const c=e4(r,{...e,normalComponent:A});c&&A.add(c)}t.source_group_id&&i?.has(t.source_group_id)?i.get(t.source_group_id).add(A):o.add(A)}var mkt=class extends g0{_adjustSilkscreenTextAutomatically=!0;get config(){const t=this.props.symbolName??"boxresistor",e=this.props.schSize==="sm"||this.props.schSize==="xs"?this.props.schSize:void 0,n=e&&(t==="boxresistor"||t==="resistor")?`${t}_${e}`:void 0;return{componentName:"Resistor",schematicSymbolName:n&&`${n}_right`in Su?n:t,zodProps:Kwn,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${H_(this._parsedProps.resistance)}Ω`}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 t1({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new t1({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new t1({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new t1({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,resistance:e.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0,display_name:e.displayName});this.source_component_id=n.source_component_id}};function fRo(t,e){const{injectionDb:n,subcircuit:o,groupsMap:i}=e,r=n.pcb_component.getWhere({source_component_id:t.source_component_id});n.cad_component.getWhere({source_component_id:t.source_component_id});const{pcbX:s,pcbY:a}=t4({pcbComponent:r,sourceGroupId:t.source_group_id,inflatorContext:e}),A=new mkt({name:t.name,resistance:t.resistance,layer:r?.layer,pcbX:s,pcbY:a,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds});if(r){const c=e4(r,{...e,normalComponent:A});c&&A.add(c)}t.source_group_id&&i?.has(t.source_group_id)?i.get(t.source_group_id).add(A):o.add(A)}function IRo(t){return t.simSwitchFrequency!==void 0||t.simCloseAt!==void 0||t.simOpenAt!==void 0||t.simStartClosed!==void 0||t.simStartOpen!==void 0}var _kt=class extends g0{_getSwitchType(){const t=this._parsedProps;return t?t.dpdt?"dpdt":t.spst?"spst":t.spdt?"spdt":t.dpst?"dpst":t.type??"spst":"spst"}get config(){const t=this._getSwitchType(),e=this._parsedProps?.isNormallyClosed??!1,n={spst:e?"spst_normally_closed_switch":"spst_switch",spdt:e?"spdt_normally_closed_switch":"spdt_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??n[t],zodProps:xMn,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:t}=this.root,e=this._parsedProps??{},n=t.source_component.insert({ftype:"simple_switch",name:this.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:this._getSwitchType()==="spst",display_name:e?.displayName});this.source_component_id=n.source_component_id}doInitialSimulationRender(){const{_parsedProps:t}=this;if(!IRo(t))return;const{db:e}=this.root,n={type:"simulation_switch",source_component_id:this.source_component_id||""};t.simSwitchFrequency!==void 0&&(n.switching_frequency=Cy.parse(t.simSwitchFrequency)),t.simCloseAt!==void 0&&(n.closes_at=Ml.parse(t.simCloseAt)),t.simOpenAt!==void 0&&(n.opens_at=Ml.parse(t.simOpenAt)),t.simStartOpen!==void 0&&(n.starts_closed=!t.simStartOpen),t.simStartClosed!==void 0&&(n.starts_closed=t.simStartClosed),e.simulation_switch.insert(n)}},CRo=(t,e)=>{const n=e.injectionDb.source_port.list().filter(s=>s.source_component_id===t.source_component_id),o={};let i=0;for(const s of n){const a=s.pin_number;if(a==null)continue;i=Math.max(i,a);const A=Array.from(new Set([s.name,...s.port_hints??[]].filter(c=>typeof c=="string"&&c.length>0)));A.length>0&&(o[`pin${a}`]=A)}let r="spst";return i>=5?r="dpdt":i===4?r="dpst":i===3&&(r="spdt"),{type:r,pinLabels:Object.keys(o).length>0?o:void 0}};function yRo(t,e){const{injectionDb:n,subcircuit:o,groupsMap:i}=e,r=n.pcb_component.getWhere({source_component_id:t.source_component_id}),{pcbX:s,pcbY:a}=t4({pcbComponent:r,sourceGroupId:t.source_group_id,inflatorContext:e}),A=CRo(t,e),c=new _kt({name:t.name,displayName:t.display_name,...A,layer:r?.layer,pcbX:s,pcbY:a,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds});if(r){const l=e4(r,{...e,normalComponent:c});l&&c.add(l)}t.source_group_id&&i?.has(t.source_group_id)?i.get(t.source_group_id).add(c):o.add(c)}function xRo(t){if(t.length<=2)return[];const e=t[0],n=t[t.length-1];return t.slice(1,-1).filter(o=>{const i=W7(o),r=W7(e),s=W7(n),a=i.x===r.x&&i.y===r.y,A=i.x===s.x&&i.y===s.y;return!a&&!A}).map(o=>{if(o.route_type==="via")return{x:o.x,y:o.y,via:!0,fromLayer:o.from_layer,toLayer:o.to_layer};const i=W7(o);return{x:i.x,y:i.y}})}var ERo=(t,e)=>{const{injectionDb:n,subcircuit:o,groupsMap:i}=e,r=[];let s=t.source_group_id;for(;s&&s!==o.source_group_id;){const a=n.source_group.get(s),A=i?.get(s);if(!a||!A)break;const c=A.props.name??A.fallbackUnassignedName;r.unshift(`.${c}`),s=a.parent_source_group_id}return r.push(`.${t.name}`),r.join(" > ")};function BRo(t,e){const{injectionDb:n,subcircuit:o}=e,i=[];for(const u of t.connected_source_port_ids){const g=n.source_port.get(u);if(!g)continue;let h;if(g.source_component_id){const d=n.source_component.get(g.source_component_id);d&&(h=`${ERo({name:d.name,source_group_id:d.source_group_id},e)} > .${g.name}`)}else h=`.${g.name}`;h&&i.push(h)}for(const u of t.connected_source_net_ids){const g=n.source_net.get(u);g&&i.push(`net.${g.name}`)}if(i.length<2)return;const r=n.pcb_trace.list().filter(u=>u.source_trace_id===t.source_trace_id),s=r[0];let a;s&&(a=xRo(s.route));let A=t.min_trace_thickness;if(!A&&s?.route){const u=s.route.find(g=>g.route_type==="wire");u&&u.route_type==="wire"&&(A=u.width)}const c={path:i};A!==void 0&&(c.thickness=A),a&&a.length>0?c.pcbPath=a:!s&&t.connected_source_port_ids.length===2&&t.connected_source_net_ids.length===0&&(c.pcbStraightLine=!0);const l=new t1(c);l._inflatedPcbTraces=r.length>0?r:void 0,l._inflatedPcbVias=s?n.pcb_via.list().filter(u=>r.some(g=>u.pcb_trace_id===g.pcb_trace_id)):void 0,o.add(l)}var bRo={collector:["c"],base:["b"],emitter:["e"]},fkt=class extends g0{get config(){const t=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??t,zodProps:aMn,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){const t={},e=this.getSchematicSymbol();for(const n of e?.ports??[]){const o=H0e(n.labels);if(o)for(const i of n.labels){const r=bRo[i];r&&(t[`pin${o}`]=r)}}super.initPorts({pinCount:3,additionalAliases:t})}get collector(){return this.portMap.collector}get base(){return this.portMap.base}get emitter(){return this.portMap.emitter}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({ftype:"simple_transistor",name:this.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,transistor_type:e.type,display_name:e.displayName});this.source_component_id=n.source_component_id}};function SRo(t,e){const{injectionDb:n,subcircuit:o,groupsMap:i}=e,r=n.pcb_component.getWhere({source_component_id:t.source_component_id});n.cad_component.getWhere({source_component_id:t.source_component_id});const{pcbX:s,pcbY:a}=t4({pcbComponent:r,sourceGroupId:t.source_group_id,inflatorContext:e}),A=new fkt({name:t.name,type:t.transistor_type,layer:r?.layer,pcbX:s,pcbY:a,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds});if(r){const c=e4(r,{...e,normalComponent:A});c&&A.add(c)}t.source_group_id&&i?.has(t.source_group_id)?i.get(t.source_group_id).add(A):o.add(A)}function QRo(t){const{injectionDb:e,subcircuit:n,groupsMap:o}=t,i=["pcb_silkscreen_rect","pcb_silkscreen_circle","pcb_silkscreen_line","pcb_silkscreen_path","pcb_silkscreen_text","pcb_fabrication_note_text","pcb_fabrication_note_path","pcb_fabrication_note_rect","pcb_note_text","pcb_note_rect","pcb_note_path","pcb_note_line","pcb_via","pcb_hole","pcb_plated_hole","pcb_cutout"],r=e.toArray().filter(a=>{if(!i.includes(a.type))return!1;if(a.type==="pcb_via"){if(!a.pcb_trace_id)return!0;const A=e.pcb_trace.get(a.pcb_trace_id),c=A?.source_trace_id;return!(c&&e.source_trace.get(c)&&A?.route.some(u=>u.route_type==="via"&&Math.abs(u.x-a.x)<1e-4&&Math.abs(u.y-a.y)<1e-4))}return a.type==="pcb_cutout"?!0:"pcb_component_id"in a&&(a.pcb_component_id===null||a.pcb_component_id===void 0)});if(r.length===0)return;const s=Db({componentName:"",componentRotation:"0deg"},r);for(const a of s)n.add(a)}var Hue=(t,e,n)=>{if(!e)return;const o=Xc(e);if(e&&n?.length>0)throw new Error("Component cannot have both circuitJson and children");const r={injectionDb:o,subcircuit:t,groupsMap:new Map},s=o.source_group.list(),a=new Set,A=[...s];for(;A.length>0;){const h=A.findIndex(p=>!p.parent_source_group_id||a.has(p.parent_source_group_id));if(h===-1){const p=A.map(m=>m.source_group_id).join(", ");throw new Error(`Cannot inflate source_groups: cyclic dependency or missing parent detected. Remaining groups: ${p}`)}const d=A[h];aRo(d,r),a.add(d.source_group_id),A.splice(h,1)}const c=o.pcb_board.list();for(const h of c)g8o(h,r);const l=o.source_component.list();for(const h of l)switch(h.ftype){case"simple_resistor":fRo(h,r);break;case"simple_capacitor":I8o(h,r);break;case"simple_inductor":ARo(h,r);break;case"simple_diode":O8o(h,r);break;case"simple_fiducial":Y8o(h,r);break;case"simple_led":lRo(h,r);break;case"simple_chip":x8o(h,r);break;case"simple_connector":F8o(h,r);break;case"simple_transistor":SRo(h,r);break;case"simple_mosfet":pRo(h,r);break;case"simple_push_button":_Ro(h,r);break;case"simple_switch":yRo(h,r);break;default:throw new Error(`No inflator implemented for source component ftype: "${h.ftype}"`)}const u=o.source_port.list();for(const h of u)mRo(h,r);const g=o.source_trace.list();for(const h of g)BRo(h,r);QRo(r)},vRo=t=>!t||typeof t!="object"?!1:typeof t.getSourcePort=="function",wRo=t=>!t||typeof t!="object"?!1:typeof t.getSourceNet=="function",PRo=t=>!t||typeof t!="object"?!1:typeof t.getPorts=="function",MRo=t=>!t||typeof t!="object"?!1:typeof t.type=="string",C$=t=>typeof t=="string"&&t.length>0,kMe=class{constructor(t){this.port=t}port;getPcbPort(){const t=this.port.pcb_port_id;return t?this.port.root?.db.pcb_port.get(t)??null:null}getSourcePort(){const t=this.port.source_port_id;return t?this.port.root?.db.source_port.get(t)??null:null}},DRo=class{constructor(t){this.net=t}net;getSourceNet(){const t=this.net.source_net_id;return t?this.net.root?.db.source_net.get(t)??null:null}},NRo=class{constructor(t){this.component=t}component;getPort(t){const e=this.component.selectOne(`port.${t}`,{type:"port"})??this.component.selectOne(`.${t}`,{type:"port"});return e?new kMe(e):null}getPorts(){return this.component.selectAll("port").map(t=>new kMe(t))}getPcbComponent(){const t=this.component.pcb_component_id;return t?this.component.root?.db.pcb_component.get(t)??null:null}getSourceComponent(){const t=this.component.source_component_id;return t?this.component.root?.db.source_component.get(t)??null:null}},RRo=class extends Ir{get config(){return{componentName:"DrcCheck",zodProps:APn}}constructor(t){super(t)}async runCustomDrcCheck(t){const e=await this._parsedProps.checkFn(this.createCustomDrcCheckContext(t));let n=[];return Array.isArray(e)?n=e:e&&(n=[e]),n.map((o,i)=>this.createCircuitJsonDiagnostic(o,i)).filter(o=>!!o)}createCustomDrcCheckContext(t){return{select:this.selectCustomDrcElement.bind(this),selectAll:this.selectAllCustomDrcElements.bind(this),isConnected:(e,n)=>this.isConnected(e,n,t),isPulledUp:e=>this.isConnected(e,"net.VCC",t)||this.isConnected(e,"net.VDD",t)||this.getResistanceBetween(e,"net.VCC",t)!==null||this.getResistanceBetween(e,"net.VDD",t)!==null,isPulledDown:e=>this.isConnected(e,"net.GND",t)||this.getResistanceBetween(e,"net.GND",t)!==null,getResistanceBetween:(e,n)=>this.getResistanceBetween(e,n,t)}}selectCustomDrcElement(t){return this.wrapSelectionResult(this.getSubcircuit().selectOne(t))}selectAllCustomDrcElements(t){const e=[];for(const n of this.getSubcircuit().selectAll(t)){const o=this.wrapSelectionResult(n);o&&e.push(o)}return e}wrapSelectionResult(t){return t?t instanceof Pu?new kMe(t):t instanceof Qb?new DRo(t):new NRo(t):null}createCircuitJsonDiagnostic(t,e){const n=t;let o="source_component_misconfigured_error";typeof n.error_type=="string"?o=n.error_type:typeof n.warning_type=="string"&&(o=n.warning_type);const i={...t};typeof n.type=="string"?i.type=n.type:i.type=o,typeof n.warning_type!="string"&&(typeof n.error_type=="string"?i.error_type=n.error_type:i.error_type=o);const r=`${o}_id`;return n[r]?i[r]=n[r]:i[r]=`${o}_${this._renderId}_${e}`,dxe.parse(i)}isConnected(t,e,n){const o=this.getConnectivityKeys(t,n),i=this.getConnectivityKeys(e,n);return o.some(r=>i.includes(r))}getResistanceBetween(t,e,n){if(this.isConnected(t,e,n))return 0;const o=this.getConnectivityKeys(t,n),i=this.getConnectivityKeys(e,n);if(o.length===0||i.length===0)return null;const r=n.filter(a=>a.type==="source_component"&&a.ftype==="simple_resistor"),s=this.root;if(!s)return null;for(const a of r){const A=s.db.source_port.list({source_component_id:a.source_component_id});if(A.length!==2)continue;const c=A.map(g=>g.subcircuit_connectivity_map_key),l=c.some(g=>g&&o.includes(g)),u=c.some(g=>g&&i.includes(g));if(l&&u)return a.resistance}return null}getConnectivityKeys(t,e){if(!t)return[];if(typeof t=="string"){const n=this.selectCustomDrcElement(t);return n?this.getConnectivityKeys(n,e):[]}return vRo(t)?[t.getSourcePort()?.subcircuit_connectivity_map_key].filter(C$):wRo(t)?[t.getSourceNet()?.subcircuit_connectivity_map_key].filter(C$):PRo(t)?t.getPorts().flatMap(n=>this.getConnectivityKeys(n,e)):MRo(t)?this.getCircuitJsonElementConnectivityKeys(t,e):[]}getCircuitJsonElementConnectivityKeys(t,e){if(!t)return[];if(t.type==="source_port")return[t.subcircuit_connectivity_map_key].filter(C$);if(t.type==="source_net")return[t.subcircuit_connectivity_map_key].filter(C$);if(t.type==="pcb_port")return this.getConnectivityKeys(t.source_port_id,e);if(t.type==="source_component"){const n=this.root;return n?n.db.source_port.list({source_component_id:t.source_component_id}).map(o=>o.subcircuit_connectivity_map_key).filter(C$):[]}return[]}},Ikt=class{firstChild=null;children;db;root=null;isRootCircuit=!1;cachedSubcircuits;pendingSubcircuitRenders;_schematicDisabledOverride;get schematicDisabled(){return this._schematicDisabledOverride!==void 0?this._schematicDisabledOverride:this.platform?.schematicDisabled!==void 0?this.platform.schematicDisabled:this._getBoard()?._parsedProps?.schematicDisabled??!1}set schematicDisabled(t){this._schematicDisabledOverride=t}pcbDisabled=!1;pcbRoutingDisabled=!1;_featureMspSchematicTraceRouting=!0;_featurePcbViaStitching=!0;name;platform;projectUrl;_hasRenderedAtleastOnce=!1;_asyncEffectIdsByPhase=new Map;_asyncEffectPhaseById=new Map;_hasUnrenderedUpdatesFromAsyncEffects=!1;_runningAsyncEffectsById=new Map;constructor({platform:t,projectUrl:e,cachedSubcircuits:n,pendingSubcircuitRenders:o}={}){this.children=[],this.db=Mr([]),this.platform=t,this.projectUrl=e,this.pcbDisabled=t?.pcbDisabled??!1,this.pcbRoutingDisabled=t?.routingDisabled??!1,this.cachedSubcircuits=n,this.pendingSubcircuitRenders=o,this.root=this}add(t){let e;ee.isValidElement(t)?e=RMt(t):e=t,this.children.push(e)}setPlatform(t){this.platform={...this.platform,...t},t.pcbDisabled!==void 0&&(this.pcbDisabled=t.pcbDisabled),t.routingDisabled!==void 0&&(this.pcbRoutingDisabled=t.routingDisabled)}_getBoard(){const t=e=>{for(const n of e){if(n.componentName==="Board")return n;if(U0e(n)){const o=t(n.children);if(o)return o}}};return t(this.children)}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: IsolatedCircuit has no children (use circuit.add(...))");const t=this.children.filter(n=>n.lowercaseComponentName==="panel");if(t.length>1)throw new Error("Only one <panel> is allowed per circuit");if(t.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=t[0];return}if(this.children.length===1&&(this.children[0].isGroup||U0e(this.children[0]))){this.firstChild=this.children[0];return}const e=new A6({subcircuit:!0});e.parent=this,e.addAll(this.children),this.children=[e],this.firstChild=e}render(){this.firstChild||this._guessRootComponent();const{firstChild:t,db:e}=this;if(!t)throw new Error("IsolatedCircuit has no root component");t.parent=this,t.runRenderCycle(),this._hasUnrenderedUpdatesFromAsyncEffects=!1,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.isDoneRendering();)await new Promise(e=>setTimeout(e,100)),this.render();this.emit("renderComplete")}isDoneRendering(){return this._hasRenderedAtleastOnce&&!this._hasIncompleteAsyncEffects()}_hasIncompleteAsyncEffects(){return this._asyncEffectPhaseById.size>0||this._hasUnrenderedUpdatesFromAsyncEffects?!0:this.children.some(t=>t._hasIncompleteAsyncEffects())}_hasIncompleteAsyncEffectsForPhase(t){return(this._asyncEffectIdsByPhase.get(t)?.size??0)>0}getRunningAsyncEffects(){return Array.from(this._runningAsyncEffectsById.values())}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(t){const e=await Promise.resolve().then(()=>njo).catch(n=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.

"${n.message}"`)});if(t.view==="pcb")return e.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(t.view==="schematic")return e.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${t.view}`)}getCoreVersion(){const[t,e,n]=jTt.version.split(".").map(Number);return`${t}.${e}.${n+1}`}async preview(t){throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return hC()}_computePcbGlobalTransformBeforeLayout(){return hC()}selectAll(t){return this._guessRootComponent(),this.firstChild?.selectAll(t)??[]}selectOne(t,e){return this._guessRootComponent(),this.firstChild?.selectOne(t,e)??null}_eventListeners={};emit(t,...e){if(t==="asyncEffect:start"?this._registerAsyncEffectStart(e[0]):t==="asyncEffect:end"&&this._registerAsyncEffectEnd(e[0]),!!this._eventListeners[t])for(const n of this._eventListeners[t])n(...e)}on(t,e){this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e)}removeListener(t,e){this._eventListeners[t]&&(this._eventListeners[t]=this._eventListeners[t].filter(n=>n!==e))}enableDebug(t){typeof t=="string"?vc.enable(t):(t===null||t===!1)&&vc.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}_registerAsyncEffectStart(t){if(!t?.asyncEffectId||!t.phase)return;const{asyncEffectId:e,phase:n}=t,o=this._asyncEffectPhaseById.get(e);o&&o!==n&&this._asyncEffectIdsByPhase.get(o)?.delete(e),this._asyncEffectIdsByPhase.has(n)||this._asyncEffectIdsByPhase.set(n,new Set),this._asyncEffectIdsByPhase.get(n).add(e),this._asyncEffectPhaseById.set(e,n),this._runningAsyncEffectsById.set(e,{asyncEffectId:e,effectName:t.effectName,componentDisplayName:t.componentDisplayName,phase:n,error:t.error})}_registerAsyncEffectEnd(t){if(!t?.asyncEffectId)return;const{asyncEffectId:e}=t,n=this._asyncEffectPhaseById.get(e)??t.phase;if(n){const o=this._asyncEffectIdsByPhase.get(n);o?.delete(e),o&&o.size===0&&this._asyncEffectIdsByPhase.delete(n)}this._asyncEffectPhaseById.delete(e),this._runningAsyncEffectsById.delete(e),this._hasUnrenderedUpdatesFromAsyncEffects=!0}};function Ckt(t){if(!t._isIsolatedSubcircuit||t._isolatedCircuitJson||!t.getSubcircuitPropHash)return;const e=t.getSubcircuitPropHash(),n=t.root?.cachedSubcircuits,o=t.root?.pendingSubcircuitRenders,i=n?.get(e);if(i){t._isolatedCircuitJson=i,t.children=[],t._normalComponentNameMap=null;return}const r=[...t.children];t.children=[],t._normalComponentNameMap=null;const s=t.root;t._queueAsyncEffect("render-isolated-subcircuit",async()=>{const a=n?.get(e);if(a){t._isolatedCircuitJson=a;return}const A=o?.get(e);if(A){t._isolatedCircuitJson=await A;return}let c,l;const u=new Promise((g,h)=>{c=g,l=h});o?.set(e,u);try{const g=new Ikt({platform:{...s.platform,pcbDisabled:s.pcbDisabled,schematicDisabled:s.schematicDisabled},cachedSubcircuits:n,pendingSubcircuitRenders:o});for(const d of r)g.add(d);await g.renderUntilSettled();const h=g.getCircuitJson();n?.set(e,h),t._isolatedCircuitJson=h,c(h)}catch(g){throw l(g instanceof Error?g:new Error(String(g))),g}finally{o?.delete(e)}})}var TRo=new Set(["name","key","pcbX","pcbY","schX","schY","pcbLeftEdgeX","pcbRightEdgeX","pcbTopEdgeY","pcbBottomEdgeY","pcbRotation","schRotation"]);function Oue(t,e=new WeakSet){if(t===null)return"null";if(t===void 0)return"undefined";const n=typeof t;if(n==="string")return`"${t}"`;if(n==="number"||n==="boolean")return String(t);if(n==="function")return"[function]";if(n==="symbol")return"[symbol]";if(n==="object"){if(e.has(t))return"[circular]";if(e.add(t),t.$$typeof!==void 0){const r=typeof t.type=="string"?t.type:t.type?.name||"[component]",s=t.props?Oue(t.props,e):"{}";return`ReactElement(${r},${s})`}return Array.isArray(t)?`[${t.map(s=>Oue(s,e)).join(",")}]`:`{${Object.keys(t).sort().map(r=>`${r}:${Oue(t[r],e)}`).join(",")}}`}return String(t)}function ykt(t){const e={},n=Object.keys(t).sort();for(const o of n)!TRo.has(o)&&t[o]!==void 0&&(e[o]=t[o]);return e}function xkt(t){return t.map(e=>({componentName:e.componentName,props:ykt(e.props??{}),children:xkt(e.children)}))}function Ekt(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return e>>>0}function kRo(t){const e=Oue(t),n=Ekt(e),o=Ekt(e+n.toString());return n.toString(16).padStart(8,"0")+o.toString(16).padStart(8,"0")}function Bkt(t){const e={props:ykt(t.props??{}),children:xkt(t.children)};return kRo(e)}var FO=1e-9,bkt=t=>t.route_type==="wire",FRo=(t,e,n)=>{const o=(t.y-e.y)*(n.x-e.x)-(t.x-e.x)*(n.y-e.y);if(Math.abs(o)>FO)return!1;const i=(t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y);if(i<-FO)return!1;const r=(n.x-e.x)**2+(n.y-e.y)**2;return!(i-r>FO)},Skt=(t,e)=>{if(e.length<3)return!1;let n=!1,o=e[e.length-1];for(const i of e){if(FRo(t,o,i))return!0;i.y>t.y!=o.y>t.y&&t.x<(o.x-i.x)*(t.y-i.y)/(o.y-i.y)+i.x&&(n=!n),o=i}return n},LRo=(t,e)=>{const{center:n,width:o,height:i}=e,r=(e.rotation??0)*Math.PI/180,s=Math.cos(-r),a=Math.sin(-r),A=t.x-n.x,c=t.y-n.y,l=A*s-c*a,u=A*a+c*s;return Math.abs(l)<=o/2+FO&&Math.abs(u)<=i/2+FO},HRo=(t,e)=>{const n=e.brep_shape.outer_ring.vertices.map(o=>({x:o.x,y:o.y}));if(!Skt(t,n))return!1;for(const o of e.brep_shape.inner_rings){const i=o.vertices.map(r=>({x:r.x,y:r.y}));if(Skt(t,i))return!1}return!0},ORo=(t,e)=>e.shape==="rect"?LRo(t,e):e.shape==="brep"?HRo(t,e):!1,GRo=(t,e,n)=>{if(t.source_trace_id===e)return!0;if(!t.source_trace_id)return!1;const o=n.get(t.source_trace_id);return o?o.connected_source_net_ids.includes(e):!1},YRo=(t,e,n)=>{const o=e.x-t.x,i=e.y-t.y;return Math.hypot(o,i)<=FO?!1:[0,.25,.5,.75,1].every(a=>ORo({x:t.x+o*a,y:t.y+i*a},n))},URo=({db:t,copperPour:e})=>{if(!e.source_net_id)return;const n=new Map(t.source_trace.list().map(o=>[o.source_trace_id,o]));for(const o of t.pcb_trace.list()){if(!GRo(o,e.source_net_id,n))continue;let i=!1;const r=o.route.map(s=>({...s}));for(let s=0;s<r.length-1;s++){const a=r[s],A=r[s+1];!a||!A||!bkt(a)||!bkt(A)||a.layer!==e.layer||A.layer!==e.layer||YRo({x:a.x,y:a.y},{x:A.x,y:A.y},e)&&(a.is_inside_copper_pour=!0,a.copper_pour_id=e.pcb_copper_pour_id,A.is_inside_copper_pour=!0,A.copper_pour_id=e.pcb_copper_pour_id,i=!0)}i&&t.pcb_trace.update(o.pcb_trace_id,{route:r})}},FMe=new WeakMap,KRo=.3,VRo=async t=>{if(!t.root)return;const{db:e}=t.root,n=t.selectAll("copperpour").filter(u=>u.getSubcircuit()===t),o=[];for(const u of n){const{_parsedProps:g}=u,d=t.selectOne(g.connectsTo)?.source_net_id;if(!d){u.renderError(`Net "${g.connectsTo}" not found for copper pour`);continue}o.push({copperPour:u,sourceNetId:d})}if(o.length===0)return;const i=e.toArray(),r=t._getBoard(),s=r?.pcb_board_id?e.pcb_board.get(r.pcb_board_id):void 0;let a=s?.outline?.length?s.outline:void 0;if(!a&&s?.width!==void 0&&s.height!==void 0){const{center:u,width:g,height:h}=s;a=[{x:u.x-g/2,y:u.y-h/2},{x:u.x+g/2,y:u.y-h/2},{x:u.x+g/2,y:u.y+h/2},{x:u.x-g/2,y:u.y+h/2}]}const A=Tbt(i,o.map(({copperPour:u,sourceNetId:g})=>{const{_parsedProps:h}=u,d=h.clearance??.2;return{layer:h.layer,subcircuit_id:t.subcircuit_id??void 0,source_net_id:g,pad_margin:h.padMargin??d,trace_margin:h.traceMargin??d,pour_margin:d,board_edge_margin:h.boardEdgeMargin??d,board_edge_outline:u._isImplicitCopperPour?a:void 0,cutout_margin:h.cutoutMargin??d,...h.useThermalReliefs?{use_thermal_reliefs:!0,thermal_relief_spoke_width:KRo}:{},outline:h.outline??a}}));await Umo();const c=new Rbt(A);t.root.emit("solver:started",{type:"solver:started",solverName:"CopperPourPipelineSolver",solverParams:A,solverConstructorArgs:[A],componentName:t.getString()});const{brep_shapes_by_region:l}=c.getOutput();for(const[u,{copperPour:g,sourceNetId:h}]of o.entries()){const{_parsedProps:d}=g,p=d.coveredWithSolderMask??!1;for(const m of l[u]??[]){const _=e.pcb_copper_pour.insert({shape:"brep",layer:d.layer,brep_shape:m,source_net_id:h,subcircuit_id:t.subcircuit_id??void 0,covered_with_solder_mask:p});URo({db:e,copperPour:_})}}};function zRo(t){t.root?.pcbDisabled||t._queueAsyncEffect("PcbCopperPourRender",async()=>{const e=t.getSubcircuit(),n=FMe.get(e);if(n){await n;return}const o=VRo(e);FMe.set(e,o);try{await o}finally{FMe.delete(e)}})}var JRo=t=>{const e=t.getSubcircuit();if(!e.root)return;const n=e.selectAll("copperpour").filter(g=>g.getSubcircuit()===e);if(n[0]!==t)return;const o=n.flatMap(g=>{const h=e.selectOne(g._parsedProps.connectsTo);return h?.source_net_id?[h.source_net_id]:[]});if(o.length===0)return;const{db:i}=e.root,r=t.getInheritedMergedProperty("pcbStyle"),{holeDiameter:s,padDiameter:a}=$N(r),A=t._getBoard(),c=A?.pcb_board_id?i.pcb_board.get(A.pcb_board_id):void 0,l={circuitJson:i.toArray(),options:{sourceNetIds:[...new Set(o)],viaHoleDiameter:c?.min_via_hole_diameter??s,viaOuterDiameter:c?.min_via_pad_diameter??a,viaStitchPitch:A?._parsedProps.viaStitchPitch}},u=new LRt(l);if(e.root.emit("solver:started",{type:"solver:started",solverName:"ViaStitchSolver",solverParams:l,solverConstructorArgs:[l],componentName:e.getString()}),u.solve(),u.failed)throw new Error(u.error??"Via stitching solver failed");for(const g of u.getOutput().pcbVias){const{pcb_via_id:h,...d}=g,p=i.pcb_via.insert(d);A?._generatedStitchingViaIds?.add(p.pcb_via_id)}};function WRo(t){t.root?.pcbDisabled||!t.root?._featurePcbViaStitching||t._getBoard()?._parsedProps.enableViaStitching&&t._queueAsyncEffect("PcbViaStitchRender",async()=>{JRo(t)})}var Qkt=class extends Ir{isPcbPrimitive=!0;_isImplicitCopperPour=!1;get config(){return{componentName:"CopperPour",zodProps:RMn}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){const{_parsedProps:t}=this;Hj(this,[t.connectsTo])}doInitialPcbCopperPourRender(){zRo(this)}doInitialPcbViaStitchRender(){WRo(this)}},jRo=t=>{const{root:e}=t;if(!e||e.pcbDisabled||!t._parsedProps.automaticPoursEnabled||e.pcbRoutingDisabled||t.getInheritedProperty("routingDisabled"))return;const{db:n}=e,o=n.subtree({subcircuit_id:t.subcircuit_id}).toArray();if(!o.some(c=>c.type==="source_net"&&(c.is_power||c.is_ground||c.is_positive_voltage_source)))return;const r={circuitJson:o,layers:[...t.allLayers]},s=new NRt(r),a=s.getConstructorParams();e.emit("solver:started",{type:"solver:started",solverName:"ImplicitCopperPourPipelineSolver",solverParams:a[0],solverConstructorArgs:a,componentName:t.getString()}),s.solve();const A=t.selectAll("net");for(const c of s.getOutput()){if(c.shape!=="polygon")continue;const l=A.find(g=>g.source_net_id===c.source_net_id);if(!l)throw new Error(`Unable to find the power net for implicit copper region ${c.pcb_copper_pour_id}`);const u=new Qkt({layer:c.layer,connectsTo:l.getPortSelector(),outline:c.points,coveredWithSolderMask:c.covered_with_solder_mask});u._isImplicitCopperPour=!0,l.getSubcircuit().add(u)}},LMe=(t,e,n=0)=>{const{a:o,b:i,c:r,d:s,e:a,f:A}=D0(M0(e.x,e.y),W4(n*Math.PI/180));return t.transform(new QF(o,i,r,s,a,A))},Qw=t=>t.orientation()===mF.CCW?t:t.reverse(),y$=(t,e)=>Qw(new Ip(new fD(new Gc(t.x,t.y),e))),LO=(t,e,n,o=0,i=0)=>{const r=e/2,s=n/2,a=Math.max(0,Math.min(o,r,s));if(a===0)return LMe(Qw(new Ip(new VBe(-r,-s,r,s))),t,i);const A=[new T8(new Gc(r-a,-s+a),a,-Math.PI/2,0,!0),new T8(new Gc(r-a,s-a),a,0,Math.PI/2,!0),new T8(new Gc(-r+a,s-a),a,Math.PI/2,Math.PI,!0),new T8(new Gc(-r+a,-s+a),a,Math.PI,Math.PI*1.5,!0)],c=[];for(let l=0;l<A.length;l++){const u=A[l],g=A[(l+1)%A.length];c.push(u),u.end.distanceTo(g.start)[0]>1e-12&&c.push(new _D(u.end,g.start))}return LMe(Qw(new Ip(c)),t,i)},vkt=t=>{const e=[];for(let n=0;n<t.vertices.length;n++){const o=t.vertices[n],i=t.vertices[(n+1)%t.vertices.length],r=i.x-o.x,s=i.y-o.y;if(r===0&&s===0)continue;const a=o.bulge??0;if(a===0)e.push(new _D(new Gc(o.x,o.y),new Gc(i.x,i.y)));else{const A=(1-a*a)/(4*a),c=new Gc((o.x+i.x)/2-s*A,(o.y+i.y)/2+r*A);e.push(new T8(c,Math.hypot(r,s)*(1+a*a)/(4*Math.abs(a)),Math.atan2(o.y-c.y,o.x-c.x),Math.atan2(i.y-c.y,i.x-c.x),a>0))}}return Qw(new Ip(e))},x$=(t,e)=>{for(const n of e.reverse().faces)t.addFace(n.shapes);return t},$Ro=t=>{if(t.shape==="rect")return LO(t.center,t.width,t.height,0,t.rotation);if(t.shape==="polygon")return Qw(new Ip(t.points.map(n=>new Gc(n.x,n.y))));const e=vkt(t.brep_shape.outer_ring);for(const n of t.brep_shape.inner_rings)x$(e,vkt(n));return e},qRo=t=>{if(t.shape==="polygon")return Qw(new Ip(t.points.map(n=>new Gc(n.x,n.y))));if(t.shape==="circle")return y$(t,t.radius);const e=t.shape==="pill"||t.shape==="rotated_pill"?t.radius:t.corner_radius??t.rect_border_radius??0;return LO(t,t.width,t.height,e,"ccw_rotation"in t?t.ccw_rotation:0)},HMe=(t,e,n)=>x$(y$(t,e/2),y$(t,n/2)),XRo=(t,e=0)=>{if(t.shape==="circle")return HMe(t,t.outer_diameter,t.hole_diameter);if("outer_width"in t)return x$(LO(t,t.outer_width,t.outer_height,Math.min(t.outer_width,t.outer_height)/2,t.ccw_rotation),LO(t,t.hole_width,t.hole_height,Math.min(t.hole_width,t.hole_height)/2,t.ccw_rotation));const n={x:t.x+t.hole_offset_x,y:t.y+t.hole_offset_y},o=t.shape==="hole_with_polygon_pad"?LMe(Qw(new Ip(t.pad_outline.map(i=>new Gc(i.x,i.y)))),t,t.ccw_rotation??e):LO(t,t.rect_pad_width,t.rect_pad_height,t.rect_border_radius,"rect_ccw_rotation"in t?t.rect_ccw_rotation:0);if(t.shape==="circular_hole_with_rect_pad"||t.shape==="hole_with_polygon_pad"&&t.hole_shape==="circle"){if(t.hole_diameter===void 0)throw new Error("Circular plated hole requires hole_diameter");return x$(o,y$(n,t.hole_diameter/2))}if(!("hole_width"in t)||t.hole_width===void 0||t.hole_height===void 0)throw new Error("Slotted plated hole requires hole_width and hole_height");return x$(o,LO(n,t.hole_width,t.hole_height,Math.min(t.hole_width,t.hole_height)/2,"hole_ccw_rotation"in t?t.hole_ccw_rotation:t.shape==="hole_with_polygon_pad"?t.ccw_rotation??e:0))},ZRo=(t,e,n,o=n)=>{const i=Math.hypot(e.x-t.x,e.y-t.y),r=n/2,s=o/2;if(i<=Math.abs(s-r))return y$(r>=s?t:e,Math.max(r,s));const a=Math.atan2(e.y-t.y,e.x-t.x),A=Math.acos((r-s)/i),c=new T8(new Gc(t.x,t.y),r,a+A,a-A,!0),l=new T8(new Gc(e.x,e.y),s,a-A,a+A,!0);return Qw(new Ip([c,new _D(c.end,l.start),l,new _D(l.end,c.start)]))},eTo=(t,e,n=1e-7)=>t.vertices.some(o=>e.contains(o))||e.vertices.some(o=>t.contains(o))||t.distanceTo(e)[0]<=n,OMe=1e6,E$=1e-7*OMe,wkt=(t,e)=>t.route_type==="wire"?{point:t,layer:t.layer}:t.route_type==="via"?{point:t,layer:e==="start"?t.from_layer:t.to_layer}:{point:t[e],layer:e==="start"?t.start_layer:t.end_layer},tTo=(t,e=new Set)=>{const n=Vf(t),o=t.filter(f=>f.type==="pcb_copper_pour"),i=new Set(o.flatMap(f=>f.source_net_id?[n.getNetConnectedToId(f.source_net_id)??f.source_net_id]:[])),r=[],s=f=>{i.has(f.netId)&&!f.polygon.isEmpty()&&r.push({...f,polygon:f.polygon.scale(OMe,OMe)})},a=new Map(t.filter(f=>f.type==="pcb_component").map(f=>[f.pcb_component_id,f])),A=t.filter(f=>f.type==="pcb_via"),c=t.find(f=>f.type==="pcb_board");for(const f of o)f.source_net_id&&s({polygon:$Ro(f),layers:[f.layer],netId:n.getNetConnectedToId(f.source_net_id)??f.source_net_id,isTerminal:!1,pourId:f.pcb_copper_pour_id});for(const f of t)if(f.type==="pcb_smtpad"){const I=n.getNetConnectedToId(f.pcb_smtpad_id);I&&i.has(I)&&s({polygon:qRo(f),layers:[f.layer],netId:I,isTerminal:!!f.pcb_port_id})}else if(f.type==="pcb_plated_hole"){const I=n.getNetConnectedToId(f.pcb_plated_hole_id);I&&i.has(I)&&s({polygon:XRo(f,f.pcb_component_id?a.get(f.pcb_component_id)?.rotation:0),layers:f.layers,netId:I,isTerminal:!!f.pcb_port_id})}else if(f.type==="pcb_via"){const I=n.getNetConnectedToId(f.pcb_via_id);I&&i.has(I)&&s({polygon:HMe(f,f.outer_diameter,f.hole_diameter),layers:f.layers,netId:I,isTerminal:!e.has(f.pcb_via_id),viaId:f.pcb_via_id})}else if(f.type==="pcb_trace"){const I=n.getNetConnectedToId(f.pcb_trace_id);if(!I||!i.has(I))continue;for(let C=0;C<f.route.length;C++){const y=f.route[C];if(y.route_type==="via"){const w=A.find(M=>M.x===y.x&&M.y===y.y&&M.layers.includes(y.from_layer)&&M.layers.includes(y.to_layer));s({polygon:HMe(y,w?.outer_diameter??y.outer_diameter??c?.min_via_pad_diameter??.3,w?.hole_diameter??y.hole_diameter??c?.min_via_hole_diameter??.2),layers:w?.layers??lw({fromLayer:y.from_layer,toLayer:y.to_layer,layerCount:c?.num_layers??2}),netId:I,isTerminal:!1})}const x=f.route[C+1];if(!x)continue;const E=wkt(y,"end"),B=wkt(x,"start");if(E.layer!==B.layer)continue;const S=y.route_type==="via"?x.route_type==="via"?void 0:x.width:y.width;if(S===void 0)continue;const Q=f.route_thickness_mode==="interpolated"&&x.route_type!=="via"?x.width:S;s({polygon:ZRo(E.point,B.point,S,Q),layers:[E.layer],netId:I,isTerminal:!1})}}const l=new Set,u=new Set;if(r.length===0)return{floatingPourIds:l,floatingViaIds:u};const g=r.map((f,I)=>I),h=f=>{for(;g[f]!==f;)g[f]=g[g[f]],f=g[f];return f},d=r.map(f=>f.polygon.box),p=new UH(r.length);for(const f of d)p.add(f.xmin,f.ymin,f.xmax,f.ymax);p.finish();for(const[f,I]of r.entries()){const C=d[f];for(const y of p.search(C.xmin-E$,C.ymin-E$,C.xmax+E$,C.ymax+E$)){if(y<=f||h(f)===h(y))continue;const x=r[y];I.netId!==x.netId||!I.layers.some(E=>x.layers.includes(E))||eTo(I.polygon,x.polygon,E$)&&(g[h(y)]=h(f))}}const m=new Set(r.flatMap(f=>f.isTerminal?[f.netId]:[])),_=new Set(r.flatMap((f,I)=>f.isTerminal?[h(I)]:[]));for(const[f,I]of r.entries())!m.has(I.netId)||_.has(h(f))||(I.pourId&&l.add(I.pourId),I.viaId&&u.add(I.viaId));return{floatingPourIds:l,floatingViaIds:u}},nTo=t=>{if(!t.root||t.root.pcbDisabled)return;const{db:e}=t.root,n=e.subtree({subcircuit_id:t.subcircuit_id}).toArray();if(e.pcb_autorouting_error.list().length>0||!n.some(r=>r.type==="pcb_copper_pour"))return;const{floatingPourIds:o,floatingViaIds:i}=tTo(n,t._generatedStitchingViaIds);for(const r of o)e.pcb_copper_pour.delete(r);for(const r of i)t._generatedStitchingViaIds.has(r)&&e.pcb_via.delete(r);for(const r of e.pcb_trace.list())r.route.some(s=>"copper_pour_id"in s&&s.copper_pour_id&&o.has(s.copper_pour_id))&&e.pcb_trace.update(r.pcb_trace_id,{route:r.route.map(s=>{if(!("copper_pour_id"in s)||!s.copper_pour_id||!o.has(s.copper_pour_id))return s;const{copper_pour_id:a,is_inside_copper_pour:A,...c}=s;return c})})},Pkt=t=>{t._pcbTraceRenderWaitingForPlacementChecks&&(t.renderPhaseStates.PcbTraceRender.initialized=!1,t.renderPhaseStates.PcbTraceRender.dirty=!1,t._pcbTraceRenderWaitingForPlacementChecks=!1);for(const e of t.children)Pkt(e)},oTo=t=>{if(t.root?.pcbDisabled)return;const e=t.root?.platform?.placementDrcChecksDisabled??t.getInheritedProperty("placementDrcChecksDisabled"),n=t.root?.platform?.drcChecksDisabled??t.getInheritedProperty("drcChecksDisabled");if(t._pcbPlacementDrcErrorCount=null,t._pcbPlacementDrcCheckError=null,t._pcbPlacementDrcChecksPending=!1,e||n){t._pcbPlacementDrcErrorCount=0;return}const{db:o}=t.root,i=o.subtree({subcircuit_id:t.subcircuit_id}).toArray(),r=o.toArray();t._pcbPlacementDrcChecksPending=!0,t._queueAsyncEffect("board:pre-route-placement-checks",async()=>{try{const s=await Wmt(i,{consolidateOverlaps:!1}),a=Bse(i,s.filter(c=>!t._isExpectedCastellatedHoleDrcError(c))),A=a.filter(c=>!r.some(l=>l.type===c.type&&"message"in l&&l.message===c.message));o.insertAll(A),t._pcbPlacementDrcErrorCount=a.filter(c=>c.type.endsWith("_error")).length}catch(s){t._pcbPlacementDrcCheckError=s instanceof Error?s.message:String(s)}finally{t._pcbPlacementDrcChecksPending=!1,Pkt(t)}})},iTo=1e-6,rTo=t=>t?Array.isArray(t)?t:[t]:[],sTo=class h4n extends Pb{outlinePointIndex;holeDiameter;padDiameter;port;trace;static fromBoardOutline(e){return(e??[]).flatMap((n,o)=>n.isCastellatedHole?[new h4n(n,o)]:[])}constructor(e,n){const o=`castellated_hole_${n+1}`,i=rTo(e.connectsTo),r=lt.parse(e.holeDiameter),s=lt.parse(e.padDiameter);super({shape:"circle",holeDiameter:r,outerDiameter:s,portHints:[o]}),this.outlinePointIndex=n,this.holeDiameter=r,this.padDiameter=s,this.port=i.length>0?new Pu({name:o}):null,this.trace=this.port?new t1({path:[`port.${o}`,...i],displayName:`Castellated hole ${n+1} connectivity`}):null}_getParentBoard(){if(this.parent?.componentName!=="Board")throw new Error("A board castellated hole must be a direct board child");return this.parent}_getPositionFromBoardOutline(){const e=this._getParentBoard(),o=(e.pcb_board_id?e.root?.db.pcb_board.get(e.pcb_board_id):null)?.outline?.[this.outlinePointIndex];if(!o)throw new Error(`Missing emitted board outline point ${this.outlinePointIndex}`);return o}_getGlobalPcbPositionBeforeLayout(){return this._getPositionFromBoardOutline()}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:e}=this.root,n=this._getPositionFromBoardOutline(),o=e.pcb_plated_hole.insert({shape:"circle",outer_diameter:this.padDiameter,hole_diameter:this.holeDiameter,...n,layers:this.getAvailablePcbLayers(),port_hints:this.getNameAndAliases(),subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0});this.pcb_plated_hole_id=o.pcb_plated_hole_id}syncPositionToBoardOutline(){this.pcb_plated_hole_id&&this._setPositionFromLayout(this._getPositionFromBoardOutline())}removePcbPrimitiveRender(){const{db:e}=this.root;this.pcb_plated_hole_id&&(e.pcb_plated_hole.delete(this.pcb_plated_hole_id),this.pcb_plated_hole_id=null),this.matchedPort?.pcb_port_id&&(e.pcb_port.delete(this.matchedPort.pcb_port_id),this.matchedPort.pcb_port_id=null)}isExpectedBoardEdgeDrcError(e){if(!this.pcb_plated_hole_id)return!1;if(e.type==="pcb_placement_error")return e.pcb_placement_error_id===`copper_too_close_to_board_edge_${this.pcb_plated_hole_id}`;if(e.type!=="pcb_trace_error"||!e.pcb_trace_error_id.startsWith("trace_too_close_to_board_"))return!1;const n=e.pcb_trace_error_id.match(/_segment_(\d+)$/);if(!n)return!1;const o=this.root?.db.pcb_trace.get(e.pcb_trace_id),i=Number(n[1]),r=[o?.route[i],o?.route[i+1]].flatMap(a=>a&&"x"in a&&"y"in a?[{x:a.x,y:a.y}]:[]),s=this.root?.db.pcb_plated_hole.get(this.pcb_plated_hole_id);return s?r.some(a=>Math.hypot(a.x-s.x,a.y-s.y)<=iTo):!1}},aTo=.01,ATo=.15,Mkt=(t,e,n)=>{const o=t/2,i=e/2,r=Math.min(n,o,i);if(r<aTo)return[{x:-o,y:-i},{x:o,y:-i},{x:o,y:i},{x:-o,y:i}];const a=Math.max(1,Math.ceil(Math.PI/2*r/.1)),A=Math.PI/2/a,c=[];c.push({x:-o+r,y:-i}),c.push({x:o-r,y:-i});for(let l=1;l<=a;l++){const u=-Math.PI/2+l*A;c.push({x:o-r+r*Math.cos(u),y:-i+r+r*Math.sin(u)})}c.push({x:o,y:i-r});for(let l=1;l<=a;l++){const u=0+l*A;c.push({x:o-r+r*Math.cos(u),y:i-r+r*Math.sin(u)})}c.push({x:-o+r,y:i});for(let l=1;l<=a;l++){const u=Math.PI/2+l*A;c.push({x:-o+r+r*Math.cos(u),y:i-r+r*Math.sin(u)})}c.push({x:-o,y:-i+r});for(let l=1;l<=a;l++){const u=Math.PI+l*A;c.push({x:-o+r+r*Math.cos(u),y:-i+r+r*Math.sin(u)})}return c},wB=class extends A6{pcb_board_id=null;source_board_id=null;_drcChecksComplete=!1;_drcChecksInProgress=!1;_connectedSchematicPortPairs=new Set;_panelPositionOffset=null;_castellatedHoles;constructor(t){super(t),this._castellatedHoles=sTo.fromBoardOutline(this._parsedProps.outline);for(const e of this._castellatedHoles)e.port&&this.add(e.port),this.add(e),e.trace&&this.add(e.trace)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:nlt}}get boardThickness(){return this._parsedProps.thickness??1.4}get allLayers(){return Owe(this._parsedProps.layers??2)}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}_computePcbGlobalTransformBeforeLayout(){if(this._panelPositionOffset){const t=this.parent?._computePcbGlobalTransformBeforeLayout?.()??{a:1,b:0,c:0,d:1,e:0,f:0};return D0(t,M0(this._panelPositionOffset.x,this._panelPositionOffset.y))}return super._computePcbGlobalTransformBeforeLayout()}_getBoardCalcVariables(){const{_parsedProps:t}=this;if((t.width==null||t.height==null)&&!t.outline)return{};const n=this.pcb_board_id?this.root?.db.pcb_board.get(this.pcb_board_id):null;let o=n?.width??t.width,i=n?.height??t.height;if((o==null||i==null)&&t.outline?.length){const l=Oh(t.outline);l&&(o??=l.maxX-l.minX,i??=l.maxY-l.minY)}const{pcbX:r,pcbY:s}=this.getResolvedPcbPositionProp(),a=n?.center??{x:r+(t.outlineOffsetX??0),y:s+(t.outlineOffsetY??0)},A=o??0,c=i??0;return{"board.minX":a.x-A/2,"board.maxX":a.x+A/2,"board.minY":a.y-c/2,"board.maxY":a.y+c/2}}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalPcbPositionBeforeLayout(),o=t.pcb_board.get(this.pcb_board_id);if(o?.width&&o?.height||o?.outline&&o.outline.length>0)return;let i=1/0,r=1/0,s=-1/0,a=-1/0;const A=uPe(t,this.subcircuit_id),c=new Set([this.subcircuit_id,...A]),l=t.pcb_component.list().filter(x=>x.subcircuit_id&&c.has(x.subcircuit_id)),u=t.pcb_group.list().filter(x=>x.subcircuit_id&&c.has(x.subcircuit_id));let g=!1;const h=(x,E,B)=>{E===0||B===0||(g=!0,i=Math.min(i,x.x-E/2),r=Math.min(r,x.y-B/2),s=Math.max(s,x.x+E/2),a=Math.max(a,x.y+B/2))};for(const x of l)h(x.center,x.width,x.height);for(const x of u){let E=x.width??0,B=x.height??0;if(x.outline&&x.outline.length>0){const S=Oh(x.outline);S&&(E=S.maxX-S.minX,B=S.maxY-S.minY)}h(x.center,E,B)}if(e.boardAnchorPosition){const{x,y:E}=e.boardAnchorPosition;i=Math.min(i,x),r=Math.min(r,E),s=Math.max(s,x),a=Math.max(a,E)}const d=2,p=g?s-i+d*2:0,m=g?a-r+d*2:0,_={x:g?(i+s)/2+(e.outlineOffsetX??0):(e.outlineOffsetX??0)+n.x,y:g?(r+a)/2+(e.outlineOffsetY??0):(e.outlineOffsetY??0)+n.y},f=e.width??p,I=e.height??m;let C=e.outline;!C&&e.borderRadius!=null&&f>0&&I>0&&(C=Mkt(f,I,e.borderRadius));const y={width:f,height:I,center:_};C&&(y.outline=C.map(x=>({x:x.x+(e.outlineOffsetX??0),y:x.y+(e.outlineOffsetY??0)}))),t.pcb_board.update(this.pcb_board_id,y)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){const t=this.root?.platform;if(!t?.printBoardInformationToSilkscreen)return;const e=this.root.db.pcb_board.get(this.pcb_board_id);if(!e)return;const n=[];if(t.projectName&&n.push(t.projectName),t.version&&n.push(`v${t.version}`),t.url&&n.push(t.url),n.length===0)return;const o=n.join(`
`),s={x:e.center.x+e.width/2-.25,y:e.center.y-e.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:o,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:s})}doInitialSourceRender(){const t=this.getDescendants().find(o=>o.lowercaseComponentName==="board");if(t)throw new Error(`Nested boards are not supported: found board "${t.name}" inside board "${this.name}"`);super.doInitialSourceRender();const{db:e}=this.root,n=e.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=n.source_board_id}getSubcircuitPropHash(){return Bkt(this)}doInitialRenderIsolatedSubcircuits(){Ckt(this)}doInitialInflateSubcircuitCircuitJson(){const t=this._isolatedCircuitJson;if(t){this._isInflatedFromCircuitJson=!0,this._isolatedCircuitJson=null,Hue(this,t,[]);return}const{circuitJson:e,children:n}=this._parsedProps;e&&(this._isInflatedFromCircuitJson=!0),Hue(this,e,n)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,o=e.circuitJson?.find(x=>x.type==="pcb_board"),i=this.props,r=i.isViaInPadAllowed??o?.is_via_in_pad_allowed,s=i.allowBlindAndBuriedVias??o?.allow_blind_and_buried_vias;let a=e.width??o?.width??0,A=e.height??o?.height??0;const c=this._getGlobalPcbPositionBeforeLayout();let l={x:c.x+(e.outlineOffsetX??0),y:c.y+(e.outlineOffsetY??0)};const{boardAnchorPosition:u,boardAnchorAlignment:g}=e;if(u&&(l=u8o({boardAnchorPosition:u,boardAnchorAlignment:g??"center",width:a,height:A})),e.outline){const x=e.outline.map(M=>M.x),E=e.outline.map(M=>M.y),B=Math.min(...x),S=Math.max(...x),Q=Math.min(...E),w=Math.max(...E);a=S-B,A=w-Q}let h=e.outline;!h&&e.borderRadius!=null&&a>0&&A>0&&(h=Mkt(a,A,e.borderRadius));let d={x:0,y:0};if(h&&h.length>0&&(this.parent?.lowercaseComponentName==="panel"||this.parent?.lowercaseComponentName==="subpanel")){const x=Oh(h);if(x){const E=(x.minX+x.maxX)/2,B=(x.minY+x.maxY)/2;d={x:l.x-E,y:l.y-B}}}const p=this.getSubcircuit()._parsedProps,m=this.getInheritedMergedProperty("pcbStyle"),_=$N(m),f=p.minViaHoleDiameter??(m?.viaHoleDiameter!==void 0?_.holeDiameter:void 0),I=f??EB.min_via_hole_diameter,C=p.minViaPadDiameter??(m?.viaPadDiameter!==void 0?_.padDiameter:f!==void 0?f+ATo:EB.min_via_pad_diameter),y=t.pcb_board.insert({source_board_id:this.source_board_id,center:l,thickness:this.boardThickness,num_layers:this.allLayers.length,width:a,height:A,outline:h?.map(x=>({x:x.x+(e.outlineOffsetX??0)+d.x,y:x.y+(e.outlineOffsetY??0)+d.y})),material:e.material,...r!==void 0&&{is_via_in_pad_allowed:r},...s!==void 0&&{allow_blind_and_buried_vias:s},...e.solderMaskColor!==void 0&&{solder_mask_color:e.solderMaskColor},...e.silkscreenColor!==void 0&&{silkscreen_color:e.silkscreenColor},min_trace_width:p.minTraceWidth??EB.min_trace_width,min_via_hole_diameter:I,min_via_pad_diameter:C,min_via_hole_edge_to_via_hole_edge_clearance:p.minViaHoleEdgeToViaHoleEdgeClearance??EB.min_via_hole_edge_to_via_hole_edge_clearance,min_via_edge_to_pad_edge_clearance:p.minViaEdgeToPadEdgeClearance??EB.min_via_edge_to_pad_edge_clearance,min_trace_to_pad_edge_clearance:p.minTraceToPadEdgeClearance??EB.min_trace_to_pad_edge_clearance,min_pad_edge_to_pad_edge_clearance:p.minPadEdgeToPadEdgeClearance??EB.min_pad_edge_to_pad_edge_clearance,min_plated_hole_drill_edge_to_drill_edge_clearance:p.minPlatedHoleDrillEdgeToDrillEdgeClearance??EB.min_plated_hole_drill_edge_to_drill_edge_clearance,min_board_edge_clearance:p.minBoardEdgeClearance??EB.min_board_edge_clearance});this.pcb_board_id=y.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){const{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}doInitialPcbDesignRuleChecks(){super.doInitialPcbDesignRuleChecks(),this.updatePcbDesignRuleChecks()}doInitialPcbPlacementDesignRuleChecks(){oTo(this)}doInitialPcbImplicitCopperPourRender(){jRo(this)}_generatedStitchingViaIds=new Set;doInitialPcbCopperPourCleanup(){nTo(this)}updatePcbDesignRuleChecks(){const{db:t}=this.root,e=this.root?.pcbRoutingDisabled||this.getInheritedProperty("routingDisabled"),n=this.root?.pcbDisabled,o=this.root?.schematicDisabled,i=this.root?.platform?.drcChecksDisabled??this.getInheritedProperty("drcChecksDisabled"),r=this.root?.platform?.netlistDrcChecksDisabled??this.getInheritedProperty("netlistDrcChecksDisabled"),s=this.getInheritedProperty("pinSpecificationDrcChecksDisabled"),a=this.root?.platform?.placementDrcChecksDisabled??this.getInheritedProperty("placementDrcChecksDisabled"),A=this.root?.platform?.routingDrcChecksDisabled??this.getInheritedProperty("routingDrcChecksDisabled"),c=!i&&!r,l=!i&&!s,u=!i&&!o,g=!i&&!n&&!a,h=!i&&!n&&!e&&!A,d=this.root?.platform?.fabricatorEngine,p=this._parsedProps.fabricatorPreset,m=!i&&!n&&!!d&&!!p;if((h||m)&&this._hasIncompleteAsyncEffectsInSubtreeForPhase("PcbTraceRender"))return;const _=this._hasTracesToRoute();if((h||m)&&_&&!this._areChildSubcircuitsRouted()||this._drcChecksComplete||this._drcChecksInProgress)return;const f=async y=>{const x=[];if(m&&d&&p&&this.pcb_board_id&&x.push(Promise.resolve(d.runDrcChecks({circuitJson:y,fabricatorPreset:p,pcbBoardId:this.pcb_board_id}))),h&&x.push(jmt(y).then(B=>B.filter(S=>!this._isExpectedCastellatedHoleDrcError(S)))),g){const B=t.toArray();x.push(Wmt(y,{consolidateOverlaps:!1}).then(S=>Bse(y,S.filter(Q=>!this._isExpectedCastellatedHoleDrcError(Q))).filter(Q=>!B.some(w=>w.type===Q.type&&"message"in w&&w.message===Q.message))))}if(c&&x.push(y$n(y)),l&&x.push(E$n(y)),u&&x.push(x$n(y)),!i)for(const B of this.selectAll("drccheck"))x.push(B.runCustomDrcCheck(y));const E=await Promise.all(x);t.insertAll(Bse(y,Ymt(E.flat())))},C=t.subtree({subcircuit_id:this.subcircuit_id}).toArray();this._drcChecksInProgress=!0,this._queueAsyncEffect("board:drc-checks",async()=>{try{await f(C),this._drcChecksComplete=!0}finally{this._drcChecksInProgress=!1}})}runRenderPhaseForChildren(t){this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t}),super.runRenderPhaseForChildren(t)}_repositionOnPcb(t){const{db:e}=this.root,n=this.pcb_board_id?e.pcb_board.get(this.pcb_board_id):null,o=n?.center;if(!o){this.pcb_board_id&&e.pcb_board.update(this.pcb_board_id,{center:t});return}const i=t.x-o.x,r=t.y-o.y;if(!(Math.abs(i)<1e-6&&Math.abs(r)<1e-6)&&this.pcb_board_id&&(e.pcb_board.update(this.pcb_board_id,{center:t}),n?.outline)){const s=Oh(n.outline);if(s){const a={x:(s.minX+s.maxX)/2,y:(s.minY+s.maxY)/2},A=t.x-a.x,c=t.y-a.y,l=n.outline.map(u=>({x:u.x+A,y:u.y+c}));e.pcb_board.update(this.pcb_board_id,{outline:l});for(const u of this._castellatedHoles)u.syncPositionToBoardOutline()}}}_isExpectedCastellatedHoleDrcError(t){return this._castellatedHoles.some(e=>e.isExpectedBoardEdgeDrcError(t))}},Dkt=class extends A6{constructor(t){super({...t,subcircuit:!0})}getSubcircuitPropHash(){return Bkt(this)}doInitialRenderIsolatedSubcircuits(){Ckt(this)}doInitialCreateNetsFromProps(){super.doInitialCreateNetsFromProps(),this._createTracesForExposedConnections()}_createTracesForExposedConnections(){const t=this._getNetNamesToExpose();if(!t?.length)return;const e=this.parent?.getSubcircuit?.();if(e&&this.name)for(const n of t){const o=cTo(n),i=`> net.${o}`,r=`.${this.name} > net.${o}`;if(e.children.find(c=>c instanceof Qb&&c._parsedProps.name===o)||e.add(new Qb({name:o})),e.children.find(c=>{if(!(c instanceof t1)||!c._exposesSubcircuitConnection)return!1;const l=c._parsedProps;return l.from===r&&l.to===i}))continue;const A=new t1({from:r,to:i,displayName:o});A._exposesSubcircuitConnection=!0,e.add(A)}}_getNetNamesToExpose(){const t=this._parsedProps.exposedNets??[];if(!this._parsedProps.exposeNets)return t;const e=this.selectAll("net").filter(n=>n instanceof Qb&&n.getSubcircuit()===this).map(n=>n._parsedProps.name);return Array.from(new Set([...t,...e]))}doInitialInflateSubcircuitCircuitJson(){const t=this._isolatedCircuitJson;if(t){this._isInflatedFromCircuitJson=!0,this._isolatedCircuitJson=null,Hue(this,t,[]);return}const{circuitJson:e,children:n}=this._parsedProps;e&&(this._isInflatedFromCircuitJson=!0),Hue(this,e,n)}},cTo=t=>t.startsWith("net.")?t.slice(4):t,lTo=class extends Dkt{pcb_board_id=null;get config(){return{componentName:"MountedBoard",zodProps:kPn}}get boardThickness(){return 1.4}get allLayers(){return["top","bottom"]}_connectedSchematicPortPairs=new Set;_getBoardCalcVariables(){return this._findCarrierBoard()?._getBoardCalcVariables()??{}}_findCarrierBoard(){let t=this.parent;for(;t;){if(t instanceof wB)return t;t=t.parent}return null}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalPcbPositionBeforeLayout(),o=t.pcb_board.insert({center:{x:n.x,y:n.y},width:e.width??0,height:e.height??0,is_mounted_to_carrier_board:!0});this.pcb_board_id=o.pcb_board_id}doInitialPcbBoardAutoSize(){if(!this.pcb_board_id||!this.root)return;const t=this._findCarrierBoard();t?.pcb_board_id&&this.root.db.pcb_board.update(this.pcb_board_id,{carrier_pcb_board_id:t.pcb_board_id})}},Nkt=5,GMe=2,Rkt=(t,e)=>{const{gapLength:n,cutoutWidth:o,mouseBites:i,mouseBiteHoleDiameter:r,mouseBiteHoleSpacing:s}=e,a=[],A=[];if(t.length<2)return{tabCutouts:a,mouseBiteHoles:A};const c=new Ip(t.map(u=>by(u.x,u.y)));let l;if(t.length>2){const u=by(t[0].x,t[0].y),g=by(t[1].x,t[1].y),h=vF(u,g).normalize(),d=h.rotate(Math.PI/2),m=u.translate(h.multiply(KBe(u,g).length/2)).translate(d.multiply(.01));l=c.contains(m)}else l=c.area()>0;for(let u=0;u<t.length;u++){const g=t[u],h=t[(u+1)%t.length];if(!g||!h)continue;const d=by(g.x,g.y),p=by(h.x,h.y),m=KBe(d,p),_=m.length;if(_<1e-6)continue;const f=vF(d,p),I=f.normalize();let C=I.rotate(Math.PI/2);const x=m.middle().translate(C.multiply(.01));c.contains(x)&&(C=C.multiply(-1));const E=2,B=E*r+(E-1)*s;let S;i?S=B:S=n,S=Math.min(S,_*.9);const Q=(_-S)/2,w=Q+S;if(i){const Y=r+s;if(S>=B&&Y>0){const W=(S-B)/2+r/2,te=Q+W;for(let j=0;j<E;j++){const J=te+j*Y,oe=d.translate(I.multiply(J));A.push({x:oe.x,y:oe.y})}}}const M=t[(u-1+t.length)%t.length],k=t[(u+2)%t.length];let R=0,F=0;if(M&&k){const Y=vF(by(M.x,M.y),d),W=Y.cross(f),te=l?W>1e-9:W<-1e-9,j=vF(p,by(k.x,k.y)),J=f.cross(j),oe=l?J>1e-9:J<-1e-9;if(te){let ie=Y.angleTo(f);ie>Math.PI&&(ie=2*Math.PI-ie),R=o*Math.tan(ie/2)}else R=0;if(oe){let ie=f.angleTo(j);ie>Math.PI&&(ie=2*Math.PI-ie),F=o*Math.tan(ie/2)}else F=0}const O=S<1e-6?[{start:0-R,end:_+F}]:[{start:0-R,end:Q},{start:w,end:_+F}],U=C.multiply(o);for(const Y of O){const W=Y.end-Y.start;if(W<1e-6)continue;const j=d.translate(I.multiply(Y.start+W/2)).translate(U.multiply(.5)),J=W,oe=o,ie=I.slope*180/Math.PI;a.push({type:"pcb_cutout",shape:"rect",center:{x:j.x,y:j.y},width:J,height:oe,rotation:ie,corner_radius:o/2})}}return{tabCutouts:a,mouseBiteHoles:A}};function uTo(t,e){const n=[],o=[];let{tabWidth:i,tabLength:r,mouseBites:s}=e;const a=[];for(const g of t)if(g.width&&g.height)a.push(Math.min(g.width,g.height));else if(g.outline&&g.outline.length>0){const h=new Ip(g.outline.map(p=>by(p.x,p.y))),d=Math.abs(h.area());d>0&&a.push(Math.sqrt(d))}if(a.length>0){const h=Math.min(...a)/20;i=Math.min(i,GMe*Math.max(h,.3)),r=Math.min(r,Nkt*Math.max(h,.3))}const A=t.map(g=>{if((!g.outline||g.outline.length===0)&&g.width&&g.height){const h=g.width/2,d=g.height/2;return{...g,outline:[{x:g.center.x-h,y:g.center.y-d},{x:g.center.x+h,y:g.center.y-d},{x:g.center.x+h,y:g.center.y+d},{x:g.center.x-h,y:g.center.y+d}]}}return g});for(const g of A)if(g.outline&&g.outline.length>0){const h=i*.45,d=h*.1,p=Rkt(g.outline,{gapLength:r,cutoutWidth:i,mouseBites:s,mouseBiteHoleDiameter:h,mouseBiteHoleSpacing:d});n.push(...p.tabCutouts),o.push(...p.mouseBiteHoles)}const c=n.map((g,h)=>({...g,pcb_cutout_id:`panel_tab_${h}`})),l=i*.45,u=o.map((g,h)=>({type:"pcb_hole",pcb_hole_id:`panel_mouse_bite_${h}`,hole_shape:"circle",hole_diameter:l,x:g.x,y:g.y}));return{tabCutouts:c,mouseBiteHoles:u}}function gTo(t,e){return t.map(i=>{if((!i.outline||i.outline.length===0)&&i.width&&i.height){const r=i.width/2,s=i.height/2;return{...i,outline:[{x:i.center.x-r,y:i.center.y-s},{x:i.center.x+r,y:i.center.y-s},{x:i.center.x+r,y:i.center.y+s},{x:i.center.x-r,y:i.center.y+s}]}}return i}).flatMap(i=>{if(!i.outline||i.outline.length===0)return[];const{tabCutouts:r}=Rkt(i.outline,{gapLength:0,cutoutWidth:e.cutoutWidth,mouseBites:!1,mouseBiteHoleDiameter:0,mouseBiteHoleSpacing:0});return r.map(s=>({...s,pcb_board_id:i.pcb_board_id}))}).map((i,r)=>({...i,pcb_cutout_id:`panel_outline_routing_cutout_${r}`}))}var Gue=t=>{const e=t._parsedProps;let n=e.width!=null?lt.parse(e.width):void 0,o=e.height!=null?lt.parse(e.height):void 0;if((n===void 0||o===void 0)&&e.outline?.length){const i=Oh(e.outline);i&&(n??=i.maxX-i.minX,o??=i.maxY-i.minY)}if((n===void 0||o===void 0)&&e.circuitJson?.length){const i=e.circuitJson.find(r=>r.type==="pcb_board");i&&(n??=i.width,o??=i.height)}return{width:n??0,height:o??0}};function dTo({items:t,db:e,row:n,col:o,cellWidth:i,cellHeight:r,boardGap:s,availablePanelWidth:a,availablePanelHeight:A}){const c=t.map(E=>{const B=hTo(E,e);return{item:E,width:B.width,height:B.height}}).filter(E=>!(E.width===0&&E.height===0));if(c.length===0)return{positions:[],gridWidth:0,gridHeight:0};let l,u;const g=i?lt.parse(i):0,h=r?lt.parse(r):0;if(o!==void 0)l=o,u=n??Math.ceil(c.length/l);else if(n!==void 0)u=n,l=Math.ceil(c.length/u);else if(a!==void 0&&A!==void 0){const E=Math.max(...c.map(w=>w.width),g),B=Math.max(...c.map(w=>w.height),h),S=Math.max(1,Math.floor((a+s)/(E+s))),Q=Math.max(1,Math.floor((A+s)/(B+s)));l=S,u=Math.ceil(c.length/l),u>Q&&(u=Q,l=Math.ceil(c.length/u),l>S&&(l=S,u=Math.ceil(c.length/l))),l=Math.max(1,l),u=Math.max(1,u)}else l=Math.ceil(Math.sqrt(c.length)),u=Math.ceil(c.length/l);const d=Array(l).fill(0),p=Array(u).fill(0);c.forEach((E,B)=>{const S=B%l,Q=Math.floor(B/l);Q<p.length&&E.height>p[Q]&&(p[Q]=E.height),S<d.length&&E.width>d[S]&&(d[S]=E.width)});for(let E=0;E<d.length;E++)d[E]=Math.max(d[E],g);for(let E=0;E<p.length;E++)p[E]=Math.max(p[E],h);const m=d.reduce((E,B)=>E+B,0)+(l>1?(l-1)*s:0),_=p.reduce((E,B)=>E+B,0)+(u>1?(u-1)*s:0),f=-m/2,I=-_/2,C=[f];for(let E=1;E<l;E++)C.push(C[E-1]+d[E-1]+s);const y=[I];for(let E=1;E<u;E++)y.push(y[E-1]+p[E-1]+s);const x=[];return c.forEach((E,B)=>{const S=B%l,Q=Math.floor(B/l);if(Q>=y.length||S>=C.length)return;const w=C[S]+d[S]/2,M=y[Q]+p[Q]/2;x.push({item:E.item,pos:{x:w,y:M}})}),{positions:x,gridWidth:m,gridHeight:_}}function hTo(t,e){if(t.componentName==="Board"){const n=t;if(e&&n.pcb_board_id){const o=e.pcb_board.get(n.pcb_board_id);if(o?.width!==void 0&&o?.height!==void 0)return{width:o.width,height:o.height}}return Gue(n)}if(t.componentName==="Subpanel"){const n=t,o=n._parsedProps;if(o.width!==void 0&&o.height!==void 0)return{width:lt.parse(o.width),height:lt.parse(o.height)};const i=n._getDirectBoardChildren();if(i.length===0){const a=n._getAllBoardInstances();if(a.length===0)return{width:0,height:0};let A=1/0,c=1/0,l=-1/0,u=-1/0;for(const g of a){const h=Gue(g);if(h.width===0||h.height===0)continue;const d=g._panelPositionOffset??{x:0,y:0};A=Math.min(A,d.x-h.width/2),l=Math.max(l,d.x+h.width/2),c=Math.min(c,d.y-h.height/2),u=Math.max(u,d.y+h.height/2)}return A===1/0?{width:0,height:0}:{width:l-A,height:u-c}}if(i.length===1)return Gue(i[0]);if(n._cachedGridWidth>0&&n._cachedGridHeight>0){const a=lt.parse(o.edgePadding??5);return{width:n._cachedGridWidth+a*2,height:n._cachedGridHeight+a*2}}let r=0,s=0;for(const a of i){const A=Gue(a);r=Math.max(r,A.width),s=Math.max(s,A.height)}return{width:r,height:s}}return{width:0,height:0}}var Tkt=class Wye extends A6{pcb_panel_id=null;_panelizationFeaturesGenerated=!1;get config(){return{componentName:"Subpanel",zodProps:fwn}}get _errorComponentName(){return this.componentName.toLowerCase()}get isGroup(){return!0}get isSubcircuit(){return!0}_getPcbLayoutMode(){return"none"}doInitialSchematicComponentRender(){}doInitialSchematicLayout(){}doInitialSchematicTraceRender(){}add(e){if(e.lowercaseComponentName!=="board"&&e.lowercaseComponentName!=="subpanel")throw new Error(`<${this._errorComponentName}> can only contain <board> or <subpanel> elements`);super.add(e)}_cachedGridWidth=0;_cachedGridHeight=0;_panelPositionOffset=null;_computePcbGlobalTransformBeforeLayout(){if(this._panelPositionOffset){const e=this.parent?._computePcbGlobalTransformBeforeLayout?.()??hC();return D0(e,M0(this._panelPositionOffset.x,this._panelPositionOffset.y))}return super._computePcbGlobalTransformBeforeLayout()}_getAllBoardInstances(){const e=[];for(const n of this.children)n instanceof wB?e.push(n):n instanceof Wye&&e.push(...n._getAllBoardInstances());return e}_containsBoards(){for(const e of this.children)if(e.componentName==="Board"||e.componentName==="Subpanel"&&"_containsBoards"in e&&e._containsBoards())return!0;return!1}_getDirectBoardChildren(){return this.children.filter(e=>e instanceof wB)}doInitialPanelBoardLayout(){if(this.root?.pcbDisabled)return;const e=this._parsedProps.layoutMode??"none",n=this.children.filter(h=>h instanceof wB||h instanceof Wye);if(e!=="none")for(const h of n)h instanceof wB&&h._hasUserDefinedPcbPosition()&&this.root.db.source_property_ignored_warning.insert({source_component_id:h.source_component_id,property_name:"pcbX/pcbY",message:`Board has manual positioning but ${this._errorComponentName} layout mode is "${e}". Manual positioning will be ignored.`,error_type:"source_property_ignored_warning"});if(e==="none"&&n.length>1&&n.filter(d=>!d._hasUserDefinedPcbPosition()).length>1&&this.root.db.pcb_placement_error.insert({error_type:"pcb_placement_error",message:`Multiple boards/subpanels in ${this._errorComponentName} without positions. When layoutMode="none", each item must have explicit positioning. Use layoutMode="grid" for automatic positioning.`}),e!=="grid")return;const o=this._parsedProps.tabWidth??GMe,i=this._parsedProps.boardGap??o;let r,s;const a=this._parsedProps.row!==void 0||this._parsedProps.col!==void 0,A=this._parsedProps.width!==void 0,c=this._parsedProps.height!==void 0;if(!a&&A&&c){const{edgePadding:h,edgePaddingLeft:d,edgePaddingRight:p,edgePaddingTop:m,edgePaddingBottom:_}=this._parsedProps,f=lt.parse(h??5),I=lt.parse(d??f),C=lt.parse(p??f),y=lt.parse(m??f),x=lt.parse(_??f),E=lt.parse(this._parsedProps.width),B=lt.parse(this._parsedProps.height);r=E-I-C,s=B-y-x}const{positions:l,gridWidth:u,gridHeight:g}=dTo({items:n,row:this._parsedProps.row,col:this._parsedProps.col,cellWidth:this._parsedProps.cellWidth,cellHeight:this._parsedProps.cellHeight,boardGap:i,availablePanelHeight:s,availablePanelWidth:r});this._cachedGridWidth=u,this._cachedGridHeight=g;for(const{item:h,pos:d}of l)h._panelPositionOffset=d}doInitialPanelLayout(){if(this.root?.pcbDisabled)return;const{db:e}=this.root;if((this._parsedProps.layoutMode??"none")==="grid"){for(const o of this.children)if(o instanceof wB){if(!o.pcb_board_id||!o._panelPositionOffset)continue;e.pcb_board.update(o.pcb_board_id,{position_mode:"relative_to_panel_anchor",display_offset_x:`${o._panelPositionOffset.x}mm`,display_offset_y:`${o._panelPositionOffset.y}mm`})}else if(o instanceof Wye&&o._panelPositionOffset)for(const i of o._getAllBoardInstances()){if(!i.pcb_board_id)continue;const r=i._panelPositionOffset??{x:0,y:0};e.pcb_board.update(i.pcb_board_id,{position_mode:"relative_to_panel_anchor",display_offset_x:`${o._panelPositionOffset.x+r.x}mm`,display_offset_y:`${o._panelPositionOffset.y+r.y}mm`})}this._updatePanelDimensions()}else{const o=this._getGlobalPcbPositionBeforeLayout();for(const i of this._getDirectBoardChildren()){if(!i.pcb_board_id)continue;const r=e.pcb_board.get(i.pcb_board_id);if(!r)continue;const s=r.center.x-o.x,a=r.center.y-o.y;e.pcb_board.update(i.pcb_board_id,{position_mode:"relative_to_panel_anchor",display_offset_x:`${s}mm`,display_offset_y:`${a}mm`})}}this._generatePanelizationFeatures()}_updatePanelDimensions(){const{db:e}=this.root,n=this._parsedProps.width!==void 0,o=this._parsedProps.height!==void 0,i=this._cachedGridWidth,r=this._cachedGridHeight;if(this.pcb_group_id){if(n&&o)e.pcb_group.update(this.pcb_group_id,{width:lt.parse(this._parsedProps.width),height:lt.parse(this._parsedProps.height)});else if(i>0||r>0){const{edgePadding:s,edgePaddingLeft:a,edgePaddingRight:A,edgePaddingTop:c,edgePaddingBottom:l}=this._parsedProps,u=lt.parse(s??5),g=lt.parse(a??u),h=lt.parse(A??u),d=lt.parse(c??u),p=lt.parse(l??u);e.pcb_group.update(this.pcb_group_id,{width:n?lt.parse(this._parsedProps.width):i+g+h,height:o?lt.parse(this._parsedProps.height):r+d+p})}}}_generatePanelizationFeatures(){if(this._panelizationFeaturesGenerated)return;const{db:e}=this.root,n=this._parsedProps,o=n.panelizationMethod??"none",i=this._getAllBoardInstances();if(o!=="none"){const r=i.map(A=>A.pcb_board_id).filter(A=>!!A),s=e.pcb_board.list().filter(A=>r.includes(A.pcb_board_id));if(s.length===0)return;const a=n.tabWidth??GMe;if(o==="outline_routing"){const A=gTo(s,{cutoutWidth:a});for(const c of A)e.pcb_cutout.insert({...c,pcb_group_id:this.pcb_group_id??void 0,pcb_panel_id:this.pcb_panel_id??void 0})}else{n.boardGap;const{tabCutouts:A,mouseBiteHoles:c}=uTo(s,{tabWidth:a,tabLength:n.tabLength??Nkt,mouseBites:n.mouseBites??!0});for(const l of A)e.pcb_cutout.insert(l);for(const l of c)e.pcb_hole.insert(l)}}this._panelizationFeaturesGenerated=!0}doInitialPcbComponentRender(){if(!this.root?.pcbDisabled){if(!this._containsBoards())throw new Error(`<${this._errorComponentName}> must contain at least one <board>`);super.doInitialPcbComponentRender()}}},pTo=class extends Tkt{get config(){return{componentName:"Panel",zodProps:olt}}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;if(!this._containsBoards())throw new Error(`<${this._errorComponentName}> must contain at least one <board>`);const{db:t}=this.root,e=this._parsedProps,n=t.pcb_panel.insert({width:e.width!==void 0?lt.parse(e.width):0,height:e.height!==void 0?lt.parse(e.height):0,thickness:1.6,center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(e.noSolderMask??!1)});this.pcb_panel_id=n.pcb_panel_id}_updatePanelDimensions(){const{db:t}=this.root,e=this._parsedProps.width!==void 0,n=this._parsedProps.height!==void 0,o=this._cachedGridWidth,i=this._cachedGridHeight;if(this.pcb_panel_id){if(e&&n)t.pcb_panel.update(this.pcb_panel_id,{width:lt.parse(this._parsedProps.width),height:lt.parse(this._parsedProps.height)});else if(o>0||i>0){const{edgePadding:r,edgePaddingLeft:s,edgePaddingRight:a,edgePaddingTop:A,edgePaddingBottom:c}=this._parsedProps,l=lt.parse(r??5),u=lt.parse(s??l),g=lt.parse(a??l),h=lt.parse(A??l),d=lt.parse(c??l);t.pcb_panel.update(this.pcb_panel_id,{width:e?lt.parse(this._parsedProps.width):o+u+g,height:n?lt.parse(this._parsedProps.height):i+h+d})}}}updatePcbComponentRender(){if(this.root?.pcbDisabled||!this.pcb_panel_id)return;const{db:t}=this.root,e=this._parsedProps,n=t.pcb_panel.get(this.pcb_panel_id);t.pcb_panel.update(this.pcb_panel_id,{width:e.width!==void 0?lt.parse(e.width):n?.width,height:e.height!==void 0?lt.parse(e.height):n?.height,center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(e.noSolderMask??!1)})}removePcbComponentRender(){this.pcb_panel_id&&(this.root?.db.pcb_panel.delete(this.pcb_panel_id),this.pcb_panel_id=null)}},mTo=1,Yue=1,_To=t=>{const e=t.route.map(p=>p.x),n=t.route.map(p=>p.y),o=t.traceWidth/2+mTo,i=Math.min(...e)-o,r=Math.max(...e)+o,s=Math.min(...n)-o,a=Math.max(...n)+o,A=[t.feedPoint,...t.secondaryPort?[t.secondaryPort.point]:[]],c=Math.min(...A.map(p=>p.x))-Yue,l=Math.max(...A.map(p=>p.x))+Yue,u=Math.min(...A.map(p=>p.y))-Yue,g=Math.max(...A.map(p=>p.y))+Yue,h=[],d=(p,m,_,f)=>{m<=p||f<=_||h.push({center:{x:(p+m)/2,y:(_+f)/2},width:m-p,height:f-_})};return t.feedKeepoutOpeningDirection==="left"?(d(i,r,g,a),d(i,r,s,u),d(l,r,u,g)):(d(i,c,s,g),d(l,r,s,g),d(i,r,g,a)),h},fTo=t=>{switch(t){case"2.4ghz_quarter_wave_monopole":return{traceWidth:.6,feedPoint:{x:0,y:0},feedKeepoutOpeningDirection:"left",route:[{x:0,y:0},{x:31,y:0}]};case"2.4ghz_meandered_monopole":return{traceWidth:.5,feedPoint:{x:0,y:0},feedKeepoutOpeningDirection:"bottom",route:[{x:0,y:0},{x:0,y:6},{x:3,y:6},{x:3,y:1.5},{x:6,y:1.5},{x:6,y:6},{x:9,y:6},{x:9,y:1.5},{x:12,y:1.5},{x:12,y:6},{x:15,y:6}]};case"2.4ghz_inverted_f":return{traceWidth:.8,feedPoint:{x:0,y:0},feedKeepoutOpeningDirection:"bottom",secondaryPort:{point:{x:-4,y:0},role:"ground"},groundViaPoint:{x:-4,y:0},route:[{x:-4,y:0},{x:-4,y:3},{x:0,y:3},{x:0,y:0},{x:0,y:3},{x:-4,y:3},{x:-4,y:8},{x:22,y:8}]};case"2.4ghz_meandered_inverted_f":return{traceWidth:.5,feedPoint:{x:0,y:0},feedKeepoutOpeningDirection:"bottom",secondaryPort:{point:{x:-1.7,y:0},role:"ground"},groundViaPoint:{x:-1.7,y:0},route:[{x:-1.7,y:0},{x:-1.7,y:4.9},{x:0,y:4.9},{x:0,y:0},{x:0,y:4.9},{x:-1.7,y:4.9},{x:2.3,y:4.9},{x:2.3,y:1.4},{x:5.3,y:1.4},{x:5.3,y:4.9},{x:8.3,y:4.9},{x:8.3,y:1.4},{x:11.3,y:1.4},{x:11.3,y:4.9},{x:13.3,y:4.9}]};case"2.4ghz_folded_dipole":return{traceWidth:.9,feedPoint:{x:0,y:0},feedKeepoutOpeningDirection:"bottom",secondaryPort:{point:{x:1.2,y:0},role:"feed2"},route:[{x:0,y:0},{x:-22.4,y:0},{x:-22.4,y:9},{x:23.6,y:9},{x:23.6,y:0},{x:1.2,y:0}]}}},ITo=class extends g0{get config(){return{componentName:"Antenna",zodProps:QPn,sourceFtype:$7.simple_chip,shouldRenderAsSchematicBox:!0}}getRefDesPrefixes(){return["ANT"]}initPorts(){const{antennaShape:t,pcbPath:e}=this._parsedProps,n=e?void 0:t==="2.4ghz_inverted_f"||t==="2.4ghz_meandered_inverted_f"?"ground":t==="2.4ghz_folded_dipole"?"feed2":void 0;super.initPorts({pinCount:n?2:1,additionalAliases:{pin1:n==="feed2"?["feed","feed1"]:["feed"],...n==="ground"?{pin2:["ground","gnd"]}:n==="feed2"?{pin2:["feed2"]}:{}}})}doInitialReactSubtreesRender(){super.doInitialReactSubtreesRender();const{antennaShape:t,pcbPath:e}=this._parsedProps;if(!t)return;const n=this.children.some(r=>r.componentName==="Footprint");if(e&&n)return;const o=e?void 0:fTo(t),i=new Y0e({name:`${this.name}_generated_antenna`});if(n||i.add(new Mb({shape:"rect",width:.8,height:.8,pcbX:o?.feedPoint.x??0,pcbY:o?.feedPoint.y??0,layer:"top",portHints:["pin1"],coveredWithSolderMask:!0})),o){const r=_To(o);for(const s of r)i.add(new k0e({shape:"rect",pcbX:s.center.x,pcbY:s.center.y,width:s.width,height:s.height,layers:[...this.root?._getBoard()?.allLayers??["top","bottom"]],excludeRefs:[this.getSubcircuitSelector()]}));i.add(new tPe({route:o.route.map(s=>({route_type:"wire",...s,width:o.traceWidth,layer:"top"}))})),o.secondaryPort&&!o.groundViaPoint&&!n&&i.add(new Mb({shape:"rect",width:.8,height:.8,pcbX:o.secondaryPort.point.x,pcbY:o.secondaryPort.point.y,layer:"top",portHints:["pin2"],coveredWithSolderMask:!0})),o.groundViaPoint&&i.add(new Pb({shape:"circle",pcbX:o.groundViaPoint.x,pcbY:o.groundViaPoint.y,holeDiameter:.3,outerDiameter:.7,portHints:["pin2"],coveredWithSolderMask:!0}))}this.add(i)}doInitialCreateTracesFromProps(){super.doInitialCreateTracesFromProps();const{pcbPath:t}=this._parsedProps;t&&this.add(new t1({name:`${this.name}_pcb_path`,path:[`${this.getSubcircuitSelector()} > port.pin1`],pcbPath:t}))}},CTo=class extends zj{constructor(t){super(t)}get config(){return{...super.config,componentName:"Pinout",zodProps:wwn}}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers,display_name:e.displayName});this.source_component_id=n.source_component_id}},yTo=class extends g0{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:Rwn,sourceFtype:$7.simple_fuse}}_getSchematicSymbolDisplayValue(){if(this._parsedProps.schShowRatings===!1)return"";const e=this._parsedProps.currentRating,n=this._parsedProps.voltageRating,o=q1(e,"A").value,i=q1(n,"V").value;return`${H_(o)}A / ${H_(i)}V`}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:n}=this,o=q1(n.currentRating,"A").value,i=q1(n.voltageRating,"V").value;let r,s;n.schShowRatings!==!1&&(r=`${H_(o)}A`,s=`${H_(i)}V`);const a=e.source_component.insert({name:this.name,ftype:$7.simple_fuse,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,...o!=null?{current_rating_amps:o}:{},...i!=null?{voltage_rating_volts:i}:{},display_current_rating:r,display_voltage_rating:s,display_name:n.displayName});this.source_component_id=a.source_component_id}},xTo=class extends g0{schematicDimensions=null;get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:clt,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){const t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;const e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),n=this._parsedProps.schDirection??"right";return{leftSize:n==="left"?e:0,rightSize:n==="right"?e:0}}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,{pcbX:n,pcbY:o}=this.getResolvedPcbPositionProp(),i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0,display_name:e.displayName});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,{pcbX:n,pcbY:o}=this.getResolvedPcbPositionProp(),i=this.getGlobalTransformRotation(),r=t.pcb_component.insert({center:{x:n,y:o},width:2,height:3,layer:e.layer??"top",rotation:k9(i),insertion_direction:this._getPcbComponentInsertionDirection(e.layer??"top",i),source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:e.doNotPlace??!1,obstructs_within_bounds:e.obstructsWithinBounds??!0,is_allowed_to_be_off_board:e.allowOffBoard??!1,metadata:e.kicadFootprintMetadata?{kicad_footprint:e.kicadFootprintMetadata}:void 0});this.pcb_component_id=r.pcb_component_id}doInitialPcbPortAttachment(){const{db:t}=this.root,e=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),n={};for(let r=0;r<e.length;r++){const s=e[r],a=t.source_port.get(s.source_port_id);let A="";if(typeof a?.pin_number=="number")A=a.pin_number.toString();else if(Array.isArray(a?.port_hints)){let c=a.port_hints.find(l=>/^(pin)?\d+$/.test(l));c&&(/^pin\d+$/.test(c)?A=c.replace(/^pin/,""):A=c)}n[A]=s.pcb_port_id}const o=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),i=r=>{if(r&&typeof r=="string"&&r.startsWith("{PIN")){const s=r.replace("{PIN","").replace("}","");return n[s]||r}return r};for(const r of o)if(r.route)for(const s of r.route)s.route_type==="wire"&&(s.start_pcb_port_id=i(s.start_pcb_port_id),s.end_pcb_port_id=i(s.end_pcb_port_id))}},kkt={"0402":"0402","0603":"0603","0805":"0805",1206:"1206"},ETo=class extends g0{get config(){return{componentName:"Interconnect",zodProps:Nwn,shouldRenderAsSchematicBox:!0,sourceFtype:"interconnect"}}get defaultInternallyConnectedPinNames(){const{standard:t}=this._parsedProps;return t&&kkt[t]?[["pin1","pin2"]]:[]}_getImpliedFootprintString(){const{standard:t}=this._parsedProps;return t?kkt[t]??null:null}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({ftype:"interconnect",name:this.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0,display_name:e.displayName});this.source_component_id=n.source_component_id}doInitialSourceParentAttachment(){const{db:t}=this.root,e=this._getInternallyConnectedPins();for(const n of e){const o=n.map(i=>i.source_port_id).filter(i=>i!==null);o.length>=2&&t.source_component_internal_connection.insert({source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id,source_port_ids:o})}}},BTo=class extends g0{schematicDimensions=null;_getPinCountFromFootprintString(t){const e=t.match(/^solderjumper([23])(?:_|$)/);return e?Number(e[1]):null}_getPinNumberFromBridgedPinsProp(t){const e=t.match(/^(?:pin)?(\d+)$/i);if(e)return Number(e[1]);const n=this._parsedProps.pinLabels??this.props.pinLabels;if(Array.isArray(n)){const o=n.findIndex(i=>i===t);return o>=0?o+1:null}if(n&&typeof n=="object")for(const[o,i]of Object.entries(n)){if(!(Array.isArray(i)?i:[i]).includes(t))continue;const s=o.match(/^(?:pin)?(\d+)$/i);return s?Number(s[1]):null}return null}_getBridgedPinNumbersForFootprint(t){const e=this._parsedProps??this.props;return Array.isArray(e.bridgedPins)&&e.bridgedPins.length>0?Array.from(new Set(e.bridgedPins.flat().map(n=>this._getPinNumberFromBridgedPinsProp(n)).filter(n=>n!==null&&n>=1&&n<=t))).sort((n,o)=>n-o):e.bridged?Array.from({length:t},(n,o)=>o+1):[]}resolveFootprint(){const t=super.resolveFootprint();if(typeof t!="string")return t;const e=this._getPinCountFromFootprintString(t);if(!e||/_bridged\d+/.test(t))return t;const n=this._getBridgedPinNumbersForFootprint(e);return n.length===0?t:t.replace(/^solderjumper[23]/,`solderjumper${e}_bridged${n.join("")}`)}_getPinNumberFromBridgedPinName(t){return this.selectOne(`port.${t}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){const t=this.children.filter(e=>e.componentName==="Port").map(e=>e.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){const t=this._parsedProps??this.props;let e=t.pinCount;if(t.pinCount==null&&!t.footprint&&(e=2),t.pinCount==null){const i=(t.bridgedPins??[]).flat().map(A=>this._getPinNumberFromBridgedPinName(A)).filter(A=>A!==null),r=i.length>0?Math.max(...i):0,s=t.pinLabels?Object.keys(t.pinLabels).length:0,a=Math.max(r,s);(a===2||a===3)&&(e=a),e==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(e=this.getPortsFromFootprint().length)}let n="";e?n+=`solderjumper${e}`:n="solderjumper";let o=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?o=Array.from(new Set(t.bridgedPins.flat().map(i=>this._getPinNumberFromBridgedPinName(i)).filter(i=>i!==null))).sort((i,r)=>i-r):t.bridged&&e&&(o=Array.from({length:e},(i,r)=>r+1)),o.length>0&&(n+=`_bridged${o.join("")}`),{schematicSymbolName:t.symbolName??n,componentName:"SolderJumper",zodProps:Pwn,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){const t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);e==null&&!this._parsedProps.footprint&&(e=2);const n=this._parsedProps.schDirection??"right";return{leftSize:n==="left"?e:0,rightSize:n==="right"?e:0}}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,{pcbX:n,pcbY:o}=this.getResolvedPcbPositionProp(),i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0,display_name:e.displayName});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,{pcbX:n,pcbY:o}=this.getResolvedPcbPositionProp(),i=this.getGlobalTransformRotation(),r=t.pcb_component.insert({center:{x:n,y:o},width:2,height:3,layer:e.layer??"top",rotation:k9(i),insertion_direction:this._getPcbComponentInsertionDirection(e.layer??"top",i),source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:e.doNotPlace??!1,obstructs_within_bounds:e.obstructsWithinBounds??!0,is_allowed_to_be_off_board:e.allowOffBoard??!1,metadata:e.kicadFootprintMetadata?{kicad_footprint:e.kicadFootprintMetadata}:void 0});this.pcb_component_id=r.pcb_component_id}doInitialPcbPortAttachment(){const{db:t}=this.root,e=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),n={};for(let r=0;r<e.length;r++){const s=e[r],a=t.source_port.get(s.source_port_id);let A="";if(typeof a?.pin_number=="number")A=a.pin_number.toString();else if(Array.isArray(a?.port_hints)){let c=a.port_hints.find(l=>/^(pin)?\d+$/.test(l));c&&(/^pin\d+$/.test(c)?A=c.replace(/^pin/,""):A=c)}n[A]=s.pcb_port_id}const o=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),i=r=>{if(r&&typeof r=="string"&&r.startsWith("{PIN")){const s=r.replace("{PIN","").replace("}","");return n[s]||r}return r};for(const r of o)if(r.route)for(const s of r.route)s.route_type==="wire"&&(s.start_pcb_port_id=i(s.start_pcb_port_id),s.end_pcb_port_id=i(s.end_pcb_port_id))}},bTo=class extends g0{get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:OMn,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Pu({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Pu({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:e.voltage,supplier_part_numbers:e.supplierPartNumbers,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,are_pins_interchangeable:!1,display_name:e.displayName});this.source_component_id=n.source_component_id}pos=this.portMap.pin1;positive=this.portMap.pin1;neg=this.portMap.pin2;negative=this.portMap.pin2},Fkt=class extends g0{simulation_voltage_source_id=null;get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:UMn,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(const e of this.children)e.runRenderPhaseForChildren(t),e.runRenderPhase(t)}doInitialPcbComponentRender(){const t=this._hasUserDefinedPcbPosition();if(!this._parsedProps.footprint){if(!t)return;throw new Error("VoltageSource requires a footprint when pcbX/pcbY or pcb edge position props are used")}super.doInitialPcbComponentRender()}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}_getSchematicSymbolDisplayValue(){const{voltage:t,frequency:e}=this._parsedProps,n=[];return t!==void 0&&n.push(`${H_(t)}V`),e!==void 0&&n.push(`${H_(e)}Hz`),n.length>0?n.join(" "):void 0}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:e.voltage,frequency:e.frequency,peak_to_peak_voltage:e.peakToPeakVoltage,wave_shape:e.waveShape,phase:e.phase,duty_cycle:e.dutyCycle,pulse_delay:e.pulseDelay,rise_time:e.riseTime,fall_time:e.fallTime,pulse_width:e.pulseWidth,period:e.period,supplier_part_numbers:e.supplierPartNumbers,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,are_pins_interchangeable:!0,display_name:e.displayName});this.source_component_id=n.source_component_id}doInitialSimulationRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=this.portMap.terminal1,o=this.portMap.terminal2,i=t.simulation_voltage_source.insert({is_dc_source:!1,terminal1_source_port_id:n.source_port_id??void 0,terminal2_source_port_id:o.source_port_id??void 0,voltage:e.voltage,frequency:e.frequency,peak_to_peak_voltage:e.peakToPeakVoltage,wave_shape:e.waveShape,phase:e.phase,duty_cycle:e.dutyCycle,pulse_delay:e.pulseDelay,rise_time:e.riseTime,fall_time:e.fallTime,pulse_width:e.pulseWidth,period:e.period,ac_magnitude:e.acMagnitude,ac_phase:e.acPhase});this.simulation_voltage_source_id=i.simulation_voltage_source_id}terminal1=this.portMap.terminal1;terminal2=this.portMap.terminal2},Lkt=class extends g0{simulation_current_source_id=null;get config(){return{componentName:"CurrentSource",schematicSymbolName:"current_source",zodProps:zMn,sourceFtype:"simple_current_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(const e of this.children)e.runRenderPhaseForChildren(t),e.runRenderPhase(t)}doInitialPcbComponentRender(){const t=this._hasUserDefinedPcbPosition();if(!this._parsedProps.footprint){if(!t)return;throw new Error("CurrentSource requires a footprint when pcbX/pcbY or pcb edge position props are used")}super.doInitialPcbComponentRender()}initPorts(){super.initPorts({additionalAliases:{pin1:["pos"],pin2:["neg"]}})}_getSchematicSymbolDisplayValue(){const{current:t,frequency:e,peakToPeakCurrent:n}=this._parsedProps,o=[];return t!==void 0&&o.push(`${H_(t)}A`),n!==void 0&&o.push(`${H_(n)}A p-p`),e!==void 0&&o.push(`${H_(e)}Hz`),o.length>0?o.join(" "):void 0}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({ftype:"simple_current_source",name:this.name,current:e.current,frequency:e.frequency,peak_to_peak_current:e.peakToPeakCurrent,wave_shape:e.waveShape,phase:e.phase,duty_cycle:e.dutyCycle,supplier_part_numbers:e.supplierPartNumbers,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,are_pins_interchangeable:!0,display_name:e.displayName});this.source_component_id=n.source_component_id}doInitialSimulationRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=e.frequency!==void 0||e.peakToPeakCurrent!==void 0||e.waveShape!==void 0||e.acMagnitude!==void 0||e.acPhase!==void 0,o=this.portMap.pos,i=this.portMap.neg;if(n){const r=t.simulation_current_source.insert({is_dc_source:!1,terminal1_source_port_id:o.source_port_id??void 0,terminal2_source_port_id:i.source_port_id??void 0,current:e.current,frequency:e.frequency,peak_to_peak_current:e.peakToPeakCurrent,wave_shape:e.waveShape,phase:e.phase,duty_cycle:e.dutyCycle,ac_magnitude:e.acMagnitude,ac_phase:e.acPhase});this.simulation_current_source_id=r.simulation_current_source_id}else{if(e.current===void 0)return;const r=t.simulation_current_source.insert({is_dc_source:!0,positive_source_port_id:o.source_port_id??void 0,negative_source_port_id:i.source_port_id??void 0,current:e.current,ac_magnitude:e.acMagnitude,ac_phase:e.acPhase});this.simulation_current_source_id=r.simulation_current_source_id}}pos=this.portMap.pos;neg=this.portMap.neg},Uue=.25,Hkt=(t,e)=>({left:t.center.x-t.size.width/2-e,right:t.center.x+t.size.width/2+e,bottom:t.center.y-t.size.height/2-e,top:t.center.y+t.size.height/2+e}),STo=(t,e)=>t.left<e.right&&t.right>e.left&&t.bottom<e.top&&t.top>e.bottom,QTo=({baseCenter:t,size:e})=>{const n=e.width+Uue*2,o=e.height+Uue*2;return[t,{x:t.x,y:t.y+o},{x:t.x,y:t.y-o},{x:t.x+n,y:t.y},{x:t.x-n,y:t.y},{x:t.x+n,y:t.y+o},{x:t.x-n,y:t.y+o},{x:t.x+n,y:t.y-o},{x:t.x-n,y:t.y-o},{x:t.x,y:t.y+o*2},{x:t.x,y:t.y-o*2}]},vTo=({ammeterSourcePortId:t,schematicPorts:e,sourceTraces:n})=>{for(const o of n){if(!o.connected_source_port_ids.includes(t))continue;const i=o.connected_source_port_ids.find(s=>s!==t);if(i===void 0)continue;const r=e.find(s=>s.source_port_id===i);if(r)return r}return null},wTo=t=>({x:t.reduce((e,n)=>e+n.center.x,0)/t.length,y:t.reduce((e,n)=>e+n.center.y,0)/t.length}),PTo=({ammeter:t,db:e,oldCenter:n,newCenter:o})=>{const i=t.schematic_component_id;if(!i)return;const r=o.x-n.x,s=o.y-n.y;if(!(r===0&&s===0)){e.schematic_component.update(i,{center:o});for(const a of e.schematic_port.list({schematic_component_id:i}))e.schematic_port.update(a.schematic_port_id,{center:{x:a.center.x+r,y:a.center.y+s}});for(const a of e.schematic_text.list({schematic_component_id:i}))e.schematic_text.update(a.schematic_text_id,{position:{x:a.position.x+r,y:a.position.y+s}});MO({db:e,schematicComponentId:i,deltaX:r,deltaY:s})}},MTo=t=>{const{root:e}=t;if(!e||e.schematicDisabled||!t.schematic_component_id||t._parsedProps.schX!==void 0||t._parsedProps.schY!==void 0||t.getGroup()?._getSchematicLayoutMode()!=="relative")return;const{db:n}=e,o=n.schematic_component.get(t.schematic_component_id);if(!o)return;const i=[t.portMap.pos.source_port_id,t.portMap.neg.source_port_id].filter(u=>typeof u=="string");if(i.length===0)return;const r=n.schematic_port.list(),s=n.source_trace.list(),a=i.map(u=>vTo({ammeterSourcePortId:u,schematicPorts:r,sourceTraces:s})).filter(u=>u!==null);if(a.length===0)return;const A=wTo(a),c=n.schematic_component.list().filter(u=>u.schematic_component_id!==o.schematic_component_id&&!u.is_schematic_group&&u.schematic_sheet_id===o.schematic_sheet_id).map(u=>Hkt(u,Uue)),l=QTo({baseCenter:A,size:o.size}).find(u=>{const g=Hkt({...o,center:u},Uue);return!c.some(h=>STo(g,h))})??A;PTo({ammeter:t,db:n,oldCenter:o.center,newCenter:l})},DTo=class extends g0{simulation_current_probe_id=null;get config(){return{componentName:"Ammeter",schematicSymbolName:"dc_ammeter",zodProps:$Mn,sourceFtype:"simple_ammeter"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(const e of this.children)e.runRenderPhaseForChildren(t),e.runRenderPhase(t)}doInitialPcbComponentRender(){const t=this._hasUserDefinedPcbPosition();if(!this._parsedProps.footprint){if(!t)return;throw new Error("Ammeter requires a footprint when pcbX/pcbY or pcb edge position props are used")}super.doInitialPcbComponentRender()}initPorts(){super.initPorts({ignoreSymbolPorts:!0,pinCount:2,additionalAliases:{pin1:["pos"],pin2:["neg"]}});const t=Su[this._getSchematicSymbolNameOrThrow()];this.portMap.pos.schematicSymbolPortDef=t.ports.find(e=>e.labels.includes("1"))??null,this.portMap.neg.schematicSymbolPortDef=t.ports.find(e=>e.labels.includes("2"))??null}doInitialSourceRender(){const{db:t}=this.root,{supplierPartNumbers:e,displayName:n}=this._parsedProps,o=t.source_component.insert({ftype:"simple_ammeter",name:this.name,supplier_part_numbers:e,manufacturer_part_number:this._parsedProps.manufacturerPartNumber??this._parsedProps.mfn,display_name:n});this.source_component_id=o.source_component_id}doInitialSimulationRender(){const{db:t}=this.root,{color:e,graphDisplayName:n,graphCenter:o,graphVerticalOffset:i,graphCurrentPerDiv:r}=this._parsedProps,s=this.portMap.pos,a=this.portMap.neg,{simulation_current_probe_id:A}=t.simulation_current_probe.insert({type:"simulation_current_probe",name:this.name,source_component_id:this.source_component_id,positive_source_port_id:s.source_port_id,negative_source_port_id:a.source_port_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0,color:e});if(this.simulation_current_probe_id=A,n!==void 0||o!==void 0||i!==void 0||r!==void 0){const l=Sw(r),u=Sw(i);t.simulation_oscilloscope_trace.insert({simulation_current_probe_id:A,display_name:n,color:e,display_center_value:o,amps_per_div:l,display_center_offset_divs:u!==void 0&&l!==void 0&&l!==0?u/l:void 0})}}doInitialSchematicLayout(){MTo(this)}pos=this.portMap.pos;neg=this.portMap.neg},NTo=["leftedge","rightedge","topedge","bottomedge","center"],RTo=class extends Ir{get config(){return{componentName:"Constraint",zodProps:oPn}}constructor(t){if(super(t),("xdist"in t||"ydist"in t)&&!("edgeToEdge"in t)&&!("centerToCenter"in t))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in t&&t.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){const t=[],e=this.getPrimitiveContainer();function n(o){const i=o.split(" ").pop(),r=NTo.includes(i)?i:void 0,s=r?o.replace(` ${r}`,""):o,a=e.selectOne(s,{pcbPrimitive:!0});a&&t.push({selector:o,component:a,componentSelector:s,edge:r})}for(const o of["left","right","top","bottom"])o in this._parsedProps&&n(this._parsedProps[o]);if("for"in this._parsedProps)for(const o of this._parsedProps.for)n(o);return{componentsWithSelectors:t}}},TTo=class extends Ir{get config(){return{componentName:"AutoroutingPhase",zodProps:iMn}}add(t){throw new Error("<autoroutingphase> cannot contain children")}},kTo=class extends Ir{fabrication_note_dimension_id=null;isPcbPrimitive=!0;get config(){return{componentName:"FabricationNoteDimension",zodProps:SMn}}_resolvePoint(t,e){if(typeof t=="string"){const i=this.getSubcircuit().selectOne(t);return i?i._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${t}"`),ts(e,{x:0,y:0}))}const n=typeof t.x=="string"?parseFloat(t.x):t.x,o=typeof t.y=="string"?parseFloat(t.y):t.y;return ts(e,{x:n,y:o})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._computePcbGlobalTransformBeforeLayout(),o=this._resolvePoint(e.from,n),i=this._resolvePoint(e.to,n),r=this.getSubcircuit(),s=this.getGroup(),{maybeFlipLayer:a}=this._getPcbPrimitiveFlippedHelpers(),A=a(e.layer??"top");if(A!=="top"&&A!=="bottom")throw new Error(`Invalid layer "${A}" for FabricationNoteDimension. Must be "top" or "bottom".`);const c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,l=e.text??this._formatDistanceText({from:o,to:i,units:e.units??"mm"}),u=t.pcb_fabrication_note_dimension.insert({pcb_component_id:c,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,layer:A,from:o,to:i,text:l,offset:e.offset,font:e.font??"tscircuit2024",font_size:e.fontSize??1,color:e.color,arrow_size:e.arrowSize??1});this.fabrication_note_dimension_id=u.pcb_fabrication_note_dimension_id}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.fabrication_note_dimension_id)return;const o=n.pcb_fabrication_note_dimension.get(this.fabrication_note_dimension_id);o&&n.pcb_fabrication_note_dimension.update(this.fabrication_note_dimension_id,{from:{x:o.from.x+t,y:o.from.y+e},to:{x:o.to.x+t,y:o.to.y+e}})}getPcbSize(){const t=this._computePcbGlobalTransformBeforeLayout(),e=this._resolvePoint(this._parsedProps.from,t),n=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(n.x-e.x),height:Math.abs(n.y-e.y)}}_formatDistanceText({from:t,to:e,units:n}){const o=e.x-t.x,i=e.y-t.y,r=Math.sqrt(o*o+i*i),s=n==="in"?r/25.4:r,a=Math.round(s);if(Math.abs(s-a)<1e-9)return`${a}${n}`;const c=n==="in"?3:2;return`${n==="in"?Number(s.toFixed(c)).toString():s.toFixed(c)}${n}`}},FTo=class extends Ir{pcb_note_dimension_id=null;isPcbPrimitive=!0;get config(){return{componentName:"PcbNoteDimension",zodProps:QDn}}_resolvePoint(t,e){if(typeof t=="string"){const i=this.getSubcircuit().selectOne(`.${t}`);if(!i)return this.renderError(`PcbNoteDimension could not find selector "${t}"`),ts(e,{x:0,y:0});const r=i.pcb_component_id,s=this.root;if(r&&s){const a=s.db.pcb_component.get(r);if(a?.center)return{x:a.center.x,y:a.center.y}}return i._getGlobalPcbPositionBeforeLayout()}const n=typeof t.x=="string"?parseFloat(t.x):t.x,o=typeof t.y=="string"?parseFloat(t.y):t.y;return ts(e,{x:n,y:o})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._computePcbGlobalTransformBeforeLayout(),o=this._resolvePoint(e.from,n),i=this._resolvePoint(e.to,n),r=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,A=e.text??this._formatDistanceText({from:o,to:i,units:e.units??"mm"}),c=t.pcb_note_dimension.insert({pcb_component_id:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,from:o,to:i,text:A,font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:e.layer==="bottom"?"bottom":"top",color:e.color,arrow_size:e.arrowSize??1});this.pcb_note_dimension_id=c.pcb_note_dimension_id}doInitialPcbLayout(){const t=this.root;if(!t||t.pcbDisabled||!this.pcb_note_dimension_id)return;const{db:e}=t,n=this._computePcbGlobalTransformBeforeLayout(),o=this._resolvePoint(this._parsedProps.from,n),i=this._resolvePoint(this._parsedProps.to,n);e.pcb_note_dimension.update(this.pcb_note_dimension_id,{from:o,to:i})}getPcbSize(){const t=this._computePcbGlobalTransformBeforeLayout(),e=this._resolvePoint(this._parsedProps.from,t),n=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(n.x-e.x),height:Math.abs(n.y-e.y)}}_formatDistanceText({from:t,to:e,units:n}){const o=e.x-t.x,i=e.y-t.y,r=Math.sqrt(o*o+i*i),s=n==="in"?r/25.4:r,a=Math.round(s);if(Math.abs(s-a)<1e-9)return`${a}${n}`;const c=n==="in"?3:2;return`${n==="in"?Number(s.toFixed(c)).toString():s.toFixed(c)}${n}`}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_note_dimension_id)return;const o=n.pcb_note_dimension.get(this.pcb_note_dimension_id);o&&n.pcb_note_dimension.update(this.pcb_note_dimension_id,{from:{x:o.from.x+t,y:o.from.y+e},to:{x:o.to.x+t,y:o.to.y+e}})}},Kue=class extends VTt{get config(){return{componentName:"AutoplacedBreakoutPoint",zodProps:CNo}}_applySolvedBreakoutPoint({sourceTraceId:t,layer:e,position:n}){this.matchedSourceTraceId=t,this._renderPcbBreakoutPoint({layer:Pr.parse(e)}),this._setPositionFromLayout(n)}},Okt=[{id:"DQ0",layer:"inner3",soc:{x:-6,y:-3},ram:{x:3.941917,y:-3.650917}},{id:"DQ1",layer:"inner6",fullLayer:"inner2",soc:{x:-5.5,y:-3},ram:{x:4.591917,y:-3.650917}},{id:"DQ2",layer:"inner5",fullLayer:"inner4",soc:{x:-4.5,y:-3},ram:{x:5.891917,y:-3.650917}},{id:"DQ3",layer:"inner2",fullLayer:"inner6",soc:{x:-4.5,y:-3.5},ram:{x:6.541917,y:-3.650917}},{id:"DQ4",layer:"inner3",fullLayer:"inner2",soc:{x:-6,y:-2.5},ram:{x:6.541917,y:-2.050917}},{id:"DQ5",layer:"inner2",fullLayer:"inner5",soc:{x:-6,y:-2},ram:{x:5.891917,y:-2.050917}},{id:"DQ6",layer:"inner5",fullLayer:"inner4",soc:{x:-5,y:-2},ram:{x:4.591917,y:-2.050917}},{id:"DQ7",layer:"inner4",fullLayer:"inner6",soc:{x:-5.5,y:-2},ram:{x:3.941917,y:-2.050917}},{id:"DM0",layer:"inner4",fullLayer:"inner5",soc:{x:-5,y:-3},ram:{x:4.591917,y:-2.850917}},{id:"DQS0",layer:"inner1",differentialPairId:"DQS0",soc:{x:-4.5,y:-2.5},ram:{x:5.241917,y:-2.850917}},{id:"DQS0_n",layer:"inner1",differentialPairId:"DQS0",soc:{x:-5,y:-2.5},ram:{x:5.891917,y:-2.850917}}],Gkt=[{id:"DQ8",layer:"inner6",fullLayer:"inner4",soc:{x:-6,y:3},ram:{x:3.941917,y:3.549083}},{id:"DQ9",layer:"inner3",fullLayer:"inner4",soc:{x:-5.5,y:2},ram:{x:4.591917,y:3.549083}},{id:"DQ10",layer:"inner3",fullLayer:"inner2",soc:{x:-4.5,y:2},ram:{x:5.891917,y:3.549083}},{id:"DQ11",layer:"inner6",fullLayer:"inner5",soc:{x:-4.5,y:2.5},ram:{x:6.541917,y:3.549083}},{id:"DQ12",layer:"inner5",fullLayer:"inner1",soc:{x:-6,y:2.5},ram:{x:6.541917,y:1.949083}},{id:"DQ13",layer:"inner2",fullLayer:"inner3",soc:{x:-6.5,y:3},ram:{x:5.891917,y:1.949083}},{id:"DQ14",layer:"inner5",fullLayer:"inner6",soc:{x:-5,y:2.5},ram:{x:4.591917,y:1.949083}},{id:"DQ15",layer:"inner4",fullLayer:"inner1",soc:{x:-4.5,y:3.5},ram:{x:3.941917,y:1.949083}},{id:"DM1",layer:"inner4",fullLayer:"inner5",soc:{x:-5,y:3.5},ram:{x:4.591917,y:2.749083}},{id:"DQS1",layer:"inner1",fullLayer:"bottom",differentialPairId:"DQS1",soc:{x:-4.5,y:3},ram:{x:5.241917,y:2.749083}},{id:"DQS1_n",layer:"inner1",fullLayer:"bottom",differentialPairId:"DQS1",soc:{x:-5,y:3},ram:{x:5.891917,y:2.749083}}],Ykt=[{id:"A0",layer:"bottom",soc:{x:-6.5,y:-.5},ram:{x:7.841917,y:-3.650917}},{id:"A1",layer:"inner3",soc:{x:-7,y:-2},ram:{x:8.491917,y:-3.650917}},{id:"A2",layer:"inner3",soc:{x:-7,y:-.5},ram:{x:7.841917,y:1.949083}},{id:"A3",layer:"inner6",soc:{x:-5,y:-1},ram:{x:7.841917,y:2.749083}},{id:"A4",layer:"inner4",soc:{x:-4.5,y:-1.5},ram:{x:7.841917,y:3.549083}},{id:"A5",layer:"inner2",soc:{x:-6.5,y:-2},ram:{x:8.491917,y:3.549083}},{id:"CS0_n",layer:"inner5",soc:{x:-5.5,y:-.5},ram:{x:7.841917,y:-2.050917}},{id:"CKE0",layer:"inner1",soc:{x:-4.5,y:-1},ram:{x:8.491917,y:-2.050917}},{id:"CK0",layer:"bottom",differentialPairId:"CK0",soc:{x:-4.5,y:1},ram:{x:8.491917,y:1.149083}},{id:"CK0_n",layer:"bottom",differentialPairId:"CK0",soc:{x:-5,y:1},ram:{x:8.491917,y:1.949083}},{id:"DDR_LINK_RESET0_n",layer:"inner6",soc:{x:-5,y:-1.5},ram:{x:13.041917,y:3.549083}}],Vue=t=>{const e=t.buses.flatMap(s=>s.ports),n=new Set,o=s=>[{regionId:"soc",position:s.soc},{regionId:"ram",position:s.ram}],i=[];for(const s of e){if(!s.differentialPairId){i.push({id:s.id,endpoints:o(s)});continue}if(n.has(s.differentialPairId))continue;n.add(s.differentialPairId);const a=e.filter(l=>l.differentialPairId===s.differentialPairId);if(a.length!==2)throw new Error(`Differential pair ${s.differentialPairId} must have two members`);const[A,c]=a;i.push({type:"differential",connections:[{id:A.id,endpoints:o(A)},{id:c.id,endpoints:o(c)}]})}const r=t.buses.map(s=>{let a={id:s.id,connectionIds:s.ports.map(A=>A.id)};return s.preferredLayer!==void 0&&(a={...a,preferredLayer:s.preferredLayer}),s.preferredLayers!==void 0&&(a={...a,preferredLayers:s.preferredLayers}),a});return{regions:[{id:"soc",bounds:{minX:-16.62808,maxX:-2.37192,minY:-10.62808,maxY:10.62808},edge:"right"},{id:"ram",bounds:{minX:1.091917,maxX:18.141917,minY:-9.650917,maxY:9.549083},edge:"left"}],connections:i,buses:r,boundaryPointSpacing:.48}};Vue({buses:[{id:"DDR_BYTE0",ports:Okt,preferredLayers:["inner1","inner4"]}]}),Vue({buses:[{id:"DDR_BYTE1",ports:Gkt,preferredLayers:["inner2","inner5"]}]}),Vue({buses:[{id:"DDR_BYTE0",ports:Okt,preferredLayers:["inner1","inner4"]},{id:"DDR_BYTE1",ports:Gkt,preferredLayers:["inner2","inner5"]},{id:"DDR_ADDR_CTRL",ports:Ykt,preferredLayers:["inner3","inner6"]}]}),Vue({buses:[{id:"DDR_ADDR_CTRL",ports:Ykt,preferredLayers:["inner3","inner6"]}]});var LTo=class extends Error{name="WindingBreakoutInputError"},Ukt=class extends Error{name="WindingBreakoutInfeasibleError"},YMe=class extends Error{name="WindingBreakoutInvariantError"},HTo=class extends Error{name="WindingBreakoutOutputUnavailableError"},zue=t=>{const e=[];for(const n of t.connections)"type"in n?e.push(...n.connections):e.push(n);return e},UMe=t=>t.preferredLayer!==void 0?[t.preferredLayer]:t.preferredLayers!==void 0?[...new Set(t.preferredLayers)]:["top"],KMe=t=>{const e=new Map;for(const n of t.buses){const o=UMe(n);for(const i of n.connectionIds)e.set(i,o)}return Object.fromEntries(zue(t).map(n=>[n.id,e.get(n.id)??["top"]]))},R0=t=>{throw new LTo(`WindingBreakoutSolver: ${t}`)},OTo=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),hR=(t,e)=>{OTo(t)||R0(`${e} must be an object`)},pR=(t,e)=>{(typeof t!="string"||t.trim().length===0)&&R0(`${e} must be a non-empty string`)},mR=(t,e)=>{(typeof t!="number"||!Number.isFinite(t))&&R0(`${e} must be finite`)},GTo=(t,e)=>{mR(t,e),t<=0&&R0(`${e} must be positive`)},B$=(t,e)=>Array.isArray(t)?t:R0(e),YTo=(t,e)=>(hR(t,e),mR(t.x,`${e}.x`),mR(t.y,`${e}.y`),t),UTo=(t,e)=>(hR(t,e),mR(t.minX,`${e}.minX`),mR(t.maxX,`${e}.maxX`),mR(t.minY,`${e}.minY`),mR(t.maxY,`${e}.maxY`),(t.minX>=t.maxX||t.minY>=t.maxY)&&R0(`${e} must have positive width and height`),{minX:t.minX,maxX:t.maxX,minY:t.minY,maxY:t.maxY}),KTo=(t,e)=>t.x>=e.minX&&t.x<=e.maxX&&t.y>=e.minY&&t.y<=e.maxY,VTo=t=>{(!Array.isArray(t.regions)||t.regions.length===0)&&R0("at least one region is required"),GTo(t.boundaryPointSpacing,"boundaryPointSpacing");const e=new Set,n=t.regions.map((d,p)=>{hR(d,`regions[${p}]`),pR(d.id,`regions[${p}].id`),e.has(d.id)&&R0(`duplicate region id "${d.id}"`),e.add(d.id);const m=UTo(d.bounds,`region "${d.id}" bounds`);return(typeof d.edge!="string"||!new Set(["left","right","bottom","top"]).has(d.edge))&&R0(`region "${d.id}" has invalid edge`),{id:d.id,bounds:m,edge:d.edge,center:{x:(m.minX+m.maxX)/2,y:(m.minY+m.maxY)/2}}}),o=n.every(d=>d.edge==="left"||d.edge==="right"),i=n.every(d=>d.edge==="bottom"||d.edge==="top");!o&&!i&&R0("all coordinated region edges must be parallel"),(!Array.isArray(t.connections)||t.connections.length===0)&&R0("at least one connection is required");const r=[],s=new Set,a=[],A=(d,p)=>{hR(d,p),pR(d.id,`${p}.id`),s.has(d.id)&&R0(`duplicate connection id "${d.id}"`),"layer"in d&&R0(`${p}.layer is not accepted; declare layer preferences on a bus`);const m=B$(d.endpoints,`${p}.endpoints must be an array`),_=new Set,f=m.map((I,C)=>{const y=`${p}.endpoints[${C}]`;hR(I,y),pR(I.regionId,`${y}.regionId`),e.has(I.regionId)||R0(`${y} references unknown region "${I.regionId}"`),_.has(I.regionId)&&R0(`${p} has duplicate endpoint for region "${I.regionId}"`),_.add(I.regionId);const x=YTo(I.position,`${y}.position`),E=n.find(B=>B.id===I.regionId);return KTo(x,E.bounds)||R0(`${p} endpoint for region "${E.id}" is outside its bounds`),{regionId:I.regionId,position:x}});for(const I of n)_.has(I.id)||R0(`${p} is missing endpoint for region "${I.id}"`);return f.length!==n.length&&R0(`${p} must contain exactly one endpoint for every region`),s.add(d.id),{id:d.id,endpoints:f}};for(const[d,p]of t.connections.entries()){const m=`connections[${d}]`;if(hR(p,m),"type"in p||"connections"in p){p.type!=="differential"&&R0(`${m} has invalid differential-pair type`),"layer"in p&&R0(`${m}.layer is not accepted; declare layer preferences on a bus`);const _=B$(p.connections,`${m}.connections must contain exactly two members`);_.length!==2&&R0(`${m}.connections must contain exactly two members`);const f=A(_[0],`${m}.connections[0]`),I=A(_[1],`${m}.connections[1]`);f.id===I.id&&R0(`${m} members must have distinct connection ids`),r.push(f,I),a.push([f.id,I.id])}else r.push(A(p,m))}const c=B$(t.buses,"buses must be an array"),l=new Set,u=new Map,g=c.map((d,p)=>{const m=`buses[${p}]`;hR(d,m),pR(d.id,`${m}.id`);const _=d.id;l.has(_)&&R0(`duplicate bus id "${_}"`),l.add(_);const f=B$(d.connectionIds,`${m}.connectionIds must be a non-empty array`);f.length===0&&R0(`${m}.connectionIds must be a non-empty array`);const I=new Set,C=f.map((B,S)=>{pR(B,`${m}.connectionIds[${S}]`),s.has(B)||R0(`${m} references unknown connection "${B}"`),I.has(B)&&R0(`${m} contains duplicate connection "${B}"`),I.add(B);const Q=u.get(B);return Q!==void 0&&R0(`connection "${B}" belongs to multiple buses "${Q}" and "${d.id}"`),u.set(B,_),B});let y;d.preferredLayer!==void 0&&(pR(d.preferredLayer,`${m}.preferredLayer`),y=d.preferredLayer);let x;if(d.preferredLayers!==void 0){const B=B$(d.preferredLayers,`${m}.preferredLayers must be a non-empty array`);B.length===0&&R0(`${m}.preferredLayers must be a non-empty array`);const S=new Set;x=B.map((Q,w)=>(pR(Q,`${m}.preferredLayers[${w}]`),S.has(Q)&&R0(`${m}.preferredLayers contains duplicate layer "${Q}"`),S.add(Q),Q))}let E={id:_,connectionIds:C};return y!==void 0&&(E={...E,preferredLayer:y}),x!==void 0&&(E={...E,preferredLayers:x}),E});for(const[d,p]of a){const m=u.get(d),_=u.get(p);m!==_&&R0(`differential pair "${d}/${p}" must belong to the same bus`)}const h=[...new Set([...g.flatMap(d=>UMe(d)),...r.filter(d=>!u.has(d.id)).map(()=>"top")])].sort((d,p)=>d.localeCompare(p));return{regions:n,connections:r,buses:g,layerNames:h,atomicConnectionGroups:a}},zTo=1e-9,JTo=t=>t==="left"||t==="right",WTo=(t,e)=>e?t.bounds.minY:t.bounds.minX,jTo=(t,e)=>e?t.bounds.maxY:t.bounds.maxX,$To=(t,e)=>e?t.y:t.x,qTo=(t,e)=>{const n=e/2;return Object.fromEntries(t.map((o,i)=>[o,(i-(t.length-1)/2)*n]))},XTo=({referenceOrder:t,layer:e,layerByConnection:n,atomicGroups:o})=>{const i=t.filter(A=>n[A]===e),r=new Map(o.flatMap(A=>A.map(c=>[c,A]))),s=new Set,a=[];for(const A of i){const c=r.get(A);if(!c){a.push(A);continue}s.has(c)||(s.add(c),a.push(...i.filter(l=>c.includes(l))))}return a},ZTo=({regions:t,connections:e,spacing:n,count:o,layerOffsets:i})=>{const r=t.every(h=>JTo(h.edge)),s=Math.max(...t.map(h=>WTo(h,r))),a=Math.min(...t.map(h=>jTo(h,r))),A=Math.min(...Object.values(i)),c=Math.max(...Object.values(i)),l=n*Math.max(0,o-1)+c-A;if(a-s+zTo<l)throw new Ukt(`WindingBreakoutSolver: declared breakout edges need ${l.toFixed(2)}mm but expose only ${(a-s).toFixed(2)}mm`);const u=t.reduce((h,d)=>{const p=e.map(m=>m.endpoints.find(_=>_.regionId===d.id).position);return h+p.reduce((m,_)=>m+$To(_,r),0)/p.length},0)/t.length,g=Math.max(s-A,Math.min(a-n*Math.max(0,o-1)-c,u-n*Math.max(0,o-1)/2));return{vertical:r,axes:Array.from({length:o},(h,d)=>g+d*n)}},eko=(t,e,n)=>{if(n){let i=t.bounds.maxX;return t.edge==="left"&&(i=t.bounds.minX),{x:i,y:e}}let o=t.bounds.maxY;return t.edge==="bottom"&&(o=t.bounds.minY),{x:e,y:o}},tko=({regions:t,connections:e,referenceOrder:n,layerNames:o,layerByConnection:i,boundaryPointSpacing:r,atomicGroups:s})=>{const a=qTo(o,r),A=Object.fromEntries(o.map(h=>[h,XTo({referenceOrder:n,layer:h,layerByConnection:i,atomicGroups:s})])),c=Math.max(...o.map(h=>e.filter(d=>i[d.id]===h).length)),{vertical:l,axes:u}=ZTo({regions:t,connections:e,spacing:r,count:c,layerOffsets:a});return{breakoutPoints:t.flatMap(h=>o.flatMap(d=>A[d].map((p,m)=>({regionId:h.id,connectionId:p,layer:d,...eko(h,u[m]+a[d],l)}))))}},nko=(t,e)=>{const n=new Set(t),o=new Map(e.flatMap(s=>s.map(a=>[a,s]))),i=new Set,r=[];for(const s of t){const a=o.get(s);if(!a){r.push([s]);continue}i.has(a)||(i.add(a),r.push(a.filter(A=>n.has(A))))}return r},oko=({validated:t,referenceOrder:e})=>{const n=new Map;for(const r of t.buses){const s=new Set(r.connectionIds),a=e.filter(l=>s.has(l)),A=UMe(r),c=nko(a,t.atomicConnectionGroups);for(const[l,u]of c.entries()){const g=A[l%A.length];for(const h of u)n.set(h,g)}}for(const r of e)n.has(r)||n.set(r,"top");const o=Object.fromEntries(e.map(r=>[r,n.get(r)])),i=[...new Set(Object.values(o))].sort((r,s)=>r.localeCompare(s));return{layerByConnection:o,layerNames:i}},VMe=t=>[...new Set(Object.values(KMe(t)).flat())].sort((e,n)=>e.localeCompare(n)),Kkt=["#2563eb","#dc2626","#059669","#7c3aed","#d97706","#0891b2","#db2777","#4f46e5","#65a30d","#c2410c","#0f766e","#9333ea"],Jue=t=>{let e=2166136261;for(const n of t)e^=n.charCodeAt(0),e=Math.imul(e,16777619);return Kkt[(e>>>0)%Kkt.length]},vw=(t,e)=>{const n=VMe(t),o=[...new Set(e)].map(i=>{const r=n.indexOf(i);if(r<0)throw new Error(`Cannot visualize unknown signal layer "${i}"`);return r});if(o.length===0)throw new Error("Cannot create graphics metadata without a signal layer");return o.sort((i,r)=>i-r),`z${o.join(",")}`},iko=(t,e)=>{const n={circles:[],rects:[],texts:[]};let i=VMe(t);e&&(i=[e]);const r=vw(t,i),s=zue(t),a=KMe(t),A=Math.min(.12,t.boundaryPointSpacing/4);for(const c of t.regions){const l={x:(c.bounds.minX+c.bounds.maxX)/2,y:(c.bounds.minY+c.bounds.maxY)/2};n.rects.push({center:l,width:c.bounds.maxX-c.bounds.minX,height:c.bounds.maxY-c.bounds.minY,fill:"rgba(226, 232, 240, 0.035)",stroke:"rgba(71, 85, 105, 0.55)",layer:r});for(const u of s){const g=a[u.id];if(e&&!g.includes(e))continue;const h=u.endpoints.find(p=>p.regionId===c.id);if(!h)continue;const d=Jue(u.id);n.circles.push({center:h.position,radius:A,fill:`${d}70`,stroke:d,layer:vw(t,g)})}n.texts.push({x:l.x,y:c.bounds.maxY+.35,text:c.id,anchorSide:"bottom_center",color:"#334155",fontSize:.34,layer:r})}return n},rko=(t,e,n)=>{const o=zue(t),i=e.breakoutPoints.filter(a=>!n||a.layer===n),r=new Map;for(const a of e.breakoutPoints){const A=`${a.regionId}:${a.x.toFixed(9)}:${a.y.toFixed(9)}`,c=r.get(A)??{x:a.x,y:a.y,layers:new Set};c.layers.add(a.layer),r.set(A,c)}return{lines:e.referenceOrder.flatMap(a=>{const A=o.find(g=>g.id===a);if(!A)return[];const c=i.filter(g=>g.connectionId===a),l=c[0]?.layer;if(!l||n&&l!==n)return[];if(c.length!==t.regions.length)return[];const u=t.regions.flatMap((g,h)=>{const d=A.endpoints.find(m=>m.regionId===g.id),p=c.find(m=>m.regionId===g.id);return!d||!p?[]:h===0?[d.position,p]:[p,d.position]});return u.length<2?[]:[{points:u,strokeColor:`${Jue(a)}55`,strokeWidth:.012,strokeDash:[.025,.07],layer:vw(t,[l])}]}),circles:[...r.values()].flatMap(a=>{const A=[...a.layers].filter(c=>!n||c===n);return A.length===0?[]:[{center:a,radius:.11,fill:"rgba(15, 23, 42, 0.06)",stroke:"#475569",layer:vw(t,A)}]}),points:i.map(a=>({x:a.x,y:a.y,color:Jue(a.connectionId),label:`${a.connectionId} · ${a.layer}`,layer:vw(t,[a.layer])}))}},Wue=({input:t,phase:e,detail:n,activeLayer:o,referenceOrder:i,referenceRegionId:r,showReferenceNumbers:s=!1,state:a})=>{const A=iko(t,o);let c;a&&(c=rko(t,a,o));let l=VMe(t);o&&(l=[o]);const u=vw(t,l),g=Math.max(...t.regions.map(_=>_.bounds.maxY)),h=Math.min(...t.regions.map(_=>_.bounds.minX)),d=[...A.texts??[],...c?.texts??[],{x:h,y:g+1.05,text:e,anchorSide:"bottom_left",color:"#0f172a",fontSize:.42,layer:u},{x:h,y:g+.68,text:n,anchorSide:"bottom_left",color:"#475569",fontSize:.25,layer:u}],p=[],m=[];if(s&&i){const _=t.regions.find(x=>x.id===r)??t.regions[0],f=zue(t),I=KMe(t),C=[];for(const[x,E]of i.entries()){const B=f.find(w=>w.id===E),S=I[E];if(!B||!S||o&&!S.includes(o))continue;const Q=B.endpoints.find(w=>w.regionId===_.id);Q&&(C.push(Q.position),d.push({x:Q.position.x+.18,y:Q.position.y+.18,text:`${x+1} · ${E}`,anchorSide:"bottom_left",color:Jue(E),fontSize:.21,layer:vw(t,S)}))}const y={x:(_.bounds.minX+_.bounds.maxX)/2,y:(_.bounds.minY+_.bounds.maxY)/2};p.push(...C.map(x=>({points:[y,x],strokeColor:"rgba(100, 116, 139, 0.35)",strokeWidth:.01,strokeDash:[.03,.05],layer:u}))),C.length>1&&p.push({points:C,strokeColor:"rgba(15, 23, 42, 0.65)",strokeWidth:.018,strokeDash:[.04,.04],label:`${_.id} angular winding order`,layer:u}),m.push({center:y,radius:.07,fill:"#0f172a",stroke:"#ffffff",label:`${_.id} angular reference center`,layer:u})}return{title:e,coordinateSystem:"cartesian",rects:A.rects,polygons:A.polygons,lines:[...c?.lines??[],...p],circles:[...A.circles??[],...c?.circles??[],...m],points:c?.points,texts:d}},Vkt=t=>new Set(t.map(e=>`${e.regionId}:${e.x.toFixed(9)}:${e.y.toFixed(9)}`)).size,sko=class extends fC{constructor(t){super(),this.params=t,this.visualizationLayer=t.visualizationLayer;const e=oko({validated:t.validated,referenceOrder:t.ordering.referenceOrder});this.layerByConnection=e.layerByConnection,this.placementBatches=t.validated.regions.flatMap(n=>e.layerNames.map(o=>({regionId:n.id,layer:o}))),this.MAX_ITERATIONS=this.placementBatches.length+2}params;batchIndex=0;output;plannedPlacement;placementBatches;visibleBreakoutPoints=[];layerByConnection;visualizationLayer;setVisualizationLayer(t){this.visualizationLayer=t}_step(){if(!this.plannedPlacement){this.plannedPlacement=tko({regions:this.params.validated.regions,connections:this.params.validated.connections,referenceOrder:this.params.ordering.referenceOrder,layerNames:[...new Set(Object.values(this.layerByConnection))].sort((e,n)=>e.localeCompare(n)),layerByConnection:this.layerByConnection,boundaryPointSpacing:this.params.input.boundaryPointSpacing,atomicGroups:this.params.validated.atomicConnectionGroups}),this.stats={phase:"plan-gate-grid",regionLayerBatches:this.placementBatches.length,placedBreakpoints:0};return}const t=this.placementBatches[this.batchIndex];if(t){this.visibleBreakoutPoints.push(...this.plannedPlacement.breakoutPoints.filter(e=>e.regionId===t.regionId&&e.layer===t.layer)),this.batchIndex+=1,this.stats={phase:"place-region-layer-batch",regionId:t.regionId,layer:t.layer,completedBatches:this.batchIndex,totalBatches:this.placementBatches.length,placedBreakpoints:this.visibleBreakoutPoints.length};return}this.output=this.plannedPlacement,this.stats={phase:"finalize-shared-gate-slots",placedBreakpoints:this.output.breakoutPoints.length,sharedGateSlots:Vkt(this.output.breakoutPoints)},this.solved=!0}computeProgress(){let t=this.batchIndex;return this.plannedPlacement&&(t+=1),this.output&&(t+=1),t/this.MAX_ITERATIONS}getConstructorParams(){return[this.params]}getOutput(){if(!this.solved||!this.output)throw new YMe("WindingBreakoutSolver: gate placement requested before placement completed");return this.output}visualize(){let t="Next microstep: derive layer offsets, atomic gate orders, and the common boundary slot grid";if(this.plannedPlacement&&this.batchIndex===0)t=`Gate grid planned · ${this.placementBatches.length} region/layer batches remain`;else if(this.plannedPlacement&&!this.output){const i=this.placementBatches[this.batchIndex-1];t=`Placed region “${i.regionId}” on layer “${i.layer}” · ${this.batchIndex}/${this.placementBatches.length} batches`}else if(this.output){const i=Vkt(this.output.breakoutPoints);t=`${this.output.breakoutPoints.length} gates placed; coincident layer positions form ${i} shared slots`}let e;if(this.plannedPlacement){let i=this.visibleBreakoutPoints;this.output&&(i=this.output.breakoutPoints),e={referenceOrder:this.params.ordering.referenceOrder,breakoutPoints:i}}const n=Wue({input:this.params.input,activeLayer:this.visualizationLayer,phase:"Step 2 · Place boundary gates",detail:t,state:e}),o=(this.plannedPlacement?.breakoutPoints??[]).filter(i=>!this.visualizationLayer||i.layer===this.visualizationLayer).map(i=>({center:i,radius:.065,fill:"rgba(255, 255, 255, 0.75)",stroke:"rgba(100, 116, 139, 0.5)",label:`planned slot ${i.regionId} · ${i.layer}`,layer:vw(this.params.input,[i.layer])}));return{...n,circles:[...n.circles??[],...o]}}},ako=(t,e)=>e.map(n=>{const o=n.endpoints.find(i=>i.regionId===t.id).position;return{id:n.id,angle:Math.atan2(o.y-t.center.y,o.x-t.center.x),radius:Math.hypot(o.x-t.center.x,o.y-t.center.y)}}).sort((n,o)=>n.angle-o.angle||o.radius-n.radius||n.id.localeCompare(o.id)).map(n=>n.id),Ako=(t,e,n)=>{const o=new Map(e.flatMap(c=>c.map(l=>[l,c]))),i=new Set,r=[];for(const c of t){const l=o.get(c);if(!l){r.push(c);continue}i.has(l)||(i.add(l),r.push(...t.filter(u=>l.includes(u))))}const s=new Map(n.flatMap(c=>c.connectionIds.map(l=>[l,c]))),a=new Set,A=[];for(const c of r){const l=s.get(c);if(!l){A.push(c);continue}if(a.has(l))continue;a.add(l);const u=new Set(l.connectionIds);A.push(...r.filter(g=>u.has(g)))}return A},cko=class extends fC{constructor(t){super(),this.params=t,this.visualizationLayer=t.visualizationLayer,this.MAX_ITERATIONS=t.validated.regions.length+1}params;naturalOrderByRegion={};currentRegionIndex=0;output;visualizedOrder;visualizedRegionId;visualizationLayer;setVisualizationLayer(t){this.visualizationLayer=t}_step(){const t=this.params.validated.regions[this.currentRegionIndex];if(t){const o=ako(t,this.params.validated.connections);this.naturalOrderByRegion[t.id]=o,this.visualizedRegionId=t.id,this.visualizedOrder=o,this.currentRegionIndex+=1,this.stats={phase:"derive-natural-order",regionId:t.id,completedRegions:this.currentRegionIndex,totalRegions:this.params.validated.regions.length,naturalOrder:o};return}const e=this.params.validated.regions[0],n=Ako(this.naturalOrderByRegion[e.id],this.params.validated.atomicConnectionGroups,this.params.validated.buses);this.output={naturalOrderByRegion:this.naturalOrderByRegion,referenceOrder:n},this.visualizedRegionId=e.id,this.visualizedOrder=n,this.stats={phase:"atomicize-reference-order",referenceRegion:e.id,referenceOrder:n},this.solved=!0}computeProgress(){let t=this.currentRegionIndex;return this.output&&(t+=1),t/this.MAX_ITERATIONS}getConstructorParams(){return[this.params]}getOutput(){if(!this.solved||!this.output)throw new YMe("WindingBreakoutSolver: reference order requested before ordering completed");return this.output}visualize(){const t=this.params.validated.regions[0].id;let e=`Next microstep: derive natural order for region “${t}”`;return this.visualizedRegionId&&!this.output&&(e=`Natural order for region “${this.visualizedRegionId}” · ${this.currentRegionIndex}/${this.params.validated.regions.length} regions processed`),this.output&&(e=`Reference region “${t}” finalized; buses are contiguous and differential pairs are atomic`),Wue({input:this.params.input,activeLayer:this.visualizationLayer,phase:"Step 1 · Derive reference order",detail:e,referenceOrder:this.visualizedOrder,referenceRegionId:this.visualizedRegionId,showReferenceNumbers:!0})}},lko=({points:t,connectionIds:e,regions:n,atomicGroups:o})=>{const i=n.map(u=>u.id),r=new Map,s=new Map;let a=!0;for(const u of t){const g=`${u.regionId}:${u.connectionId}`;r.set(g,(r.get(g)??0)+1);const h=s.get(u.connectionId);h!==void 0&&h!==u.layer&&(a=!1),s.set(u.connectionId,u.layer)}const A=i.flatMap(u=>e.map(g=>`${u}:${g}`)),c=r.size===A.length&&A.every(u=>r.get(u)===1),l=o.every(u=>{const g=s.get(u[0]);return!g||u.some(h=>s.get(h)!==g)?!1:n.every(h=>{const d=t.filter(I=>I.regionId===h.id&&I.layer===g),p=h.edge==="left"||h.edge==="right",m=[...d].sort((I,C)=>p?I.y-C.y:I.x-C.x).map(I=>I.connectionId),_=m.indexOf(u[0]),f=m.indexOf(u[1]);return _!==-1&&f!==-1&&Math.abs(_-f)===1})});return c&&a&&l},uko=({validated:t,placement:e})=>{if(!lko({points:e.breakoutPoints,connectionIds:t.connections.map(o=>o.id),regions:t.regions,atomicGroups:t.atomicConnectionGroups}))throw new YMe("WindingBreakoutSolver: generated invalid breakout points");return{breakoutPoints:e.breakoutPoints}},gko=["referenceOrdering","gatePlacement"],dko=class extends eve{validatedInput;output;visualizationLayer;pipelineDef=[TH("referenceOrdering",cko,t=>[{input:t.inputProblem,validated:t.getValidatedInput(),visualizationLayer:t.visualizationLayer}]),TH("gatePlacement",sko,t=>[{input:t.inputProblem,validated:t.getValidatedInput(),ordering:t.getRequiredStageOutput("referenceOrdering"),visualizationLayer:t.visualizationLayer}])];constructor(t){super(t)}_setup(){this.validatedInput=VTo(this.inputProblem),this.stats={phase:"setup-input-validation",regionCount:this.validatedInput.regions.length,connectionCount:this.validatedInput.connections.length,layerCount:this.validatedInput.layerNames.length}}getValidatedInput(){if(!this.validatedInput)throw new Error("WindingBreakoutSolver: input has not been validated");return this.validatedInput}_step(){super._step(),!this.output&&!this.activeSubSolver&&this.currentPipelineStageIndex>=this.pipelineDef.length&&(this.output=uko({validated:this.getValidatedInput(),placement:this.getRequiredStageOutput("gatePlacement")}),this.solved=!0),this.stats={phase:this.getCurrentStageName(),completedStages:this.currentPipelineStageIndex,totalStages:this.pipelineDef.length},this.solved&&(this.stats.phase="finalize-output-validation"),this.output&&(this.stats.valid=!0,this.stats.breakoutPointCount=this.output.breakoutPoints.length)}getRequiredStageOutput(t){const e=this.getStageOutput(t);if(e===void 0)throw new Error(`WindingBreakoutSolver: pipeline stage “${t}” has no output`);return e}setVisualizationLayer(t){this.visualizationLayer=t;for(const e of gko){const n=this.getSolver(e);n&&"setVisualizationLayer"in n&&n.setVisualizationLayer(t)}}getConstructorParams(){return[this.inputProblem]}getOutput(){if(!this.solved||!this.output)throw new HTo("WindingBreakoutSolver: getOutput() called before successful completion");return this.output}initialVisualize(){return Wue({input:this.inputProblem,activeLayer:this.visualizationLayer,phase:"Input · Validated during setup",detail:"Region bounds, breakout edges, bus layer preferences, and canonical endpoints"})}finalVisualize(){if(!this.output)return null;const t=this.getRequiredStageOutput("referenceOrdering");return Wue({input:this.inputProblem,activeLayer:this.visualizationLayer,phase:"Output · Validated after gate placement",detail:"Valid: one bus-constrained breakout point per connection and region; pairs are adjacent",state:{referenceOrder:t.referenceOrder,breakoutPoints:this.output.breakoutPoints}})}visualize(){return{...super.visualize(),title:"Winding breakout solver · step-by-step pipeline",coordinateSystem:"cartesian"}}},zkt=t=>({id:t.connectionId,endpoints:t.endpoints}),hko=t=>{const e={regions:t.regions.map(o=>({id:o.regionId,bounds:o.bounds,edge:o.edge})),connections:t.connections.map(o=>"type"in o?{type:"differential",connections:o.connections.map(zkt)}:zkt(o)),buses:t.buses.map(o=>({id:o.busId,connectionIds:o.connectionIds,preferredLayers:o.targetLayers})),boundaryPointSpacing:t.boundaryPointSpacing},n=new dko(e);return n.solve(),n.getOutput()},Jkt=t=>{const e=t.outline?Oh(t.outline):null,n=t.width??(e?e.maxX-e.minX:void 0),o=t.height??(e?e.maxY-e.minY:void 0);return n===void 0||o===void 0?null:{minX:t.center.x-n/2,maxX:t.center.x+n/2,minY:t.center.y-o/2,maxY:t.center.y+o/2}},Wkt=(t,e,n,o)=>Math.max(t-o,n-e,0),pko=t=>{if(t.root?.pcbDisabled||!t.pcb_group_id)return;const e=t.root;if(!e)return;const n=t.parent?.children.filter(a=>a instanceof t.constructor);if(!n)return;const o=n.indexOf(t);if(o<0)return;const{db:i}=e,r=i.pcb_group.get(t.pcb_group_id);if(!r)return;const s=Jkt(r);if(s)for(const a of n.slice(o+1)){if(!a.pcb_group_id)continue;const A=i.pcb_group.get(a.pcb_group_id);if(!A)continue;const c=Jkt(A);if(!c)continue;const l=t._parsedProps.fanoutMargin,u=a._parsedProps.fanoutMargin,g=Math.max(typeof l=="number"?l:0,typeof u=="number"?u:0),h=Wkt(s.minX,s.maxX,c.minX,c.maxX),d=Wkt(s.minY,s.maxY,c.minY,c.maxY),p=Math.min(s.maxX,c.maxX)-Math.max(s.minX,c.minX),m=Math.min(s.maxY,c.maxY)-Math.max(s.minY,c.minY),_=p>0&&m>0,f=g>0&&h<g&&d<g;if(!_&&!f)continue;const I=_?`Fanout boundaries "${t.name}" and "${a.name}" overlap. Fanout boundaries may not overlap.`:`Fanout boundaries "${t.name}" and "${a.name}" do not maintain the required ${g}mm fanoutMargin.`;i.pcb_placement_error.list().some(y=>y.message===I)||i.pcb_placement_error.insert({error_type:"pcb_placement_error",message:I,subcircuit_id:t.subcircuit_id??void 0})}},mko=(t,e)=>{if(!(e instanceof Ukt)||!t.root||!t.pcb_group_id)return!1;const n=t.root.db.pcb_component.list().filter(o=>o.pcb_group_id===t.pcb_group_id).map(o=>o.source_component_id?t.root.db.source_component.get(o.source_component_id)?.name:void 0).filter(o=>!!o);return t.root.db.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouting_error_winding_breakout_${t.pcb_group_id}`,error_type:"pcb_autorouting_error",message:`Winding fanout failed for ${n.join(", ")||t.name}: ${e.message}. The connections could not escape to the breakout boundary. Give the fanout more room by increasing the breakout's padding, or by extending the breakout to include the parts crowding it (decoupling capacitors, series resistors).`}),!0},_ko=t=>{const e=t.parent;if(!e?.selectAll)throw new Error(`Automatic breakout "${t.name}" has no coordinated routing scope`);return e},fko=(t,e)=>{const n=[];for(const r of t.selectAll("group")){if(!r.isRoutingDirective||r.parent!==t)continue;const s=r;s.children.some(A=>A instanceof Kue)&&n.push(s)}const o=r=>new Set(jkt(r).endpointBySourceTraceId.keys()),i=o(e);return n.filter(r=>{const s=o(r);return s.size===i.size&&[...i].every(a=>s.has(a))})},jkt=t=>{if(!t.root||!t.pcb_group_id)throw new Error(`Automatic breakout "${t.name}" has no PCB region`);const e=t.root.db.pcb_group.get(t.pcb_group_id);if(!e||!e.width||!e.height)throw new Error(`Automatic breakout "${t.name}" has invalid PCB region bounds`);const n={minX:e.center.x-e.width/2,maxX:e.center.x+e.width/2,minY:e.center.y-e.height/2,maxY:e.center.y+e.height/2},o={x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2},i=new Map,r=new Map;for(const s of t.children.filter(a=>a instanceof Kue)){const a=s.matchedPort;if(!a?.pcb_port_id||!a.source_port_id)throw new Error(`Automatic breakout "${t.name}" is missing a PCB endpoint`);let A=s.matchedSourceTraceId;if(!A){const l=t.root.db.source_trace.list().filter(h=>h.connected_source_port_ids.includes(a.source_port_id));if(l.length===0)throw new Error(`Automatic breakout "${t.name}" has a point without a source trace identity`);const u=l.filter(h=>h.connected_source_port_ids.some(d=>{if(d===a.source_port_id)return!1;const p=t.root.db.pcb_port.getWhere({source_port_id:d});return!p||p.pcb_group_id===t.pcb_group_id?!1:!(p.x>=n.minX&&p.x<=n.maxX&&p.y>=n.minY&&p.y<=n.maxY)}));A=(u.length>0?u:l).slice().sort((h,d)=>h.source_trace_id.localeCompare(d.source_trace_id))[0].source_trace_id,s.matchedSourceTraceId=A}if(i.has(A))throw new Error(`Connection "${A}" has duplicate endpoint for region "${t.pcb_group_id}"`);const c=t.root.db.pcb_port.get(a.pcb_port_id);if(!c)throw new Error(`Connection "${A}" references unknown PCB endpoint "${a.pcb_port_id}"`);if(c.pcb_group_id!==t.pcb_group_id)throw new Error(`Connection "${A}" endpoint references unknown region "${c.pcb_group_id??"unassigned"}" instead of "${t.pcb_group_id}"`);if(c.x===void 0||c.y===void 0)throw new Error(`Connection "${A}" is missing endpoint coordinates for region "${t.pcb_group_id}"`);i.set(A,{regionId:t.pcb_group_id,position:{x:c.x,y:c.y}}),r.set(A,a.source_port_id)}return{breakout:t,pcbGroupId:t.pcb_group_id,bounds:n,center:o,endpointBySourceTraceId:i,sourcePortIdBySourceTraceId:r}},Iko=t=>{const e=t.map(s=>s.center.x),n=t.map(s=>s.center.y),o=Math.max(...e)-Math.min(...e),i=Math.max(...n)-Math.min(...n),r=o>=i;return t.sort((s,a)=>{if(r){const A=s.center.x-a.center.x;if(A!==0)return A;const c=s.center.y-a.center.y;if(c!==0)return c}else{const A=s.center.y-a.center.y;if(A!==0)return A;const c=s.center.x-a.center.x;if(c!==0)return c}return s.breakout.name.localeCompare(a.breakout.name)}),{regions:t,horizontalPlacement:r}},Cko=({region:t,regionIndex:e,regions:n,horizontalPlacement:o,singleRegionPreferredEdge:i})=>{if(n.length===1&&i)return i;const r=n.filter(a=>a!==t),s=r.reduce((a,A)=>({x:a.x+A.center.x/r.length,y:a.y+A.center.y/r.length}),{x:0,y:0});return o?s.x>t.center.x?"right":s.x<t.center.x?"left":e<n.length/2?"right":"left":s.y>t.center.y?"top":s.y<t.center.y?"bottom":e<n.length/2?"top":"bottom"},yko=({region:t,sourceTraces:e})=>{const n=t.breakout.root;if(!n)return;const o=new Set(t.sourcePortIdBySourceTraceId.values()),i=new Map;for(const a of e)if(a.connected_source_port_ids.some(A=>o.has(A)))for(const A of a.connected_source_port_ids){if(o.has(A))continue;const c=n.db.pcb_port.getWhere({source_port_id:A});!c?.pcb_port_id||c.x===void 0||c.y===void 0||c.x>=t.bounds.minX&&c.x<=t.bounds.maxX&&c.y>=t.bounds.minY&&c.y<=t.bounds.maxY||i.set(c.pcb_port_id,{x:c.x,y:c.y})}if(i.size===0)return;const r=(a,A)=>{const c=A==="left"||A==="right"?{x:A==="left"?t.bounds.minX:t.bounds.maxX,y:Math.max(t.bounds.minY,Math.min(t.bounds.maxY,a.y))}:{x:Math.max(t.bounds.minX,Math.min(t.bounds.maxX,a.x)),y:A==="bottom"?t.bounds.minY:t.bounds.maxY};return Math.hypot(a.x-c.x,a.y-c.y)},s=["right","left","top","bottom"];return s.reduce((a,A)=>{const c=[...i.values()].reduce((u,g)=>u+r(g,a),0);return[...i.values()].reduce((u,g)=>u+r(g,A),0)<c?A:a},s[0])},zMe=({connectionOwner:t,connectionOwnerLabel:e,connectionSelector:n,sourceTraces:o})=>{let r=o.filter(s=>s.name===n);if(r.length===0){const s=t.getSubcircuit().selectOne(n,{type:"port"});s?.source_port_id&&(r=o.filter(a=>a.connected_source_port_ids.includes(s.source_port_id)))}if(r.length===0)throw new Error(`Could not resolve "${n}" in ${e}`);if(r.length>1)throw new Error(`Connection "${n}" resolves to multiple source traces in ${e}`);return r[0]},xko=({routingScope:t,sourceTraces:e,coordinatedSourceTraceIds:n,availableLayers:o})=>{const i=[],r=t.getSubcircuit().subcircuit_id;for(const s of t.selectAll("bus")){if(s.getSubcircuit().subcircuit_id!==r)continue;const a=[];for(const c of s._parsedProps.connections){const l=zMe({connectionOwner:s,connectionOwnerLabel:`bus "${s.name}"`,connectionSelector:c,sourceTraces:e});n.has(l.source_trace_id)&&a.push(l.source_trace_id)}if(a.length===0)continue;let A={busId:s.name,connectionIds:a};if(s._parsedProps.preferredLayer!==void 0)A={...A,targetLayers:[s._parsedProps.preferredLayer]};else if(s._parsedProps.preferredLayers!==void 0)A={...A,targetLayers:s._parsedProps.preferredLayers};else{const c=s._parsedProps.pcbAllowedLayers??o;A={...A,targetLayers:[...new Set(c)]}}i.push(A)}return i},Eko=({routingScope:t,sourceTraces:e})=>{const n=t.getSubcircuit().subcircuit_id,o=[];for(const i of t.selectAll("differentialpair")){if(i.getSubcircuit().subcircuit_id!==n)continue;const r=zMe({connectionOwner:i,connectionOwnerLabel:`differential pair "${i.name}"`,connectionSelector:i._parsedProps.positiveConnection,sourceTraces:e}),s=zMe({connectionOwner:i,connectionOwnerLabel:`differential pair "${i.name}"`,connectionSelector:i._parsedProps.negativeConnection,sourceTraces:e});o.push({differentialPair:i,positiveSourceTraceId:r.source_trace_id,negativeSourceTraceId:s.source_trace_id})}return o},Bko=t=>{const e=t.root?.db.pcb_board.list()[0],n=e?.min_trace_width??.15,o=e?.min_trace_to_pad_edge_clearance??.2,i=e?.min_via_pad_diameter??.3;return gRt({traceWidth:n,traceToPadClearance:o,viaPadDiameter:i})},bko=({routingScope:t,automaticBreakouts:e})=>{let n=Owe(t._getSubcircuitLayerCount());for(const o of e){const i=o._parsedProps.fanoutRoutingLayers?.map(String);if(!i)continue;const r=new Set(i);n=n.filter(s=>r.has(s))}if(n.length===0)throw new Error(`Automatic breakouts in routing scope "${t.name}" have no shared fanout routing layer`);return n},Sko=t=>{if(!t.root)throw new Error(`Automatic breakout "${t.name}" has no circuit root`);const e=_ko(t),n=fko(e,t),o=new Set,i=n.map(I=>{const C=jkt(I);if(o.has(C.pcbGroupId))throw new Error(`Duplicate automatic breakout region "${C.pcbGroupId}"`);return o.add(C.pcbGroupId),C}),{regions:r,horizontalPlacement:s}=Iko(i),a=new Set;for(const I of r)for(const C of I.endpointBySourceTraceId.keys())a.add(C);const A=t.root.db.source_trace.list().filter(I=>I.subcircuit_id===e.getSubcircuit().subcircuit_id),c=new Map;for(const I of A){if(c.has(I.source_trace_id))throw new Error(`Duplicate connection identity "${I.source_trace_id}"`);c.set(I.source_trace_id,I)}const l=[...a].sort((I,C)=>{const y=c.get(I)?.name??I,x=c.get(C)?.name??C,E=y.localeCompare(x);return E!==0?E:I.localeCompare(C)});for(const I of l){if(!c.has(I))throw new Error(`Unknown connection identity "${I}"`);for(const C of r)if(!C.endpointBySourceTraceId.has(I))throw new Error(`Connection "${I}" is missing endpoint for region "${C.pcbGroupId}"`)}const u=xko({routingScope:e,sourceTraces:A,coordinatedSourceTraceIds:a,availableLayers:bko({routingScope:e,automaticBreakouts:n})}),g=new Map;for(const I of l)g.set(I,r.map(C=>C.endpointBySourceTraceId.get(I)));const h=new Map;for(const I of Eko({routingScope:e,sourceTraces:A})){const C=a.has(I.positiveSourceTraceId),y=a.has(I.negativeSourceTraceId);if(C!==y)throw new Error(`Differential pair "${I.differentialPair.name}" is missing one coordinated member`);if(C){if(h.has(I.positiveSourceTraceId)||h.has(I.negativeSourceTraceId))throw new Error("A connection belongs to multiple differential pairs");h.set(I.positiveSourceTraceId,I),h.set(I.negativeSourceTraceId,I)}}const d=[],p=new Set;for(const I of l){const C=h.get(I);if(!C){d.push({connectionId:I,endpoints:g.get(I)});continue}p.has(C.differentialPair)||(p.add(C.differentialPair),d.push({type:"differential",connections:[{connectionId:C.positiveSourceTraceId,endpoints:g.get(C.positiveSourceTraceId)},{connectionId:C.negativeSourceTraceId,endpoints:g.get(C.negativeSourceTraceId)}]}))}const m=new Map,_=r.length===1?yko({region:r[0],sourceTraces:A}):void 0;return{input:{regions:r.map((I,C)=>(m.set(I.pcbGroupId,I.sourcePortIdBySourceTraceId),{regionId:I.pcbGroupId,bounds:I.bounds,edge:Cko({region:I,regionIndex:C,regions:r,horizontalPlacement:s,singleRegionPreferredEdge:_})})),connections:d,buses:u,boundaryPointSpacing:Bko(t)},sourcePortIdByConnectionIdByRegionId:m}},$kt=new WeakMap,Qko=(t,e)=>{const n=Sko(t),o=e(n.input);if(o instanceof Promise)throw new Error("Implicit breakout point solvers must return synchronously during PCB layout");let i=0;for(const a of n.input.connections){if("type"in a){i+=a.connections.length;continue}i+=1}const r=new Map,s=new Set;for(const a of n.input.regions)r.set(a.regionId,[]);for(const a of o.breakoutPoints){const A=r.get(a.regionId);if(!A)throw new Error(`Implicit breakout point solver returned unknown region "${a.regionId}"`);const c=`${a.regionId}:${a.connectionId}`;if(s.has(c))throw new Error(`Implicit breakout point solver returned duplicate endpoint for connection "${a.connectionId}" in region "${a.regionId}"`);s.add(c);const l=n.sourcePortIdByConnectionIdByRegionId.get(a.regionId)?.get(a.connectionId);if(!l)throw new Error(`Implicit breakout point solver returned unknown connection "${a.connectionId}" for region "${a.regionId}"`);A.push({sourcePortId:l,sourceTraceId:a.connectionId,layer:a.layer,x:a.x,y:a.y})}for(const[a,A]of r)if(A.length!==i)throw new Error(`Implicit breakout point solver output is missing endpoints for region "${a}"`);return{breakoutPointsByRegionId:r}},vko=(t,e)=>{const n=t.parent;if(!n||!t.pcb_group_id)throw new Error(`Automatic breakout "${t.name}" has no coordinated PCB region`);let o=$kt.get(n);(!o||o.solverFn!==e)&&(o={solverFn:e,solutions:[]},$kt.set(n,o));let i=o.solutions.find(s=>s.breakoutPointsByRegionId.has(t.pcb_group_id));i||(i=Qko(t,e),o.solutions.push(i));const r=i.breakoutPointsByRegionId.get(t.pcb_group_id);if(!r)throw new Error(`Automatic breakout "${t.name}" references unknown implicit-breakout region "${t.pcb_group_id}"`);return r},JMe=class extends A6{get isRoutingDirective(){return!0}get config(){return{...super.config,zodProps:Ewn}}doInitialCreateAutoplacedBreakoutPoints(){for(const s of this._parsedProps.pcbTracePaths??[]){const a=s.route.at(-1),A=new zTt({connection:s.connection,pcbX:a.x,pcbY:a.y});if(A.exitLayer=a.route_type==="wire"?a.layer:a.to_layer,this.add(A),A._matchConnection(),!A.matchedPort||!this.selectAll("port").includes(A.matchedPort))throw new Error(`Fanout trace path "${s.connection}" must select a port inside the fanout`);if(this.children.some(l=>!(l instanceof dR)||l===A?!1:(l._matchConnection(),l.matchedPort===A.matchedPort)))throw new Error(`Duplicate fanout exit for "${s.connection}"`)}const t=this.selectAll("port"),e=new Set(t),n=this.children.filter(s=>s instanceof dR),o=new Set(n.map(s=>(s._matchConnection(),s.matchedPort)).filter(Boolean)),i=this.getSubcircuit().selectAll("trace"),r=new Set;for(const s of i){const a=s._findConnectedPorts();if(!(!a.allPortsFound||!a.ports))for(const A of a.ports){const c=e.has(A),l=a.ports.some(g=>!e.has(g));if(!c||!l||o.has(A)||r.has(A))continue;r.add(A);const u=new Kue({});u.matchedPort=A,u.matchedSourceTraceId=s.source_trace_id,this.add(u)}}}doInitialPcbAutoplaceBreakoutPoints(){if(this.root?.pcbDisabled)return;const t=this.props.autorouter,e=t===void 0?this.parent?.getInheritedProperty("autorouter"):void 0,n=typeof t=="object"?t.implicitBreakoutPointSolverFn:typeof e=="object"?e.implicitBreakoutPointSolverFn:void 0,o=this.children.filter(c=>c instanceof Kue);if(o.length===0||!this.root||!this.pcb_group_id)return;const i=this.root.db.pcb_group.get(this.pcb_group_id);if(!i?.width||!i.height)return;const r={minX:i.center.x-i.width/2,maxX:i.center.x+i.width/2,minY:i.center.y-i.height/2,maxY:i.center.y+i.height/2};let s;try{s=vko(this,n??hko)}catch(c){if(n||!mko(this,c))throw c;return}const a=1e-4,A=(c,l)=>({x:Math.max(r.minX+a,Math.min(r.maxX-a,c)),y:Math.max(r.minY+a,Math.min(r.maxY-a,l))});for(const c of s){const l=o.find(u=>u.matchedPort?.source_port_id===c.sourcePortId);if(l){const u=A(c.x,c.y);l._applySolvedBreakoutPoint({sourceTraceId:c.sourceTraceId,layer:c.layer,position:u})}}}doInitialPcbPrimitiveRender(){super.doInitialPcbPrimitiveRender()}doInitialPcbPlacementDesignRuleChecks(){pko(this)}},wko=class extends Ir{pcb_silkscreen_graphic_id=null;pcb_silkscreen_graphic_ids=[];pcb_silkscreen_path_ids=[];isPcbPrimitive=!0;get config(){return{componentName:"SilkscreenGraphic",zodProps:CDn}}doInitialPcbPrimitiveRender(){this.root?.pcbDisabled||this._queueAsyncEffect("SilkscreenGraphicRender",async()=>{if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),o=n(e.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenGraphic. Must be "top" or "bottom".`);const i=await xPt(e.imageUrl);if(i.mimetype!==Eb&&i.mimetype!==yPt)throw new Error(`Unsupported imageUrl for SilkscreenGraphic: "${e.imageUrl}". Expected an SVG or PNG image.`);const r={project_relative_path:i.projectRelativePath,url:i.dataUrl,mimetype:i.mimetype},s=i.mimetype===Eb?eBo({svg:i.text,width:e.width,height:e.height,transform:this._computePcbGlobalTransformBeforeLayout()}):[this.getPlacementBoxBRepShape()],a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??"";for(const A of s){const c=t.insert({type:"pcb_silkscreen_graphic",pcb_component_id:a,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0,layer:o,shape:"brep",brep_shape:A,image_asset:r});this.pcb_silkscreen_graphic_ids.push(c.pcb_silkscreen_graphic_id)}this.pcb_silkscreen_graphic_id=this.pcb_silkscreen_graphic_ids[0]??null,i.mimetype===Eb&&this.insertRenderableSilkscreenPaths(i.text,o)})}insertRenderableSilkscreenPaths(t,e){const{db:n}=this.root,{_parsedProps:o}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??"";for(const s of EPt({svg:t,width:o.width,height:o.height,transform:i})){if(s.length<2)continue;const a=n.pcb_silkscreen_path.insert({pcb_component_id:r,layer:e,route:s,stroke_width:Math.max(Math.min(o.width,o.height)/60,.05),subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_ids.push(a.pcb_silkscreen_path_id)}}getPcbSize(){const{_parsedProps:t}=this;return{width:t.width,height:t.height}}getPlacementBoxBRepShape(){const{_parsedProps:t}=this,e=t.width/2,n=t.height/2,o=this._computePcbGlobalTransformBeforeLayout();return{outer_ring:{vertices:BPt([{x:-e,y:n},{x:e,y:n},{x:e,y:-n},{x:-e,y:-n}]).map(i=>ts(o,i))},inner_rings:[]}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root,o=i=>({...i,x:i.x+t,y:i.y+e});for(const i of this.pcb_silkscreen_graphic_ids){const r=n.pcb_silkscreen_graphic.get(i);r&&n.pcb_silkscreen_graphic.update(i,{brep_shape:{outer_ring:{vertices:r.brep_shape.outer_ring.vertices.map(o)},inner_rings:r.brep_shape.inner_rings.map(s=>({vertices:s.vertices.map(o)}))}})}for(const i of this.pcb_silkscreen_path_ids){const r=n.pcb_silkscreen_path.get(i);r&&n.pcb_silkscreen_path.update(i,{route:r.route.map(s=>({...s,x:s.x+t,y:s.y+e}))})}}},Pko=class extends Ir{pcb_smtpad_id=null;isPcbPrimitive=!0;get config(){return{componentName:"Fiducial",zodProps:llt,sourceFtype:"simple_fiducial"}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),i=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,r=t.pcb_smtpad.insert({pcb_component_id:i,layer:o(e.layer||"top"),shape:"circle",x:n.x,y:n.y,radius:lt.parse(e.padDiameter)/2,soldermask_margin:e.soldermaskPullback?lt.parse(e.soldermaskPullback):lt.parse(e.padDiameter)/2,is_covered_with_solder_mask:!0});this.pcb_smtpad_id=r.pcb_smtpad_id}getPcbSize(){const{_parsedProps:t}=this,e=lt.parse(t.padDiameter);return{width:e,height:e}}_setPositionFromLayout(t){if(!this.pcb_smtpad_id)return;const{db:e}=this.root;e.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y})}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_smtpad_id)return;const o=n.pcb_smtpad.get(this.pcb_smtpad_id);o&&(o.shape==="rect"||o.shape==="circle"||o.shape==="rotated_rect"||o.shape==="pill"?this._setPositionFromLayout({x:o.x+t,y:o.y+e}):o.shape==="polygon"&&n.pcb_smtpad.update(this.pcb_smtpad_id,{points:o.points.map(i=>({x:i.x+t,y:i.y+e}))}))}},qkt=class extends Ir{isAssemblyDeviceContainer=!0;get config(){return{componentName:"AssemblyDevice",zodProps:mvn}}doInitialAssignNameToUnnamedComponents(){}computeSchematicGlobalTransform(){return hC()}_computePcbGlobalTransformBeforeLayout(){return hC()}},Mko=({cad:t,authoredModel:e})=>{const n=t.model_bounds??e?.modelBounds,o=t.model_origin_position??e?.modelOriginPosition;if(!n?.min||!n?.max||!o)return;const i=t.model_board_normal_direction??e?.modelBoardNormalDirection??"z+",r=i[0];if(r!=="x"&&r!=="y"&&r!=="z")return;const s=n.min[r],a=n.max[r],A=o[r];if(s===void 0||a===void 0||A===void 0)return;const c=i.endsWith("-")?A-s:a-A;return Number.isFinite(c)&&c>=0?c:void 0},Dko=({owner:t,pcbComponent:e,cadComponent:n,boardSurfaceZ:o})=>{const i=t?._parsedProps?.cadModel,r=i&&typeof i=="object"?i:void 0,s=n?.size??r?.size,a=s?.x,A=s?.y,c=s?.z,l=n?Mko({cad:n,authoredModel:r}):void 0,u=n?.position?.z,g=l!==void 0&&u!==void 0?l+Math.abs(u-o):void 0;return{size:a!==void 0&&A!==void 0?{x:a,y:A,z:c}:void 0,aboveBoardHeight:g,rotation:n?.rotation?.z??e.rotation??0,footprint:{width:e.width,height:e.height}}},Nko=({point:t,board:e})=>{const n=(e.width??0)/2,o=(e.height??0)/2,i=[["x_neg",Math.abs(t.x-(e.center.x-n))],["x_pos",Math.abs(t.x-(e.center.x+n))],["y_neg",Math.abs(t.y-(e.center.y-o))],["y_pos",Math.abs(t.y-(e.center.y+o))]];return i.sort((r,s)=>r[1]-s[1]),i[0][0]},Rko=t=>t,Tko={from_top:"y_pos",from_bottom:"y_neg",from_left:"x_neg",from_right:"x_pos"},kko=(t,{board:e,pcbBoard:n})=>{let o=t.parent;for(;o&&o!==e&&!o.pcb_component_id;)o=o.parent;const i=o?.pcb_component_id?t.root?.db.pcb_component.get(o.pcb_component_id):null;if(!i)throw new Error("<enclosure.cutoutaperture /> must be nested inside a component with a PCB footprint");const r=t._parsedProps,a=o?._getEnclosureApertureAxisDirection?.(i.layer,i.rotation??0),A=a?a.z!==0?a.z>0?"from_above":"from_below":Math.abs(a.x)>=Math.abs(a.y)?a.x>=0?"from_right":"from_left":a.y>=0?"from_top":"from_bottom":i.insertion_direction,c=A==="from_above"?"z_pos":A==="from_below"?"z_neg":void 0,l=i.layer==="bottom"?"bottom":"top";let u,g;if(c)u=c,g={x:i.center.x-n.center.x,y:i.center.y-n.center.y};else{const _=i.cable_insertion_center??i.center,f=Tko[A]??Nko({point:_,board:n}),I=i.cable_insertion_center?{x:i.cable_insertion_center.x-i.center.x,y:i.cable_insertion_center.y-i.center.y}:null,C=I!=null&&(f==="x_neg"||f==="x_pos"?Math.abs(I.x)>=Math.abs(I.y):Math.abs(I.y)>=Math.abs(I.x)),y=a?i.center:C?_:i.center;u=Rko(f),g={x:y.x-n.center.x,y:y.y-n.center.y}}const h=t.root?.db.cad_component.getWhere({pcb_component_id:i.pcb_component_id})??null,d=(l==="bottom"?-1:1)*((n.thickness??e.boardThickness)/2),p=Dko({owner:o,pcbComponent:i,cadComponent:h,boardSurfaceZ:d}),m={face:u,center:g,boardSide:l,apertureAxisDirection:a,rotation:i.rotation??void 0,depth:r.depth,componentBody:p,widthDimensionOffset:r.widthDimensionOffset,heightDimensionOffset:r.heightDimensionOffset,margin:r.margin};switch(r.shape){case"pill":case"rect":return{...m,shape:r.shape,width:r.width,height:r.height};case"circle":return{...m,shape:"circle",radius:r.radius}}},WMe=class extends Ir{get config(){return{componentName:"EnclosureCutoutAperture",zodProps:fvn}}getFdmEnclosureSolverInput(t){return kko(this,t)}},Xkt=(t,e)=>{const n=t.root?.firstChild,o=n?poe(e,n,{adapter:S0e}):null,i=o instanceof wB?o:[n,...n?.getDescendants()??[]].find(r=>r instanceof wB&&r.isMatchingNameOrAlias(e));if(!(i instanceof wB))throw new Error(`Could not find a <board /> matching enclosure boardRef "${e}"`);return i},Fko=t=>{const e=t.root;if(!e||e.pcbDisabled||!t.source_component_id||!t.pcb_component_id)return;const{db:n}=e,o=t._parsedProps,i=Xkt(t,o.boardRef),r=i.pcb_board_id?n.pcb_board.get(i.pcb_board_id):null;if(!r?.width||!r.height)throw new Error(`Could not resolve dimensions for boardRef "${o.boardRef}"`);const s=r.thickness??i.boardThickness,a={board:{width:r.width,height:r.height,thickness:s},width:o.width,height:o.height,depth:o.depth,wallThickness:o.wallThickness,floorThickness:o.floorThickness,lidThickness:o.lidThickness,boardClearance:o.boardClearance,standoffHeight:o.standoffHeight,topHeadroom:o.topHeadroom,lidLipDepth:o.lidLipDepth,apertures:o.disableCutouts?[]:i.getDescendants().filter(h=>h instanceof WMe).map(h=>h.getFdmEnclosureSolverInput({board:i,pcbBoard:r}))},A=new Vbt(a),c=A.getConstructorParams();if(e.emit("solver:started",{type:"solver:started",solverName:"CreateFdmEnclosureSolver",solverParams:c[0],solverConstructorArgs:c,componentName:t.getString()}),A.solve(),A.failed)throw new Error(A.error??"Failed to create FDM enclosure");const l=A.getOutput();n.pcb_component.update(t.pcb_component_id,{center:r.center,width:l.dimensions.width,height:l.dimensions.height});const u={x:r.center.x,y:r.center.y,z:-s/2-l.dimensions.floorThickness-l.dimensions.standoffHeight},g=l.parts.map(h=>n.cad_component.insert({position:u,rotation:{x:0,y:0,z:0},pcb_component_id:t.pcb_component_id,source_component_id:t.source_component_id,model_jscad:h.jscadPlan,model_unit_to_mm_scale_factor:1,model_object_fit:"contain_within_bounds",model_origin_alignment:"bottom_center_of_component",anchor_alignment:"center",show_as_translucent_model:!1,show_hidden_edges:o.showHiddenEdges}));t.cad_component_id=g[0]?.cad_component_id??null},Zkt=class p4n extends Ir{get config(){return{componentName:"EnclosureFdmBox",zodProps:Ivn}}doInitialAssignNameToUnnamedComponents(){if(this._parsedProps.name)return;let e=this;for(;e.parent instanceof Ir;)e=e.parent;const o=[e,...e.getDescendants()].filter(i=>i instanceof p4n).indexOf(this);this.fallbackUnassignedName=`unnamed_enclosure_fdm_box_${o===-1?0:o+1}`}doInitialSourceRender(){const e=this.root.db.source_component.insert({ftype:"simple_chip",name:this.name});this.source_component_id=e.source_component_id}doInitialPcbComponentRender(){const e=this.root;if(!e||e.pcbDisabled||!this.source_component_id)return;const n=Xkt(this,this._parsedProps.boardRef),i=(n.pcb_board_id?e.db.pcb_board.get(n.pcb_board_id):null)?.center??n._getGlobalPcbPositionBeforeLayout(),r=e.db.pcb_component.insert({center:i,width:0,height:0,layer:"top",rotation:0,source_component_id:this.source_component_id,obstructs_within_bounds:!1,do_not_place:!0,is_allowed_to_be_off_board:!0});this.pcb_component_id=r.pcb_component_id}doInitialCadModelRender(){Fko(this)}},Lko=class extends g0{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:TPn,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,are_pins_interchangeable:!1,display_name:e.displayName});this.source_component_id=n.source_component_id}},Hko=class extends g0{_getPcbRotationBeforeLayout(){const e=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+e}get config(){return{componentName:"PinHeader",zodProps:LPn,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){const e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),n=this._parsedProps.holeDiameter,o=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels,s=this._parsedProps.doubleRow?2:1,a=this._parsedProps.gender;if(e>0){let A;if(i)!n&&!o?A=`pinrow${e}_p${i}`:A=`pinrow${e}_p${i}_id${n}_od${o}`;else if(!n&&!o)A=`pinrow${e}`;else return null;return r!==!0&&(A+="_nopinlabels"),a==="female"&&(A+="_female"),s>1&&(A+=`_rows${s}`),A}return null}initPorts(){const e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let n=1;n<=e;n++){const o=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[n-1]:this._parsedProps.pinLabels?.[`pin${n}`];if(o){const i=Array.isArray(o)?o[0]:o,r=Array.isArray(o)?o.slice(1):[];this.add(new Pu({pinNumber:n,name:i,aliases:[`pin${n}`,...r]}))}else this.add(new Pu({pinNumber:n,name:`pin${n}`}))}}_getSchematicPortArrangement(){const e=this._parsedProps.pinCount??1,n=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",o=this._parsedProps.schPinArrangement,i=Array.from({length:e},(r,s)=>`pin${s+1}`);return n==="left"?{leftSide:{direction:o?.leftSide?.direction??"top-to-bottom",pins:o?.leftSide?.pins??i}}:n==="up"?{topSide:{direction:o?.topSide?.direction??"left-to-right",pins:o?.topSide?.pins??i}}:n==="down"?{bottomSide:{direction:o?.bottomSide?.direction??"left-to-right",pins:o?.bottomSide?.pins??i}}:{rightSide:{direction:o?.rightSide?.direction??"top-to-bottom",pins:o?.rightSide?.pins??i}}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:n}=this,o=e.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:n.supplierPartNumbers,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,pin_count:n.pinCount,gender:n.gender,are_pins_interchangeable:!0,display_name:n.displayName});this.source_component_id=o.source_component_id}};function Oko(t){switch(t){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var Gko=class extends g0{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??Oko(this.props.pinVariant),zodProps:jwn,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=e.pinVariant||"no_ground",o=t.source_component.insert({ftype:"simple_resonator",name:this.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:n,are_pins_interchangeable:n==="no_ground"||n==="ground_pin",display_name:e.displayName});this.source_component_id=o.source_component_id}_getSchematicSymbolDisplayValue(){const t=`${H_(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${t} / ${H_(this._parsedProps.loadCapacitance)}F`:t}};function Yko(t){switch(t){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var Uko=class extends g0{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??Yko(this.props.pinVariant),zodProps:zwn,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${H_(this._parsedProps.maxResistance)}Ω`}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:n}=this,o=n.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,max_resistance:n.maxResistance,pin_variant:o,are_pins_interchangeable:o==="two_pin",display_name:n.displayName,display_max_resistance:this._getSchematicSymbolDisplayValue()});this.source_component_id=i.source_component_id}},Kko=10,eFt=0,Vko=class extends g0{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:Wwn,sourceFtype:"simple_crystal"}}initPorts(){const e=this.props.pinVariant==="four_pin"?{pin1:["left1","1","X1"],pin2:["top1","2","gnd1"],pin3:["right1","3","X2"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left","X1"],pin2:["neg","right","X2"]};super.initPorts({additionalAliases:e})}_getSchematicSymbolDisplayValue(){const e=`${H_(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${H_(this._parsedProps.loadCapacitance)}F`:e}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:n}=this,o=e.source_component.insert({name:this.name,ftype:"simple_crystal",manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,frequency:n.frequency,load_capacitance:n.loadCapacitance,pin_variant:n.pinVariant||"two_pin",are_pins_interchangeable:(n.pinVariant||"two_pin")==="two_pin",display_name:n.displayName});this.source_component_id=o.source_component_id}doInitialSourceDesignRuleChecks(){if(super.doInitialSourceDesignRuleChecks(),!this.source_component_id)return;const{db:e}=this.root,n=this._parsedProps.maxTraceLength??Kko,o=new Set,i=new Set;for(const r of[this.portMap.X1,this.portMap.X2]){if(!r.source_port_id)continue;const s=e.source_port.get(r.source_port_id);s&&(o.add(r.source_port_id),s.subcircuit_connectivity_map_key&&i.add(s.subcircuit_connectivity_map_key))}for(const r of e.source_trace.list()){const s=r.connected_source_port_ids.some(l=>o.has(l)),a=r.subcircuit_connectivity_map_key!==void 0&&i.has(r.subcircuit_connectivity_map_key);if(!s&&!a)continue;const A=typeof r.max_length!="number"||r.max_length>n,c=r.max_via_count!==eFt;!A&&!c||e.source_trace.update(r.source_trace_id,{...A?{max_length:n}:{},...c?{max_via_count:eFt}:{}})}}},zko=class extends g0{getSchematicSymbolName(){return this.props.symbolName?this.props.symbolName:this.props.connections?.positive_supply||this.props.connections?.negative_supply?"opamp_with_power":"opamp_no_power"}get config(){return{componentName:"OpAmp",schematicSymbolName:this.getSchematicSymbolName(),zodProps:uMn,sourceFtype:"simple_op_amp"}}initPorts(){const t={pin1:["non_inverting_input"],pin2:["inverting_input"]};this.getSchematicSymbolName()==="opamp_with_power"?Object.assign(t,{pin4:["output"],pin5:["positive_supply","vcc","vdd"],pin3:["negative_supply","vee","vss","gnd"]}):Object.assign(t,{pin3:["output"],pin4:["positive_supply","vcc","vdd"],pin5:["negative_supply","vee","vss","gnd"]}),super.initPorts({pinCount:5,additionalAliases:t})}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({ftype:"simple_op_amp",name:this.name,supplier_part_numbers:e.supplierPartNumbers,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,display_name:e.displayName});this.source_component_id=n.source_component_id}doInitialSimulationRender(){const{db:t}=this.root,e=this.portMap.inverting_input,n=this.portMap.non_inverting_input,o=this.portMap.output,i=this.portMap.positive_supply,r=this.portMap.negative_supply;!e?.source_port_id||!n?.source_port_id||!o?.source_port_id||!i?.source_port_id||!r?.source_port_id||t.simulation_op_amp.insert({type:"simulation_op_amp",source_component_id:this.source_component_id,inverting_input_source_port_id:e.source_port_id,non_inverting_input_source_port_id:n.source_port_id,output_source_port_id:o.source_port_id,positive_supply_source_port_id:i.source_port_id,negative_supply_source_port_id:r.source_port_id})}inverting_input=this.portMap.inverting_input;non_inverting_input=this.portMap.non_inverting_input;output=this.portMap.output;positive_supply=this.portMap.positive_supply;negative_supply=this.portMap.negative_supply},jMe={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},Jko=class extends g0{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:vMn,sourceFtype:$7.simple_test_point}}_getPropsWithDefaults(){let{padShape:t,holeDiameter:e,footprintVariant:n,padDiameter:o,width:i,height:r}=this._parsedProps;return!n&&e&&(n="through_hole"),n??="through_hole",t??="circle",n==="pad"?t==="circle"?o??=jMe.SMT_CIRCLE_DIAMETER:t==="rect"&&(i??=jMe.SMT_RECT_SIZE,r??=i):n==="through_hole"&&(e??=jMe.HOLE_DIAMETER),{padShape:t,holeDiameter:e,footprintVariant:n,padDiameter:o,width:i,height:r}}_getImpliedFootprintString(){const{padShape:t,holeDiameter:e,footprintVariant:n,padDiameter:o,width:i,height:r}=this._getPropsWithDefaults();if(n==="through_hole")return`platedhole_d${e}`;if(n==="pad"){if(t==="circle")return`smtpad_circle_d${o}`;if(t==="rect")return`smtpad_rect_w${i}_h${r}`}throw new Error(`Footprint variant "${n}" with pad shape "${t}" not implemented`)}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,{padShape:n,holeDiameter:o,footprintVariant:i,padDiameter:r,width:s,height:a}=this._getPropsWithDefaults(),A=t.source_component.insert({ftype:$7.simple_test_point,name:this.name,supplier_part_numbers:e.supplierPartNumbers,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,footprint_variant:i,pad_shape:n,pad_diameter:r,hole_diameter:o,width:s,height:a,are_pins_interchangeable:!0,display_name:e.displayName});this.source_component_id=A.source_component_id}},Wko=t=>{if(t.root?.schematicDisabled||t.getCollapsedSchematicBoxAncestor())return;const{db:e}=t.root,n=t._getSchematicSymbolNameOrThrow(),o=Su[n];if(!o)throw new Error(`No schematic symbol found for "${n}"`);const i=t._getGlobalSchematicPositionBeforeLayout(),r=t._resolveSchematicSheetId(),s=t.getSubcircuit().subcircuit_id??void 0,a=e.schematic_component.insert({center:i,size:{...o.size},is_box_with_pins:!0,symbol_name:n,source_component_id:t.source_component_id??void 0,schematic_sheet_id:r});t.schematic_component_id=a.schematic_component_id;for(const A of o.ports){const c=t.getPortForSymbolPort(A);if(!c?.source_port_id)throw new Error(`Missing source port for schematic symbol port "${A.labels.join("/")}" on ${t.getString()}`);const l={x:i.x+A.x-o.center.x,y:i.y+A.y-o.center.y},u=e.schematic_port.insert({schematic_component_id:a.schematic_component_id,center:l,source_port_id:c.source_port_id,facing_direction:IMt(i,l),distance_from_component_edge:.4,pin_number:c._parsedProps.pinNumber,display_pin_label:c._parsedProps.aliases?.[0],is_connected:!1,schematic_sheet_id:r,subcircuit_id:s});c.schematic_port_id=u.schematic_port_id}},jko=(t,e)=>{const n=Array.isArray(e)?e:[e];if(n.length!==1)throw new Error(`SchematicSymbol connection "${t}" must select exactly one physical port`);return n[0]},$ko=t=>{const{db:e}=t.root,{chipRef:n,connections:o}=t._parsedProps;if(n&&!o){e.source_property_ignored_warning.insert({source_component_id:t.source_component_id,property_name:"chipRef",message:`${t.getString()} has chipRef "${n}" without connections. chipRef will be ignored.`,error_type:"source_property_ignored_warning",subcircuit_id:t.getSubcircuit().subcircuit_id??void 0});return}if(o&&!n){e.source_property_ignored_warning.insert({source_component_id:t.source_component_id,property_name:"connections",message:`${t.getString()} has connections without chipRef. connections will be ignored.`,error_type:"source_property_ignored_warning",subcircuit_id:t.getSubcircuit().subcircuit_id??void 0});return}if(!n||!o)return;const i=t.getSubcircuit().selectOne(n);if(!i?.source_component_id)throw new Error(`Could not resolve chipRef "${n}" for ${t.getString()}`);const r=new Set;for(const a of t.ports){const A=a.schematicSymbolPortDef,c=Object.entries(o).filter(([p])=>a.isMatchingAnyOf([p]));if(c.length===0)throw new Error(`${t.getString()} is missing an explicit connection for symbol port "${A.labels.join("/")}"`);if(c.length>1)throw new Error(`${t.getString()} has multiple connections for symbol port "${A.labels.join("/")}"`);const[l,u]=c[0];r.add(l);const g=jko(l,u),h=t.getSubcircuit().selectOne(g,{type:"port"});if(!h?.source_port_id)throw new Error(`Could not resolve connection "${l}" target "${g}" for ${t.getString()}`);if(e.source_port.get(h.source_port_id)?.source_component_id!==i.source_component_id)throw new Error(`Connection "${l}" target "${g}" does not belong to chipRef "${n}"`);a.source_port_id=h.source_port_id,a.source_component_id=h.source_component_id}const s=Object.keys(o).filter(a=>!r.has(a));if(s.length>0)throw new Error(`${t.getString()} has connections that do not match symbol ports: ${s.join(", ")}`)},qko=class extends Ir{isSchematicPrimitive=!0;isPrimitiveContainer=!0;get config(){return{componentName:"SchematicSymbol",schematicSymbolName:this.props.symbolName,zodProps:eDn}}initPorts(){const t=Su[this._getSchematicSymbolNameOrThrow()],e=!(this._parsedProps.chipRef&&this._parsedProps.connections);for(const n of t.ports){const o=H0e(n.labels);if(!o)throw new Error(`Schematic symbol port must have a numeric pin label: ${n.labels.join("/")}`);const i=this.ports.find(a=>a._parsedProps.pinNumber===o);if(i){i.schematicSymbolPortDef=n;continue}const r=n.labels.filter(a=>a!==o.toString()&&a!==`pin${o}`),s=new Pu({pinNumber:o,aliases:r},{shouldCreateSourcePort:e});s.schematicSymbolPortDef=n,this.add(s)}}doInitialInitializePortsFromChildren(){this.initPorts()}updateInitializePortsFromChildren(){this.initPorts()}get ports(){return this.children.filter(t=>t instanceof Pu)}getPortForSymbolPort(t){return this.ports.find(e=>e.schematicSymbolPortDef===t)??null}doInitialSourceRender(){const t=this.root.db.source_component.insert({ftype:"simple_chip",name:this.name,display_name:this._parsedProps.displayName,are_pins_interchangeable:!1});this.source_component_id=t.source_component_id}doInitialPortMatching(){$ko(this)}doInitialSchematicComponentRender(){Wko(this)}},Xko=class m4n extends Ir{isSchematicPrimitive=!0;get config(){return{componentName:"SchematicSection",zodProps:lDn}}_computeSectionBounds(e,n,o){const{db:i}=this.root,r=e.getDescendants().filter(a=>a.getSchematicSectionName()===n);if(r.length===0)return null;const s=[];for(const a of r){const A=a.schematic_component_id;if(!A)continue;const c=i.schematic_component.get(A);if(!c||c.schematic_sheet_id!==o)continue;const l=c.size.width/2,u=c.size.height/2;s.push({minX:c.center.x-l,maxX:c.center.x+l,minY:c.center.y-u,maxY:c.center.y+u});for(const g of i.schematic_text.list({schematic_component_id:A}))s.push(cTt({text:g.text,position:g.position,anchor:g.anchor,fontSize:g.font_size}))}return s.length===0?null:Dwe(s)}doInitialSchematicSectionRender(){if(this.root?.schematicDisabled)return;const e=this.root?._getBoard();if(!e)return;const n=this._resolveSchematicSheetId(),o=e.getDescendants().filter(_=>_ instanceof m4n&&_._resolveSchematicSheetId()===n);if(o[0]!==this)return;const{db:i}=this.root,r=.5,s=.2,a=.02,A=.001,c=o.map(_=>{const f=_._computeSectionBounds(e,_._parsedProps.name,n);return f?{displayName:_._parsedProps.displayName,sectionTitleFontSize:_._parsedProps.sectionTitleFontSize,rawBounds:f,cell:{minX:f.minX-r,maxX:f.maxX+r,minY:f.minY-r,maxY:f.maxY+r}}:null}).filter(_=>_!==null),l=this._computeSectionBounds(e,null,n),u=[...c];if(l&&u.push({displayName:void 0,sectionTitleFontSize:void 0,rawBounds:l,cell:{minX:l.minX-r,maxX:l.maxX+r,minY:l.minY-r,maxY:l.maxY+r}}),u.length===0)return;const g=u.map(_=>_.cell),h=Dwe(g),d=C9o(u.map(_=>_.rawBounds),{cellMargin:1});for(const _ of d)i.schematic_line.insert({x1:_.start.x,y1:_.start.y,x2:_.end.x,y2:_.end.y,stroke_width:a,color:"#000000",is_dashed:!0,schematic_sheet_id:n});const p=d.filter(_=>Math.abs(_.start.y-_.end.y)<A),m=d.filter(_=>Math.abs(_.start.x-_.end.x)<A);for(const _ of u){const{displayName:f,sectionTitleFontSize:I,rawBounds:C,cell:y}=_;if(!f)continue;const x=u.some(M=>M!==_&&z4(M.rawBounds,C)),E=p.map(M=>M.start.y).filter(M=>M>C.maxY),B=E.length>0?Math.min(...E):h.maxY,S=m.map(M=>M.start.x).filter(M=>M<C.minX);let Q=h.minX;x&&(Q=y.minX),S.length>0&&(Q=Math.max(...S));const w=I??.18;i.schematic_text.insert({anchor:"top_left",text:f,font_size:w,color:"#000000",position:{x:Q+s,y:Math.max(B-s,C.maxY+s+w)},rotation:0,schematic_sheet_id:n})}}},Zko=t=>L2e.parse(t.toLowerCase()),eFo={a4:{width:297,height:210},ansi_b:{width:431.8,height:279.4}},tFt=({sheetSize:t,sheetWidth:e,sheetHeight:n})=>{const o=Zko(t),i=eFo[o];return{sheetSize:o,sheetWidth:e??i.width,sheetHeight:n??i.height}},$Me=10.16/1.1,jue=5/$Me,$ue=1e-6,tFo=t=>{switch(t.type){case"schematic_component":return t.schematic_component_id;case"schematic_net_label":return t.schematic_net_label_id;case"schematic_trace":return t.schematic_trace_id}},nFo=({db:t,schematicSheetId:e,schematicSheetName:n,schematicSheetCenter:o,sheetWidth:i,sheetHeight:r})=>{const s=i/$Me,a=r/$Me,A={minX:o.x-s/2+jue,maxX:o.x+s/2-jue,minY:o.y-a/2+jue,maxY:o.y+a/2-jue},c=[...t.schematic_component.list(),...t.schematic_net_label.list(),...t.schematic_trace.list()].filter(l=>l.schematic_sheet_id===e);for(const l of c){const u=vWn(l);if(!u||!(u.minX<A.minX-$ue||u.maxX>A.maxX+$ue||u.minY<A.minY-$ue||u.maxY>A.maxY+$ue))continue;const h=tFo(l);t.schematic_element_outside_sheet_warning.insert({warning_type:"schematic_element_outside_sheet_warning",message:`${l.type} ${h} extends outside the drawing area of schematic sheet "${n}"`,schematic_sheet_id:e,schematic_element_type:l.type,schematic_element_id:h})}},oFo=class extends Ir{isSchematicPrimitive=!0;resolvedSchematicSheetDisplayName="Schematic Sheet";get config(){return{componentName:"SchematicSheet",zodProps:uDn}}doInitialSourceGroupRender(){if(this.root?.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=new Set(this.root.children.flatMap(l=>[l,...l.getDescendants()]).filter(l=>l.componentName==="SchematicSheet").map(l=>l._parsedProps.sheetIndex).filter(l=>l!==void 0)),o=new Set([...n,...t.schematic_sheet.list().map(l=>l.sheet_index).filter(l=>l!==void 0)]);let i=0;for(;o.has(i);)i+=1;const r=e.sheetIndex??i,s=e.name??e.displayName??`Sheet ${r+1}`,a=e.displayName??s;this.resolvedSchematicSheetDisplayName=a;const A=tFt(e),c=t.schematic_sheet.insert({name:s,display_name:a,sheet_index:r,sheet_size:A.sheetSize,sheet_width:A.sheetWidth,sheet_height:A.sheetHeight,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_sheet_id=c.schematic_sheet_id}doInitialSchematicSheetRender(){if(this.root?.schematicDisabled||!this.schematic_sheet_id)return;const{db:t}=this.root,e=tFt(this._parsedProps),n=[...t.schematic_component.list(),...t.schematic_port.list(),...t.schematic_text.list(),...t.schematic_line.list(),...t.schematic_rect.list(),...t.schematic_circle.list(),...t.schematic_arc.list(),...t.schematic_path.list()].filter(i=>i.schematic_sheet_id===this.schematic_sheet_id);let o={x:0,y:0};if(n.length>0){const i=Gj(n);Number.isFinite(i.minX)&&Number.isFinite(i.maxX)&&Number.isFinite(i.minY)&&Number.isFinite(i.maxY)&&(o={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2},t.schematic_sheet.update(this.schematic_sheet_id,{center:o}))}nFo({db:t,schematicSheetId:this.schematic_sheet_id,schematicSheetName:this.resolvedSchematicSheetDisplayName,schematicSheetCenter:o,sheetWidth:e.sheetWidth,sheetHeight:e.sheetHeight})}},iFo=class extends Ir{isSchematicPrimitive=!0;schematic_graphic_id;get config(){return{componentName:"SchematicGraphic",zodProps:dDn}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled||this.getCollapsedSchematicBoxAncestor())return;const{db:t}=this.root,{imageUrl:e,svgContent:n,width:o,height:i}=this._parsedProps;if(e!==void 0){this._queueAsyncEffect("SchematicGraphicRender",async()=>{if(this.root?.schematicDisabled)return;const r=await EDt(e,this.root?.platform),s=await xPt(r).catch(l=>{if(n===void 0||r.startsWith("data:"))throw l;return null});if(s===null){const l={project_relative_path:e.startsWith("data:")?"inline":e,url:r,mimetype:Eb},u=this.root.db.schematic_graphic.insert({asset:l,schematic_sheet_id:this._resolveSchematicSheetId(),svg_content:n,...o===void 0?{}:{width:o},...i===void 0?{}:{height:i}});this.schematic_graphic_id=u.schematic_graphic_id;return}if(s.mimetype!==Eb)throw new Error(`Unsupported imageUrl for SchematicGraphic: "${e}". Expected an SVG image.`);const a={project_relative_path:e.startsWith("data:")?s.projectRelativePath:e,url:s.dataUrl,mimetype:s.mimetype},A=s.dataUrl.startsWith("data:")?n:s.text,c=this.root.db.schematic_graphic.insert({asset:a,schematic_sheet_id:this._resolveSchematicSheetId(),...A===void 0?{}:{svg_content:A},...o===void 0?{}:{width:o},...i===void 0?{}:{height:i}});this.schematic_graphic_id=c.schematic_graphic_id});return}if(n!==void 0){const r={project_relative_path:"inline",url:`data:image/svg+xml,${encodeURIComponent(n)}`,mimetype:Eb},s=t.schematic_graphic.insert({asset:r,schematic_sheet_id:this._resolveSchematicSheetId(),...o===void 0?{}:{width:o},...i===void 0?{}:{height:i}});this.schematic_graphic_id=s.schematic_graphic_id}}},rFo=class extends Ir{isSchematicPrimitive=!0;schematic_table_id=null;get config(){return{componentName:"SchematicTable",zodProps:aDn}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled||this.getCollapsedSchematicBoxAncestor())return;const{db:t}=this.root,{_parsedProps:e}=this,n=this.children.filter(u=>u.componentName==="SchematicRow");if(n.length===0)return;const o=[];let i=0;for(const u of n){const g=u.children.filter(h=>h.componentName==="SchematicCell");i=Math.max(i,g.length)}for(let u=0;u<n.length;u++)o[u]=[];for(let u=0;u<n.length;u++){const h=n[u].children.filter(p=>p.componentName==="SchematicCell");let d=0;for(let p=0;p<h.length;p++){for(;o[u][d];)d++;const m=h[p],_=m._parsedProps.colSpan??1,f=m._parsedProps.rowSpan??1;for(let I=0;I<f;I++)for(let C=0;C<_;C++)o[u+I]||(o[u+I]=[]),o[u+I][d+C]=m;d+=_}}i=Math.max(0,...o.map(u=>u.length));const r=n.map((u,g)=>u._parsedProps.height??1),s=Array.from({length:i},(u,g)=>{let h=0;for(let d=0;d<n.length;d++){const p=o[d]?.[g];if(p){const m=p._parsedProps.text??p._parsedProps.children,_=p._parsedProps.width??(m?.length??2)*.5;_>h&&(h=_)}}return h||10}),a=this._getGlobalSchematicPositionBeforeLayout(),A=t.schematic_table.insert({anchor_position:a,column_widths:s,row_heights:r,cell_padding:e.cellPadding,border_width:e.borderWidth,anchor:e.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||"",schematic_sheet_id:this._resolveSchematicSheetId()});this.schematic_table_id=A.schematic_table_id;const c=new Set;let l=0;for(let u=0;u<n.length;u++){let g=0;for(let h=0;h<i;h++){const d=o[u]?.[h];if(d&&!c.has(d)){c.add(d);const p=d._parsedProps,m=p.rowSpan??1,_=p.colSpan??1;let f=0;for(let C=0;C<_;C++)f+=s[h+C];let I=0;for(let C=0;C<m;C++)I+=r[u+C];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:u,end_row_index:u+m-1,start_column_index:h,end_column_index:h+_-1,text:p.text??p.children,center:{x:a.x+g+f/2,y:a.y-l-I/2},width:f,height:I,horizontal_align:p.horizontalAlign,vertical_align:p.verticalAlign,font_size:p.fontSize??e.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}s[h]&&(g+=s[h])}l+=r[u]}}},sFo=class extends Ir{isSchematicPrimitive=!0;get config(){return{componentName:"SchematicRow",zodProps:ADn}}},aFo=class extends Ir{isSchematicPrimitive=!0;canHaveTextChildren=!0;get config(){return{componentName:"SchematicCell",zodProps:cDn}}},AFo=class extends Ir{simulation_experiment_id=null;get config(){return{componentName:"AnalogSimulation",zodProps:GPn}}getSpiceEngineName(){return this._parsedProps.spiceEngine}usesIndependentGraphAxes(){return this._parsedProps.graphIndependentAxes===!0}doInitialSimulationRender(){const{db:t}=this.root,{duration:e,name:n,startTime:o,timePerStep:i,spiceOptions:r}=this._parsedProps,s=e||10,a=i||.01,A=t.simulation_experiment.insert({name:n??"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:s,start_time_ms:o,time_per_step:a,spice_options:r});this.simulation_experiment_id=A.simulation_experiment_id}},HO=class extends Ir{simulation_experiment_id=null;getSpiceEngineName(){return typeof this.props.spiceEngine=="string"?this.props.spiceEngine:void 0}usesIndependentGraphAxes(){return this.props.graphIndependentAxes===!0}getOrCreateSimulationExperiment(){if(this.simulation_experiment_id)return this.root?.db.simulation_experiment.get(this.simulation_experiment_id)??null;if(this.children.filter(n=>n.componentName==="AnalogSweepParameter").length>1)return this.renderError("An analog simulation can contain at most one sweep parameter."),null;const e=this.insertSimulationExperiment();return this.simulation_experiment_id=e?.simulation_experiment_id??null,e}doInitialSimulationRender(){this.getOrCreateSimulationExperiment()}},cFo=class extends HO{get config(){return{componentName:"AnalogTransientSimulation",zodProps:YPn}}insertSimulationExperiment(){const{db:t}=this.root,{duration:e,name:n,startTime:o,timePerStep:i,spiceOptions:r}=this._parsedProps;return t.simulation_experiment.insert({name:n??"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:e,start_time_ms:o,time_per_step:i,spice_options:r})}},lFo=class extends HO{get config(){return{componentName:"AnalogDcOperatingPointSimulation",zodProps:UPn}}insertSimulationExperiment(){const{name:t,spiceOptions:e}=this._parsedProps;return this.root.db.simulation_experiment.insert({name:t??"spice_dc_operating_point",experiment_type:"spice_dc_operating_point",spice_options:e})}},uFo=class extends HO{get config(){return{componentName:"AnalogDcSweepSimulation",zodProps:KPn}}insertSimulationExperiment(){const{name:t,spiceOptions:e,sweepSource:n,sweepStart:o,sweepStop:i,sweepStep:r}=this._parsedProps,a=(this.getGroup()??this.getSubcircuit())?.selectOne(n);let A;if(a instanceof Fkt){a.runRenderPhase("SimulationRender");const c=a.simulation_voltage_source_id;if(!c)return this.renderError(`DC sweep source "${n}" must resolve to one voltage or current source.`),null;A={dc_sweep_voltage_source_id:c,dc_sweep_unit:"V"}}else if(a instanceof Lkt){a.runRenderPhase("SimulationRender");const c=a.simulation_current_source_id;if(!c)return this.renderError(`DC sweep source "${n}" must resolve to one voltage or current source.`),null;A={dc_sweep_current_source_id:c,dc_sweep_unit:"A"}}else return this.renderError(`DC sweep source "${n}" must resolve to one voltage or current source.`),null;return this.root.db.simulation_experiment.insert({name:t??"spice_dc_sweep",experiment_type:"spice_dc_sweep",spice_options:e,...A,dc_sweep_start:o,dc_sweep_stop:i,dc_sweep_step:r})}},gFo=class extends HO{get config(){return{componentName:"AnalogAcSweepSimulation",zodProps:VPn}}insertSimulationExperiment(){const{name:t,spiceOptions:e,sweepType:n,samplesPerInterval:o,sampleCount:i,startFrequency:r,stopFrequency:s}=this._parsedProps;return this.root.db.simulation_experiment.insert({name:t??"spice_ac_analysis",experiment_type:"spice_ac_analysis",spice_options:e,ac_sweep_type:n,ac_samples_per_interval:o,ac_sample_count:i,ac_start_frequency_hz:r,ac_stop_frequency_hz:s})}},dFo={resistance:"Ω",capacitance:"F",inductance:"H",voltage:"V",current:"A"},hFo=({parameterSweepCoordinate:t,stop:e,step:n})=>{const o=Math.abs(n)*1e-9;return n>0?t<=e+o:t>=e-o},pFo=({start:t,stop:e,step:n})=>{const o=[];for(let i=t;hFo({parameterSweepCoordinate:i,stop:e,step:n});i=t+o.length*n)if(o.push(i),o.length>1e6)throw new Error("Parameter sweep exceeds 1,000,000 points");return o},mFo=t=>t.parameterType==="resistance"?t.resistorRef:t.parameterType==="capacitance"?t.capacitorRef:t.parameterType==="inductance"?t.inductorRef:t.parameterType==="voltage"?t.net:t.currentSourceRef,_Fo=t=>{if(!(t.parent instanceof HO)){t.renderError("analog.sweepparameter must be nested directly in an analog simulation.");return}const e=t.parent.getOrCreateSimulationExperiment();if(!e)return;const n=t._parsedProps,o=n.values??pFo({start:n.start,stop:n.stop,step:n.step}),i=t.parent.getGroup()??t.parent.getSubcircuit(),r=mFo(n),s=dFo[n.parameterType],a=t.root.db.simulation_parameter_sweep,A={simulation_experiment_id:e.simulation_experiment_id,name:n.name,parameter_type:n.parameterType,parameter_values:o,parameter_unit:s};let c;if(n.parameterType==="voltage"){const l=i?.selectOne(r,{type:"net"});if(!l?.source_net_id){t.renderError(`Voltage sweep net "${r}" could not be resolved.`);return}c=a.insert({...A,parameter_type:"voltage",source_net_id:l.source_net_id}).simulation_parameter_sweep_id}else{const u=i?.selectOne(r)?.source_component_id;if(!u){t.renderError(`Parameter sweep target "${r}" could not be resolved.`);return}n.parameterType==="resistance"?c=a.insert({...A,parameter_type:"resistance",resistor_source_component_id:u}).simulation_parameter_sweep_id:n.parameterType==="capacitance"?c=a.insert({...A,parameter_type:"capacitance",capacitor_source_component_id:u}).simulation_parameter_sweep_id:n.parameterType==="inductance"?c=a.insert({...A,parameter_type:"inductance",inductor_source_component_id:u}).simulation_parameter_sweep_id:c=a.insert({...A,parameter_type:"current",current_source_component_id:u}).simulation_parameter_sweep_id}t.simulation_parameter_sweep_id=c},fFo=class extends Ir{simulation_parameter_sweep_id=null;get config(){return{componentName:"AnalogSweepParameter",zodProps:oMn}}doInitialSimulationRender(){_Fo(this)}};function IFo(t,e,n,o=.3){const r=Math.max(e.length*.1,.3),a=.25+.2;let A=t.x,c=t.y;const l=o+r/2;n.includes("top")?c+=l:n.includes("bottom")&&(c-=l),n.includes("right")?A+=l:n.includes("left")&&(A-=l);let u,g,h,d;return n.includes("left")?(u=A,g=A+r):n.includes("right")?(u=A-r,g=A):(u=A-r/2,g=A+r/2),n.includes("top")?(h=c-a,d=c):n.includes("bottom")?(h=c,d=c+a):(h=c-a/2,d=c+a/2),{minX:u,maxX:g,minY:h,maxY:d}}function CFo(t){let e,n,o,i;if(t.type==="schematic_component")e=t.center?.x,n=t.center?.y,o=t.size?.width,i=t.size?.height;else if(t.type==="schematic_text")e=t.position?.x,n=t.position?.y,o=(t.text?.length??0)*.1,i=.2;else return null;return typeof e=="number"&&typeof n=="number"&&typeof o=="number"&&typeof i=="number"?{minX:e-o/2,maxX:e+o/2,minY:n-i/2,maxY:n+i/2}:null}function yFo(t,e){if(!z4(t,e))return 0;const n=Math.min(t.maxX,e.maxX)-Math.max(t.minX,e.minX),o=Math.min(t.maxY,e.maxY)-Math.max(t.minY,e.minY);return n*o}function xFo({probePosition:t,labelText:e,schematicElements:n,defaultAlignment:o="top_right"}){const r=[o,...["top_right","top_left","bottom_right","bottom_left","top_center","bottom_center","center_right","center_left"].filter(A=>A!==o)];let s=o,a=1/0;for(const A of r){const c=IFo(t,e,A);let l=0;for(const u of n){const g=CFo(u);g&&(l+=yFo(c,g))}if(l===0)return A;l<a&&(a=l,s=A)}return s}var EFo=class extends Ir{simulation_voltage_probe_id=null;schematic_voltage_probe_id=null;finalProbeName=null;color=null;get config(){return{componentName:"VoltageProbe",zodProps:JMn}}doInitialSimulationRender(){const{db:t}=this.root,{connectsTo:e,name:n,referenceTo:o,color:i,graphDisplayName:r,graphCenter:s,graphVerticalOffset:a,graphVoltagePerDiv:A}=this._parsedProps,c=this.getSubcircuit();if(!c){this.renderError("VoltageProbe must be inside a subcircuit");return}const l=Array.isArray(e)?e:[e];if(l.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}const u=l[0],g=c.selectOne(u,{type:"port"}),h=g?null:c.selectOne(u,{type:"net"});if(h&&h.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${u}" resolved to a non-net component "${h.componentName}".`);return}if(!g&&!h){this.renderError(`VoltageProbe could not find connection target "${u}"`);return}const d=g?.source_port_id??h?.source_net_id;if(!d){this.renderError("Could not identify connected source for VoltageProbe");return}let p=null,m=null;if(o){const C=Array.isArray(o)?o:[o];if(C.length!==1){this.renderError("VoltageProbe must reference exactly one port or net");return}const y=C[0];if(p=c.selectOne(y,{type:"port"}),m=p?null:c.selectOne(y,{type:"net"}),m&&m.componentName!=="Net"){this.renderError(`VoltageProbe reference target "${y}" resolved to a non-net component "${m.componentName}".`);return}if(!p&&!m){this.renderError(`VoltageProbe could not find reference target "${y}"`);return}}this.color=i??jDo(d);let _=n;_||(_=l[0].split(" > ").map(C=>C.replace(/^\./,"")).join(".")),this.finalProbeName=_??null;const{simulation_voltage_probe_id:f}=t.simulation_voltage_probe.insert({name:_,signal_input_source_port_id:g?.source_port_id??void 0,signal_input_source_net_id:h?.source_net_id??void 0,reference_input_source_port_id:p?.source_port_id??void 0,reference_input_source_net_id:m?.source_net_id??void 0,subcircuit_id:c.subcircuit_id||void 0,color:this.color});if(this.simulation_voltage_probe_id=f,r!==void 0||s!==void 0||a!==void 0||A!==void 0){const C=Sw(A),y=Sw(a);t.simulation_oscilloscope_trace.insert({simulation_voltage_probe_id:f,display_name:r,color:i??void 0,display_center_value:s,volts_per_div:C,display_center_offset_divs:y!==void 0&&C!==void 0&&C!==0?y/C:void 0})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled)return;const{db:t}=this.root,{connectsTo:e,name:n}=this._parsedProps,o=this.getSubcircuit();if(!o)return;const i=Array.isArray(e)?e:[e];if(i.length!==1)return;const r=i[0],s=o.selectOne(r,{type:"port"});if(!s||!s.schematic_port_id)return;const a=s._getGlobalSchematicPositionAfterLayout();let A=null;for(const g of t.schematic_trace.list()){for(const h of g.edges)if(Math.abs(h.from.x-a.x)<1e-6&&Math.abs(h.from.y-a.y)<1e-6||Math.abs(h.to.x-a.x)<1e-6&&Math.abs(h.to.y-a.y)<1e-6){A=g.schematic_trace_id;break}if(A)break}if(!A)return;const c=this.finalProbeName,l=xFo({probePosition:a,labelText:c,schematicElements:[...t.schematic_component.list(),...t.schematic_text.list()],defaultAlignment:"top_right"}),u=t.schematic_voltage_probe.insert({name:c,position:a,schematic_trace_id:A,subcircuit_id:o.subcircuit_id||void 0,color:this.color??void 0,label_alignment:l});this.schematic_voltage_probe_id=u.schematic_voltage_probe_id}},BFo=class extends Ir{get config(){return{componentName:"SpiceModel",zodProps:rMn}}doInitialSimulationRender(){if(this.getInheritedProperty("analogSimulationDisabled"))return;const t=this.parent;if(!t)return;const e=t.source_component_id;if(!e){this._insertSpiceModelError("spicemodel must be attached to a source component.",this._parsedProps);return}const{source:n,spicePinMapping:o}=this._parsedProps,i=W5o(n).subckts[0]??null,r=i?.pins.map(c=>c.name);if(!i||!r||r.length===0){this._insertSpiceModelError("spicemodel source must contain a .subckt declaration with a model name and pins.",n);return}const s=o??{};for(const c of Object.keys(s))if(!r.includes(c)){this._insertSpiceModelError(`spicePinMapping references SPICE pin "${c}", but it is not present in .subckt ${i.name}.`,s);return}const a={},A=new Set;for(const c of r){const l=s[c]??c,u=t.selectAll("port").filter(h=>h instanceof Pu&&h.isMatchingAnyOf([l]));if(u.length!==1||!u[0].source_port_id){this._insertSpiceModelError(`Could not resolve SPICE pin "${c}" to exactly one component port using "${l}".`,s);return}const g=u[0].source_port_id;if(A.has(g)){this._insertSpiceModelError(`spicePinMapping maps more than one SPICE pin to component port "${l}".`,s);return}A.add(g),a[c]=g}this.root.db.simulation_spice_subcircuit.insert({source_component_id:e,spice_pin_to_source_port_map:a,subcircuit_source:n})}_insertSpiceModelError(t,e){this.root.db.source_invalid_component_property_error.insert({source_component_id:this.parent?.source_component_id||"",property_name:"spiceModel",property_value:e,message:t,error_type:"source_invalid_component_property_error"})}},bFo=class extends Ikt{isRootCircuit=!0;constructor({platform:t,projectUrl:e}={}){super({platform:t,projectUrl:e,cachedSubcircuits:new Map,pendingSubcircuitRenders:new Map}),this.root=this}},SFo=bFo;new Proxy(t=>new Proxy({},{get:(e,n)=>`.${t} > .${n}`}),{get:(t,e)=>{const n=(...o)=>(o[0],new Proxy({},{get:(i,r)=>`.${e} > .${r}`}));return new Proxy(n,{get:(o,i)=>e==="net"?`net.${i}`:e==="subcircuit"?new Proxy({},{get:(r,s)=>new Proxy({},{get:(a,A)=>`subcircuit.${i} > .${s} > .${A}`})}):`.${e} > .${i}`,apply:(o,i,r)=>e==="net"?new Proxy({},{get:(s,a)=>`net.${a}`}):new Proxy({},{get:(s,a)=>{const A=`.${e} > .${a}`;return["U","J","CN"].some(l=>e.startsWith(l))?A:new Proxy(new String(A),{get:(l,u)=>typeof u=="symbol"||u==="toString"?()=>A:`.${e} > .${a} > .${u}`})}})})}}),NMt(qPt),NMt({"assembly.device":qkt,Bug:zj,"enclosure.cutoutaperture":WMe,"enclosure.fdm.box":Zkt,Fanout:JMe,FanoutPoint:dR});const nFt=vc("run-frame"),QFo={},oFt=t=>{let e;const n=new Set,o=(l,u)=>{const g=typeof l=="function"?l(e):l;if(!Object.is(g,e)){const h=e;e=u??(typeof g!="object"||g===null)?g:Object.assign({},e,g),n.forEach(d=>d(e,h))}},i=()=>e,A={setState:o,getState:i,getInitialState:()=>c,subscribe:l=>(n.add(l),()=>n.delete(l)),destroy:()=>{(QFo?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},c=e=t(o,i,A);return A},iFt=t=>t?oFt(t):oFt;var que={exports:{}},qMe={},Xue={exports:{}},XMe={};var rFt;function vFo(){if(rFt)return XMe;rFt=1;var t=L3();function e(u,g){return u===g&&(u!==0||1/u===1/g)||u!==u&&g!==g}var n=typeof Object.is=="function"?Object.is:e,o=t.useState,i=t.useEffect,r=t.useLayoutEffect,s=t.useDebugValue;function a(u,g){var h=g(),d=o({inst:{value:h,getSnapshot:g}}),p=d[0].inst,m=d[1];return r(function(){p.value=h,p.getSnapshot=g,A(p)&&m({inst:p})},[u,h,g]),i(function(){return A(p)&&m({inst:p}),u(function(){A(p)&&m({inst:p})})},[u]),s(h),h}function A(u){var g=u.getSnapshot;u=u.value;try{var h=g();return!n(u,h)}catch{return!0}}function c(u,g){return g()}var l=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?c:a;return XMe.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:l,XMe}var ZMe={},sFt;function wFo(){if(sFt)return ZMe;sFt=1;var t={env:{}};return t.env.NODE_ENV!=="production"&&(function(){function e(d,p){return d===p&&(d!==0||1/d===1/p)||d!==d&&p!==p}function n(d,p){u||r.startTransition===void 0||(u=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var m=p();if(!g){var _=p();s(m,_)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),g=!0)}_=a({inst:{value:m,getSnapshot:p}});var f=_[0].inst,I=_[1];return c(function(){f.value=m,f.getSnapshot=p,o(f)&&I({inst:f})},[d,m,p]),A(function(){return o(f)&&I({inst:f}),d(function(){o(f)&&I({inst:f})})},[d]),l(m),m}function o(d){var p=d.getSnapshot;d=d.value;try{var m=p();return!s(d,m)}catch{return!0}}function i(d,p){return p()}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var r=L3(),s=typeof Object.is=="function"?Object.is:e,a=r.useState,A=r.useEffect,c=r.useLayoutEffect,l=r.useDebugValue,u=!1,g=!1,h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?i:n;ZMe.useSyncExternalStore=r.useSyncExternalStore!==void 0?r.useSyncExternalStore:h,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})(),ZMe}var aFt;function AFt(){if(aFt)return Xue.exports;aFt=1;var t={env:{}};return t.env.NODE_ENV==="production"?Xue.exports=vFo():Xue.exports=wFo(),Xue.exports}var cFt;function PFo(){if(cFt)return qMe;cFt=1;var t=L3(),e=AFt();function n(c,l){return c===l&&(c!==0||1/c===1/l)||c!==c&&l!==l}var o=typeof Object.is=="function"?Object.is:n,i=e.useSyncExternalStore,r=t.useRef,s=t.useEffect,a=t.useMemo,A=t.useDebugValue;return qMe.useSyncExternalStoreWithSelector=function(c,l,u,g,h){var d=r(null);if(d.current===null){var p={hasValue:!1,value:null};d.current=p}else p=d.current;d=a(function(){function _(x){if(!f){if(f=!0,I=x,x=g(x),h!==void 0&&p.hasValue){var E=p.value;if(h(E,x))return C=E}return C=x}if(E=C,o(I,x))return E;var B=g(x);return h!==void 0&&h(E,B)?(I=x,E):(I=x,C=B)}var f=!1,I,C,y=u===void 0?null:u;return[function(){return _(l())},y===null?void 0:function(){return _(y())}]},[l,u,g,h]);var m=i(c,d[0],d[1]);return s(function(){p.hasValue=!0,p.value=m},[m]),A(m),m},qMe}var eDe={},lFt;function MFo(){if(lFt)return eDe;lFt=1;var t={env:{}};return t.env.NODE_ENV!=="production"&&(function(){function e(l,u){return l===u&&(l!==0||1/l===1/u)||l!==l&&u!==u}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var n=L3(),o=AFt(),i=typeof Object.is=="function"?Object.is:e,r=o.useSyncExternalStore,s=n.useRef,a=n.useEffect,A=n.useMemo,c=n.useDebugValue;eDe.useSyncExternalStoreWithSelector=function(l,u,g,h,d){var p=s(null);if(p.current===null){var m={hasValue:!1,value:null};p.current=m}else m=p.current;p=A(function(){function f(E){if(!I){if(I=!0,C=E,E=h(E),d!==void 0&&m.hasValue){var B=m.value;if(d(B,E))return y=B}return y=E}if(B=y,i(C,E))return B;var S=h(E);return d!==void 0&&d(B,S)?(C=E,B):(C=E,y=S)}var I=!1,C,y,x=g===void 0?null:g;return[function(){return f(u())},x===null?void 0:function(){return f(x())}]},[u,g,h,d]);var _=r(l,p[0],p[1]);return a(function(){m.hasValue=!0,m.value=_},[_]),c(_),_},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})(),eDe}var uFt;function DFo(){if(uFt)return que.exports;uFt=1;var t={env:{}};return t.env.NODE_ENV==="production"?que.exports=PFo():que.exports=MFo(),que.exports}var NFo=DFo();const RFo=_y(NFo),gFt={},{useDebugValue:TFo}=Fs,{useSyncExternalStoreWithSelector:kFo}=RFo;let dFt=!1;const FFo=t=>t;function hFt(t,e=FFo,n){(gFt?"production":void 0)!=="production"&&n&&!dFt&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),dFt=!0);const o=kFo(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,n);return TFo(o),o}const LFo=t=>{(gFt?"production":void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof t=="function"?iFt(t):t,n=(o,i)=>hFt(e,o,i);return Object.assign(n,e),n},pFt=t=>LFo,tDe={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},nDe=new Map,Zue=t=>{const e=nDe.get(t);return e?Object.fromEntries(Object.entries(e.stores).map(([n,o])=>[n,o.getState()])):{}},HFo=(t,e,n)=>{if(t===void 0)return{type:"untracked",connection:e.connect(n)};const o=nDe.get(n.name);if(o)return{type:"tracked",store:t,...o};const i={connection:e.connect(n),stores:{}};return nDe.set(n.name,i),{type:"tracked",store:t,...i}},mFt=(t,e={})=>(n,o,i)=>{const{enabled:r,anonymousActionType:s,store:a,...A}=e;let c;try{c=(r??(tDe?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!c)return(tDe?"production":void 0)!=="production"&&r&&console.warn("[zustand devtools middleware] Please install/enable Redux devtools extension"),t(n,o,i);const{connection:l,...u}=HFo(a,c,A);let g=!0;i.setState=(p,m,_)=>{const f=n(p,m);if(!g)return f;const I=_===void 0?{type:s||"anonymous"}:typeof _=="string"?{type:_}:_;return a===void 0?(l?.send(I,o()),f):(l?.send({...I,type:`${a}/${I.type}`},{...Zue(A.name),[a]:i.getState()}),f)};const h=(...p)=>{const m=g;g=!1,n(...p),g=m},d=t(i.setState,o,i);if(u.type==="untracked"?l?.init(d):(u.stores[u.store]=i,l?.init(Object.fromEntries(Object.entries(u.stores).map(([p,m])=>[p,p===u.store?d:m.getState()])))),i.dispatchFromDevtools&&typeof i.dispatch=="function"){let p=!1;const m=i.dispatch;i.dispatch=(..._)=>{(tDe?"production":void 0)!=="production"&&_[0].type==="__setState"&&!p&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),p=!0),m(..._)}}return l.subscribe(p=>{var m;switch(p.type){case"ACTION":if(typeof p.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return oDe(p.payload,_=>{if(_.type==="__setState"){if(a===void 0){h(_.state);return}Object.keys(_.state).length!==1&&console.error(`
                    [zustand devtools middleware] Unsupported __setState action format. 
                    When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
                    and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
                    `);const f=_.state[a];if(f==null)return;JSON.stringify(i.getState())!==JSON.stringify(f)&&h(f);return}i.dispatchFromDevtools&&typeof i.dispatch=="function"&&i.dispatch(_)});case"DISPATCH":switch(p.payload.type){case"RESET":return h(d),a===void 0?l?.init(i.getState()):l?.init(Zue(A.name));case"COMMIT":if(a===void 0){l?.init(i.getState());return}return l?.init(Zue(A.name));case"ROLLBACK":return oDe(p.state,_=>{if(a===void 0){h(_),l?.init(i.getState());return}h(_[a]),l?.init(Zue(A.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return oDe(p.state,_=>{if(a===void 0){h(_);return}JSON.stringify(i.getState())!==JSON.stringify(_[a])&&h(_[a])});case"IMPORT_STATE":{const{nextLiftedState:_}=p.payload,f=(m=_.computedStates.slice(-1)[0])==null?void 0:m.state;if(!f)return;h(a===void 0?f:f[a]),l?.send(null,_);return}case"PAUSE_RECORDING":return g=!g}return}}),d},oDe=(t,e)=>{let n;try{n=JSON.parse(t)}catch(o){console.error("[zustand devtools middleware] Could not parse the received json",o)}n!==void 0&&e(n)},QC=window.TSCIRCUIT_FILESERVER_API_BASE_URL??"/api",OFo=[".tsx",".ts",".jsx",".js",".mjs",".json",".kicad_pcb",".kicad_sym",".kicad_sch",".kicad_prl",".kicad_pro"],iDe=t=>OFo.some(e=>t.endsWith(e)),b$=nFt.extend("store");async function _Ft(t,e){return(await(await fetch(`${QC}/files/upsert`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file_path:t,text_content:e})})).json()).file}async function rDe(t){return(await(await fetch(`${QC}/files/get?file_path=${encodeURIComponent(t)}`)).json()).file}async function GFo(t){const e=t?`${QC}/events/list?since=${encodeURIComponent(t)}`:`${QC}/events/list`;return(await(await fetch(e)).json()).event_list}async function YFo(){const t=await fetch(`${QC}/files/list`),{file_list:e}=await t.json(),n=new Map;for(const o of e){if(iDe(o.file_path)){const i=await rDe(o.file_path);n.set(o.file_path,i.text_content);continue}n.set(o.file_path,"__STATIC_ASSET__")}return n}const UFo=["manual-edits.json","manual_edits.json"],md=pFt()(mFt((t,e)=>({fsMap:new Map,lastEventTime:new Date().toISOString(),isPolling:!1,error:null,circuitJson:null,lastManualEditsChangeSentAt:0,recentEvents:[],simulateScenarioOrder:void 0,currentMainComponentPath:null,recentlySavedFiles:[],loadInitialFiles:async()=>{const n=await YFo();b$("loaded initial files",{fsMap:n}),t({fsMap:n})},upsertFile:async(n,o)=>{try{const i=await _Ft(n,o);t(r=>({fsMap:new Map(r.fsMap).set(i.file_path,i.text_content)}))}catch(i){t({error:i})}},getFile:async n=>{try{const o=await rDe(n);t(i=>({fsMap:new Map(i.fsMap).set(o.file_path,o.text_content)}))}catch(o){t({error:o})}},setCircuitJson:n=>{n!==e().circuitJson&&t({circuitJson:n})},addRecentlySavedFile:n=>{t(o=>{if(UFo.includes(n)||!iDe(n))return o;const i=o.recentlySavedFiles.filter(r=>r!==n);return{recentlySavedFiles:[n,...i].slice(0,10)}})},startPolling:()=>{const n=async()=>{const o=e();if(o.isPolling){try{const i=await GFo(o.lastEventTime);if(i.length>0){const r=i[i.length-1].created_at;b$("received events",i.map(A=>A.event_type)),t(A=>({recentEvents:[...A.recentEvents,...i].slice(0,100),lastEventTime:r}));let s=0;const a=new Map(o.fsMap);for(const A of i)if(A.event_type==="FILE_UPDATED"){s++;const c=await rDe(A.file_path);if(A.file_path==="manual_edits.json"&&Date.now()-o.lastManualEditsChangeSentAt<1e3)continue;iDe(c.file_path)?a.set(c.file_path,c.text_content??""):a.set(c.file_path,"__STATIC_ASSET__"),e().addRecentlySavedFile(A.file_path)}else A.event_type==="FILE_DELETED"&&(s++,a.delete(A.file_path));s>0&&(b$("updating fsMap, fsUpdateCount:",s),t({fsMap:a}))}}catch(i){t({error:i})}setTimeout(n,1e3)}};t({isPolling:!0}),n()},stopPolling:()=>{t({isPolling:!1})},pushEvent:async n=>{await fetch(`${QC}/events/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})},applyEditEventsAndUpdateManualEditsJson:async n=>{b$("applyEditEventsAndUpdateManualEditsJson",{editEvents:n});const o=e();if(!o.circuitJson)return;const i=o.fsMap.get("manual-edits.json"),r=i?JSON.parse(i):{},s=VRt({circuitJson:o.circuitJson,editEvents:n,manualEditsFile:r});b$("updatedManualEditsFileContent",s),t(a=>({lastManualEditsChangeSentAt:Date.now(),fsMap:new Map(a.fsMap).set("manual-edits.json",JSON.stringify(s))})),await _Ft("manual-edits.json",JSON.stringify(s,null,2))},setSimulateScenarioOrder:n=>t({simulateScenarioOrder:n}),setCurrentMainComponentPath:n=>t({currentMainComponentPath:n})}),{name:"run-frame-store"})),KFo=nFt.extend("useEditEventController"),VFo=()=>{const t=md(h=>h.applyEditEventsAndUpdateManualEditsJson),[e,n]=ee.useState([]),[o,i]=ee.useState(!1),r=e.filter(h=>!h._applied),s=e.filter(h=>h._applied),a=o?e:r,A=ee.useCallback(h=>{n(d=>[...d,{...h,_applied:!1}])},[]),c=ee.useCallback(h=>{n(d=>d.map(p=>p===h?{...p,_applied:!0}:p))},[]),l=ee.useCallback(()=>{n(h=>h.map(d=>({...d,_applied:!0})))},[]),u=ee.useCallback(()=>{i(!0),e.length!==0&&(KFo("removing edit events that are applied"),n(h=>h.filter(d=>!d._applied)))},[e]),g=ee.useCallback(()=>{i(!1)},[]);return ee.useEffect(()=>{if(e.filter(d=>!d._applied).length===0)return;const h=setTimeout(()=>{l(),t(e)},1e3);return()=>clearTimeout(h)},[e]),{unappliedEditEvents:r,appliedEditEvents:s,editEventsForRender:a,pushEditEvent:A,markEditEventApplied:c,markRenderStarted:u,markRenderComplete:g,markAllEditEventsApplied:l}},sDe=vc("run-frame:useHasReceivedInitialFilesLoaded"),zFo=()=>{const[t,e]=ee.useState(!1),n=md(i=>i.recentEvents),o=md(i=>i.loadInitialFiles);return ee.useEffect(()=>{(async()=>{await o();try{const r=await fetch(`${QC}/events/list?event_type=INITIAL_FILES_UPLOADED`);if(r.ok){const{event_list:s}=await r.json();if(s.length>0){sDe("INITIAL_FILES_UPLOADED found in history. Assuming ready."),e(!0);return}}}catch(r){console.error("Failed to check for event history",r)}sDe("No INITIAL_FILES_UPLOADED in history, waiting for polling.")})()},[o]),ee.useEffect(()=>{t||n.some(i=>i.event_type==="INITIAL_FILES_UPLOADED")&&(sDe("INITIAL_FILES_UPLOADED received via polling. Assuming ready."),e(!0))},[n,t]),t};function OO(t,e,n){const[o,i]=ee.useState(()=>{if(n!==void 0)return n;try{const r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return console.error("Error reading from localStorage:",r),e}});return ee.useEffect(()=>{try{window.localStorage.setItem(t,JSON.stringify(o))}catch(r){console.error("Error writing to localStorage:",r)}},[t,o]),[o,i]}var JFo=Object.defineProperty,GO=(t,e)=>JFo(t,"name",{value:e,configurable:!0}),fFt=!!(typeof window<"u"&&window.document&&window.document.createElement);function ar(t,e,{checkForDefaultPrevented:n=!0}={}){return GO(function(i){if(t?.(i),n===!1||!i||!i.defaultPrevented)return e?.(i)},"handleEvent")}GO(ar,"composeEventHandlers");function WFo(t){if(!fFt)throw new Error("Cannot access window outside of the DOM");return t?.ownerDocument?.defaultView??window}GO(WFo,"getOwnerWindow");function aDe(t){if(!fFt)throw new Error("Cannot access document outside of the DOM");return t?.ownerDocument??document}GO(aDe,"getOwnerDocument");function IFt(t,e=!1){const{activeElement:n}=aDe(t);if(!n?.nodeName)return null;if(CFt(n)&&n.contentDocument)return IFt(n.contentDocument.body,e);if(e){const o=n.getAttribute("aria-activedescendant");if(o){const i=aDe(n).getElementById(o);if(i)return i}}return n}GO(IFt,"getActiveElement");function CFt(t){return t.tagName==="IFRAME"}GO(CFt,"isFrame");var jFo=Object.defineProperty,s4=(t,e)=>jFo(t,"name",{value:e,configurable:!0});function $Fo(t,e){const n=ee.createContext(e);n.displayName=t+"Context";const o=s4(r=>{const{children:s,...a}=r,A=ee.useMemo(()=>a,Object.values(a));return K.jsx(n.Provider,{value:A,children:s})},"Provider");o.displayName=t+"Provider";function i(r,s={}){const{optional:a=!1}=s,A=ee.useContext(n);if(A)return A;if(e!==void 0)return e;if(!a)throw new Error(`\`${r}\` must be used within \`${t}\``)}return s4(i,"useContext"),[o,i]}s4($Fo,"createContext");function Nx(t,e=[]){let n=[];function o(r,s){const a=ee.createContext(s);a.displayName=r+"Context";const A=n.length;n=[...n,s];const c=s4(u=>{const{scope:g,children:h,...d}=u,p=g?.[t]?.[A]||a,m=ee.useMemo(()=>d,Object.values(d));return K.jsx(p.Provider,{value:m,children:h})},"Provider");c.displayName=r+"Provider";function l(u,g,h={}){const{optional:d=!1}=h,p=g?.[t]?.[A]||a,m=ee.useContext(p);if(m)return m;if(s!==void 0)return s;if(!d)throw new Error(`\`${u}\` must be used within \`${r}\``)}return s4(l,"useContext"),[c,l]}s4(o,"createContext");const i=s4(()=>{const r=n.map(s=>ee.createContext(s));return s4(function(a){const A=a?.[t]||r;return ee.useMemo(()=>({[`__scope${t}`]:{...a,[t]:A}}),[a,A])},"useScope")},"createScope");return i.scopeName=t,[o,yFt(i,...e)]}s4(Nx,"createContextScope");function yFt(...t){const e=t[0];if(t.length===1)return e;const n=s4(()=>{const o=t.map(i=>({useScope:i(),scopeName:i.scopeName}));return s4(function(r){const s=o.reduce((a,{useScope:A,scopeName:c})=>{const u=A(r)[`__scope${c}`];return{...a,...u}},{});return ee.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])},"useComposedScopes")},"createScope");return n.scopeName=e.scopeName,n}s4(yFt,"composeContextScopes");var qFo=Object.defineProperty,ADe=(t,e)=>qFo(t,"name",{value:e,configurable:!0});function cDe(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}ADe(cDe,"setRef");function _R(...t){return e=>{let n=!1;const o=t.map(i=>{const r=cDe(i,e);return!n&&typeof r=="function"&&(n=!0),r});if(n)return()=>{for(let i=0;i<o.length;i++){const r=o[i];typeof r=="function"?r():cDe(t[i],null)}}}}ADe(_R,"composeRefs");function $A(...t){return ee.useCallback(_R(...t),t)}ADe($A,"useComposedRefs");var XFo=Object.defineProperty,PB=(t,e)=>XFo(t,"name",{value:e,configurable:!0});function MB(t){const e=ee.forwardRef((n,o)=>{let{children:i,...r}=n,s=null,a=!1;const A=[];lDe(i)&&typeof ege=="function"&&(i=ege(i._payload)),ee.Children.forEach(i,g=>{if(SFt(g)){a=!0;const h=g;let d="child"in h.props?h.props.child:h.props.children;lDe(d)&&typeof ege=="function"&&(d=ege(d._payload)),s=eLo(h,d),A.push(s?.props?.children)}else A.push(g)}),s?s=ee.cloneElement(s,void 0,A):!a&&ee.Children.count(i)===1&&ee.isValidElement(i)&&(s=i);const c=s?bFt(s):void 0,l=$A(o,c);if(!s){if(i||i===0)throw new Error(a?oLo(t):nLo(t));return i}const u=BFt(r,s.props??{});return s.type!==ee.Fragment&&(u.ref=o?l:c),ee.cloneElement(s,u)});return e.displayName=`${t}.Slot`,e}PB(MB,"createSlot");var ZFo=MB("Slot"),xFt=Symbol.for("radix.slottable");function EFt(t){const e=PB(n=>"child"in n?n.children(n.child):n.children,"Slottable");return e.displayName=`${t}.Slottable`,e.__radixId=xFt,e}PB(EFt,"createSlottable");var eLo=PB((t,e)=>{if("child"in t.props){const n=t.props.child;return ee.isValidElement(n)?ee.cloneElement(n,void 0,t.props.children(n.props.children)):null}return ee.isValidElement(e)?e:null},"getSlottableElementFromSlottable");function BFt(t,e){const n={...e};for(const o in e){const i=t[o],r=e[o];/^on[A-Z]/.test(o)?i&&r?n[o]=(...a)=>{const A=r(...a);return i(...a),A}:i&&(n[o]=i):o==="style"?n[o]={...i,...r}:o==="className"&&(n[o]=[i,r].filter(Boolean).join(" "))}return{...t,...n}}PB(BFt,"mergeProps");function bFt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}PB(bFt,"getElementRef");function SFt(t){return ee.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===xFt}PB(SFt,"isSlottable");var tLo=Symbol.for("react.lazy");function lDe(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===tLo&&"_payload"in t&&QFt(t._payload)}PB(lDe,"isLazyComponent");function QFt(t){return typeof t=="object"&&t!==null&&"then"in t}PB(QFt,"isPromiseLike");var nLo=PB(t=>`${t} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),oLo=PB(t=>`${t} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),ege=Q5[" use ".trim().toString()],iLo=Object.defineProperty,o1=(t,e)=>iLo(t,"name",{value:e,configurable:!0});function tge(t){const e=t+"CollectionProvider",[n,o]=Nx(e),[i,r]=n(e,{collectionRef:{current:null},itemMap:new Map}),s=o1(p=>{const{scope:m,children:_}=p,f=ee.useRef(null),I=ee.useRef(new Map).current;return K.jsx(i,{scope:m,itemMap:I,collectionRef:f,children:_})},"CollectionProvider");s.displayName=e;const a=t+"CollectionSlot",A=MB(a),c=ee.forwardRef((p,m)=>{const{scope:_,children:f}=p,I=r(a,_),C=$A(m,I.collectionRef);return K.jsx(A,{ref:C,children:f})});c.displayName=a;const l=t+"CollectionItemSlot",u="data-radix-collection-item",g=MB(l),h=ee.forwardRef((p,m)=>{const{scope:_,children:f,...I}=p,C=ee.useRef(null),y=$A(m,C),x=r(l,_);return ee.useEffect(()=>(x.itemMap.set(C,{ref:C,...I}),()=>{x.itemMap.delete(C)})),K.jsx(g,{[u]:"",ref:y,children:f})});h.displayName=l;function d(p){const m=r(t+"CollectionConsumer",p);return ee.useCallback(()=>{const f=m.collectionRef.current;if(!f)return[];const I=Array.from(f.querySelectorAll(`[${u}]`));return Array.from(m.itemMap.values()).sort((x,E)=>I.indexOf(x.ref.current)-I.indexOf(E.ref.current))},[m.collectionRef,m.itemMap])}return o1(d,"useCollection"),[{Provider:s,Slot:c,ItemSlot:h},d,o]}o1(tge,"createCollection");var vFt=new WeakMap,uDe=(YE=class extends Map{constructor(n){super(n);uit(this,h_);Yte(this,h_,[...super.keys()]),vFt.set(this,!0)}set(n,o){return vFt.get(this)&&(this.has(n)?w0(this,h_)[w0(this,h_).indexOf(n)]=n:w0(this,h_).push(n)),super.set(n,o),this}insert(n,o,i){const r=this.has(o),s=w0(this,h_).length,a=gDe(n);let A=a>=0?a:s+a;const c=A<0||A>=s?-1:A;if(c===this.size||r&&c===this.size-1||c===-1)return this.set(o,i),this;const l=this.size+(r?0:1);a<0&&A++;const u=[...w0(this,h_)];let g,h=!1;for(let d=A;d<l;d++)if(A===d){let p=u[d];u[d]===o&&(p=u[d+1]),r&&this.delete(o),g=this.get(p),this.set(o,i)}else{!h&&u[d-1]===o&&(h=!0);const p=u[h?d:d-1],m=g;g=this.get(p),this.delete(p),this.set(p,m)}return this}with(n,o,i){const r=new YE(this);return r.insert(n,o,i),r}before(n){const o=w0(this,h_).indexOf(n)-1;if(!(o<0))return this.entryAt(o)}setBefore(n,o,i){const r=w0(this,h_).indexOf(n);return r===-1?this:this.insert(r,o,i)}after(n){let o=w0(this,h_).indexOf(n);if(o=o===-1||o===this.size-1?-1:o+1,o!==-1)return this.entryAt(o)}setAfter(n,o,i){const r=w0(this,h_).indexOf(n);return r===-1?this:this.insert(r+1,o,i)}first(){return this.entryAt(0)}last(){return this.entryAt(-1)}clear(){return Yte(this,h_,[]),super.clear()}delete(n){const o=super.delete(n);return o&&w0(this,h_).splice(w0(this,h_).indexOf(n),1),o}deleteAt(n){const o=this.keyAt(n);return o!==void 0?this.delete(o):!1}at(n){const o=nge(w0(this,h_),n);if(o!==void 0)return this.get(o)}entryAt(n){const o=nge(w0(this,h_),n);if(o!==void 0)return[o,this.get(o)]}indexOf(n){return w0(this,h_).indexOf(n)}keyAt(n){return nge(w0(this,h_),n)}from(n,o){const i=this.indexOf(n);if(i===-1)return;let r=i+o;return r<0&&(r=0),r>=this.size&&(r=this.size-1),this.at(r)}keyFrom(n,o){const i=this.indexOf(n);if(i===-1)return;let r=i+o;return r<0&&(r=0),r>=this.size&&(r=this.size-1),this.keyAt(r)}find(n,o){let i=0;for(const r of this){if(Reflect.apply(n,o,[r,i,this]))return r;i++}}findIndex(n,o){let i=0;for(const r of this){if(Reflect.apply(n,o,[r,i,this]))return i;i++}return-1}filter(n,o){const i=[];let r=0;for(const s of this)Reflect.apply(n,o,[s,r,this])&&i.push(s),r++;return new YE(i)}map(n,o){const i=[];let r=0;for(const s of this)i.push([s[0],Reflect.apply(n,o,[s,r,this])]),r++;return new YE(i)}reduce(...n){const[o,i]=n;let r=0,s=i??this.at(0);for(const a of this)r===0&&n.length===1?s=a:s=Reflect.apply(o,this,[s,a,r,this]),r++;return s}reduceRight(...n){const[o,i]=n;let r=i??this.at(-1);for(let s=this.size-1;s>=0;s--){const a=this.at(s);s===this.size-1&&n.length===1?r=a:r=Reflect.apply(o,this,[r,a,s,this])}return r}toSorted(n){const o=[...this.entries()].sort(n);return new YE(o)}toReversed(){const n=new YE;for(let o=this.size-1;o>=0;o--){const i=this.keyAt(o),r=this.get(i);n.set(i,r)}return n}toSpliced(...n){const o=[...this.entries()];return o.splice(...n),new YE(o)}slice(n,o){const i=new YE;let r=this.size-1;if(n===void 0)return i;n<0&&(n=n+this.size),o!==void 0&&o>0&&(r=o-1);for(let s=n;s<=r;s++){const a=this.keyAt(s),A=this.get(a);i.set(a,A)}return i}every(n,o){let i=0;for(const r of this){if(!Reflect.apply(n,o,[r,i,this]))return!1;i++}return!0}some(n,o){let i=0;for(const r of this){if(Reflect.apply(n,o,[r,i,this]))return!0;i++}return!1}},h_=new WeakMap,o1(YE,"OrderedDict"),YE);function nge(t,e){if("at"in Array.prototype)return Array.prototype.at.call(t,e);const n=wFt(t,e);return n===-1?void 0:t[n]}o1(nge,"at");function wFt(t,e){const n=t.length,o=gDe(e),i=o>=0?o:n+o;return i<0||i>=n?-1:i}o1(wFt,"toSafeIndex");function gDe(t){return t!==t||t===0?0:Math.trunc(t)}o1(gDe,"toSafeInteger");function rLo(t){const e=t+"CollectionProvider",[n,o]=Nx(e),[i,r]=n(e,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new uDe,setItemMap:o1(()=>{},"setItemMap")}),s=o1(({state:I,...C})=>I?K.jsx(A,{...C,state:I}):K.jsx(a,{...C}),"CollectionProvider");s.displayName=e;const a=o1(I=>{const C=m();return K.jsx(A,{...I,state:C})},"CollectionInit");a.displayName=e+"Init";const A=o1(I=>{const{scope:C,children:y,state:x}=I,E=ee.useRef(null),[B,S]=ee.useState(null),Q=$A(E,S),[w,M]=x;return ee.useEffect(()=>{if(!B)return;const k=DFt(()=>{});return k.observe(B,{childList:!0,subtree:!0}),()=>{k.disconnect()}},[B]),K.jsx(i,{scope:C,itemMap:w,setItemMap:M,collectionRef:Q,collectionRefObject:E,collectionElement:B,children:y})},"CollectionProviderImpl");A.displayName=e+"Impl";const c=t+"CollectionSlot",l=MB(c),u=ee.forwardRef((I,C)=>{const{scope:y,children:x}=I,E=r(c,y),B=$A(C,E.collectionRef);return K.jsx(l,{ref:B,children:x})});u.displayName=c;const g=t+"CollectionItemSlot",h="data-radix-collection-item",d=MB(g),p=ee.forwardRef((I,C)=>{const{scope:y,children:x,...E}=I,B=ee.useRef(null),[S,Q]=ee.useState(null),w=$A(C,B,Q),M=r(g,y),{setItemMap:k}=M,R=ee.useRef(E);PFt(R.current,E)||(R.current=E);const F=R.current;return ee.useEffect(()=>{const O=F;return k(U=>S?U.has(S)?U.set(S,{...O,element:S}).toSorted(dDe):(U.set(S,{...O,element:S}),U.toSorted(dDe)):U),()=>{k(U=>!S||!U.has(S)?U:(U.delete(S),new uDe(U)))}},[S,F,k]),K.jsx(d,{[h]:"",ref:w,children:x})});p.displayName=g;function m(){return ee.useState(new uDe)}o1(m,"useInitCollection");function _(I){const{itemMap:C}=r(t+"CollectionConsumer",I);return C}return o1(_,"useCollection"),[{Provider:s,Slot:u,ItemSlot:p},{createCollectionScope:o,useCollection:_,useInitCollection:m}]}o1(rLo,"createCollection");function PFt(t,e){if(t===e)return!0;if(typeof t!="object"||typeof e!="object"||t==null||e==null)return!1;const n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(const i of n)if(!Object.prototype.hasOwnProperty.call(e,i)||t[i]!==e[i])return!1;return!0}o1(PFt,"shallowEqual");function MFt(t,e){return!!(e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_PRECEDING)}o1(MFt,"isElementPreceding");function dDe(t,e){return!t[1].element||!e[1].element?0:MFt(t[1].element,e[1].element)?-1:1}o1(dDe,"sortByDocumentPosition");function DFt(t){return new MutationObserver(n=>{for(const o of n)if(o.type==="childList"){t();return}})}o1(DFt,"getChildListObserver");var Ep=globalThis?.document?ee.useLayoutEffect:()=>{},sLo=Object.defineProperty,aLo=(t,e)=>sLo(t,"name",{value:e,configurable:!0}),ALo=Q5[" useId ".trim().toString()]||(()=>{}),cLo=0;function t_(t){const[e,n]=ee.useState(ALo());return Ep(()=>{t||n(o=>o??String(cLo++))},[t]),t||(e?`radix-${e}`:"")}aLo(t_,"useId");var c6=Xye();const NFt=_y(c6);var lLo=Object.defineProperty,uLo=(t,e)=>lLo(t,"name",{value:e,configurable:!0}),gLo=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Na=gLo.reduce((t,e)=>{const n=MB(`Primitive.${e}`),o=ee.forwardRef((i,r)=>{const{asChild:s,...a}=i,A=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),K.jsx(A,{...a,ref:r})});return o.displayName=`Primitive.${e}`,{...t,[e]:o}},{});function hDe(t,e){t&&c6.flushSync(()=>t.dispatchEvent(e))}uLo(hDe,"dispatchDiscreteCustomEvent");var dLo=Object.defineProperty,hLo=(t,e)=>dLo(t,"name",{value:e,configurable:!0});function lE(t){const e=ee.useRef(t);return ee.useEffect(()=>{e.current=t}),ee.useMemo(()=>((...n)=>e.current?.(...n)),[])}hLo(lE,"useCallbackRef");var pLo=Object.defineProperty,mLo=(t,e)=>pLo(t,"name",{value:e,configurable:!0}),RFt=Q5[" useEffectEvent ".trim().toString()],TFt=Q5[" useInsertionEffect ".trim().toString()];function kFt(t){if(typeof RFt=="function")return RFt(t);const e=ee.useRef(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof TFt=="function"?TFt(()=>{e.current=t}):Ep(()=>{e.current=t}),ee.useMemo(()=>((...n)=>e.current?.(...n)),[])}mLo(kFt,"useEffectEvent");var _Lo=Object.defineProperty,S$=(t,e)=>_Lo(t,"name",{value:e,configurable:!0}),fLo=Q5[" useInsertionEffect ".trim().toString()]||Ep;function DB({prop:t,defaultProp:e,onChange:n=S$(()=>{},"onChange"),caller:o}){const[i,r,s]=FFt({defaultProp:e,onChange:n}),a=t!==void 0,A=a?t:i,c=ee.useCallback(l=>{if(a){const u=LFt(l)?l(t):l;u!==t&&s.current?.(u)}else r(l)},[a,t,r,s]);return[A,c]}S$(DB,"useControllableState");function FFt({defaultProp:t,onChange:e}){const[n,o]=ee.useState(t),i=ee.useRef(n),r=ee.useRef(e);return fLo(()=>{r.current=e},[e]),ee.useEffect(()=>{i.current!==n&&(r.current?.(n),i.current=n)},[n,i]),[n,o,r]}S$(FFt,"useUncontrolledState");function LFt(t){return typeof t=="function"}S$(LFt,"isFunction");var HFt=Symbol("RADIX:SYNC_STATE");function ILo(t,e,n,o){const{prop:i,defaultProp:r,onChange:s,caller:a}=e,A=i!==void 0,c=kFt(s),l=[{...n,state:r}];o&&l.push(o);const[u,g]=ee.useReducer((m,_)=>{if(_.type===HFt)return{...m,state:_.state};const f=t(m,_);return A&&!Object.is(f.state,m.state)&&c(f.state),f},...l),h=u.state,d=ee.useRef(h);ee.useEffect(()=>{d.current!==h&&(d.current=h,A||c(h))},[h,d,A]);const p=ee.useMemo(()=>i!==void 0?{...u,state:i}:u,[u,i]);return ee.useEffect(()=>{A&&!Object.is(i,u.state)&&g({type:HFt,state:i})},[i,u.state,A]),[p,g]}S$(ILo,"useControllableStateReducer");var CLo=Object.defineProperty,yLo=(t,e)=>CLo(t,"name",{value:e,configurable:!0}),xLo=ee.createContext(void 0);function Q$(t){const e=ee.useContext(xLo);return t||e||"ltr"}yLo(Q$,"useDirection");var ELo=Object.defineProperty,pDe=(t,e)=>ELo(t,"name",{value:e,configurable:!0}),mDe=!1;function OFt(){const[t,e]=ee.useState(mDe);return ee.useEffect(()=>{mDe||(mDe=!0,e(!0))},[]),t}pDe(OFt,"useIsHydrated");var GFt=Q5[" useSyncExternalStore ".trim().toString()];function YFt(){return()=>{}}pDe(YFt,"subscribe");function UFt(){return GFt(YFt,()=>!0,()=>!1)}pDe(UFt,"useIsHydratedModern");var BLo=typeof GFt=="function"?UFt:OFt,bLo=Object.defineProperty,fR=(t,e)=>bLo(t,"name",{value:e,configurable:!0}),_De="rovingFocusGroup.onEntryFocus",SLo={bubbles:!1,cancelable:!0},oge="RovingFocusGroup",[fDe,KFt,QLo]=tge(oge),[vLo,ige]=Nx(oge,[QLo]),[wLo,PLo]=vLo(oge),MLo=ee.forwardRef(fR(function(e,n){return K.jsx(fDe.Provider,{scope:e.__scopeRovingFocusGroup,children:K.jsx(fDe.Slot,{scope:e.__scopeRovingFocusGroup,children:K.jsx(DLo,{...e,ref:n})})})},"RovingFocusGroup")),DLo=ee.forwardRef(fR(function(e,n){const{__scopeRovingFocusGroup:o,orientation:i,loop:r=!1,dir:s,currentTabStopId:a,defaultCurrentTabStopId:A,onCurrentTabStopIdChange:c,onEntryFocus:l,preventScrollOnEntryFocus:u=!1,...g}=e,h=ee.useRef(null),d=$A(n,h),p=Q$(s),[m,_]=DB({prop:a,defaultProp:A??null,onChange:c,caller:oge}),[f,I]=ee.useState(!1),C=lE(l),y=KFt(o),x=ee.useRef(!1),[E,B]=ee.useState(0);return ee.useEffect(()=>{const S=h.current;if(S)return S.addEventListener(_De,C),()=>S.removeEventListener(_De,C)},[C]),K.jsx(wLo,{scope:o,orientation:i,dir:p,loop:r,currentTabStopId:m,onItemFocus:ee.useCallback(S=>_(S),[_]),onItemShiftTab:ee.useCallback(()=>I(!0),[]),onFocusableItemAdd:ee.useCallback(()=>B(S=>S+1),[]),onFocusableItemRemove:ee.useCallback(()=>B(S=>S-1),[]),children:K.jsx(Na.div,{tabIndex:f||E===0?-1:0,"data-orientation":i,...g,ref:d,style:{outline:"none",...e.style},onMouseDown:ar(e.onMouseDown,()=>{x.current=!0}),onFocus:ar(e.onFocus,S=>{const Q=!x.current;if(S.target===S.currentTarget&&Q&&!f){const w=new CustomEvent(_De,SLo);if(S.currentTarget.dispatchEvent(w),!w.defaultPrevented){const M=y().filter(U=>U.focusable),k=M.find(U=>U.active),R=M.find(U=>U.id===m),O=[k,R,...M].filter(Boolean).map(U=>U.ref.current);IDe(O,u)}}x.current=!1}),onBlur:ar(e.onBlur,()=>I(!1))})})},"RovingFocusGroupImpl")),NLo="RovingFocusGroupItem",RLo=ee.forwardRef(fR(function(e,n){const{__scopeRovingFocusGroup:o,focusable:i=!0,active:r=!1,tabStopId:s,children:a,...A}=e,c=t_(),l=s||c,u=PLo(NLo,o),g=u.currentTabStopId===l,h=KFt(o),{onFocusableItemAdd:d,onFocusableItemRemove:p,currentTabStopId:m}=u,_=BLo();return Ep(()=>{if(!(!_||!i))return d(),()=>p()},[_,i,d,p]),ee.useEffect(()=>{if(!(_||!i))return d(),()=>p()},[_,i,d,p]),K.jsx(fDe.ItemSlot,{scope:o,id:l,focusable:i,active:r,children:K.jsx(Na.span,{tabIndex:g?0:-1,"data-orientation":u.orientation,...A,ref:n,onMouseDown:ar(e.onMouseDown,f=>{i?u.onItemFocus(l):f.preventDefault()}),onFocus:ar(e.onFocus,()=>u.onItemFocus(l)),onKeyDown:ar(e.onKeyDown,f=>{if(f.key==="Tab"&&f.shiftKey){u.onItemShiftTab();return}if(f.target!==f.currentTarget)return;const I=zFt(f,u.orientation,u.dir);if(I!==void 0){if(f.metaKey||f.ctrlKey||f.altKey||f.shiftKey)return;f.preventDefault();let y=h().filter(x=>x.focusable).map(x=>x.ref.current);if(I==="last")y.reverse();else if(I==="prev"||I==="next"){I==="prev"&&y.reverse();const x=y.indexOf(f.currentTarget);y=u.loop?JFt(y,x+1):y.slice(x+1)}setTimeout(()=>IDe(y))}}),children:typeof a=="function"?a({isCurrentTabStop:g,hasTabStop:m!=null}):a})})},"RovingFocusGroupItem")),TLo={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function VFt(t,e){return e!=="rtl"?t:t==="ArrowLeft"?"ArrowRight":t==="ArrowRight"?"ArrowLeft":t}fR(VFt,"getDirectionAwareKey");function zFt(t,e,n){const o=VFt(t.key,n);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(o))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(o)))return TLo[o]}fR(zFt,"getFocusIntent");function IDe(t,e=!1){const n=document.activeElement;for(const o of t)if(o===n||(o.focus({preventScroll:e}),document.activeElement!==n))return}fR(IDe,"focusFirst");function JFt(t,e){return t.map((n,o)=>t[(e+o)%t.length])}fR(JFt,"wrapArray");var WFt=MLo,jFt=RLo,kLo=Object.defineProperty,Lb=(t,e)=>kLo(t,"name",{value:e,configurable:!0});function $Ft(t,e){return ee.useReducer((n,o)=>e[n][o]??n,t)}Lb($Ft,"useStateMachine");var uE=Lb(t=>{const{present:e,children:n}=t,o=qFt(e),i=typeof n=="function"?n({present:o.isPresent}):ee.Children.only(n),r=XFt(o.ref,ZFt(i));return typeof n=="function"||o.isPresent?ee.cloneElement(i,{ref:r}):null},"Presence");function qFt(t){const[e,n]=ee.useState(),o=ee.useRef(null),i=ee.useRef(t),r=ee.useRef("none"),s=ee.useRef(void 0),a=t?"mounted":"unmounted",[A,c]=$Ft(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return ee.useEffect(()=>{A==="mounted"?(r.current=s.current??YO(o.current),s.current=void 0):r.current="none"},[A]),Ep(()=>{const l=o.current,u=i.current;if(u!==t){const h=r.current,d=YO(l);t?(s.current=d,c("MOUNT")):d==="none"||l?.display==="none"?c("UNMOUNT"):c(u&&h!==d?"ANIMATION_OUT":"UNMOUNT"),i.current=t}},[t,c]),Ep(()=>{if(e){let l;const u=e.ownerDocument.defaultView??window,g=Lb(d=>{const m=YO(o.current).includes(CSS.escape(d.animationName));if(d.target===e&&m&&(c("ANIMATION_END"),!i.current)){const _=e.style.animationFillMode;e.style.animationFillMode="forwards",l=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=_)})}},"handleAnimationEnd"),h=Lb(d=>{d.target===e&&(r.current=YO(o.current))},"handleAnimationStart");return e.addEventListener("animationstart",h),e.addEventListener("animationcancel",g),e.addEventListener("animationend",g),()=>{u.clearTimeout(l),e.removeEventListener("animationstart",h),e.removeEventListener("animationcancel",g),e.removeEventListener("animationend",g)}}else c("ANIMATION_END")},[e,c]),{isPresent:["mounted","unmountSuspended"].includes(A),ref:ee.useCallback(l=>{if(l){const u=getComputedStyle(l);o.current=u,s.current=YO(u)}else o.current=null;n(l)},[])}}Lb(qFt,"usePresence");function CDe(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}Lb(CDe,"setRef");function XFt(...t){const e=ee.useRef(t);return e.current=t,ee.useCallback(n=>{const o=e.current;let i=!1;const r=o.map(s=>{const a=CDe(s,n);return!i&&typeof a=="function"&&(i=!0),a});if(i)return()=>{for(let s=0;s<r.length;s++){const a=r[s];typeof a=="function"?a():CDe(o[s],null)}}},[])}Lb(XFt,"useStableComposedRefs");function YO(t){return t?.animationName||"none"}Lb(YO,"getAnimationName");function ZFt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}Lb(ZFt,"getElementRef");var FLo=Object.defineProperty,UO=(t,e)=>FLo(t,"name",{value:e,configurable:!0}),yDe="Tabs",[LLo,zhr]=Nx(yDe,[ige]),eLt=ige(),[HLo,xDe]=LLo(yDe),OLo=ee.forwardRef(UO(function(e,n){const{__scopeTabs:o,value:i,onValueChange:r,defaultValue:s,orientation:a="horizontal",dir:A,activationMode:c="automatic",...l}=e,u=Q$(A),[g,h]=DB({prop:i,onChange:r,defaultProp:s??"",caller:yDe});return K.jsx(HLo,{scope:o,baseId:t_(),value:g,onValueChange:h,orientation:a,dir:u,activationMode:c,children:K.jsx(Na.div,{dir:u,"data-orientation":a,...l,ref:n})})},"Tabs")),GLo="TabsList",YLo=ee.forwardRef(UO(function(e,n){const{__scopeTabs:o,loop:i=!0,...r}=e,s=xDe(GLo,o),a=eLt(o);return K.jsx(WFt,{asChild:!0,...a,orientation:s.orientation,dir:s.dir,loop:i,children:K.jsx(Na.div,{role:"tablist","aria-orientation":s.orientation,...r,ref:n})})},"TabsList")),ULo="TabsTrigger",KLo=ee.forwardRef(UO(function(e,n){const{__scopeTabs:o,value:i,disabled:r=!1,...s}=e,a=xDe(ULo,o),A=eLt(o),c=EDe(a.baseId,i),l=BDe(a.baseId,i),u=i===a.value;return K.jsx(jFt,{asChild:!0,...A,focusable:!r,active:u,children:K.jsx(Na.button,{type:"button",role:"tab","aria-selected":u,"aria-controls":l,"data-state":u?"active":"inactive","data-disabled":r?"":void 0,disabled:r,id:c,...s,ref:n,onMouseDown:ar(e.onMouseDown,g=>{!r&&g.button===0&&g.ctrlKey===!1?a.onValueChange(i):g.preventDefault()}),onKeyDown:ar(e.onKeyDown,g=>{r||g.target!==g.currentTarget||[" ","Enter"].includes(g.key)&&a.onValueChange(i)}),onFocus:ar(e.onFocus,()=>{const g=a.activationMode!=="manual";!u&&!r&&g&&a.onValueChange(i)})})})},"TabsTrigger")),VLo="TabsContent",zLo=ee.forwardRef(UO(function(e,n){const{__scopeTabs:o,value:i,forceMount:r,children:s,...a}=e,A=xDe(VLo,o),c=EDe(A.baseId,i),l=BDe(A.baseId,i),u=i===A.value,g=ee.useRef(u);return ee.useEffect(()=>{const h=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(h)},[]),K.jsx(uE,{present:r||u,children:({present:h})=>K.jsx(Na.div,{"data-state":u?"active":"inactive","data-orientation":A.orientation,role:"tabpanel","aria-labelledby":c,hidden:!h,id:l,tabIndex:0,...a,ref:n,style:{...e.style,animationDuration:g.current?"0s":void 0},children:h&&s})})},"TabsContent"));function EDe(t,e){return`${t}-trigger-${e}`}UO(EDe,"makeTriggerId");function BDe(t,e){return`${t}-content-${e}`}UO(BDe,"makeContentId");var JLo=OLo,tLt=YLo,nLt=KLo,oLt=zLo;function iLt(t){var e,n,o="";if(typeof t=="string"||typeof t=="number")o+=t;else if(typeof t=="object")if(Array.isArray(t)){var i=t.length;for(e=0;e<i;e++)t[e]&&(n=iLt(t[e]))&&(o&&(o+=" "),o+=n)}else for(n in t)t[n]&&(o&&(o+=" "),o+=n);return o}function NB(){for(var t,e,n=0,o="",i=arguments.length;n<i;n++)(t=arguments[n])&&(e=iLt(t))&&(o&&(o+=" "),o+=e);return o}const bDe="-",WLo=t=>{const e=$Lo(t),{conflictingClassGroups:n,conflictingClassGroupModifiers:o}=t;return{getClassGroupId:s=>{const a=s.split(bDe);return a[0]===""&&a.length!==1&&a.shift(),rLt(a,e)||jLo(s)},getConflictingClassGroupIds:(s,a)=>{const A=n[s]||[];return a&&o[s]?[...A,...o[s]]:A}}},rLt=(t,e)=>{if(t.length===0)return e.classGroupId;const n=t[0],o=e.nextPart.get(n),i=o?rLt(t.slice(1),o):void 0;if(i)return i;if(e.validators.length===0)return;const r=t.join(bDe);return e.validators.find(({validator:s})=>s(r))?.classGroupId},sLt=/^\[(.+)\]$/,jLo=t=>{if(sLt.test(t)){const e=sLt.exec(t)[1],n=e?.substring(0,e.indexOf(":"));if(n)return"arbitrary.."+n}},$Lo=t=>{const{theme:e,prefix:n}=t,o={nextPart:new Map,validators:[]};return XLo(Object.entries(t.classGroups),n).forEach(([r,s])=>{SDe(s,o,r,e)}),o},SDe=(t,e,n,o)=>{t.forEach(i=>{if(typeof i=="string"){const r=i===""?e:aLt(e,i);r.classGroupId=n;return}if(typeof i=="function"){if(qLo(i)){SDe(i(o),e,n,o);return}e.validators.push({validator:i,classGroupId:n});return}Object.entries(i).forEach(([r,s])=>{SDe(s,aLt(e,r),n,o)})})},aLt=(t,e)=>{let n=t;return e.split(bDe).forEach(o=>{n.nextPart.has(o)||n.nextPart.set(o,{nextPart:new Map,validators:[]}),n=n.nextPart.get(o)}),n},qLo=t=>t.isThemeGetter,XLo=(t,e)=>e?t.map(([n,o])=>{const i=o.map(r=>typeof r=="string"?e+r:typeof r=="object"?Object.fromEntries(Object.entries(r).map(([s,a])=>[e+s,a])):r);return[n,i]}):t,ZLo=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,n=new Map,o=new Map;const i=(r,s)=>{n.set(r,s),e++,e>t&&(e=0,o=n,n=new Map)};return{get(r){let s=n.get(r);if(s!==void 0)return s;if((s=o.get(r))!==void 0)return i(r,s),s},set(r,s){n.has(r)?n.set(r,s):i(r,s)}}},ALt="!",eHo=t=>{const{separator:e,experimentalParseClassName:n}=t,o=e.length===1,i=e[0],r=e.length,s=a=>{const A=[];let c=0,l=0,u;for(let m=0;m<a.length;m++){let _=a[m];if(c===0){if(_===i&&(o||a.slice(m,m+r)===e)){A.push(a.slice(l,m)),l=m+r;continue}if(_==="/"){u=m;continue}}_==="["?c++:_==="]"&&c--}const g=A.length===0?a:a.substring(l),h=g.startsWith(ALt),d=h?g.substring(1):g,p=u&&u>l?u-l:void 0;return{modifiers:A,hasImportantModifier:h,baseClassName:d,maybePostfixModifierPosition:p}};return n?a=>n({className:a,parseClassName:s}):s},tHo=t=>{if(t.length<=1)return t;const e=[];let n=[];return t.forEach(o=>{o[0]==="["?(e.push(...n.sort(),o),n=[]):n.push(o)}),e.push(...n.sort()),e},nHo=t=>({cache:ZLo(t.cacheSize),parseClassName:eHo(t),...WLo(t)}),oHo=/\s+/,iHo=(t,e)=>{const{parseClassName:n,getClassGroupId:o,getConflictingClassGroupIds:i}=e,r=[],s=t.trim().split(oHo);let a="";for(let A=s.length-1;A>=0;A-=1){const c=s[A],{modifiers:l,hasImportantModifier:u,baseClassName:g,maybePostfixModifierPosition:h}=n(c);let d=!!h,p=o(d?g.substring(0,h):g);if(!p){if(!d){a=c+(a.length>0?" "+a:a);continue}if(p=o(g),!p){a=c+(a.length>0?" "+a:a);continue}d=!1}const m=tHo(l).join(":"),_=u?m+ALt:m,f=_+p;if(r.includes(f))continue;r.push(f);const I=i(p,d);for(let C=0;C<I.length;++C){const y=I[C];r.push(_+y)}a=c+(a.length>0?" "+a:a)}return a};function rHo(){let t=0,e,n,o="";for(;t<arguments.length;)(e=arguments[t++])&&(n=cLt(e))&&(o&&(o+=" "),o+=n);return o}const cLt=t=>{if(typeof t=="string")return t;let e,n="";for(let o=0;o<t.length;o++)t[o]&&(e=cLt(t[o]))&&(n&&(n+=" "),n+=e);return n};function sHo(t,...e){let n,o,i,r=s;function s(A){const c=e.reduce((l,u)=>u(l),t());return n=nHo(c),o=n.cache.get,i=n.cache.set,r=a,a(A)}function a(A){const c=o(A);if(c)return c;const l=iHo(A,n);return i(A,l),l}return function(){return r(rHo.apply(null,arguments))}}const _d=t=>{const e=n=>n[t]||[];return e.isThemeGetter=!0,e},lLt=/^\[(?:([a-z-]+):)?(.+)\]$/i,aHo=/^\d+\/\d+$/,AHo=new Set(["px","full","screen"]),cHo=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,lHo=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,uHo=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,gHo=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,dHo=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Hb=t=>KO(t)||AHo.has(t)||aHo.test(t),ww=t=>VO(t,"length",yHo),KO=t=>!!t&&!Number.isNaN(Number(t)),QDe=t=>VO(t,"number",KO),v$=t=>!!t&&Number.isInteger(Number(t)),hHo=t=>t.endsWith("%")&&KO(t.slice(0,-1)),LA=t=>lLt.test(t),Pw=t=>cHo.test(t),pHo=new Set(["length","size","percentage"]),mHo=t=>VO(t,pHo,uLt),_Ho=t=>VO(t,"position",uLt),fHo=new Set(["image","url"]),IHo=t=>VO(t,fHo,EHo),CHo=t=>VO(t,"",xHo),w$=()=>!0,VO=(t,e,n)=>{const o=lLt.exec(t);return o?o[1]?typeof e=="string"?o[1]===e:e.has(o[1]):n(o[2]):!1},yHo=t=>lHo.test(t)&&!uHo.test(t),uLt=()=>!1,xHo=t=>gHo.test(t),EHo=t=>dHo.test(t),BHo=sHo(()=>{const t=_d("colors"),e=_d("spacing"),n=_d("blur"),o=_d("brightness"),i=_d("borderColor"),r=_d("borderRadius"),s=_d("borderSpacing"),a=_d("borderWidth"),A=_d("contrast"),c=_d("grayscale"),l=_d("hueRotate"),u=_d("invert"),g=_d("gap"),h=_d("gradientColorStops"),d=_d("gradientColorStopPositions"),p=_d("inset"),m=_d("margin"),_=_d("opacity"),f=_d("padding"),I=_d("saturate"),C=_d("scale"),y=_d("sepia"),x=_d("skew"),E=_d("space"),B=_d("translate"),S=()=>["auto","contain","none"],Q=()=>["auto","hidden","clip","visible","scroll"],w=()=>["auto",LA,e],M=()=>[LA,e],k=()=>["",Hb,ww],R=()=>["auto",KO,LA],F=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],O=()=>["solid","dashed","dotted","double","none"],U=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Y=()=>["start","end","center","between","around","evenly","stretch"],W=()=>["","0",LA],te=()=>["auto","avoid","all","avoid-page","page","left","right","column"],j=()=>[KO,LA];return{cacheSize:500,separator:":",theme:{colors:[w$],spacing:[Hb,ww],blur:["none","",Pw,LA],brightness:j(),borderColor:[t],borderRadius:["none","","full",Pw,LA],borderSpacing:M(),borderWidth:k(),contrast:j(),grayscale:W(),hueRotate:j(),invert:W(),gap:M(),gradientColorStops:[t],gradientColorStopPositions:[hHo,ww],inset:w(),margin:w(),opacity:j(),padding:M(),saturate:j(),scale:j(),sepia:W(),skew:j(),space:M(),translate:M()},classGroups:{aspect:[{aspect:["auto","square","video",LA]}],container:["container"],columns:[{columns:[Pw]}],"break-after":[{"break-after":te()}],"break-before":[{"break-before":te()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...F(),LA]}],overflow:[{overflow:Q()}],"overflow-x":[{"overflow-x":Q()}],"overflow-y":[{"overflow-y":Q()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[p]}],"inset-x":[{"inset-x":[p]}],"inset-y":[{"inset-y":[p]}],start:[{start:[p]}],end:[{end:[p]}],top:[{top:[p]}],right:[{right:[p]}],bottom:[{bottom:[p]}],left:[{left:[p]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",v$,LA]}],basis:[{basis:w()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",LA]}],grow:[{grow:W()}],shrink:[{shrink:W()}],order:[{order:["first","last","none",v$,LA]}],"grid-cols":[{"grid-cols":[w$]}],"col-start-end":[{col:["auto",{span:["full",v$,LA]},LA]}],"col-start":[{"col-start":R()}],"col-end":[{"col-end":R()}],"grid-rows":[{"grid-rows":[w$]}],"row-start-end":[{row:["auto",{span:[v$,LA]},LA]}],"row-start":[{"row-start":R()}],"row-end":[{"row-end":R()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",LA]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",LA]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...Y()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...Y(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...Y(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[f]}],px:[{px:[f]}],py:[{py:[f]}],ps:[{ps:[f]}],pe:[{pe:[f]}],pt:[{pt:[f]}],pr:[{pr:[f]}],pb:[{pb:[f]}],pl:[{pl:[f]}],m:[{m:[m]}],mx:[{mx:[m]}],my:[{my:[m]}],ms:[{ms:[m]}],me:[{me:[m]}],mt:[{mt:[m]}],mr:[{mr:[m]}],mb:[{mb:[m]}],ml:[{ml:[m]}],"space-x":[{"space-x":[E]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[E]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",LA,e]}],"min-w":[{"min-w":[LA,e,"min","max","fit"]}],"max-w":[{"max-w":[LA,e,"none","full","min","max","fit","prose",{screen:[Pw]},Pw]}],h:[{h:[LA,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[LA,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[LA,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[LA,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Pw,ww]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",QDe]}],"font-family":[{font:[w$]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",LA]}],"line-clamp":[{"line-clamp":["none",KO,QDe]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Hb,LA]}],"list-image":[{"list-image":["none",LA]}],"list-style-type":[{list:["none","disc","decimal",LA]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[_]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[_]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...O(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Hb,ww]}],"underline-offset":[{"underline-offset":["auto",Hb,LA]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:M()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",LA]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",LA]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[_]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...F(),_Ho]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",mHo]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},IHo]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[d]}],"gradient-via-pos":[{via:[d]}],"gradient-to-pos":[{to:[d]}],"gradient-from":[{from:[h]}],"gradient-via":[{via:[h]}],"gradient-to":[{to:[h]}],rounded:[{rounded:[r]}],"rounded-s":[{"rounded-s":[r]}],"rounded-e":[{"rounded-e":[r]}],"rounded-t":[{"rounded-t":[r]}],"rounded-r":[{"rounded-r":[r]}],"rounded-b":[{"rounded-b":[r]}],"rounded-l":[{"rounded-l":[r]}],"rounded-ss":[{"rounded-ss":[r]}],"rounded-se":[{"rounded-se":[r]}],"rounded-ee":[{"rounded-ee":[r]}],"rounded-es":[{"rounded-es":[r]}],"rounded-tl":[{"rounded-tl":[r]}],"rounded-tr":[{"rounded-tr":[r]}],"rounded-br":[{"rounded-br":[r]}],"rounded-bl":[{"rounded-bl":[r]}],"border-w":[{border:[a]}],"border-w-x":[{"border-x":[a]}],"border-w-y":[{"border-y":[a]}],"border-w-s":[{"border-s":[a]}],"border-w-e":[{"border-e":[a]}],"border-w-t":[{"border-t":[a]}],"border-w-r":[{"border-r":[a]}],"border-w-b":[{"border-b":[a]}],"border-w-l":[{"border-l":[a]}],"border-opacity":[{"border-opacity":[_]}],"border-style":[{border:[...O(),"hidden"]}],"divide-x":[{"divide-x":[a]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[a]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[_]}],"divide-style":[{divide:O()}],"border-color":[{border:[i]}],"border-color-x":[{"border-x":[i]}],"border-color-y":[{"border-y":[i]}],"border-color-s":[{"border-s":[i]}],"border-color-e":[{"border-e":[i]}],"border-color-t":[{"border-t":[i]}],"border-color-r":[{"border-r":[i]}],"border-color-b":[{"border-b":[i]}],"border-color-l":[{"border-l":[i]}],"divide-color":[{divide:[i]}],"outline-style":[{outline:["",...O()]}],"outline-offset":[{"outline-offset":[Hb,LA]}],"outline-w":[{outline:[Hb,ww]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:k()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[_]}],"ring-offset-w":[{"ring-offset":[Hb,ww]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Pw,CHo]}],"shadow-color":[{shadow:[w$]}],opacity:[{opacity:[_]}],"mix-blend":[{"mix-blend":[...U(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":U()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[o]}],contrast:[{contrast:[A]}],"drop-shadow":[{"drop-shadow":["","none",Pw,LA]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[l]}],invert:[{invert:[u]}],saturate:[{saturate:[I]}],sepia:[{sepia:[y]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[o]}],"backdrop-contrast":[{"backdrop-contrast":[A]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[l]}],"backdrop-invert":[{"backdrop-invert":[u]}],"backdrop-opacity":[{"backdrop-opacity":[_]}],"backdrop-saturate":[{"backdrop-saturate":[I]}],"backdrop-sepia":[{"backdrop-sepia":[y]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[s]}],"border-spacing-x":[{"border-spacing-x":[s]}],"border-spacing-y":[{"border-spacing-y":[s]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",LA]}],duration:[{duration:j()}],ease:[{ease:["linear","in","out","in-out",LA]}],delay:[{delay:j()}],animate:[{animate:["none","spin","ping","pulse","bounce",LA]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[C]}],"scale-x":[{"scale-x":[C]}],"scale-y":[{"scale-y":[C]}],rotate:[{rotate:[v$,LA]}],"translate-x":[{"translate-x":[B]}],"translate-y":[{"translate-y":[B]}],"skew-x":[{"skew-x":[x]}],"skew-y":[{"skew-y":[x]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",LA]}],accent:[{accent:["auto",t]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",LA]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":M()}],"scroll-mx":[{"scroll-mx":M()}],"scroll-my":[{"scroll-my":M()}],"scroll-ms":[{"scroll-ms":M()}],"scroll-me":[{"scroll-me":M()}],"scroll-mt":[{"scroll-mt":M()}],"scroll-mr":[{"scroll-mr":M()}],"scroll-mb":[{"scroll-mb":M()}],"scroll-ml":[{"scroll-ml":M()}],"scroll-p":[{"scroll-p":M()}],"scroll-px":[{"scroll-px":M()}],"scroll-py":[{"scroll-py":M()}],"scroll-ps":[{"scroll-ps":M()}],"scroll-pe":[{"scroll-pe":M()}],"scroll-pt":[{"scroll-pt":M()}],"scroll-pr":[{"scroll-pr":M()}],"scroll-pb":[{"scroll-pb":M()}],"scroll-pl":[{"scroll-pl":M()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",LA]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Hb,ww,QDe]}],stroke:[{stroke:[t,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}),Fn="u">typeof window?window:void 0,vC="u">typeof globalThis?globalThis:Fn,tf=vC?.navigator,No=vC?.document,fd=vC?.location,P$=vC?.fetch,vDe=vC?.XMLHttpRequest&&"withCredentials"in new vC.XMLHttpRequest?vC.XMLHttpRequest:void 0,gLt=vC?.AbortController,bHo=vC?.CompressionStream,jy=tf?.userAgent;function dLt(){return!(!Fn||Fn.navigator.onLine===!1)}const M$=typeof globalThis<"u"?globalThis:Fn;M$&&typeof self>"u"&&(M$.self=M$),M$&&typeof File>"u"&&(M$.File=function(){});const Vr=Fn??{},SHo="0.9.1",Ob={DEBUG:!1,LIB_VERSION:SHo,LIB_NAME:"browser-common"};var l6=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.AiCaptureQueue="ai_capture_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysInProgress="surveys_in_progress",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),wDe=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({});const QHo=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],vHo=["token"];function as(t,e){return t.indexOf(e)!==-1}const rge=function(t){return t.trim()},PDe=function(t){return t.replace(/^\$/,"")};function hLt(t){var e;const n=[];return(e=JSON.stringify(t,function(o,i){if(typeof i=="bigint")return i.toString();if(typeof i!="function"&&typeof i!="symbol"){if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(i&&typeof i=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(i))return"[Circular]";n.push(i)}return i}}))!==null&&e!==void 0?e:"null"}const pLt=Object.prototype,MDe=pLt.hasOwnProperty,sge=pLt.toString,As=Array.isArray||function(t){return sge.call(t)==="[object Array]"},nf=t=>typeof t=="function",QA=t=>t===Object(t)&&!As(t),Rx=t=>{if(QA(t)){for(const e in t)if(MDe.call(t,e))return!1;return!0}return!1},Eo=t=>t===void 0,rA=t=>sge.call(t)=="[object String]",D$=t=>rA(t)&&t.trim().length===0,Id=t=>t===null,Hs=t=>Eo(t)||Id(t),Ah=t=>sge.call(t)=="[object Number]"&&t==t,Gb=t=>Ah(t)&&t>0,$y=t=>sge.call(t)==="[object Boolean]",wHo=t=>as(QHo,t),PHo=t=>as(vHo,t);function mLt(t){return t===null||typeof t!="object"}function age(t,e){return{}.toString.call(t)===`[object ${e}]`}function zO(t){switch({}.toString.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return _Lt(t,Error)}}function DDe(t){return"u">typeof Event&&_Lt(t,Event)}function _Lt(t,e){try{return t instanceof e}catch{return!1}}const MHo=[!0,"true",1,"1","yes"],NDe=t=>as(MHo,t),DHo=[!1,"false",0,"0","no"];function fLt(t,e,n,o,i,r,s){try{var a=t[r](s),A=a.value}catch(c){return void n(c)}a.done?e(A):Promise.resolve(A).then(o,i)}function Zu(t){return function(){var e=this,n=arguments;return new Promise(function(o,i){var r=t.apply(e,n);function s(A){fLt(r,o,i,s,a,"next",A)}function a(A){fLt(r,o,i,s,a,"throw",A)}s(void 0)})}}const NHo=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],ILt=function(t,e=[]){if(!t)return!1;const n=t.toLowerCase();return NHo.concat(e).some(o=>{const i=o.toLowerCase();return n.indexOf(i)!==-1})};function u6(t,e,n,o,i){return e>n&&(o.warn("min cannot be greater than max."),e=n),Ah(t)?t>n?(o.warn(" cannot be  greater than max: "+n+". Using max value instead."),n):e>t?(o.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(o.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+i),u6(i??n,e,n,o))}var RHo=class{constructor(e){this.C={},this.I=e.I,this.R=u6(e.bucketSize,0,100,e.A),this.$=u6(e.refillRate,0,this.R,e.A),this.O=u6(e.refillInterval,0,864e5,e.A)}F(e,n){const o=Math.floor((n-e.lastAccess)/this.O);o>0&&(e.tokens=Math.min(e.tokens+o*this.$,this.R),e.lastAccess=e.lastAccess+o*this.O)}consumeRateLimit(e){var n;const o=Date.now(),i=String(e);let r=this.C[i];return r?this.F(r,o):(r={tokens:this.R,lastAccess:o},this.C[i]=r),r.tokens===0||(r.tokens--,r.tokens===0&&((n=this.I)===null||n===void 0||n.call(this,e)),r.tokens===0)}stop(){this.C={}}};const JO="Mobile",N$="Android",Age="Tablet",CLt="Android Tablet",yLt="iPad",xLt="Apple Watch",cge="Safari",lge="BlackBerry",ELt="Samsung Internet",uge="Chrome",BLt="Chrome iOS",bLt="Internet Explorer",SLt="Internet Explorer Mobile",QLt="Opera",vLt="Microsoft Edge",gge="Firefox",wLt="Firefox iOS",dge="Nintendo",hge="PlayStation",pge="Xbox",PLt="Android Mobile",MLt="Mobile Safari",RDe="Windows",DLt="Windows Phone",NLt="Nokia",TDe="Ouya",THo="Generic "+JO.toLowerCase(),RLt="Generic "+Age.toLowerCase(),kDe="Konqueror",TLt="Oculus Browser",kLt="Vivaldi",FLt="Yandex",LLt="Whale",HLt="DuckDuckGo",OLt="Pale Moon",GLt="Waterfox",FDe="Brave",YLt="Claude",ULt="Codex",KLt="ChatGPT",VLt="Google Search App",LDe=new RegExp("Version/(\\d+(\\.\\d+)?)"),HDe=new RegExp("(Claude|Codex|ChatGPT)\\/(\\d+(\\.\\d+)?)"),kHo=new RegExp(pge,"i"),FHo=new RegExp("PlayStation \\w+","i"),LHo=new RegExp("Nintendo \\w+","i"),ODe=new RegExp("BlackBerry|PlayBook|BB10","i"),HHo={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},zLt=function(t,e,n,o){return e=e||"",(function(r){return r?.brave?FDe:null})(n)||(o?.detectGoogleSearchApp&&as(t,"GSA/")?VLt:as(t," OPR/")&&as(t,"Mini")?"Opera Mini":as(t," OPR/")?QLt:ODe.test(t)?lge:as(t,"IEMobile")||as(t,"WPDesktop")?SLt:as(t,"OculusBrowser")?TLt:as(t,"SamsungBrowser")?ELt:as(t,"Edge")||as(t,"Edg/")?vLt:as(t,"Vivaldi/")?kLt:as(t,"YaBrowser/")?FLt:as(t,"Whale/")?LLt:as(t,"DuckDuckGo/")||as(t,"Ddg/")?HLt:as(t,"Claude/")?YLt:as(t,"Codex/")?ULt:as(t,"ChatGPT/")?KLt:as(t,"FBIOS")?"Facebook Mobile":as(t,"UCWEB")||as(t,"UCBrowser")?"UC Browser":as(t,"CriOS")?BLt:as(t,"CrMo")||as(t,uge)?uge:as(t,N$)&&as(t,cge)?PLt:as(t,"FxiOS")?wLt:as(t.toLowerCase(),kDe.toLowerCase())?kDe:as(t,"Brave/")?FDe:((r,s)=>s&&as(s,"Apple")||(function(a){return as(a,cge)&&!as(a,uge)&&!as(a,N$)})(r))(t,e)?as(t,JO)?MLt:cge:as(t,"PaleMoon/")?OLt:as(t,"Waterfox/")?GLt:as(t,gge)?gge:as(t,"MSIE")||as(t,"Trident/")?bLt:as(t,"Gecko")?gge:"")},OHo={[SLt]:[new RegExp("rv:(\\d+(\\.\\d+)?)")],[vLt]:[new RegExp("Edge?\\/(\\d+(\\.\\d+)?)")],[uge]:[new RegExp("(Chrome|CrMo)\\/(\\d+(\\.\\d+)?)")],[BLt]:[new RegExp("CriOS\\/(\\d+(\\.\\d+)?)")],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/(\\d+(\\.\\d+)?)")],[cge]:[LDe],[MLt]:[LDe],[QLt]:[new RegExp("(Opera|OPR)\\/(\\d+(\\.\\d+)?)")],[gge]:[new RegExp("Firefox\\/(\\d+(\\.\\d+)?)")],[wLt]:[new RegExp("FxiOS\\/(\\d+(\\.\\d+)?)")],[kDe]:[new RegExp("Konqueror[:/]?(\\d+(\\.\\d+)?)","i")],[lge]:[new RegExp("BlackBerry (\\d+(\\.\\d+)?)"),LDe],[PLt]:[new RegExp("android\\s(\\d+(\\.\\d+)?)","i")],[ELt]:[new RegExp("SamsungBrowser\\/(\\d+(\\.\\d+)?)")],[TLt]:[new RegExp("OculusBrowser\\/(\\d+(\\.\\d+)?)")],[kLt]:[new RegExp("Vivaldi\\/(\\d+(\\.\\d+)?)")],[FLt]:[new RegExp("YaBrowser\\/(\\d+(\\.\\d+)?)")],[LLt]:[new RegExp("Whale\\/(\\d+(\\.\\d+)?)")],[FDe]:[new RegExp("Brave\\/(\\d+(\\.\\d+)?)")],[YLt]:[HDe],[ULt]:[HDe],[KLt]:[HDe],[HLt]:[new RegExp("(DuckDuckGo|Ddg)\\/(\\d+(\\.\\d+)?)")],[OLt]:[new RegExp("PaleMoon\\/(\\d+(\\.\\d+)?)")],[GLt]:[new RegExp("Waterfox\\/(\\d+(\\.\\d+)?)")],[VLt]:[new RegExp("GSA\\/(\\d+(\\.\\d+)?)")],[bLt]:[new RegExp("(rv:|MSIE )(\\d+(\\.\\d+)?)")],Mozilla:[new RegExp("rv:(\\d+(\\.\\d+)?)")]},GHo=function(t,e,n,o){const i=zLt(t,e,n,o),r=OHo[i];if(Eo(r))return null;for(let s=0;r.length>s;s++){const a=t.match(r[s]);if(a)return parseFloat(a[a.length-2])}return null},JLt=[[new RegExp("Xbox; Xbox (.*?)[);]","i"),t=>[pge,t&&t[1]||""]],[new RegExp(dge,"i"),[dge,""]],[new RegExp(hge,"i"),[hge,""]],[ODe,[lge,""]],[new RegExp(RDe,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[DLt,""];if(new RegExp(JO).test(e)&&!/IEMobile\b/.test(e))return["Windows Mobile",""];const n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){let o=HHo[n[1]]||"";return/arm/i.test(e)&&(o="RT"),[RDe,o]}return[RDe,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?["iOS",[t[3],t[4],t[5]||"0"].join(".")]:["iOS",""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=Eo(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("(Android (\\d+)\\.(\\d+)\\.?(\\d+)?|Android)","i"),t=>t&&t[2]?[N$,[t[2],t[3],t[4]||"0"].join(".")]:[N$,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{const e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,["Chrome OS",""]],[/Linux|debian/i,["Linux",""]]],WLt=function(t){for(let e=0;JLt.length>e;e++){const[n,o]=JLt[e],i=n.exec(t),r=i&&(nf(o)?o(i,t):o);if(r)return r}return["",""]},jLt=function(t){return LHo.test(t)?dge:FHo.test(t)?hge:kHo.test(t)?pge:new RegExp(TDe,"i").test(t)?TDe:new RegExp("(Windows Phone|WPDesktop)","i").test(t)?DLt:/iPad/.test(t)?yLt:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?xLt:ODe.test(t)?lge:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(NLt,"i").test(t)?NLt:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(JO).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?N$:CLt:new RegExp("(pda|Mobile)","i").test(t)?THo:new RegExp(Age,"i").test(t)&&!new RegExp("Tablet pc","i").test(t)?RLt:""},YHo=function(t,e){var n;const o=jLt(t);return o===yLt||o===CLt||o==="Kobo"||o==="Kindle Fire"||o===RLt?Age:o===dge||o===pge||o===hge||o===TDe?"Console":o===xLt?"Wearable":o?JO:e?.userAgentDataPlatform==="Android"&&((n=e?.maxTouchPoints)!==null&&n!==void 0?n:0)>0?600>Math.min((i=e?.screenWidth)!==null&&i!==void 0?i:0,(r=e?.screenHeight)!==null&&r!==void 0?r:0)/((s=e?.devicePixelRatio)!==null&&s!==void 0?s:1)?JO:Age:"Desktop";var i,r,s},GDe=/\bFBAV\/(\d+(?:\.\d+)*)/i,$Lt=[[/\bInstagram(?:[ /](\d+(?:\.\d+)*))?\b/i,"Instagram"],[/\bBarcelona[ /](\d+(?:\.\d+)*)?/i,"Threads"],[/\b(?:MessengerForiOS|(?:FBAN|FB_IAB)\/Orca-Android)\b/i,"Messenger",GDe],[/\bFBAN\/EMA\b/i,"Facebook Lite",GDe],[/\b(?:FBIOS|(?:FBAN|FB_IAB)\/(?:FB4A|FBIOS))\b/i,"Facebook",GDe],[/\bLinkedInApp(?:\]?\/(\d+(?:\.\d+)*))?\b/i,"LinkedIn"],[/\bTwitter(?:Android| for (?:iPhone|iPad|Android))(?:\/(\d+(?:\.\d+)*))?\b/i,"Twitter"],[/\b(?:musical_ly|trill)(?:[_/](\d+\.\d+(?:\.\d+)*))?(?=\b|_)/i,"TikTok",/\bapp_version\/(\d+(?:\.\d+)*)/i],[/\b(?:MicroMessenger|WeChat)\/(\d+(?:\.\d+)*)?/i,"WeChat"],[/\bLine\/(\d+(?:\.\d+)*)?/i,"Line"],[/\bGSA\/(\d+(?:\.\d+)*)?/i,"Google"],[/\[Pinterest\/(?:iOS|Android)\b|\bPinterest(?: for (?:Android(?: Tablet)?|iOS))?\/(\d+(?:\.\d+)*)/i,"Pinterest"],[/\b(?:WA4A|WAiOS)\/(\d+(?:\.\d+)*)?/i,"WhatsApp"],[/\bSnapchat[ /](\d+(?:\.\d+)*)?/i,"Snapchat"],[/\bBing(?:Web|Sapphire)\/(\d+(?:\.\d+)*)?/i,"Bing"],[/\bNAVER\(inapp; search;/i,"Naver",/\bNAVER\(inapp; search;[^;)]*; (\d+(?:\.\d+)*)/i],[/\bKAKAOTALK[ /](\d+\.\d+(?:\.\d+)*)?/i,"KakaoTalk"]],YDe="[Truncated]",R$="[Unserializable]";function WO(t){let e="";for(let n=0;t.length>n;n++){const o=t.charCodeAt(n);if(55296>o||o>56319)e+=56320>o||o>57343?t[n]:"�";else{const i=t.charCodeAt(n+1);56320>i||i>57343?e+="�":(e+=t[n]+t[n+1],n++)}}return e}function qLt(t,e){if(!e)return t;let n=[];try{n=Object.keys(e)}catch{n=[]}for(const o of n){let i;try{i=e[o]}catch{i=R$}Object.defineProperty(t,o,{value:i,enumerable:!0,writable:!0,configurable:!0})}return t}const mge=3e5;var XLt=class{record(e){if(e.kind==="too-large")return;if(e.kind!=="retry-later")return void this.reset();if(!e.retryAfterMs)return;const n=this.isOpen(),o=Date.now(),i=Math.min(e.retryAfterMs,mge);if(!n)return this.ts=o,void(this.es=o+i);this.es=Math.max(this.es,Math.min(o+i,this.ts+mge))}remainingMs(){const e=Date.now();if(this.ts-5e3>e)return this.reset(),0;const n=Math.min(mge,Math.max(0,this.es-e));return n===0&&this.reset(),n}isOpen(){return this.remainingMs()>0}reset(){this.es=0,this.ts=0}constructor(){this.es=0,this.ts=0}};const UHo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ZLt(t,e){return typeof(n=t)=="string"&&UHo.test(n)?t:e();var n}function eHt(t,e){const n=new Error(e);try{Object.defineProperty(n,"name",{value:t,writable:!0,enumerable:!0,configurable:!0})}catch{}return n}function Mw(t){return t&&t.split("#")[0]}function tHt(t){try{return t()}catch{return}}function nHt(t,e){const n=setTimeout(t,e);return n!=null&&n.unref&&n?.unref(),n}function oHt(t,e,n){return iHt.apply(this,arguments)}function iHt(){return(iHt=Zu(function*(t,e,n){let o;try{return yield Promise.race([t,new Promise((i,r)=>{o=nHt(()=>{try{n?.(),i()}catch(s){r(s)}},e)})])}finally{clearTimeout(o)}})).apply(this,arguments)}let _ge,rHt,UDe;function KHo(t){const e=globalThis._posthogChunkIds;if(!e)return;const n=Object.keys(e);return UDe&&n.length===rHt||(rHt=n.length,UDe=n.reduce((o,i)=>{_ge||(_ge={});const r=_ge[i];if(r)o[r[0]]=r[1];else{const s=t(i);for(let a=s.length-1;a>=0;a--){const A=s[a],c=A?.filename,l=e[i];if(c&&l){o[c]=l,_ge[i]=[c,l];break}}}return o},{})),UDe}function T$(t){return T$=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},T$(t)}function VHo(t,e,n){return(e=(function(o){var i=(function(r){if(T$(r)!="object"||!r)return r;var s=r[Symbol.toPrimitive];if(s!==void 0){var a=s.call(r,"string");if(T$(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(r)})(o);return T$(i)=="symbol"?i:i+""})(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function sHt(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,o)}return n}function sn(t){for(var e=1;arguments.length>e;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?sHt(Object(n),!0).forEach(function(o){VHo(t,o,n[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):sHt(Object(n)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(n,o))})}return t}var zHo=class{constructor(e,n,o=[]){this.coercers=e,this.stackParser=n,this.modifiers=o}buildFromUnknown(e,n={}){const o=n&&n.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(o,n,0).apply(e),r=this.buildParsingContext(n),s=this.parseStacktrace(i,r);return{$exception_list:this.convertToExceptionList(s,o),$exception_level:"error"}}modifyFrames(e){var n=this;return Zu(function*(){for(const o of e)o.stacktrace&&o.stacktrace.frames&&As(o.stacktrace.frames)&&(o.stacktrace.frames=yield n.applyModifiers(o.stacktrace.frames));return e})()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)===null||n===void 0?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var o;let i,r;if(e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null)try{r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)}catch{}return sn(sn({},e),{},{cause:i,stack:r,errors:(o=e.errors)===null||o===void 0?void 0:o.map(s=>this.parseStacktrace(s,n))})}applyChunkIds(e,n){return e.map(o=>(o.filename&&n&&(o.chunk_id=n[o.filename]),o))}applyCoercers(e,n){for(const o of this.coercers)if(o.match(e))return o.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return Zu(function*(){let o=e;for(const i of n.modifiers)o=yield i(o);return o})()}convertToExceptionList(e,n){const o=[],i=(r,s,a)=>{var A;const c=o.length,l=s===void 0?sn(sn({type:typeof n.type=="string"&&n.type.length>0?n.type:"generic"},typeof n.handled=="boolean"?{handled:n.handled}:n.handled===void 0?{handled:!0}:{}),{},{synthetic:typeof n.synthetic=="boolean"?n.synthetic:r.synthetic,exception_id:c}):{type:"chained",source:a,synthetic:r.synthetic,exception_id:c,parent_id:s},u={type:r.type,value:r.value,mechanism:l};r.stack&&(u.stacktrace={type:"raw",frames:r.stack}),o.push(u),r.cause&&i(r.cause,c,"cause");for(const g of(A=r.errors)!==null&&A!==void 0?A:[])i(g,c,"member")};return i(e),o}buildParsingContext(e){var n;return{chunkIdMap:KHo(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}getAggregateErrors(e){try{if(zO(e)){let o=Object.getPrototypeOf(e);for(let i=0;o&&100>i;i++){var n;const r=(n=Object.getOwnPropertyDescriptor(o,"constructor"))===null||n===void 0?void 0:n.value;if(typeof r=="function"&&r.name==="AggregateError"){const s=e.errors;return As(s)?s:void 0}o=Object.getPrototypeOf(o)}}}catch{}}buildCoercingContext(e,n,o=0){let i=0,r=0,s=!1;const a=new Set,A=[],c={},l=(h,d,p=0)=>{const m=u(d,p),_=m.apply;if(m.apply=E=>{A.push(h);try{return _(E)}finally{A.pop()}},p>4||p>0&&A.indexOf(h)!==-1)return this.coerceFallback(m);const f=typeof h=="object"&&h!==null||typeof h=="function";if(p===0&&i>=50||f&&a.has(h))return;f&&a.add(h),p===0&&i++;const I=this.getAggregateErrors(h);let C,y;s||(s=!!I);try{if(C=this.applyCoercers(h,m),!C)throw c}catch(E){if(E===c)return void(p===0&&i--);if(!s)throw E;C=this.coerceFallback(m)}if(!I||i>=50)return C;try{y=I.length}catch{return C}if(!Number.isInteger(y)||0>y||y>4294967295)return C;const x=[];for(let E=0;50>i&&1e3>r&&y>E;E++){let B;r++;try{B=m.next(I[E])}catch{i++,B=this.coerceFallback(u(d+1))}B&&x.push(B)}return sn(sn({},C),{},{errors:x})},u=(h,d=0)=>sn(sn({},n),{},{syntheticException:h==0?n.syntheticException:void 0,mechanism:h==0?e:{},apply(p){const m=l(p,h,d+1);if(!m)throw c;return m},next:p=>l(p,h+1)}),g=u(o);return sn(sn({},g),{},{apply:h=>{var d;return(d=l(h,o))!==null&&d!==void 0?d:this.coerceFallback(g)}})}};const JHo=/^([a-z][a-z0-9.+-]+):/i,WHo=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function jHo(t){if(!t||t==="<anonymous>")return!1;const e=JHo.exec(t);return!e||WHo.includes(e[1].toLowerCase())}function KDe(t,e,n,o,i){const r={platform:t,filename:e,function:n==="<anonymous>"?"?":n,in_app:jHo(e)};return Eo(o)||(r.lineno=o),Eo(i)||(r.colno=i),r}const aHt=(t,e)=>{const n=t.indexOf("safari-extension")!==-1,o=t.indexOf("safari-web-extension")!==-1;return n||o?[t.indexOf("@")!==-1?t.split("@")[0]:"?",n?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]},$Ho=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,qHo=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,XHo=/\((\S*)(?::(\d+))(?::(\d+))\)/,ZHo=(t,e)=>{const n=$Ho.exec(t);if(n){const[,i,r,s]=n;return KDe(e,i,"?",+r,+s)}const o=qHo.exec(t);if(o){if(o[2]&&o[2].indexOf("eval")===0){const s=XHo.exec(o[2]);s&&(o[2]=s[1],o[3]=s[2],o[4]=s[3])}const[i,r]=aHt(o[1]||"?",o[2]);return KDe(e,r,i,o[3]?+o[3]:void 0,o[4]?+o[4]:void 0)}},eOo=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,tOo=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,nOo=(t,e)=>{const n=eOo.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){const r=tOo.exec(n[3]);r&&(n[1]=n[1]||"eval",n[3]=r[1],n[4]=r[2],n[5]="")}let o=n[3],i=n[1]||"?";return[i,o]=aHt(i,o),KDe(e,o,i,n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},AHt=/\(error: (.*)\)/;function VDe(t,e){return t.filename===e.filename&&t.function===e.function&&t.module===e.module&&t.lineno===e.lineno&&t.colno===e.colno}function oOo(t){for(let e=1;10>=e;e++){const n=t.length-2*e;if(0>n)break;let o=!0;for(let i=0;e>i;i++)if(!VDe(t[n+i],t[n+e+i])){o=!1;break}if(o){for(let i=0;e>i;i++)t[n+i]=t[n+e+i];return t.length=n+e,{start:n,length:e}}}}function iOo(t,e){const n=e.start+e.length,o=lHt(t,e);o&&t.splice(n+o===t.length?n:e.start,o)}function cHt(t,e){let n=e.start;for(;n>0&&VDe(t[n-1],t[n-1+e.length]);)n--;return e.start-n}function lHt(t,e){const n=e.start+e.length;let o=n;for(;t.length>o&&VDe(t[o],t[o-e.length]);)o++;return o-n}function rOo(t,e){const n=e[0];let o=t.length-(n?cHt(t,n):0);for(const i of e)o-=lHt(t,i);return o}function sOo(t,e,n){for(let o=0;t.length>o;o++){const i=t[(e+o)%t.length],r=t[(n+o)%t.length];if(i!==r)return r>i}return!1}var aOo=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){const o=rA(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:o?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){const n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${n}: ${e.message}`:n}isDOMException(e){return age(e,"DOMException")}isDOMError(e){return age(e,"DOMError")}},AOo=class{match(e){return zO(e)}coerce(e,n){var o;const i=this.getStack(e),r=i===void 0?(o=n.syntheticException)===null||o===void 0?void 0:o.stack:void 0,s=!!r;return{type:this.getType(e),value:this.getMessage(e,n),stack:i??r,cause:e.cause?n.next(e.cause):void 0,synthetic:s}}getType(e){return e.name||e.constructor.name}getMessage(e,n){const o=e.message;return String(o.error&&typeof o.error.message=="string"?o.error.message:o)}getStack(e){try{const n=e.stacktrace;if(typeof n=="string"&&n.length>0)return n;const o=e.stack;return typeof o=="string"&&o.length>0?o:void 0}catch{return}}},cOo=class{match(e){return!!age(e,"ErrorEvent")&&(e.error!=null||this.ar(e))}coerce(e,n){var o;if(e.error!=null)return n.apply(e.error);const i=n.apply(e.message);return sn(sn({},i),{},{stack:(o=this.lr(e))!==null&&o!==void 0?o:i.stack,synthetic:!0})}ar(e){return rA(e.message)&&e.message.length>0}lr(e){var n,o;const i=e,r=(n=i.lineno)!==null&&n!==void 0?n:0,s=(o=i.colno)!==null&&o!==void 0?o:0;if(rA(i.filename)&&i.filename.length!==0&&r!==0)return`Error
    at ${i.filename}:${r}:${s}`}};const lOo=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;var uOo=class{match(e){return typeof e=="string"}coerce(e,n){var o;const[i,r]=this.getInfos(e);return{type:i??"Error",value:r??e,stack:(o=n.syntheticException)===null||o===void 0?void 0:o.stack,synthetic:!0}}getInfos(e){let n="Error",o=e;const i=e.match(lOo);return i&&(n=i[1],o=i[2]),[n,o]}};const gOo=["fatal","error","warning","log","info","debug"];function uHt(t,e=40){const n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(let o=n.length;o>0;o--){const i=n.slice(0,o).join(", ");if(e>=i.length)return o===n.length?i:i.length>e?`${i.slice(0,e)}...`:i}return""}var dOo=class{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var o,i;const r=this.getErrorPropertyFromObject(e);return r?n.apply(r):{type:this.getType(e),value:this.getValue(e),stack:(o=this.getStack(e))!==null&&o!==void 0?o:(i=n.syntheticException)===null||i===void 0?void 0:i.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(DDe(e))return e.constructor.name;const n="name"in e?e.name:void 0;return rA(n)&&!D$(n)?n:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let o=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(o+=` with message: '${e.message}'`),o}if("message"in e&&typeof e.message=="string")return e.message;const n=this.getObjectClassName(e);return`${n&&n!=="Object"?`'${n}'`:"Object"} captured as exception with keys: ${uHt(e)}`}isSeverityLevel(e){return rA(e)&&!D$(e)&&gOo.indexOf(e)>=0}getStack(e){try{return rA(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:rA(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(const n in e)if({}.hasOwnProperty.call(e,n)){const o=e[n];if(zO(o))return o}}getObjectClassName(e){try{const n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}},hOo=class{match(e){return DDe(e)}coerce(e,n){var o;const i=e.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${uHt(e)}`,stack:(o=n.syntheticException)===null||o===void 0?void 0:o.stack,synthetic:!0}}},pOo=class{match(e){return mLt(e)}coerce(e,n){var o;return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:(o=n.syntheticException)===null||o===void 0?void 0:o.stack,synthetic:!0}}},mOo=class{match(e){return age(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!DDe(e))return!1;try{const n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var o;const i=this.getUnhandledRejectionReason(e);return mLt(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:(o=n.syntheticException)===null||o===void 0?void 0:o.stack,synthetic:!0}:n.apply(i)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}};const fge="$message",Ige="$timestamp",_Oo=new Set([fge,Ige]),zDe={enabled:!0,max_bytes:32768};function Cge(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:zDe.enabled,max_bytes:IOo(t.max_bytes,zDe.max_bytes)}:sn({},zDe)}var fOo=class{constructor(e){this.ns=[],this.ss=0,this.Mr=Cge(e)}setConfig(e){this.Mr=Cge(e),this.rs()}add(e){const n=(function(i){let r;try{r=hLt(i)}catch{return}try{const s=JSON.parse(r);if(!QA(s))return;const a=s,A=a[fge],c=a[Ige];return!rA(A)||A.trim().length===0||!rA(c)&&!Ah(c)?void 0:{step:a,json:r}}catch{return}})(e);if(!n)return;const o=(function(i){if("u">typeof TextEncoder)return new TextEncoder().encode(i).length;const r=encodeURIComponent(i);let s=0;for(let a=0;r.length>a;a++)r[a]==="%"?(s+=1,a+=2):s+=1;return s})(n.json);o>this.Mr.max_bytes||(this.ns.push({step:n.step,bytes:o}),this.ss+=o,this.rs())}getAttachable(){return this.ns.map(e=>e.step)}clear(){this.ns=[],this.ss=0}size(){return this.ns.length}rs(){for(;this.ss>this.Mr.max_bytes&&this.ns.length>0;){const e=this.ns.shift();e&&(this.ss-=e.bytes)}}};function IOo(t,e){if(!Ah(t)||t===1/0||t===-1/0)return e;const n=Math.floor(t);return 0>n?e:n}const gHt=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function dHt(t){return typeof t=="string"||t}function hHt(t){return typeof t=="string"?t:void 0}const COo=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],pHt="NativeGzipValidationError",JDe=t=>t.length>=2&&t[0]===31&&t[1]===139,mHt=(t,e)=>t===wDe.GZipJS||e===wDe.GZipJS||e==="gzip",_Ht=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError";let k$;const yge=t=>{throw eHt(pHt,`Native gzip produced invalid output: ${t}`)},yOo=(fHt=Zu(function*(t,e){18>t.size&&yge("too-short");const n=new Uint8Array(yield t.slice(0,10).arrayBuffer());JDe(n)&&n[2]===8||yge("invalid-header");const o=new DataView(yield t.slice(t.size-8).arrayBuffer());o.getUint32(0,!0)!==(r=>{const s=(()=>{if(k$)return k$;k$=[];for(let A=0;256>A;A++){let c=A;for(let l=0;8>l;l++)c=1&c?3988292384^c>>>1:c>>>1;k$[A]=c>>>0}return k$})();let a=4294967295;for(let A=0;r.length>A;A++)a=s[255&(a^r[A])]^a>>>8;return(4294967295^a)>>>0})(e)&&yge("invalid-crc");const i=e.length>>>0;o.getUint32(4,!0)!==i&&yge("invalid-size")}),function(t,e){return fHt.apply(this,arguments)});var fHt;function WDe(){return WDe=Zu(function*(t,e=!0,n){try{const i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),a=s.write(i).then(()=>s.close()).catch((o=Zu(function*(l){try{yield s.abort(l)}catch{}throw l}),function(l){return o.apply(this,arguments)})),A=new Response(r.readable).blob(),[c]=yield Promise.all([A,a]);return yield yOo(c,i),c}catch(i){if(n?.rethrow)throw i;return e&&console.error("Failed to gzip compress data",i),null}var o}),WDe.apply(this,arguments)}function IHt(t,e){if(t==null)return{};var n,o,i=(function(s,a){if(s==null)return{};var A={};for(var c in s)if({}.hasOwnProperty.call(s,c)){if(a.includes(c))continue;A[c]=s[c]}return A})(t,e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);for(o=0;r.length>o;o++)e.includes(n=r[o])||{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}const xOo={}.propertyIsEnumerable;function xge(t,e){try{return CHt(t,e,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function jDe(t,e,n,o){if(0>=n.remainingNodes)return{stringValue:YDe};if(n.remainingNodes--,$y(t))return{boolValue:t};if(typeof t=="bigint")return(function(i,r){const s=i.toString(),a=BigInt("9223372036854775808");return i>=a||-a>i?(r?.debug(`Attribute ${s} is outside the int64 range; encoding it as a string`),{stringValue:s}):{intValue:s}})(t,e);if(typeof t=="number"){if(!Number.isFinite(t))return{stringValue:String(t)};if(Number.isInteger(t)){if(Number.isSafeInteger(t))return{intValue:String(t)};if(typeof BigInt>"u")return{stringValue:String(t)};const i=BigInt(t).toString();return t>=9223372036854776e3||-9223372036854776e3>t?(e?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:t}}if(typeof t=="string")return{stringValue:WO(t)};if(typeof t=="function")return{stringValue:"[Function]"};if(typeof t=="symbol")return{stringValue:String(t)};if(typeof t=="object"&&t!==null){if(n.ancestors.has(t))return{stringValue:"[Circular]"};if(o>=20)return{stringValue:YDe};if(t instanceof Date){const i=t.getTime(),r=Number.isFinite(i)?t.toISOString():String(t);return{stringValue:typeof r=="string"?WO(r):String(r)}}n.ancestors.add(t);try{try{const i=t.toJSON;if(typeof i=="function")return jDe(i.call(t),e,n,o+1)}catch{}return As(t)?{arrayValue:{values:EOo(t,e,n,o+1)}}:{kvlistValue:{values:CHt(t,e,n,o+1)}}}finally{n.ancestors.delete(t)}}return{stringValue:WO(String(t))}}function EOo(t,e,n,o){const i=[],r=Math.min(t.length,1e3);let s=0;for(;r>s&&n.remainingNodes>0;s++)try{const a=s in t?t[s]:void 0;if(Hs(a))continue;i.push(jDe(a,e,n,o))}catch{i.push({stringValue:R$})}return t.length>s&&i.push({stringValue:YDe}),i}function CHt(t,e,n,o){const i=[];for(const r in t)if(xOo.call(t,r)){if(!r){e?.debug("Dropping an attribute with an empty key");continue}if(i.length>=1e3||0>=n.remainingNodes){e?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{const s=t[r];if(Id(s)||Eo(s))continue;i.push({key:WO(r),value:jDe(s,e,n,o)})}catch{i.push({key:WO(r),value:{stringValue:R$}})}}return i}function yHt(t,e,n){return sn(sn(sn(sn({},qLt({},t.resourceAttributes)),{},{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment}),t.serviceVersion&&{"service.version":t.serviceVersion}),{},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}const BOo=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function xHt(t,e){const n=qLt({},t),o={};for(const i of BOo)({}).hasOwnProperty.call(n,i)&&(o[i]=n[i],delete n[i]);return[...xge(n,e),...xge(o,e)]}const EHt={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"},BHt={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},bOo=BHt.info;function SOo(t){try{return WO(String(t))}catch{return R$}}function QOo(t,e,n,o){const i=t.level||"info",{text:r,number:s}=BHt[i]||bOo,a=(function(g=Date.now()){return String(g)+"000000"})(Ah(o)?o:void 0),A={};e.distinctId&&(A.posthogDistinctId=e.distinctId),e.sessionId&&(A.sessionId=e.sessionId),e.windowId&&(A["window.id"]=e.windowId),Hs(e.sessionStartTimestamp)||(A.sessionStartTimestamp=String(e.sessionStartTimestamp)),Hs(e.lastActivityTimestamp)||(A.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(A["url.full"]=e.currentUrl),e.screenName&&(A["screen.name"]=e.screenName),e.appState&&(A["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(A.feature_flags=e.activeFeatureFlags);const c=sn({},A),l=t.attributes;if(l){let g=[];try{g=Object.keys(l)}catch{g=[]}for(const h of g){let d;try{d=l[h]}catch{d=R$}Object.defineProperty(c,h,{value:d,enumerable:!0,writable:!0,configurable:!0})}}const u={timeUnixNano:a,observedTimeUnixNano:a,severityNumber:s,severityText:r,body:{stringValue:SOo(t.body)},attributes:xge(c,n)};return t.trace_id&&(u.traceId=t.trace_id),t.span_id&&(u.spanId=t.span_id),Eo(t.trace_flags)||(u.flags=t.trace_flags),u}function bHt(t,e,n){return yHt(t,e,n)}function SHt(t,e,n,o){return{resourceLogs:[{resource:{attributes:xHt(e)},scopeLogs:[{scope:{name:n,version:o},logRecords:t}]}]}}var QHt=class{constructor(e){this.ls=e,this.us=0}get pending(){return!!this.hs}arm(e){this.clear(),this.us=Date.now()+e,this.hs=nHt(()=>{this.hs=void 0,this.ls()},e)}armNoEarlierThan(e){this.hs&&Date.now()+e<=this.us||this.arm(e)}clear(){this.hs&&(clearTimeout(this.hs),this.hs=void 0)}};function vHt(){return .75+.5*Math.random()}function wHt(t,e,n,o){const i=Math.min(Math.max(0,e-1),6),r=t*Math.pow(2,i);return Math.round(Math.min(r,Math.max(o,t))*n)}var vOo=class{constructor(e,n,o,i,r,s=()=>Promise.resolve(),a){var A;this._instance=e,this.Mr=n,this.A=o,this.cs=i,this.ds=r,this.vs=s,this.fs=a,this.ps=new QHt(()=>this.gs()),this.ys=null,this.bs=0,this._s=0,this.ws=new XLt,this.ks=0,this.Ss=1,this.xs=0,this.$s=0,this.Cs=!1,this.Ts=n.maxBufferSize,this.Is=Math.max((A=n.maxQueueSize)!==null&&A!==void 0?A:n.maxBufferSize,n.maxBufferSize),this.Ms=n.flushIntervalMs,this.Es=n.maxBatchRecordsPerPost,this.Ps=n.rateCapWindowMs,this.Rs=n.maxLogsPerInterval}clearQueue(){this._s++,this._instance.setPersistedProperty(l6.LogsQueue,[])}reset(){this.ps.clear(),this.xs=0,this.$s=0,this.Cs=!1,this.ks=0,this.Ss=1,this.ws.reset(),this.Es=this.Mr.maxBatchRecordsPerPost}onReconnect(){this.ks=0,this.Ss=1,this.ws.isOpen()?this.As()&&this.Os():this.gs()}captureLog(e,n){var o;if(this._instance.isDisabled||this._instance.optedOut||!e?.body)return;const i=this.Fs(e);if(i===null)return;if(!i.body)return void this.A.info("Log was rejected in beforeSend function");if(!this.Ds())return;const r={record:QOo(i,(o=n?.context)!==null&&o!==void 0?o:this.cs(),this.A,n?.occurredAtMs)};this.ds(()=>this.Ls(r))}Fs(e){const n=this.Mr.beforeSend;if(!n)return e;const o=As(n)?n:[n];let i=e;for(const r of o)try{const s=r(i);if(!s)return this.A.info("Log was rejected in beforeSend function"),null;i=s}catch(s){return this.A.error("Error in beforeSend function for log:",s),null}return i}Ds(){if(this.Rs===void 0)return!0;const e=Date.now(),n=e-this.xs;return this.Ps>n&&n>=0||(this.xs=e,this.$s=0,this.Cs=!1),this.Rs>this.$s?(this.$s++,!0):(this.Cs||(this.A.warn(`captureLog dropping logs: exceeded ${this.Rs} logs per ${this.Ps}ms`),this.Cs=!0),!1)}flush(){var e=this;return Zu(function*(){if(!e._instance.isDisabled)return e.ys||(e.ys=e.Ns().finally(()=>{e.ys=null})),e.ys})()}Ns(){var e=this;return Zu(function*(){var n;e.ps.clear();let o=(n=e._instance.getPersistedProperty(l6.LogsQueue))!==null&&n!==void 0?n:[];if(o.length===0)return;const i=o.length;let r=0;for(;o.length>0&&i>r;){var s,a;const A=e._s;e.bs=0;const c=Math.min(o.length,e.Es),l=o.slice(0,c),u=SHt(l.map(h=>h.record),e.qs(),(s=e.fs)!==null&&s!==void 0?s:e._instance.getLibraryId(),e._instance.getLibraryVersion()),g=yield e._instance.js(u);if(e._s!==A)return;if(g.kind==="too-large"&&l.length>1)e.Es=Math.max(1,Math.floor(l.length/2)),e.A.warn(`Logs batch of size ${l.length} was too large for the ingestion endpoint, reducing batch size to ${e.Es}`);else if(e.ws.record(g),e.ps.pending&&e.ps.arm(Math.max(e.Ms,e.ws.remainingMs())),g.kind==="retry-later"||(g.kind==="too-large"?e.A.warn("Dropping a single log record with batch size 1 — the record is larger than the server cap and cannot be split further."):g.kind==="ok"&&e.Mr.maxBatchRecordsPerPost>e.Es&&(e.Es=Math.min(e.Mr.maxBatchRecordsPerPost,e.Es+1)),yield e.Bs(l.length),o=(a=e._instance.getPersistedProperty(l6.LogsQueue))!==null&&a!==void 0?a:[],r+=l.length,g.kind==="fatal"))throw g.error}})()}Bs(e){var n=this;return Zu(function*(){var o;const i=Math.max(0,e-n.bs),r=(o=n._instance.getPersistedProperty(l6.LogsQueue))!==null&&o!==void 0?o:[];n._instance.setPersistedProperty(l6.LogsQueue,r.slice(i)),yield n.vs()})()}qs(){return bHt(this.Mr,this._instance.getLibraryId(),this._instance.getLibraryVersion())}Ls(e){var n;if(this._instance.optedOut)return;const o=(n=this._instance.getPersistedProperty(l6.LogsQueue))!==null&&n!==void 0?n:[];this.Is>o.length||(o.shift(),this.bs++,this.A.info("Logs queue is full, dropping oldest record.")),o.push(e),this._instance.setPersistedProperty(l6.LogsQueue,o),this.Ts>o.length||this.ws.isOpen()?this.Os():this.gs()}Os(){this.ps.pending||this.ps.arm(Math.max(this.Ms,this.ws.remainingMs()))}Hs(){return Math.max(wHt(this.Ms,this.ks,this.Ss,3e4),this.ws.remainingMs())}As(){const e=this._instance.getPersistedProperty(l6.LogsQueue);return!!e&&e.length>0}shutdown(e){var n=this;return Zu(function*(){n.ps.clear();const o=n.flush().catch(()=>{});e!==void 0?yield oHt(o,e):yield o})()}flushWithTimeout(e){var n=this;return Zu(function*(){const o=n.flush();yield oHt(o,e,()=>{o.catch(()=>{})})})()}gs(){this.flush().then(()=>{this.ks=0,this.Ss=1},e=>{this.ks++,this.Ss=vHt(),this.A.error("PostHog logs flush failed:",e)}).finally(()=>{!this._instance.isDisabled&&this.As()&&this.ps.armNoEarlierThan(this.Hs())})}};const $De=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function PHt(t){return String(t)+"000000"}function MHt(t,e,n,o){let i="";return o&&(i=Object.keys(o).sort().map(r=>`${JSON.stringify(r)}:${JSON.stringify(o[r])}`).join(",")),`${t}\0${e}\0${n??""}\0${i}`}var wOo=class{constructor(e,n,o){this._instance=e,this.Mr=n,this.A=o,this.zs=new Map,this.ps=new QHt(()=>this.flush().catch(i=>{this.A.error("Metrics flush failed:",i)})),this.ys=null,this.Us=!1,this.Ws=new Map,this.Vs=new Set,this.ws=new XLt,this.ks=0,this.Ss=1,this.Gs=0}count(e,n=1,o){this.Qs({name:e,type:"count",value:n,unit:o?.unit,attributes:o?.attributes})}gauge(e,n,o){this.Qs({name:e,type:"gauge",value:n,unit:o?.unit,attributes:o?.attributes})}histogram(e,n,o){this.Qs({name:e,type:"histogram",value:n,unit:o?.unit,attributes:o?.attributes})}flush(){var e=this;const n=this.ys,o=(function(){var i=Zu(function*(){n&&(yield n.catch(()=>{})),yield e.Js()});return function(){return i.apply(this,arguments)}})()().finally(()=>{this.ys===o&&(this.ys=null)});return this.ys=o,o}drainWindow(){if(this.zs.size===0)return null;const e=this.zs;return this.zs=new Map,this.Us=!1,this.Ws=new Map,this.Vs=new Set,this.Zs(e)}reset(){this.Gs++,this.ws.reset(),this.ks=0,this.Ss=1,this.ps.clear(),this.zs=new Map,this.ys=null,this.Us=!1,this.Ws=new Map,this.Vs=new Set}Qs(e){if(this._instance.isDisabled||this._instance.optedOut)return;const n=this.Fs(e);if(n===null)return;if(!n.name||typeof n.name!="string")return void this.A.warn("Dropping metric with empty name");if(typeof n.value!="number"||!Number.isFinite(n.value))return void this.A.warn(`Dropping metric '${n.name}': value must be a finite number`);if(n.type==="count"&&0>n.value)return void this.A.warn(`Dropping count '${n.name}': counters are monotonic, value must be >= 0`);let o,i;try{o=n.attributes?sn({},n.attributes):void 0,i=MHt(n.type,n.name,n.unit,o)}catch(a){return void this.A.warn(`Dropping metric '${n.name}': attributes could not be serialized`,a)}let r=this.zs.get(i);if(!r){if(!this.Ks())return;r={name:n.name,type:n.type,unit:n.unit,attributes:o,windowStartMs:Date.now()},this.zs.set(i,r)}const s=this.Ws.get(n.name);s===void 0?this.Ws.set(n.name,n.type):s===n.type||this.Vs.has(n.name)||(this.Vs.add(n.name),this.A.warn(`Metric name '${n.name}' is already used as a ${s}; recording it as a ${n.type} too will blend both series in charts. Use a distinct name.`)),this.Xs(r,n.value),this.Os()}Ks(){return this.Mr.maxSeriesPerFlush>this.zs.size||(this.Us||(this.Us=!0,this.A.warn(`Metric series cap reached (${this.Mr.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}Xs(e,n){switch(e.type){case"count":var o;e.total=((o=e.total)!==null&&o!==void 0?o:0)+n;break;case"gauge":e.last=n;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:n,max:n,bucketCounts:new Array($De.length+1).fill(0)});const i=e.hist;i.count+=1,i.sum+=n,i.min=Math.min(i.min,n),i.max=Math.max(i.max,n),i.bucketCounts[(function(r,s){for(let a=0;s.length>a;a++)if(s[a]>=r)return a;return s.length})(n,$De)]+=1;break}}}Fs(e){const n=this.Mr.beforeSend;if(!n)return e;const o=As(n)?n:[n];let i=e;for(const r of o)try{const s=r(i);if(!s)return this.A.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this.A.error("Error in beforeSend function for metric:",s),null}return i}Os(){this.ps.pending||this.ps.arm(this.Hs())}Hs(){return Math.max(wHt(this.Mr.flushIntervalMs,this.ks,this.Ss,3e4),this.ws.remainingMs())}Js(){var e=this;return Zu(function*(){if(e.ps.clear(),e.zs.size===0)return;const n=e.zs;e.zs=new Map,e.Us=!1,e.Ws=new Map,e.Vs=new Set;const o=e.Gs,i=yield e._instance.Ys(e.Zs(n));if(o===e.Gs)switch(e.ws.record(i),i.kind==="retry-later"?(e.ks++,e.Ss=vHt()):(e.ks=0,e.Ss=1),e.ps.pending&&e.ps.arm(e.Hs()),i.kind){case"ok":return;case"retry-later":return e.ho(n),void e.ps.armNoEarlierThan(e.Hs());case"too-large":return void e.A.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void e.A.error("Failed to send metrics batch:",i.error)}})()}Zs(e){return n=this.co(e),o=(function(s,a,A){return yHt(s,a,A)})(this.Mr,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:xHt(o)},scopeMetrics:[{scope:{name:i,version:r},metrics:n}]}]};var n,o,i,r}co(e){const n=PHt(Date.now()),o=new Map;for(const a of e.values()){var i;const A=MHt(a.type,a.name,a.unit,void 0);let c=o.get(A);c||(c=sn({name:a.name},a.unit&&{unit:a.unit}),a.type==="count"?c.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:a.type==="gauge"?c.gauge={dataPoints:[]}:c.histogram={aggregationTemporality:1,dataPoints:[]},o.set(A,c));const l=xge((i=a.attributes)!==null&&i!==void 0?i:{},this.A),u=PHt(a.windowStartMs);if(a.type==="count"){var r;const g={attributes:l,startTimeUnixNano:u,timeUnixNano:n,asDouble:(r=a.total)!==null&&r!==void 0?r:0};c.sum.dataPoints.push(g)}else if(a.type==="gauge"){var s;const g={attributes:l,timeUnixNano:n,asDouble:(s=a.last)!==null&&s!==void 0?s:0};c.gauge.dataPoints.push(g)}else a.hist&&c.histogram.dataPoints.push({attributes:l,startTimeUnixNano:u,timeUnixNano:n,count:a.hist.count,sum:a.hist.sum,min:a.hist.min,max:a.hist.max,bucketCounts:a.hist.bucketCounts,explicitBounds:$De})}return Array.from(o.values())}ho(e){for(const[i,r]of e){const s=this.zs.get(i);if(s)switch(s.windowStartMs=Math.min(s.windowStartMs,r.windowStartMs),s.type){case"count":var n,o;s.total=((n=s.total)!==null&&n!==void 0?n:0)+((o=r.total)!==null&&o!==void 0?o:0);break;case"gauge":break;case"histogram":if(r.hist)if(s.hist){s.hist.count+=r.hist.count,s.hist.sum+=r.hist.sum,s.hist.min=Math.min(s.hist.min,r.hist.min),s.hist.max=Math.max(s.hist.max,r.hist.max);for(let a=0;s.hist.bucketCounts.length>a;a++)s.hist.bucketCounts[a]+=r.hist.bucketCounts[a]}else s.hist=r.hist}else this.Ks()&&this.zs.set(i,r)}}};const DHt=(t,{debugEnabled:e}={})=>{const n={N(o,...i){Fn&&(Ob.DEBUG||Fn.POSTHOG_DEBUG||e)&&!Eo(Fn.console)&&Fn.console&&("__rrweb_original__"in Fn.console[o]?Fn.console[o].__rrweb_original__:Fn.console[o])(t,...i)},debug(...o){n.N("debug",...o)},info(...o){n.N("log",...o)},warn(...o){n.N("warn",...o)},error(...o){n.N("error",...o)},critical(...o){console.error(t,...o)},uninitializedWarning(o){n.error(`You must initialize PostHog before calling ${o}`)},createLogger:(o,i)=>DHt(`${t} ${o}`,i)};return n},ui=DHt("[PostHog.js]"),Cd=ui.createLogger,POo=Cd("[ExternalScriptsLoader]"),Ege=t=>{const e=No?.querySelectorAll("script");if(e){for(let n=0;e.length>n;n++)if(e[n].src===t||e[n].getAttribute("src")===t)return e[n]}},IR=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return POo.warn(`${e} was requested but loading of external scripts is disabled.`),n("Loading of external scripts is disabled");const o=Ege(e);if(o){if(o.__posthog_loading_callback_fired)return n();const r=o.__posthog_loading_error;return r?n(r):(o.addEventListener("load",s=>{o.__posthog_loading_callback_fired=!0,n(void 0,s)}),void o.addEventListener("error",s=>{o.__posthog_loading_error=s,n(s)}))}const i=()=>{if(!No)return n("document not found");if(Ege(e))return IR(t,e,n);let r=No.createElement("script");if(r.type="text/javascript",r.crossOrigin="anonymous",r.src=e,r.onload=a=>{r.__posthog_loading_callback_fired=!0,n(void 0,a)},r.onerror=a=>{r.__posthog_loading_error=a,n(a)},t.config.prepare_external_dependency_script&&(r=t.config.prepare_external_dependency_script(r)),!r)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")No.head.appendChild(r);else{const a=No.querySelectorAll("body > script");var s;a.length>0?(s=a[0].parentNode)===null||s===void 0||s.insertBefore(r,a[0]):No.body.appendChild(r)}};No?.body?i():No?.addEventListener("DOMContentLoaded",i)},qDe={},NHt=(t,e)=>{let n=`/static/${e}.js?v=${t.version}`;return e==="toolbar"&&(n=`${n}&t=${Math.floor(Date.now()/3e5)*3e5}`),t.requestRouter.endpointFor("assets",n)};Vr.__PosthogExtensions__=Vr.__PosthogExtensions__||{},Vr.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e==="remote-config"){const i=t.requestRouter.endpointFor("assets",`/array/${t.config.token}/config.js`);return void IR(t,i,n)}const o=t.config.strict_script_versioning;if(o){const i=t.requestRouter.endpointFor("assets",`/static/${t.version}/${e}.js`),r=qDe[i];if(o==="fallback"&&r){if(Ege(r))return void IR(t,r,n);delete qDe[i]}return void IR(t,i,o==="fallback"?(s,a)=>{if(s)if(typeof s=="string")n(s);else{var A;const c=NHt(t,e);qDe[i]=c;const l=Ege(i);l==null||(A=l.parentNode)===null||A===void 0||A.removeChild(l),IR(t,c,n)}else n(void 0,a)}:n)}IR(t,NHt(t,e),n)},Vr.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{const o=t.requestRouter.endpointFor("api",e);IR(t,o,n)},Ob.DEBUG=!1,Ob.LIB_VERSION="1.435.8",Ob.LIB_NAME="web";var n_=Ob;const MOo="$people_distinct_id",RB="distinct_id",XDe="$device_id",ZDe="$device_model",Bge="__alias",DOo="__cmpns",RHt="$fbc",jO="$fbc_persistence",THt="$fbp",F$="$fbp_persistence",eNe="__timers",kHt="$autocapture_disabled_server_side",tNe="$heatmaps_enabled_server_side",nNe="$exception_capture_enabled_server_side",FHt="$error_tracking_suppression_rules",oNe="$error_tracking_capture_extension_exceptions",iNe="$web_vitals_enabled_server_side",rNe="$dead_clicks_enabled_server_side",sNe="$product_tours_enabled_server_side",LHt="$logs_capture_enabled_server_side",HHt="$web_vitals_allowed_metrics",L$="$session_recording_remote_config",NOo="$session_recording_enabled_server_side",ROo="$replay_sample_rate",TOo="$replay_override_sampling",kOo="$replay_override_linked_flag",FOo="$replay_override_url_trigger",LOo="$replay_override_event_trigger",$O="$sesid",OHt="$session_is_sampled",HOo="$session_past_minimum_duration",OOo="$session_recording_url_trigger_activated_session",GOo="$session_recording_event_trigger_activated_session",YOo="$debug_first_full_snapshot_timestamp",UOo="$sess_rec_flush_size",TB="$enabled_feature_flags",Yb="$active_feature_flags",aNe="$early_access_features",CR="$feature_flag_details",Dw="$feature_flag_payloads",yR="$feature_flag_request_id",H$="$minimal_flag_called_events",g6="$override_feature_flags",xR="$override_feature_flag_payloads",Nw="$stored_person_properties",Rw="$stored_group_properties",GHt="$groups",O$="$surveys",bge="$surveys_loaded_at",YHt="$surveys_activated",UHt="$surveys_activated_session",KHt="$surveys_activated_timestamps",ANe="ph_product_tours",KOo="$product_tours_activated",VOo="$product_tours_activated_session",zOo="$conversations_widget_session_id",JOo="$conversations_ticket_id",WOo="$conversations_widget_state",jOo="$conversations_user_traits",Tw="$flag_call_reported",G$="$flag_call_reported_session_id",Y$="$feature_flag_errors",kw="$feature_flag_evaluated_at",qy="$user_state",cNe="$client_session_props",$Oo="$capture_rate_limit",VHt="$initial_campaign_params",zHt="$initial_referrer_info",qO="$initial_person_info",lNe="$epp",uNe="$posthog_cookieless",JHt="$cookieless_mode",WHt="$sdk_debug_extensions_init_method",jHt="$sdk_debug_extensions_init_time_ms",gNe="$sdk_debug_recording_script_not_loaded",dNe="$sdk_debug_replay_stale_config",$Ht="$sdk_debug_replay_event_trigger_status",qHt="$sdk_debug_replay_linked_flag_trigger_status",XHt="$sdk_debug_replay_matched_recording_trigger_groups",ZHt="$sdk_debug_replay_pending_trigger_conditions",eOt="$sdk_debug_replay_remote_trigger_matching_config",tOt="$sdk_debug_replay_trigger_groups_count",nOt="$sdk_debug_replay_url_trigger_status",qOo="$session_recording_start_reason",hNe="PostHog loadExternalDependency extension not found.",Ub="anonymous",Sge="identified",oOt="identified_only",U$="visibilitychange",Qge="beforeunload",pNe="$pageview",iOt="$pageleave",rOt="$identify",sOt="$groupidentify";function XO(t,e){As(t)&&t.forEach(e)}function kl(t,e){if(!Hs(t))if(As(t))t.forEach(e);else if((n=>n instanceof FormData)(t))t.forEach((n,o)=>e(n,o));else for(const n in t)MDe.call(t,n)&&e(t[n],n)}const eg=function(t,...e){for(const n of e)for(const o in n)n[o]!==void 0&&(t[o]=n[o]);return t};function vge(t){const e=Object.keys(t);let n=e.length;const o=new Array(n);for(;n--;)o[n]=[e[n],t[e[n]]];return o}const XOo=function(t){return function(...e){try{return t.apply(this,e)}catch(n){ui.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),ui.critical(n)}}},mNe=function(t){const e={};return kl(t,function(n,o){(rA(n)&&n.length>0||Ah(n))&&(e[o]=n)}),e};function aOt(t){const e=sn({},t);for(const n of["name","message","stack","cause","errors"])try{n in t&&(e[n]=t[n])}catch{}return e}const ZOo=["herokuapp.com","vercel.app","netlify.app"];function eGo(t){const e=t?.hostname;if(!rA(e))return!1;const n=e.split(".").slice(-2).join(".");for(const o of ZOo)if(n===o)return!1;return!0}function el(t,e,n,o){const{capture:i=!1,passive:r=!0}=o??{};t?.addEventListener(e,n,{capture:i,passive:r})}function _Ne(t){return t.name==="ph_toolbar_internal"}const K$=t=>{if(No){try{const e=t+"=",n=No.cookie.split(";").filter(o=>o.length);for(let o=0;n.length>o;o++){let i=n[o];for(;i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return decodeURIComponent(i.substring(e.length,i.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return Ah(t)&&isFinite(t)&&Math.floor(t)===t});var tGo=class Eit{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,o,i){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(o)||!Number.isInteger(i)||0>e||0>n||0>o||0>i||e>0xffffffffffff||n>4095||o>1073741823||i>4294967295)throw new RangeError("invalid field value");const r=new Uint8Array(16);return r[0]=e/Math.pow(2,40),r[1]=e/Math.pow(2,32),r[2]=e/Math.pow(2,24),r[3]=e/Math.pow(2,16),r[4]=e/256,r[5]=e,r[6]=112|n>>>8,r[7]=n,r[8]=128|o>>>24,r[9]=o>>>16,r[10]=o>>>8,r[11]=o,r[12]=i>>>24,r[13]=i>>>16,r[14]=i>>>8,r[15]=i,new Eit(r)}toString(){let e="";for(let n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new Eit(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let n=0;16>n;n++){const o=this.bytes[n]-e.bytes[n];if(o!==0)return Math.sign(o)}return 0}},nGo=class{generate(){const e=this.generateOrAbort();if(!Eo(e))return e;{this.Ct=0;const n=this.generateOrAbort();if(Eo(n))throw new Error("Could not generate UUID after timestamp reset");return n}}generateOrAbort(){const e=(()=>{const n=Date.now();return Ah(n)&&isFinite(n)?Math.min(Math.max(Math.floor(n),0),0xffffffffffff):0})();if(e>this.Ct)this.Ct=e,this.It();else{if(this.Ct>=e+1e4)return;this.Mt++,this.Mt>4398046511103&&(this.Ct++,this.It())}return tGo.fromFieldsV7(this.Ct,Math.trunc(this.Mt/Math.pow(2,30)),this.Mt&Math.pow(2,30)-1,this.Tt.nextUint32())}It(){this.Mt=1024*this.Tt.nextUint32()+(1023&this.Tt.nextUint32())}constructor(){this.Ct=0,this.Mt=0,this.Tt=new oGo}};let AOt=t=>{if("u">typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(let e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};Fn&&!Eo(Fn.crypto)&&crypto.getRandomValues&&(AOt=t=>crypto.getRandomValues(t));var oGo=class{nextUint32(){return this.Rt.length>this.At||(AOt(this.Rt),this.At=0),this.Rt[this.At++]}constructor(){this.Rt=new Uint32Array(8),this.At=1/0}};let cOt;const kB=()=>iGo().toString(),iGo=()=>(cOt||(cOt=new nGo)).generate();let V$="";const rGo=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;let ZO=null;const yd={Et(){if(!Id(ZO))return ZO;if(ZO=!1,No)try{const t=`__ph_cookie_support_${kB()}`;yd.$t(t,"xyz"),ZO=K$(t)==='"xyz"',yd.Pt(t)}catch{ZO=!1}return ZO},Dt(t){ui.error("cookieStore error: "+t)},Ot:K$,Lt(t){let e;try{e=JSON.parse(yd.Ot(t))||{}}catch{}return e},$t(t,e,n,o,i){if(!No)return!1;try{let r="",s="";const a=(function(c,l){if(l){let u=(function(g,h=No){if(V$)return V$;if(!h||["localhost","127.0.0.1"].includes(g))return"";const d=g.split(".");let p=Math.min(d.length,8);const m="dmn_chk_"+kB();for(;!V$&&p--;){const _=d.slice(p).join("."),f=m+"=1;domain=."+_+";path=/";h.cookie=f+";max-age=3",h.cookie.includes(m)&&(h.cookie=f+";max-age=0",V$=_)}return V$})(c);if(!u){const g=(h=>{const d=h.match(rGo);return d?d[0]:""})(c);g!==u&&ui.info("Warning: cookie subdomain discovery mismatch",g,u),u=g}return u?"; domain=."+u:""}return""})(No.location.hostname,o);if(n){const c=new Date;c.setTime(c.getTime()+864e5*n),r="; expires="+c.toUTCString()}i&&(s="; secure");const A=t+"="+encodeURIComponent(JSON.stringify(e))+r+"; SameSite=Lax; path=/"+a+s;return A.length>3686.4&&ui.warn("cookieStore warning: large cookie, len="+A.length),No.cookie=A,!0}catch{return!1}},Pt(t,e){if(No?.cookie&&(!e||!Id(K$(t))))try{yd.$t(t,"",-1,e)}catch{return}}};let fNe=null;const hc={Et(){if(!Id(fNe))return fNe;let t=!0;if(Eo(Fn))t=!1;else try{const e="__mplssupport__";hc.$t(e,"xyz"),hc.Ot(e)!=='"xyz"'&&(t=!1),hc.Pt(e)}catch{t=!1}return t||ui.error("localStorage unsupported; falling back to cookie store"),fNe=t,t},Dt(t){ui.error("localStorage error: "+t)},Ot(t){try{return Fn?.localStorage.getItem(t)}catch(e){hc.Dt(e)}return null},Lt(t){try{return JSON.parse(hc.Ot(t))||{}}catch{}return null},$t(t,e){try{return Fn?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){hc.Dt(n)}return!1},Pt(t){try{Fn?.localStorage.removeItem(t)}catch(e){hc.Dt(e)}}},INe=[Nw,Yb,TB,CR,Dw,yR,kw,Y$,Tw],ER=[XDe,RB,$O,OHt,lNe,qO,jO,qy],wge=t=>t+"_cpm",sGo=["__proto__","constructor","prototype"],CNe=t=>{if(!QA(t))return{};const e={};return Object.keys(t).forEach(n=>{sGo.indexOf(n)===-1&&(e[n]=t[n])}),e},yNe=(t,e=[])=>{const n={};return[...ER,...e].forEach(o=>{const i=t[o];Eo(i)||Id(i)||i===""||(n[o]=i)}),n},lOt=t=>{let e=5381,n=2166136261;for(let o=0;t.length>o;o++){const i=t.charCodeAt(o);e=33*e^i,n=Math.imul(n^i,16777619)}return t.length.toString(36)+"."+(e>>>0).toString(36)+"."+(n>>>0).toString(36)},uOt=(t,e)=>({p:e,f:lOt(JSON.stringify(t))}),gOt=(t,e)=>{if(!e)return{properties:[],isValid:!1};try{const n=yd.Lt(wge(t)),o=n?.f===lOt(e)&&As(n.p);return{properties:o?n.p:[],isValid:o}}catch{return{properties:[],isValid:!1}}},xNe=(t,e)=>e+"|"+(yd.Ot(wge(t))||""),eG={},ENe={Et:()=>!0,Dt(t){ui.error("memoryStorage error: "+t)},Ot:t=>t in eG?eG[t]:null,Lt:t=>t in eG?eG[t]:null,$t:(t,e)=>(eG[t]=e,!0),Pt(t){delete eG[t]}};let BR=null;const nu={Et(){if(!Id(BR))return BR;if(BR=!0,Eo(Fn))BR=!1;else try{const t="__support__";nu.$t(t,"xyz"),nu.Ot(t)!=='"xyz"'&&(BR=!1),nu.Pt(t)}catch{BR=!1}return BR},Dt(t){ui.error("sessionStorage error: ",t)},Ot(t){try{return Fn?.sessionStorage.getItem(t)}catch(e){nu.Dt(e)}return null},Lt(t){try{return JSON.parse(nu.Ot(t))||null}catch{}return null},$t(t,e){try{return Fn?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){nu.Dt(n)}return!1},Pt(t){try{Fn?.sessionStorage.removeItem(t)}catch(e){nu.Dt(e)}}};var aGo=class{constructor(e){this._instance=e}get Mr(){return this._instance.config}get consent(){return this.Do()?0:this.Lo}isOptedOut(){return this.Mr.cookieless_mode==="always"||this.isRejected()||this.consent===-1&&this.Mr.cookieless_mode==="on_reject"}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Mr.opt_out_capturing_by_default}optInOut(e){this.No.$t(this.qo,e?1:0,this.Mr.cookie_expiration,this.Mr.cross_subdomain_cookie,this.Mr.secure_cookie)}reset(){this.No.Pt(this.qo,this.Mr.cross_subdomain_cookie)}get qo(){const{token:e,opt_out_capturing_cookie_prefix:n,consent_persistence_name:o}=this._instance.config;return o||(n?n+e:"__ph_opt_in_out_"+e)}get Lo(){const e=this.No.Ot(this.qo);return NDe(e)?1:as(DHo,e)?0:-1}get No(){const e=this.Mr.opt_out_capturing_persistence_type,n=e==="localStorage"?hc:yd,o=n.Et()?n:ENe;if(!this.jo||this.jo!==o){this.jo=o;const i=e==="localStorage"?yd:hc;i.Ot(this.qo)&&(this.jo.Ot(this.qo)||this.optInOut(NDe(i.Ot(this.qo))),i.Pt(this.qo,this.Mr.cross_subdomain_cookie))}return this.jo}Do(){return!!this.Mr.respect_dnt&&[tf?.doNotTrack,tf?.msDoNotTrack,Vr.doNotTrack,tf?.globalPrivacyControl].some(e=>NDe(e))}};function dOt(t,e){var n;const o=t==null||(n=t.config)===null||n===void 0?void 0:n.get_current_url;if(!nf(o))return e;try{const i=o(e);return rA(i)&&i?i:e}catch(i){return ui.error("Error in get_current_url, falling back to window.location.href",i),e}}function hOt(t){var e;return t instanceof Element&&(t.id==="__POSTHOG_TOOLBAR__"||!!(!((e=t.closest)===null||e===void 0)&&e.call(t,".toolbar-global-fade-container")))}function d6(t){return!!t&&t.nodeType===1}function AI(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function pOt(t){return!!t&&t.nodeType===3}function BNe(t){return!!t&&t.nodeType===11&&d6(t.host)}function bNe(t){return t?rge(t).split(/\s+/):[]}function mOt(t,e){const n=(function(o){var i;const r=Fn==null||(i=Fn.location)===null||i===void 0?void 0:i.href;return Eo(r)?void 0:dOt(o,r)})(e);return!!(n&&t&&t.some(o=>n.match(o)))}function tG(t){let e="";switch(typeof t.className){case"string":e=t.className;break;case"object":e=(t.className&&"baseVal"in t.className?t.className.baseVal:null)||t.getAttribute("class")||"";break;default:e=""}return bNe(e)}function _Ot(t){return Hs(t)?null:rge(t).split(/(\s+)/).filter(e=>j$(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function z$(t){let e="";return nG(t)&&!W$(t)&&t.childNodes&&t.childNodes.length&&kl(t.childNodes,function(n){var o;pOt(n)&&n.textContent&&(e+=(o=_Ot(n.textContent))!==null&&o!==void 0?o:"")}),rge(e)}function J$(t){var e;return Eo(t.target)?t.srcElement||null:!((e=t.target)===null||e===void 0)&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}const SNe=["a","button","form","input","select","textarea","label"];function QNe(t,e){const n=t.matches||t.matchesSelector||t.msMatchesSelector||t.mozMatchesSelector||t.webkitMatchesSelector||t.oMatchesSelector;try{return!!n&&n.call(t,e)}catch{return!1}}function vNe(t,e){if(Eo(e))return!0;for(const n of t)if(e.some(o=>QNe(n,o)))return!0;return!1}function fOt(t){const e=t.parentNode;return!(!e||!d6(e))&&e}const wNe=[".ph-no-autocapture","[data-ph-no-autocapture]"],IOt=["next","previous","prev",">","<"],AGo=[...IOt,"+","-","−","–"],COt=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,yOt=[".ph-no-rageclick",".ph-no-capture"],cGo=["","text","search","email","password","url","tel","number"];function xOt(t,e){if(!Fn||PNe(t))return!1;let n,o,i;var r,s;if($y(e)?(n=!!e&&yOt,o=void 0,i=!1):(n=(r=e?.css_selector_ignorelist)!==null&&r!==void 0?r:yOt,o=e?.content_ignorelist,i=(s=e?.ignore_text_selection)!==null&&s!==void 0&&s),n===!1||i&&(function(A){return!(!A||!d6(A))&&(!!AI(A,"textarea")||(AI(A,"input")?as(cGo,(A.getAttribute("type")||"").toLowerCase()):(function(c){var l;if(c.isContentEditable)return!0;const u=(l=c.getAttribute)===null||l===void 0?void 0:l.call(c,"contenteditable");return u==="true"||u===""})(A)))})(t))return!1;const{targetElementList:a}=EOt(t,!1);return!(function(A,c){if(A===!1||Eo(A))return!1;let l;if(A===!0)l=IOt;else{if(!As(A))return!1;if(A.length>10)return ui.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;l=A.map(u=>u.toLowerCase())}return c.some(({safeText:u,ariaLabel:g})=>l.some(h=>COt(u,h)||COt(g,h)))})(o,a.map(A=>{var c;return{safeText:z$(A).toLowerCase(),ariaLabel:((c=A.getAttribute("aria-label"))===null||c===void 0?void 0:c.toLowerCase().trim())||""}}))&&!vNe(a,n)}const PNe=t=>!t||AI(t,"html")||!d6(t),EOt=(t,e)=>{if(!Fn||PNe(t))return{parentIsUsefulElement:!1,targetElementList:[]};let n=!1;const o=[t];let i=t;for(;i.parentNode&&!AI(i,"body");){if(BNe(i.parentNode)){o.push(i.parentNode.host),i=i.parentNode.host;continue}const r=fOt(i);if(!r)break;if(e||SNe.indexOf(r.tagName.toLowerCase())>-1)n=!0;else try{const s=Fn.getComputedStyle(r);s&&s.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}o.push(r),i=r}return{parentIsUsefulElement:n,targetElementList:o}};function nG(t){const e=new Set;let n=0;for(let r=t;r.parentNode&&!AI(r,"body");r=r.parentNode){if(n++>=1e3||e.has(r))return!1;e.add(r);const s=tG(r);if(as(s,"ph-sensitive")||as(s,"ph-no-capture"))return!1}if(as(tG(t),"ph-include"))return!0;const o=t.type||"";if(rA(o))switch(o.toLowerCase()){case"hidden":case"password":return!1}const i=t.name||t.id||"";return!rA(i)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,""))}function W$(t){return!!(AI(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||AI(t,"select")||AI(t,"textarea")||t.getAttribute("contenteditable")==="true")}const BOt=new RegExp("^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$"),bOt=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,lGo=[16,15,14,13],uGo=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),SOt=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),QOt=/[0-9A-Za-z_]/;function gGo(t){let e=0,n=!1;for(let o=t.length-1;o>=0;o--){let i=t.charCodeAt(o)-48;n&&(i*=2,i>9&&(i-=9)),e+=i,n=!n}return e%10==0}function j$(t,e=!0){return!(Hs(t)||rA(t)&&(t=rge(t),(e?BOt.test((t||"").replace(/[- ]/g,"")):(function(n){let o;for(bOt.lastIndex=0;o=bOt.exec(n);){const i=o[2];if(!i)continue;const r=i.replace(/[- ]/g,"");for(let s=0;r.length>s;s++)for(const a of lGo){const A=s+a;if(r.length>=A){const c=r.slice(s,A);if(BOt.test(c)&&gGo(c))return!0}}}return!1})(t))||(e?uGo.test(t):(function(n){let o;for(SOt.lastIndex=0;o=SOt.exec(n);){const i=o[1],r=o[3];if(!(i&&r&&QOt.test(i)&&QOt.test(r)))return!0}return!1})(t))))}function vOt(t){let e=z$(t);return e=`${e} ${wOt(t)}`.trim(),j$(e)?e:""}function wOt(t){let e="";return t&&t.childNodes&&t.childNodes.length&&kl(t.childNodes,function(n){var o;if(n&&((o=n.tagName)===null||o===void 0?void 0:o.toLowerCase())==="span")try{const i=z$(n);e=`${e} ${i}`.trim(),n.childNodes&&n.childNodes.length&&(e=`${e} ${wOt(n)}`.trim())}catch(i){ui.error("[AutoCapture]",i)}}),e}function POt(t){return t.replace(/"|\\"/g,'\\"')}function dGo(t){const e=t.attr__class;if(e)return As(e)?e:bNe(e)}const Pge=Cd("[Dead Clicks]"),hGo=()=>!0,pGo=t=>{var e;const n=!!(!((e=t.instance.persistence)===null||e===void 0)&&e.get_property(rNe)),o=t.instance.config.capture_dead_clicks;return $y(o)?o:!!QA(o)||n};var MOt=class{get lazyLoadedDeadClicksAutocapture(){return this.Bo}constructor(e,n,o){this.instance=e,this.isEnabled=n,this.onCapture=o,this.startIfEnabledOrStop()}onRemoteConfig(e){if(!e.ok)return;const n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[rNe]:n.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this.Ho(()=>{this.zo()}):this.stop()}Ho(e){var n,o,i;!((n=Vr.__PosthogExtensions__)===null||n===void 0)&&n.initDeadClicksAutocapture?e():(o=Vr.__PosthogExtensions__)===null||o===void 0||(i=o.loadExternalDependency)===null||i===void 0||i.call(o,this.instance,"dead-clicks-autocapture",r=>{r?Pge.error("failed to load script",r):e()})}zo(){var e;if(No){if(!this.Bo&&(!((e=Vr.__PosthogExtensions__)===null||e===void 0)&&e.initDeadClicksAutocapture)){const n=QA(this.instance.config.capture_dead_clicks)?sn({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.Bo=Vr.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.Bo.start(No),Pge.info("starting...")}}else Pge.error("`document` not found. Cannot start.")}stop(){this.Bo&&(this.Bo.stop(),this.Bo=void 0,Pge.info("stopping..."))}};const $$=Cd("[SegmentIntegration]");function DOt(t,e,n=!0){const o=t.config.segment;if(!o)return e();const{analytics:i,filterProperties:r}=(a=>nf(a.register))(s=o)?{analytics:s}:s;var s;(function(a,A,c,l){const u=h=>{const d=()=>h.anonymousId()||kB();a.config.get_device_id=d,l&&h.id()&&(a.register({distinct_id:h.id(),$device_id:d()}),a.persistence.set_property(qy,Sge)),c(l?void 0:h.anonymousId()||void 0)},g=A.user();"then"in g&&nf(g.then)?g.then(u):u(g)})(t,i,a=>{i.register(((A,c,{filterProperties:l}={})=>{typeof Promise<"u"&&Promise.resolve||$$.warn("This browser does not have Promise support, and can not use the segment integration");const u=(g,h)=>{if(!h)return g;const d=!!c&&g.event.anonymousId===c&&!g.event.userId;d||g.event.userId||g.event.anonymousId===A.get_distinct_id()||($$.info("No userId set, resetting PostHog"),A.reset()),d||(c=void 0),g.event.userId&&g.event.userId!==A.get_distinct_id()&&($$.info("UserId set, identifying with PostHog"),A.identify(g.event.userId));let p=A.calculateEventProperties(h,g.event.properties);if(!Hs(l)){const m=g.event.properties||{},_={};for(const I of Object.keys(p))MDe.call(m,I)||(_[I]=p[I]);const f=((I,C)=>{const y=As(I)?I:[I];let x=sn({},C);for(const E of y)try{if(x=E(x),Hs(x))return null}catch(B){return $$.error("Error in Segment filterProperties:",B),null}return x})(l,_);if(Hs(f))return g;p=f}return g.event.properties=Object.assign({},p,g.event.properties),g};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded(){return!0},load(){return Promise.resolve()},track(g){return u(g,g.event.event)},page(g){return u(g,pNe)},identify(g){return u(g,rOt)},screen(g){return u(g,"$screen")}}})(t,a,{filterProperties:r})).then(()=>{e()},A=>{$$.error("Failed to register the Segment integration",A),e()})},n)}const NOt="posthog-js";function ROt(t,{organization:e,projectId:n,prefix:o,severityAllowList:i=["error"],sendExceptionsToPostHog:r=!0}={}){return s=>{var a,A,c,l,u;if(i!=="*"&&!i.includes(s.level)||!t.__loaded)return s;s.tags||(s.tags={});const g=t.requestRouter.endpointFor("ui",`/project/${t.config.token}/person/${t.get_distinct_id()}`);s.tags["PostHog Person URL"]=g,t.sessionRecordingStarted()&&(s.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));const h=((a=s.exception)===null||a===void 0?void 0:a.values)||[],d=h.map(_=>sn(sn({},_),{},{stacktrace:_.stacktrace?sn(sn({},_.stacktrace),{},{type:"raw",frames:(_.stacktrace.frames||[]).map(f=>sn(sn({},f),{},{platform:"web:javascript"}))}):void 0})),p={$exception_message:((A=h[0])===null||A===void 0?void 0:A.value)||s.message,$exception_type:(c=h[0])===null||c===void 0?void 0:c.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:((l=h[0])===null||l===void 0?void 0:l.value)||s.message,$sentry_exception_type:(u=h[0])===null||u===void 0?void 0:u.type,$sentry_tags:s.tags};var m;return e&&n&&(p.$sentry_url=(o||"https://sentry.io/organizations/")+e+"/issues/?project="+n+"&query="+s.event_id),r&&((m=t.exceptions)===null||m===void 0||m.sendExceptionEvent(p)),s}}var mGo=class{constructor(e,n,o,i,r,s){this.name=NOt,this.setupOnce=function(a){a(ROt(e,{organization:n,projectId:o,prefix:i,severityAllowList:r,sendExceptionsToPostHog:s==null||s}))}}},TOt=class{constructor(e){this.Uo=(n,o,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength||i.crossTabAdoption)&&(ui.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:i}),this.Wo=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Vo()}Vo(){var e;this.Go=(e=this._instance.sessionManager)===null||e===void 0?void 0:e.onSessionId(this.Uo)}destroy(){var e;(e=this.Go)===null||e===void 0||e.call(this),this.Go=void 0}doPageView(e,n){var o;const i=this.Qo(e,n);return this.Wo={pathname:(o=Fn?.location.pathname)!==null&&o!==void 0?o:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),i}doPageLeave(e){var n;return this.Qo(e,(n=this.Wo)===null||n===void 0?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Wo)===null||e===void 0?void 0:e.pageViewId}}Qo(e,n){const o=this.Wo;if(!o)return{$pageview_id:n};let i={$pageview_id:n,$prev_pageview_id:o.pageViewId};const r=this._instance.scrollManager.getContext();if(r&&!this._instance.config.disable_scroll_properties){let{maxScrollHeight:s,lastScrollY:a,maxScrollY:A,maxContentHeight:c,lastContentY:l,maxContentY:u}=r;if(!(Eo(s)||Eo(a)||Eo(A)||Eo(c)||Eo(l)||Eo(u))){s=Math.ceil(s),a=Math.ceil(a),A=Math.ceil(A),c=Math.ceil(c),l=Math.ceil(l),u=Math.ceil(u);const g=s>1?u6(a/s,0,1,ui):1,h=s>1?u6(A/s,0,1,ui):1,d=c>1?u6(l/c,0,1,ui):1,p=c>1?u6(u/c,0,1,ui):1;i=eg(i,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:g,$prev_pageview_max_scroll:A,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:l,$prev_pageview_last_content_percentage:d,$prev_pageview_max_content:u,$prev_pageview_max_content_percentage:p})}}return o.pathname&&(i.$prev_pageview_pathname=o.pathname),o.timestamp&&(i.$prev_pageview_duration=(e.getTime()-o.timestamp.getTime())/1e3),i}};const q$=["flags","surveys"],_Go={[MOo]:{exposure:"hidden"},[Bge]:{exposure:"hidden"},[DOo]:{exposure:"hidden"},[eNe]:{exposure:"hidden"},[jO]:{exposure:"hidden"},[F$]:{exposure:"hidden"},[kHt]:{exposure:"event"},[tNe]:{exposure:"hidden"},[LHt]:{exposure:"hidden"},[nNe]:{exposure:"event"},[FHt]:{exposure:"hidden"},[oNe]:{exposure:"event"},[iNe]:{exposure:"event"},[rNe]:{exposure:"event"},[sNe]:{exposure:"hidden"},[HHt]:{exposure:"event"},[L$]:{exposure:"hidden"},[NOo]:{exposure:"hidden"},[$O]:{exposure:"hidden"},[OHt]:{exposure:"event"},[ROo]:{exposure:"event",shouldSkipFromEventProperties:t=>Id(t)},[HOo]:{exposure:"event"},[OOo]:{exposure:"event"},[GOo]:{exposure:"event"},[YOo]:{exposure:"event"},[UOo]:{exposure:"hidden"},[TB]:{exposure:"hidden",storageGroup:"flags"},[Yb]:{exposure:"hidden",storageGroup:"flags"},[aNe]:{exposure:"hidden"},[CR]:{exposure:"hidden",storageGroup:"flags"},[Dw]:{exposure:"hidden",storageGroup:"flags"},[yR]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[H$]:{exposure:"hidden",storageGroup:"flags"},[g6]:{exposure:"hidden"},[xR]:{exposure:"hidden"},[Nw]:{exposure:"hidden"},[Rw]:{exposure:"hidden"},[O$]:{exposure:"hidden",storageGroup:"surveys"},[bge]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[YHt]:{exposure:"event"},[UHt]:{exposure:"hidden"},[KHt]:{exposure:"hidden"},[ANe]:{exposure:"hidden"},[KOo]:{exposure:"hidden"},[VOo]:{exposure:"hidden"},[zOo]:{exposure:"event"},[JOo]:{exposure:"event"},[WOo]:{exposure:"event"},[jOo]:{exposure:"event"},[Tw]:{exposure:"hidden"},[G$]:{exposure:"hidden"},[GHt]:{exposure:"event"},[Y$]:{exposure:"hidden"},[kw]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[qy]:{exposure:"hidden"},[cNe]:{exposure:"hidden"},[$Oo]:{exposure:"hidden"},[VHt]:{exposure:"hidden"},[zHt]:{exposure:"hidden"},[qO]:{exposure:"hidden"},[lNe]:{exposure:"hidden"},[TOo]:{exposure:"event"},[kOo]:{exposure:"event"},[FOo]:{exposure:"event"},[LOo]:{exposure:"event"},[WHt]:{exposure:"event"},[jHt]:{exposure:"event"},[gNe]:{exposure:"hidden"},[dNe]:{exposure:"hidden"},[$Ht]:{exposure:"hidden"},[qHt]:{exposure:"hidden"},[XHt]:{exposure:"hidden"},[ZHt]:{exposure:"hidden"},[eOt]:{exposure:"hidden"},[tOt]:{exposure:"hidden"},[nOt]:{exposure:"hidden"},[qOo]:{exposure:"event"}},fGo=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],i1=t=>{const e=_Go[t];if(e)return e;for(const[n,o]of fGo)if(t.indexOf(n)===0)return o},oG=(t,e)=>{try{let n;return JSON.stringify(t,(o,i)=>{var r;return zO(i)?((r=n)!==null&&r!==void 0||(n=new WeakMap),n.has(i)||n.set(i,aOt(i)),n.get(i)):typeof i=="bigint"?i.toString():i},e)}catch{return hLt(t)}},Kb=t=>{const e=No?.createElement("a");return Eo(e)?null:(e.href=t,e)},iG=function(t,e){const n=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&");let o;for(let i=0;n.length>i;i++){const r=n[i].split("=");if(r[0]===e){o=r;break}}if(!As(o)||2>o.length)return"";{let i=o[1];try{i=decodeURIComponent(i)}catch{ui.error("Skipping decoding for malformed query param: "+i)}return i.replace(/\+/g," ")}},X$=function(t,e,n){if(!t||!e||!e.length)return t;const o=t.split("#"),i=o[1],r=(o[0]||"").split("?"),s=r[1],a=r[0],A=(s||"").split("&"),c=[];for(let u=0;A.length>u;u++){const g=A[u].split("=");As(g)&&(e.includes(g[0])?c.push(g[0]+"="+n):c.push(A[u]))}let l=a;return s!=null&&(l+="?"+c.join("&")),i!=null&&(l+="#"+i),l},Mge=function(t,e){const n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},kOt=(t,e)=>t>=e&&dLt(),FOt=(t,e,n,o)=>{if(t===0){if(dLt()){const i=e+1;return i===n&&o(),i}return e}return 0},rG=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx"],IGo=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...rG],Z$="<masked>",CGo=["li_fat_id"];function LOt(t,e,n){if(!No)return{};const o=e?[...rG,...n||[]]:[],i=HOt(X$(No.URL,o,Z$),t),r=(function(){const s={};return kl(CGo,function(a){const A=K$(a);s[a]=A||null}),s})();return eg(r,i)}function HOt(t,e){const n=IGo.concat(e||[]),o={};return kl(n,function(i){const r=iG(t,i);o[i]=r||null}),o}function OOt(t){const e=(function(i){return i?i.search("https?://(.*)google.([^/?]*)")===0?"google":i.search("https?://(.*)bing.com")===0?"bing":i.search("https?://(.*)yahoo.com")===0?"yahoo":i.search("https?://(.*)duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",o={};if(!Id(e)){o.$search_engine=e;const i=No?iG(No.referrer,n):"";i.length&&(o.ph_keyword=i)}return o}function GOt(){return navigator.language||navigator.userLanguage}function yGo(){const t=GOt();return typeof t=="string"?t.split("-")[0]:void 0}const Dge="$direct";function YOt(){return No?.referrer||Dge}function UOt(t,e,n=!1){const o=t?[...rG,...e||[]]:[],i=n?Mw(fd?.href):fd?.href,r=i?.substring(0,1e3);return{r:YOt().substring(0,1e3),u:r?X$(r,o,Z$):void 0}}function KOt(t,e=!1){var n;const{r:o,u:i}=t,r=e?Mw(i):i,s={$referrer:o,$referring_domain:o==null?void 0:o==Dge?Dge:(n=Kb(o))===null||n===void 0?void 0:n.host};if(r){s.$current_url=r;const a=Kb(r);s.$host=a?.host,s.$pathname=a?.pathname;const A=HOt(r);eg(s,A)}if(o){const a=OOt(o);eg(s,a)}return s}function VOt(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function xGo(){try{return new Date().getTimezoneOffset()}catch{return}}const EGo={flags:kw,surveys:bge},BGo=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Nge=t=>`${t}_cookie_identity_change_pending`,Rge=t=>{let e="",n=0;for(const o of t){const i=encodeURIComponent(JSON.stringify(o).slice(1,-1)).length;if(n+i>1e3)break;e+=o,n+=i}return e},o_="main",Vb=[TB,Yb,CR,Dw,yR,kw,H$,Nw],MNe=t=>Vb.indexOf(t)!==-1,zOt=[jO,F$],JOt=t=>zOt.indexOf(t)!==-1,Fw=(t,e)=>{try{return JSON.stringify(t)===JSON.stringify(e)}catch{return t===e}},sG=t=>{if(!t)return{};const e=JSON.parse(t);return QA(e)?e:{}},WOt=(t,e)=>{kl(t,(n,o)=>{const i=i1(o);i&&i.exposure!=="event"||{}.hasOwnProperty.call(e,o)||delete t[o]})};var DNe=class{constructor(e,n,o=!0,i=!e.cookieless_mode){if(this.Jo={},this.Zo=!1,this.Ko=!1,this.Xo=!1,this.Yo=!1,this.ta=!1,this.ea=new Map,this.ia=!1,this.na=!1,this.sa=!1,this.ra=new Set,this.oa=new Set,this.Mr=e,this.aa=o,this.props={},this.la=void 0,this.ua=(r=>{let s="";return r.token&&(s=r.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),r.persistence_name?"ph_"+r.persistence_name:"ph_"+s+"_posthog"})(e),this.hi=e.disable_persistence||!!n,this.No=this.ha(e),this.Xo=this.ca(e),this.load(i),this.da(),e.debug&&ui.info("Persistence loaded",e.persistence,sn({},this.props)),this.update_config(e,e,n),this.save(),Fn){const r=()=>this.flush();el(Fn,"beforeunload",r,{capture:!1}),el(Fn,"pagehide",r,{capture:!1}),this.va=s=>{if(this.Zo&&(!s.storageArea||s.storageArea===Fn?.localStorage)&&s.key)if(s.key!==this.ua){if(this.Xo){const a=q$.find(A=>s.key===this.fa(A));a&&this.pa(s.key,a)}}else this.pa(s.key,o_)},el(Fn,"storage",this.va)}}markCrossTabFeatureFlagChanges(e){Object.entries(e).forEach(([n,o])=>{const i=this.ea.get(n);if(!MNe(n)||i===!0)return;if(o===!0)return void this.ga(n,!0);const r=new Set(i||[]);o.forEach(s=>r.add(s)),r.size&&this.ga(n,r)})}onCrossTabFeatureFlagChange(e){return this.oa.add(e),()=>this.oa.delete(e)}destroy(){this.va&&Fn&&(Fn.removeEventListener("storage",this.va),this.va=void 0),this.oa.clear()}pa(e,n,o=!0){if(this.hi)return!1;let i,r;try{if(r=hc.Ot(e),Id(r)){const A=this.ma(n);return A.storageValue=null,n!==o_&&(A.persisted=!1),!1}i=sG(r)}catch{return!1}const s=n===o_?i:hc.Lt(this.ua);if(s&&this.ya(s))return!1;const a=this.ba(i,n,o);return n===o_&&this.Xo&&!Fw(this._a().main,i)||this.wa(i,n,!0,r),a}ya(e){const n=this.props[RB],o=e[RB];return!Eo(n)&&!Eo(o)&&n!==o}wa(e,n,o,i){const r=this.ma(n);r.storageValue=i,n!==o_&&(r.persisted=o);try{r.fingerprint=this.ka(e,n)}catch{r.fingerprint=void 0}}ba(e,n,o){let i=!1;return Vb.forEach(r=>{var s;const a=(s=i1(r))===null||s===void 0?void 0:s.storageGroup;if(n===o_&&this.Xo&&a||n!==o_&&a!==n)return;const A=r in e,c=this.Sa(r,A?e[r]:void 0),l=this.ea.has(r)?r in this.props:A;l===r in this.props&&Fw(c,this.props[r])||(l?this.xa(r,c,!1):this.$a(r,!1),i=!0)}),i&&o&&this.oa.forEach(r=>r()),i}Ca(){if(!this.Zo)return!1;try{this.sa=!1;const e=hc.Ot(this.ua),n=this.ma(o_);let o,i=!1,r=!1;if(e!==n.storageValue)if(Id(e))n.storageValue=null;else{if(o=sG(e),this.sa=!this.na&&this.ya(o),this.sa)return!1;r=this.ba(o,o_,!1),!this.Xo||Fw(this._a().main,o)?this.wa(o,o_,!0,e):n.storageValue=e,i=!0}return this.Xo&&q$.forEach(s=>{const a=hc.Ot(this.fa(s)),A=this.ma(s),c=o||{},l=i&&Vb.some(g=>{var h;return((h=i1(g))===null||h===void 0?void 0:h.storageGroup)===s&&g in c});if(a===A.storageValue&&!l)return;if(Id(a))return A.storageValue=null,A.persisted=!1,void(l&&(r=this.ba(c,s,!1)||r));const u=sG(a);r=this.ba(u,s,!1)||r,this.wa(u,s,!0,a)}),r}catch{return!1}}ga(e,n){this.ea.set(e,n);const o=i1(e);o?.volatile||(this.ma((this.Xo?o?.storageGroup:void 0)||o_).fingerprint=void 0,this.Ta(e))}Ia(){Vb.forEach(e=>this.ea.set(e,!0))}da(){if(this.Zo)try{const e=hc.Ot(this.ua),n=sG(e);this.ma(o_).storageValue=e,Vb.forEach(o=>{var i;const r=this.Xo?(i=i1(o))===null||i===void 0?void 0:i.storageGroup:void 0,s=r?hc.Ot(this.fa(r)):null;if(r){const A=this.ma(r);A.storageValue=s,A.persisted=!Id(s)}const a=r&&!Id(s)?sG(s):n;o in this.props?this.Ma(o,a[o],this.props[o]):o in a&&this.ga(o,!0)})}catch{}}Sa(e,n){const o=this.ea.get(e);if(!o)return n;if(o===!0)return this.props[e];if(e==="$active_feature_flags"){const s=new Set(As(n)?n:[]),a=new Set(As(this.props[e])?this.props[e]:[]);return o.forEach(A=>a.has(A)?s.add(A):s.delete(A)),Array.from(s)}const i=QA(n)?sn({},n):{},r=QA(this.props[e])?this.props[e]:{};return o.forEach(s=>{s in r?i[s]=r[s]:delete i[s]}),i}Ma(e,n,o){if(!MNe(e))return;const i=this.ea.get(e);if(i===!0)return;let r=n;if(this.Zo)try{var s;const A=this.Xo?(s=i1(e))===null||s===void 0?void 0:s.storageGroup:void 0,c=A?this.fa(A):this.ua;r=sG(hc.Ot(c))[e]}catch{}const a=new Set(i||[]);if(e==="$active_feature_flags"){if(!Eo(n)&&!As(n)||!Eo(r)&&!As(r)||!As(o))return void this.ga(e,!0);const A=new Set(n||[]),c=new Set(r||[]),l=new Set(o);new Set([...A,...l]).forEach(u=>{A.has(u)!==l.has(u)&&a.add(u)}),a.forEach(u=>{c.has(u)===l.has(u)&&a.delete(u)})}else{if(!QA(o))return void(Fw(r,o)?this.ea.delete(e):this.ga(e,!0));{if(!Eo(n)&&!QA(n)||Eo(n)&&Rx(o)&&Eo(r))return void this.ga(e,!0);const A=QA(n)?n:{},c=QA(r)?r:{};new Set([...Object.keys(A),...Object.keys(o)]).forEach(l=>{l in A==l in o&&Fw(A[l],o[l])||a.add(l)}),a.forEach(l=>{l in c==l in o&&Fw(c[l],o[l])&&a.delete(l)})}}a.size?this.ga(e,a):this.ea.delete(e)}Ea(){var e;const n=(e=this.Mr)===null||e===void 0?void 0:e.persistence_save_debounce_ms;return Ah(n)&&n>0?n:0}Pa(e){if(this.Mr.cookieWinsOnConflict&&this.Mr.persistence.toLowerCase()==="localstorage+cookie")if(e)try{const n=yNe(e,this.Mr.cookie_persisted_properties||[]),o=uOt(n,this.Mr.cookie_persisted_properties||[]),i=JSON.stringify(n)+"|"+JSON.stringify(o),r=yd.Ot(this.ua)||void 0;r&&xNe(this.ua,r)===i&&(this.Ra=i,this.Aa=r)}catch{}else try{const n=yd.Ot(this.ua)||void 0;this.Ra=n?xNe(this.ua,n):void 0,this.Aa=n}catch{}}syncCookieProperties(){return this.Oa(this.Mr)}Oa(e,n=!1){if(this.hi&&!n||this.ta||!e.cookieWinsOnConflict||e.persistence.toLowerCase()!=="localstorage+cookie")return!1;let o;try{o=yd.Ot(this.ua)||void 0}catch{}if(!o||o===this.Aa)return!1;const i=xNe(this.ua,o);let r;try{r=CNe(JSON.parse(o))}catch{return!1}if((yd.Ot(this.ua)||void 0)!==o)return!1;this.Ra=i,this.Aa=o;const s=gOt(this.ua,o),a=[...ER,...s.properties],A={};if(Object.keys(r).forEach(m=>{const _=r[m];(Eo(_)||Id(_)||_===""||m==="$user_state"&&_!=="anonymous"&&_!=="identified")&&(A[m]=!0,delete r[m])}),Rx(r))return!1;const c="distinct_id"in r||r.$user_state==="anonymous"||r.$user_state==="identified",l=this.props,u=l[RB],g=l[qy],h=eg({},l);[...ER,...e.cookie_persisted_properties||[]].forEach(m=>{if(a.indexOf(m)!==-1&&!(m in r)&&!A[m]&&(c||m!=="distinct_id"&&m!=="$user_state")){const _=h[m];(s.isValid||ER.indexOf(m)===-1||_!==!1&&_!==0)&&delete h[m]}}),this.props=eg(h,r),Vb.forEach(m=>{const _=m in this.props;m in l===_&&Fw(l[m],this.props[m])||(_?this.Ma(m,l[m],this.props[m]):this.ga(m,!0))}),!c||"$user_state"in r||"$user_state"in this.props||this.xa(qy,Ub);const d=this.props[RB],p=this.props[qy];return!c||d===u&&p===g||(this.na=!0,this.Yo=!0,nu.$t(Nge(this.ua),!0),this.$a(Nw),this.$a(Yb),this.$a(TB),this.$a(CR),this.$a(Dw),this.$a(yR),this.$a(kw),this.$a(Y$),this.$a(Tw),p!=="anonymous"||g!=="identified"&&r.$user_state!=="anonymous"&&(Eo(u)||d===u)||(WOt(this.props,r),this.$a(Rw)),p==="identified"?this.props.$user_id=d:delete this.props.$user_id,this.$a(Bge)),!0}consumeCookieIdentityChange(){const e=Nge(this.ua),n=this.Yo||!!nu.Ot(e);return this.Yo=!1,n&&nu.Pt(e),n}Fa(e=!1){return!(this.ta||this.hi&&!e||!this.Mr.cookieWinsOnConflict||this.Mr.persistence.toLowerCase()!=="localstorage+cookie"||(this.ta=!0,0))}Da(){this.ta&&(Eo(this.La)||(clearTimeout(this.La),this.La=void 0),delete this.Jo[o_],this.Na(!0))}qa(e=!0){if(this.ta)try{e?this.Da():Eo(this.La)||(clearTimeout(this.La),this.La=void 0)}finally{this.ta=!1}}isDisabled(){return!!this.hi}ha(e){BGo.indexOf(e.persistence.toLowerCase())===-1&&(ui.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");const n=((a=[],A=!1,c=()=>!1)=>{const l=[...ER,...a];return sn(sn({},hc),{},{Lt(u){try{let h,d={};try{h=yd.Ot(u)||void 0,d=h?CNe(JSON.parse(h)):{}}catch{}const p=JSON.parse(hc.Ot(u)||"{}");let m;if(A){const _=gOt(u,h),f=[...ER,..._.properties],I={};Object.keys(d).forEach(y=>{const x=d[y];Id(x)||x===""||y==="$user_state"&&x!=="anonymous"&&x!=="identified"||(I[y]=x)});const C="distinct_id"in I||I.$user_state==="anonymous"||I.$user_state==="identified";if(Object.keys(I).length>0){var g;const y=p[RB],x=(g=p.$user_state)!==null&&g!==void 0?g:Ub;l.forEach(E=>{if(f.indexOf(E)!==-1&&!(E in d)&&(C||E!=="distinct_id"&&E!=="$user_state")){const B=p[E];(_.isValid||ER.indexOf(E)===-1||B!==!1&&B!==0)&&delete p[E]}}),!C||"$user_state"in d||"$user_state"in p||(p[qy]=Ub),!C||("distinct_id"in I?I[RB]:p[RB])===y&&("$user_state"in I?I[qy]:p[qy])===x||(INe.forEach(E=>delete p[E]),I.$user_state==="identified"&&"distinct_id"in I?p.$user_id=I[RB]:delete p.$user_id,I.$user_state!=="identified"&&(delete p[GHt],delete p[Rw]),delete p.__alias)}m=eg(p,I)}else m=eg(d,p);return c()||hc.$t(u,m),m}catch{}return null},$t(u,g,h,d,p,m){const _=hc.$t(u,g,void 0,void 0,m);try{const f=yNe(g,a);if(Object.keys(f).length){if(A){const I=wge(u),C=uOt(f,a);if(yd.$t(I,C,h,d,p,m),yd.Ot(I)!==JSON.stringify(C)){yd.Pt(I,d);const y=yNe(g);return yd.$t(u,y,h,d,p,m),_}}yd.$t(u,f,h,d,p,m)}}catch(f){hc.Dt(f)}return _},Pt(u,g){try{Fn?.localStorage.removeItem(u),yd.Pt(u,g),yd.Pt(wge(u),g)}catch(h){hc.Dt(h)}}})})(e.cookie_persisted_properties||[],e.cookieWinsOnConflict,()=>!!this.hi);let o,i=!1,r=!1;const s=e.persistence.toLowerCase();return s==="localstorage"&&hc.Et()?(o=hc,r=!0):s==="localstorage+cookie"&&n.Et()?(o=n,r=!0,i=!0):s==="sessionstorage"&&nu.Et()?o=nu:s==="memory"?o=ENe:s==="cookie"&&yd.Et()?(o=yd,i=!0):n.Et()?(o=n,r=!0,i=!0):yd.Et()?(o=yd,i=!0):o=ENe,this.Zo=r,this.Ko=i,o}fa(e){return`${this.ua}__${e}`}ca(e){return this.Zo&&!!e.split_storage}properties(){const e={};return kl(this.props,(n,o)=>{const i=i1(o);if(!i||i.exposure==="event"){var r;if(!(i==null||(r=i.shouldSkipFromEventProperties)===null||r===void 0)&&r.call(i,n))return;e[o]=n}}),e}load(e=!1){if(this.hi&&!e)return;const n=this.Mr.cookieWinsOnConflict&&this.Mr.persistence.toLowerCase()==="localstorage+cookie",o=n?hc.Lt(this.ua):null;let i={};if(n)try{i=CNe(yd.Lt(this.ua)),kl(i,(A,c)=>{(Eo(A)||Id(A)||A==="")&&delete i[c]})}catch{}const r=this.No.Lt(this.ua);if(r&&(this.props=eg({},r)),this.Xo&&this.ja(),n&&r){var s,a;const A=o?.[RB],c=(s=o?.$user_state)!==null&&s!==void 0?s:Ub,l=r[RB],u=(a=r.$user_state)!==null&&a!==void 0?a:Ub;if(l!==A||u!==c){this.Yo=!0,this.hi||nu.$t(Nge(this.ua),!0);const g=eg({},this.props);INe.forEach(d=>delete g[d]),u!=="anonymous"||c!=="identified"&&i.$user_state!=="anonymous"&&(Eo(A)||l===A)||(WOt(g,i),delete g[Rw]),this.props=g;const h=new Set;INe.forEach(d=>{var p;const m=(p=i1(d))===null||p===void 0?void 0:p.storageGroup;m&&h.add(m)}),h.forEach(d=>{if(this.hi)return;const p={};kl(this.props,(m,_)=>{var f;((f=i1(_))===null||f===void 0?void 0:f.storageGroup)===d&&(p[_]=m)}),Rx(p)?(hc.Pt(this.fa(d)),this.Jo[d]={}):hc.$t(this.fa(d),p)&&(this.Jo[d]={persisted:!0,fingerprint:this.ka(p,d)})})}}nu.Ot(Nge(this.ua))&&(this.Yo=!0)}ja(){for(const e of q$){const n=hc.Lt(this.fa(e));if(n&&!Rx(n)){const o=this.ma(e);o.persisted=!0,this.Ba(e)||(o.fingerprint=this.ka(n,e)),this.Ha(e,n)||eg(this.props,n)}}}Ba(e){return Object.keys(this.props).some(n=>{var o;return((o=i1(n))===null||o===void 0?void 0:o.storageGroup)===e})}Ha(e,n){const o=EGo[e];if(!o)return!1;const i=n[o],r=this.props[o];return Ah(i)&&Ah(r)&&r>i}refreshKey(e){var n;if(this.hi||this.ra.has(e))return;const o=this.Xo?(n=i1(e))===null||n===void 0?void 0:n.storageGroup:void 0,i=o?hc.Lt(this.fa(o)):this.No.Lt(this.ua);if(i&&e in i)this.xa(e,i[e],!1);else{if(o){const r=this.No.Lt(this.ua);if(r&&e in r)return void this.xa(e,r[e],!1)}this.$a(e,!1)}}save(){if(this.hi)return;const e=this.Ea();e>0?Eo(this.La)&&(this.La=setTimeout(()=>{this.La=void 0,this.Na()},e)):this.Na()}flush(){Eo(this.La)||(clearTimeout(this.La),this.La=void 0,this.Na())}Na(e=!1){if(this.hi||this.ta&&!e)return;e||(this.syncCookieProperties(),this.Mr.cookieWinsOnConflict&&this.Mr.persistence.toLowerCase()==="localstorage+cookie"||zOt.forEach(r=>this.refreshKey(r)));const n=!e&&!this.ia;n||(this.sa=!1);const o=!!n&&this.Ca();if(this.sa)return void(this.Mr.debug&&ui.warn("skipping persistence write because storage belongs to a different distinct ID"));if(this.Xo)return this.za(),void(o&&this.oa.forEach(r=>r()));const i=this.Ua(this.No,this.ua,this.props,o_);i==="written"&&this.Pa(this.props),i!=="failed"&&(this.ea.clear(),this.na=!1,this.ra.clear()),o&&this.oa.forEach(r=>r())}za(){const{main:e,groups:n}=this._a(),o=this.Ua(this.No,this.ua,e,o_);o==="written"&&this.Pa(e),o!=="failed"&&(this.na=!1,this.ra.clear(),Vb.forEach(r=>{var s;!((s=i1(r))===null||s===void 0)&&s.storageGroup||this.ea.delete(r)}));for(const r of q$){var i;const s=n[r];if(Rx(s)&&!(!((i=this.Jo[r])===null||i===void 0)&&i.persisted)){Vb.forEach(A=>{var c;((c=i1(A))===null||c===void 0?void 0:c.storageGroup)===r&&this.ea.delete(A)});continue}const a=this.Ua(hc,this.fa(r),s,r);a!=="failed"&&Vb.forEach(A=>{const c=i1(A);c?.storageGroup!==r||a!=="written"&&c.volatile||this.ea.delete(A)})}}_a(){const e={},n={flags:{},surveys:{}};return kl(this.props,(o,i)=>{var r;const s=(r=i1(i))===null||r===void 0?void 0:r.storageGroup;s?n[s][i]=o:e[i]=o}),{main:e,groups:n}}ka(e,n){if(n===o_)return JSON.stringify(e)+"|"+this.Wa+"|"+this.Va+"|"+this.Ga;const o={};return kl(e,(i,r)=>{var s;o[r]=!((s=i1(r))===null||s===void 0)&&s.volatile?"__volatile__":i}),JSON.stringify(o)}Ua(e,n,o,i){const r=this.ma(i);if(i!==o_&&!r.dirty&&!Eo(r.fingerprint))return"skipped";let s;try{if(s=this.ka(o,i),s===r.fingerprint)return r.dirty=!1,"skipped"}catch{s=void 0}return e.$t(n,o,this.Wa,this.Va,this.Ga,this.Mr.debug)?(r.dirty=!1,i!==o_&&(r.persisted=!0),Eo(s)||(r.fingerprint=s),this.Zo&&(r.storageValue=hc.Ot(n)),"written"):(this.Mr.debug&&ui.warn(`failed to persist storage entry "${n}"; will retry on next save`),"failed")}remove({keepGroupEntries:e=!1}={}){if(this.Ia(),Eo(this.La)||(clearTimeout(this.La),this.La=void 0),this.No.Pt(this.ua,!1),this.No.Pt(this.ua,!0),!e&&this.aa)for(const n of q$)hc.Pt(this.fa(n));e?delete this.Jo[o_]:this.Jo={},this.Ra=void 0,this.Aa=void 0}clear(){this.remove(),this.props={}}register_once(e,n,o){if(QA(e)){this.syncCookieProperties(),Eo(n)&&(n="None"),this.Wa=Eo(o)?this.Qa:o;let i=!1;if(kl(e,(r,s)=>{this.props.hasOwnProperty(s)&&this.props[s]!==n||(this.xa(s,r),i=!0)}),i)return this.save(),!0}return!1}register(e,n){if(QA(e)){this.syncCookieProperties(),this.Wa=Eo(n)?this.Qa:n;let o=!1;if(kl(e,(i,r)=>{e.hasOwnProperty(r)&&(this.props[r]!==i||QA(i)||As(i))&&(this.xa(r,i),o=!0)}),o)return this.save(),!0}return!1}unregister(e){this.syncCookieProperties();const n=typeof e=="string"?[e]:e;let o=!1;for(const i of n)i in this.props&&(this.$a(i),o=!0);o&&this.save()}update_campaign_params(){const e=No?.URL;if(e===this.la)return;const n=LOt(this.Mr.custom_campaign_params,this.Mr.mask_personal_data_properties,this.Mr.custom_personal_data_properties),o=!Rx(mNe(n));return o&&this.register(n),this.la=e,o?n:void 0}update_search_keyword(){this.register((function(){const e=No?.referrer;return e?OOt(e):{}})())}update_referrer_info(){var e;this.register_once({$referrer:YOt(),$referring_domain:No?.referrer&&((e=Kb(No.referrer))===null||e===void 0?void 0:e.host)||Dge},void 0)}set_initial_person_info(){if(this.props.$initial_campaign_params||this.props.$initial_referrer_info)return;const e=UOt(this.Mr.mask_personal_data_properties,this.Mr.custom_personal_data_properties,this.Mr.disable_capture_url_hashes);this.register_once({[qO]:this.Ko?{r:Rge(e.r),u:e.u?Rge(e.u):void 0}:e},void 0)}get_initial_props(){const e={};kl([zHt,VHt],o=>{const i=this.props[o];i&&kl(i,function(r,s){e["$initial_"+PDe(s)]=r})});const n=this.props[qO];if(n){const o=(function(i,r=!1){const s=KOt(i,r),a={};return kl(s,function(A,c){a[`$initial_${PDe(c)}`]=A}),a})(n,this.Mr.disable_capture_url_hashes);eg(e,o)}return e}safe_merge(e){return kl(this.props,function(n,o){o in e||(e[o]=n)}),e}update_config(e,n,o){const i=e.persistence!==n.persistence,r=!((d,p)=>{if(d.length!==p.length)return!1;const m=[...d].sort(),_=[...p].sort();return m.every((f,I)=>f===_[I])})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=i||r,a=e.cookieWinsOnConflict!==n.cookieWinsOnConflict,A=e.disable_persistence||!!o,c=!!this.hi&&!A;A||this.Oa(n,c),this.Mr=e,!A&&(i||r||a)&&(this.Ra=void 0,this.Aa=void 0,this.Oa(sn(sn({},e),{},{cookie_persisted_properties:n.cookie_persisted_properties}),c));const l=s||a?this.ha(e):this.No;this.Ja();const u=this.ca(e),g=s||u!==this.Xo,h=!A&&(g||e.cross_subdomain_cookie!==this.Va||e.secure_cookie!==this.Ga)&&this.Fa(c);this.ia=g;try{if(this.Qa=this.Wa=e.cookie_expiration,this.set_disabled(A),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),g){const d=this.props;this.clear(),this.No=l,this.Xo=u,this.props=d,this.save()}else a&&(this.No=l,A||(delete this.Jo[o_],this.Na()))}finally{this.ia=!1,h&&this.qa()}}Ja(){const e=this.props[qO];if(!this.Ko||!QA(e)||typeof e.r!="string")return;const n=Rge(e.r),o=typeof e.u=="string"?Rge(e.u):e.u;n===e.r&&o===e.u||this.xa(qO,sn(sn({},e),{},{r:n,u:o}))}set_disabled(e){this.hi=e,this.hi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Va&&(this.Va=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.Ga&&(this.Ga=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){const o=this.props.__timers||{};o[e]=n,this.xa(eNe,o),this.save()}remove_event_timer(e){const n=this.props.__timers||{},o=n[e];return Eo(o)||(delete n[e],this.xa(eNe,n),this.save()),o}get_property(e){return this.props[e]}set_property(e,n){this.xa(e,n),this.save()}xa(e,n,o=!0){var i;const r=this.props[e];this.props[e]=n,o&&(e!=="distinct_id"&&e!=="$user_state"||r===n||(this.na=!0),JOt(e)&&!Fw(r,n)&&this.ra.add(e),this.Ma(e,r,n),!((i=i1(e))===null||i===void 0)&&i.volatile||this.Ta(e))}$a(e,n=!0){delete this.props[e],n&&(MNe(e)&&this.ga(e,!0),JOt(e)&&this.ra.add(e),this.Ta(e))}Ta(e){var n;const o=(n=i1(e))===null||n===void 0?void 0:n.storageGroup;o&&(this.ma(o).dirty=!0)}ma(e){return this.Jo[e]||(this.Jo[e]={})}};const gE={GZipJS:"gzip-js",Base64:"base64"},eq={Activation:"events",Cancellation:"cancelEvents"},NNe={Popover:"popover",API:"api",Widget:"widget"},dE={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},RNe={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},TNe={Popover:"popover",Inline:"inline"};function Tge(t){let e=!0;return{dispose(){if(e){e=!1;const n=t();n&&nf(n.then)&&n.then(void 0,()=>{})}}}}const bGo={SHOWN:"product tour shown"},jOt={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},$Ot=Cd("[RateLimiter]");var SGo=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{const o=n.text;if(o&&o.length)try{(JSON.parse(o).quota_limited||[]).forEach(i=>{$Ot.info(`${i||"events"} is quota limited.`),this.serverLimits[i]=new Date().getTime()+6e4})}catch(i){return void $Ot.warn(`could not rate limit - continuing. Error: "${i?.message}"`,{text:o})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)===null||e===void 0?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)===null||e===void 0?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e=!1){var n,o,i;const{captureEventsBurstLimit:r,captureEventsPerSecond:s}=this,a=new Date().getTime(),A=(n=(o=this.instance.persistence)===null||o===void 0?void 0:o.get_property("$capture_rate_limit"))!==null&&n!==void 0?n:{tokens:r,last:a};A.tokens+=(a-A.last)/1e3*s,A.last=a,A.tokens>r&&(A.tokens=r);const c=1>A.tokens;if(c||e||(A.tokens=Math.max(0,A.tokens-1)),c&&!e){const l=(Ah(A.dropped)?A.dropped:0)+1;A.dropped=l,!this.lastEventRateLimited&&this.Za(l)&&(A.dropped=0)}return this.lastEventRateLimited=c,(i=this.instance.persistence)===null||i===void 0||i.set_property("$capture_rate_limit",A),{isRateLimited:c,remainingTokens:A.tokens}}Ka(e){const n=this.instance.config.property_denylist;return!As(n)||!n.includes(e)}Xa(){var e;if(this.Ka("$current_url")&&this.Ka("$pathname")&&fd?.pathname)return`${(e=fd.origin)!==null&&e!==void 0?e:""}${fd.pathname}`}Za(e){var n,o;const{captureEventsBurstLimit:i,captureEventsPerSecond:r}=this,s=this.Xa(),a=this.Ka("$session_id")?(n=(o=this.instance).get_session_id)===null||n===void 0?void 0:n.call(o):void 0,A=[`${e} event(s) dropped since the last warning`,s?`triggered on ${s}`:void 0,a?`session ${a}`:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:`posthog-js client rate limited: ${A}. Config is set to ${r} events per second and ${i} events burst limit.`},{skip_client_rate_limiting:!0})}isServerRateLimited(e){const n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()<n}};const Lw=Cd("[RemoteConfig]");var qOt=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=Vr._POSTHOG_REMOTE_CONFIG)===null||e===void 0||(e=e[this._instance.config.token])===null||e===void 0?void 0:e.config}Ya(e){var n,o,i;!((n=Vr.__PosthogExtensions__)===null||n===void 0)&&n.loadExternalDependency?(o=Vr.__PosthogExtensions__)===null||o===void 0||(i=o.loadExternalDependency)===null||i===void 0||i.call(o,this._instance,"remote-config",()=>e(this.remoteConfig)):e()}tl(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets",`/array/${this._instance.config.token}/config`),callback:e})}load(){try{if(this.remoteConfig)return Lw.info("Using preloaded remote config",this.remoteConfig),void this.el(this.remoteConfig);if(this._instance.il())return void Lw.warn("Remote config is disabled. Falling back to local config.");this.Ya(e=>{if(!e)return Lw.info("No config found after loading remote JS config. Falling back to JSON."),void this.tl(n=>{this.el(n.json,n)});this.el(e)})}catch(e){Lw.error("Error loading remote config",e),this.el()}}el(e,n){!e&&n&&(n.statusCode===0?n.error||Lw.warn("Failed to fetch remote config from PostHog."):Lw.error("Failed to fetch remote config from PostHog."));try{this._instance.el(e?{ok:!0,config:e}:{ok:!1})}catch(i){Lw.error("Error applying remote config",i)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var o;(o=this._instance.featureFlags)===null||o===void 0||o.ensureFlagsLoaded()}catch(i){Lw.error("Error loading feature flags",i)}}},a4=Uint8Array,Tx=Uint16Array,aG=Uint32Array,kNe=new a4([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),FNe=new a4([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),XOt=new a4([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ZOt=function(t,e){for(var n=new Tx(31),o=0;31>o;++o)n[o]=e+=1<<t[o-1];var i=new aG(n[30]);for(o=1;30>o;++o)for(var r=n[o];n[o+1]>r;++r)i[r]=r-n[o]<<5|o;return[n,i]},eGt=ZOt(kNe,2),LNe=eGt[1];eGt[0][28]=258,LNe[258]=28;for(var tGt=ZOt(FNe,0)[1],nGt=new Tx(32768),xd=0;32768>xd;++xd){var AG=(43690&xd)>>>1|(21845&xd)<<1;nGt[xd]=((65280&(AG=(61680&(AG=(52428&AG)>>>2|(13107&AG)<<2))>>>4|(3855&AG)<<4))>>>8|(255&AG)<<8)>>>1}var tq=function(t,e,n){for(var o=t.length,i=0,r=new Tx(e);o>i;++i)++r[t[i]-1];var s,a=new Tx(e);for(i=0;e>i;++i)a[i]=a[i-1]+r[i-1]<<1;for(s=new Tx(o),i=0;o>i;++i)s[i]=nGt[a[t[i]-1]++]>>>15-t[i];return s},bR=new a4(288);for(xd=0;144>xd;++xd)bR[xd]=8;for(xd=144;256>xd;++xd)bR[xd]=9;for(xd=256;280>xd;++xd)bR[xd]=7;for(xd=280;288>xd;++xd)bR[xd]=8;var kge=new a4(32);for(xd=0;32>xd;++xd)kge[xd]=5;var QGo=tq(bR,9),vGo=tq(kge,5),oGt=function(t){return(t/8|0)+(7&t&&1)},iGt=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var o=new(t instanceof Tx?Tx:t instanceof aG?aG:a4)(n-e);return o.set(t.subarray(e,n)),o},zb=function(t,e,n){var o=e/8|0;t[o]|=n<<=7&e,t[o+1]|=n>>>8},nq=function(t,e,n){var o=e/8|0;t[o]|=n<<=7&e,t[o+1]|=n>>>8,t[o+2]|=n>>>16},HNe=function(t,e){for(var n=[],o=0;t.length>o;++o)t[o]&&n.push({s:o,f:t[o]});var i=n.length,r=n.slice();if(!i)return[new a4(0),0];if(i==1){var s=new a4(n[0].s+1);return s[n[0].s]=1,[s,1]}n.sort(function(y,x){return y.f-x.f}),n.push({s:-1,f:25001});var a=n[0],A=n[1],c=0,l=1,u=2;for(n[0]={s:-1,f:a.f+A.f,l:a,r:A};l!=i-1;)a=n[n[u].f>n[c].f?c++:u++],A=n[c!=l&&n[u].f>n[c].f?c++:u++],n[l++]={s:-1,f:a.f+A.f,l:a,r:A};var g=r[0].s;for(o=1;i>o;++o)r[o].s>g&&(g=r[o].s);var h=new Tx(g+1),d=ONe(n[l-1],h,0);if(d>e){o=0;var p=0,m=d-e,_=1<<m;for(r.sort(function(y,x){return h[x.s]-h[y.s]||y.f-x.f});i>o;++o){var f=r[o].s;if(e>=h[f])break;p+=_-(1<<d-h[f]),h[f]=e}for(p>>>=m;p>0;){var I=r[o].s;e>h[I]?p-=1<<e-h[I]++-1:++o}for(;o>=0&&p;--o){var C=r[o].s;h[C]==e&&(--h[C],++p)}d=e}return[new a4(h),d]},ONe=function(t,e,n){return t.s==-1?Math.max(ONe(t.l,e,n+1),ONe(t.r,e,n+1)):e[t.s]=n},rGt=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Tx(++e),o=0,i=t[0],r=1,s=function(A){n[o++]=A},a=1;e>=a;++a)if(t[a]==i&&a!=e)++r;else{if(!i&&r>2){for(;r>138;r-=138)s(32754);r>2&&(s(r>10?r-11<<5|28690:r-3<<5|12305),r=0)}else if(r>3){for(s(i),--r;r>6;r-=6)s(8304);r>2&&(s(r-3<<5|8208),r=0)}for(;r--;)s(i);r=1,i=t[a]}return[n.subarray(0,o),e]},oq=function(t,e){for(var n=0,o=0;e.length>o;++o)n+=t[o]*e[o];return n},GNe=function(t,e,n){var o=n.length,i=oGt(e+2);t[i]=255&o,t[i+1]=o>>>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var r=0;o>r;++r)t[i+r+4]=n[r];return 8*(i+4+o)},sGt=function(t,e,n,o,i,r,s,a,A,c,l){zb(e,l++,n),++i[256];for(var u=HNe(i,15),g=u[0],h=u[1],d=HNe(r,15),p=d[0],m=d[1],_=rGt(g),f=_[0],I=_[1],C=rGt(p),y=C[0],x=C[1],E=new Tx(19),B=0;f.length>B;++B)E[31&f[B]]++;for(B=0;y.length>B;++B)E[31&y[B]]++;for(var S=HNe(E,7),Q=S[0],w=S[1],M=19;M>4&&!Q[XOt[M-1]];--M);var k,R,F,O,U=c+5<<3,Y=oq(i,bR)+oq(r,kge)+s,W=oq(i,g)+oq(r,p)+s+14+3*M+oq(E,Q)+(2*E[16]+3*E[17]+7*E[18]);if(Y>=U&&W>=U)return GNe(e,l,t.subarray(A,A+c));if(zb(e,l,1+(Y>W)),l+=2,Y>W){k=tq(g,h),R=g,F=tq(p,m),O=p;var te=tq(Q,w);for(zb(e,l,I-257),zb(e,l+5,x-1),zb(e,l+10,M-4),l+=14,B=0;M>B;++B)zb(e,l+3*B,Q[XOt[B]]);l+=3*M;for(var j=[f,y],J=0;2>J;++J){var oe=j[J];for(B=0;oe.length>B;++B)zb(e,l,te[ie=31&oe[B]]),l+=Q[ie],ie>15&&(zb(e,l,oe[B]>>>5&127),l+=oe[B]>>>12)}}else k=QGo,R=bR,F=vGo,O=kge;for(B=0;a>B;++B)if(o[B]>255){var ie;nq(e,l,k[257+(ie=o[B]>>>18&31)]),l+=R[ie+257],ie>7&&(zb(e,l,o[B]>>>23&31),l+=kNe[ie]);var ne=31&o[B];nq(e,l,F[ne]),l+=O[ne],ne>3&&(nq(e,l,o[B]>>>5&8191),l+=FNe[ne])}else nq(e,l,k[o[B]]),l+=R[o[B]];return nq(e,l,k[256]),l+R[256]},wGo=new aG([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),PGo=(function(){for(var t=new aG(256),e=0;256>e;++e){for(var n=e,o=9;--o;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),YNe=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function MGo(t,e){e===void 0&&(e={});var n=(function(){var u=4294967295;return{p(g){for(var h=u,d=0;g.length>d;++d)h=PGo[255&h^g[d]]^h>>>8;u=h},d(){return 4294967295^u}}})(),o=t.length;n.p(t);var i,r,s,a,A,c=(a=10+((i=e).filename&&i.filename.length+1||0),A=8,(function(u,g,h,d,p,m){var _=u.length,f=new a4(d+_+5*(1+Math.floor(_/7e3))+p),I=f.subarray(d,f.length-p),C=0;if(!g||8>_)for(var y=0;_>=y;y+=65535){var x=y+65535;_>x?C=GNe(I,C,u.subarray(y,x)):(I[y]=m,C=GNe(I,C,u.subarray(y,_)))}else{for(var E=wGo[g-1],B=E>>>13,S=8191&E,Q=(1<<h)-1,w=new Tx(32768),M=new Tx(Q+1),k=Math.ceil(h/3),R=2*k,F=function(Ce){return(u[Ce]^u[Ce+1]<<k^u[Ce+2]<<R)&Q},O=new aG(25e3),U=new Tx(288),Y=new Tx(32),W=0,te=0,j=(y=0,0),J=0,oe=0;_>y;++y){var ie=F(y),ne=32767&y,le=M[ie];if(w[ne]=le,M[ie]=ne,y>=J){var ge=_-y;if((W>7e3||j>24576)&&ge>423){C=sGt(u,I,0,O,U,Y,te,j,oe,y-oe,C),j=W=te=0,oe=y;for(var _e=0;286>_e;++_e)U[_e]=0;for(_e=0;30>_e;++_e)Y[_e]=0}var ue=2,fe=0,pe=S,ye=ne-le&32767;if(ge>2&&ie==F(y-ye))for(var Me=Math.min(B,ge)-1,ve=Math.min(32767,y),he=Math.min(258,ge);ve>=ye&&--pe&&ne!=le;){if(u[y+ue]==u[y+ue-ye]){for(var Qe=0;he>Qe&&u[y+Qe]==u[y+Qe-ye];++Qe);if(Qe>ue){if(ue=Qe,fe=ye,Qe>Me)break;var Pe=Math.min(ye,Qe-2),we=0;for(_e=0;Pe>_e;++_e){var Te=y-ye+_e+32768&32767,Re=Te-w[Te]+32768&32767;Re>we&&(we=Re,le=Te)}}}ye+=(ne=le)-(le=w[ne])+32768&32767}if(fe){O[j++]=268435456|LNe[ue]<<18|tGt[fe];var Ee=31&LNe[ue],ke=31&tGt[fe];te+=kNe[Ee]+FNe[ke],++U[257+Ee],++Y[ke],J=y+ue,++W}else O[j++]=u[y],++U[u[y]]}}C=sGt(u,I,m,O,U,Y,te,j,oe,y-oe,C)}return iGt(f,0,d+oGt(C)+p)})(r=t,(s=e).level==null?6:s.level,s.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+s.mem,a,A,!0)),l=c.length;return(function(u,g){var h=g.filename;if(u[0]=31,u[1]=139,u[2]=8,u[8]=2>g.level?4:g.level==9?2:0,u[9]=3,g.mtime!=0&&YNe(u,4,Math.floor(new Date(g.mtime||Date.now())/1e3)),h){u[3]=8;for(var d=0;h.length>=d;++d)u[d+10]=h.charCodeAt(d)}})(c,e),YNe(c,l-8,n.d()),YNe(c,l-4,o),c}const DGo=!!vDe||!!P$,aGt=new WeakMap,AGt="text/plain";let UNe=0,Fge=!1;const cGt=(t,e)=>{const[n,o]=t.split("#"),[i,r]=n.split("?");if(!r)return t;const s=r.split("&").filter(a=>a.split("=")[0]!==e).join("&");return`${i}${s?`?${s}`:""}${o?`#${o}`:""}`},iq=(t,e,n=!0)=>{var o;const[i,r]=t.split("?"),s=sn({},e),a=(o=r?.split("&").map(c=>{var l;const[u,g]=c.split("="),h=n&&(l=s[u])!==null&&l!==void 0?l:g;return delete s[u],`${u}=${h}`}))!==null&&o!==void 0?o:[],A=(function(c,l="&"){let u,g;const h=[];return kl(c,function(d,p){Eo(d)||Eo(p)||p==="undefined"||(u=encodeURIComponent((m=>m instanceof File)(d)?d.name:d.toString()),g=encodeURIComponent(p),h[h.length]=g+"="+u)}),h.join(l)})(s);return A&&a.push(A),a.length>0?`${i}?${a.join("&")}`:i},KNe=t=>{if(t.nl)return t.nl;const{data:e,compression:n}=t;if(!e)return;if(n===gE.GZipJS){const i=MGo((function(r){var s=r.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(r);for(var a=new a4(r.length+(r.length>>>1)),A=0,c=function(h){a[A++]=h},l=0;s>l;++l){if(A+5>a.length){var u=new a4(A+8+(s-l<<1));u.set(a),a=u}var g=r.charCodeAt(l);128>g?c(g):2048>g?(c(192|g>>>6),c(128|63&g)):g>55295&&57344>g?(c(240|(g=65536+(1047552&g)|1023&r.charCodeAt(++l))>>>18),c(128|g>>>12&63),c(128|g>>>6&63),c(128|63&g)):(c(224|g>>>12),c(128|g>>>6&63),c(128|63&g))}return iGt(a,0,A)})(oG(e)),{mtime:0});return{contentType:AGt,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===gE.Base64){const i=(function(s){return s&&btoa(encodeURIComponent(s).replace(/%([0-9A-F]{2})/g,(a,A)=>String.fromCharCode(parseInt(A,16))))})(oG(e)),r=(s=>"data="+encodeURIComponent(typeof s=="string"?s:oG(s)))(i);return{contentType:"application/x-www-form-urlencoded",body:r,estimatedSize:new Blob([r]).size}}const o=oG(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}},lGt=t=>{const e=()=>t.transport==="sendBeacon"?{url:iq(t.url,{compression:gE.Base64}),encodedBody:KNe(sn(sn({},t),{},{compression:gE.Base64,nl:void 0}))}:{url:cGt(t.url,"compression"),encodedBody:KNe(sn(sn({},t),{},{compression:void 0,nl:void 0}))};let n;try{n=KNe(t)}catch(i){if(mHt(t.compression,iG(t.url,"compression")))return ui.error("Failed to gzip request body, sending uncompressed payload",i),e();throw i}return n&&mHt(t.compression,iG(t.url,"compression"))&&!((o=n.body)instanceof ArrayBuffer?JDe(new Uint8Array(o)):ArrayBuffer.isView(o)&&JDe(new Uint8Array(o.buffer,o.byteOffset,o.byteLength)))?(Fge=!0,e()):{url:t.url,encodedBody:n};var o},uGt=t=>{try{return lGt(t)}catch(n){var e;return ui.error(n),void((e=t.callback)===null||e===void 0||e.call(t,{statusCode:0,error:n}))}},NGo=(function(){var t=Zu(function*(e){const n=yield(function(i){return WDe.apply(this,arguments)})(oG(e.data),n_.DEBUG,{rethrow:!0});if(!n)return e;const o=yield n.arrayBuffer();return sn(sn({},e),{},{nl:{contentType:AGt,body:o,estimatedSize:o.byteLength}})});return function(e){return t.apply(this,arguments)}})(),RGo=/Failed to fetch|NetworkError|Load failed/i,gGt=t=>t?.name==="TypeError"&&RGo.test(t?.message||""),dGt=t=>{try{const e=(function(n,o=Date.now()){if(typeof n!="string"||!n)return;const i=n.trim(),r=/^\d+\s*,/.test(i)?i.slice(0,i.indexOf(",")).trim():i;if(/^\d+$/.test(r)){const A=1e3*Math.min(Number(r),300);return A>0?A:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(r))return;const s=/^\w{3} \w{3} /.test(r)?r+" GMT":r,a=Date.parse(s)-o;return Number.isFinite(a)&&a>0?Math.min(a,mge):void 0})(t());return Eo(e)?void 0:Math.min(e,3e4)}catch{return}},hGt=t=>{const e=uGt(t);if(!e)return;const n=new vDe;aGt.set(n,!0);const{url:o,encodedBody:i}=e;n.open(t.method||"GET",o,!0);const{contentType:r,body:s}=i??{};kl(t.headers,function(a,A){n.setRequestHeader(A,a)}),r&&n.setRequestHeader("Content-Type",r),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a;const A={statusCode:n.status,text:n.responseText};if(n.status===200)try{A.json=JSON.parse(n.responseText)}catch{}(a=t.callback)===null||a===void 0||a.call(t,A,dGt(()=>n.getResponseHeader("Retry-After")))}},n.send(s)},pGt=t=>{const e=uGt(t);if(!e)return;const{url:n,encodedBody:o}=e,{contentType:i,body:r,estimatedSize:s}=o??{},a=new Headers;kl(t.headers,function(d,p){a.append(p,d)}),i&&a.append("Content-Type",i);let A=null,c=!1;if(gLt){const d=new gLt;A={signal:d.signal,timeout:setTimeout(()=>{c=!0;try{d.abort(eHt("AbortError","PostHog request timed out"+((p=t.timeout)?` after ${p}ms`:"")))}catch(m){u(m)}var p},t.timeout)}}let l=!1;const u=d=>{var p;l||(l=!0,c&&d?.name==="AbortError"||gGt(d)?ui.warn(d):ui.error(d),(p=t.callback)===null||p===void 0||p.call(t,{statusCode:0,error:d}))};let g=0;const h=()=>{UNe-=g,g=0,A&&clearTimeout(A.timeout)};try{const d=sn({method:t?.method||"GET",headers:a,referrerPolicy:"strict-origin",body:r,signal:A?.signal},t.fetchOptions),p=s??(Eo(r)?0:void 0);d.keepalive=d.method==="POST"&&!t.sl&&d.keepalive!==!1&&d.body===r&&!Eo(p)&&p>=0&&52428.8>UNe+p,d.keepalive&&(g=p,UNe+=g),P$(n,d).then(m=>m.text().then(_=>{var f;if(l)return;const I={statusCode:m.status,text:_};if(m.status===200)try{I.json=JSON.parse(_)}catch(C){ui.error(C)}l=!0,h(),(f=t.callback)===null||f===void 0||f.call(t,I,dGt(()=>m.headers.get("Retry-After")))})).catch(m=>{h(),u(m)}).finally(h)}catch(d){h(),u(d)}},VNe=t=>{try{var e;const{url:n,encodedBody:o}=lGt(t),{contentType:i,body:r,estimatedSize:s}=o??{};if(!r)return;const a=r instanceof Blob?r:new Blob([r],{type:i});if(tf.sendBeacon(n,a))return;const A=As(t.data)?t.data:(e=t.data)===null||e===void 0?void 0:e.batch;if(As(A)&&A.length>1&&(s??0)>16384){const c=Math.ceil(A.length/2),l=u=>As(t.data)?u:sn(sn({},t.data),{},{batch:u});return VNe(sn(sn({},t),{},{data:l(A.slice(0,c))})),void VNe(sn(sn({},t),{},{data:l(A.slice(c))}))}ui.warn(`Beacon of ~${s??0} bytes was rejected by the browser, falling back to ${P$?"fetch":"XHR"}`),P$?pGt(sn(sn({},t),{},{sl:!0})):hGt(t)}catch(n){ui.warn("Beacon send failed",n)}},mGt=(t,e,n,o)=>{const i=o==="query"?e==="POST"?"sent_at":"_":void 0;return iq(n===gE.GZipJS?cGt(t,"compression"):t,sn(sn({},i?{[i]:Date.now().toString()}:{}),n===gE.GZipJS?{}:{compression:n}))},TGo=(()=>{const t=[];return P$&&t.push({transport:"fetch",method:pGt}),vDe&&t.push({transport:"XHR",method:hGt}),tf?.sendBeacon&&t.push({transport:"sendBeacon",method:VNe}),t})();let _Gt=!DGo&&jy?.indexOf("MSIE")===-1&&jy?.indexOf("Mozilla")===-1;function fGt(t,e,n){var o,i,r;n&&(e=sn(sn({},e),{},{callback:s=>n(s)})),t.__loaded?_Gt?t.__request_queue.push(e):t.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&((i=e.callback)===null||i===void 0||i.call(e,{statusCode:429})):(e.transport=e.transport||t.config.api_transport,e.headers=sn(sn({},t.config.request_headers),e.headers),e.compression=e.compression==="best-available"?(o=t.compression)!==null&&o!==void 0?o:e.compressionFallback:e.compression,(Eo(t.config.disable_beacon)?t.config.__preview_disable_beacon:t.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||t.config.fetch_options,((s,a)=>{var A,c,l;const u=sn(sn({},s),{},{callback:a??(m=>{var _;return(_=s.callback)===null||_===void 0?void 0:_.call(s,m)})});u.timeout=u.timeout||6e4;const g=(A=u.transport)!==null&&A!==void 0?A:"fetch";g==="sendBeacon"&&Eo(u.compression)&&u.data&&(u.compression=gE.Base64),u.method==="POST"&&u.data&&(u.timestampMode==="capture-body"?u.data=(m=>{var _,f;const I=(As(m)?m:[m]).map(y=>sn(sn({},y),y.timestamp instanceof Date&&!isNaN(y.timestamp.getTime())?{timestamp:y.timestamp.toISOString()}:{})),C=I[0];return{api_key:(_=C==null||(f=C.properties)===null||f===void 0?void 0:f.token)!==null&&_!==void 0?_:C?.token,batch:I,sent_at:new Date().toISOString()}})(u.data):u.timestampMode==="body"&&(u.data=((m,_=new Date().toISOString())=>As(m)?m.map(f=>sn(sn({},f),{},{sent_at:_})):sn(sn({},m),{},{sent_at:_}))(u.data))),u.url=mGt(u.url,u.method,u.compression,u.timestampMode);const h=TGo.filter(m=>!u.disableTransport||!m.transport||!u.disableTransport.includes(m.transport)),d=(c=(l=(function(m,_){for(let f=0;m.length>f;f++)if(_(m[f]))return m[f]})(h,m=>m.transport===g))===null||l===void 0?void 0:l.method)!==null&&c!==void 0?c:h[0].method;if(!d)throw new Error("No available transport method");const p=m=>{try{d(m)}catch(f){var _;gGt(f)?ui.warn(f):ui.error(f),(_=u.callback)===null||_===void 0||_.call(u,{statusCode:0,error:f})}};g!=="sendBeacon"&&!u.preferSyncCompression&&u.data&&u.compression===gE.GZipJS&&bHo&&typeof Promise<"u"&&!Fge?NGo(u).then(m=>{p(m)}).catch(m=>{if(_Ht(m))return Fge=!0,void p(sn(sn({},u),{},{compression:void 0,url:mGt(s.url,s.method,void 0,s.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;const f="name"in _?String(_.name):"";return _Ht(_)||f===pHt})(m)&&(Fge=!0),p(u)}):p(u)})(e,(s,a)=>{var A,c,l;t.rateLimiter.checkForLimiting(s),400>s.statusCode||(A=(c=t.config).on_request_error)===null||A===void 0||A.call(c,s),n?n(s,a):(l=e.callback)===null||l===void 0||l.call(e,s)})):e.fireCallbackOnDrop&&((r=e.callback)===null||r===void 0||r.call(e,{statusCode:0}))}var kGo=class{constructor(e,n){this.rl=!0,this.ol=[],this.al=u6(n?.flush_interval_ms||3e3,250,5e3,ui.createLogger("flush interval"),3e3),this.ll=e}enqueue(e){this.ol.push(e),this.ul||this.hl()}unload(){this.cl();const e=this.ol.length>0?this.dl():{},n=Object.values(e);[...n.filter(o=>o.url.indexOf("/e")===0),...n.filter(o=>o.url.indexOf("/e")!==0)].map(o=>{this.vl(o,"sendBeacon")})}enable(){this.rl=!1,this.hl()}hl(){this.rl||(this.ul=setTimeout(()=>{if(this.cl(),this.ol.length>0){const e=this.dl();for(const n in e)this.vl(e[n])}},this.al))}vl(e,n){try{this.ll(e,n)}catch(o){ui.error(o)}}cl(){clearTimeout(this.ul),this.ul=void 0}dl(){const e={};return kl(this.ol,n=>{var o;const i=n,r=((i?i.batchKey:null)||i.url)+(i.batchGroup?`:${i.batchGroup}`:"");Eo(e[r])&&(e[r]=sn(sn({},i),{},{data:[]})),(o=e[r].data)===null||o===void 0||o.push(i.data)}),this.ol=[],e}};const FGo=["retriesPerformedSoFar"];var LGo=class{constructor(e){this._instance=e,this.fl=!1,this.pl=3e3,this.ol=[],this.ol=[],this.gl=!0,this.resume()}resume(){if(!Eo(Fn)&&"onLine"in Fn.navigator){if(this.gl=Fn.navigator.onLine,this.ml)return;this.ml=()=>{this.gl=!0,this.yl()},this.bl=()=>{this.gl=!1},el(Fn,"online",this.ml),el(Fn,"offline",this.bl)}}get length(){return this.ol.length}retriableRequest(e,n){let{retriesPerformedSoFar:o}=e,i=IHt(e,FGo);Gb(o)&&(i.url=iq(i.url,{retry_count:o})),fGt(this._instance,n?sn(sn({},i),{},{transport:n}):i,(r,s)=>{var a;if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(o??0))return void this.Ls(sn({retriesPerformedSoFar:o},i),s);r.statusCode===0&&ui.warn(`Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after ${o??0} retries.`)}(a=i.callback)===null||a===void 0||a.call(i,r)})}Ls(e,n){const o=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=o+1;const i=Math.max((function(a){const A=3e3*Math.pow(2,a),c=A/2,l=Math.min(18e5,A),u=(Math.random()-.5)*(l-c);return Math.ceil(l+u)})(o),n??0),r=Date.now()+i;this.ol.push({retryAt:r,requestOptions:e});let s=`Enqueued failed request for retry in ${i}`;navigator.onLine||(s+=" (Browser is offline)"),ui.warn(s),this.fl||(this.fl=!0,this._l())}_l(){if(this.wl&&clearTimeout(this.wl),this.ol.length===0)return this.fl=!1,void(this.wl=void 0);this.wl=setTimeout(()=>{this.gl&&this.ol.length>0&&this.yl(),this._l()},this.pl)}yl(){const e=Date.now(),n=[],o=this.ol.filter(i=>e>i.retryAt||(n.push(i),!1));if(this.ol=n,o.length>0)for(const{requestOptions:i}of o)this.retriableRequest(i)}unload(){this.wl&&(clearTimeout(this.wl),this.wl=void 0),this.fl=!1,Eo(Fn)||(this.ml&&(Fn.removeEventListener("online",this.ml),this.ml=void 0),this.bl&&(Fn.removeEventListener("offline",this.bl),this.bl=void 0));for(const{requestOptions:e}of this.ol)try{this._instance._send_request(sn(sn({},e),{},{transport:"sendBeacon"}))}catch(n){ui.error(n)}this.ol=[]}},HGo=class{constructor(e){this._instance=e,this.kl=()=>{var n,o,i,r;this.Sl||(this.Sl={});const s=this.scrollElement(),a=this.scrollY(),A=s?Math.max(0,s.scrollHeight-s.clientHeight):0,c=a+(s?.clientHeight||0),l=s?.scrollHeight||0;this.Sl.lastScrollY=Math.ceil(a),this.Sl.maxScrollY=Math.max(a,(n=this.Sl.maxScrollY)!==null&&n!==void 0?n:0),this.Sl.maxScrollHeight=Math.max(A,(o=this.Sl.maxScrollHeight)!==null&&o!==void 0?o:0),this.Sl.lastContentY=c,this.Sl.maxContentY=Math.max(c,(i=this.Sl.maxContentY)!==null&&i!==void 0?i:0),this.Sl.maxContentHeight=Math.max(l,(r=this.Sl.maxContentHeight)!==null&&r!==void 0?r:0)}}get xl(){return this._instance.config.scroll_root_selector}getContext(){return this.Sl}resetContext(){const e=this.Sl;return this.Sl=void 0,setTimeout(this.kl,0),e}startMeasuringScrollPosition(){el(Fn,"scroll",this.kl,{capture:!0}),el(Fn,"scrollend",this.kl,{capture:!0}),el(Fn,"resize",this.kl)}scrollElement(){if(this.xl){const o=As(this.xl)?this.xl:[this.xl];for(const i of o){var e;const r=Fn==null||(e=Fn.document)===null||e===void 0?void 0:e.querySelector(i);if(r)return r}return}var n;return Fn==null||(n=Fn.document)===null||n===void 0?void 0:n.documentElement}$l(e){var n,o;const i=e==="y"?"scrollTop":"scrollLeft";if(this.xl){const r=this.scrollElement();return r&&r[i]||0}return Fn?e==="y"?Fn.scrollY||Fn.pageYOffset||((n=Fn.document)===null||n===void 0||(n=n.documentElement)===null||n===void 0?void 0:n.scrollTop)||0:Fn.scrollX||Fn.pageXOffset||((o=Fn.document)===null||o===void 0||(o=o.documentElement)===null||o===void 0?void 0:o.scrollLeft)||0:0}scrollY(){return this.$l("y")}scrollX(){return this.$l("x")}};const OGo=t=>UOt(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);var IGt=class{constructor(e,n,o,i){this.qe=r=>{const s=this.Cl();if(s&&s.sessionId===r)return;const a={sessionId:r,props:this.Tl(this._instance)};this.Il.register({[cNe]:a})},this._instance=e,this.Ml=n,this.Il=o,this.Tl=i||OGo,this.Ml.onSessionId(this.qe)}Cl(){return this.Il.props[cNe]}getSetOnceProps(){var e;const n=(e=this.Cl())===null||e===void 0?void 0:e.props;return n?"r"in n?KOt(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){const e={};return kl(mNe(this.getSetOnceProps()),(n,o)=>{o==="$current_url"&&(o="url"),e[`$session_entry_${PDe(o)}`]=n}),e}},Lge=class{on(t,e){return this.El[t]||(this.El[t]=[]),this.El[t].push(e),()=>{this.El[t]=this.El[t].filter(n=>n!==e)}}emit(t,e){for(const n of this.El[t]||[])n(e);for(const n of this.El["*"]||[])n(t,e)}constructor(){this.El={}}};const cG=Cd("[SessionId]"),CGt=864e5;var yGt=class{on(e,n){return this.Pl.on(e,n)}constructor(e,n,o){var i;if(this.Rl=null,this.Al=null,this.Ol=[],this.Fl=void 0,this.Dl=!1,this.Pl=new Lge,this.Ll=(s,a)=>!(!Gb(s)||!Gb(a))&&Math.abs(s-a)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Mr=e.config,this.Il=e.persistence,this.je=void 0,this.Xt=void 0,this._sessionStartTimestamp=null,this.Nl=void 0,this._sessionActivityTimestamp=null,this.ql=n||kB,this.jl=o||kB;const r=this.Mr.persistence_name||this.Mr.token;if(this._sessionTimeoutMs=1e3*u6(this.Mr.session_idle_timeout_seconds||1800,60,36e3,cG.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.Bl(),this.Hl="ph_"+r+"_window_id",this.zl="ph_"+r+"_primary_window_exists",this.Ul()){const s=nu.Lt(this.Hl),a=nu.Lt(this.zl);s&&!a?this.je=s:nu.Pt(this.Hl),nu.$t(this.zl,!0)}!((i=this.Mr.bootstrap)===null||i===void 0)&&i.sessionID&&this.setBootstrapSessionId(this.Mr.bootstrap.sessionID),this.Wl()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return Eo(this.Ol)&&(this.Ol=[]),this.Ol.push(e),this.Xt&&e(this.Xt,this.je),()=>{this.Ol=this.Ol.filter(n=>n!==e)}}Ul(){return this.Mr.persistence!=="memory"&&!this.Il.hi&&nu.Et()}Vl(e){e!==this.je&&(this.je=e,this.Ul()&&nu.$t(this.Hl,e))}Gl(){return this.je?this.je:this.Ul()?nu.Lt(this.Hl):null}Ql(e){const n=this.Rl;return!Id(n)&&!Id(e)&&5e3>Math.abs(e-n)}Jl(e,n,o){const i=n!==this._sessionActivityTimestamp,r=!(e!==this.Xt||o!==this._sessionStartTimestamp);this._sessionStartTimestamp=o,this._sessionActivityTimestamp=n,this.Xt=e,r&&!i||r&&this.Ql(n)||(this.Rl=n,this.Il.register({[$O]:[n,e,o]}))}Zl(){var e;const n=(e=this.Mr)===null||e===void 0?void 0:e.persistence_save_debounce_ms;return Gb(n)&&n>0}Kl(){this.Zl()?this.Il.refreshKey($O):(this.Il.flush(),this.Il.load())}Xl(){var e;if(Id(this._sessionActivityTimestamp)||this._sessionActivityTimestamp===this.Rl)return;this.Kl();const[,n,o]=this.Yl();n===this.Xt&&o===this._sessionStartTimestamp&&(this.Rl=this._sessionActivityTimestamp,this.Il.register({[$O]:[this._sessionActivityTimestamp,(e=this.Xt)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Il.flush())}tu(){const[e]=this.Yl(),n=Gb(e)?e:0,o=Gb(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,o)}eu(e){return this.Kl(),this.Ll(e,this.tu())}Yl(){const e=this.Il.props[$O];return As(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Rl=null,this.Nl=void 0,clearTimeout(this.iu),this.iu=void 0,this.Jl(null,null,null)}setBootstrapSessionId(e,n=!1){const o=((i,r=new Date().getTime())=>{try{const s=(a=>{const A=a.replace(/-/g,"");if(A.length!==32)throw new Error("Not a valid UUID");if(A[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(A.substring(0,12),16)})(i);return s>r+6e4?void cG.error("Bootstrap sessionID cannot be in the future"):s}catch(s){return void cG.error("Invalid sessionID in bootstrap",s)}})(e);return!Eo(o)&&(n?this.Nl={sessionId:e,sessionStartTimestamp:o}:this.Jl(e,new Date().getTime(),o),!0)}destroy(){this.Dl=!0,this.Xl(),clearTimeout(this.iu),this.iu=void 0,this.Fl&&Fn&&(Fn.removeEventListener(Qge,this.Fl,{capture:!1}),this.Fl=void 0),this.Ol=[]}Wl(){this.Fl=()=>{this.Xl(),this.Ul()&&nu.Pt(this.zl)},el(Fn,Qge,this.Fl,{capture:!1})}checkAndGetSessionAndWindowId(e=!1,n=null,o=!1){if(this.Mr.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');const i=n||new Date().getTime(),r=this.Xt;if(o)this.Al=i;else if(Id(this.Al)||this.Al>i||i-this.Al>=1e3){var s,a;(s=(a=this.Il).syncCookieProperties)===null||s===void 0||s.call(a),this.Al=i}let[,A,c]=this.Yl();const l=!Eo(r)&&A!==r,u=this.tu();let g=this.Gl();const h=this.Nl,d=!!h&&(h.sessionStartTimestamp>i+6e4||i-h.sessionStartTimestamp>CGt),p=h?d:Gb(c)&&Math.abs(i-c)>CGt;let m=!1,_=l,f=!A||!!h;const I=A;let C=!f&&!e&&this.Ll(i,u);if(C&&(C=this.eu(i),C||cG.info("cross-tab refresh kept the session alive",{sessionId:A}),[,A,c]=this.Yl(),C||(f=!A||!!h)),f||C||p){_=!1;const B=h&&!d;A=B?h.sessionId:this.ql(),g=this.jl(),cG.info("new session ID assigned",{sessionId:A,windowId:g,bootstrapped:!!B,changeReason:{noSessionId:f,activityTimeout:C,sessionPastMaximumLength:p}}),c=B?h.sessionStartTimestamp:i,this.Nl=void 0,m=!0}else g||(g=this.jl(),m=!0),_=_||A!==I,_&&(cG.info("adopted cross-tab session id",{sessionId:A,windowId:g}),m=!0);const y=Gb(u)&&e&&!p?u:i,x=Gb(c)?c:new Date().getTime();this.Vl(g),this.Jl(A,y,x),e||this.Bl();const E={noSessionId:f,activityTimeout:C,sessionPastMaximumLength:p,crossTabAdoption:_};return m&&this.Ol.forEach(B=>B(A,g,E)),{sessionId:A,windowId:g,sessionStartTimestamp:x,changeReason:m?E:void 0,lastActivityTimestamp:u}}Bl(){this.Dl||(clearTimeout(this.iu),this.iu=setTimeout(()=>{if(!this.Dl)if(this.eu(new Date().getTime())){const e=this.Xt;this.resetSessionId(),this.Pl.emit("forcedIdleReset",{idleSessionId:e})}else this.Bl()},1.1*this.sessionTimeoutMs))}};const xGt=function(t,e){if(!t)return!1;const n=t.userAgent;if(n&&ILt(n,e))return!0;try{const o=t?.userAgentData;if(o?.brands&&o.brands.some(i=>ILt(i?.brand,e)))return!0}catch{}return!!t.webdriver};function EGt(){return(EGt=Zu(function*(){const t=tf?.userAgentData;if(t?.getHighEntropyValues)try{const e=yield t.getHighEntropyValues(["model"]),n=e?.model;return rA(n)&&n.length>0?n:void 0}catch(e){return void ui.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",e)}})).apply(this,arguments)}function GGo(t,e){let n=`$survey_${e}/${t.id}`;return t.current_iteration&&t.current_iteration>0&&(n=`$survey_${e}/${t.id}/${t.current_iteration}`),n}function BGt(t){var e;return!!(!((e=t.conditions)===null||e===void 0||(e=e.events)===null||e===void 0||(e=e.values)===null||e===void 0)&&e.length)}const Hge=(t,e)=>{if(!(n=>{try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}},Oge=t=>t.toLowerCase(),bGt={exact:(t,e)=>e.some(n=>t.some(o=>n===o)),is_not:(t,e)=>e.every(n=>t.every(o=>n!==o)),regex:(t,e)=>e.some(n=>t.some(o=>Hge(n,o))),not_regex:(t,e)=>e.every(n=>t.every(o=>!Hge(n,o))),icontains:(t,e)=>e.map(Oge).some(n=>t.map(Oge).some(o=>n.includes(o))),not_icontains:(t,e)=>e.map(Oge).every(n=>t.map(Oge).every(o=>!n.includes(o))),gt:(t,e)=>e.some(n=>{const o=parseFloat(n);return!isNaN(o)&&t.some(i=>o>parseFloat(i))}),lt:(t,e)=>e.some(n=>{const o=parseFloat(n);return!isNaN(o)&&t.some(i=>o<parseFloat(i))})};function SGt(t,e){return!t||Object.entries(t).every(([n,o])=>{const i=e?.[n];if(i==null)return!1;const r=bGt[o.operator];return!!r&&r(o.values.map(String),[String(i)])})}function zNe(t,e,n){return oG({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}const JNe="custom",QGt="i.posthog.com",YGo=/^\/static\//,UGo=["/s/","/e/","/i/"];var KGo=class{constructor(t){this.nu={},this.instance=t}get apiHost(){const t=this.instance.config.api_host.trim().replace(/\/$/,"");return t==="https://app.posthog.com"?"https://us.i.posthog.com":t}get flagsApiHost(){const t=this.instance.config.flags_api_host;return t?t.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var t;let e=(t=this.instance.config.ui_host)===null||t===void 0?void 0:t.replace(/\/$/,"");return e||(e=this.apiHost.replace(`.${QGt}`,".posthog.com")),e==="https://app.posthog.com"?"https://us.posthog.com":e}get region(){return this.nu[this.apiHost]||(this.nu[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":JNe),this.nu[this.apiHost]}su(t){if(!YGo.test(t))return;const e=this.instance.config.asset_host;return typeof e=="string"&&e.trim().replace(/\/$/,"")||void 0}ru(t){const e=Kb(t);return e?e.protocol+"//"+e.host+e.pathname:void 0}ou(t,e,n){if(t==="ui")return n;let o=n;const i=this.instance.config.rewriteRequestPath;if(i){var r;const s=((r=Kb(n))===null||r===void 0?void 0:r.href)||n;o=i(new URL(s)).toString()}if(i&&t==="api"&&UGo.some(s=>e.indexOf(s)===0)){const s=this.ru(o);if(s){const a=this.apiHost;let A=this.au;A?.apiHost===a&&A.rewriteRequestPath===i||(A={apiHost:a,rewriteRequestPath:i,urls:new Set},this.au=A),A.urls.add(s)}}return o}isIngestionEndpoint(t){const e=this.au,n=this.ru(t);return e?.apiHost===this.apiHost&&e.rewriteRequestPath===this.instance.config.rewriteRequestPath&&!!n&&e.urls.has(n)}endpointFor(t,e=""){if(e&&(e=e[0]==="/"?e:`/${e}`),t==="ui")return this.ou(t,e,this.uiHost+e);if(t==="flags")return this.ou(t,e,this.flagsApiHost+e);if(t==="assets"){const o=this.su(e);if(o)return this.ou(t,e,`${o}${e}`)}if(this.region===JNe)return this.ou(t,e,this.apiHost+e);const n=QGt+e;switch(t){case"assets":return this.ou(t,e,`https://${this.region}-assets.${n}`);case"api":return this.ou(t,e,`https://${this.region}.${n}`)}}};const yl=Cd("[Surveys]"),vGt=t=>{try{const e=(n=>((o,i)=>`seenSurvey_${(function(r){return r.current_iteration&&r.current_iteration>0?`${r.id}_${r.current_iteration}`:r.id})(i)}`)(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(e){yl.error("Failed to persist survey seen state",e)}},VGo=[NNe.Popover,NNe.Widget,NNe.API],zGo={ignoreConditions:!1,ignoreDelay:!1,displayType:TNe.Popover},JGo=Cd("[PostHog ExternalIntegrations]"),WGo={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};var jGo=class{constructor(t){this._instance=t}Ho(t,e){var n,o;(n=Vr.__PosthogExtensions__)===null||n===void 0||(o=n.loadExternalDependency)===null||o===void 0||o.call(n,this._instance,t,i=>{if(i)return JGo.error("failed to load script",i);e()})}startIfEnabledOrStop(){var t;for(const[i,r]of Object.entries((t=this._instance.config.integrations)!==null&&t!==void 0?t:{})){var e,n,o;r&&!(!((e=Vr.__PosthogExtensions__)===null||e===void 0||(e=e.integrations)===null||e===void 0)&&e[i])&&this.Ho(WGo[i],()=>{var s;(s=Vr.__PosthogExtensions__)===null||s===void 0||(s=s.integrations)===null||s===void 0||(s=s[i])===null||s===void 0||s.start(this._instance)}),!r&&(!((n=Vr.__PosthogExtensions__)===null||n===void 0||(n=n.integrations)===null||n===void 0)&&n[i])&&((o=Vr.__PosthogExtensions__)===null||o===void 0||(o=o.integrations)===null||o===void 0||(o=o[i])===null||o===void 0||o.stop())}}},$Go=class{constructor(e,n){this.A=e,this.bo=n,this.lu=new Map,this.To=!1}add(e){var n=this;return Zu(function*(){if(n.To)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.lu.has(e.name))throw new Error(`Browser extension "${e.name}" is already registered`);n.lu.set(e.name,e);try{const o=e.setup(n.bo);o&&(yield o)}catch(o){const i=n.lu.get(e.name)===e;i&&n.lu.delete(e.name),n.A.error(`Failed to set up browser extension "${e.name}"`,o),i&&n.uu(e)}})()}getExtension(e){return this.lu.get(e)}dispose(){if(this.To)return;this.To=!0;const e=Array.from(this.lu.values()).reverse();this.lu.clear();for(const n of e)this.uu(n)}uu(e){try{var n;const o=(n=e.dispose)===null||n===void 0?void 0:n.call(e);o&&nf(o.then)&&o.then(void 0,i=>{this.A.error(`Failed to dispose browser extension "${e.name}"`,i)})}catch(o){this.A.error(`Failed to dispose browser extension "${e.name}"`,o)}}},qGo=class{constructor(t){this._instance=t}initialize(){}get(t){const e=this._instance.persistence;if(typeof t=="string")return e?.get_property(t);const n={};for(const o of t){const i=e?.get_property(o);Eo(i)||(n[o]=i)}return n}set(t,e){var n;(n=this._instance.persistence)===null||n===void 0||n.register(typeof t=="string"?{[t]:e}:t)}remove(t){var e;(e=this._instance.persistence)===null||e===void 0||e.unregister(t)}};const wGt="extensionsRemoteConfig";var XGo=class{constructor(t){this.instance=t,this.To=!1,this.A=ui,this.hu=t.cu,this.kv=new qGo(t),this.onEvent=e=>Tge(this.instance.on("eventCaptured",n=>{try{e({event:n.event,properties:n.properties})}catch(o){this.A.error("Browser extension event listener failed",o)}})),this.onRemoteConfig=e=>{if(this.To)return Tge(()=>{});const n=i=>{try{e(i)}catch(r){this.A.error("Browser extension remote config listener failed",r)}},o=this.instance.du.on(wGt,n);return this.hu&&n(this.hu),Tge(o)},this.vu=new $Go(ui.createLogger("[BrowserExtensions]"),this)}get logger(){return this.A}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var t;return(t=this.instance.get_property("$device_id"))!==null&&t!==void 0?t:this.distinctId}get deviceId(){const t=this.instance.get_property(XDe);return typeof t=="string"?t:void 0}get library(){return{name:n_.LIB_NAME,version:n_.LIB_VERSION}}get initialPersonProperties(){var t,e;return(t=(e=this.instance.persistence)===null||e===void 0?void 0:e.get_initial_props())!==null&&t!==void 0?t:{}}get groups(){return this.instance.getGroups()}get session(){try{var t,e,n,o;const i=(t=this.instance.sessionManager)===null||t===void 0?void 0:t.checkAndGetSessionAndWindowId(!0);return{sessionId:(e=i?.sessionId)!==null&&e!==void 0?e:"",windowId:(n=i?.windowId)!==null&&n!==void 0?n:"",sessionStartTimestamp:(o=i?.sessionStartTimestamp)!==null&&o!==void 0?o:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get canCapture(){return this.instance.is_capturing()}get projectToken(){return this.instance.config.token}add(t){return this.vu.add(t)}getExtension(t){return this.vu.getExtension(t)}capture(t,e,n){n?this.instance.capture(t,e,{timestamp:n.timestamp,uuid:n.uuid,$set:n.set,$set_once:n.setOnce}):this.instance.capture(t,e)}registerDynamicEventProperties(t){return Tge(this.instance.fu(t))}handleRemoteConfig(t){this.To||(this.hu=t,this.instance.du.emit(wGt,t))}sendRequest(t){var e=this;return Zu(function*(n,o={}){var i;const r=e.instance.requestRouter.endpointFor((i=o.target)!==null&&i!==void 0?i:"api",n),s={method:o.method,url:o.query?iq(r,o.query):r,data:o.body,headers:o.headers,timeout:o.timeoutMs,fireCallbackOnDrop:!0,transport:o.transport,compression:o.compression,compressionFallback:o.target==="flags"&&o.compression==="best-available"?wDe.Base64:void 0,timestampMode:o.sentAt};return o.transport==="sendBeacon"?(e.instance._send_request(s),{statusCode:202}):new Promise(a=>{s.callback=a,e.instance._send_request(s)})}).apply(this,arguments)}dispose(){this.To||(this.To=!0,this.vu.dispose())}};const rq={};let WNe=0;const sq=()=>{},PGt='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',lG="Surveys module not available",MGt="sanitize_properties is deprecated. Use before_send instead",DGt="Invalid value for property_denylist config: ",ZGo=["$recording_status","$sdk_debug_recording_script_not_loaded","$sdk_debug_replay_url_trigger_status","$sdk_debug_replay_event_trigger_status","$sdk_debug_replay_linked_flag_trigger_status","$sdk_debug_replay_rrweb_error","$sdk_debug_replay_internal_buffer_length","$sdk_debug_replay_flushed_size"],eYo=["$feature_flag_called","$$heatmap","$snapshot"],NGt=t=>t.charAt(0)==="$"&&!as(eYo,t),tYo=/^[A-Za-z0-9_-]{1,400}$/,RGt=/^fb\.[0-9]+\.[0-9]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/,TGt=/^fb\.[0-9]+\.[0-9]+\.[0-9]+$/,nYo=["token","distinct_id",JHt],aq="posthog",oYo=t=>{const e={};return t&&t!=="unset"&&("2025-11-30">t||(e.strictMinimumDuration=!0),"2026-05-30">t||(e.canvasCapture={resolutionScale:.6}),"2026-06-25">t||(e.streamNetworkBody=!0),"2026-08-30">t||(e.captureJsonLd=!0)),e},jNe=t=>{var e;return sn({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:eGo(No?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:sq,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:fd&&rA(fd?.search)&&fd.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,reuseAnonymousId:!1,disable_external_dependency_loading:!1,strict_script_versioning:"fallback",enable_recording_console_log:void 0,secure_cookie:(Fn==null||(e=Fn.location)===null||e===void 0?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,feature_flag_request_max_retries:1,surveys_request_timeout_ms:1e4,on_request_error(n){ui.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:oOt,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:3e3},error_tracking:{},_onCapture:sq},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:AGo,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:oYo(n),external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n),cookieWinsOnConflict:!(!n||n==="unset"||"2026-08-29">n)}))(t))},iYo=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["__preview_disable_beacon","disable_beacon"],["store_google","save_campaign_params"],["verbose","debug"],["__preview_cookie_wins_on_conflict","cookieWinsOnConflict"]],kGt=t=>{const e={};for(const[i,r]of iYo)Eo(t[i])||(e[r]=t[i]);const n=eg({},e,t),o=t.__preview_external_dependency_versioned_paths;return Eo(o)||(Eo(t.strict_script_versioning)&&(n.strict_script_versioning=!!o),rA(o)&&Eo(t.asset_host)&&(n.asset_host=o)),As(t.property_blacklist)&&(Eo(t.property_denylist)?n.property_denylist=t.property_blacklist:As(t.property_denylist)?n.property_denylist=[...t.property_blacklist,...t.property_denylist]:ui.error(DGt+t.property_denylist)),n};var rYo=class{constructor(){this.__forceAllowLocalhost=!1}get pu(){return this.__forceAllowLocalhost}set pu(t){ui.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=t}},Aq=class KM{gu(e){if(!e)return;const n=this.lu.indexOf(e);n!==-1&&this.lu.splice(n,1)}mu(e,n){var o;return this.gu(e),this.lu.push(n),(o=n.initialize)===null||o===void 0||o.call(n),n}yu(){return this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isRejected()}bu(){if(this._u||this.config.reuseAnonymousId||this.config.segment||this.yu())return;const e=this.config.persistence==="memory"||this.config.persistence==="sessionStorage";if(!e&&!this.config.disable_persistence||this.wu)return;let n,o,i;e?(n=`persistence is set to '${this.config.persistence}'`,o=this.config.persistence==="memory"?"on every page load":"for every new browser tab or window",i="Either set persistence to 'localStorage+cookie', keep this persistence and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."):(n="persistence is disabled (disable_persistence is true)",o="on every page load",i="Either set disable_persistence to false, keep persistence disabled and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."),this._u=!0,console.warn("[PostHog.js]",`${n} but no bootstrap.distinctID was provided. PostHog will mint a new distinct ID ${o}, so calling identify() merges a new ID onto the person each time. A person can then pass the distinct-ID limit and its events stop appearing on person pages and the session tab. ${i}`)}ku(){const e=this.persistence;if(!e||this.Su)return;if(this.yu())return void(this.config.cookieless_mode==="on_reject"&&this.get_distinct_id()!=="$posthog_cookieless"&&(this.xu(),this.$u()));if(this.get_distinct_id()!=="$posthog_cookieless")return;this.Cu()||e.load(!0);const n=this.get_distinct_id();if(!n||n==="$posthog_cookieless"){const o=this.config.get_device_id(kB());this.register({distinct_id:o,$device_id:o}),e.set_property(qy,Ub)}this.xu()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)===null||n===void 0?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)===null||n===void 0?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.Tu=!1,this.Iu=!1,this.webPerformance=new rYo,this.Mu=!1,this.version=n_.LIB_VERSION,this.Eu=new Set,this.Pu="",this.du=new Lge,this.lu=[],this.Ru=[],this.Au=!1,this.wu=!1,this._u=!1,this.Su=!1,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=jNe(),this.SentryIntegration=mGo,this.sentryIntegration=o=>(function(i,r){const s=ROt(i,r);return{name:NOt,processEvent:a=>s(a)}})(this,o),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Ou=!1,this.Fu=null,this.Du=null,this.Lu=null,this.scrollManager=new HGo(this),this.pageViewManager=new TOt(this),this.rateLimiter=new SGo(this),this.requestRouter=new KGo(this),this.consent=new aGo(this),this.externalIntegrations=new jGo(this);const n=(e=KM.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(o,i,r)=>{const s=rA(o)?{[o]:i}:o;this.setPersonProperties(s),r?.({})},set_once:(o,i,r)=>{const s=rA(o)?{[o]:i}:o;this.setPersonProperties(void 0,s),r?.({})}},this.on("eventCaptured",o=>ui.info(`send "${o?.event}"`,o))}init(e,n,o){if(o&&o!==aq){var i;const r=(i=rq[o])!==null&&i!==void 0?i:new KM;return r._init(e,n,o),rq[o]=r,rq[aq][o]=r,r}return this._init(e,n,o)}_init(e,n={},o){var i,r,s;const a=rA(e)?e.trim():"";if(!a)return ui.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;var A;if(this.__loaded)return a!==((A=this.config)===null||A===void 0?void 0:A.token)?console.warn("[PostHog.js]",`You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('${a}', { ... }, 'project2')`):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=jNe(n.defaults),n.debug=this.Nu(n.debug),this.qu=n,this.ju=[],n.person_profiles?this.Du=n.person_profiles:n.process_person&&(this.Du=n.process_person);const c=jNe(n.defaults),l=kGt(n),u=eg({},c,l,{name:o,token:a});QA(c.rageclick)&&QA(l.rageclick)&&(u.rageclick=eg({},c.rageclick,l.rageclick)),QA(c.session_recording)&&QA(l.session_recording)&&(u.session_recording=eg({},c.session_recording,l.session_recording)),this.set_config(u),this.config.on_xhr_error&&ui.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:gE.GZipJS;const g=this.Cu(),h=!this.yu();if(this.persistence=new DNe(this.config,g,!0,h),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new DNe(sn(sn({},this.config),{},{persistence:"sessionStorage"}),g,!1,h),this.Pu="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!g&&nu.Et()){const f=nu.Lt(this.Pu);As(f)&&f.forEach(I=>{rA(I)&&this.Eu.add(I)})}else nu.Pt(this.Pu);const d=sn({},this.persistence.props),p=sn({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Bu=new kGo((f,I)=>this.Hu(f,I),this.config.request_queue_config),this.zu=new LGo(this),this.__request_queue=[];const m=this.yu();m||(this.sessionManager=new yGt(this),this.sessionPropsManager=new IGt(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId((f,I,C)=>{(C?.activityTimeout||C?.sessionPastMaximumLength||C?.crossTabAdoption)&&this.Uu()})),this.Wu(),this.config.__preview_deferred_init_extensions?(ui.info("Deferring extension initialization to improve startup performance"),setTimeout(()=>{this.Vu(m)},0)):(ui.info("Initializing extensions synchronously"),this.Vu(m)),n_.DEBUG=n_.DEBUG||this.config.debug,n_.DEBUG&&ui.info("Starting in debug mode",{this:this,config:n,thisC:sn({},this.config),p:d,s:p}),this.config.identity_distinct_id&&!(!((i=n.bootstrap)===null||i===void 0)&&i.distinctID)&&(n.bootstrap=sn(sn({},n.bootstrap),{},{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0}));const _=(r=n.bootstrap)===null||r===void 0?void 0:r.distinctID;if(this.wu=!!_&&!D$(_),(s=n.bootstrap)===null||s===void 0?void 0:s.distinctID){const f=n.bootstrap.distinctID,I=this.get_distinct_id(),C=this.persistence.get_property(qy);if(n.bootstrap.isIdentifiedID&&I!=null&&I!==f&&C==="anonymous")this.identify(f);else if(n.bootstrap.isIdentifiedID&&I!=null&&I!==f&&C==="identified")ui.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{const y=this.config.get_device_id(kB()),x=n.bootstrap.isIdentifiedID?y:f;this.persistence.set_property(qy,n.bootstrap.isIdentifiedID?Sge:Ub),this.register({distinct_id:f,$device_id:x})}}if(m)this.register_once({distinct_id:uNe,$device_id:null},"");else if(!this.get_distinct_id()){const f=this.config.get_device_id(kB());this.register_once({distinct_id:f,$device_id:f},""),this.persistence.set_property(qy,Ub)}return el(Fn,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),el(Fn,"pageshow",()=>{var f;this.Tu=!1,this.Iu||(f=this.zu)===null||f===void 0||f.resume()}),n.segment?DOt(this,()=>this.Gu()):this.Gu(),nf(this.config._onCapture)&&this.config._onCapture!==sq&&(ui.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",f=>this.config._onCapture(f.event,f))),this.config.ip&&ui.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return EGt.apply(this,arguments)})().then(f=>{f&&this.register({[ZDe]:f})}).catch(sq),this}Qu(e){const n=e;return rA(n.name)&&nf(n.setup)}Ju(e,n){this.Qu(e)?n.push(()=>{this.Zu().add(e).catch(()=>{var o;return(o=e.dispose)===null||o===void 0?void 0:o.call(e)}).catch(o=>{ui.error(`Failed to dispose browser extension "${e.name}"`,o)})}):this.lu.push(e)}Wu(){var e,n,o;const i=(e=(n=this.config.__extensionClasses)===null||n===void 0?void 0:n.featureFlags)!==null&&e!==void 0?e:(o=KM.__defaultExtensionClasses)===null||o===void 0?void 0:o.featureFlags;var r,s,a;i&&(this.featureFlags&&this.featureFlags instanceof i||((r=this.Ku)===null||r===void 0||r.call(this),this.Ku=void 0,this.featureFlags=new i(this)),nf(this.featureFlags.onReloading)&&nf(this.featureFlags.setup)?this.Ku||(this.Ku=this.featureFlags.onReloading(()=>{this.du.emit("featureFlagsReloading",!0)}),this.Zu().add(this.featureFlags)):(s=(a=this.featureFlags).initialize)===null||s===void 0||s.call(a))}Vu(e){const n=performance.now(),o=sn(sn({},KM.__defaultExtensionClasses),this.config.__extensionClasses),i=[];var r,s,a,A,c,l,u;o.exceptions&&this.lu.push(this.exceptions=(r=this.exceptions)!==null&&r!==void 0?r:new o.exceptions(this)),o.historyAutocapture&&this.lu.push(this.historyAutocapture=new o.historyAutocapture(this)),o.tracingHeaders&&this.lu.push(this.tracingHeaders=new o.tracingHeaders(this)),o.siteApps&&this.lu.push(this.siteApps=new o.siteApps(this)),o.sessionRecording&&!e&&this.lu.push(this.sessionRecording=new o.sessionRecording(this)),this.config.disable_scroll_properties||i.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),o.autocapture&&this.Ju(this.autocapture=new o.autocapture(this),i),o.surveys&&this.Ju(this.surveys=(s=this.surveys)!==null&&s!==void 0?s:new o.surveys(this),i),o.logs&&this.Ju(this.logs=(a=this.logs)!==null&&a!==void 0?a:new o.logs(this),i),o.metrics&&this.lu.push(this.metrics=(A=this.metrics)!==null&&A!==void 0?A:new o.metrics(this)),o.conversations&&this.lu.push(this.conversations=(c=this.conversations)!==null&&c!==void 0?c:new o.conversations(this)),o.productTours&&this.lu.push(this.productTours=new o.productTours(this)),o.heatmaps&&this.lu.push(this.heatmaps=new o.heatmaps(this)),o.webVitalsAutocapture&&this.lu.push(this.webVitalsAutocapture=new o.webVitalsAutocapture(this)),o.exceptionObserver&&this.lu.push(this.exceptionObserver=new o.exceptionObserver(this)),o.deadClicksAutocapture&&this.lu.push(this.deadClicksAutocapture=new o.deadClicksAutocapture(this,pGo)),o.toolbar&&this.lu.push(this.toolbar=(l=this.toolbar)!==null&&l!==void 0?l:new o.toolbar(this)),o.experiments&&this.lu.push(this.experiments=(u=this.experiments)!==null&&u!==void 0?u:new o.experiments(this)),this.lu.forEach(g=>{g.initialize&&i.push(()=>{var h;(h=g.initialize)===null||h===void 0||h.call(g)})}),i.push(()=>{if(this.Xu){const g=this.Xu;this.Xu=void 0,this.lu.forEach(h=>{var d;return(d=h.onRemoteConfig)===null||d===void 0?void 0:d.call(h,g)})}}),this.Yu(i,n)}Yu(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout(()=>{this.Yu(e,n)},0);const i=e.shift();if(i)try{i()}catch(r){ui.error("Error initializing extension:",r)}}const o=Math.round(performance.now()-n);this.register_for_session({[WHt]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[jHt]:o}),this.config.__preview_deferred_init_extensions&&ui.info(`PostHog extensions initialized (${o}ms)`)}el(e){var n;if(!No||!No.body)return ui.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.el(e)},500);if(this.config.__preview_deferred_init_extensions&&(this.Xu=e),this.cu=e,this.compression=void 0,e.ok){var o;const i=e.config;i.supportedCompression&&!this.config.disable_compression&&(this.compression=as(i.supportedCompression,gE.GZipJS)?gE.GZipJS:as(i.supportedCompression,gE.Base64)?gE.Base64:void 0),!((o=i.analytics)===null||o===void 0)&&o.endpoint&&(this.analyticsDefaultEndpoint=i.analytics.endpoint)}this.set_config({person_profiles:this.Du?this.Du:oOt}),(n=this.th)===null||n===void 0||n.handleRemoteConfig(e),this.lu.forEach(i=>{var r;return(r=i.onRemoteConfig)===null||r===void 0?void 0:r.call(i,e)})}Gu(){try{this.config.loaded(this)}catch(e){ui.critical("`loaded` function failed",e)}if(this.eh(),this.config.internal_or_test_user_hostname&&fd?.hostname){const e=fd.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.yu())&&this.ih()},1),this.nh=new qOt(this),this.nh.load()}eh(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.Bu)===null||e===void 0||e.enable())}_dom_loaded(){this.is_capturing()&&XO(this.__request_queue,e=>this.Hu(e)),this.__request_queue=[],this.eh()}_handle_unload(){var e,n,o,i,r,s;this.Tu=!0,(e=this.surveys)===null||e===void 0||(n=e.handlePageUnload)===null||n===void 0||n.call(e),(o=this.metrics)===null||o===void 0||o.flush("sendBeacon"),this.config.request_batching?(this.sh()&&this.capture(iOt),(i=this.logs)===null||i===void 0||i.flushLogs("sendBeacon"),(r=this.Bu)===null||r===void 0||r.unload(),(s=this.zu)===null||s===void 0||s.unload()):this.sh()&&this.capture(iOt,null,{transport:"sendBeacon"})}_send_request(e){fGt(this,e)}Hu(e,n){this.zu?this.zu.retriableRequest(e,n):this._send_request(n?sn(sn({},e),{},{transport:n}):e)}_execute_array(e){WNe++;try{let n;const o=[],i=[],r=[];XO(e,a=>{if(a)if(n=a[0],As(n))r.push(a);else if(nf(a))try{a.call(this)}catch(A){ui.error("Error executing queued PostHog call",a,A)}else As(a)&&n==="alias"?o.push(a):As(a)&&n.indexOf("capture")!==-1&&nf(this[n])?r.push(a):i.push(a)});const s=function(a,A){XO(a,function(c){try{if(As(c[0])){let l=A;kl(c,function(u){l=l[u[0]].apply(l,u.slice(1))})}else A[c[0]].apply(A,c.slice(1))}catch(l){ui.error("Error executing queued PostHog call",c,l)}})};s(o,this),s(i,this),s(r,this)}finally{WNe--}}push(e){if(WNe>0&&As(e)&&rA(e[0])){const n=KM.prototype[e[0]];return void(nf(n)&&n.apply(this,e.slice(1)))}this._execute_array([e])}get rh(){return{property:RHt,persistenceKey:jO,cookieName:"_fbc",pattern:RGt,register:(e,n)=>{var o;return(o=this.persistence)===null||o===void 0?void 0:o.register({[jO]:{value:e,delivered:n}})},unregister:()=>{var e;return(e=this.persistence)===null||e===void 0?void 0:e.unregister(jO)}}}get oh(){return{property:THt,persistenceKey:F$,cookieName:"_fbp",pattern:TGt,register:(e,n)=>{var o;return(o=this.persistence)===null||o===void 0?void 0:o.register({[F$]:{value:e,delivered:n}})},unregister:()=>{var e;return(e=this.persistence)===null||e===void 0?void 0:e.unregister(F$)}}}ah(e){var n;const o=(n=this.persistence)===null||n===void 0?void 0:n.get_property(e.persistenceKey);return rA(o)&&e.pattern.test(o)?{value:o,delivered:!1}:QA(o)&&rA(o.value)&&e.pattern.test(o.value)?{value:o.value,delivered:o.delivered===!0}:void 0}uh(e,n,o){return n===o?.value?{value:n,pending:!o.delivered}:(e.register(n,!1),{value:n,pending:!0})}hh(e){if(!this.config.save_campaign_params||this.yu())return;const n=K$(e.cookieName);return rA(n)&&e.pattern.test(n)?n:void 0}dh(e,n,o,i){if(!this.persistence)return;const r=this.rh;this.persistence.refreshKey(r.persistenceKey);const s=this.ah(r);if(i)return void r.unregister();if(o)return rA(n)&&RGt.test(n)?this.uh(r,n,s):void r.unregister();const a=rA(e)&&tYo.test(e)?e:void 0,A=this.hh(r);return A&&((c,l,u)=>{const g=c.split(".");if(l)return g[3]===l;if(!u)return!0;const h=u.value.split(".");return g[3]===h[3]||Number(g[2])>Number(h[2])})(A,a,s)?this.uh(r,A,s):a?s?.value.split(".")[3]===a?{value:s.value,pending:!s.delivered}:this.uh(r,`fb.1.${Date.now()}.${a}`,s):s?{value:s.value,pending:!s.delivered}:void 0}fh(e,n,o){if(!this.persistence)return;const i=this.oh;this.persistence.refreshKey(i.persistenceKey);const r=this.ah(i);if(o)return void i.unregister();if(n)return rA(e)&&TGt.test(e)?this.uh(i,e,r):void i.unregister();const s=this.hh(i);return s?this.uh(i,s,r):r?{value:r.value,pending:!r.delivered}:void 0}ph(e,n){if(!this.persistence)return;this.persistence.refreshKey(e.persistenceKey);const o=this.ah(e);o?.value!==n||o.delivered||e.register(n,!0)}capture(e,n,o){var i,r;if(!(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Bu))return void ui.uninitializedWarning("posthog.capture");if(!this.is_capturing())return;if(Eo(e)||!rA(e))return void ui.error("No event name provided to posthog.capture");if(this.ku(),e==="$snapshot"&&this.yu())return;const s=!this.config.opt_out_useragent_filter&&this._is_bot();if(s&&!this.config.__preview_capture_bot_pageviews)return;const a=o?.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(a?.isRateLimited)return void ui.critical("This capture call is ignored due to client rate limiting.");let A;n?.$current_url&&!rA(n?.$current_url)&&(ui.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||o?.gh||ui.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&(A=this.sessionPersistence.update_campaign_params()),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();const c=new Date,l=o?.timestamp||c,u=ZLt(o?.uuid,kB);let g={uuid:u,event:e,properties:this.calculateEventProperties(e,n||{},l,u)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&s&&(g.event="$bot_pageview",g.properties.$browser_type="bot"),a&&(g.properties.$lib_rate_limit_remaining_tokens=a.remainingTokens);const h=e==="$feature_flag_called"&&g.properties.$feature_flag_has_experiment===!1&&this.get_property("$minimal_flag_called_events")===!0;o?.$set&&!h&&(g.$set=o?.$set);const d=QA(n?.$set)?n.$set:void 0,p=As(n?.$unset)?n.$unset:[],m=o?.$unset||[],_=R=>{var F;const O=!!o?.$set&&R in o.$set;return{hasProvided:O||!!d&&R in d,provided:O?o==null||(F=o.$set)===null||F===void 0?void 0:F[R]:d?.[R],unset:p.indexOf(R)!==-1||m.indexOf(R)!==-1}},f=_(RHt),I=_(THt),C=[{channel:this.rh,hasProvided:f.hasProvided,update:this.dh(A?.fbclid,f.provided,f.hasProvided,f.unset)},{channel:this.oh,hasProvided:I.hasProvided,update:this.fh(I.provided,I.hasProvided,I.unset)}];for(const{channel:R,hasProvided:F,update:O}of C)O&&g.properties.$process_person_profile===!0&&O.pending&&!F&&!h&&(g.$set=sn({[R.property]:O.value},g.$set));const y=o?.$unset;y&&(g.$unset=y);const x=h?void 0:this.mh(o?.$set_once,e!==sOt,e===rOt);if(x&&(g.$set_once=x),o?._noTruncate||(E=this.config.properties_string_max_length,g=(function(R,F){const O=new Set;return(function U(Y,W){if(Y!==Object(Y))return F?F(Y):Y;if(O.has(Y))return;let te;if(O.add(Y),As(Y))te=[],XO(Y,j=>{te.push(U(j))});else{const j={};kl(zO(Y)?aOt(Y):Y,(J,oe)=>{O.has(J)||(j[oe]=U(J))}),te=j}return te})(R)})(g,R=>rA(R)?R.slice(0,E):R)),g.timestamp=l,Eo(o?.timestamp)||(g.properties.$event_time_override_provided=!0,g.properties.$event_time_override_system_time=c),h&&(g.properties=((R,F=[])=>{const O={},U=Y=>{R[Y]!==void 0&&(O[Y]=R[Y])};return COo.forEach(U),F.forEach(U),O})(g.properties,nYo)),e===dE.DISMISSED||e===dE.SENT){const R=n?.[RNe.SURVEY_ID],F=n?.[RNe.SURVEY_ITERATION];vGt({id:R,current_iteration:F}),g.$set=sn(sn({},g.$set),{},{[GGo({id:R,current_iteration:F},e===dE.SENT?"responded":"dismissed")]:!0})}else e===dE.SHOWN&&(g.$set=sn(sn({},g.$set),{},{[RNe.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var E;if(e===bGo.SHOWN){const R=n?.[jOt.TOUR_TYPE];R&&(g.$set=sn(sn({},g.$set),{},{[`${jOt.TOUR_LAST_SEEN_DATE}/${R}`]:new Date().toISOString()}))}const B=sn(sn({},g.properties.$set),g.$set);if(Rx(B)||this.setPersonPropertiesForFlags(B),!Hs(this.config.before_send)){const R=this.Fs(g);if(!R)return;g=R,g.uuid=ZLt(g.uuid,kB)}this.sessionRecording&&!this.Au&&NGt(e)&&(this.Au=!0,setTimeout(()=>this.Au=!1,3e4));const S=C.filter(({channel:R,update:F})=>{var O,U,Y;const W=(O=(U=g.$set)===null||U===void 0?void 0:U[R.property])!==null&&O!==void 0?O:QA((Y=g.properties)===null||Y===void 0?void 0:Y.$set)?g.properties.$set[R.property]:void 0;return F?.pending&&W===F.value});this.du.emit("eventCaptured",g);const Q=(i=o?._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),w=o?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(Q),M=sn(sn(sn({method:"POST",url:Q,data:g,compression:"best-available",preferSyncCompression:o?.send_instantly,timestampMode:w?"body":"capture-body",batchKey:o?._batchKey},w&&(!((r=g.properties)===null||r===void 0)&&r.$session_id)?{batchGroup:g.properties.$session_id+(g.properties.$window_id?`-${g.properties.$window_id}`:"")}:{}),o?.transport?{transport:o.transport}:{}),S.length?{fireCallbackOnDrop:!0,callback:R=>{if(R.statusCode>=200&&300>R.statusCode)for(const{channel:F,update:O}of S)this.ph(F,O.value)}}:{});if(!this.config.request_batching||o&&!o?._batchKey||o?.send_instantly||S.length){var k;let R;!M.transport&&!M.callback&&Rx((k=this.config.request_headers)!==null&&k!==void 0?k:{})&&this.Tu&&(R="sendBeacon"),this.Hu(M,R)}else this.Bu.enqueue(M);return g}_addCaptureHook(e){return this.on("eventCaptured",n=>e(n.event,n))}getExtension(e){var n;return(n=this.th)===null||n===void 0?void 0:n.getExtension(e)}Zu(){var e;return(e=this.th)!==null&&e!==void 0?e:this.th=new XGo(this)}fu(e){this.Ru.push(e);let n=!0;return()=>{if(!n)return;n=!1;const o=this.Ru.indexOf(e);o!==-1&&this.Ru.splice(o,1)}}yh(e=!0){var n,o,i;return!!(!((n=this.persistence)===null||n===void 0)&&n.consumeCookieIdentityChange())&&(this.Lu=null,this.persistence.get_property("$user_state")==="anonymous"&&((i=this.sessionPersistence)===null||i===void 0||i.clear(),this.Eu.clear(),this.bh()),(o=this.featureFlags)===null||o===void 0||o.reset(),e&&this.reloadFeatureFlags(),!0)}calculateEventProperties(e,n,o,i,r){if(o=o||new Date,!this.persistence||!this.sessionPersistence)return n;this.ku(),this.persistence.syncCookieProperties(),this.yh();const s=r?void 0:this.persistence.remove_event_timer(e);let a=sn({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.yu()&&(a[JHt]=!0),e==="$snapshot"){const f=sn(sn({},this.persistence.properties()),this.sessionPersistence.properties());return a.distinct_id=f.distinct_id,(!rA(a.distinct_id)&&!Ah(a.distinct_id)||D$(a.distinct_id))&&ui.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}const A=(function(f,I,C,y=!1){var x,E,B,S;if(!jy)return{};const Q=f?[...rG,...I||[]]:[],[w,M]=WLt(jy),[k,R]=(function(ie){for(let ne=0;$Lt.length>ne;ne++){const[le,ge,_e]=$Lt[ne],ue=ie.match(le);if(ue){const fe=_e&&ie.match(_e)||ue;return[ge,fe?.[1]||""]}}return["",""]})(jy),F=(function(){const ie="u">typeof navigator?navigator:void 0;return ie?.brave?{brave:!0}:{}})(),O={};Eo(C)||(O.detectGoogleSearchApp=C);const U={},Y=(x=navigator)===null||x===void 0||(x=x.userAgentData)===null||x===void 0?void 0:x.platform,W=(E=navigator)===null||E===void 0?void 0:E.maxTouchPoints,te=Fn==null||(B=Fn.screen)===null||B===void 0?void 0:B.width,j=Fn==null||(S=Fn.screen)===null||S===void 0?void 0:S.height,J=Fn?.devicePixelRatio;Eo(Y)||(U.userAgentDataPlatform=Y),Eo(W)||(U.maxTouchPoints=W),Eo(te)||(U.screenWidth=te),Eo(j)||(U.screenHeight=j),Eo(J)||(U.devicePixelRatio=J);const oe=eg(mNe({$os:w,$os_version:M,$browser:zLt(jy,navigator.vendor,F,O),$webview_app:k,$webview_app_version:R,$device:jLt(jy),$device_type:YHo(jy,U),$timezone:VOt(),$timezone_offset:xGo()}),{$current_url:X$(y?Mw(fd?.href):fd?.href,Q,Z$),$host:fd?.host,$pathname:fd?.pathname,$raw_user_agent:jy.length>1e3?jy.substring(0,997)+"...":jy,$browser_version:GHo(jy,navigator.vendor,F,O),$browser_language:GOt(),$browser_language_prefix:yGo(),$screen_height:Fn?.screen.height,$screen_width:Fn?.screen.width,$viewport_height:Fn?.innerHeight,$viewport_width:Fn?.innerWidth,$lib:Ob.LIB_NAME,$lib_version:Ob.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Ob.SDK_DIST_CHANNEL&&(oe.$sdk_dist_channel=Ob.SDK_DIST_CHANNEL),oe})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){const{sessionId:f,windowId:I}=this.sessionManager.checkAndGetSessionAndWindowId(r,o.getTime(),!0);a.$session_id=f,a.$window_id=I}this.sessionPropsManager&&eg(a,this.sessionPropsManager.getSessionProps());try{var c;if(this.sessionRecording){const f=this.sessionRecording.sdkDebugProperties,I=!this.Au&&NGt(e);for(const C in f)(I||as(ZGo,C))&&(a[C]=f[C])}a.$sdk_debug_retry_queue_size=(c=this.zu)===null||c===void 0?void 0:c.length}catch(f){a.$sdk_debug_error_capturing_properties=String(f)}let l;if(this.requestRouter.region===JNe&&(a.$lib_custom_api_host=this.config.api_host),l=e!=="$pageview"||r?e!=="$pageleave"||r?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(o):this.pageViewManager.doPageView(o,i),a=eg(a,l),e==="$pageview"&&No&&(a.title=No.title),!Eo(s)){const f=o.getTime()-s;a.$duration=parseFloat((f/1e3).toFixed(3))}jy&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");const u=this.persistence.properties(),g=this.sessionPersistence.properties(),h=a.$groups,d=u.$groups;QA(h)&&!Rx(h)&&(a.$groups=sn(sn({},QA(d)?d:{}),h)),kl(["$referrer","$referring_domain"],f=>{f in u&&delete g[f]});const p={};if(this.Ru.length>0)for(const f of this.Ru.slice())try{eg(p,f())}catch(I){ui.error("Failed to produce browser extension event properties",I)}a=eg({},A,u,g,sn(sn({},p),a)),a.$is_identified=this._isIdentified(),As(this.config.property_denylist)?kl(this.config.property_denylist,function(f){delete a[f]}):ui.error(DGt+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);const m=this.config.sanitize_properties;m&&(ui.error(MGt),a=m(a,e));const _=this._h();return a.$process_person_profile=_,_&&!r&&this.wh("_calculate_event_properties"),a}mh(e,n=!0,o=!1){var i;if(!this.persistence||!this._h()||this.Mu&&!o)return e;const r=this.persistence.get_initial_props(),s=(i=this.sessionPropsManager)===null||i===void 0?void 0:i.getSetOnceProps();let a=eg({},r,s||{},e||{});const A=this.config.sanitize_properties;return A&&(ui.error(MGt),a=A(a,"$set_once")),n&&(this.Mu=!0),Rx(a)?void 0:a}register(e,n){var o;(o=this.persistence)===null||o===void 0||o.register(e,n)}register_once(e,n,o){var i;(i=this.persistence)===null||i===void 0||i.register_once(e,n,o)}register_for_session(e){var n,o;(n=this.persistence)===null||n===void 0||n.syncCookieProperties(),this.yh(),(o=this.sessionPersistence)===null||o===void 0||o.register(e),Object.keys(e).forEach(i=>this.Eu.add(i)),this.bh()}unregister(e){var n;(n=this.persistence)===null||n===void 0||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)===null||n===void 0||n.unregister(e),this.Eu.delete(e),this.bh()}kh(e,n){this.register({[e]:n})}Uu(){this.Eu.forEach(e=>{var n;(n=this.sessionPersistence)===null||n===void 0||n.unregister(e)}),this.Eu.clear(),this.bh()}bh(){var e;if(!this.Pu)return;if(this.config.persistence==="memory"||!((e=this.sessionPersistence)===null||e===void 0)&&e.hi||!nu.Et())return void nu.Pt(this.Pu);const n=[];this.Eu.forEach(o=>n.push(o)),n.length>0?nu.$t(this.Pu,n):nu.Pt(this.Pu)}getFeatureFlag(e,n){var o;return(o=this.featureFlags)===null||o===void 0?void 0:o.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)===null||n===void 0?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var o;return(o=this.featureFlags)===null||o===void 0?void 0:o.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)===null||n===void 0?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var o,i;return(o=(i=this.featureFlags)===null||i===void 0?void 0:i.isFeatureEnabled(e,n))!==null&&o!==void 0?o:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)===null||e===void 0||e.reloadFeatureFlags()}updateFlags(e,n,o){var i;(i=this.featureFlags)===null||i===void 0||i.updateFlags(e,n,o)}updateEarlyAccessFeatureEnrollment(e,n,o){var i;(i=this.featureFlags)===null||i===void 0||i.updateEarlyAccessFeatureEnrollment(e,n,o)}getEarlyAccessFeatures(e,n=!1,o){var i;return(i=this.featureFlags)===null||i===void 0?void 0:i.getEarlyAccessFeatures(e,n,o)}on(e,n){return this.du.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:lG}),()=>{})}onSessionId(e){var n,o;return(n=(o=this.sessionManager)===null||o===void 0?void 0:o.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n=!1){this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:lG})}getActiveMatchingSurveys(e,n=!1){this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:lG})}onActiveMatchingSurveysChanged(e){return this.surveys?this.surveys.onActiveMatchingSurveysChanged(e):(e([],{isLoaded:!1,error:lG}),()=>{})}renderSurvey(e,n){var o;(o=this.surveys)===null||o===void 0||o.renderSurvey(e,n)}displaySurvey(e,n=zGo){var o;(o=this.surveys)===null||o===void 0||o.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)===null||n===void 0||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,o;return(n=(o=this.surveys)===null||o===void 0?void 0:o.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:lG}}canRenderSurveyAsync(e,n=!1){var o,i;return(o=(i=this.surveys)===null||i===void 0?void 0:i.canRenderSurveyAsync(e,n))!==null&&o!==void 0?o:Promise.resolve({visible:!1,disabledReason:lG})}Sh(e){return!e||D$(e)?(ui.critical("Unique user id has not been set in posthog.identify"),!1):e==="$posthog_cookieless"?(ui.critical(`The string "${e}" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.`),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(ui.critical(`The string "${e}" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.`),!1)}identify(e,n,o){if(!this.__loaded||!this.persistence)return ui.uninitializedWarning("posthog.identify");if(Ah(e)&&(e=e.toString(),ui.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),!this.Sh(e)||!this.wh("posthog.identify"))return;this.ku();const i=this.get_distinct_id(),r=this.persistence.syncCookieProperties()&&this.get_distinct_id()!==i,s=this.yh(!1),a=this.persistence.Fa();let A=!1;try{const l=this.get_distinct_id();this.register({$user_id:e}),this.get_property("$device_id")||this.register_once({$had_persisted_distinct_id:!0,$device_id:l},""),e!==l&&e!==this.get_property("__alias")&&(this.unregister(Bge),this.register({distinct_id:e}));const u=(this.persistence.get_property("$user_state")||"anonymous")===Ub,g=e!==l,h=!g&&u;if(g&&u){var c;const d=this.config.reuseAnonymousId?{distinct_id:e}:{distinct_id:e,$anon_distinct_id:l};this.persistence.set_property(qy,Sge),this.setPersonPropertiesForFlags({$set:n||{},$set_once:o||{}},!1),this.config.cookieWinsOnConflict&&this.persistence.Da(),this.capture("$identify",d,{$set:n||{},$set_once:o||{}})&&(this.Lu=zNe(e,n,o)),(c=this.featureFlags)===null||c===void 0||c.setAnonymousDistinctId(this.config.reuseAnonymousId?void 0:l)}else if(h){this.persistence.set_property(qy,Sge);const d=n||{},p=o||{};this.setPersonPropertiesForFlags({$set:d,$set_once:p},!1),this.config.cookieWinsOnConflict&&this.persistence.Da(),this.capture("$set",{$set:d,$set_once:p})&&(this.Lu=zNe(e,n,o))}else(n||o)&&this.setPersonProperties(n,o);g||r||s?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Tw)):h&&(n||o)&&this.reloadFeatureFlags(),A=!0}finally{a&&this.persistence.qa(A)}}setPersonProperties(e,n){if(!e&&!n||!this.wh("posthog.setPersonProperties"))return;const o=zNe(this.get_distinct_id(),e,n);this.Lu!==o?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}})&&(this.Lu=o)):ui.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}unsetPersonProperties(e){var n;const o=(As(e)?e:[e]).filter(i=>rA(i)&&i.length>0);o.length!==0&&this.wh("posthog.unsetPersonProperties")&&((n=this.featureFlags)===null||n===void 0||n.unsetPersonPropertiesForFlags(o,!0),this.capture("$set",{$unset:o}),this.Lu=null)}group(e,n,o){var i;if(!e||!n)return void ui.error("posthog.group requires a group type and group key");(i=this.persistence)===null||i===void 0||i.syncCookieProperties(),this.yh();const r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:sn(sn({},r),{},{[e]:n})}),(s||o)&&this._h()){const a={$group_type:e,$group_key:n};o&&(a.$group_set=o),this.capture(sOt,a)}o&&this.setGroupPropertiesForFlags({[e]:o}),s&&!o&&this.reloadFeatureFlags()}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n=!0){var o;(o=this.featureFlags)===null||o===void 0||o.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e=!0){var n;(n=this.featureFlags)===null||n===void 0||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n=!0){var o;this.wh("posthog.setGroupPropertiesForFlags")&&((o=this.featureFlags)===null||o===void 0||o.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)===null||n===void 0||n.resetGroupPropertiesForFlags(e)}reset(e){const n=$y(e)?e:e?.resetDeviceID,o=$y(e)||e==null?void 0:e.bootstrap;this.xh(n,!1,o)}xh(e,n=!1,o){var i,r,s,a,A,c;if(ui.info("reset"),!this.__loaded)return ui.uninitializedWarning("posthog.reset");const l=o?.sessionID;this.config.bootstrap=o||((i=this.qu)===null||i===void 0?void 0:i.bootstrap)||{},(r=this.featureFlags)===null||r===void 0||(s=r.updateConfig)===null||s===void 0||s.call(r,this.config,this.il());const u=this.get_property(XDe),g=this.get_property(ZDe),h=this.get_property(L$);(a=this.sessionRecording)===null||a===void 0||a.flushBeforeIdentityReset();const d=this.is_capturing();n||this.consent.reset(),n||!d||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after.");const p=(A=this.persistence)===null||A===void 0||(c=A.Fa)===null||c===void 0?void 0:c.call(A),m=this.Su;this.Su=m||n;let _=!1;try{var f,I,C,y,x,E,B,S,Q,w,M,k,R;if((f=this.persistence)===null||f===void 0||f.clear(),(I=this.sessionPersistence)===null||I===void 0||I.clear(),this.Eu.clear(),this.bh(),Eo(h)||(w=this.persistence)===null||w===void 0||w.register({$session_recording_remote_config:h}),(C=this.surveys)===null||C===void 0||C.reset(),(y=this.featureFlags)===null||y===void 0||y.reset(),(x=this.conversations)===null||x===void 0||x.reset(),(E=this.logs)===null||E===void 0||E.reset(),(B=this.metrics)===null||B===void 0||B.reset(),(S=this.persistence)===null||S===void 0||S.set_property("$user_state","anonymous"),(Q=this.sessionManager)===null||Q===void 0||Q.resetSessionId(),this.Lu=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:uNe,$device_id:null},"");else{const U=this.config.get_device_id(kB());this.register_once({distinct_id:U,$device_id:e?U:u},""),e||Eo(g)||this.register({[ZDe]:g})}if(this.register({$last_posthog_reset:new Date().toISOString()},1),o&&(o.distinctID&&!this.yu()&&((R=this.persistence)===null||R===void 0||R.set_property("$user_state",o.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:o.distinctID})),(M=this.featureFlags)===null||M===void 0||M.initialize(),!Hs(l)&&!(!((k=this.sessionManager)===null||k===void 0)&&k.setBootstrapSessionId(l,!0)))){const U=sn({},o);delete U.sessionID,this.config.bootstrap=U}delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,_=!0}finally{var F,O;this.Su=m,p&&((F=this.persistence)===null||F===void 0||(O=F.qa)===null||O===void 0||O.call(F,_))}this.reloadFeatureFlags()}shutdown(e){var n=this;return Zu(function*(){var o,i,r,s,a,A,c,l;if(n.__loaded){n.Iu=!0,n.Zu().dispose(),(o=n.sessionRecording)===null||o===void 0||o.dispose(),(i=n.logs)===null||i===void 0||i.flushLogs("sendBeacon"),(r=n.metrics)===null||r===void 0||r.flush("sendBeacon"),(s=n.metrics)===null||s===void 0||s.dispose(),(a=n.Bu)===null||a===void 0||a.unload(),(A=n.zu)===null||A===void 0||A.unload();try{var u;(u=n.featureFlags)===null||u===void 0||u.destroy()}catch(g){ui.error("Error while destroying feature flags",g)}(c=n.persistence)===null||c===void 0||c.destroy(),(l=n.sessionPersistence)===null||l===void 0||l.destroy()}else ui.uninitializedWarning("posthog.shutdown")})()}setIdentity(e,n){var o;delete this.config.identity_claims,this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(o=this.conversations)===null||o===void 0||o.$h()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,(e=this.conversations)===null||e===void 0||e.Ch()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)===null||n===void 0?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";const{sessionId:n,sessionStartTimestamp:o}=this.sessionManager.checkAndGetSessionAndWindowId(!0);let i=this.requestRouter.endpointFor("ui",`/project/${this.config.token}/replay/${n}`);if(e?.withTimestamp&&o){var r;const s=(r=e.timestampLookBack)!==null&&r!==void 0?r:10;if(!o)return i;i+=`?t=${Math.max(Math.floor((new Date().getTime()-o)/1e3)-s,0)}`}return i}alias(e,n){return e===this.get_property("$people_distinct_id")?(ui.critical("Attempting to create alias for existing People user - aborting."),-2):this.wh("posthog.alias")?(Eo(n)&&(n=this.get_distinct_id()),e!==n?(this.kh(Bge,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(ui.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){const n=sn({},this.config);if(QA(e)){var o,i,r,s,a,A,c,l,u,g,h,d,p;eg(this.config,kGt(e));const C=this.Cu();if(this.persistence){const x=this.config.persistence==="sessionStorage"||this.config.persistence==="memory";var m,_;if(x&&this.sessionPersistence!==this.persistence&&((m=this.sessionPersistence)===null||m===void 0||m.remove(),(_=this.sessionPersistence)===null||_===void 0||_.destroy()),this.persistence.update_config(this.config,n,C),x)this.sessionPersistence=this.persistence;else if(this.sessionPersistence===this.persistence)this.sessionPersistence=new DNe(sn(sn({},this.config),{},{persistence:"sessionStorage"}),C,!1);else{var f;(f=this.sessionPersistence)===null||f===void 0||f.update_config(sn(sn({},this.config),{},{persistence:"sessionStorage"}),sn(sn({},n),{},{persistence:"sessionStorage"}),C)}}const y=this.Nu(this.config.debug);var I;$y(y)&&(this.config.debug=y),$y(this.config.debug)&&(this.config.debug?(n_.DEBUG=!0,hc.Et()&&hc.$t("ph_debug",!0),ui.info("set_config",{config:e,oldConfig:n,newConfig:sn({},this.config)})):(n_.DEBUG=!1,hc.Et()&&hc.Pt("ph_debug"))),(o=this.featureFlags)===null||o===void 0||(i=o.updateConfig)===null||i===void 0||i.call(o,this.config,this.il()),(r=this.exceptionObserver)===null||r===void 0||r.onConfigChange(),(s=this.exceptions)===null||s===void 0||s.onConfigChange(),(a=this.metrics)===null||a===void 0||a.onConfigChange(),(A=this.sessionRecording)===null||A===void 0||A.startIfEnabledOrStop(),(c=this.tracingHeaders)===null||c===void 0||c.startIfEnabledOrStop(),(l=this.autocapture)===null||l===void 0||l.startIfEnabled(),(u=this.heatmaps)===null||u===void 0||u.startIfEnabled(),("capture_pageview"in e||"disable_capture_url_hashes"in e)&&((I=this.historyAutocapture)===null||I===void 0||I.startIfEnabledOrStop()),(g=this.exceptionObserver)===null||g===void 0||g.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)===null||h===void 0||h.startIfEnabledOrStop(),(d=this.surveys)===null||d===void 0||d.loadIfEnabled(),this.xu(),(p=this.externalIntegrations)===null||p===void 0||p.startIfEnabledOrStop(),!n.segment&&this.config.segment&&this.persistence&&DOt(this,sq,!1)}}_overrideSDKInfo(e,n){n_.LIB_NAME=e,n_.LIB_VERSION=n}startSessionRecording(e){const n=e===!0,o={sampling:n||!!e?.sampling,linked_flag:n||!!e?.linked_flag,url_trigger:n||!!e?.url_trigger,event_trigger:n||!!e?.event_trigger};var i,r,s,a,A;Object.values(o).some(Boolean)&&((i=this.sessionManager)===null||i===void 0||i.checkAndGetSessionAndWindowId(),o.sampling&&((r=this.sessionRecording)===null||r===void 0||r.overrideSampling()),o.linked_flag&&((s=this.sessionRecording)===null||s===void 0||s.overrideLinkedFlag()),o.url_trigger&&((a=this.sessionRecording)===null||a===void 0||a.overrideTrigger("url")),o.event_trigger&&((A=this.sessionRecording)===null||A===void 0||A.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!!(!((e=this.sessionRecording)===null||e===void 0)&&e.started)}captureException(e,n){try{if(!this.exceptions)return;const o=this.exceptions.buildProperties(e,{handled:!0,syntheticException:new Error("PostHog syntheticException")});return this.exceptions.sendExceptionEvent(sn(sn({},o),n))}catch{return}}addExceptionStep(e,n){var o;(o=this.exceptions)===null||o===void 0||o.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)===null||n===void 0||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)===null||n===void 0?void 0:n.logger)!==null&&e!==void 0?e:KM.Th}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,o;return(n=(o=this.toolbar)===null||o===void 0?void 0:o.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)===null||n===void 0?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)===null||n===void 0?void 0:n.props[e]}toString(){var e;let n=(e=this.config.name)!==null&&e!==void 0?e:aq;return n!==aq&&(n="posthog."+n),n}_isIdentified(){var e,n;return((e=this.persistence)===null||e===void 0?void 0:e.get_property("$user_state"))==="identified"||((n=this.sessionPersistence)===null||n===void 0?void 0:n.get_property("$user_state"))==="identified"}_h(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&Rx(this.getGroups())&&!(!((e=this.persistence)===null||e===void 0||(e=e.props)===null||e===void 0)&&e.__alias)&&!(!((n=this.persistence)===null||n===void 0||(n=n.props)===null||n===void 0)&&n.$epp))}sh(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&!!this.config.capture_pageview}createPersonProfile(){this._h()||this.wh("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.wh("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}wh(e){return this.config.person_profiles==="never"?(ui.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.bu(),this.kh(lNe,!0),!0)}Cu(){if(this.config.cookieless_mode==="always")return!0;const e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!=="on_reject")}xu(){var e,n;const o=this.Cu();var i,r,s;return this.is_capturing()||(i=this.logs)===null||i===void 0||i.Ih(),((e=this.persistence)===null||e===void 0?void 0:e.hi)!==o&&((r=this.persistence)===null||r===void 0||r.set_disabled(o)),((n=this.sessionPersistence)===null||n===void 0?void 0:n.hi)!==o&&((s=this.sessionPersistence)===null||s===void 0||s.set_disabled(o)),this.bh(),o}opt_in_capturing(e){var n;if(this.config.cookieless_mode!=="always"){if(this.yu()){var o,i,r,s,a,A;(o=this.sessionRecording)===null||o===void 0||o.dispose({discardBufferedEvents:!0}),this.xh(!0,!0),(i=this.sessionManager)===null||i===void 0||i.destroy(),(r=this.pageViewManager)===null||r===void 0||r.destroy(),this.sessionManager=new yGt(this),this.pageViewManager=new TOt(this),this.persistence&&(this.sessionPropsManager=new IGt(this,this.sessionManager,this.persistence));const h=(s=(a=this.config.__extensionClasses)===null||a===void 0?void 0:a.sessionRecording)!==null&&s!==void 0?s:(A=KM.__defaultExtensionClasses)===null||A===void 0?void 0:A.sessionRecording;var c,l;h&&(this.sessionRecording=this.mu(this.sessionRecording,new h(this)),this.cu&&((c=this.sessionRecording)===null||c===void 0||(l=c.onRemoteConfig)===null||l===void 0||l.call(c,this.cu)))}var u,g;this.consent.optInOut(!0),this.xu(),this.eh(),(n=this.sessionRecording)===null||n===void 0||n.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&((u=this.surveys)===null||u===void 0||u.loadIfEnabled()),(Eo(e?.captureEventName)||e?.captureEventName)&&this.capture((g=e?.captureEventName)!==null&&g!==void 0?g:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.ih()}else ui.warn(PGt)}opt_out_capturing(){this.config.cookieless_mode!=="always"?(this.consent.optInOut(!1),this.xu(),this.config.cookieless_mode==="on_reject"&&this.$u()):ui.warn(PGt)}$u(){var e,n;const o=this.sessionRecording;o?.dispose({discardBufferedEvents:!0}),this.get_distinct_id()!=="$posthog_cookieless"&&this.xh(!0,!0),this.register({distinct_id:uNe,$device_id:null}),this.gu(o),this.sessionRecording=void 0,(e=this.sessionManager)===null||e===void 0||e.destroy(),(n=this.pageViewManager)===null||n===void 0||n.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.ih(),this.eh()}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){const e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return!this.Su&&(this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing()))}clear_opt_in_out_capturing(){this.consent.reset(),this.xu()}_is_bot(){return tf?xGt(tf,this.config.custom_blocked_useragents):void 0}ih(){No&&(No.visibilityState==="visible"?this.Ou||(this.Ou=!0,this.capture(pNe,{title:No.title},{send_instantly:!0}),this.Fu&&(No.removeEventListener(U$,this.Fu),this.Fu=null)):this.Fu||(this.Fu=this.ih.bind(this),el(No,U$,this.Fu)))}debug(e){e===!1?(Fn?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(Fn?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}il(){const e=this.qu||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(ui.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,o,i,r,s){const a=o in n&&!Hs(n[o]),A=i in n&&!Hs(n[i]);return a?n[o]:!!A&&(s&&s.warn(`Config field '${i}' is deprecated. Please use '${o}' instead. The old field will be removed in a future major version.`),n[i])})(e,"advanced_disable_flags","advanced_disable_decide",0,ui)}Fs(e){var n;if(Hs(this.config.before_send))return e;const o=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(PHo),i=As(this.config.before_send)?this.config.before_send:[this.config.before_send];let r=e;for(const s of i)try{if(r=s(r),Hs(r)){const a=`Event '${e.event}' was rejected in beforeSend function`;return wHo(e.event)?ui.warn(`${a}. This can cause unexpected behavior.`):ui.info(a),null}r.properties&&!Rx(r.properties)||ui.warn(`Event '${e.event}' has no properties after beforeSend function, this is likely an error.`)}catch(a){return ui.error(`Error in beforeSend function for event '${e.event}':`,a),null}for(const s of o)if(r.properties&&Hs(r.properties[s]))return ui.warn(`Event '${e.event}' had its '${s}' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped.`),null;return r}getPageViewId(){var e;return(e=this.pageViewManager.Wo)===null||e===void 0?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,o){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(o)})}Nu(e){const n=$y(e)&&!e,o=hc.Et()&&hc.Ot("ph_debug")==="true";return!n&&(!!o||e)}};Aq.__defaultExtensionClasses={},Aq.Th=(()=>{const t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(let n=0;e.length>n;n++)t.prototype[e[n]]=XOo(t.prototype[e[n]])})(Aq,["identify"]);var FGt=class{constructor(t){this.disabled=t===!1;const e=QA(t)?t:{};this.thresholdPx=e.threshold_px||30,this.timeoutMs=e.timeout_ms||1e3,this.clickCount=e.click_count||3,this.clicks=[]}isRageClick(t,e,n){if(this.disabled)return!1;const o=this.clicks[this.clicks.length-1];if(o&&Math.abs(t-o.x)+Math.abs(e-o.y)<this.thresholdPx&&this.timeoutMs>n-o.timestamp){if(this.clicks.push({x:t,y:e,timestamp:n}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:t,y:e,timestamp:n}];return!1}};const $Ne="$copy_autocapture",qNe=Cd("[AutoCapture]");function XNe(t,e){return e.length>t?e.slice(0,t)+"...":e}function sYo(t){if(t.previousElementSibling)return t.previousElementSibling;let e=t;do e=e.previousSibling;while(e&&!d6(e));return e}function aYo(t,{e,maskAllElementAttributes:n,maskAllText:o,elementAttributeIgnoreList:i,elementsChainAsString:r,disableCaptureUrlHashes:s}){var a,A;if(!d6(t))return{props:{}};const c=[t],l=new Set([t]);let u=t;for(;u.parentNode&&!AI(u,"body")&&1e3>c.length;){if(BNe(u.parentNode)){const x=u.parentNode.host;if(l.has(x))break;l.add(x),c.push(x),u=x;continue}if(!d6(u.parentNode)||l.has(u.parentNode))break;l.add(u.parentNode),c.push(u.parentNode),u=u.parentNode}const g=e.type==="click"&&t.namespaceURI==="http://www.w3.org/2000/svg"?c.findIndex(x=>AI(x,"button")||AI(x,"a")):-1;g>0&&(o=o||c.slice(0,g+1).some(x=>!nG(x)||W$(x)));const h=[],d={};let p,m=!1,_=!1;if(kl(c,x=>{const E=nG(x);if(AI(x,"a")&&!n&&!i?.includes("href")){const B=x.getAttribute("href");m=!!(E&&B&&j$(B))&&(s?Mw(B):B)}as(tG(x),"ph-no-capture")&&(_=!0),h.push((function(B,S,Q,w,M=!1){const k=B.tagName.toLowerCase(),R={tag_name:k};SNe.indexOf(k)>-1&&!Q&&(R.$el_text=k.toLowerCase()==="a"||k.toLowerCase()==="button"?XNe(1024,vOt(B)):XNe(1024,z$(B)));const F=tG(B);S||w?.includes("class")||0>=F.length||(R.classes=F.filter(function(W){return W!==""})),kl(B.attributes,function(W){var te;if((!W$(B)||["name","id","class","aria-label"].indexOf(W.name)!==-1)&&!w?.includes(W.name)&&!S&&j$(W.value)&&(!rA(te=W.name)||te.substring(0,10)!=="_ngcontent"&&te.substring(0,7)!=="_nghost")){let j=W.value;W.name==="class"&&(j=bNe(j).join(" ")),R["attr__"+W.name]=XNe(1024,W.name==="href"&&M?Mw(j):j)}});let O=1,U=1,Y=B;for(;Y=sYo(Y);)O++,Y.tagName===B.tagName&&U++;return R.nth_child=O,R.nth_of_type=U,R})(x,n,o,i,s)),kl((function(B){if(!nG(B))return{};const S={};return kl(B.attributes,function(Q){if(Q.name&&Q.name.indexOf("data-ph-capture-attribute")===0){const w=Q.name.replace("data-ph-capture-attribute-",""),M=Q.value;w&&M&&j$(M)&&(S[w]=M)}}),S})(x),(B,S)=>{({}).hasOwnProperty.call(d,S)||(d[S]=B)})}),_)return{props:{},explicitNoCapture:_};if(g>0&&(t=c[g],h.splice(0,g)),o||(h[0].$el_text=AI(t,"a")||AI(t,"button")?vOt(t):z$(t)),m){var f,I;h[0].attr__href=m;const x=(f=Kb(m))===null||f===void 0?void 0:f.host,E=Fn==null||(I=Fn.location)===null||I===void 0?void 0:I.host;x&&E&&x!==E&&(p=m)}return{props:eg((y=e.type,{$event_type:y,$ce_version:1}),r?{}:{$elements:h},{$elements_chain:(C=h,As(C)?(function(x){return x.map(E=>{var B,S;let Q="";if(E.tag_name&&(Q+=E.tag_name),E.attr_class){E.attr_class.sort();for(const k of E.attr_class)Q+=`.${k.replace(/"/g,"")}`}const w=sn(sn(sn(sn({},E.text?{text:E.text}:{}),{},{"nth-child":(B=E.nth_child)!==null&&B!==void 0?B:0,"nth-of-type":(S=E.nth_of_type)!==null&&S!==void 0?S:0},E.href?{href:E.href}:{}),E.attr_id?{attr_id:E.attr_id}:{}),E.attributes),M={};return vge(w).sort(([k],[R])=>(function(F,O){return O>F?-1:F>O?1:0})(k,R)).forEach(([k,R])=>M[POt(k.toString())]=POt(R.toString())),Q+=":",Q+=vge(M).map(([k,R])=>`${k}="${R}"`).join(""),Q}).join(";")})((function(x){return x.map(E=>{var B,S;const Q={text:(B=E.$el_text)===null||B===void 0?void 0:B.slice(0,400),tag_name:E.tag_name,href:(S=E.attr__href)===null||S===void 0?void 0:S.slice(0,2048),attr_class:dGo(E),attr_id:E.attr__id,nth_child:E.nth_child,nth_of_type:E.nth_of_type,attributes:{}};return vge(E).filter(([w])=>w.indexOf("attr__")===0).forEach(([w,M])=>Q.attributes[w]=M),Q})})(C)):"")},!((a=h[0])===null||a===void 0)&&a.$el_text?{$el_text:(A=h[0])===null||A===void 0?void 0:A.$el_text}:{},p&&e.type==="click"?{$external_click_url:p}:{},d),target:t};var C,y}var AYo=class{do(){this.vo=void 0,clearTimeout(this.fo),this.fo=void 0}po(t){var e;if(!nG(t))return!0;const n=(e=this.mo().css_selector_ignorelist)!==null&&e!==void 0?e:wNe,o=new Set;let i=t;for(;i;){if(o.size>=1e3||o.has(i))return!0;o.add(i);const r=i,s=tG(r);if(as(s,"ph-no-capture")||as(s,"ph-sensitive")||W$(r)||n.some(A=>QNe(r,A)))return!0;const a=i.parentNode;i=BNe(a)?a.host:a&&d6(a)?a:null}return!1}yo(t){if(!this.isEnabled||t.type==="pointercancel")return void this.do();if(t.type==="pointerdown"){this.do();const o=J$(t);var e;return void(t.isPrimary&&t.button===0&&!t.ctrlKey&&o&&d6(o)&&(this.vo={target:o,excluded:this.po(o),id:t.pointerId,x:t.clientX,y:t.clientY,released:!1,distinctId:(e=this.bo)===null||e===void 0?void 0:e.distinctId}))}const n=this.vo;n&&(t.pointerId!==n.id||Math.abs(t.clientX-n.x)>5||Math.abs(t.clientY-n.y)>5?this.do():t.type==="pointerup"&&(n.released=!0,this.fo=setTimeout(()=>this.do(),0)))}_o(t){var e;const n=this.vo;this.do();const o=J$(t);if(n?.released&&n.target.isConnected&&n.distinctId===((e=this.bo)===null||e===void 0?void 0:e.distinctId)&&t.pointerId===n.id&&(t.detail>0||t.pointerType==="touch"||t.pointerType==="pen")&&t.button===0&&5>=Math.abs(t.clientX-n.x)&&5>=Math.abs(t.clientY-n.y)&&o&&(AI(o,"html")||AI(o,"body"))){var i;if(n.excluded)return null;const r=(i=this.mo().css_selector_ignorelist)!==null&&i!==void 0?i:wNe;return[o,No?.documentElement,No?.body].some(s=>{if(!s)return!1;const a=tG(s);return as(a,"ph-no-capture")||as(a,"ph-sensitive")||!nG(s)||W$(s)||r.some(A=>QNe(s,A))})?null:n.target}}constructor(t){this.wo=t,this.name="autocapture",this.ko=!1,this.So=null,this.xo=!1,this.$o=new Map,this.Co=!1,this.Mr={enabled:!1,rageclick:!1,maskAllElementAttributes:!1,maskAllText:!1,disableCaptureUrlHashes:!1,remoteRequestsDisabled:!1},this.To=!1,this.wo.refresh(this.Mr),this.rageclicks=new FGt(this.Mr.rageclick),this.Io=null}setup(t){this.Mo(),this.bo=t;const e=t.onRemoteConfig(this.onRemoteConfig.bind(this));this.To?e.dispose():(this.Eo=e,this.startIfEnabled())}dispose(){var t;this.To||(this.To=!0,this.bo=void 0,(t=this.Eo)===null||t===void 0||t.dispose(),this.Eo=void 0,this.$o.clear(),this.Io=null,this.Po())}mo(){return this.wo.refresh(this.Mr),this.Mr}Mo(){var t,e;return this.mo(),this.Mr.url_allowlist=(t=this.Mr.url_allowlist)===null||t===void 0?void 0:t.map(n=>new RegExp(n)),this.Mr.url_ignorelist=(e=this.Mr.url_ignorelist)===null||e===void 0?void 0:e.map(n=>new RegExp(n)),this.Mr}Ro(){if(!this.isBrowserSupported())return void qNe.info("Disabling Automatic Event Collection because this browser is not supported");if(!Fn||!No)return;const t=this.Ao=e=>{e=e||Fn?.event;try{if(e.type==="blur")return void this.do();if(e.type.indexOf("pointer")===0)return void this.yo(e);const n=e.type==="click"?this._o(e):void 0;if(Id(n))return;this.Oo(e,"$autocapture",n)}catch(n){qNe.error("Failed to capture event",n)}};if(el(Fn,"blur",t),el(No,"submit",t,{capture:!0}),el(No,"change",t,{capture:!0}),el(No,"click",t,{capture:!0}),kl(["pointerdown","pointermove","pointerup","pointercancel"],e=>{el(No,e,t,{capture:!0})}),this.mo().capture_copied_text){const e=this.Fo=n=>{n=n||Fn?.event;try{this.Oo(n,$Ne)}catch(o){qNe.error("Failed to capture clipboard event",o)}};el(No,"copy",e,{capture:!0}),el(No,"cut",e,{capture:!0}),el(No,"paste",e,{capture:!0})}}Po(){this.do(),this.Ao&&(Fn?.removeEventListener("blur",this.Ao),kl(["pointerdown","pointermove","pointerup","pointercancel"],t=>{No?.removeEventListener(t,this.Ao,!0)}),No?.removeEventListener("submit",this.Ao,!0),No?.removeEventListener("change",this.Ao,!0),No?.removeEventListener("click",this.Ao,!0),this.Ao=void 0),this.Fo&&(No?.removeEventListener("copy",this.Fo,!0),No?.removeEventListener("cut",this.Fo,!0),No?.removeEventListener("paste",this.Fo,!0),this.Fo=void 0),this.ko=!1}startIfEnabled(){this.isEnabled||this.do(),!this.To&&this.bo&&this.isEnabled&&!this.ko&&(this.Ro(),this.ko=!0)}onRemoteConfig(t){if(this.To)return;if(this.xo=!0,!t.ok)return void this.startIfEnabled();const e=t.config;e.elementsChainAsString&&(this.Co=e.elementsChainAsString);const n=e.autocapture_opt_out;var o;$y(n)&&((o=this.bo)===null||o===void 0||o.kv.set("$autocapture_disabled_server_side",n),this.So=n),this.startIfEnabled()}setElementSelectors(t,e=this){if(this.To)return;t.size?this.$o.set(e,new Set(t)):this.$o.delete(e);const n=new Set;this.$o.forEach(o=>{o.forEach(i=>n.add(i))}),this.Io=n}getElementSelectors(t,e){var n;const o=[];return(n=this.Io)===null||n===void 0||n.forEach(i=>{const r=No?.querySelectorAll(i);r?.forEach(s=>{t!==s&&e!==s||as(o,i)||o.push(i)})}),o}get isEnabled(){var t,e;if(this.To)return!1;const n=(t=this.bo)===null||t===void 0?void 0:t.kv.get(kHt),o=this.So,i=this.mo();if(!i.remoteRequestsDisabled&&!this.xo)return!1;const r=i.remoteRequestsDisabled&&!this.xo;if(Id(o)&&!$y(n)&&!r)return!1;const s=(e=this.So)!==null&&e!==void 0?e:!!n;return!!i.enabled&&!s}Oo(t,e="$autocapture",n){if(!this.isEnabled)return void this.do();let o=n||J$(t);pOt(o)&&(o=o.parentNode||null);const i=this.Mo();var r;e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&i.rageclick&&(!((r=this.rageclicks)===null||r===void 0)&&r.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime()))&&xOt(o,i.rageclick)&&this.Oo(t,"$rageclick",n);const s=e===$Ne,a=s?sn(sn({},i),{},{dom_event_allowlist:void 0}):i;if(o&&(function(u,g,h,d,p,m){var _;if(!Fn||PNe(u)||h?.url_allowlist&&!mOt(h.url_allowlist,m)||h?.url_ignorelist&&mOt(h.url_ignorelist,m))return!1;if(h?.dom_event_allowlist){const y=h.dom_event_allowlist;if(y&&!y.some(x=>g.type===x))return!1}const{parentIsUsefulElement:f,targetElementList:I}=EOt(u,d);if(!(function(y,x){const E=x?.element_allowlist;if(Eo(E))return!0;for(const B of y)if(E.some(S=>B.tagName.toLowerCase()===S))return!0;return!1})(I,h)||!vNe(I,h?.css_selector_allowlist)||vNe(I,(_=h?.css_selector_ignorelist)!==null&&_!==void 0?_:wNe))return!1;try{const y=Fn.getComputedStyle(u);if(y&&y.getPropertyValue("cursor")==="pointer"&&g.type==="click")return!0}catch{}const C=u.tagName.toLowerCase();switch(C){case"html":return!1;case"form":return(p||["submit"]).indexOf(g.type)>=0;case"input":case"select":case"textarea":return(p||["change","click"]).indexOf(g.type)>=0;default:return f?(p||["click"]).indexOf(g.type)>=0:(p||["click"]).indexOf(g.type)>=0&&(SNe.indexOf(C)>-1||u.getAttribute("contenteditable")==="true")}})(o,t,a,s,s?["copy","cut","paste"]:void 0,{config:{get_current_url:i.getCurrentUrl}})){var A;const{props:u,explicitNoCapture:g,target:h}=aYo(o,{e:t,maskAllElementAttributes:i.maskAllElementAttributes,maskAllText:i.maskAllText,elementAttributeIgnoreList:i.element_attribute_ignorelist,elementsChainAsString:this.Co,disableCaptureUrlHashes:i.disableCaptureUrlHashes});if(g)return!1;const d=this.getElementSelectors(o,h);if(d&&d.length>0&&(u.$element_selectors=d),e===$Ne){const p=t.type||"clipboard";if(p!=="paste"){var c,l;const m=Fn==null||(c=Fn.getSelection())===null||c===void 0?void 0:c.toString(),_=_Ot(m);if(!_)return!1;u.$selected_content=_,u.$clipboard_text_length=(l=m?.length)!==null&&l!==void 0?l:0}u.$copy_type=p}return(A=this.bo)===null||A===void 0||A.capture(e,u),!0}}isBrowserSupported(){return nf(No?.querySelectorAll)}},cYo=class{constructor(t){this._instance=t}refresh(t){const e=this._instance.config,n=QA(e.autocapture)?e.autocapture:void 0;t.enabled=!!e.autocapture,t.rageclick=e.rageclick,t.maskAllElementAttributes=e.mask_all_element_attributes,t.maskAllText=e.mask_all_text,t.disableCaptureUrlHashes=e.disable_capture_url_hashes,t.getCurrentUrl=e.get_current_url,t.remoteRequestsDisabled=this._instance.il(),t.url_allowlist=n?.url_allowlist,t.url_ignorelist=n?.url_ignorelist,t.dom_event_allowlist=n?.dom_event_allowlist,t.element_allowlist=n?.element_allowlist,t.css_selector_allowlist=n?.css_selector_allowlist,t.css_selector_ignorelist=n?.css_selector_ignorelist,t.element_attribute_ignorelist=n?.element_attribute_ignorelist,t.capture_copied_text=n?.capture_copied_text}};const cq=Cd("[ExceptionAutocapture]"),LGt=()=>{},HGt=t=>{var e;if(nf(t))return(e=t.__posthog_layer__)!==null&&e!==void 0?e:t.__rrweb_layer__};function lq(t,e,n){try{if(!(e in t))return LGt;const o={next:t[e]},i=n(function(...r){return o.next.apply(this,r)});return nf(i)&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),t[e]=i,()=>{if(t[e]===i)return void(t[e]=o.next);let r=t[e],s=HGt(r);for(;s;){if(s.next===i)return void(s.next=o.next);r=s.next,s=HGt(r)}}}catch{return LGt}}const lYo=Cd("[TracingHeaders]"),SR=Cd("[Web Vitals]"),OGt=9e5,GGt=["CLS","FCP","INP","LCP"],uYo=["INP","LCP"],gYo=["interactionTarget","interactionType","inputDelay","processingDuration","presentationDelay","loadState","target","url","timeToFirstByte","resourceLoadDelay","resourceLoadDuration","elementRenderDelay","largestShiftTarget","largestShiftTime","largestShiftValue","firstByteToFCP"],ZNe="disabled",YGt="lazy_loading",Jb=Cd("[SessionRecording]"),dYo=[gNe,dNe,$Ht,qHt,XHt,ZHt,eOt,tOt,nOt],hYo=Cd("[Heatmaps]");function eRe(t){return QA(t)&&"clientX"in t&&"clientY"in t&&Ah(t.clientX)&&Ah(t.clientY)}const Gge=Cd("[Product Tours]"),tRe=t=>{var e;return!t.config.disable_product_tours&&!!(!((e=t.persistence)===null||e===void 0)&&e.get_property(sNe))},pYo=["$set_once","$set"],h6=Cd("[SiteApps]"),UGt="Error while initializing PostHog app with config id ",KGt=(t,e)=>t?.then?t.then(e):e(t),uG="SDK is not enabled or survey functionality is not yet loaded",VGt="Disabled. Not loading surveys.";var mYo=class{constructor(t,e){this.wo=t,this.Mh=e,this.name="surveys",this._surveyEventReceiver=null,this._surveyManager=null,this.Eh=!1,this.Ph=!1,this.Rh=[],this.Ah=[],this.Oh=null,this.Fh=null,this.To=!1,this.Dh=new Set,this.onRemoteConfig=n=>{if(this.To||this.Mr.disableSurveys)return;if(!n.ok)return this.Ph=!0,this.Lh({isLoaded:!1,error:"Remote config unavailable. Not loading surveys."}),yl.warn("Remote config unavailable. Not loading surveys.");const o=n.config.surveys;if(Hs(o))return yl.warn("Flags not loaded yet. Not loading surveys.");this.Nh=$y(o)?o:o.length>0,yl.info(`flags response received, isSurveysEnabled: ${this.Nh}`),this.loadIfEnabled()},this.Lh=n=>{this.Ah.slice().forEach(o=>this.qh(o,n))}}setup(t){if(!this.To)return this.jh=t,KGt(t.kv.initialize(),()=>{if(this.jh!==t||this.To)return;this.jh=void 0,this.bo=t;const e=t.onRemoteConfig(this.onRemoteConfig);this.To?e.dispose():(this.Eo=e,this.loadIfEnabled())})}dispose(){var t,e,n,o,i;this.To||(this.To=!0,this.jh=void 0,this.bo=void 0,(t=this.Eo)===null||t===void 0||t.dispose(),this.Eo=void 0,(e=this._surveyEventReceiver)===null||e===void 0||e.dispose(),this._surveyEventReceiver=null,(n=this._surveyManager)===null||n===void 0||(o=n.dispose)===null||o===void 0||o.call(n),this._surveyManager=null,this.Rh=[],this.Ah.forEach(r=>{r.active=!1}),this.Ah=[],(i=this.Bh)===null||i===void 0||i.call(this),this.Bh=void 0,this.Oh=null,this.Dh.forEach(r=>clearTimeout(r)),this.Dh.clear())}get Mr(){return this.wo.get()}initialize(){this.loadIfEnabled()}reset(){var t,e;(t=this._surveyManager)===null||t===void 0||(e=t.clearInMemoryInProgressSurveyState)===null||e===void 0||e.call(t);try{var n;(n=this._surveyEventReceiver)===null||n===void 0||n.reset(),localStorage.removeItem("lastSeenSurveyDate");const o=[];for(let i=0;i<localStorage.length;i++){const r=localStorage.key(i);(r?.startsWith("seenSurvey_")||r?.startsWith("inProgressSurvey_"))&&o.push(r)}o.forEach(i=>localStorage.removeItem(i))}catch{}this.Lh()}loadIfEnabled(){if(this.To||!this.bo)return;const t=this.Mr;if(this._surveyManager)return;if(this.Eh)return void yl.info("Already initializing surveys, skipping...");if(t.disableSurveys)return void yl.info(VGt);if(t.cookielessMode&&this.wo.isOptedOut())return void yl.info("Not loading surveys in cookieless mode without consent.");const e=this.wo.getExtensions();if(!e)return void this.Hh("PostHog Extensions not found.");if(Eo(this.Nh)&&!t.advancedEnableSurveys)return;const n=this.Nh||t.advancedEnableSurveys;this.Eh=!0,this.Ph=!1;try{const o=e.generateSurveys;if(o)return this.zh(o,n),void(this.Eh=!1);const i=e.loadExternalDependency;if(!i)return this.Hh(hNe),void(this.Eh=!1);i(r=>{try{if(this.To)return;const s=this.wo.getExtensions();r||!s?.generateSurveys?this.Hh("Could not load surveys script",r):this.zh(s.generateSurveys,n)}finally{this.Eh=!1}})}catch(o){throw this.Eh=!1,this.Hh("Error initializing surveys",o),o}}zh(t,e){var n,o;if(this.To)return;this._surveyManager=t(e),this._surveyEventReceiver=this.wo.createEventReceiver(this.Lh);const i=(n=(o=this.bo)!==null&&o!==void 0?o:this.Mh)===null||n===void 0?void 0:n.kv.get(O$);i&&this.Uh(i),yl.info("Surveys loaded successfully"),this.Wh(),this.Lh(),this.Vh({isLoaded:!0})}Hh(t,e){this.Ph=!0,yl.error(t,e),this.Lh({isLoaded:!1,error:t}),this.Vh({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Rh.push(t),this._surveyManager&&this.Vh({isLoaded:!0}),()=>{this.Rh=this.Rh.filter(e=>e!==t)}}getSurveys(t,e=!1){var n;const o=(n=this.bo)!==null&&n!==void 0?n:this.Mh;if(!o||this.To)return;if(this.Mr.disableSurveys)return yl.info(VGt),t([]);const i=o.kv.get(O$);if(i&&!e)return t(i,{isLoaded:!0}),void(this.Gh()&&this.getSurveys(()=>{},!0));if(this.Oh)return void this.Oh.then(({surveys:a,context:A})=>{this.To||t(a,A)}).catch(a=>yl.error("Error in survey callback",a));const r=this.Qh("/api/surveys/",{method:"GET",query:{token:o.projectToken},sentAt:"query",timeoutMs:this.Mr.requestTimeoutMs}).then(a=>{try{return this.Jh(o,a)}catch(A){return yl.error("Error processing surveys response",A),this.Jh(o,{statusCode:0,error:A})}},a=>this.Jh(o,{statusCode:0,error:a}));this.Oh=r;const s=()=>{this.Oh===r&&(this.Oh=null)};r.then(a=>{s(),this.To||(this.Lh(a.context),t(a.surveys,a.context))},s).catch(a=>yl.error("Error in survey callback",a))}Qh(t,e){const n=this.bo;return n?n.sendRequest(t,e):new Promise(o=>o({statusCode:0,error:new Error(uG)}))}Jh(t,e){if(this.To)return{surveys:[],context:{isLoaded:!1,error:uG}};const n=e.statusCode;if(n!==200||!e.json){const i=`Surveys API could not be loaded, status: ${n}`;return n!==0?yl.error(i):e.error||yl.warn(i),this.Fh=Date.now(),{surveys:[],context:{isLoaded:!1,error:i}}}this.Fh=null;const o=e.json.surveys||[];return t.kv.set({[O$]:o,[bge]:Date.now()}),this.Uh(o),{surveys:o,context:{isLoaded:!0}}}Uh(t){var e;const n=t.filter(o=>(function(i){return!(!i.start_date||i.end_date)})(o)&&(BGt(o)||(function(i){var r;return!!(!((r=i.conditions)===null||r===void 0||(r=r.actions)===null||r===void 0||(r=r.values)===null||r===void 0)&&r.length)})(o)));(e=this._surveyEventReceiver)===null||e===void 0||e.replace(n)}Gh(){return this.Zh()&&!this.Oh&&!this.Kh()}Zh(){var t,e;const n=(t=(e=this.bo)!==null&&e!==void 0?e:this.Mh)===null||t===void 0?void 0:t.kv.get(bge);return Ah(n)&&Date.now()-n>3e5}Kh(){return Ah(this.Fh)&&3e5>Date.now()-this.Fh}markSurveyAsSeen(t,e){var n;const o={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};vGt(o);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}this.Lh()}Vh(t){for(const e of this.Rh)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){yl.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e=!1){if(!Hs(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);yl.warn("init was not called")}onActiveMatchingSurveysChanged(t){var e,n;if(this.To)return()=>{};const o={callback:t,active:!0,revision:0};this.Ah.push(o),this.Wh();const i=(e=(n=this.bo)!==null&&n!==void 0?n:this.Mh)===null||e===void 0?void 0:e.kv.get(O$);return this.Mr.disableSurveys||!this._surveyManager&&this.Ph&&!this.Eh||!i&&!Hs(this.Fh)&&!this.Oh?this.qh(o,{isLoaded:!1}):this._surveyManager&&this.qh(o),()=>{var r;o.active=!1,this.Ah=this.Ah.filter(s=>s!==o),this.Ah.length===0&&((r=this.Bh)===null||r===void 0||r.call(this),this.Bh=void 0)}}Wh(){var t,e,n;this._surveyManager&&this.Ah.length>0&&((t=this.Bh)!==null&&t!==void 0||(this.Bh=(e=(n=this.wo).onMatchingConditionsChanged)===null||e===void 0?void 0:e.call(n,this.Lh)))}qh(t,e){if(this.To||!t.active)return;const n=++t.revision,o=i=>{if(!this.To&&t.active&&n===t.revision)try{const r=e??{isLoaded:!0},s=JSON.stringify([i,r]);if(s===t.lastResult)return;t.lastResult=s,t.callback(i,r)}catch(r){yl.error("Error in active matching surveys callback",r)}};try{e&&!e.isLoaded?o([]):this.getActiveMatchingSurveys(o)}catch(i){yl.error("Error in active matching surveys callback",i)}}Xh(t){let e=null;return this.getSurveys(n=>{var o;e=(o=n.find(i=>i.id===t))!==null&&o!==void 0?o:null}),e}Yh(t){if(Hs(this._surveyManager))return{eligible:!1,reason:uG};const e=typeof t=="string"?this.Xh(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}tc(t){if(!this.wo.isCapturing())return{eligible:!1,reason:"PostHog is not capturing, so a survey response cannot be recorded"};if(Hs(this._surveyManager))return{eligible:!1,reason:uG};const e=typeof t=="string"?this.Xh(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(Hs(this._surveyManager))return yl.warn("init was not called"),{visible:!1,disabledReason:uG};const e=this.tc(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return Hs(this._surveyManager)?(yl.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:uG})):new Promise(n=>{this.getSurveys(o=>{var i;const r=(i=o.find(s=>s.id===t))!==null&&i!==void 0?i:null;if(r){const s=this.tc(r);n({visible:s.eligible,disabledReason:s.reason})}else n({visible:!1,disabledReason:"Survey not found"})},e)})}renderSurvey(t,e,n){var o;if(!this.wo.isCapturing())return;if(Hs(this._surveyManager))return void yl.warn("init was not called");const i=typeof t=="string"?this.Xh(t):t;if(!i?.id)return void yl.warn("Survey not found");if(!VGo.includes(i.type))return void yl.warn(`Surveys of type ${i.type} cannot be rendered in the app`);const r=No?.querySelector(e);if(r){if(!((o=i.appearance)===null||o===void 0)&&o.surveyPopupDelaySeconds){yl.info(`Rendering survey ${i.id} with delay of ${i.appearance.surveyPopupDelaySeconds} seconds`);const s=setTimeout(()=>{var a,A;this.Dh.delete(s),!this.To&&this.wo.isCapturing()&&(yl.info(`Rendering survey ${i.id} with delay of ${(a=i.appearance)===null||a===void 0?void 0:a.surveyPopupDelaySeconds} seconds`),(A=this._surveyManager)===null||A===void 0||A.renderSurvey(i,r,n),yl.info(`Survey ${i.id} rendered`))},1e3*i.appearance.surveyPopupDelaySeconds);return void this.Dh.add(s)}this._surveyManager.renderSurvey(i,r,n)}else yl.warn("Survey element not found")}displaySurvey(t,e){var n;if(!this.wo.isCapturing())return;if(Hs(this._surveyManager))return void yl.warn("init was not called");const o=this.Xh(t);if(!o)return void yl.warn("Survey not found");let i=o;if(!((n=o.appearance)===null||n===void 0)&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(i=sn(sn({},o),{},{appearance:sn(sn({},o.appearance),{},{surveyPopupDelaySeconds:0})})),e.displayType!==TNe.Popover&&e.initialResponses&&yl.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){const r=this.Yh(o);if(!r.eligible)return void yl.warn("Survey is not eligible to be displayed: ",r.reason)}e.displayType!==TNe.Inline?this._surveyManager.handlePopoverSurvey(i,e):this.renderSurvey(i,e.selector,e.properties)}cancelPendingSurvey(t){Hs(this._surveyManager)?yl.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t,e;(t=this._surveyManager)===null||t===void 0||(e=t.handlePageUnload)===null||e===void 0||e.call(t)}};function gG(t,e,n){if(Hs(t))return!1;switch(n){case"exact":return t===e;case"contains":{const o=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(o,"i").test(t)}case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}var _Yo=class{constructor(e){this._instance=e,this.ec=new Set,this.nc=new Set,this.sc=new Lge,this.rc=(n,o)=>this.oc(n,o)&&this.ac(n,o)&&this.lc(n,o)&&this.uc(n,o),this.oc=(n,o)=>!o?.event||n?.event===o?.event}init(){var e,n;Eo((e=this._instance)===null||e===void 0?void 0:e._addCaptureHook)||(this.hc=(n=this._instance)===null||n===void 0?void 0:n._addCaptureHook((o,i)=>{this.on(o,i)}))}dispose(){var e,n;(e=this.hc)===null||e===void 0||e.call(this),this.hc=void 0,(n=this._instance)===null||n===void 0||(n=n.autocapture)===null||n===void 0||n.setElementSelectors(new Set,this),this.sc=new Lge}register(e){var n,o;if(!Eo((n=this._instance)===null||n===void 0?void 0:n._addCaptureHook)&&(e.forEach(i=>{var r;this.ec.add(i),(r=i.steps)===null||r===void 0||r.forEach(s=>{this.nc.add(s?.event||"")})}),(o=this._instance)===null||o===void 0?void 0:o.autocapture)){const i=new Set;this.ec.forEach(r=>{var s;(s=r.steps)===null||s===void 0||s.forEach(a=>{a?.selector&&i.add(a.selector)})}),this._instance.autocapture.setElementSelectors(i,this)}}replace(e){this.ec.clear(),this.nc.clear(),this.register(e)}on(e,n){n!=null&&e.length!=0&&(this.nc.has(e)||this.nc.has(n.event))&&this.ec.forEach(o=>{this.cc(n,o)&&this.sc.emit("actionCaptured",o.name)})}dc(e){this.onAction("actionCaptured",n=>e(n))}cc(e,n){if(n?.steps==null)return!1;for(const o of n.steps)if(this.rc(e,o))return!0;return!1}onAction(e,n){return this.sc.on(e,n)}ac(e,n){if(n?.url){var o;const i=e==null||(o=e.properties)===null||o===void 0?void 0:o.$current_url;if(!i||typeof i!="string"||!gG(i,n.url,n.url_matching||"contains"))return!1}return!0}lc(e,n){return!!this.vc(e,n)&&!!this.fc(e,n)&&!!this.gc(e,n)}vc(e,n){var o;if(!n?.href)return!0;const i=this.mc(e);if(i.length>0)return i.some(s=>gG(s.href,n.href,n.href_matching||"exact"));const r=(e==null||(o=e.properties)===null||o===void 0?void 0:o.$elements_chain)||"";return!!r&&gG((function(s){const a=s.match(/(?::|")href="(.*?)"/);return a?a[1]:""})(r),n.href,n.href_matching||"exact")}fc(e,n){var o;if(!n?.text)return!0;const i=this.mc(e);if(i.length>0)return i.some(c=>gG(c.text,n.text,n.text_matching||"exact")||gG(c.$el_text,n.text,n.text_matching||"exact"));const r=(e==null||(o=e.properties)===null||o===void 0?void 0:o.$elements_chain)||"";return!!r&&(s=(function(c){const l=[],u=/(?::|")text="(.*?)"/g;let g;for(;!Hs(g=u.exec(c));)l.includes(g[1])||l.push(g[1]);return l})(r),a=n.text,A=n.text_matching||"exact",s.some(c=>gG(c,a,A)));var s,a,A}gc(e,n){var o,i;if(!n?.selector)return!0;const r=e==null||(o=e.properties)===null||o===void 0?void 0:o.$element_selectors;if(r?.includes(n.selector))return!0;const s=(e==null||(i=e.properties)===null||i===void 0?void 0:i.$elements_chain)||"";if(n.selector_regex&&s)try{return new RegExp(n.selector_regex).test(s)}catch{return!1}return!1}mc(e){var n;return(e==null||(n=e.properties)===null||n===void 0?void 0:n.$elements)==null?[]:e?.properties.$elements}uc(e,n){return!n?.properties||n.properties.length===0||SGt(n.properties.reduce((o,i)=>{const r=As(i.value)?i.value.map(String):i.value!=null?[String(i.value)]:[];return o[i.key]={values:r,operator:i.operator||"exact"},o},{}),e?.properties)}},fYo=class{constructor(e,n){var o,i;this.yc=[],this._instance=e,this.bc=n,this._c=new Map,this.wc=new Map,this.kc=new Map,this.Sc=(o=this._instance)===null||o===void 0||(i=o.onSessionId)===null||i===void 0?void 0:i.call(o,r=>this.xc(r))}$c(e){return!1}Cc(){return null}Tc(e){}Ic(){}Mc(e,n){return!!e&&SGt(e.propertyFilters,n?.properties)}Ec(e,n){const o=new Map;return e.forEach(i=>{var r;(r=i.conditions)===null||r===void 0||(r=r[n])===null||r===void 0||(r=r.values)===null||r===void 0||r.forEach(s=>{if(s?.name){const a=o.get(s.name)||[];a.push(i.id),o.set(s.name,a)}})}),o}Pc(e,n,o){const i=(o===eq.Activation?this._c:this.wc).get(e);let r=[];return this.Rc(s=>{r=s.filter(a=>i?.includes(a.id))}),r.filter(s=>{var a;const A=(a=s.conditions)===null||a===void 0||(a=a[o])===null||a===void 0||(a=a.values)===null||a===void 0?void 0:a.find(c=>c.name===e);return this.Mc(A,n)})}register(e){this.Ac(e,!1)}replace(e){this.Ac(e,!0)}Ac(e,n){var o;Eo((o=this._instance)===null||o===void 0?void 0:o._addCaptureHook)||(this.Oc(e,n),this.Fc(e,n))}Fc(e,n){const o=e.filter(s=>{var a;return(a=s.conditions)===null||a===void 0||(a=a.actions)===null||a===void 0||(a=a.values)===null||a===void 0?void 0:a.length});var i;if(n&&this.kc.clear(),o.length===0)return void(n&&((i=this.Dc)===null||i===void 0||i.replace([])));this.Dc||(this.Dc=new _Yo(this._instance),this.Dc.init(),this.Dc.dc(s=>this.onAction(s)));const r=[];o.forEach(s=>{var a;(a=s.conditions)===null||a===void 0||(a=a.actions)===null||a===void 0||a.values.forEach(A=>{if(r.push(A),A.name){var c;const l=(c=this.kc.get(A.name))!==null&&c!==void 0?c:[];l.includes(s.id)||l.push(s.id),this.kc.set(A.name,l)}})}),n?this.Dc.replace(r):this.Dc.register(r)}Lc(e,n){n.forEach((o,i)=>{var r;const s=(r=e.get(i))!==null&&r!==void 0?r:[];o.forEach(a=>{s.includes(a)||s.push(a)}),e.set(i,s)})}Oc(e,n){var o,i;const r=e.filter(c=>{var l,u;return((l=c.conditions)===null||l===void 0?void 0:l.events)&&((u=c.conditions)===null||u===void 0||(u=u.events)===null||u===void 0||(u=u.values)===null||u===void 0?void 0:u.length)>0}),s=e.filter(c=>{var l,u;return((l=c.conditions)===null||l===void 0?void 0:l.cancelEvents)&&((u=c.conditions)===null||u===void 0||(u=u.cancelEvents)===null||u===void 0||(u=u.values)===null||u===void 0?void 0:u.length)>0}),a=this.Ec(e,eq.Activation),A=this.Ec(e,eq.Cancellation);n?(this._c=a,this.wc=A):(this.Lc(this._c,a),this.Lc(this.wc,A)),(r.length!==0||s.length!==0||e.some(c=>{var l;return(l=c.conditions)===null||l===void 0||(l=l.actions)===null||l===void 0||(l=l.values)===null||l===void 0?void 0:l.length}))&&((o=this.hc)!==null&&o!==void 0||(this.hc=(i=this._instance)===null||i===void 0?void 0:i._addCaptureHook((c,l)=>{this.onEvent(c,l)})))}onEvent(e,n){var o,i;const r=this.Nc(),s=(n==null||(o=n.properties)===null||o===void 0?void 0:o.$survey_id)||(n==null||(i=n.properties)===null||i===void 0?void 0:i.$product_tour_id);if(s&&this.getActivatedIds().includes(s)){const A=this.qc(e,s,n);if(A==="consume")return r.info("event consumed activated item, removing it",{event:e,itemId:s}),void this.jc([s]);if(A==="persist")return r.info("shown item promoted to persisted activation",{event:e,itemId:s}),this.Bc(s),void this.Hc([s])}if(this.wc.has(e)){const A=this.Pc(e,n,eq.Cancellation);A.length>0&&(r.info("cancel event matched, cancelling items",{event:e,itemsToCancel:A.map(c=>c.id)}),this.jc(A.map(c=>c.id)),A.forEach(c=>this.zc(c.id)))}if(!this._c.has(e))return;r.info("event name matched",{event:e,eventPayload:n,items:this._c.get(e)});const a=this.Pc(e,n,eq.Activation);this.Uc(a.map(A=>A.id))}onAction(e){this.kc.has(e)&&this.Uc(this.kc.get(e)||[])}Uc(e){var n,o;if(e.length===0)return;const i=!!(!((n=this._instance)===null||n===void 0||(o=n.get_session_id)===null||o===void 0)&&o.call(n)),r=[];for(const s of e)i&&this.$c(s)?this.Bc(s)&&this.Wc(s):r.push(s);r.length>0&&(this.yc=[...new Set([...this.yc,...r])]),this.Nc().info("updating activated items",{activatedItems:this.getActivatedIds()}),this.Vc()}Bc(e){this.yc=this.yc.filter(o=>o!==e);const n=this.Gc();return!n.includes(e)&&(this.Qc([...n,e]),this.Jc(),!0)}jc(e){const n=new Set(e);this.yc=this.yc.filter(r=>!n.has(r));const o=this.Zc(),i=o.filter(r=>!n.has(r));i.length!==o.length&&(this.Qc(i),i.length===0&&this.Kc()),this.Hc(e),this.Vc()}Vc(){try{var e;(e=this.bc)===null||e===void 0||e.call(this)}catch(n){this.Nc().error("Error while handling activated items change",n)}}Xc(){var e;const n=this.Cc();if(!n)return{};const o=(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.props[n];return o&&typeof o=="object"?o:{}}Wc(e){if(!this.Cc())return;const n=this.Xc();this.Tc(sn(sn({},n),{},{[e]:Date.now()}))}Hc(e){if(!this.Cc())return;const n=this.Xc(),o={};let i=!1;for(const[r,s]of Object.entries(n))e.includes(r)?i=!0:o[r]=s;i&&(Rx(o)?this.Ic():this.Tc(o))}Yc(){this.Cc()&&this.Ic()}getActivationTimestamp(e){if(!this.Gc().includes(e))return;const n=this.Xc()[e];return Ah(n)?n:void 0}Zc(){var e;const n=this.td();return((e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.props[n])||[]}Gc(){var e,n,o;const i=this.Zc();if(i.length===0)return[];const r=(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.props[this.ed()],s=(n=this._instance)===null||n===void 0||(o=n.get_session_id)===null||o===void 0?void 0:o.call(n);return s&&r===s?i:[]}Jc(){var e,n;const o=(e=this._instance)===null||e===void 0||(n=e.get_session_id)===null||n===void 0?void 0:n.call(e);o&&this.nd(o)}Kc(){this.sd()}xc(e){var n;const o=(n=this._instance)===null||n===void 0||(n=n.persistence)===null||n===void 0?void 0:n.props[this.ed()];if(o&&o!==e){const i=this.Zc(),r=this.Xc();i.length>0&&(this.Qc([]),i.filter(s=>Ah(r[s])).forEach(s=>this.zc(s))),this.Kc(),this.Yc(),i.length>0&&this.Vc()}}getActivatedIds(){return[...new Set([...this.Gc(),...this.yc])].filter(e=>!this.rd(e))}dispose(){var e,n,o;(e=this.Sc)===null||e===void 0||e.call(this),this.Sc=void 0,(n=this.hc)===null||n===void 0||n.call(this),this.hc=void 0,(o=this.Dc)===null||o===void 0||o.dispose(),this.Dc=void 0}reset(){this.yc=[],this.Zc().length>0&&this.Qc([]),this.Kc(),this.Yc(),this.Vc()}getEventToItemsMap(){return this._c}od(){return this.Dc}},IYo=class extends fYo{constructor(e,n){super(e,n)}td(){return YHt}ed(){return UHt}Cc(){return KHt}Tc(e){var n;(n=this._instance)===null||n===void 0||(n=n.persistence)===null||n===void 0||n.register({$surveys_activated_timestamps:e})}Ic(){var e;(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0||e.unregister("$surveys_activated_timestamps")}$c(e){var n;let o;this.Rc(r=>{o=r.find(s=>s.id===e)});const i=o==null||(n=o.appearance)===null||n===void 0?void 0:n.surveyPopupDelaySeconds;return Ah(i)&&i>0}ad(){return dE.SHOWN}Rc(e){var n;(n=this._instance)===null||n===void 0||n.getSurveys(e)}zc(e){var n;(n=this._instance)===null||n===void 0||n.cancelPendingSurvey(e)}Nc(){return yl}Qc(e){var n;(n=this._instance)===null||n===void 0||(n=n.persistence)===null||n===void 0||n.register({$surveys_activated:e})}nd(e){var n;(n=this._instance)===null||n===void 0||(n=n.persistence)===null||n===void 0||n.register({$surveys_activated_session:e})}sd(){var e;(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0||e.unregister("$surveys_activated_session")}rd(){return!1}qc(e,n,o){var i;if(e===dE.SENT&&(o==null||(i=o.properties)===null||i===void 0?void 0:i.$survey_completed)===!1)return"ignore";let r;return this.Rc(s=>{r=s.find(a=>a.id===n)}),!r||(function(s){var a;return BGt(s)&&!!(!((a=s.conditions)===null||a===void 0||(a=a.events)===null||a===void 0)&&a.repeatedActivation)||s.schedule==="always"})(r)?e===dE.SHOWN?"consume":"ignore":e===dE.SHOWN?"persist":e===dE.DISMISSED||e===dE.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},CYo=class{constructor(e){this._instance=e}initialize(){}get(e){if(typeof e=="string")return this._instance.get_property(e);const n={};for(const o of e){const i=this._instance.get_property(o);Eo(i)||(n[o]=i)}return n}set(e,n){this._instance.register(typeof e=="string"?{[e]:n}:e)}remove(e){typeof e!="string"?e.forEach(n=>this._instance.unregister(n)):this._instance.unregister(e)}},yYo=class{constructor(e){this._instance=e}get(){const e=this._instance.config;return{disableSurveys:e.disable_surveys,cookielessMode:!!e.cookieless_mode,advancedEnableSurveys:e.advanced_enable_surveys,requestTimeoutMs:e.surveys_request_timeout_ms}}isOptedOut(){return this._instance.consent.isOptedOut()}isCapturing(){return this._instance.is_capturing()}getExtensions(){const e=Vr?.__PosthogExtensions__;if(!e)return;const{generateSurveys:n,loadExternalDependency:o}=e;return{generateSurveys:n?i=>n(this._instance,i):void 0,loadExternalDependency:o?i=>o(this._instance,"surveys",i):void 0}}createEventReceiver(e){return new IYo(this._instance,e)}onMatchingConditionsChanged(e){const n=this._instance._addCaptureHook(s=>{s!=="$pageview"&&s!==dE.SHOWN&&s!==dE.DISMISSED&&s!==dE.SENT||e()}),o=()=>e();el(Fn,"PHSurveyShown",o);let i=!1;const r=this._instance.onFeatureFlags(()=>{i&&e()});return i=!0,()=>{i=!1,n(),r(),Fn?.removeEventListener("PHSurveyShown",o)}}};const xYo=Fn?.location?Mge(Fn.location.hash,"__posthog")||Mge(location.hash,"state"):null,zGt="_postHogToolbarParams",JGt=Cd("[Toolbar]"),WGt=Cd("[FeatureFlags]");var EYo=class{constructor(e,n=!1){this.ld=!1,this.update(e,n)}update(e,n){this.ud=((o,i)=>{var r,s,a,A,c,l,u,g;return{bootstrap:{featureFlags:(r=(s=o.bootstrap)===null||s===void 0?void 0:s.featureFlags)!==null&&r!==void 0?r:void 0,featureFlagPayloads:(a=(A=o.bootstrap)===null||A===void 0?void 0:A.featureFlagPayloads)!==null&&a!==void 0?a:void 0},remoteRequestsDisabled:i,featureFlagsDisabled:!!o.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!o.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!o.advanced_feature_flags_dedup_per_session,cacheTtlMs:o.feature_flag_cache_ttl_ms,refreshIntervalMs:(c=o.remote_config_refresh_interval_ms)!==null&&c!==void 0?c:3e5,idleRefreshBackoff:Eo(o.remote_config_refresh_interval_ms),requestTimeoutMs:o.feature_flag_request_timeout_ms,requestMaxRetries:Math.max(0,(l=o.feature_flag_request_max_retries)!==null&&l!==void 0?l:1),compression:o.disable_compression?void 0:"best-available",evaluationContexts:(u=(g=o.evaluation_contexts)!==null&&g!==void 0?g:o.evaluation_environments)!==null&&u!==void 0?u:[],flagKeys:As(o.flag_keys)?o.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.ld||(WGt.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.ld=!0),Eo(e.flag_keys)||As(e.flag_keys)||WGt.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.ud}};const jGt=Cd("[FeatureFlags]"),QR=Cd("[FeatureFlags]",{debugEnabled:!0}),nRe=`" failed. Feature flags didn't load in time.`,BYo=[502,504],$Gt=["click","keydown","wheel","touchstart","pointerdown"],qGt="connection_error",XGt=t=>{const e={};for(let n=0;t.length>n;n++)e[t[n]]=!0;return e},ZGt=t=>{const e={};for(const[n,o]of vge(t||{}))o&&(e[n]=o);return e},eYt=t=>zO(t)&&(t.name==="RangeError"&&t.message.indexOf("Maximum call stack size exceeded")===0||t.name==="InternalError"&&t.message==="too much recursion"),FB=Cd("[Error tracking]"),oRe="webkit-masked-url:",bYo=[{value:"isolatedAPI.contexts.topHostname",exact:!1},{value:"No response from target",exact:!0}],SYo=["chrome-extension://","moz-extension://","safari-extension:","safari-web-extension:",oRe],QYo=["__firefox__","__gCrWeb"],tYt="Refusing to render web experiment since the viewer is a likely bot",vYo={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>Hge(e,t),not_regex:(t,e)=>!Hge(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t},A4=Cd("[Conversations]"),vR="Conversations not available yet.";function nYt(t,e){var n,o,i,r,s,a,A;const c=(n=t?.flushIntervalMs)!==null&&n!==void 0?n:3e3,l=(o=t?.maxBufferSize)!==null&&o!==void 0?o:100,u=e?.consoleCapture?void 0:(i=t?.maxLogsPerInterval)!==null&&i!==void 0?i:1e3,g=Eo(u)?Math.max(l,2048):Math.max(l,u),h=sn(sn({},(function(){let d="",p="";try{const m=tf?.userAgent;m&&([d,p]=WLt(m))}catch{}return(function(m,_){const f=(function(I){if(I)return{}.hasOwnProperty.call(EHt,I)?EHt[I]:I})(m);return sn(sn({},f?{"os.name":f}:{}),_?{"os.version":_}:{})})(d,p)})()),t?.resourceAttributes);return{serviceName:(r=(s=h?.["service.name"])!==null&&s!==void 0?s:t?.serviceName)!==null&&r!==void 0?r:e?.serviceNameDefault,serviceVersion:(a=h?.["service.version"])!==null&&a!==void 0?a:t?.serviceVersion,environment:(A=h?.["deployment.environment"])!==null&&A!==void 0?A:t?.environment,resourceAttributes:h,beforeSend:t?.beforeSend,flushIntervalMs:c,maxBufferSize:l,maxQueueSize:g,maxBatchRecordsPerPost:100,rateCapWindowMs:c,maxLogsPerInterval:u,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}}const wYo=["debug","log","warn","error","info"],PYo=t=>{for(;t?.__rrweb_original__;)t=t.__rrweb_original__;return t},oYt="console",iYt="__posthogHandledLogsRequestError",iRe=(t,e)=>{const n=t instanceof Error?t:new Error(e);return n[iYt]=!0,n},rYt=t=>!!t&&typeof t=="object"&&t[iYt]===!0,Yge=Cd("[NetworkMetrics]"),rRe=()=>{var t;return!(Fn==null||(t=Fn.performance)===null||t===void 0)&&t.now?Fn.performance.now():Date.now()},MYo={"http:":80,"https:":443},DYo=new Set(["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"]),sYt=(t,e)=>{var n;const o=String(e);return{method:String(t).toUpperCase(),url:((n=Kb(o))===null||n===void 0?void 0:n.href)||o}},sRe=(t,e,n,o,i,r,s=!1)=>{try{var a,A;const c=i();if(!c)return;const l=n||void 0,u=rRe()-o,g=Kb(e.url);if(g&&g.protocol!=="http:"&&g.protocol!=="https:")return;const h={url:g?.href||e.url,method:e.method},d=nf(c.name)?c.name(h):rA(c.name)?c.name:"http.client.request.duration";if(!d)return;const p=s&&!l?void 0:((_,f)=>_?400>_?void 0:String(_):f?.name||"_OTHER")(l,r),m=sn(sn(sn(sn(sn({},(_=>{const f=DYo.has(_)?_:"_OTHER";return sn({"http.request.method":f},f==="_OTHER"&&_!==f?{"http.request.method_original":_}:{})})(h.method)),g?(_=>{return{"server.address":_.hostname.startsWith("[")&&_.hostname.endsWith("]")?_.hostname.slice(1,-1):_.hostname,"server.port":Number(_.port)||MYo[_.protocol],"url.scheme":_.protocol.slice(0,-1),"url.template":(f=_.pathname,f.split("/").map(I=>(C=>/^\d+$/.test(C)||C.length>=8&&/^[0-9a-f-]*\d[0-9a-f-]*$/i.test(C))(I)?":id":I).join("/"))};var f})(g):{}),l?{"http.response.status_code":l}:{}),p?{"error.type":p}:{}),(a=c.attributes)===null||a===void 0?void 0:a.call(c,h,{status:l,durationMs:u}));(A=t.metrics)===null||A===void 0||A.histogram(d,u,{unit:"ms",attributes:m})}catch(c){Yge.error("Failed to record network metric",c)}},aYt=()=>{},NYo=(t,e)=>nf(Fn?.fetch)?lq(Fn,"fetch",n=>function(...o){const i=rRe(),r=n.apply(this,o);if(!e())return r;try{var s,a,A;const[c,l]=o,u=sYt((s=(a=l?.method)!==null&&a!==void 0?a:c?.method)!==null&&s!==void 0?s:"GET",(A=c?.url)!==null&&A!==void 0?A:c);return r.then(g=>(sRe(t,u,g?.status,i,e,void 0,!0),g),g=>{throw sRe(t,u,void 0,i,e,g),g})}catch(c){return Yge.error("Failed to observe fetch",c),r}}):aYt,RYo=(t,e)=>{var n;const o=Fn==null||(n=Fn.XMLHttpRequest)===null||n===void 0?void 0:n.prototype;if(!o)return aYt;const i=new WeakMap,r=lq(o,"open",a=>function(...A){try{aGt.has(this)||i.set(this,sYt(A[0],A[1]))}catch(c){Yge.error("Failed to observe XHR open",c)}return a.apply(this,A)}),s=lq(o,"send",a=>function(...A){let c;try{const l=i.get(this);if(l&&e()){const u=rRe();c=()=>{this.removeEventListener("loadend",c),sRe(t,l,this.status,u,e)},el(this,"loadend",c)}}catch(l){Yge.error("Failed to observe XHR send",l)}try{return a.apply(this,A)}catch(l){throw c&&this.removeEventListener("loadend",c),l}});return()=>{r(),s()}},Uge={featureFlags:class{constructor(t){this.name="featureFlags",this.hd=!1,this.featureFlagEventHandlers=[],this.A=jGt,this.dd={},this.vd={},this.fd=[],this.pd=!1,this.gd=!1,this.md=0,this.yd=!1,this.bd=!1,this._d=!1,this.wd=!1,this.kd=0,this.Sd=!1,this.rn=()=>{const e=this.xd();this.kd=0,e&&this.reloadFeatureFlags()},this.$d=()=>{var e,n;const o=this.Cd,i=(e=this.Td)!==null&&e!==void 0?e:o;Eo(o)||Eo(i)||this.Mr.remoteRequestsDisabled||!No||No.visibilityState==="hidden"||Date.now()-((n=this.Id)!==null&&n!==void 0?n:0)<i||(this.Td=this.Sd||!this.Mr.idleRefreshBackoff?o:Math.min(2*i,36e5),this.Sd=!1,this.reloadFeatureFlags(),this.Md())},this.Ed=()=>{this.Sd&&this.Td===this.Cd||this.Pd()},this.sn=()=>{No?.visibilityState==="visible"&&this.Pd()},"get"in t?this.wo=t:(this._instance=t,this.Rd=new EYo(t.config,t.il()),this.wo=this.Rd)}updateConfig(t,e){var n;(n=this.Rd)===null||n===void 0||n.update(t,e),this.bo&&this.Ad()}setup(t){return this.jh=t,this.A=t.logger.createLogger("[FeatureFlags]"),KGt(t.kv.initialize(),()=>{this.jh===t&&(this.jh=void 0,this.bo=t,this.Od(t))})}Od(t){var e;if(this.bo===t)return Fn&&el(Fn,"online",this.rn),this.Ad(),this.Fd=t.registerDynamicEventProperties(()=>this.Dd()?this.dd:this.vd),this.Ld=(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.onCrossTabFeatureFlagChange(()=>{this.Nd(),this.qd(),this.jd()}),this.qd(),this.initialize()}Pd(){this.Sd=!0,this.Td=this.Cd,this.$d()}Ad(){const t=this.Mr.refreshIntervalMs,e=!this.Mr.remoteRequestsDisabled&&No&&!Eo(t)&&t>0?t:void 0;this.Mr.idleRefreshBackoff||(this.Td=e),e!==this.Cd&&(this.Bd(),Eo(e)||(this.Cd=e,this.Td=e,this.Md(),No?.addEventListener&&(el(No,U$,this.sn),XO($Gt,n=>{el(No,n,this.Ed,{capture:!0})}))))}Md(){Eo(this.Cd)||(Eo(this.Hd)||clearInterval(this.Hd),this.Id=Date.now(),this.Hd=setInterval(this.$d,this.Cd))}Bd(){var t;Eo(this.Hd)||(clearInterval(this.Hd),this.Hd=void 0,No==null||(t=No.removeEventListener)===null||t===void 0||t.call(No,"visibilitychange",this.sn),XO($Gt,e=>{var n;No==null||(n=No.removeEventListener)===null||n===void 0||n.call(No,e,this.Ed,{capture:!0})})),this.Cd=void 0,this.Td=void 0,this.Sd=!1,this.Id=void 0}destroy(){this.zd()}dispose(){this.zd()}zd(){var t,e;this.Bd(),this.md++,this.bd=!1,this.jh=void 0,this.bo&&(this.Ud(),(t=this.Fd)===null||t===void 0||t.dispose(),this.Fd=void 0,(e=this.Ld)===null||e===void 0||e.call(this),this.Ld=void 0,this.fd=[],Fn?.removeEventListener("online",this.rn),this.bo=void 0)}get Mr(){return this.wo.get()}Wd(t){var e;return this.Vd&&t in this.Vd?this.Vd[t]:(e=this.bo)===null||e===void 0?void 0:e.kv.get(t)}Nd(){return!!this.Vd&&(this.Vd=void 0,!0)}Gd(){var t;return!Eo((t=this.bo)===null||t===void 0?void 0:t.kv.get("$enabled_feature_flags"))&&this.Nd()}$t(t){this.Qd(()=>{var e;return(e=this.bo)===null||e===void 0?void 0:e.kv.set(t)})}Jd(t,e,n){var o;if(!(!((o=this._instance)===null||o===void 0)&&o.persistence)||!t.$enabled_feature_flags)return;const i=this.Wd("$enabled_feature_flags")||{},r=t.$enabled_feature_flags||{},s=e.flags||e.featureFlags,a=e.flags?Object.entries(e.flags).filter(([,_])=>!_?.failed).map(([_])=>_):[],A=!!e.errorsWhileComputingFlags&&!!e.flags,c=A?a:n&&!As(s)?Object.keys(s||{}):Array.from(new Set([...Object.keys(i),...Object.keys(r)])),l=this.Wd("$feature_flag_payloads")||{},u=t.$feature_flag_payloads||{},g=A||n?c:Array.from(new Set([...Object.keys(l),...Object.keys(u)])),h=!A&&!n,d=!!h||c,p=!!h||g,m={[Yb]:d,[TB]:d,[Dw]:p};t.$feature_flag_details&&(m[CR]=d);for(const _ of[yR,kw,H$])Eo(t[_])||(m[_]=!0);this._instance.persistence.markCrossTabFeatureFlagChanges(m)}Pt(t){this.Qd(()=>{var e;return(e=this.bo)===null||e===void 0?void 0:e.kv.remove(t)})}Qd(t){try{t()}catch(e){this.A.error("Failed to update feature flag persistence",e)}}qd(){const t={};for(const o of[Yb,Dw,yR,g6]){const i=this.Wd(o);Eo(i)||(t[o]=i)}this.dd=t;const e=sn({},t),n=this.Wd(TB);if(n)for(const[o,i]of Object.entries(n))e[`$feature/${o}`]=i;this.vd=e}Dd(){const t=this.Mr.cacheTtlMs;if(!t||0>=t)return!1;const e=this.Wd(kw);return typeof e!="number"||Date.now()-e>t}Zd(){return!!this.Dd()&&(this.wd||this.gd||(this.wd=!0,this.A.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Kd(){const t=this.Mr.evaluationContexts;return t?.length?t.filter(e=>{const n=e&&typeof e=="string"&&e.trim().length>0;return n||this.A.error("Invalid evaluation context found:",e,"Expected non-empty string"),n}):[]}Xd(){const t=this.Mr.flagKeys;if(!Eo(t))return t.filter(e=>{const n=e&&typeof e=="string"&&e.trim().length>0;return n||this.A.error("Invalid flag key found:",e,"Expected non-empty string"),n})}initialize(){var t,e;const n=this.Mr,o=(t=(e=n.bootstrap)===null||e===void 0?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(o).length){var i,r;const s=(i=(r=n.bootstrap)===null||r===void 0?void 0:r.featureFlagPayloads)!==null&&i!==void 0?i:{},a=Object.keys(o).filter(c=>!Eo(o[c])).reduce((c,l)=>(c[l]=o[l],c),{}),A=Object.keys(s).filter(c=>a[c]).reduce((c,l)=>(c[l]=s[l],c),{});return this.Yd({featureFlags:a,featureFlagPayloads:A},void 0,{persist:!1})}}updateFlags(t,e,n){var o,i;const r=n?.merge&&(o=this.Wd("$enabled_feature_flags"))!==null&&o!==void 0?o:{},s=n?.merge&&(i=this.Wd("$feature_flag_payloads"))!==null&&i!==void 0?i:{},a=sn(sn({},r),t),A=sn(sn({},s),e),c={};for(const[l,u]of Object.entries(a))c[l]={key:l,enabled:dHt(u),variant:hHt(u),reason:void 0,metadata:Eo(A?.[l])?void 0:{id:0,version:void 0,description:void 0,payload:A[l]}};this.Yd({flags:c})}get hasLoadedFlags(){return this.pd}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){const t=this.Wd(CR),e=this.Wd(g6),n=this.Wd(xR);if(!n&&!e)return t||{};const o=eg({},t||{}),i=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(const a of i){var r;const A=o[a],c=e?.[a],l=Eo(c)?(r=A?.enabled)!==null&&r!==void 0&&r:!!c,u=Eo(c)?A?.variant:typeof c=="string"?c:void 0,g=n?.[a],h=sn(sn({},A),{},{enabled:l,variant:l?u??A?.variant:void 0});var s;l!==A?.enabled&&(h.original_enabled=A?.enabled),u!==A?.variant&&(h.original_variant=A?.variant),g&&(h.metadata=sn(sn({},A?.metadata),{},{payload:g,original_payload:A==null||(s=A.metadata)===null||s===void 0?void 0:s.payload})),o[a]=h}return this.hd||(this.A.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:o}),this.hd=!0),o}getAllFeatureFlags(){const t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map(n=>{const o=t[n];return{key:n,enabled:dHt(o),variant:hHt(o),payload:gHt(e[n])}})}getFlagVariants(){const t=this.Wd(TB),e=this.Wd(g6);if(!e)return t||{};const n=eg({},t||{}),o=Object.keys(e);for(let i=0;o.length>i;i++)n[o[i]]=e[o[i]];return this.hd||(this.A.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.hd=!0),n}getFlagPayloads(){const t=this.Wd(Dw),e=this.Wd(xR);if(!e)return t||{};const n=eg({},t||{}),o=Object.keys(e);for(let i=0;o.length>i;i++)n[o[i]]=e[o[i]];return this.hd||(this.A.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.hd=!0),n}reloadFeatureFlags(){this.yd||this.Mr.featureFlagsDisabled||this.xd()||(this.gd&&(this.bd=!0),this.tv||(this.fd.slice().forEach(t=>{try{t()}catch(e){this.A.error("Error while running feature flags reloading callback",e)}}),this.tv=setTimeout(()=>{this.ev()},5)))}Ud(){clearTimeout(this.tv),this.tv=void 0}onReloading(t){return this.fd.push(t),()=>{this.fd=this.fd.filter(e=>e!==t)}}ensureFlagsLoaded(){this.pd||this.gd||this.tv||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this.yd=t}resetFlagCallReported(){this.Pt(Tw)}ev(t){this.Ud();const e=this.bo;if(!e||this.Mr.remoteRequestsDisabled||this.xd())return;if(this.gd)return void(this.bd=!0);const n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:sn(sn(sn({},e.initialPersonProperties),this.Wd("$stored_person_properties")||{}),{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Wd(Rw),timezone:VOt()};Eo(e.deviceId)||(n.$device_id=e.deviceId),(t?.disableFlags||this.Mr.featureFlagsDisabled)&&(n.disable_flags=!0);const o=this.Kd();o.length&&(n.evaluation_contexts=o);const i=this.Xd();Eo(i)||(n.flag_keys=i);const r=this.Mr.onlyEvaluateSurveyFeatureFlags,s="/flags/?v=2"+(r?"&only_evaluate_survey_feature_flags=true":""),a=this.md;this.gd=!0;const A=()=>{this.bd&&(this.bd=!1,this.ev())},c=d=>{var p,m;const _=(p=d.json)!==null&&p!==void 0?p:{},f=d.statusCode!==200;if(this.gd=!1,a!==this.md)return void A();if(this.iv(d.statusCode),f||this.bd||(this.$anon_distinct_id=void 0),n.disable_flags&&!this.bd)return;this._d=!f;const I=[];d.error?I.push(d.error instanceof Error&&d.error.name==="AbortError"?"timeout":d.error instanceof Error?qGt:"unknown_error"):d.statusCode!==200&&I.push(`api_error_${d.statusCode}`),_.errorsWhileComputingFlags&&I.push("errors_while_computing_flags");const C=!!(!((m=_.quotaLimited)===null||m===void 0)&&m.includes("feature_flags"));C&&I.push("quota_limited"),this.$t({[Y$]:I}),C?this.A.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset.  Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.Yd(_,f,{partialResponse:r}),A()},l=d=>{this.gd=!1,a===this.md&&(this.$t({[Y$]:[qGt]}),this.A.error("Feature flag request failed",d),this.Gd()&&this.jd(!0)),A()};let u=this.Mr.requestMaxRetries;const g=()=>u>0&&a===this.md,h=()=>{if(a!==this.md||!this.bo||this.Mr.remoteRequestsDisabled)return this.gd=!1,void A();try{e.sendRequest(s,{target:"flags",method:"POST",body:n,compression:this.Mr.compression,sentAt:"body",timeoutMs:this.Mr.requestTimeoutMs}).then(d=>{if((p=>BYo.includes(p.statusCode)||(m=>m.statusCode===0&&m.error instanceof Error&&m.error.name==="AbortError")(p))(d)&&g())return u--,void setTimeout(h,500);c(d)}).catch(l)}catch(d){l(d)}};h()}xd(){return kOt(this.kd,3)}iv(t){this.kd=FOt(t,this.kd,3,()=>this.A.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes."))}getFeatureFlag(t,e={}){var n;if(e.fresh&&!this._d)return;if(!(this.pd||this.getFlags()&&this.getFlags().length>0))return void this.A.warn('getFeatureFlag for key "'+t+nRe);if(this.Zd())return;const o=this.getFeatureFlagResult(t,e);return(n=o?.variant)!==null&&n!==void 0?n:o?.enabled}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){const e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e={}){if(e.fresh&&!this._d)return;if(!(this.pd||this.getFlags()&&this.getFlags().length>0))return void this.A.warn('getFeatureFlagResult for key "'+t+nRe);if(this.Zd())return;const n=this.getFlagVariants(),o=t in n,i=n[t],r=this.getFlagPayloads()[t],s=String(i),a=this.Wd("$feature_flag_request_id")||void 0,A=this.Wd("$feature_flag_evaluated_at")||void 0;let c,l=this.Wd("$flag_call_reported")||{};if(this.Mr.deduplicateCallsPerSession){var u;const S=(u=this.bo)===null||u===void 0?void 0:u.session.sessionId,Q=this.Wd(G$);S&&S!==Q&&(l={},c=S)}if(e.send_event||!("send_event"in e))if(t in l&&l[t].includes(s))c&&this.$t({[Tw]:l,[G$]:c});else{var g,h,d,p,m,_,f,I,C,y,x,E;As(l[t])?l[t].push(s):l[t]=[s],this.$t(sn({[Tw]:l},c?{[G$]:c}:{}));const S=this.getFeatureFlagDetails(t),Q=[...(g=this.Wd("$feature_flag_errors"))!==null&&g!==void 0?g:[]];Eo(i)&&Q.push("flag_missing");const w={$feature_flag:t,$feature_flag_response:i,$feature_flag_payload:r??null,$feature_flag_request_id:a,$feature_flag_evaluated_at:A,$feature_flag_bootstrapped_response:(h=(d=this.Mr.bootstrap)===null||d===void 0||(d=d.featureFlags)===null||d===void 0?void 0:d[t])!==null&&h!==void 0?h:null,$feature_flag_bootstrapped_payload:(p=(m=this.Mr.bootstrap)===null||m===void 0||(m=m.featureFlagPayloads)===null||m===void 0?void 0:m[t])!==null&&p!==void 0?p:null,$used_bootstrap_value:!this._d};Eo(S==null||(_=S.metadata)===null||_===void 0?void 0:_.has_experiment)||(w.$feature_flag_has_experiment=S.metadata.has_experiment),Eo(S==null||(f=S.metadata)===null||f===void 0?void 0:f.version)||(w.$feature_flag_version=S.metadata.version);const M=(I=S==null||(C=S.reason)===null||C===void 0?void 0:C.description)!==null&&I!==void 0?I:S==null||(y=S.reason)===null||y===void 0?void 0:y.code;var B;M&&(w.$feature_flag_reason=M),!(S==null||(x=S.metadata)===null||x===void 0)&&x.id&&(w.$feature_flag_id=S.metadata.id),Eo(S?.original_variant)&&Eo(S?.original_enabled)||(w.$feature_flag_original_response=Eo(S.original_variant)?S.original_enabled:S.original_variant),!(S==null||(E=S.metadata)===null||E===void 0)&&E.original_payload&&(w.$feature_flag_original_payload=S==null||(B=S.metadata)===null||B===void 0?void 0:B.original_payload),Q.length&&(w.$feature_flag_error=Q.join(",")),this.nv(w)}else c&&this.$t({[Tw]:l,[G$]:c});return o?{key:t,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:gHt(r)}:void 0}nv(t){try{var e;(e=this.bo)===null||e===void 0||e.capture("$feature_flag_called",t)}catch(n){this.A.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.sv(t,e)}sv(t,e){var n=this;return Zu(function*(){const o=n.bo;if(!o)return;const i={distinct_id:o.distinctId,token:o.projectToken,person_properties:{$lib:o.library.name,$lib_version:o.library.version}},r=n.Kd();r.length&&(i.evaluation_contexts=r);const s=n.Xd();let a;Eo(s)||(i.flag_keys=s);try{var A;const c=(A=(yield o.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:i,compression:n.Mr.compression,sentAt:"body",timeoutMs:n.Mr.requestTimeoutMs})).json)===null||A===void 0?void 0:A.featureFlagPayloads;a=c?.[t]||void 0}catch(c){return void n.A.error("Remote config feature flag request failed",c)}try{e(a)}catch(c){n.A.error("Remote config feature flag callback failed",c)}})()}isFeatureEnabled(t,e={}){if(e.fresh&&!this._d)return e.defaultValue;if(!(this.pd||this.getFlags()&&this.getFlags().length>0))return this.A.warn('isFeatureEnabled for key "'+t+nRe),e.defaultValue;const n=this.getFeatureFlag(t,e);return Eo(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(e=>e!==t)}receivedFeatureFlags(t,e,n){this.Yd(t,e,n)}Yd(t,e,n){if(!this.bo)return;this.pd=!0;const o=((i,r={},s={},a={},A,c=jGt)=>{const l=((I,C)=>{const y=I.flags;if(y){const x=Object.fromEntries(Object.keys(y).map(B=>{var S;return[B,(S=y[B].variant)!==null&&S!==void 0?S:y[B].enabled]})),E=Object.fromEntries(Object.keys(y).filter(B=>y[B].enabled).filter(B=>{var S;return!Eo((S=y[B].metadata)===null||S===void 0?void 0:S.payload)}).map(B=>{var S;return[B,(S=y[B].metadata)===null||S===void 0?void 0:S.payload]}));return sn(sn({},I),{},{featureFlags:x,featureFlagPayloads:E})}return I.featureFlags&&C.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),I})(i,c),u=l.flags,g=l.featureFlags,h=l.featureFlagPayloads;if(!g)return;const d=i.requestId,p=i.evaluatedAt;if(As(g)){c.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");const I={};if(g)for(let C=0;g.length>C;C++)I[g[C]]=!0;return{[Yb]:g,[TB]:I,[H$]:!1}}let m=g,_=h,f=u;if(A?.partialResponse){const I=Object.keys(m),C=_||{};m=sn(sn({},r),m),_=sn(sn({},s),C),I.forEach(y=>{y in C||_==null||delete _[y]}),f=sn(sn({},a),f)}else if(i.errorsWhileComputingFlags)if(u){const I=new Set(Object.keys(u).filter(y=>{var x;return!(!((x=u[y])===null||x===void 0)&&x.failed)}));m=sn(sn({},r),Object.fromEntries(Object.entries(m).filter(([y])=>I.has(y))));const C=Object.fromEntries(Object.entries(_||{}).filter(([y])=>I.has(y)));_=sn(sn({},s),C),I.forEach(y=>{y in C||_==null||delete _[y]}),f=sn(sn({},a),Object.fromEntries(Object.entries(f||{}).filter(([y])=>I.has(y))))}else m=sn(sn({},r),m),_=sn(sn({},s),_),f=sn(sn({},a),f);return sn(sn({[Yb]:Object.keys(ZGt(m)),[TB]:m||{},[Dw]:_||{},[CR]:f||{},[H$]:i.minimalFlagCalledEvents===!0},d?{[yR]:d}:{}),p?{[kw]:p}:{})})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.A);if(o)if(n?.persist===!1){const i=!Eo(this.bo.kv.get(TB));this.Vd=o,i||this.$t(o)}else this.Nd(),this.Jd(o,t,!!n?.partialResponse),this.$t(o);else e&&this.Gd();e||(this.wd=!1),this.jd(e)}override(t,e=!1){this.A.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.rv(t)}rv(t){if(this.bo){if(t===!1)return this.Pt([g6,xR]),this.jd(),void QR.info("All overrides cleared");if(As(t))return this.$t({[g6]:XGt(t)}),this.jd(),void QR.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e;const n=t;this.hd=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);const o={},i=n.flags,r=n.payloads;return i&&(o[g6]=As(i)?XGt(i):i),r&&(o[xR]=r),Object.keys(o).length&&this.$t(o),i===!1&&r===!1?this.Pt([g6,xR]):i===!1?this.Pt(g6):r===!1&&this.Pt(xR),this.jd(),i===!1?QR.info("Flag overrides cleared"):i&&QR.info("Flag overrides set",{flags:i}),void(r===!1?QR.info("Payload overrides cleared"):r&&QR.info("Payload overrides set",{payloads:r}))}if(t&&typeof t=="object")return this.$t({[g6]:t}),this.jd(),void QR.info("Flag overrides set",{flags:t});this.A.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.A.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.pd){const{flags:e,flagVariants:n}=this.ov();try{t(e,n)}catch(o){this.A.error("Error while running feature flags callback",o)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var o;const i=(this.Wd("$early_access_features")||[]).find(c=>c.flagKey===t),r={[`$feature_enrollment/${t}`]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);const a=sn(sn({},this.getFlagVariants()),{},{[t]:e});(o=this._instance)===null||o===void 0||(o=o.persistence)===null||o===void 0||o.markCrossTabFeatureFlagChanges({$active_feature_flags:[t],$enabled_feature_flags:[t],$stored_person_properties:Object.keys(r)}),this.$t({[Yb]:Object.keys(ZGt(a)),[TB]:a,[Nw]:sn(sn({},this.Wd("$stored_person_properties")||{}),r)}),this.jd();try{var A;(A=this.bo)===null||A===void 0||A.capture("$feature_enrollment_update",s)}catch(c){this.A.error("Failed to capture early access feature enrollment",c)}}getEarlyAccessFeatures(t,e=!1,n){const o=this.Wd(aNe);!o||e?this.av(t,n):t(o)}av(t,e){var n=this;return Zu(function*(){const o=n.bo;if(!o)return;const i=e?`&${e.map(s=>`stage=${s}`).join("&")}`:"";let r;try{const s=yield o.sendRequest(`/api/early_access_features/?token=${o.projectToken}${i}`,{target:"api",method:"GET",sentAt:"query"});if(!s.json)return;r=s.json.earlyAccessFeatures,n.$t({[aNe]:r})}catch(s){return void n.A.error("Early access feature request failed",s)}try{t(r)}catch(s){n.A.error("Early access feature callback failed",s)}})()}ov(){const t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter(n=>e[n]),flagVariants:Object.keys(e).filter(n=>e[n]).reduce((n,o)=>(n[o]=e[o],n),{})}}jd(t){this.qd();const{flags:e,flagVariants:n}=this.ov();this.featureFlagEventHandlers.forEach(o=>{try{o(e,n,{errorsLoading:t})}catch(i){this.A.error("Error while running feature flags callback",i)}})}setPersonPropertiesForFlags(t,e=!0){this.lv(t,e)}lv(t,e=!0){const n=this.Wd("$stored_person_properties")||{},o=t?.$set||(t?.$set_once?{}:t),i=t?.$set_once,r={};if(i)for(const s in i)({}).hasOwnProperty.call(i,s)&&(s in n||(r[s]=i[s]));this.$t({[Nw]:sn(sn(sn({},n),r),o)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e=!0){const n=sn({},this.Wd("$stored_person_properties")||{});t.forEach(o=>{delete n[o]}),this.$t({[Nw]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t=!0){this.Pt(Nw),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e=!0){const n=this.Wd("$stored_group_properties")||{},o=sn({},n);for(const i of Object.keys(t))o[i]=sn(sn({},n[i]),t[i]);this.$t({[Rw]:o}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){const e=this.Wd("$stored_group_properties")||{};this.$t({[Rw]:sn(sn({},e),{},{[t]:{}})})}else this.Pt(Rw)}reset(){this.md++,this.bd=!1,this.dd={},this.vd={},this.Vd=void 0,this.pd=!1,this.yd=!1,this._d=!1,this.$anon_distinct_id=void 0,this.Ud(),this.hd=!1,this.kd=0}}},TYo={sessionRecording:class{get Mr(){return this._instance.config}get Il(){return this._instance.persistence}get started(){var t;return!!(!((t=this.uv)===null||t===void 0)&&t.isStarted)}get status(){var t,e;return this.hv==="awaiting_config"||this.hv==="missing_config"?this.hv:(t=(e=this.uv)===null||e===void 0?void 0:e.status)!==null&&t!==void 0?t:this.hv}constructor(t){if(this._instance=t,this._forceAllowLocalhostNetworkCapture=!1,this.hv=ZNe,this.dv=void 0,this.vv=!1,this.Je=(()=>{var e,n;if(!No?.visibilityState||No.visibilityState==="visible")return!0;const o=Fn==null||(e=Fn.performance)===null||e===void 0||(n=e.getEntriesByType)===null||n===void 0?void 0:n.call(e,"visibility-state");return!o?.length||o.some(i=>i.name==="visible")})(),this.sn=()=>{var e,n;No?.visibilityState==="visible"&&(this.Je=!0,(e=this.uv)===null||e===void 0||(n=e.setDocumentWasEverVisible)===null||n===void 0||n.call(e,!0))},!this._instance.sessionManager)throw Jb.error("started without valid sessionManager"),new Error("[SessionRecording] started without valid sessionManager. This is a bug.");if(this.Mr.cookieless_mode==="always")throw new Error('[SessionRecording] cannot be used with cookieless_mode="always"');No?.addEventListener&&el(No,"visibilitychange",this.sn)}initialize(){this.startIfEnabledOrStop()}dispose({discardBufferedEvents:t=!1}={}){var e;this.vv=!0,No==null||(e=No.removeEventListener)===null||e===void 0||e.call(No,"visibilitychange",this.sn),t?this.fv(!0):this.stopRecording()}get pv(){var t;const e=!!(!((t=this._instance.get_property("$session_recording_remote_config"))===null||t===void 0)&&t.enabled),n=!this.Mr.disable_session_recording,o=this.Mr.disable_session_recording||this._instance.consent.isOptedOut();return Fn&&e&&n&&!o}startIfEnabledOrStop(t){var e;if(this.vv||this.pv&&(!((e=this.uv)===null||e===void 0)&&e.isStarted))return;const n=!Eo(Object.assign)&&!Eo(Array.from);this.pv&&n?(this.gv(t),Jb.info("starting")):(this.hv=ZNe,this.stopRecording())}gv(t){var e,n;if(this.pv)if(this.hv!=="awaiting_config"&&this.hv!=="missing_config"&&(this.hv=YGt),(Vr==null||(e=Vr.__PosthogExtensions__)===null||e===void 0||(e=e.rrweb)===null||e===void 0?void 0:e.record)&&((n=Vr.__PosthogExtensions__)===null||n===void 0?void 0:n.initSessionRecording))this.mv(t);else{var o,i;const r=this._instance.sessionManager;(o=Vr.__PosthogExtensions__)===null||o===void 0||(i=o.loadExternalDependency)===null||i===void 0||i.call(o,this._instance,this.yv,s=>{if(!this.vv&&this.pv&&this._instance.sessionManager===r)return s?(this._instance.register_for_session({$sdk_debug_recording_script_not_loaded:!0}),Jb.error("could not load recorder",s)):void this.mv(t);this.hv="disabled"})}}stopRecording(){var t,e;(t=this.dv)===null||t===void 0||t.call(this),this.dv=void 0,(e=this.uv)===null||e===void 0||e.stop()}fv(t=!1){var e,n;(e=this.dv)===null||e===void 0||e.call(this),this.dv=void 0,(n=this.uv)===null||n===void 0||n.discard({discardProducerEvents:t})}bv(){var t,e;(t=this.Il)===null||t===void 0||t.unregister("$session_is_sampled"),(e=this.Il)===null||e===void 0||e.unregister("$replay_sample_rate")}_v(t,e){if(Hs(t))return null;const n=Ah(t)?t:parseFloat(t);return typeof(o=n)!="number"||!Number.isFinite(o)||0>o||o>1?(Jb.warn(`${e} must be between 0 and 1. Ignoring invalid value:`,t),null):n;var o}wv(t){if(this.Il){var e,n;const o=this.Il,i=()=>{var r;const s=t.sessionRecording===!1?void 0:t.sessionRecording,a=this._v((r=this.Mr.session_recording)===null||r===void 0?void 0:r.sampleRate,"session_recording.sampleRate"),A=this._v(s?.sampleRate,"remote config sampleRate"),c=a??A;Hs(c)&&this.bv();const l=s?.minimumDurationMilliseconds;o.register({[L$]:sn(sn({cache_timestamp:Date.now(),enabled:!!s},s),{},{networkPayloadCapture:sn({capturePerformance:t.capturePerformance},s?.networkPayloadCapture),canvasRecording:{enabled:s?.recordCanvas,fps:s?.canvasFps,quality:s?.canvasQuality},sampleRate:c,minimumDurationMilliseconds:Eo(l)?null:l,endpoint:s?.endpoint,triggerMatchType:s?.triggerMatchType,masking:s?.masking,urlTriggers:s?.urlTriggers,version:s?.version,triggerGroups:s?.triggerGroups})})};i(),(e=this.dv)===null||e===void 0||e.call(this),this.dv=(n=this._instance.sessionManager)===null||n===void 0?void 0:n.onSessionId(i)}}onRemoteConfig(t){const e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.wv(e),void this.fv()):(this.wv(e),void this.startIfEnabledOrStop()):(this.hv==="awaiting_config"&&(this.hv="missing_config",this._instance.register_for_session({[dNe]:!0}),Jb.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e="log"){var n;!((n=this.uv)===null||n===void 0)&&n.log?this.uv.log(t,e):Jb.warn("log called before recorder was ready")}get yv(){var t,e;const n=(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0?void 0:t.get_property(L$);return(n==null||(e=n.scriptConfig)===null||e===void 0?void 0:e.script)||"lazy-recorder"}Sv(){const t=this._instance.get_property(L$);if(!t)return!1;let e;try{e=typeof t=="object"?t:JSON.parse(t)}catch(n){return Jb.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!Hs(e.cache_timestamp)&&36e5>=Date.now()-e.cache_timestamp}mv(t){var e,n,o;if(!this.vv&&this.pv&&this._instance.sessionManager){if(!(!((e=Vr.__PosthogExtensions__)===null||e===void 0)&&e.initSessionRecording))return Jb.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[gNe]:!0});var i;if(this.uv||(this.uv=(i=Vr.__PosthogExtensions__)===null||i===void 0?void 0:i.initSessionRecording(this._instance,this.Je),this.uv._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.Sv())return this.hv==="missing_config"||this.hv==="awaiting_config"?void 0:(this.hv="awaiting_config",Jb.info("persisted remote config is stale, requesting fresh config before starting"),void new qOt(this._instance).load());this.hv=YGt,(n=(o=this.uv).setDocumentWasEverVisible)===null||n===void 0||n.call(o,this.Je),this.uv.start(t)}else this.hv=ZNe}onRRwebEmit(t){var e,n;(e=this.uv)===null||e===void 0||(n=e.onRRwebEmit)===null||n===void 0||n.call(e,t)}overrideLinkedFlag(){var t,e;this.uv||(e=this.Il)===null||e===void 0||e.register({$replay_override_linked_flag:!0}),(t=this.uv)===null||t===void 0||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.uv||(e=this.Il)===null||e===void 0||e.register({$replay_override_sampling:!0}),(t=this.uv)===null||t===void 0||t.overrideSampling()}overrideTrigger(t){var e,n;this.uv||(n=this.Il)===null||n===void 0||n.register({[t==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(e=this.uv)===null||e===void 0||e.overrideTrigger(t)}get sdkDebugProperties(){var t;const e={};for(const o of dYo){var n;const i=(n=this._instance.sessionPersistence)===null||n===void 0?void 0:n.get_property(o);Eo(i)||(e[o]=i)}return sn(sn({},e),((t=this.uv)===null||t===void 0?void 0:t.sdkDebugProperties)||{$recording_status:this.status})}tryAddCustomEvent(t,e){var n;return!!(!((n=this.uv)===null||n===void 0)&&n.tryAddCustomEvent(t,e))}flushBeforeIdentityReset(){var t,e;(t=this.uv)===null||t===void 0||(e=t.flushBeforeIdentityReset)===null||e===void 0||e.call(t)}}},kYo={autocapture:class extends AYo{constructor(t){super(new cYo(t)),this.instance=t}},historyAutocapture:class{constructor(t){this.xv=!1,this._instance=t,this.$v=this.Cv()}initialize(){this.startIfEnabled()}get isEnabled(){const t=this.Tv();return!!(t.path||t.search||this.Iv(t))}startIfEnabled(){this.isEnabled&&(ui.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}startIfEnabledOrStop(){this.stop(),this.$v=this.Cv(),this.startIfEnabled()}stop(){this.Mv&&this.Mv(),this.Mv=void 0,this.Ev&&this.Ev(),this.Ev=void 0,ui.info("History API monitoring stopped")}monitorHistoryChanges(){Fn&&Fn.history&&(this.Pv("pushState"),this.Pv("replaceState"),this.Rv(),this.Iv()&&this.Av())}Pv(t){var e;if(!Fn||!((e=Fn.history[t])===null||e===void 0)&&e.__posthog_wrapped__)return;const n=this;lq(Fn.history,t,o=>function(i,r,s){var a;n.Ov(s)&&n.Fv(),o.call(this,i,r,s),n.Dv(t,!n.xv&&(Fn==null||(a=Fn.event)===null||a===void 0?void 0:a.type)!=="popstate")})}Cv(){const t=Fn?.location;if(t?.pathname)return{pathname:t.pathname,search:t.search,hash:t.hash}}Tv(){const t=this._instance.config.capture_pageview;return t==="history_change"?{path:!0}:QA(t)?t:{}}Iv(t=this.Tv()){return!!t.hash&&!this._instance.config.disable_capture_url_hashes}Lv(t){const e=this.Tv(),n=this.$v;return!(!n||!(e.path&&t.pathname!==n.pathname||e.search&&t.search!==n.search||this.Iv(e)&&t.hash!==n.hash))}Dv(t,e=!1){try{e||this.Fv();const n=this.Cv();if(!n)return;if(this.Lv(n)){const o=()=>this._instance.capture(pNe,{navigation_type:t});e?(this.Nv=o,Promise.resolve().then(()=>this.Fv())):o()}this.$v=n}catch(n){ui.error(`Error capturing ${t} pageview`,n)}}Ov(t){var e,n;return!(Hs(t)||!Fn)&&((e=Kb(String(t)))===null||e===void 0?void 0:e.href)!==((n=Fn.location)===null||n===void 0?void 0:n.href)}Fv(){const t=this.Nv;if(t){this.Nv=void 0,this.xv=!0;try{t()}catch(e){ui.error("Error capturing deferred pageview",e)}finally{this.xv=!1}this.$v=this.Cv()}}Rv(){if(this.Mv)return;const t=()=>{this.Dv("popstate")};el(Fn,"popstate",t),this.Mv=()=>{Fn&&Fn.removeEventListener("popstate",t)}}Av(){if(this.Ev)return;const t=()=>{this.Dv("hashchange")};el(Fn,"hashchange",t),this.Ev=()=>{Fn&&Fn.removeEventListener("hashchange",t)}}},heatmaps:class{get Mr(){return this.instance.config}constructor(t){var e;this.qv=!1,this.ko=!1,this.jv=null,this.instance=t,this.qv=!!(!((e=this.instance.persistence)===null||e===void 0)&&e.props[tNe]),this.rageclicks=new FGt(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){let t=5e3;return QA(this.Mr.capture_heatmaps)&&this.Mr.capture_heatmaps.flush_interval_milliseconds&&(t=this.Mr.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return Hs(this.Mr.capture_heatmaps)?Hs(this.Mr.enable_heatmaps)?this.qv:this.Mr.enable_heatmaps:this.Mr.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.ko)return;hYo.info("starting..."),this.Bv(),this.sn()}else{var t;clearInterval((t=this.jv)!==null&&t!==void 0?t:void 0),this.Hv(),this.getAndClearBuffer()}}onRemoteConfig(t){if(!t.ok)return;const e=t.config;if(!("heatmaps"in e))return;const n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[tNe]:n}),this.qv=n,this.startIfEnabled()}getAndClearBuffer(){const t=this.Rt;return this.Rt=void 0,t}zv(t){eRe(t.originalEvent)&&this.Ir(t.originalEvent,"deadclick")}sn(){this.jv&&clearInterval(this.jv),this.jv=No?.visibilityState==="visible"?setInterval(this.yl.bind(this),this.flushIntervalMilliseconds):null}Bv(){Fn&&No&&(this.Uv=this.yl.bind(this),el(Fn,Qge,this.Uv),this.Wv=t=>this.Ir(t||Fn?.event),el(No,"click",this.Wv,{capture:!0}),this.Vv=t=>this.Gv(t||Fn?.event),el(No,"mousemove",this.Vv,{capture:!0}),this.Qv=new MOt(this.instance,hGo,this.zv.bind(this)),this.Qv.startIfEnabledOrStop(),this.Jv=this.sn.bind(this),el(No,U$,this.Jv),this.ko=!0)}Hv(){var t;Fn&&No&&(this.Uv&&Fn.removeEventListener(Qge,this.Uv),this.Wv&&No.removeEventListener("click",this.Wv,{capture:!0}),this.Vv&&No.removeEventListener("mousemove",this.Vv,{capture:!0}),this.Jv&&No.removeEventListener(U$,this.Jv),clearTimeout(this.Zv),(t=this.Qv)===null||t===void 0||t.stop(),this.ko=!1)}Kv(t,e){const n=this.instance.scrollManager.scrollY(),o=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),r=(function(s,a,A){let c=s;for(;c&&d6(c)&&!AI(c,"body");){if(c===A)return!1;let h;try{var l,u,g;h=(l=(u=(g=c.ownerDocument)===null||g===void 0?void 0:g.defaultView)!==null&&u!==void 0?u:Fn)===null||l===void 0?void 0:l.getComputedStyle(c).position}catch{return!1}if(as(a,h))return!0;c=fOt(c)}return!1})(J$(t),["fixed","sticky"],i);return{x:t.clientX+(r?0:o),y:t.clientY+(r?0:n),target_fixed:r,type:e}}Ir(t,e="click"){var n;if(hOt(t.target)||!eRe(t))return;const o=this.Kv(t,e);!((n=this.rageclicks)===null||n===void 0)&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&xOt(J$(t),this.instance.config.rageclick)&&this.Qs(sn(sn({},o),{},{type:"rageclick"})),this.Qs(o)}Gv(t){!hOt(t.target)&&eRe(t)&&(clearTimeout(this.Zv),this.Zv=setTimeout(()=>{this.Qs(this.Kv(t,"mousemove"))},500))}Qs(t){if(!Fn)return;const e=this.Mr.disable_capture_url_hashes?Mw(Fn.location.href):Fn.location.href,n=this.Mr.custom_personal_data_properties,o=this.Mr.mask_personal_data_properties?[...rG,...n||[]]:[],i=X$(e,o,Z$);this.Rt=this.Rt||{},this.Rt[i]||(this.Rt[i]=[]),this.Rt[i].push(t)}yl(){this.Rt&&!Rx(this.Rt)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:MOt,webVitalsAutocapture:class{constructor(t){var e;this._instance=t,this.qv=!1,this.ko=!1,this.Rt={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Xv=()=>{clearTimeout(this.Yv),this.Yv=void 0,this.Rt.metrics.length!==0&&(this._instance.capture("$web_vitals",sn({$current_url:this.Rt.url},this.Rt.metrics.reduce((n,o)=>sn(sn({},n),{},{[`$web_vitals_${o.name}_event`]:sn({},o),[`$web_vitals_${o.name}_value`]:o.value}),{}))),this.Rt={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.tf=n=>{var o;if(this.Rt=this.Rt||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},Hs(n?.name)||Hs(n?.value))return void SR.error("Invalid metric received",n);const i=typeof n.navigationURL=="string"?n.navigationURL:void 0,r=this.ef(i);if(Eo(r))return;const s=Ah(n.navigationId)||typeof n.navigationId=="string"?`navigation:${n.navigationId}`:`url:${r}`;if(this.if&&n.value>=this.if)return void SR.error("Ignoring metric with value >= "+this.if,n);this.Rt.navigationKey!==s&&(this.Xv(),this.Yv=setTimeout(this.Xv,this.flushToCaptureTimeoutMs)),Eo(this.Rt.navigationKey)&&(this.Rt.navigationKey=s,this.Rt.url=r),this.Rt.firstMetricTimestamp=Eo(this.Rt.firstMetricTimestamp)?Date.now():this.Rt.firstMetricTimestamp;const a=(o=this._instance.sessionManager)===null||o===void 0?void 0:o.checkAndGetSessionAndWindowId(!0),A=sn(sn(sn({},n),i?{navigationURL:r}:{}),{},{$current_url:r,timestamp:Date.now()});if(delete A.entries,QA(n.attribution)&&this.attributionMetrics.indexOf(n.name)>-1){const c={};for(const l of gYo){const u=l==="url"&&typeof n.attribution[l]=="string"?this.ef(n.attribution[l]):n.attribution[l];Eo(u)||(c[l]=u)}A.attribution=c}else delete A.attribution;Eo(a)||(A.$session_id=a.sessionId,A.$window_id=a.windowId),this.Rt.metrics.push(A),this.Rt.metrics.length===this.allowedMetrics.length&&this.Xv()},this.nf=()=>{if(this.ko)return;let n,o,i,r,s=!1;const a=Vr.__PosthogExtensions__,A=a?.postHogWebVitalsCallbacksByFlavor,c=A?.[this.sf]||(this.sf==="web-vitals"&&Eo(A)?a?.postHogWebVitalsCallbacks:void 0);if(!Eo(c)){const g=c.withoutAttribution,h=this.attributionMetrics;s=!Eo(g),n=h.indexOf("LCP")>-1?c.onLCP:g?.onLCP||c.onLCP,o=h.indexOf("CLS")>-1?c.onCLS:g?.onCLS||c.onCLS,i=h.indexOf("FCP")>-1?c.onFCP:g?.onFCP||c.onFCP,r=h.indexOf("INP")>-1?c.onINP:g?.onINP||c.onINP}if(!(n&&o&&i&&r))return void SR.error("web vitals callbacks not loaded - not starting");const l={reportSoftNavs:this.useSoftNavs},u=s&&this.attributionMetrics.indexOf("INP")>-1?sn(sn({},l),{},{includeProcessedEventEntries:!1}):l;this.allowedMetrics.indexOf("LCP")>-1&&n(this.tf.bind(this),l),this.allowedMetrics.indexOf("CLS")>-1&&o(this.tf.bind(this),l),this.allowedMetrics.indexOf("FCP")>-1&&i(this.tf.bind(this),l),this.allowedMetrics.indexOf("INP")>-1&&r(this.tf.bind(this),u),this.ko=!0},this.qv=!!(!((e=this._instance.persistence)===null||e===void 0)&&e.props[iNe]),this.startIfEnabled()}get rf(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e;const n=QA(this.rf)?(t=this.rf)===null||t===void 0?void 0:t.web_vitals_allowed_metrics:void 0;return Hs(n)?((e=this._instance.persistence)===null||e===void 0?void 0:e.props.$web_vitals_allowed_metrics)||GGt:n}get flushToCaptureTimeoutMs(){return(QA(this.rf)?this.rf.web_vitals_delayed_flush_ms:void 0)||5e3}get attributionMetrics(){const t=QA(this.rf)?this.rf.web_vitals_attribution:void 0;return $y(t)?t?GGt:[]:As(t)?t:uYo}get useAttribution(){return this.attributionMetrics.length>0}get useSoftNavs(){const t=QA(this.rf)?this.rf.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get if(){const t=QA(this.rf)&&Ah(this.rf.__web_vitals_max_value)?this.rf.__web_vitals_max_value:OGt;return t>0&&6e4>=t?OGt:t}get isEnabled(){const t=fd?.protocol;if(t!=="http:"&&t!=="https:")return SR.info("Web Vitals are disabled on non-http/https protocols"),!1;const e=QA(this.rf)?this.rf.web_vitals:$y(this.rf)?this.rf:void 0;return $y(e)?e:this.qv}startIfEnabled(){this.isEnabled&&!this.ko&&(SR.info("enabled, starting..."),this.Ho(this.nf))}onRemoteConfig(t){if(!t.ok)return;const e=t.config;if(!("capturePerformance"in e))return;const n=QA(e.capturePerformance)&&!!e.capturePerformance.web_vitals,o=QA(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[iNe]:n}),this._instance.persistence.register({[HHt]:o})),this.qv=n,this.startIfEnabled()}get sf(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}Ho(t){var e;const n=Vr.__PosthogExtensions__,o=this.sf,i=n?.postHogWebVitalsCallbacksByFlavor;i?.[o]||o==="web-vitals"&&Eo(i)&&n?.postHogWebVitalsCallbacks?t():n==null||(e=n.loadExternalDependency)===null||e===void 0||e.call(n,this._instance,o,r=>{r?SR.error("failed to load script",r):t()})}ef(t){const e=t||Fn?.location.href;if(!e)return void SR.error("Could not determine current URL");const n=this._instance.config.disable_capture_url_hashes?Mw(e):e,o=this._instance.config.custom_personal_data_properties,i=this._instance.config.mask_personal_data_properties?[...rG,...o||[]]:[];return X$(n,i,Z$)}}},FYo={exceptionObserver:class{constructor(t){var e;this.nf=()=>{var n;if(!Fn||!this.isEnabled||!(!((n=Vr.__PosthogExtensions__)===null||n===void 0)&&n.errorWrappingFunctions))return;const o=Vr.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=Vr.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,r=Vr.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.af&&this.Mr.capture_unhandled_errors&&(this.af=o(this.captureException.bind(this))),!this.lf&&this.Mr.capture_unhandled_rejections&&(this.lf=i(this.captureException.bind(this))),!this.uf&&this.Mr.capture_console_errors&&(this.uf=r(this.captureException.bind(this)))}catch(s){cq.error("failed to start",s),this.hf()}},this._instance=t,this.cf=!!(!((e=this._instance.persistence)===null||e===void 0)&&e.props[nNe]),this.wt=new RHo(sn(sn({},(function(n={}){var o,i,r,s;return{refillRate:(o=(i=n.exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:n.__exceptionRateLimiterRefillRate)!==null&&o!==void 0?o:1,bucketSize:(r=(s=n.exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:n.__exceptionRateLimiterBucketSize)!==null&&r!==void 0?r:10}})(this._instance.config.error_tracking)),{},{refillInterval:1e4,A:cq})),this.Mr=this.df(),this.startIfEnabledOrStop()}df(){const t=this._instance.config.capture_exceptions;let e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return QA(t)?e=sn(sn({},e),t):(Eo(t)?this.cf:t)&&(e=sn(sn({},e),{},{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Mr.capture_console_errors||this.Mr.capture_unhandled_errors||this.Mr.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(cq.info("enabled"),this.hf(),this.Ho(this.nf)):this.hf()}Ho(t){var e,n,o;!((e=Vr.__PosthogExtensions__)===null||e===void 0)&&e.errorWrappingFunctions?t():(n=Vr.__PosthogExtensions__)===null||n===void 0||(o=n.loadExternalDependency)===null||o===void 0||o.call(n,this._instance,"exception-autocapture",i=>{if(i)return cq.error("failed to load script",i);t()})}hf(){var t,e,n;(t=this.af)===null||t===void 0||t.call(this),this.af=void 0,(e=this.lf)===null||e===void 0||e.call(this),this.lf=void 0,(n=this.uf)===null||n===void 0||n.call(this),this.uf=void 0}onRemoteConfig(t){if(!t.ok)return;const e=t.config;"autocaptureExceptions"in e&&(this.cf=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[nNe]:this.cf}),this.Mr=this.df(),this.startIfEnabledOrStop())}onConfigChange(){this.Mr=this.df()}captureException(t){try{var e,n,o;const i=(e=t==null||(n=t.$exception_list)===null||n===void 0||(n=n[0])===null||n===void 0?void 0:n.type)!==null&&e!==void 0?e:"Exception";if(this.wt.consumeRateLimit(i))return void cq.info("Skipping exception capture because of client rate limiting.",{exception:i});(o=this._instance.exceptions)===null||o===void 0||o.sendExceptionEvent(t)}catch{}}},exceptions:class{constructor(t){var e,n;this.vf=[],this.ff=new zHo([new aOo,new mOo,new cOo,new AOo,new hOo,new dOo,new uOo,new pOo],(function(o,...i){return(r,s=0)=>{const a=[],A=r.split(`
`),c=Math.min(A.length,s+1e3),l=[];for(let h=s;c>h;h++){const d=A[h];if(d.length>1024)continue;const p=AHt.test(d)?d.replace(AHt,"$1"):d;if(!p.match(/\S*Error: /)){for(const m of i){const _=m(p,o);if(_){a.push(_);const f=oOo(a);if(f){for(let I=l.length-1;I>=0;I--){const C=l[I];if(f.start>=C.start+C.length)break;l.pop()}l.push(f)}break}}if(rOo(a,l)>=50)break}}const u=[...l].sort((h,d)=>d.start-h.start),g=u[u.length-1];if(g){const h=cHt(a,g);a.splice(g.start-h,h);for(const d of u)d.start-=h}for(const h of u)iOo(a,h);return l.some(h=>h.start===0&&a.length===h.length)&&(function(h){const d=h.map(m=>`${m.function}|${m.filename}|${m.lineno}|${m.colno}|${m.module}`);let p=0;for(let m=1;d.length>m;m++)sOo(d,m,p)&&(p=m);h.push(...h.splice(0,p))})(a),(function(h){if(!h.length)return[];const d=Array.from(h);return d.reverse(),d.slice(0,50).map(p=>{return sn(sn({},p),{},{filename:p.filename||(m=d,m[m.length-1]||{}).filename,function:p.function||"?"});var m})})(a)}})("web:javascript",ZHo,nOo)),this._instance=t,this.vf=(e=(n=this._instance.persistence)===null||n===void 0?void 0:n.get_property("$error_tracking_suppression_rules"))!==null&&e!==void 0?e:[],this.pf=Cge(this.gf()),this.mf=new fOo(this.pf)}onConfigChange(){this.pf=Cge(this.gf()),this.mf.setConfig(this.pf)}onRemoteConfig(t){var e,n,o;if(!t.ok)return;const i=t.config;if(!("errorTracking"in i))return;const r=(e=(n=i.errorTracking)===null||n===void 0?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],s=(o=i.errorTracking)===null||o===void 0?void 0:o.captureExtensionExceptions;this.vf=r,this._instance.persistence&&this._instance.persistence.register({[FHt]:this.vf,[oNe]:s})}get yf(){var t;const e=!!this._instance.get_property(oNe),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.ff.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.pf.enabled)try{if(!rA(t)||t.trim().length===0)return void FB.warn("Ignoring exception step because message must be a non-empty string");const{sanitizedProperties:n,droppedKeys:o}=(function(i){if(!i)return{sanitizedProperties:{},droppedKeys:[]};const r=[];return{sanitizedProperties:Object.keys(i).reduce((s,a)=>_Oo.has(a)?(r.push(a),s):(s[a]=i[a],s),{}),droppedKeys:r}})(this.bf(e));o.length>0&&FB.warn("Ignoring reserved exception step fields",{droppedKeys:o}),this.mf.add(sn({[fge]:t,[Ige]:new Date().toISOString()},n))}catch(n){FB.error("Failed to add exception step. Ignoring breadcrumb.",n)}}sendExceptionEvent(t){try{const e=t.$exception_list;if(this._f(e)){if(this.wf(e))return this.kf("Exception dropped: matched a suppression rule"),void FB.info("Skipping exception capture because a suppression rule matched");if(!this.yf&&this.Sf(e))return this.kf("Exception dropped: thrown by a browser extension"),void FB.info("Skipping exception capture because it was thrown by an extension");if(!this.yf&&this.xf(e))return this.kf("Exception dropped: thrown by an injected browser script"),void FB.info("Skipping exception capture because it was thrown by an injected browser script");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.$f(e))return this.kf("Exception dropped: thrown by the PostHog SDK"),void FB.info("Skipping exception capture because it was thrown by the PostHog SDK")}const n=this.pf.enabled&&Hs(t.$exception_steps)?this.Cf(t):t,o=(function(){const i=globalThis._posthogReleaseId;return typeof i=="string"&&i.length>0?i:void 0})();o&&(n.$release_id=o);try{const i=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",gh:!0});return i&&this.mf.clear(),i}catch(i){return eYt(i)||FB.error("Failed to capture exception event. Dropping this exception.",i),void this.mf.clear()}}catch(e){return void(eYt(e)||FB.error("Failed to process exception event. Ignoring this exception.",e))}}Cf(t){try{const e=this.mf.getAttachable();return e.length===0?t:sn(sn({},t),{},{$exception_steps:e})}catch(e){return FB.error("Failed to read buffered exception steps. Capturing exception without steps.",e),t}}kf(t){this.pf.enabled&&this.mf.add({[fge]:t,[Ige]:new Date().toISOString()})}bf(t){return QA(t)?sn({},t):{}}gf(){var t,e;return(t=(e=this._instance.config.error_tracking)===null||e===void 0?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}wf(t){if(t.length===0)return!1;try{const e=t.reduce((n,{type:o,value:i})=>(rA(o)&&o.length>0&&n.$exception_types.push(o),rA(i)&&i.length>0&&n.$exception_values.push(i),n),{$exception_types:[],$exception_values:[]});return this.vf.some(n=>{const o=n.values.map(i=>{const r=bGt[i.operator],s=e[i.key];if(!r||!s)return!1;const a=As(i.value)?i.value:[i.value];return a.length>0&&r(a,s)});return n.type==="OR"?o.some(Boolean):o.every(Boolean)})}catch(e){return FB.warn("Failed to evaluate suppression rules. Capturing the exception.",e),!1}}Sf(t){const e=t.flatMap(o=>{var i,r;return(i=(r=o.stacktrace)===null||r===void 0?void 0:r.frames)!==null&&i!==void 0?i:[]}),n=e.filter(({filename:o})=>!!o&&SYo.some(i=>o.startsWith(i)));return n.length!==0&&(!n.every(({filename:o})=>!!o&&o.startsWith(oRe))||t.some(({type:o,value:i})=>o==="NoResponse"||rA(i)&&bYo.some(({value:r,exact:s})=>s?i===r:i.includes(r)))&&!e.some(({in_app:o,filename:i})=>o&&!i?.startsWith(oRe)))}xf(t){return t.some(({value:e})=>rA(e)&&QYo.some(n=>e.includes(n)))}$f(t){if(t.length>0){var e,n,o,i;const r=(e=(n=t[0].stacktrace)===null||n===void 0?void 0:n.frames)!==null&&e!==void 0?e:[],s=r[r.length-1];return(o=s==null||(i=s.filename)===null||i===void 0?void 0:i.includes("posthog.com/static"))!==null&&o!==void 0&&o}return!1}_f(t){return!Hs(t)&&As(t)}}},LYo=sn({productTours:class{get Il(){return this._instance.persistence}constructor(t){this.Tf=null,this.If=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!t.ok)return;const e=t.config;if("productTours"in e){var n,o;if(this.Il&&this.Il.register({[sNe]:!!e.productTours}),!tRe(this._instance))return!this.Tf&&Hs((n=this.Il)===null||n===void 0?void 0:n.props.ph_product_tours)||Gge.info("product tours disabled; stopping and clearing cached tours"),(o=this.Tf)===null||o===void 0||o.stop(),this.Tf=null,void this.clearCache();this.loadIfEnabled()}}loadIfEnabled(){!this.Tf&&tRe(this._instance)&&this.Ho(()=>this.Mf())}Ho(t){var e,n,o;!((e=Vr.__PosthogExtensions__)===null||e===void 0)&&e.generateProductTours?t():(n=Vr.__PosthogExtensions__)===null||n===void 0||(o=n.loadExternalDependency)===null||o===void 0||o.call(n,this._instance,"product-tours",i=>{i?Gge.error("Could not load product tours script",i):t()})}Mf(){var t;!this.Tf&&(!((t=Vr.__PosthogExtensions__)===null||t===void 0)&&t.generateProductTours)&&(this.Tf=Vr.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e=!1){if(As(this.If)&&!e)return void t(this.If,{isLoaded:!0});const n=this.Il;if(n){const o=n.props[ANe];if(As(o)&&!e)return this.If=o,void t(o,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/product_tours/?token=${this._instance.config.token}`),method:"GET",timestampMode:"query",callback:o=>{if(!tRe(this._instance))return void t([],{isLoaded:!0});const i=o.statusCode;if(i!==200||!o.json){const s=`Product Tours API could not be loaded, status: ${i}`;return i===0?o.error||Gge.warn(s):Gge.error(s),void t([],{isLoaded:!1,error:s})}const r=As(o.json.product_tours)?o.json.product_tours:[];this.If=r,n&&n.register({[ANe]:r}),t(r,{isLoaded:!0})}})}getActiveProductTours(t){Hs(this.Tf)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.Tf.getActiveProductTours(t)}showProductTour(t){var e;(e=this.Tf)===null||e===void 0||e.showTourById(t)}previewTour(t){this.Tf?this.Tf.previewTour(t):this.Ho(()=>{var e;this.Mf(),(e=this.Tf)===null||e===void 0||e.previewTour(t)})}dismissProductTour(){var t;(t=this.Tf)===null||t===void 0||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.Tf)===null||t===void 0||t.nextStep()}previousStep(){var t;(t=this.Tf)===null||t===void 0||t.previousStep()}clearCache(){var t;this.If=null,(t=this.Il)===null||t===void 0||t.unregister("ph_product_tours")}resetTour(t){var e;(e=this.Tf)===null||e===void 0||e.resetTour(t)}resetAllTours(){var t;(t=this.Tf)===null||t===void 0||t.resetAllTours()}cancelPendingTour(t){var e;(e=this.Tf)===null||e===void 0||e.cancelPendingTour(t)}}},Uge),HYo={siteApps:class{constructor(t){this._instance=t,this.Ef=0,this.Pf=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Rf(t,e){if(!e)return;const n=this.globalsForEvent(e);this.Pf.push(n),this.Pf.length>1e3&&(this.Pf=this.Pf.slice(10))}get siteAppLoaders(){var t;return(t=Vr._POSTHOG_REMOTE_CONFIG)===null||t===void 0||(t=t[this._instance.config.token])===null||t===void 0?void 0:t.siteApps}initialize(){if(this.isEnabled){const t=this._instance._addCaptureHook(this.Rf.bind(this));this.Af=()=>{t(),this.Pf=[],this.Af=void 0}}}globalsForEvent(t){var e,n,o,i,r,s,a;if(!t)throw new Error("Event payload is required");const A={},c=this._instance.get_property("$groups")||[],l=this._instance.get_property("$stored_group_properties")||{};for(const[h,d]of Object.entries(l))A[h]={id:c[h],type:h,properties:d};const{$set_once:u,$set:g}=t;return{event:sn(sn({},IHt(t,pYo)),{},{properties:sn(sn(sn({},t.properties),g?{$set:sn(sn({},(e=(n=t.properties)===null||n===void 0?void 0:n.$set)!==null&&e!==void 0?e:{}),g)}:{}),u?{$set_once:sn(sn({},(o=(i=t.properties)===null||i===void 0?void 0:i.$set_once)!==null&&o!==void 0?o:{}),u)}:{}),elements_chain:(r=(s=t.properties)===null||s===void 0?void 0:s.$elements_chain)!==null&&r!==void 0?r:"",distinct_id:(a=t.properties)===null||a===void 0?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:A}}Of(t){var e;const n=(e=t.tagName)===null||e===void 0?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(h6.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(h6.error("prepare_external_dependency_script returned null"),null):t}Ff(){var t,e,n,o,i,r,s,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};const A=No?.defaultView,c=A==null||(t=A.Node)===null||t===void 0?void 0:t.prototype;if(!A||!c)return()=>{};if(this.Ef++,this.Df)return this.Lf();const l=[],u=this,g=new WeakSet,h=(m,_,f)=>{if(!m?.[_])return;const I=m[_];m[_]=f(I),l.push(()=>{m[_]=I})},d=m=>{if(g.has(m))return m;const _=u.Of(m);return _&&g.add(_),_},p=m=>m.map(_=>typeof _=="string"?_:d(_)).filter(_=>!Id(_));return h(c,"appendChild",m=>function(_){const f=d(_);return f?m.call(this,f):_}),h(c,"insertBefore",m=>function(_,f){const I=d(_);return I?m.call(this,I,f):_}),h(c,"replaceChild",m=>function(_,f){const I=d(_);return I?m.call(this,I,f):f}),[(e=A.Element)===null||e===void 0?void 0:e.prototype,(n=A.Document)===null||n===void 0?void 0:n.prototype,(o=A.DocumentFragment)===null||o===void 0?void 0:o.prototype].forEach(m=>{h(m,"append",_=>function(...f){return _.apply(this,p(f))}),h(m,"prepend",_=>function(...f){return _.apply(this,p(f))})}),[(i=A.Element)===null||i===void 0?void 0:i.prototype,(r=A.CharacterData)===null||r===void 0?void 0:r.prototype,(s=A.DocumentType)===null||s===void 0?void 0:s.prototype].forEach(m=>{h(m,"before",_=>function(...f){return _.apply(this,p(f))}),h(m,"after",_=>function(...f){return _.apply(this,p(f))}),h(m,"replaceWith",_=>function(...f){const I=p(f);return f.length&&!I.length?void 0:_.apply(this,I)})}),h((a=A.Element)===null||a===void 0?void 0:a.prototype,"insertAdjacentElement",m=>function(_,f){const I=d(f);return I?m.call(this,_,I):null}),this.Df=()=>{l.forEach(m=>m()),this.Df=void 0},this.Lf()}Lf(){let t=!1;return()=>{var e;t||(t=!0,this.Ef--,this.Ef===0&&((e=this.Df)===null||e===void 0||e.call(this)))}}Nf(t,e=!0){const n=this.Ff();try{const o=t(n);return e&&n(),o}catch(o){throw n(),o}}setupSiteApp(t){const e=this.apps[t.id],n=()=>{var r;!e.errored&&this.Pf.length&&(h6.info(`Processing ${this.Pf.length} events for site app with id ${t.id}`),this.Pf.forEach(s=>this.Nf(()=>{var a;return(a=e.processEvent)===null||a===void 0?void 0:a.call(e,s)})),e.processedBuffer=!0),Object.values(this.apps).every(s=>s.processedBuffer||s.errored)&&((r=this.Af)===null||r===void 0||r.call(this))};let o=!1;const i=r=>{e.errored=!r,e.loaded=!0,h6.info(`Site app with id ${t.id} ${r?"loaded":"errored"}`),o&&n()};try{const{processEvent:r}=this.Nf(s=>t.init({posthog:this._instance,callback(a){s(),i(a)}}),!1);r&&(e.processEvent=r),o=!0}catch(r){h6.error(UGt+t.id,r),i(!1)}if(o&&e.loaded)try{n()}catch(r){h6.error(`Error while processing buffered events PostHog app with config id ${t.id}`,r),e.errored=!0}}qf(){const t=this.siteAppLoaders||[];for(const e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(const e of t)this.setupSiteApp(e)}jf(t){if(Object.keys(this.apps).length===0)return;const e=this.globalsForEvent(t);for(const n of Object.values(this.apps))try{this.Nf(()=>{var o;return(o=n.processEvent)===null||o===void 0?void 0:o.call(n,e)})}catch(o){h6.error(`Error while processing event ${t.event} for site app ${n.id}`,o)}}onRemoteConfig(t){var e,n,o;if(!((e=this.siteAppLoaders)===null||e===void 0)&&e.length)return this.isEnabled?(this.qf(),void this._instance.on("eventCaptured",a=>this.jf(a))):void h6.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.Af)===null||n===void 0||n.call(this),!t.ok)return;const i=t.config;if(!((o=i.siteApps)===null||o===void 0)&&o.length)if(this.isEnabled)for(const{id:a,url:A}of i.siteApps){var r,s;Vr[`__$$ph_site_app_${a}`]=this._instance,(r=Vr.__PosthogExtensions__)===null||r===void 0||(s=r.loadSiteApp)===null||s===void 0||s.call(r,this._instance,A,c=>{if(c)return h6.error(UGt+a,c)})}else h6.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},OYo={tracingHeaders:class{constructor(t){this._instance=t,this.Bf=void 0,this.Hf=void 0,this.zf=void 0,this.nf=()=>{const e=this.Uf();var n,o;e?(Eo(this.Bf)&&(this.Bf=(n=Vr.__PosthogExtensions__)===null||n===void 0||(n=n.tracingHeadersPatchFns)===null||n===void 0?void 0:n._patchXHR(e,()=>this._instance.get_distinct_id(),this._instance.sessionManager)),Eo(this.Hf)&&(this.Hf=(o=Vr.__PosthogExtensions__)===null||o===void 0||(o=o.tracingHeadersPatchFns)===null||o===void 0?void 0:o._patchFetch(e,()=>this._instance.get_distinct_id(),this._instance.sessionManager))):this.hf()}}initialize(){this.startIfEnabledOrStop()}Ho(t){var e,n,o;!((e=Vr.__PosthogExtensions__)===null||e===void 0)&&e.tracingHeadersPatchFns?t():(n=Vr.__PosthogExtensions__)===null||n===void 0||(o=n.loadExternalDependency)===null||o===void 0||o.call(n,this._instance,"tracing-headers",i=>{if(i)return lYo.error("failed to load script",i);t()})}Wf(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Uf(){const t=this.Wf();return As(t)?(As(this.zf)?this.zf.splice(0,this.zf.length,...t):this.zf=[...t],t.length>0?this.zf:void 0):(As(this.zf)&&this.zf.splice(0),this.zf=t||void 0,this.zf)}hf(){var t,e;(t=this.Bf)===null||t===void 0||t.call(this),(e=this.Hf)===null||e===void 0||e.call(this),this.Bf=void 0,this.Hf=void 0}startIfEnabledOrStop(){this.Uf()?this.Ho(this.nf):this.hf()}}},GYo=sn({surveys:class extends mYo{constructor(t){var e;super(new yYo(t),(e=t,{get projectToken(){return e.config.token},kv:new CYo(e)})),this._instance=t}Qh(t,e){const n=e.query?iq(t,e.query):t;return new Promise(o=>{var i;this._instance._send_request({method:e.method,url:this._instance.requestRouter.endpointFor((i=e.target)!==null&&i!==void 0?i:"api",n),data:e.body,headers:e.headers,timeout:e.timeoutMs,fireCallbackOnDrop:!0,transport:e.transport,compression:e.compression,timestampMode:e.sentAt,callback:o})})}}},Uge),YYo={toolbar:class{constructor(t){this.instance=t}Vf(t){Vr.ph_toolbar_state=t}Gf(){var t;return(t=Vr.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t=void 0,e=void 0,n=void 0){var o,i;if(_Ne(this.instance.config)||!Fn||!No)return!1;t=(o=t)!==null&&o!==void 0?o:Fn.location,n=(i=n)!==null&&i!==void 0?i:Fn.history;try{if(!e){try{Fn.localStorage.setItem("test","test"),Fn.localStorage.removeItem("test")}catch{return!1}e=Fn?.localStorage}const r=xYo||Mge(t.hash,"__posthog")||Mge(t.hash,"state");let s;const a=r?tHt(()=>JSON.parse(atob(decodeURIComponent(r))))||tHt(()=>JSON.parse(decodeURIComponent(r))):null;return a&&a.action==="ph_authorize"?(s=a,s.source="url",s&&Object.keys(s).length>0&&(a.desiredHash?t.hash=a.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):(s=JSON.parse(e.getItem(zGt)||"{}"),s.source="localstorage",delete s.userIntent),!(!s.token||this.instance.config.token!==s.token||(this.loadToolbar(s),0))}catch{return!1}}Qf(t){const e=Vr.ph_load_toolbar||Vr.ph_load_editor;!Hs(e)&&nf(e)?e(t,this.instance):JGt.warn("No toolbar load function found")}loadToolbar(t){const e=!!No?.getElementById("__POSTHOG_TOOLBAR__");if(!Fn||e)return!1;const n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,o=sn(sn({token:this.instance.config.token},t),{},{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(Fn.localStorage.setItem(zGt,JSON.stringify(sn(sn({},o),{},{source:void 0}))),this.Gf()===2)this.Qf(o);else if(this.Gf()===0){var i,r;this.Vf(1),(i=Vr.__PosthogExtensions__)===null||i===void 0||(r=i.loadExternalDependency)===null||r===void 0||r.call(i,this.instance,"toolbar",s=>{if(s)return JGt.error("[Toolbar] Failed to load",s),void this.Vf(0);this.Vf(2),this.Qf(o)}),el(Fn,"turbolinks:load",()=>{this.Vf(0),this.loadToolbar(o)})}return!0}Jf(t){return this.loadToolbar(t)}maybeLoadEditor(t=void 0,e=void 0,n=void 0){return this.maybeLoadToolbar(t,e,n)}}},UYo=sn({experiments:class sx{get Mr(){return this._instance.config}constructor(e){this._instance=e,this.getWebExperimentsAndEvaluateDisplayLogic=(n=!1)=>{this.getWebExperiments(o=>{sx.Zf("retrieved web experiments from the server"),this.Kf=new Map,o.forEach(i=>{if(i.feature_flag_key){var r;this.Kf&&(sx.Zf("setting flag key ",i.feature_flag_key," to web experiment ",i),(r=this.Kf)===null||r===void 0||r.set(i.feature_flag_key,i));const s=this._instance.getFeatureFlag(i.feature_flag_key);rA(s)&&i.variants[s]&&this.Xf(i.name,s,i.variants[s].transforms)}else if(i.variants)for(const s in i.variants){const a=i.variants[s];sx.Yf(a,this._instance)&&this.Xf(i.name,s,a.transforms)}})},n)},this._instance.onFeatureFlags(n=>{this.onFeatureFlags(n)})}initialize(){}onFeatureFlags(e){if(this._is_bot())sx.Zf(tYt);else if(!this.Mr.disable_web_experiments){if(Hs(this.Kf))return this.Kf=new Map,this.loadIfEnabled(),void this.previewWebExperiment();sx.Zf("applying feature flags",e),e.forEach(n=>{var o;if(this.Kf&&(!((o=this.Kf)===null||o===void 0)&&o.has(n))){var i;const r=this._instance.getFeatureFlag(n),s=(i=this.Kf)===null||i===void 0?void 0:i.get(n);r&&s?.variants[r]&&this.Xf(s.name,r,s.variants[r].transforms)}})}}previewWebExperiment(){const e=sx.getWindowLocation();if(e?.search){const n=iG(e?.search,"__experiment_id"),o=iG(e?.search,"__experiment_variant");n&&o&&(sx.Zf(`previewing web experiments ${n} && ${o}`),this.getWebExperiments(i=>{this.tp(parseInt(n),o,i)},!1,!0))}}loadIfEnabled(){this.Mr.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,o){if(this.Mr.disable_web_experiments&&!o)return e([]);const i=this._instance.get_property("$web_experiments");if(i&&!n)return e(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/web_experiments/?token=${this.Mr.token}`),method:"GET",timestampMode:"query",callback:r=>e(r.statusCode===200&&r.json&&r.json.experiments||[])})}tp(e,n,o){const i=o.filter(r=>r.id===e);i&&i.length>0&&(sx.Zf(`Previewing web experiment [${i[0].name}] with variant [${n}]`),this.Xf(i[0].name,n,i[0].variants[n].transforms))}static Yf(e,n){return!Hs(e.conditions)&&sx.ep(e,n)&&sx.np(e)}static ep(e,n){var o;if(Hs(e.conditions)||Hs((o=e.conditions)===null||o===void 0?void 0:o.url))return!0;const i=sx.getWindowLocation();if(i){var r,s,a;const A=dOt(n,i.href);return!(!((r=e.conditions)===null||r===void 0)&&r.url)||vYo[(s=(a=e.conditions)===null||a===void 0?void 0:a.urlMatchType)!==null&&s!==void 0?s:"icontains"](e.conditions.url,A)}return!1}static getWindowLocation(){return Fn?.location}static np(e){var n;if(Hs(e.conditions)||Hs((n=e.conditions)===null||n===void 0?void 0:n.utm))return!0;const o=LOt();if(o.utm_source){var i,r,s,a,A,c,l,u;const g=!(!((i=e.conditions)===null||i===void 0||(i=i.utm)===null||i===void 0)&&i.utm_campaign)||((r=e.conditions)===null||r===void 0||(r=r.utm)===null||r===void 0?void 0:r.utm_campaign)==o.utm_campaign,h=!(!((s=e.conditions)===null||s===void 0||(s=s.utm)===null||s===void 0)&&s.utm_source)||((a=e.conditions)===null||a===void 0||(a=a.utm)===null||a===void 0?void 0:a.utm_source)==o.utm_source,d=!(!((A=e.conditions)===null||A===void 0||(A=A.utm)===null||A===void 0)&&A.utm_medium)||((c=e.conditions)===null||c===void 0||(c=c.utm)===null||c===void 0?void 0:c.utm_medium)==o.utm_medium,p=!(!((l=e.conditions)===null||l===void 0||(l=l.utm)===null||l===void 0)&&l.utm_term)||((u=e.conditions)===null||u===void 0||(u=u.utm)===null||u===void 0?void 0:u.utm_term)==o.utm_term;return g&&d&&p&&h}return!1}static Zf(e,...n){ui.info(`[WebExperiments] ${e}`,n)}Xf(e,n,o){this._is_bot()?sx.Zf(tYt):n!=="control"?o.forEach(i=>{if(i.selector){var r;sx.Zf(`applying transform of variant ${n} for experiment ${e} `,i);const s=(r=document)===null||r===void 0?void 0:r.querySelectorAll(i.selector);s?.forEach(a=>{const A=a;i.html&&(A.innerHTML=i.html),i.css&&A.setAttribute("style",i.css)})}}):sx.Zf("Control variants leave the page unmodified.")}_is_bot(){return tf&&this._instance?xGt(tf,this.Mr.custom_blocked_useragents):void 0}}},Uge),KYo={conversations:class{constructor(t){this._instance=t,this.sp=void 0,this._conversationsManager=null,this.rp=!1,this.ne=null,this.op=!1}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(this._instance.config.disable_conversations||(this.ap=t.ok,!t.ok))return;const e=t.config.conversations;Hs(e)||($y(e)?this.sp=e:(this.sp=e.enabled,this.ne=e),this.loadIfEnabled())}reset(){var t;(t=this._conversationsManager)===null||t===void 0||t.reset(),this._conversationsManager=null,this.sp=void 0,this.ne=null,this.ap=void 0,this.op=!1}loadIfEnabled(){if(this._conversationsManager||this.rp||this._instance.config.disable_conversations||_Ne(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())return;const t=Vr?.__PosthogExtensions__;if(t&&!Eo(this.sp)&&this.sp)if(this.ne&&this.ne.token){this.rp=!0;try{const e=t.initConversations;if(e)return this.lp(e),void(this.rp=!1);const n=t.loadExternalDependency;if(!n)return void this.up(hNe);n(this._instance,"conversations",o=>{o||!t.initConversations?this.up("Could not load conversations script",o):this.lp(t.initConversations),this.rp=!1})}catch(e){this.up("Error initializing conversations",e),this.rp=!1}}else A4.error("Conversations enabled but missing token in remote config.")}lp(t){if(this.ne)try{this._conversationsManager=t(this.ne,this._instance),this.op=!1,A4.info("Conversations loaded successfully")}catch(e){this.up("Error completing conversations initialization",e)}else A4.error("Cannot complete initialization: remote config is null")}up(t,e){A4.error(t,e),this._conversationsManager=null,this.rp=!1,this.op=!0}show(){this._conversationsManager?this._conversationsManager.show():A4.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.sp===!0&&!Id(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":_Ne(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.ap===!1?"remote_config_failed":Eo(this.sp)?this.ap?"disabled_in_project":"remote_config_pending":this.sp?Hs(this.ne)||!this.ne.token?"missing_token":Vr?.__PosthogExtensions__?this.rp?"initializing":this.op?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)===null||e===void 0?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var o=this;return Zu(function*(){return o._conversationsManager?o._conversationsManager.sendMessage(t,e,n):(A4.warn(vR),null)})()}getMessages(t,e){var n=this;return Zu(function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(A4.warn(vR),null)})()}markAsRead(t){var e=this;return Zu(function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(A4.warn(vR),null)})()}getTickets(t){var e=this;return Zu(function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(A4.warn(vR),null)})()}requestRestoreLink(t){var e=this;return Zu(function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(A4.warn(vR),null)})()}restoreFromToken(t){var e=this;return Zu(function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(A4.warn(vR),null)})()}restoreFromUrlToken(){var t=this;return Zu(function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(A4.warn(vR),null)})()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)===null||e===void 0?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)===null||e===void 0?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}$h(){var t;(t=this._conversationsManager)===null||t===void 0||t.setIdentity()}Ch(){var t;(t=this._conversationsManager)===null||t===void 0||t.clearIdentity()}}},VYo={logs:class{constructor(t){var e;this._instance=t,this.name="logs",this.hp=!1,this.cp=!1,this.dp=!1,this.A=Cd("[logs]"),this.vp=sn(sn({},this.A),{},{error:(...n)=>{n.some(rYt)||this.A.error(...n)}}),this.ol=[],this.fp=[],this.kd=0,this.To=!1,this.pp=[],this.gp=[],this.mp=!1,this.yp=!1,this.bp=()=>{var n,o;this.To||(this.kd=0,(n=this._p)===null||n===void 0||n.onReconnect(),(o=this.wp)===null||o===void 0||o.onReconnect())},this._instance&&(!((e=this._instance.config.logs)===null||e===void 0)&&e.captureConsoleLogs)&&(this.hp=!0),Fn&&el(Fn,"online",this.bp)}kp(t,e,n,o){var i;const r=nYt((i=this._instance)===null||i===void 0||(i=i.config)===null||i===void 0?void 0:i.logs,n);return[new vOo(this.Sp(t,e),r,this.vp,()=>this.xp(),s=>s(),void 0,o),r]}$p(){var t;const e=(t=this._instance)===null||t===void 0||(t=t.config)===null||t===void 0?void 0:t.logs;var n;return this._p&&this.Cp===e||((n=this._p)===null||n===void 0||n.reset(),this.Cp=e,[this._p,this.Tp]=this.kp(()=>this.ol,o=>{this.ol=o})),this._p}Ip(){var t;const e=(t=this._instance)===null||t===void 0||(t=t.config)===null||t===void 0?void 0:t.logs;var n;return this.wp&&this.Mp===e||((n=this.wp)===null||n===void 0||n.reset(),this.Mp=e,[this.wp,this.Ep]=this.kp(()=>this.fp,o=>{this.fp=o},{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},oYt)),this.wp}setup(t){var e;if(this.To)return;this.bo=t,!((e=this._instance)===null||e===void 0||(e=e.config)===null||e===void 0||(e=e.logs)===null||e===void 0)&&e.captureConsoleLogs&&(this.hp=!0),(this.hp||this.Pp()&&this.Rp())&&this.Ap();let n=!1;const o=t.onRemoteConfig(i=>{var r;n=i.ok&&((r=i.config.logs)===null||r===void 0?void 0:r.captureConsoleLogs)===!0,this.onRemoteConfig(i)});this.To?o.dispose():(this.Eo=o,n||this.loadIfEnabled())}dispose(){var t,e,n,o;this.To||(this.To=!0,this.Op(),(t=this.Eo)===null||t===void 0||t.dispose(),this.Eo=void 0,this.bo=void 0,this.dp=!1,Fn?.removeEventListener("online",this.bp),(e=this.Fp)===null||e===void 0||e.call(this),this.Fp=void 0,(n=this._p)===null||n===void 0||n.reset(),(o=this.wp)===null||o===void 0||o.reset())}onRemoteConfig(t){var e,n;if(this.To)return;const o=t.ok?(e=t.config.logs)===null||e===void 0?void 0:e.captureConsoleLogs:void 0;Hs(o)?this.Dp():((n=this._instance)===null||n===void 0||(n=n.persistence)===null||n===void 0||n.register({$logs_capture_enabled_server_side:!!o}),o?(this.hp=!0,this.cp||this.Ap(),this.loadIfEnabled()):this.Dp())}reset(){var t,e,n,o;this.Op(),(t=this._p)===null||t===void 0||t.clearQueue(),this.ol=[],(e=this._p)===null||e===void 0||e.reset(),(n=this.wp)===null||n===void 0||n.clearQueue(),this.fp=[],(o=this.wp)===null||o===void 0||o.reset(),this.kd=0}captureLog(t){this.To||this.$p().captureLog(t)}captureConsoleLog(t){this.To||this.Ip().captureLog(t)}captureBufferedConsoleLog(t,e,n){this.To||this.Ip().captureLog(t,{context:e,occurredAtMs:n})}Rp(){var t;return!!(!((t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0||(t=t.props)===null||t===void 0)&&t[LHt])}Pp(){var t,e,n;return!(!((t=this._instance)===null||t===void 0||(e=t.il)===null||e===void 0)&&e.call(t))||!!(!((n=Vr._POSTHOG_REMOTE_CONFIG)===null||n===void 0||(n=n[this._instance.config.token])===null||n===void 0)&&n.config)}Ih(){var t;this.Op(),(t=this.wp)===null||t===void 0||t.clearQueue(),this.fp=[]}Dp(){this.hp||this.Op()}Ap(){var t;if(this.mp||!Vr?.console)return;const e=nYt((t=this._instance)===null||t===void 0||(t=t.config)===null||t===void 0?void 0:t.logs).maxBufferSize;let n=!0;this.gp.push(()=>{n=!1});for(const o of wYo){let i;try{i=PYo(Vr.console[o])}catch{continue}i&&this.gp.push(lq(Vr.console,o,r=>{const s=(...a)=>{try{n&&this.Lp(o,a,e)}catch{}return r.apply(Vr.console,a)};return s.__rrweb_original__=i,s}))}this.mp=!0,this.Np=setTimeout(()=>{this.Op()},3e4)}Lp(t,e,n){var o;if(this.mp&&!this.yp&&e.length!==0)if(!((o=this._instance)===null||o===void 0)&&o.is_capturing()){if(n>this.pp.length){this.yp=!0;try{this.pp.push({level:t,args:e,occurredAtMs:Date.now(),context:this.xp()})}finally{this.yp=!1}}}else this.Op()}Op(){if(this.pp=[],this.mp){this.mp=!1,this.Np&&(clearTimeout(this.Np),this.Np=void 0);for(const t of this.gp)t();this.gp=[]}}qp(){const t=this.pp;return this.Op(),t}get logger(){return this.jp||(this.jp={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.jp}flushLogs(t){t?this.Bp(t):(this._p&&this._p.flush().catch(e=>this.Hp(e)),this.wp&&this.wp.flush().catch(e=>this.Hp(e)))}Hp(t){rYt(t)||this.A.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.To||!this.hp||this.cp||this.dp)return;const t=Vr?.__PosthogExtensions__;if(!t)return this.A.error("PostHog Extensions not found."),void this.Op();const e=t.loadExternalDependency;if(!e)return this.A.error(hNe),void this.Op();this.dp=!0;try{e(this._instance,"logs",n=>{if(this.dp=!1,this.To||!this.hp)return;const o=t.logs;if(n||!o?.initializeLogs)this.A.error("Could not load logs script",n),this.Op();else{var i;const a=this.qp();var r,s;this.Fp=o.initializeLogs((i=this.bo)!==null&&i!==void 0?i:this._instance),this.cp=!0,a.length>0&&((r=o.replayConsoleBuffer)===null||r===void 0||r.call(o,(s=this.bo)!==null&&s!==void 0?s:this._instance,a))}})}catch(n){throw this.dp=!1,n}}Sp(t,e){const n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:o=>o===l6.LogsQueue?t():void 0,setPersistedProperty(o,i){var r;o===l6.LogsQueue&&e((r=i)!==null&&r!==void 0?r:[])},js:o=>this.js(o),getLibraryId:()=>n_.LIB_NAME,getLibraryVersion:()=>n_.LIB_VERSION}}js(t){return new Promise(e=>{if(kOt(this.kd,3))return void e({kind:"fatal",error:iRe(void 0,"logs endpoint is unreachable, dropping batch")});let n=!1;const o=r=>{n||(n=!0,clearTimeout(i),e(r))},i=setTimeout(()=>{this.A.warn("Logs request timed out before receiving a response"),o({kind:"retry-later",error:iRe(void 0,"logs request timed out")})},9e4);this._instance._send_request({method:"POST",url:this.zp(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:r=>{const s=r.statusCode;if(this.Up(s),s>=200&&300>s)o({kind:"ok"});else if(s===413)o({kind:"too-large"});else if(s!==0&&s!==408&&s!==429&&500>s)o({kind:"fatal",error:new Error(`logs request failed with status ${s}`)});else{var a;s===0?(r.error||this.A.warn("Logs request failed before receiving an HTTP response"),o({kind:"retry-later",error:iRe(r.error,"logs request failed before receiving an HTTP response")})):o({kind:"retry-later",error:(a=r.error)!==null&&a!==void 0?a:new Error(`logs request failed with status ${s}`)})}}})})}Up(t){(t!==0||this._instance.__loaded)&&(this.kd=FOt(t,this.kd,3,()=>this.A.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes.")))}Bp(t){this.ol.length>0&&this.Wp(t,this.ol,this.Tp,n_.LIB_NAME,e=>{this.ol=e}),this.fp.length>0&&this.Wp(t,this.fp,this.Ep,oYt,e=>{this.fp=e})}Wp(t,e,n,o,i){if(e.length===0)return;const r=e.map(a=>a.record);i([]);const s=SHt(r,bHt(n,n_.LIB_NAME,n_.LIB_VERSION),o,n_.LIB_VERSION);this._instance._send_request({method:"POST",url:this.zp(),data:s,compression:"best-available",batchKey:"logs",transport:t})}zp(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}xp(){var t;const e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){const{sessionId:n,windowId:o,sessionStartTimestamp:i,lastActivityTimestamp:r}=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0);e.sessionId=n,e.windowId=o,Hs(i)||(e.sessionStartTimestamp=i),Hs(r)||(e.lastActivityTimestamp=r)}if(!(Vr==null||(t=Vr.location)===null||t===void 0)&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Mw(Vr.location.href):Vr.location.href),this._instance.featureFlags){const n=this._instance.featureFlags.getFlags();n&&n.length>0&&(e.activeFeatureFlags=n)}return e}}},zYo={metrics:class{constructor(t){this._instance=t,this.A=Cd("[metrics]"),this.To=!1}initialize(){this.onConfigChange()}onConfigChange(){var t;if(this.To)return;const e=!!(!((t=this._instance.config.metrics)===null||t===void 0)&&t.network);e&&!this.Vp?this.Vp=(n=>{let o=!0;const i=()=>o?(a=>{var A;const c=(A=a.config.metrics)===null||A===void 0?void 0:A.network;return c===!0?{}:c||void 0})(n):void 0,r=NYo(n,i),s=RYo(n,i);return()=>{o=!1,r(),s()}})(this._instance):!e&&this.Vp&&(this.Vp(),this.Vp=void 0)}$p(){var t;const e=(t=this._instance)===null||t===void 0||(t=t.config)===null||t===void 0?void 0:t.metrics;var n;return this._p&&this.Cp===e||((n=this._p)===null||n===void 0||n.reset(),this.Cp=e,this._p=new wOo(this.Sp(),(function(o){var i,r,s,a,A;const c=o?.resourceAttributes;return{serviceName:(i=c?.["service.name"])!==null&&i!==void 0?i:o?.serviceName,serviceVersion:(r=c?.["service.version"])!==null&&r!==void 0?r:o?.serviceVersion,environment:(s=c?.["deployment.environment"])!==null&&s!==void 0?s:o?.environment,resourceAttributes:c,beforeSend:o?.beforeSend,flushIntervalMs:(a=o?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(A=o?.maxSeriesPerFlush)!==null&&A!==void 0?A:1e3}})(e),this.A)),this._p}count(t,e=1,n){this.$p().count(t,e,n)}gauge(t,e,n){this.$p().gauge(t,e,n)}histogram(t,e,n){this.$p().histogram(t,e,n)}flush(t){if(!this._p)return Promise.resolve();if(t){const e=this._p.drainWindow();return e&&this.Ys(e,t),Promise.resolve()}return this._p.flush().catch(e=>this.A.error("PostHog metrics flush failed:",e))}reset(){var t;(t=this._p)===null||t===void 0||t.reset()}dispose(){var t,e;this.To=!0,(t=this.Vp)===null||t===void 0||t.call(this),this.Vp=void 0,(e=this._p)===null||e===void 0||e.reset()}Sp(){const t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Ys:n=>e.Ys(n),getLibraryId:()=>n_.LIB_NAME,getLibraryVersion:()=>n_.LIB_VERSION}}Ys(t,e){return new Promise(n=>{let o=!1;const i=s=>{o||(o=!0,clearTimeout(r),n(s))},r=setTimeout(()=>i({kind:"retry-later",error:new Error("metrics request timed out")}),9e4);this._instance._send_request(sn(sn({method:"POST",url:this.Gp(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e}),{},{fireCallbackOnDrop:!0,callback(s){const a=s.statusCode;if(a>=200&&300>a)i({kind:"ok"});else if(a===413)i({kind:"too-large"});else if(a!==0&&a!==408&&a!==429&&500>a)i({kind:"fatal",error:new Error(`metrics request failed with status ${a}`)});else{var A;i({kind:"retry-later",error:(A=s.error)!==null&&A!==void 0?A:new Error(`metrics request failed with status ${a}`)})}}}))})}Gp(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}};Aq.__defaultExtensionClasses=sn({},sn(sn(sn(sn(sn(sn(sn(sn(sn(sn(sn(sn(sn({},Uge),TYo),kYo),FYo),LYo),HYo),GYo),OYo),YYo),UYo),KYo),VYo),zYo));var dG=(function(){n_.SDK_DIST_CHANNEL="npm";const t=rq[aq]=new Aq;return(function(){function e(){e.done||(e.done=!0,_Gt=!1,kl(rq,function(n){n._dom_loaded()}))}No?.addEventListener?No.readyState==="complete"?e():el(No,"DOMContentLoaded",e,{capture:!1}):Fn&&ui.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();class Wb extends Error{response;request;options;constructor(e,n,o){const i=e.status||e.status===0?e.status:"",r=e.statusText??"",s=`${i} ${r}`.trim(),a=s?`status code ${s}`:"an unknown error";super(`Request failed with ${a}: ${n.method} ${n.url}`),this.name="HTTPError",this.response=e,this.request=n,this.options=o}}class AYt extends Error{name="NonError";value;constructor(e){let n="Non-error value was thrown";try{typeof e=="string"?n=e:e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"&&(n=e.message)}catch{}super(n),this.value=e}}class aRe extends Error{name="ForceRetryError";customDelay;code;customRequest;constructor(e){const n=e?.cause?e.cause instanceof Error?e.cause:new AYt(e.cause):void 0;super(e?.code?`Forced retry: ${e.code}`:"Forced retry",n?{cause:n}:void 0),this.customDelay=e?.delay,this.code=e?.code,this.customRequest=e?.request}}const cYt=(()=>{let t=!1,e=!1;const n=typeof globalThis.ReadableStream=="function",o=typeof globalThis.Request=="function";if(n&&o)try{e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type")}catch(i){if(i instanceof Error&&i.message==="unsupported BodyInit type")return!1;throw i}return t&&!e})(),JYo=typeof globalThis.AbortController=="function",lYt=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",WYo=typeof globalThis.ReadableStream=="function",jYo=typeof globalThis.FormData=="function",uYt=["get","post","put","patch","head","delete"],$Yo={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},ARe=2147483647,qYo=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,gYt=Symbol("stop");class dYt{options;constructor(e){this.options=e}}const XYo=t=>new dYt(t),ZYo={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},eUo={next:!0},tUo={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0},nUo=t=>{if(!t)return 0;if(t instanceof FormData){let e=0;for(const[n,o]of t)e+=qYo,e+=new TextEncoder().encode(`Content-Disposition: form-data; name="${n}"`).length,e+=typeof o=="string"?new TextEncoder().encode(o).length:o.size;return e}if(t instanceof Blob)return t.size;if(t instanceof ArrayBuffer)return t.byteLength;if(typeof t=="string")return new TextEncoder().encode(t).length;if(t instanceof URLSearchParams)return new TextEncoder().encode(t.toString()).length;if("byteLength"in t)return t.byteLength;if(typeof t=="object"&&t!==null)try{const e=JSON.stringify(t);return new TextEncoder().encode(e).length}catch{return 0}return 0},hYt=(t,e,n)=>{let o,i=0;return t.pipeThrough(new TransformStream({transform(r,s){if(s.enqueue(r),o){i+=o.byteLength;let a=e===0?0:i/e;a>=1&&(a=1-Number.EPSILON),n?.({percent:a,totalBytes:Math.max(e,i),transferredBytes:i},o)}o=r},flush(){o&&(i+=o.byteLength,n?.({percent:1,totalBytes:Math.max(e,i),transferredBytes:i},o))}}))},oUo=(t,e)=>{if(!t.body)return t;if(t.status===204)return new Response(null,{status:t.status,statusText:t.statusText,headers:t.headers});const n=Math.max(0,Number(t.headers.get("content-length"))||0);return new Response(hYt(t.body,n,e),{status:t.status,statusText:t.statusText,headers:t.headers})},iUo=(t,e,n)=>{if(!t.body)return t;const o=nUo(n??t.body);return new Request(t,{duplex:"half",body:hYt(t.body,o,e)})},wR=t=>t!==null&&typeof t=="object",Kge=(...t)=>{for(const e of t)if((!wR(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return cRe({},...t)},pYt=(t={},e={})=>{const n=new globalThis.Headers(t),o=e instanceof globalThis.Headers,i=new globalThis.Headers(e);for(const[r,s]of i.entries())o&&s==="undefined"||s===void 0?n.delete(r):n.set(r,s);return n};function Vge(t,e,n){return Object.hasOwn(e,n)&&e[n]===void 0?[]:cRe(t[n]??[],e[n]??[])}const mYt=(t={},e={})=>({beforeRequest:Vge(t,e,"beforeRequest"),beforeRetry:Vge(t,e,"beforeRetry"),afterResponse:Vge(t,e,"afterResponse"),beforeError:Vge(t,e,"beforeError")}),rUo=(t,e)=>{const n=new URLSearchParams;for(const o of[t,e])if(o!==void 0)if(o instanceof URLSearchParams)for(const[i,r]of o.entries())n.append(i,r);else if(Array.isArray(o))for(const i of o){if(!Array.isArray(i)||i.length!==2)throw new TypeError("Array search parameters must be provided in [[key, value], ...] format");n.append(String(i[0]),String(i[1]))}else if(wR(o))for(const[i,r]of Object.entries(o))r!==void 0&&n.append(i,String(r));else{const i=new URLSearchParams(o);for(const[r,s]of i.entries())n.append(r,s)}return n},cRe=(...t)=>{let e={},n={},o={},i;const r=[];for(const s of t)if(Array.isArray(s))Array.isArray(e)||(e=[]),e=[...e,...s];else if(wR(s)){for(let[a,A]of Object.entries(s)){if(a==="signal"&&A instanceof globalThis.AbortSignal){r.push(A);continue}if(a==="context"){if(A!=null&&(!wR(A)||Array.isArray(A)))throw new TypeError("The `context` option must be an object");e={...e,context:A==null?{}:{...e.context,...A}};continue}if(a==="searchParams"){A==null?i=void 0:i=i===void 0?A:rUo(i,A);continue}wR(A)&&a in e&&(A=cRe(e[a],A)),e={...e,[a]:A}}wR(s.hooks)&&(o=mYt(o,s.hooks),e.hooks=o),wR(s.headers)&&(n=pYt(n,s.headers),e.headers=n)}return i!==void 0&&(e.searchParams=i),r.length>0&&(r.length===1?e.signal=r[0]:lYt?e.signal=AbortSignal.any(r):e.signal=r.at(-1)),e},sUo=t=>uYt.includes(t)?t.toUpperCase():t,_Yt={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:t=>.3*2**(t-1)*1e3,jitter:void 0,retryOnTimeout:!1},aUo=(t={})=>{if(typeof t=="number")return{..._Yt,limit:t};if(t.methods&&!Array.isArray(t.methods))throw new Error("retry.methods must be an array");if(t.methods&&=t.methods.map(n=>n.toLowerCase()),t.statusCodes&&!Array.isArray(t.statusCodes))throw new Error("retry.statusCodes must be an array");const e=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0));return{..._Yt,...e}};class lRe extends Error{request;constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.name="TimeoutError",this.request=e}}async function AUo(t,e,n,o){return new Promise((i,r)=>{const s=setTimeout(()=>{n&&n.abort(),r(new lRe(t))},o.timeout);o.fetch(t,e).then(i).catch(r).then(()=>{clearTimeout(s)})})}async function cUo(t,{signal:e}){return new Promise((n,o)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",i,{once:!0}));function i(){clearTimeout(r),o(e.reason)}const r=setTimeout(()=>{e?.removeEventListener("abort",i),n()},t)})}const lUo=(t,e)=>{const n={};for(const o in e)Object.hasOwn(e,o)&&!(o in tUo)&&!(o in ZYo)&&(!(o in t)||o in eUo)&&(n[o]=e[o]);return n},uUo=t=>t===void 0?!1:Array.isArray(t)?t.length>0:t instanceof URLSearchParams?t.size>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!!t;function gUo(t){return t instanceof Wb||t?.name===Wb.name}function dUo(t){return t instanceof lRe||t?.name===lRe.name}let fYt=class Bit{static create(e,n){const o=new Bit(e,n),i=async()=>{if(typeof o.#e.timeout=="number"&&o.#e.timeout>ARe)throw new RangeError(`The \`timeout\` option cannot be greater than ${ARe}`);await Promise.resolve();let s=await o.#_();for(const a of o.#e.hooks.afterResponse){const A=o.#g(s.clone());let c;try{c=await a(o.request,o.#u(),A,{retryCount:o.#i})}catch(u){throw o.#A(A),o.#A(s),u}if(c instanceof dYt)throw o.#A(A),o.#A(s),new aRe(c.options);const l=c instanceof globalThis.Response?c:s;A!==l&&o.#A(A),s!==l&&o.#A(s),s=l}if(o.#g(s),!s.ok&&(typeof o.#e.throwHttpErrors=="function"?o.#e.throwHttpErrors(s.status):o.#e.throwHttpErrors)){let a=new Wb(s,o.request,o.#u());for(const A of o.#e.hooks.beforeError)a=await A(a,{retryCount:o.#i});throw a}if(o.#e.onDownloadProgress){if(typeof o.#e.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!WYo)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");const a=s.clone();return o.#A(s),oUo(a,o.#e.onDownloadProgress)}return s},r=o.#m(i).finally(()=>{const s=o.#s;o.#d(s?.body??void 0),o.#d(o.request.body??void 0)});for(const[s,a]of Object.entries($Yo))s==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(r[s]=async()=>{o.request.headers.set("accept",o.request.headers.get("accept")||a);const A=await r;if(s==="json"){if(A.status===204)return"";const c=await A.text();return c===""?"":n.parseJson?n.parseJson(c):JSON.parse(c)}return A[s]()});return r}static#o(e){return e&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof URLSearchParams)?Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0)):e}request;#n;#i=0;#t;#e;#s;#r;#c;constructor(e,n={}){if(this.#t=e,this.#e={...n,headers:pYt(this.#t.headers,n.headers),hooks:mYt({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:sUo(n.method??this.#t.method??"GET"),prefixUrl:String(n.prefixUrl||""),retry:aUo(n.retry),throwHttpErrors:n.throwHttpErrors??!0,timeout:n.timeout??1e4,fetch:n.fetch??globalThis.fetch.bind(globalThis),context:n.context??{}},typeof this.#t!="string"&&!(this.#t instanceof URL||this.#t instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this.#e.prefixUrl&&typeof this.#t=="string"){if(this.#t.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this.#e.prefixUrl.endsWith("/")||(this.#e.prefixUrl+="/"),this.#t=this.#e.prefixUrl+this.#t}JYo&&lYt&&(this.#r=this.#e.signal??this.#t.signal,this.#n=new globalThis.AbortController,this.#e.signal=this.#r?AbortSignal.any([this.#r,this.#n.signal]):this.#n.signal),cYt&&(this.#e.duplex="half"),this.#e.json!==void 0&&(this.#e.body=this.#e.stringifyJson?.(this.#e.json)??JSON.stringify(this.#e.json),this.#e.headers.set("content-type",this.#e.headers.get("content-type")??"application/json"));const o=n.headers&&new globalThis.Headers(n.headers).has("content-type");if(this.#t instanceof globalThis.Request&&(jYo&&this.#e.body instanceof globalThis.FormData||this.#e.body instanceof URLSearchParams)&&!o&&this.#e.headers.delete("content-type"),this.request=new globalThis.Request(this.#t,this.#e),uUo(this.#e.searchParams)){const r="?"+(typeof this.#e.searchParams=="string"?this.#e.searchParams.replace(/^\?/,""):new URLSearchParams(Bit.#o(this.#e.searchParams)).toString()),s=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,r);this.request=new globalThis.Request(s,this.#e)}if(this.#e.onUploadProgress){if(typeof this.#e.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!cYt)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request=this.#p(this.request,this.#e.body??void 0)}}#a(){const e=this.#e.retry.delay(this.#i);let n=e;this.#e.retry.jitter===!0?n=Math.random()*e:typeof this.#e.retry.jitter=="function"&&(n=this.#e.retry.jitter(e),(!Number.isFinite(n)||n<0)&&(n=e));const o=this.#e.retry.backoffLimit??Number.POSITIVE_INFINITY;return Math.min(o,n)}async#l(e){if(this.#i++,this.#i>this.#e.retry.limit)throw e;const n=e instanceof Error?e:new AYt(e);if(n instanceof aRe)return n.customDelay??this.#a();if(!this.#e.retry.methods.includes(this.request.method.toLowerCase()))throw e;if(this.#e.retry.shouldRetry!==void 0){const o=await this.#e.retry.shouldRetry({error:n,retryCount:this.#i});if(o===!1)throw e;if(o===!0)return this.#a()}if(dUo(e)&&!this.#e.retry.retryOnTimeout)throw e;if(gUo(e)){if(!this.#e.retry.statusCodes.includes(e.response.status))throw e;const o=e.response.headers.get("Retry-After")??e.response.headers.get("RateLimit-Reset")??e.response.headers.get("X-RateLimit-Retry-After")??e.response.headers.get("X-RateLimit-Reset")??e.response.headers.get("X-Rate-Limit-Reset");if(o&&this.#e.retry.afterStatusCodes.includes(e.response.status)){let i=Number(o)*1e3;Number.isNaN(i)?i=Date.parse(o)-Date.now():i>=Date.parse("2024-01-01")&&(i-=Date.now());const r=this.#e.retry.maxRetryAfter??i;return i<r?i:r}if(e.response.status===413)throw e}return this.#a()}#g(e){return this.#e.parseJson&&(e.json=async()=>this.#e.parseJson(await e.text())),e}#d(e){e&&e.cancel().catch(()=>{})}#A(e){this.#d(e.body??void 0)}async#m(e){try{return await e()}catch(n){const o=Math.min(await this.#l(n),ARe);if(this.#i<1)throw n;if(await cUo(o,this.#r?{signal:this.#r}:{}),n instanceof aRe&&n.customRequest){const i=this.#e.signal?new globalThis.Request(n.customRequest,{signal:this.#e.signal}):new globalThis.Request(n.customRequest);this.#h(i)}for(const i of this.#e.hooks.beforeRetry){const r=await i({request:this.request,options:this.#u(),error:n,retryCount:this.#i});if(r instanceof globalThis.Request){this.#h(r);break}if(r instanceof globalThis.Response)return r;if(r===gYt)return}return this.#m(e)}}async#_(){this.#n?.signal.aborted&&(this.#n=new globalThis.AbortController,this.#e.signal=this.#r?AbortSignal.any([this.#r,this.#n.signal]):this.#n.signal,this.request=new globalThis.Request(this.request,{signal:this.#e.signal}));for(const n of this.#e.hooks.beforeRequest){const o=await n(this.request,this.#u(),{retryCount:this.#i});if(o instanceof Response)return o;if(o instanceof globalThis.Request){this.#h(o);break}}const e=lUo(this.request,this.#e);return this.#s=this.request,this.request=this.#s.clone(),this.#e.timeout===!1?this.#e.fetch(this.#s,e):AUo(this.#s,e,this.#n,this.#e)}#u(){if(!this.#c){const{hooks:e,...n}=this.#e;this.#c=Object.freeze(n)}return this.#c}#h(e){this.#c=void 0,this.request=this.#p(e)}#p(e,n){return!this.#e.onUploadProgress||!e.body?e:iUo(e,this.#e.onUploadProgress,n??this.#e.body??void 0)}};const uRe=t=>{const e=(n,o)=>fYt.create(n,Kge(t,o));for(const n of uYt)e[n]=(o,i)=>fYt.create(o,Kge(t,i,{method:n}));return e.create=n=>uRe(Kge(n)),e.extend=n=>(typeof n=="function"&&(n=n(t??{})),uRe(Kge(t,n))),e.stop=gYt,e.retry=XYo,e},hUo=uRe();class pUo extends Wb{constructor(e,n,o,i){super(e,n,o),this.name="RegistryHTTPError",this.message=i}}function uq(t){return typeof window<"u"?window[t]:null}function Hw(){const t=uq("TSCIRCUIT_REGISTRY_API_BASE_URL")||void 0||"https://registry-api.tscircuit.com",e=uq("TSCIRCUIT_REGISTRY_TOKEN");return hUo.create({prefixUrl:t,headers:{Authorization:`Bearer ${e}`},timeout:3e4,hooks:{afterResponse:[async(n,o,i)=>{if(i.ok)return i;let r=null;try{r=await i.clone().json()}catch(u){console.error("Failed to parse registry error response",u)}const s=r?.error?.message??r?.error?.error_message??r?.message,a=r?.error?.error_code??r?.error_code,A=new URL(i.url),l=[`Registry request failed for ${`${A.pathname}${A.search}`} (${i.status})`];throw s&&l.push(`Server message: ${s}`),a&&l.push(`Error code: ${a}`),new pUo(i,n,o,l.join(" | "))}]}})}function zge(){return!!uq("TSCIRCUIT_REGISTRY_TOKEN")}const gq={get:(t,e)=>Hw().get(t,e),post:(t,e)=>Hw().post(t,e),put:(t,e)=>Hw().put(t,e),delete:(t,e)=>Hw().delete(t,e),patch:(t,e)=>Hw().patch(t,e)},mUo="phc_htd8AQjSfVEsFCLQMAiUooG4Q0DKBCjqYuQglc9V3Wo",_Uo="https://postpig.tscircuit.com",IYt="runframe:anonymous-id",gRe=()=>typeof window<"u",CYt=t=>t.includes("localhost")||t.includes("127.0.0.1"),fUo=t=>{try{return new URL(t).hostname}catch{return null}},IUo=()=>{if(!gRe())return null;let t=null;return document.referrer&&(t=fUo(document.referrer)),t??window.location.hostname},CUo=()=>typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,yUo=()=>{if(!gRe())return null;try{const t=window.localStorage.getItem(IYt);if(t)return t;const e=CUo();return window.localStorage.setItem(IYt,e),e}catch{return null}},xUo=()=>uq("TSCIRCUIT_USE_RUNFRAME_FOR_CLI")===!0,yYt=()=>!gRe()||CYt(window.location.hostname)&&!xUo()?!1:(dG.__loaded||dG.init(mUo,{api_host:_Uo,person_profiles:"always"}),!0),EUo=()=>{if(!yYt())return null;const t=IUo(),e=t!=null&&!CYt(t);let n=null;e||(n=yUo());let o,i;return e?(o=`domain:${t}`,i="domain"):(o=void 0,n&&(o=`anonymous:${n}`),i="anonymous_id"),{embedDomain:t,anonymousId:n,distinctId:o,identityType:i}},BUo=(t,{source:e,...n})=>{const o=EUo();if(!o)return;const{embedDomain:i,anonymousId:r,distinctId:s,identityType:a}=o;if(s){const A={};a==="domain"&&i&&(A.embed_domain=i),a==="anonymous_id"&&r&&(A.runframe_anonymous_id=r),dG.identify(s,A)}dG.capture(t,{...n,source:e,embed_domain:i,runframe_anonymous_id:r,identity_type:a})},bUo=t=>{BUo("runframe_activity",t)};yYt();function SUo(t){const e=String.fromCodePoint(...t);return btoa(e)}function QUo(t,e){const n=JSON.stringify(t),o=RQe(TQe(n));return`https://tscircuit.com/editor?#data:application/gzip;base64,${SUo(o)}`}function Oi(...t){return BHo(NB(t))}const xYt=t=>t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()),dRe=JLo,Jge=ee.forwardRef(({className:t,...e},n)=>K.jsx(tLt,{ref:n,className:Oi("rf-inline-flex rf-h-9 rf-items-center rf-justify-center rf-rounded-lg rf-bg-zinc-100 rf-p-1 rf-text-zinc-500 dark:rf-bg-zinc-800 dark:rf-text-zinc-400",t),...e}));Jge.displayName=tLt.displayName;const p6=ee.forwardRef(({className:t,...e},n)=>K.jsx(nLt,{ref:n,className:Oi("rf-inline-flex rf-items-center rf-justify-center rf-whitespace-nowrap rf-rounded-md rf-px-3 rf-py-1 rf-text-sm rf-font-medium rf-ring-offset-white rf-transition-all focus-visible:rf-outline-none focus-visible:rf-ring-2 focus-visible:rf-ring-zinc-950 focus-visible:rf-ring-offset-2 disabled:rf-pointer-events-none disabled:rf-opacity-50 data-[state=active]:rf-bg-white data-[state=active]:rf-text-zinc-950 data-[state=active]:rf-shadow dark:rf-ring-offset-zinc-950 dark:focus-visible:rf-ring-zinc-300 dark:data-[state=active]:rf-bg-zinc-950 dark:data-[state=active]:rf-text-zinc-50",t),...e}));p6.displayName=nLt.displayName;const cI=ee.forwardRef(({className:t,...e},n)=>K.jsx(oLt,{ref:n,className:Oi("rf-h-full rf-mt-2 rf-ring-offset-white focus-visible:rf-outline-none focus-visible:rf-ring-2 focus-visible:rf-ring-zinc-950 focus-visible:rf-ring-offset-2 dark:rf-ring-offset-zinc-950 dark:focus-visible:rf-ring-zinc-300",t),...e}));cI.displayName=oLt.displayName;const EYt="T1RUTwAJAIAAAwAQQ0ZGIFhQSpcAAAcwAABJ3U9TLzJqmmVhAAABAAAAAGBjbWFwFN0WswAABEwAAALEaGVhZC1P1HwAAACcAAAANmhoZWEDrgI1AAAA1AAAACRobXR44xAAAAAAURAAAAFQbWF4cABUUAAAAAD4AAAABm5hbWUZQ94BAAABYAAAAutwb3N0AAMAAAAABxAAAAAgAAEAAAABAADb+Z65Xw889QADA+gAAAAA5e9IsgAAAADl70iy/9P/PwKHAvkAAAADAAIAAAAAAAAAAQAAA6z/LAAAArQAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAFQAAFAAAFQAAAADArQB9AAFAAACigK7AAAAjAKKArsAAAHfADEBAgAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAABYWFhYAEAAIQB6A6z/LAAAAvkAwQAAAAEAAAAAAiwC1wAAAAAAAAAAACIBngABAAAAAAAAAAEAWQABAAAAAAABABEAAAABAAAAAAACAAcAMwABAAAAAAADABsA/AABAAAAAAAEABkASAABAAAAAAAFAAsA2wABAAAAAAAGABgAkwABAAAAAAAHAAEAWQABAAAAAAAIAAEAWQABAAAAAAAJAAEAWQABAAAAAAAKAAEAWQABAAAAAAALAAEAWQABAAAAAAAMAAEAWQABAAAAAAANAAEAWQABAAAAAAAOAAEAWQABAAAAAAAQABEAAAABAAAAAAARAAcAMwADAAEECQAAAAIAgwADAAEECQABACIAEQADAAEECQACAA4AOgADAAEECQADADYBFwADAAEECQAEADIAYQADAAEECQAFABYA5gADAAEECQAGADAAqwADAAEECQAHAAIAgwADAAEECQAIAAIAgwADAAEECQAJAAIAgwADAAEECQAKAAIAgwADAAEECQALAAIAgwADAAEECQAMAAIAgwADAAEECQANAAIAgwADAAEECQAOAAIAgwADAAEECQAQACIAEQADAAEECQARAA4AOlRzY2lyY3VpdEFscGhhYmV0AFQAcwBjAGkAcgBjAHUAaQB0AEEAbABwAGgAYQBiAGUAdFJlZ3VsYXIAUgBlAGcAdQBsAGEAclRzY2lyY3VpdEFscGhhYmV0IFJlZ3VsYXIAVABzAGMAaQByAGMAdQBpAHQAQQBsAHAAaABhAGIAZQB0ACAAUgBlAGcAdQBsAGEAclRzY2lyY3VpdEFscGhhYmV0UmVndWxhcgBUAHMAYwBpAHIAYwB1AGkAdABBAGwAcABoAGEAYgBlAHQAUgBlAGcAdQBsAGEAclZlcnNpb24gMC4xAFYAZQByAHMAaQBvAG4AIAAwAC4AMSA6VHNjaXJjdWl0QWxwaGFiZXQgUmVndWxhcgAgADoAVABzAGMAaQByAGMAdQBpAHQAQQBsAHAAaABhAGIAZQB0ACAAUgBlAGcAdQBsAGEAcgAAAAABAAMAAQAAAAwABAK4AAAAqgCAAAYAKgAAACEAIgAjACQAJwAoACkAKgArACwALQAuAC8AMAAxADIAMwA0ADUANgA3ADgAOQA8AD0APgBBAEIAQwBEAEUARgBHAEgASQBKAEsATABNAE4ATwBQAFEAUgBTAFQAVQBWAFcAWABZAFoAWwBcAF0AXgBfAGEAYgBjAGQAZQBmAGcAaABpAGoAawBsAG0AbgBvAHAAcQByAHMAdAB1AHYAdwB4AHkAev//AAAAAAAhACIAIwAkACcAKAApACoAKwAsAC0ALgAvADAAMQAyADMANAA1ADYANwA4ADkAPAA9AD4AQQBCAEMARABFAEYARwBIAEkASgBLAEwATQBOAE8AUABRAFIAUwBUAFUAVgBXAFgAWQBaAFsAXABdAF4AXwBhAGIAYwBkAGUAZgBnAGgAaQBqAGsAbABtAG4AbwBwAHEAcgBzAHQAdQB2AHcAeAB5AHr//wAA/+D/4P/g/+D/3v/e/97/3v/e/97/3v/e/97/3v/e/97/3v/e/97/3v/e/97/3v/c/9z/3P/a/9r/2v/a/9r/2v/a/9r/2v/a/9r/2v/a/9r/2v/a/9r/2v/a/9r/2v/a/9r/2v/a/9r/2v/a/9r/2v/a/9n/2f/Z/9n/2f/Z/9n/2f/Z/9n/2f/Z/9n/2f/Z/9n/2f/Z/9n/2f/Z/9n/2f/Z/9n/2QABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEABAEAAQEBGVRzY2lyY3VpdEFscGhhYmV0UmVndWxhcgABAQEo+BsA+BwC+B0D+B4Ei/tV+kD5SAUdAAABOQ8dAAAB4BGLHQAASd0SAFcBAQwlNj0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkFZlcnNpb24gMC4xVHNjaXJjdWl0QWxwaGFiZXQgUmVndWxhclRzY2lyY3VpdEFscGhhYmV0UmVndWxhciEiIyQnKCkqKywtLi8wMTIzNDU2Nzg5PD0+QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2FiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6AAAAAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AbgBuQG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHGAccByAHJAcoBywHMAc0BzgHPAdAB0QHSAdMB1AHVAdYB1wHYAdkB2gHbAdwB3QBUAgABAAQAeADuAgwFUgWPBmUHOwffCGMIzwkMCUgJhQq1CzwMhg5ADwwQUBHfEt8U3hYZFqIXFxeiGEIZtBsIHCccsh0sHpIfGh9XIC8gtiEFIjwjJSRTJWUmviftKXQp2CqzK0gsfS0ILW8uPy6iLuAvQy+2L/IxEDItM0A0XjWWNlQ39zjFOTk59zp9Oro76Dy1Pd8+/EAaQJVCDELOQ49EGEVZReRGgUdR+UgO+Uj37vlBFYv8VgWIewWBfQV8ggV6iAV6jgV8lAWBmQWImwWL+FYFjpsFlZkFmpQFnI8FnIcFmoIFlX0FL/z3Fe+LBZyIBZmCBZV9BY97BYd7BYF9BX2CBXqIBSeLBXqOBX2UBYGZBYebBY+bBZWZBZmUBQ75SPdm+UEVi/uBBYh7BYF9BXyCBXqIBXqOBXyUBYGZBYibBYv3gQWOmwWVmQWalAWcjwWchwWaggWVfQX3p3sVi/uBBYh7BYF9BXyCBXqIBXqOBXyUBYGZBYibBYv3gQWOmwWVmQWalAWcjwWchwWaggWVfQUO+Uj3XvcoFYAiBYZ7BYB/BXyDBXmJBXqQBX6VBYOaBYmbBZPgBSR/BXqMBXuSBX+YBYaaBYycBZOaBZiVBZyRBfcPmgWe91QFKH8FeYwFfJIFf5gFhZoFjZwFkpkFmZYFm5EF9wyZBZ33RgWQmgWWmAWakwWdjQWchgWYgQWUfAWMewV7+zIF9zifBZr3JgWQmgWWmAWbkwWcjQWchgWZgQWTfAWNewV++xMF8JcFnIoFm4QFl34FkHwFinoFg30FfoAFeoUF+w19BXj7VQXslwWdigWahAWXfwWRewWKegWDfQV+gAV6hgX7CnwFfvscBYZ7BX9/BXyDBXqJBXqQBX2VBYOaBYmbBZf3CQX7MM0V9zifBZ/3VAX7OHcFDvlI9/T5XhWL/awFiHoFgX4FfIEFeogFeo4FfJUFgpgFh5wFi/msBY+bBZSZBZqUBZyOBZyIBZqCBZV9BfcB+2YVNd0FgpkFiJsFjpsFlZkFmpQFnI4FnIcFmoIF4DkFlX0FjnoFh3sFgX4FfYIFeYgFeo4FQ9sV+z+bBXuQBX2VBYOaBYmbBZCbBZeYBZqTBZ2MBfc+ewWchgWZgAWTfQWMegWGfAWAfgV8gwX7LqUVKjgFe4MFeogFeo8FfZUFgpkFiJwFkJsFlZgF7d4FmpMFnI0FnIcFmYEFlH0FjnsFh3sFLD4VZvsHBYN8BX2BBXqGBXqMBXuTBYCYBYabBY2bBa/3CAWTmQWZlgWckAWciQWbgwWWfwWQewVkIRWkSQWNegWHewWAfgV8gwV6iQV6jwV9lQWCmQVyzQWJmwWPmwWWmQWakwWcjQWchwWZgQWdTxXUWgWXfwWRewWKewWEfAV+fwV7hgV5iwV7kgVCvQV/lwWFmgWLnAWTmgWYlgWbkQWdigXTWhX3fFkFm4QFl38FkXwFi3oFhHwFfoAFe4UFeYwF+3y8BXuSBX+XBYWaBYycBZKaBZeWBZyRBfedUhXVWgWWfwWSewWKewWEfAV+fwV6hgV6iwV7kgVCvAV/mAWFmgWLnAWTmgWXlgWckQWcigX2PBWjOAWMewWGewV/fgV8hAV5igV6kAV+lgWDmQVz3gWKmwWQmwWXmAWakgWdjAWbhgWZgAWp+xAVW/sHBYF9BX2BBXqIBXmOBX2UBYGYBYebBY6cBbz3BwWUmQWalQWcjgWciAWaggWVfQWPewU/+y8V+w5aBXqHBXmOBX2UBYGZBYebBY6bBZWZBZmUBfcOvQWcjgWciAWaggWVfgWPewWIewWBfQX7M00V+zObBXuQBX2WBYOZBYqcBZCaBZaYBZuTBZyMBfczewWchgWYgAWTfAWNewWFewWAfwV7gwX7VqAVNb0Ff5YFg5oFi5sFkZsFl5cFm5IFnIsFnIYF4FkFmIAFknwFjHoFhXwFf38Fe4QFeYoF+wzZFWbuBYmbBY+bBZaYBZqUBZyNBZyHBZmBBZR9BbAnBY17BYd7BYB+BXyDBXmIBXqQBX2VBQ75SPfu+UEVi/uBBYh7BYF9BXyCBXqIBXqOBXyUBYGZBYibBYv3gQWOmwWVmQWalAWcjwWchwWaggWVfQUO+Uj4Ko0VsmUFlX0FjnsFh3sFgX0FfYIFeYgFeo8FfZQFYrMFio0FiYwFY7sFiowFiowFYsMFiowFiowFY8oFio4FiY0FbcoFio4FiY4Fd8oFi44Fio0FgcMFi5IFi5IFlcMFjI0Fi44Fn8oFjY4FjI4FqcoFjY0FjI4Fs8oFjIwFjIwFtMMFjIwFjIwFs7sFjYwFjI0FtLMFmZQFnI8FnYgFmYIFlX0Fj3sFiHsFgX0FZGUFZV4FZFUFZE8Fb1AFeFEFg10Fk10FnlEFp1AFsk8FslUFDvlI95tWFYqJBWJjBX2CBXqHBXmOBX2UBYGZBYebBY6bBZWZBbKxBbG4BbLBBbLHBafGBZ7FBZO5BYO5BXjFBW/GBWTHBWTBBWW4BWSxBYGZBYibBY+bBZWZBZqUBZyOBZyHBZmCBbRjBYyJBY2KBbRbBYuKBY2KBbNTBYyKBYyKBbRMBYuIBY2JBapMBYuIBY2IBZ9MBYuIBYyJBZVTBYuEBYuEBYFTBYqJBYuIBXdMBYmIBYuIBWxMBYmJBYuIBWJMBYqKBYqKBWNTBYmKBYuKBWJbBQ75SPeU+FUV+zRWBXqIBXqPBX2VBYKZBYicBY+bBZaYBZqTBfc5wgUh9yQFhJoFi5sFkZsFmJYFm5IFnIsFm4UFmIAF8fsfBfH3HwWYlgWbkQWciwWchAWXgAWRewWLewWEfAUh+yQF9zlUBZqDBZZ+BY97BYh6BYJ9BX2BBXqHBXqOBfs0wAWL+yoFiHsFgX0FfIIFeogFeo4FfJQFgZkFiJsFDvlI95T39hWL90sFjpwFlZgFmpUFnI4FnIgFmoEFlX4FjnoFi/tLBfdpiwWciAWaggWVfQWOewWIegWBfgV8ggV6hwX7aYsFi/tLBYh7BYF9BXyCBXqIBXqOBXyUBYGZBYibBYv3SwX7aYsFeo8FfJQFgZgFiJwFjpsFlZkFmpQFnI4FDvlI96puFcJVBZV9BY56BYd7BYF+BXyCBXqIBXqOBX2VBTXfBYeRBYaRBYuMBYqMBYqSBYmSBYyMBYqMBY2SBYyTBYyLBYuMBZCRBY+RBfc/9zwFmpUFnI4FnIgFmoMFlX0Fj3sFiHsFgX0FDvlI90L35RX3kosFnIgFmoIFlX0FjnsFiHsFgX0FfIIFeogF+5KLBXqOBXyUBYGZBYibBY6bBZWZBZqUBQ75SPf/7RX7D4sFeY4FfZQFgZkFiJsFjpsFlZkFmZQFnY4F9w+LBZyIBZmCBZV9BY97BYd7BYF9BX2CBQ75SKOAFfhx+WMFl5cFm5EFnYwFm4UFmIAFknwFjHoFhXwF/HH9YwV/fwV7hQV5igV7kQV+lgWEmgWKnAUO+Uj4CfkPFUOeBUN4BUZQBWMvBYH7JQWj+wwFxi0F2F0FyYsF2LkFxukFo/cMBYH3JQVj5wVq9x4VjYoFkYgFkYgFjIoFjYoF4EEFi4sFjIoFj4UFkIUFi4oFjIoFuSEFjIQFjYUFlvsyBYqGBYuGBXH7GQWIhQWJhAVH+wIFiYoFiokFhocFh4YFiYoFiooFKVEFh4kFiIkFhooFh4oFh4sFh4oFM4sFh4wFh4sFh4wFhowFiI0Fh40FKcUFiowFiYwFh5AFho8Fio0FiowFRvcCBYmSBYiRBXH3GQWLkAWKkAWW9zIFjZEFjJIFufUFjIwFi4wFkJEFj5EFjIwFjIsF39UFjYwFjIwFkY4FkY4FjYwFjYsF6aMFjowFjowFkYoFkYwFjooFjooF6XMFDvlI9/v5ZRWQjgWNjAWNjAWSiwWSjQWMigWNiwWSigWSiQWMigWNiwWRhwWQhwWMigWNigWOhQWPhQWMigWLiQWMhQWNhAWL/REFh3sFgX0FfYIFeogFeY4FfZQFgZkFiJsFi/i2BTRFBXuDBXqJBXqPBX2WBYOZBYmbBY+bBZaYBfc19xUFDvlI90rmFffoiwWdiAWZggWVfQWOewWIewWBfQV9ggV5iAX8TosFg4wFg4wFiowFiosFhY8FhI8Fi4sFiowFhpEFh5EFi4wFiowFipIFiZIFi4wFi4wFjJIFjJIFjIwFi4wFj5EFj5EF9zn3PgX3L/dKBcTlBZezBYueBYOqBXeiBV6dBUaQBWaGBVBzBWttBX9mBYN9BX6ABXqGBXmNBXyTBYCYBYaaBYycBZu6BYuMBYyNBY+QBY6RBYyMBYyNBbi2BYuLBYuLBZOQBZKQBYuLBYuLBdWoBZCNBZGMBbqSBZCKBZCMBd2FBZKJBZKKBclxBYyKBY2LBZCHBZGHBYyKBY2JBaxlBYyKBYuKBY+FBY6EBYuKBYyKBZdeBYuFBYyGBYptBYqGBYuGBX1ZBYiFBYmGBUwpBYmJBYqJBfsy+04FiooFiooFDvlI9wqUFYeMBVObBXySBX+YBYabBY2bBZOaBZmVBZuQBZ2KBcB8BdeABeiJBb2WBdGxBbW2BZy5BYOvBWWzBUStBTSiBT2UBYiMBYiLBYWOBYaMBYmNBYiNBYePBYeOBYmOBYmNBYmQBYmQBYuOBYqOBYuQBYuRBYyNBYuOBY2QBY2QBY2NBY2OBY+PBY+PBY6MBY2NBZCNBZGNBY6LBY6MBduVBeKdBdGpBauoBZGqBXWtBV2uBUagBTyPBUp2BVZxBWhxBXyEBXmKBXuQBX2WBYOZBYqcBZCaBZeYBbCnBY+MBY6OBceoBY6MBY6NBdikBZOMBZSMBemGBZCKBZGKBd1yBZKIBZOHBcVeBZCGBZCGBa9UBY2EBY6FBYuKBYyKBYqEBYuDBYBQBYmHBYqHBYmIBYmHBYiIBYiHBVxfBYWGBYSHBUduBdFqBZGGBZKHBcBUBYyIBY6JBY2GBY6HBYuIBY2HBZZQBYuJBYyIBYqFBYuGBYqIBYuJBXNKBYuLBYuLBYeEBYaEBYuLBYuLBVZUBYWHBYaHBTlfBYWJBYWIBU19BYWLBYWKBSeNBYiMBYiLBTmWBQ75SPgF98IVi+oFj5sFlJgFmpUFnI4FnIgFmoEFlX4FjnsFiywF6YsFnIcFmoIFlX0FjnsFiHsFgX0FfIIFeogFLYsFi/s9BYh7BYF9BXyCBXqIBXqOBXyUBYKZBYebBYv3PQX71IsFhIwFhYwFiYwFiYsFhY8FhY0Fio0FiYwFh5AFh5AFi40FiY0FipEFiZEFi40Fi40FjJEFjJEFjI0Fi40Fj5EFjpAF+Ab4PgWYlgWcjwWcigWbgwWWfgWQfAWKegWCfQX7yfv5BQ75SKn5QRWOmwWVmQWalAWcjwX4WIsFnIcFmoIFlX0FjnsFiHsFgX0FfIIFeogF/CuLBYv7dwX3HakFk4sFk4wF9x57BZOIBZOJBcJuBZGGBZGHBbFiBYyJBYyKBY6FBY+FBYuKBYyJBaj7BAWLigWLigWLhAWMhAWKigWLiQV9UQWLiwWLigWHhAWIhAWLiwWKigVnXgWFhQWFhgVFYQWFiQWFiAU5dQWGigWGigU+hwWFjAWGiwVKlwWGjQWGjAVWogWGjgWFjwVUugWAmAWHmwWOmwWUmQWZlQWcjwWciQWaggW9YQW0eQXCgQXNjgXSngXFrgWlqwWUswVz5wVxpwVjoAX7DZkF+01iBYaLBYaKBYeMBYiKBYaNBYaMBYiNBYeMBYePBYeNBYmOBYiNBYmQBYiPBYuOBYmPBYuPBYqQBQ75SPch96QVi4sFi4sFbW4FioMFnlkFm24FtWEFtHIFzoEF2o8FxaMFsqoFnrMFjaoFf7MFeKwFcqQFZ5sFUJcFU44FU4MFU28F+yxcFYqPBYyRBYy5BYuLBYuLBY7cBY2RBYyRBafaBYyNBYuNBbTfBZCSBZCRBcC7BY6NBY2NBdC4BZGOBZCOBdykBYyLBYuLBeKlBZ2NBZuGBZmBBZN8BY17BYZ7BYB+BXyDBTRyBUFzBU9kBV5jBWdABXJEBYp7BZGOBZCPBdGtBZKNBZKOBc6UBZCLBY+LBcuJBY+KBY+LBc58BZCKBZCJBbt2BZKGBZKHBa5oBY6GBY+GBaNhBYyHBY2HBZpZBYyEBYyFBYlbBYuLBYuLBYmDBYmDBYuLBYuLBW9UBYuKBYqKBYaGBYeFBYqKBYqLBVhiBYaIBYaIBUNtBYOJBYOJBS+GBYeMBYaLBTmXBYqLBYqLBYSOBYOOBYuLBYqLBVasBYiPBYaNBVq8BYeQBYeQBXaxBYqOBYqOBXXHBYqSBYmTBQ75SPfP90gVg/saBYd7BYF+BXyCBXmJBXqPBX2VBYKZBYmbBZL3HAWMjQWLjQWc9wcFi4wFjI0Fms0FjI0Fi4wFnsYFjIwFi40FoL4FjIwFi40ForcFjIwFi40Fo7EFjIwFjI0FoqoFjI0FjIwFoqYFjYwF+96LBXmOBX2UBYGZBYibBY6bBZWZBZmUBZ2PBfhfiwWQigWQigWOigWPigWPiAWQiQWOiQWNiQWOhwWPhwWMiAWNiAWMhgWNhgWLiAWMiAWJhgWLhgWKiAWKiAWIhwWJhgWIiQWJiAWHiAWHiAVqeQV9gQVkaAV3dAV2bgV1aAV2YgV4WwV5UwV8TAUO+Uj3pvf2FUR0BUpaBXBZBYleBaZdBcVnBdlzBciJBeCmBb6wBaLEBYLEBWK1BTi2BVKfBdH3sxU4kQVLgAVXcwVrXQWVaQW4ZQW/bAXDeAWwlgXetQWdpgWMwwV1rwVr9wEVi4sFk4gFk4kFi4sFjIsF0GgFjokFj4kFjocFj4gFjYgFjYgFrVIFjIkFjYgFjIYFjYYFiogFjIgFiTwFi4gFi4kFiYUFioYFiYkFiogFbVwFiYkFiYgFh4gFh4cFiIoFiYkFUm4F0mYFkIcFkYcFw1IFjYcFj4gFjIcFjYgFjIYFjIcFmDoFi4kFi4kFioUFi4UFiokFiokFbDwFiYcFiogFh4cFiYgFiIgFiIkFR1sFhYgFhYcFJ2sFg4oFg4oFP40FhY0FhIsFMqcFho4FhY0FQ7gFio0FiYwFho8Fh5AFio0FiYwFZc0Fio4Fio4FipAFiZAFjI4Fio4Fjs0Fi4wFi4sFjZMFjZIFi4wFi4sFr80Fi4wFjIwFkJAFkJEFi4wFjIsF2sYFkY4Fko8FmI8FaZ8FiI4Fh40FUrwFiY0FiI4FiY8FiI8Fio4FiY4FeMsFi40Fi4wFipIFi5IFi4wFi4wFjpIFjZIFjIsFjI0Fu9IFjo4FjY4Fj44Fj44Fjo0Fjo0F0KsFkYwFkY0F15gFkIsFkYwF7YQFDvlI+Fr4mBWVnQV8xwVwqwVfoAVIkwVHgwVTdAVnagV+XwWYYAWvaQXDdAXMhAXMmgW8qgVf/BoVi4oFZ0IFgX4FfIIFeYgFeo8FfZUFgpkFiJsFj5sFr9QFtuoFwPcXBYuLBYuMBZKcBT55BYOKBYKLBTuUBYWNBYWMBUWoBYSPBYSQBVm6BYqNBYmMBYiQBYeQBYuOBYqNBXfNBYqOBYqOBYyQBYqQBYyOBYyPBZ/NBYyNBYuNBY+QBY6QBY2NBYyNBb26BZKPBZKQBdGnBZGMBZGNBduVBZGKBZGMBduBBZKJBZKJBcdvBYyKBYyLBZGGBZGHBYuKBYyKBbNcBYyKBYyKBY6FBY6FBYuJBYyKBZ83BYuFBYyEBYqJBYuJBYmFBYmGBYqHBUH7SAVW+xgFi4oFiooFXysFDvlI9y/3yxX4OvtDBZqBBZR9BY57BYd7BYF9BXyCBXqJBXqOBfyY92oFhI8FhY8FiowFiowFh5EFh5EFi4wFiosFipMFiZIFi4wFi4wFjZIFjJIFjIwFi4wFj5EFj5EFjIwFjIsFkY8Fko8F+Jj3agWcjwWciAWaggWVfgWPewWIegWCfQV8ggUO+Ui2+GkV+JiLBZyIBZqCBZV9BY57BYh7BYF9BXyCBXqIBfyYiwV6jgV8lAWBmQWImwWOmwWVmQWalAWc+4gV+JiLBZyIBZqCBZV9BY57BYh7BYF9BXyCBXqIBfyYiwV6jgV8lAWBmQWImwWOmwWVmQWalAUO+Uj44/fpFYyKBY+FBY+FBYuKBYyKBYyEBY2EBYuKBYuKBYmEBYqDBYqLBYuKBYeFBYeFBYqKBYqKBYWHBYSHBfyY+2oFeogFeo0FfJQFgZkFh5sFjpsFlJkFmpUF+Dv3QwX8O/dDBXyUBYKZBYicBY+bBZWYBZqUBZyOBZyHBfiY+2oFkocFkYcFDvlI+Ev3kxWGigX7q4sFi4sFLPtyBYF9BX2CBXqIBXmOBX2UBYGYBYecBY6bBfek+REFkJIFkJIFi4sFi4sFko8FkpAFi4sFjIsFk40Fk40FjIsFi4sFk4kFlIoFi4sFi4sFkoYFkocFjIsFi4sFkIQFj4QF97r9EQWPewWIegWBfgV9gQV6iAV5jgV9lAWBmAX7IvfIFfsB94AFJvuABQ75SPe++GUV2bYFlMsFTL8F+weeBSmGBYv7VgX32vxEFYSJBYmLBYmLBfv7hwWKiwWLiwWDjAWCjQWLiwWLiwWEjwWEkAWKiwWLiwWGkgWHkQWLjAWKiwWKkwWJkgWLjAWLiwWL+QoFjJIFjZIFi4wFi4wFkJEFjpEFjIwFjIwFkY8FkY8FjYsFjIwFkowFk40F9yWTBZCKBZCLBfcZdQWOigWPigWQiQWQiQWNiQWOiQXlQQWNiAWPiQWNhwWOhwWMhwWNiAWLhgWMhwWLhwWLhwV9+wAFiokFi4gFiIYFiYYFiYkFiogFh4cFh4cFiIoFiYkFSGYF9wJmBY6JBY+KBY+IBY+JBY2IBY6IBdE3BY6GBY6FBYyJBYuKBYyEBYyEBYX7AAWLiQWLiQWJhQWJhQWKiQWKiQVsWwWIiQWKiAWHiAWHhwWIigWIiQU+ZAWJigWJigVu3BXEqAWeqAWP3QVYyQX7JLsF+1CWBYv7nAUO+Uj4ZPclFaDbBZOZBZiXBZuQBZ2KBZuEBZd/BZF7BYp7BXIwBYqIBYqHBYiHBYmHBYiIBYmIBUNLBYiJBYmJBYaJBYaIBYiLBYiJBSl1BYuLBYuLBYOLBYKLBYuLBYuLBfsEnAWJiwWKjAWEjQWEjgWKjAWKiwVRsQWFkQWFkQVU3QWLiwWLiwWIkwWIkgWLiwWLiwVm918Fi5MFi5MFuvdeBYyMBYuNBY+RBY2RBY2MBYyNBc7XBYyMBYuLBZGQBZKQBYuLBYuLBdGsBZKNBZKOBdqVBYyLBYyLBZOKBZKLBYyKBY2LBfVqBYyLBYyLBZKHBZGHBYyLBYyKBcNZBYyLBYuKBZCFBY+FBYyKBYuLBapEBY57BYh7BYF9BXyCBXqIBXqOBXyVBYGYBXDJBWKwBTSlBU6EBVVxBVRNBWD7TAWt+04FuUgFtG8F6H0F2JwFDvlI93uVFYaKBfs1iAWLiwWKiwWDjAWDjQWKiwWLiwWEjwWEjwWLjAWKiwWHkgWGkQWLjAWLiwWJkwWJkgWMjAWKiwWT+QQFjJAFi5EFjY0Fi48Fj48FjY8FjY4FjY0FkI4Fj44Fjo0FjowFkIwFkY0F7pgFj4sFjowF14kFkYoFkIsF9xBrBYuLBYuLBZOHBZKIBYyLBYuKBeZIBYyKBYuLBZCFBZGFBYuLBYuKBb8wBY2FBY6GBaAsBYuHBYyHBY1EBYqHBYuIBYJOBYmHBYqHBXhXBYeFBYmGBUw8BYWGBYWGBTdZBYWJBYWIBfsdaAV53hX3EasF0rUFwM4Fm7UFlMAFicsFeOAFXtoFPsQF+wGnBUiMBVGDBYX8tAUO+Uj3EeUV+CGLBZyIBZqCBZV9BY57BYh7BYF9BXyCBXqIBfxOiwV6jgV8lAWCmQWHmwWL99MFi/fSBY+bBZSZBZqUBZyPBfhOiwWchwWaggWVfQWOewWIewWBfQV8ggV6iAX8IYsFi/t+BfeciwWdiAWZggWVfQWOewWIegWBfgV9ggV5hwX7nIsFDvlI9xf32hWL+6oFiHsFgX0FfYIFeYgFeo4FfZQFgZkFh5sFi/kRBY+bBZWZBZmUBZyPBZ2HBYyKBfgviwWciAWZggWVfQWPewWHewWBfQV9ggV6iAX8FYsFi/t4BffQiwWdiAWZggWVfQWOewWIewWBfQV9ggV5hwUO+Uj4fve0Ffs1iwV6jwV9lAWBmQWImwWOmwWVmQWZlAWdjgX3bIsFj4oFkIsFj4kFj4oFj4kFj4kFjogFj4kFjYgFjocFjYgFjYcFjIcFjYcFi4cFjIcFiocFi4cFXvtaBYqJBYuIBYiGBYiGBYmJBYqJBUtGBYmKBYqJBYWIBYaHBYmKBYmKBTpwBYqLBYuKBYOKBYOKBYqLBYqLBTWSBYSNBYSNBTmuBYWOBYaOBUfCBYaQBYaQBV/QBYuMBYqMBYmRBYiSBYuMBYuMBXf3UgWLkQWLkgWx90IFjIwFi40FjpEFjpEFjIwFjI0FzdsFjIwFi4wFkZAFkY8FjIwFjIsF37QFi4sFi4sFk40Fk44Fi4sFi4sF9xeVBZKKBZGLBfcQcQWbhQWXfwWRfAWLegWEfAV+gAV7hQV5iwX7CKMF+weCBUhrBVZJBWj7MwWe+0IFrlUFxFwF0W4Fz4UFx6AFvL8FDvlI+H74OhWL95sFj5sFlJkFmpQFnI8FnIcFmoIFlX0FjnsFi/0RBYh7BYF9BXyCBXqIBXqOBXyUBYKZBYebBYv3tgX8DosFi/u2BYd7BYJ9BXyCBXqIBXqOBXyUBYGZBYibBYv34AWL98UFjpsFlZkFmpQFnI8FnIcFmoIFlH0Fj3sFi/ubBQ75SPfu+UEVi/0RBYh7BYF9BXyCBXqIBXqOBXyUBYGZBYibBYv5EQWOmwWVmQWalAWcjwWchwWaggWVfQUO+Ui/9z4Vio4Fia8FjpsFlJkFmZUFnY4FnIkFmoIFlX4Fj3sFjGsFkXIFlXYFmXkFnX0FunoFzoQFu5EFwp8FoJkFnJ0Fl6EFk70FivhxBY6bBZWZBZqUBZyPBZyHBZqCBZR+BY96BYz8dAWKiAWLiAWCTgWJhQWJhAV5awWHhgWIhwVycQWHiAWIiAVtdwWGiQWGiAVKcwWGigWFigVRhAWGiwWGiwU8kwWFjAWFjAVRoQWFjwWFjQVvoQWHjwWHjgV2pQWJkAWIjwV+qAWKkAWJjwWEqwUO+Uj3Uff3FfsBOQWL+3UFiHsFgX0FfYIFeYgFeo4FfZQFgZkFh5sFi/kRBY+bBZWZBZmUBZyPBZ2HBZmCBZV9BY57BYv7xAX4Hve7BZuSBZyNBZyGBZiABZR8BYx7BYZ7BX9/Bfui+14F9+b70AWVfQWPewWHewWCfQV8ggV6iAV6jgV8lAUO+Uj3DOUV+CuLBZyIBZmCBZV9BY97BYd7BYF9BX2CBXqIBfxYiwV6jgV9lAWBmQWHmwWL+REFj5sFlZkFmZQFnI8FnYcFmYIFlX0FjnsFDvlI+KH5WxWOjwWNjQWNjQWRjQWPjgWOjAWOjAWRjAWRjAWOigWOiwWQiQWRigWNigWOigWQhwWPiAWNiQWNiQWOhgWOhgWMiQWMiAWLhgWNhQWL/REFh3sFgX0FfYIFeogFeY4FfZQFgZkFiJsFi/h1BftD+6wFiYkFiokFhocFh4cFiYkFiYoFhYkFhYgFiYsFiIoFhYwFhYoFiIwFiYsFhY4FhY0FiYwFiY0Fh48Fho8Fio0FiY0F+0P3rAWL/HUFiHsFgX0FfYIFeYgFeo4FfZQFgZkFh5sFi/kRBY2RBYuQBYyOBYyNBY6QBY6QBY2NBY2NBY+OBZCPBY6MBY2MBZGMBZCNBY6LBY6MBZGKBZGKBY6KBY6KBY+IBZGJBY2JBY2JBY6HBY+HBfdw+/UF93D39QUO+Uj4e/dPFYT4hgWOmwWVmQWZlAWcjwWdiAWZggWVfQWPewWU/REFioYFi4cFiocFiocFiYgFiYcFiIgFiIcFiIkFiIgFh4kFh4kFh4oFh4oFhosFh4oFhosFh4sFh40Fh4wFh40Fh4wFiI4Fh44FiI4FiI4F/BT4oQWL/IkFh3sFgn0FfIIFeogFeo4FfJQFgZkFiJsFi/kRBYyPBYuPBYyPBYyPBY6PBYyOBY6OBY6PBY6NBY6OBZCNBY+NBY+MBY6NBZCLBZCMBY+KBY+LBY+JBZCKBY+JBY6KBY+IBY+IBY2IBY6IBQ75SPgblBWFiAWJiwWJiwUzgAWKiwWKigWEjAWDjAWKiwWKiwUypQWJjAWIjAWGjgWGjgWJjQWJjAU62gWJjgWIjgWJjwWIjwWLjwWJjgVP96AFi40Fi4wFi5IFi5IFjIwFi40FxPddBY2PBYyPBY6OBY2PBY6NBY6PBdHEBYyMBYyMBZKOBZGOBY2LBYyMBfcOqQWPiwWPjAWQigWPjAWPiQWPiwX3B2cFjIoFjYsFkYcFkYgFjIoFjYkFzkoFjYgFjYkFjocFjYYFjIgFjIgFxfuJBYuDBYuDBW/7LgWIhAWJhQVYMgWKiQWLigWGhgWGhgWKigWKigUwTgWJigWKigUg0BXOkwXUvAW11gWl9x8FVvd1BVm8BTCoBShzBVdgBVj7RgXD+4sFy00FDvlI93j3xxWJigX7AooFi/uVBYd7BYF9BX2CBXqIBXmOBX2UBYGZBYibBYv5BQWMkQWMkgWMjAWLjQWPkQWOkAWNjAWMjQWQjwWRjwWNiwWMjAWSjQWRjAX3HZcFjosFj4sF9w6EBY+KBZCLBdp2BY+KBY+KBa96BZCIBZCIBcRbBYuKBYuLBZCFBZCEBYuLBYyLBaRXBY2EBY2EBZA/BYuJBYuJBYqFBYqFBYqJBYuJBXRcBYqJBYqJBYeHBYeFBYmKBYqKBWhxBYWIBYWIBVN2BYeKBYeJBTp8BYiLBYmLBfsCggWF4BX1kwXWmQW5nAWgmwWZpwWGxAV6sAVesQVxlwVEnQX7BpIFL4MFi/uJBQ75SPiTtRXQOQWTfAWNewWFewWAfwV7gwV6igV6kAV+lQVRzwVUYAWIigWJiQWGiQWGiAWHiwWIigU1fgWJjAWJigWEjAWFiwWJjAWIiwU0qQWJjAWIjAWGjgWGjgWJjgWJjAU75AWKjgWJjQWJkAWIkAWLjgWKjQVQ98MFi4sFi4sFi5MFi5MFi4sFi4wFw/d2BY2OBYyPBY2PBY6PBY2OBY2OBdDLBY2MBYyNBZGOBZGOBY2MBY2MBfcLrAWRjAWRjAWNigWOjAWRiQWRigX3BGMFjYoFjooFj4cFkYgFjIkFjYoFzUEFjIkFjYkFjYYFjoYFjIgFjIkFw/uoBYuEBYuEBW/7QgWJhQWJhQX7K0AVMfUFg5oFipsFkJsFlpcFm5MFnIwFnIYFmIEF0zcFmqkFpfc1BVb3lgVZxAU0qgUucQVXWgVY+2IFwvuvBctDBcx2BcmUBQ75SPfz+EoV3JcFrpgFoJsFlqIFjLMFfbkFgZYFd5gFcZUFQZsF+xSQBfsofgWL+10F90g8FftIhQWL+7cFh3oFgn4FfIEFeogFeo4FfJUFgZgFiJwFi/j8BYyRBYyRBYyNBYuNBY+QBY6RBY2MBYyNBZGOBZCPBY2MBY2MBZGMBZKNBfdUmwWOiwWOjAX3G4UFj4oFj4sF3HoFj4kFj4sFrX0Fj4kFj4kFp3kFj4cFkIgFoHQFi4oFjIsFjoQFj4UFi4oFjIoFnU0FjIUFjIUFiVQFi4sFiYMFiYMFi4sFeWQFiooFi4oFhoUFhoUFiosFi4oFaXAFhIgFhYcFXXoFhooFhokFNX8F94H7rQWTfQWNegWGewV/fwV8gwV5igV6kAV+lgX7nPfLBYOaBQ75SOXBFYaOBYqNBYiNBYmQBYeQBVr3AQWHnAWOmwWVmQWZlAWcjgWdiAWZggWVfgW3KgXNaQX3IIcF7bgFq/AFdsUFS68F+4ezBYiNBYiLBYaNBYaNBYmOBYiMBUu+BYiPBYiOBYmOBYiOBYqQBYmOBXrHBYuPBYqOBYuQBYuPBYyPBYyPBbT3DAWOkAWNkAWNjQWMjQWQjwWPjwXvzAWRjgWQjgWOiwWNjAWRiwWRjAX3R4IFjYoFjIwFkogFkooFjIoFjYoFkIcFkYcFjIoFjIoF1zAFknwFjXoFhXwFgH4Fe4QFeYoFe5AFfpYFTNYF+yOTBUBaBWssBZVoBbZoBfeDYwWTiQWTiAXfWgWQhwWQhwWNiQWMigWOhQWOhgWrNgWLhgWNhwWLhwWLiAWKhgWKhgVi+xgFi4oFiooFh4UFiIQFiosFiooFhYYFhYcFiosFiooF+xJRBYmLBYqKBYSKBYSJBYmLBYmLBfs2jwWJjAWJiwWFjQWEjAWJjAWJjAUzuQUO+Uj3yflsFfeiiwWchwWaggWVfQWOewWIewWBfQV8ggV6iAX7dYsFi/znBYh7BYF9BX2CBXmIBXqOBXyUBYKZBYebBYv45wX7hYsFeo4FfJQFgZkFiJsFjpsFlZkFmpQFnI8FDvlI+HT3hxWQ+E4Fj5sFlZkFmZQFnY4FnIcFmYIFlX0FjnsFhvxQBYqIBYyJBYFHBYqHBYqGBXdYBYmIBYmHBX53BYiHBYiIBW1sBYWHBYaHBVhxBYSJBYSJBU2BBYWLBYSLBTOUBYaNBYWMBUWlBYWPBYWOBVyvBYeQBYWQBWjCBYiRBYiRBXnSBYqPBYqOBYTsBYuNBYuMBYr39wWOmwWVmQWalAWcjwWchwWaggWVfgWOegWM+/UFki8Fm00Fp2EFr28FxXYF14IFu5MFsJ4FoqIFk5cFnLYFDvlI99H3NRX3a/ivBZSZBZqVBZyPBZyIBZqCBZV+BY97BYh6BfuS/REFi4sFi4oFhoUFh4QFi4sFiooFhIcFhYYFiosFi4sFg4kFg4oFiosFi4sFg4wFgowFi4wFiosFhI8FhI8Fi4sFi4wFhpEFhpEFi4wFi4sF+7j5EgWHmwWOmwWVmQWZlAWcjwWciAWaggWVfQUO+Uj4dvdYFdf4gwWQmwWXlwWbkgWcjAWchgWYgAWTfAWMegUq/REFiYcFioYFiYgFiocFiIgFiIcFiIkFiIgFh4kFh4kFh4oFh4kFh4sFhooFh4sFh4sFho0Fh4sFh40Fh40FiI4Fh40FiI4FiI4FiY8FiI4F+0b3/wX7Ofv2BYiHBYiGBYmJBYmJBYaIBYeHBYiKBYiKBYaKBYWJBYiLBYiLBYWMBYaLBYiNBYiLBYaOBYaOBYmNBYiNBYiPBYiPBYqOBYmOBYqQBYmQBTv5CQWNnAWTmQWYlgWckAWcigWbhAWWfgWRewXH/G8F9x/3vgWPkAWPkQWMjAWMjAWRjwWRjwWNiwWMjAWSjAWSjQWNiwWMiwWSiQWTigWMiwWMigWRhwWSiAWMigWMigWPhQWPhQUO+Uj3/Pf/FfeZ+7QFlH0FjXsFhnsFgH4FfIMFeYkFeo8FfpYF+5D3qQX7kPupBX6ABXqHBXmNBXyTBYCYBYabBY2bBZSZBfeZ97QF+5/3uwWCmQWJnAWQmwWWlwWalAWdjAWchwWYgQX3lvuxBfeW97EFmZUFm48FnYoFmoIFln8FkHsFiXoFgn0FDvlI9+j4EhWV++EFiHsFgn0FfYEFeogFeY0FfJQFgZkFh5sFgffjBfud96cFgpkFiJsFj5sFlpkFmpMFnI4FnIcFmYEF94n7kQX3k/eQBZqVBZyPBZyIBZqCBZV+BY96BYh7BYJ9BQ75SPci5RX4KosFnYgFmYIFlX0FjnsFiHsFgX0FfYIFeYgF/IKLBYWMBYaLBYiMBYeMBYeOBYaNBYmNBYiNBYiPBYePBYqOBYmOBYqQBYmPBYuPBYuOBYyQBYuQBYyOBYyOBY6PBY2QBfhP+M4F/CqLBXmOBX2UBYGZBYibBY6bBZWZBZmUBZ2PBfiCiwWRigWQigWOigWPigWPiQWQiAWNiQWOiQWOhwWPhwWMiAWNiAWMhwWNhgWLiAWLhwWKhgWLhgWKiAWKiAWIhwWJhgUO+Uj3h3QV9zaLBZyIBZmCBZV9BY97BYd7BYF9BX2CBXqHBftjiwV5jwV9lAWBmQWImwWL+Z8FjpsFlZkFmZQFnY4F92OLBZyIBZmCBZV9BY97BYd7BYF9BX2CBXqIBfs2iwUO+Ujw+VgV+HH9YwWRfAWKegWEfAV+gAV7hQV5jAV7kQV/lwX8cfljBYWaBYycBZKaBZiWBZuRBZ2KBZuFBQ75SPhWShWHewWBfQV9ggV6hwX7Y4sFeY8FfZQFgZkFiJsFjpsFlZkFmZQFnY4F9zaLBYv5SwX7NosFeY4FfZQFgZkFiJsFjpsFlZkFmZQFnY4F92OLBZyIBZmCBZV9BY97BQ75SPeo+WQVko8FjIsFjIwFkowFk40FjIoFjIwFk4kFkooFjIoFjIsFkocFkYcF9577ggWVfgWPewWIegWBfQV9ggV6hwV6jgV8lAX7f/dmBft/+2YFfIIFeogFeo8FfZQFgZkFiJwFj5sFlZgF9573ggUO+UiL+wEV+O6LBZyIBZqCBZV9BY57BYh7BYF9BXyCBXqIBfzuiwV6jgV8lAWBmQWImwWOmwWVmQWalAUO+Uj4POoVxcIFi/eQBVLBBVCnBS+LBVBvBUxQBWsvBYtQBaswBcpPBcdvBeaLBfcIZhWHiAWFhwVAZwWKigWJigWEigWFiQWJjAWJigX7BYsFiYwFiYoFhI0FhYwFiYwFiYwFQK8FhY8FhY8FP9MFiowFiowFiJEFh5EFiowFiowFZvYFipIFipIFi9IFjJIFjJEFsPcABYyNBYyMBY+RBY6RBYyMBYyMBdfTBZGPBZGPBdeuBYyMBY2MBZKMBZKNBYyKBY2MBfcFiwWMigWNjAWSiQWSigWMigWNigXWaAWQhwWQiAWLjwWPnAWUmAWalQWcjgWciAWagQWVfgWOegWL/IoFiHsFgX4FfIEFeogFeo4FfJUFgpgFh5sFDvlI9xOvFYaOBYuKBYd6BYF+BX2CBXqHBXmPBX2UBYGYBYicBYv5OAWOmwWVmQWZlAWdjgWciAWZggWVfQWPewWL+3YFkI4FkY8F1asFjIsFjIsFko0Fk40FjIoFjIwF9wSLBYyLBYuLBZOJBZOJBYyLBYuLBddrBZCHBZKIBdZKBYyKBY2KBY6FBY+GBYyJBYyKBbApBYyEBYyEBYtLBYqEBYqDBWYrBYqKBYqJBYeGBYiFBYmKBYqJBUBLBYWIBYWHBUBqBYqLBYqLBYSJBYOJBYqLBYqLBfsEiwWKjAWKigWDjQWEjQWKiwWKiwVBrAWA9w0VwlwFxnEF54sFx6UFycAFqdoFi70FbdsFTcAFT6QFL4sFUHIFVFwFDvlI+DLqFczNBZqVBZyPBZyIBZqDBZV9BY97BYl7BYF9BUVDBYWHBYWHBUZmBYiLBYmJBYWKBYWJBYiMBYmKBSGLBYmMBYiKBYWNBYWMBYmNBYmLBUSwBYWPBYWPBUXTBYqMBYqMBYeRBYeRBYuMBYqMBWn2BYqRBYqSBYvSBYyRBYySBa33AAWMjAWLjAWPkQWPkQWMjAWMjAXR0wWRjwWRjwXSrwWNiwWNjQWRjAWSjQWNigWNjAX1iwWNigWNjAWSiQWRigWNiQWNiwXRZwWRhwWRhwXRQwWVfQWNewWHewWBfQV8gwV6iAV6jwV8lQVKzQVWpgU3iwVVcAVRUAVtLgWLUAWoLwXGUAXCbwXdiwUO+Uj4PfUVwroFi/dxBVS6BVCkBS+LBU9yBU1WBW07BYtZBak8BclWBcdxBeeLBfcGYhWGiAWFhwVBagWKiwWKiwWEiQWDiQWKjAWKigX7BIsFiosFiosFhI0Fg40FiosFiosFQKwFhY8Fho4FP8sFio0FiYwFiJEFh5AFio0FiowFZusFipMFipIFi8sFjJIFjJIFsO0FjIwFjI0Fj5AFjpEFjYwFjIwF18wFkY4FkI8F16sFi4sFjIsFk40Fk40Fi4sFjIsF9wSLBYyKBYyMBZOJBZKJBYyLBYyLBdVrBZGHBZCIBYv3dgWPmwWVmQWZlAWcjgWdiAWZggWVfQWOewWL/TgFiHoFgX4FfYIFeYcFeo8FfZQFgZgFh5wFDvlI9x74IBV8YQX4GIsFg5QFZs0FbaYFS6cFJosFSm8F93r7/BXXzgWZlAWdjgWchwWZggWVfQWNegWIewWAfgU6QwWGiAWFhwU8ZgWJiwWKigWEigWEiQWJiwWKiwX7DYsFiosFiosFg40FhIwFiowFiosFOrAFhY8FhY4FO9MFiYwFiowFh5EFh5AFi40Fio0FY/YFipIFipIFi9IFjJIFjJIFs/cABYyNBYuNBY+QBY+QBYyNBY2MBdvTBZKOBZCPBdyvBYyLBYyMBZOMBZKNBYyLBYyLBfcNiwWMiwWMiwWTiQWSigWMigWMiwXbZwWQhwWRiAW1ZwWPhQWQhQWyRAWQewWJegWDfQV/ggWUhQWVfgWOegWIewWBfQV9ggV5iAX8SYsFi3UFrDAFz08FzG4F8IsFDvlI97n4VhWL/CQFiHsFgX0FfIIFeogFeo4FfJQFgZkFiJsFi/gkBfsGiwV6jgV8lQWCmAWHmwWPnAWUmAWalQWcjgX3BosFi8AFi40Fi40FjZEFjJEFjY0Fi4wFwOoFkZEFkJEFi4sFi4wFk44Fko8F9asFkowFkowF9YsFnIgFmoIFlX0FjnsFiHsFgX0FfIIFeogFKIsFOXIFZEUFi2EF9zuLBZyIBZqBBZV+BY56BYh7BYF+BXyBBXqIBQ75SPg99yMVwroFi/dxBVS7BVCkBS+LBU9yBU1WBW06BYtaBak7BclWBcdxBeeLBfcGYhWGiAWFhwVBagWKiwWKigWEigWDiQWKiwWKiwX7BIsFiosFiosFg40FhIwFiowFiosFQKwFhY8FhY4FQMwFiowFiYwFiJEFh5AFio0FiowFZuwFipIFipIFi8wFjJIFjJIFsOwFjI0FjI0Fj5AFjpAFjY0FjIwF1swFko4FkI8F16sFi4sFjIwFk4wFk40Fi4sFjIsF9wSLBYyLBYyLBZOJBZKKBYyKBYyLBdVrBZGHBZCIBYuLBY+cBZWYBZmVBZyOBZ2IBZmBBZV+BY56BYv8mAWKhAWKhAVmKgWKigWKiQWHhgWIhQWJigWKiQVlawWFhwWFhwVBbAWKigWKiwWEiQWDigWKiwWKiwX7BIsFiosFi4sFg4wFg40FiosFi4sFP6sFho8FhI8FQMsFio0FiYwFiJAFh5AFio0Fio0FZuwFiZwFj5sFlZgFm5QFnI0FnIcFmYEFlH0FrDQFyVYFx3EF54sFxqUFpKAFqdoFDvlI+L34CRWNhAWL+9AFiHsFgX0FfIIFeogFeo4FfJQFgZkFiJsFi/fIBW7TBVqfBSyLBU1yBS49BYv7vQWIewWBfQV8ggV6iAV6jgV8lAWBmQWImwWL+SwFjpsFlZkFmpQFnI4FnIgFmoIFlX0FjnsFi/uSBbKsBZGOBZGPBdeqBYyLBYuMBZOMBZONBYyLBYuLBfcGiwWMiwWLiwWTiQWTigWMigWLiwXXbAWLiwWLiwWShgWShwWLigWMiwWPhAWQhQWLigWLiwWxLAUO+Uj3mfmIFduLBZyIBZqCBZV9BY57BYh7BYF9BXyCBXqIBTuLBXqOBXyUBYGZBYibBY6bBZWZBZqUBfH7mRWL/E4FiHsFgX0FfIIFeogFeo4FfJQFgZkFiJsFi/hOBY6cBZWYBZqVBZyOBZyIBZqBBZV+BQ75SPgV+YgVyYsFnIgFmoIFlX0FjnsFiHsFgX0FfIIFeogFTYsFeo4FfJQFgpkFh5sFj5sFlJkFmpQF+wn+MhWGigWIjQWHiwUpqQV8kwWAmAWGmwWNmwWUmQWZlgWbjwWdiQXhcQXpoQWhyQWL+I4Fj5sFlJkFmpQFnI8FnIcFmoIFlX0FjnsFi/yVBYqEBYqFBWswBYiGBYmHBYmIBYmIBYeIBYeIBYiJBYiJBYaKBYaJBfsXbQWIiwWHigUO+Uj3f/eMFfsRLwWLIQWIewWBfQV8ggV6iAV6jgV8lAWCmQWHmwWL+SwFj5sFlJkFmpQFnI4FnIgFmoIFlX0FjnsFi/xXBff495sFm5IFnIwFnIYFmIEFk3wFjHoFhnwFgH4F+2v7MgX3mPtwBZV+BZB7BYh7BYJ9BX2BBXqHBXqNBXyTBQ75SPfu+WMVi/0xBYh7BYF9BXyCBXqIBXqOBXyUBYGZBYibBYv5MQWOmwWVmQWalAWcjwWchwWaggWVfQUO+Uj43/iYFZCGBYuKBYyJBYyFBY2EBYuKBYyJBYv8WwWHewWBfQV9ggV6iAV5jgV9lAWBmQWImwWL+EgFfJYFXIsFdHgFVDEFi/vmBYh7BYF9BX2CBXmIBXqOBX2UBYGZBYebBYv36gVo4wV1nAVdiwVzeAVVMQWL++YFh3sFgX0FfYIFeogFeY4FfZQFgZkFiJsFi/h9BY6cBZWYBZmVBZ2OBZyIBZmBBZV+BY2ABa2mBZGOBZGPBY2LBYyMBZKLBZKNBduLBZKJBZKLBYyKBY2LBZGHBZGIBbZoBYyJBY2KBY+GBY+GBYuJBY2JBZN1BZynBZCQBZCRBbWtBZGPBZGPBY2LBYyMBZKLBZKNBdyLBZKJBZKLBYyKBY2LBZGHBZGIBbZoBYyKBYyKBQ75SPi++B0VjIUFi/vyBYh7BYF9BXyCBXqIBXqOBXyUBYGZBYibBYv36wVt3QVaoQUtiwVPcAUsMwWL++AFiHsFgX0FfIIFeogFeo4FfJQFgZkFiJsFi/h9BY6cBZWYBZqVBZyOBZyIBZqBBZV+BY56BYtlBbCtBZKPBZCPBdiuBYyLBYyMBZKMBZONBYyLBYyLBfcGiwWMiwWNiwWSiQWSigWMigWNiwXWaAWMiwWLiwWShgWRhgWMiwWLiwWPhAWPhAWLiwWLiwWyIQUO+Uj37Ph4FTWLBVRwBU9PBWwvBYtQBaowBcdPBcNvBeCLBcKnBcfHBarmBYvGBWznBU/HBWH3AxWNjAWRiQWSigWNiQWNiwXTaAWRhgWRhwXTQwWLigWMiwWPhAWPhQWLigWMigWv+wAFjIUFjIQFi0QFioQFioUFZyAFiooFi4oFh4QFh4UFiosFi4oFQ0MFhYcFhYcFQ2YFiYsFiYkFhYoFhIkFiYwFiYoF+wCLBYmMBYmKBYSNBYWMBYmNBYmLBUOwBYWPBYWPBUPTBYuMBYqLBYeRBYeSBYuMBYqMBWf2BYqRBYqSBYvSBYySBYyRBa/3AAWMjAWLjAWPkQWPkgWMiwWLjAXT0wWSjwWQkAXTrgWNiwWNjQWSjAWRjQWNigWNjAX3AIsFDvlI9xTXFYWPBYv7dQWHewWCfQV8ggV6iAV6jgV8lAWBmQWImwWL+TMFjpwFlZgFmpUFnI4FnIgFmoEFlH4Fj3oFi4sFkY8FkI4F1asFjIsFjIwFk4wFko0FjIsFjIsF9wSLBYyLBYuLBZOJBZOKBYyKBYuLBdZsBZGHBZGHBdZLBY2KBYyJBY+GBY+GBYuJBY2JBa8rBY2EBYyDBYtLBYqEBYmEBWYsBYqJBYuJBYeGBYeFBYqKBYmKBUBLBYWHBYaIBUBqBYqLBYqKBYOKBYSJBYqLBYqLBfsEiwWKiwWKiwWDjQWEjAWKjAWKiwVBrAWA9w0VwlwFxnEF54sFx6UFyb8FqdoFi7wFbdsFTb8FT6QFL4sFUHIFVFwFDvlI+D33JRXCugWL924FVLoFUKQFL4sFT3IFTVcFbTsFi1oFqTwFyVcFx3EF54sF9wZiFYaIBYWHBUFqBYqLBYqLBYSJBYOJBYqMBYqKBfsEiwWKjAWKigWEjQWDjQWKiwWKiwVArAWGjgWFjwVAywWJjAWKjQWHkAWHkAWLjQWKjQVm6gWJkgWKkwWLywWMkgWNkgWw6wWMjQWLjQWPkAWPkQWMjAWNjAXWywWRjwWRjwXWqgWLiwWMjAWTjAWTjQWLiwWMiwX3BIsFjIsFjIsFkokFk4oFjIoFjIsF1WwFkIcFkYgFi4sFj5sFlJkFmpQFnI4FnIgFmoIFlX0FjnsFi/00BYh7BYF9BXyCBXqIBXqOBXyUBYKZBYebBQ75SPfp+MsVk40F9yaLBZyIBZmBBZV+BY96BYd7BYF+BX2BBXqIBfsdiwU4bgU5TwViNAWL+6MFiHsFgX0FfYIFeYgFeo4FfZQFgZkFh5sFi/h9BY+cBZWYBZmVBZyOBZ2IBZmBBZV+BY56BYtWBdTABZGNBZGPBeutBQ75SO6nFYSQBYuLBYuMBYeSBYeSBXLSBYmcBY+bBZaYBZuTBZyNBZyGBZmBBZN9BZ9TBbt0BfWLBeSsBbuhBYuoBVHCBfsBygX7BIsFiYsFiosFhI0FhIwFiowFiYwFQK8FhY8Fho8FiowFiYwFiJEFh5EFi4wFio0FipEFipIFi9IFjJMFjZMFi4sFi4wFkJEFj5IF1tMFjIsFjIwFkY8Fko8FjIsFi4wF764Fk4wFk40F9xGLBYyKBY2MBZKJBZKKBYyKBY2KBdZoBZmBBZN8BY17BYd7BYB+BXyDBXmJBXqPBUqqBSGLBTluBVRWBYtuBbN4BfcGiwWOigWPiwWQiQWQigWOigWPiQX3EEQFj4cFkIgF1kQFj4QFkIQFi4sFi4sFjYMFjIMFi0MFioUFioQFiooFi4kFh4UFiIYFiYoFiokFhYgFhoYFQGgFiYsFiYkFJ2cFg4oFg4kF+xGLBYmMBYmKBYWNBYSMBYmMBYqMBUCvBQ75SPdd+DEV+wyLBXqOBXyUBYGZBYibBY6bBZWZBZqUBZyOBfcMiwWL9zcFjpsFlZkFmpQFnI4FnIgFmoIFlX0FjnsFi/s3BfdDiwWciAWaggWVfQWOewWIewWBfQV8ggV6iAX7Q4sFi/uCBbNMBeF0BfOLBZyHBZqCBZV9BY57BYh7BYF9BXyCBXqIBfsCiwWFjAWFjAX7AqgFg48FhI4Fi4sFiowFhpEFhZAFVOIFio4FiY4FipAFiZAFjI4Fio4FDvlI+GX3SRWL9+AFjpsFlZkFmpQFnI4FnIgFmoIFlX0FjnsFi/x9BYh6BYF+BXyBBXqIBXqOBXyVBYGYBYicBYuyBWZpBYWHBYWHBT9oBYmKBYqKBYSKBYSJBYmMBYqKBfsGiwWJjAWKigWEjQWEjAWJjAWKjAU/rgWEkAWEkAWLiwWLiwWHkgWHkgVk9AWKkgWKkQWL9/IFjpsFlZkFmpQFnI4FnIgFmoIFlX0FjnsFi/vrBak6Bb10BeeLBcinBQ75SPfB9xcV92j4JgWWmAWakwWcjQWchwWZgQWUfQWNegWHewX7kfxyBYiHBYiGBYiJBYqJBYaIBYaIBYiKBYiKBYaKBYWKBYiLBYiLBYWMBYaMBYiMBYiMBYaOBYaOBYqNBYiNBYiQBYiPBfuQ+HIFhpsFjZwFlJkFmZUFnI8FnIkFmoMFln4FDvlI+Fj3TRX29+kFk5oFmZUFm5AFnYoFmoMFl34FkHsFiXsF+yr8cgWIhwWKhwWIiAWKhwWHiQWIhwWHiQWIiQWGiQWHiQWHiwWHigWHiwWGiwWHjAWHiwWHjQWGjQWIjQWHjQWIjwWIjQWJjwWIjgWKjwWIjwUg9+kFIPvpBYiHBYqHBYiIBYmHBYiJBYiHBYeJBYiJBYaJBYeJBYeLBYeKBYeLBYaLBYeMBYeLBYeNBYaNBYiNBYeNBYiPBYiNBYmPBYiOBYqPBYiPBfsq+HIFiZsFkJsFl5gFmpMFnYwFm4YFmYEFk3wF9wD76QX29+kFjY8FjI8Fjo4FjY8Fj44Fjo4Fjo0Fj40Fj40Fj40Fj4sFj4wFkIsFkIsFj4oFj4sFj4kFkIkFjokFjokFjogFj4gFjYcFjogFjIcFjYcFDvlI+AL3pxX3evtlBZV+BY97BYh7BYF9BX2BBXqIBXmOBX2UBft992YF+337ZgV9ggV5iAV6jgV9lQWBmQWImwWPmwWVmAX3evdlBft692UFgZgFh5sFjpwFlZgFmZUFnI4FnYgFmYMF9337ZwX3ffdnBZmTBZ2OBZyIBZmBBZV+BY56BYd7BYF+BQ75SOj7TxWDigWLiwWLiwVjiwV6jgV8lAWBmQWImwWOmwWVmQWalAWcjgWqiwXLpQXOwQXJ7gX7dfg4BYebBY2bBZSaBZiVBZyPBZ2JBZqDBZZ+BfdX/AEF91n4AQWWmAWakwWdjQWbhwWZgQWUfAWNewWGewX7gfxMBYuKBYqJBT37EQWGhQWGhgU9TAWEiAWGhwU8bAWLiwWLiwUO+Uj3UtkV98+LBZ2IBZmCBZV9BY57BYh7BYF9BX2CBXmIBfwsiwWEjAWFiwWJjQWIiwWGjgWGjgWJjQWJjAWHkAWHkAWKjQWKjQWKkQWJkAWLjgWLjQWMkQWLkQWNjQWLjQWPkAWOkQX38vguBfvPiwV5jgV9lAWBmQWImwWOmwWVmQWZlAWdjgX4LIsFkooFkYsFjYoFjooFkIgFkYgFjIkFjYoFj4YFj4YFjIkFjIkFjIUFjYYFi4gFi4kFioUFi4UFiYkFi4kFh4YFiIYFDgAAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAAK0AAACtAAAArQAAA==";function hn(t,e){return Array.isArray(e)?[t.a*e[0]+t.c*e[1]+t.e,t.b*e[0]+t.d*e[1]+t.f]:{x:t.a*e.x+t.c*e.y+t.e,y:t.b*e.x+t.d*e.y+t.f}}const vUo=/^matrix\(\s*([0-9_+-.e]+)\s*,\s*([0-9_+-.e]+)\s*,\s*([0-9_+-.e]+)\s*,\s*([0-9_+-.e]+)\s*,\s*([0-9_+-.e]+)\s*,\s*([0-9_+-.e]+)\s*\)$/i;function wUo(t){const e=t.match(vUo);if(e===null||e.length<7)throw new Error(`'${t}' is not a matrix`);return{a:parseFloat(e[1]),b:parseFloat(e[2]),c:parseFloat(e[3]),d:parseFloat(e[4]),e:parseFloat(e[5]),f:parseFloat(e[6])}}function PUo(t){const{a:e,b:n,c:o,d:i,e:r,f:s}=t,a=e*i-n*o;return{a:i/a,b:n/-a,c:o/-a,d:e/a,e:(i*r-o*s)/-a,f:(n*r-e*s)/a}}function dq(t){return typeof t>"u"}function of(t,e=0){return{a:1,c:0,e:t,b:0,d:1,f:e}}function hq(...t){t=Array.isArray(t[0])?t[0]:t;const e=(n,o)=>({a:n.a*o.a+n.c*o.b,c:n.a*o.c+n.c*o.d,e:n.a*o.e+n.c*o.f+n.e,b:n.b*o.a+n.d*o.b,d:n.b*o.c+n.d*o.d,f:n.b*o.e+n.d*o.f+n.f});switch(t.length){case 0:throw new Error("no matrices provided");case 1:return t[0];case 2:return e(t[0],t[1]);default:{const[n,o,...i]=t,r=e(n,o);return hq(r,...i)}}}function m0(...t){return hq(...t)}const{cos:MUo,sin:DUo}=Math;function jb(t,e,n){const o=MUo(t),i=DUo(t),r={a:o,c:-i,e:0,b:i,d:o,f:0};return dq(e)||dq(n)?r:hq([of(e,n),r,of(-e,-n)])}function kx(t,e=void 0,n=void 0,o=void 0){dq(e)&&(e=t);const i={a:t,c:0,e:0,b:0,d:e,f:0};return dq(n)||dq(o)?i:hq([of(n,o),i,of(-n,-o)])}function NUo(t){return $b(t)}function $b(t){return`matrix(${t.a},${t.b},${t.c},${t.d},${t.e},${t.f})`}function RUo(t,e=1e10){return{a:Math.round(t.a*e)/e,b:Math.round(t.b*e)/e,c:Math.round(t.c*e)/e,d:Math.round(t.d*e)/e,e:Math.round(t.e*e)/e,f:Math.round(t.f*e)/e}}function TUo(t,e){const n=t[0].x!=null?t[0].x:t[0][0],o=t[0].y!=null?t[0].y:t[0][1],i=e[0].x!=null?e[0].x:e[0][0],r=e[0].y!=null?e[0].y:e[0][1],s=t[1].x!=null?t[1].x:t[1][0],a=t[1].y!=null?t[1].y:t[1][1],A=e[1].x!=null?e[1].x:e[1][0],c=e[1].y!=null?e[1].y:e[1][1],l=t[2].x!=null?t[2].x:t[2][0],u=t[2].y!=null?t[2].y:t[2][1],g=e[2].x!=null?e[2].x:e[2][0],h=e[2].y!=null?e[2].y:e[2][1],d={a:n-l,b:o-u,c:s-l,d:a-u,e:l,f:u},p={a:i-g,b:r-h,c:A-g,d:c-h,e:g,f:h},m=PUo(d),_=hq([p,m]);return RUo(_)}function kUo(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n}function Wge(t,e,n,o){var i=Error.call(this,t);return Object.setPrototypeOf&&Object.setPrototypeOf(i,Wge.prototype),i.expected=e,i.found=n,i.location=o,i.name="SyntaxError",i}kUo(Wge,Error);function hRe(t,e,n){return n=n||" ",t.length>e?t:(e-=t.length,n+=n.repeat(e),t+n.slice(0,e))}Wge.prototype.format=function(t){var e="Error: "+this.message;if(this.location){var n=null,o;for(o=0;o<t.length;o++)if(t[o].source===this.location.source){n=t[o].text.split(/\r\n|\n|\r/g);break}var i=this.location.start,r=this.location.source&&typeof this.location.source.offset=="function"?this.location.source.offset(i):i,s=this.location.source+":"+r.line+":"+r.column;if(n){var a=this.location.end,A=hRe("",r.line.toString().length," "),c=n[i.line-1],l=i.line===a.line?a.column:c.length+1,u=l-i.column||1;e+=`
 --> `+s+`
`+A+` |
`+r.line+" | "+c+`
`+A+" | "+hRe("",i.column-1," ")+hRe("",u,"^")}else e+=`
 at `+s}return e},Wge.buildMessage=function(t,e){var n={literal:function(c){return'"'+i(c.text)+'"'},class:function(c){var l=c.parts.map(function(u){return Array.isArray(u)?r(u[0])+"-"+r(u[1]):r(u)});return"["+(c.inverted?"^":"")+l.join("")+"]"},any:function(){return"any character"},end:function(){return"end of input"},other:function(c){return c.description}};function o(c){return c.charCodeAt(0).toString(16).toUpperCase()}function i(c){return c.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(l){return"\\x0"+o(l)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(l){return"\\x"+o(l)})}function r(c){return c.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(l){return"\\x0"+o(l)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(l){return"\\x"+o(l)})}function s(c){return n[c.type](c)}function a(c){var l=c.map(s),u,g;if(l.sort(),l.length>0){for(u=1,g=1;u<l.length;u++)l[u-1]!==l[u]&&(l[g]=l[u],g++);l.length=g}switch(l.length){case 1:return l[0];case 2:return l[0]+" or "+l[1];default:return l.slice(0,-1).join(", ")+", or "+l[l.length-1]}}function A(c){return c?'"'+i(c)+'"':"end of input"}return"Expected "+a(t)+" but "+A(e)+" found."};var pq="TscircuitAlphabet",BYt="data-tscircuit-alphabet-font";function Ow(t){const e=o=>({...o,children:(o.children??[]).filter(i=>!(BYt in(i.attributes??{}))).map(e)}),n=e(t);return n.children.push({name:"style",type:"element",value:"",attributes:{[BYt]:"",type:"text/css"},children:[{name:"",type:"text",value:`@font-face { font-family: '${pq}'; src: url('data:font/ttf;base64,${EYt}') format('truetype'); font-weight: normal; font-style: normal; }`,attributes:{},children:[]}]}),Cbt(n)}function FUo(t,e,n){const{transform:o,shouldDrawErrors:i}=n;if(!i)return[];const{pcb_port_ids:r}=t,s=e.find(g=>g.type==="pcb_port"&&g.pcb_port_id===r?.[0]),a=e.find(g=>g.type==="pcb_port"&&g.pcb_port_id===r?.[1]);if(!s||!a){const h=t.message?.match(/pcb_via\[#?(pcb_via_\d+)\]/)?.[1],d=e.find(p=>p.type==="pcb_via"&&p.pcb_via_id===h);if(d&&d.type==="pcb_via")return LUo(t,d,n);if(t.center){const p=hn(o,{x:t.center.x,y:t.center.y});return pRe([{name:"rect",type:"element",attributes:{x:(p.x-5).toString(),y:(p.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${p.x} ${p.y})`},children:[],value:""},{name:"text",type:"element",attributes:{x:p.x.toString(),y:(p.y-15).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle"},children:[{type:"text",value:t.message||"Pcb Trace Error",name:"",attributes:{},children:[]}],value:""}])}else return[]}const A=hn(o,{x:s.x,y:s.y}),c=hn(o,{x:a.x,y:a.y}),l={x:(A.x+c.x)/2,y:(A.y+c.y)/2};if(isNaN(A.x)||isNaN(A.y)||isNaN(c.x)||isNaN(c.y)||isNaN(l.x)||isNaN(l.y))return[];const u=[{name:"line",type:"element",attributes:{x1:A.x.toString(),y1:A.y.toString(),x2:l.x.toString(),y2:l.y.toString(),stroke:"red","stroke-width":"1.5","stroke-dasharray":"2,2"},children:[],value:""},{name:"line",type:"element",attributes:{x1:l.x.toString(),y1:l.y.toString(),x2:c.x.toString(),y2:c.y.toString(),stroke:"red","stroke-width":"1.5","stroke-dasharray":"2,2"},children:[],value:""},{name:"rect",type:"element",attributes:{x:(l.x-5).toString(),y:(l.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${l.x} ${l.y})`},children:[],value:""},{name:"text",type:"element",attributes:{x:l.x.toString(),y:(l.y-15).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle"},children:[{type:"text",value:t.message||"Pcb Trace Error",name:"",attributes:{},children:[]}],value:""}];return pRe(u)}function LUo(t,e,n){const{transform:o}=n;if(t.center&&e){const i=hn(o,{x:t.center.x,y:t.center.y}),r=hn(o,{x:e.x,y:e.y}),s=r.x-i.x,a=r.y-i.y,A=Math.sqrt(s*s+a*a),c=Math.atan2(a,s)*180/Math.PI,u=A+10*2,g=20,h=(i.x+r.x)/2,d=(i.y+r.y)/2;return pRe([{name:"rect",type:"element",attributes:{x:(h-u/2).toString(),y:(d-g/2).toString(),width:u.toString(),height:g.toString(),fill:"none",stroke:"red","stroke-width":"1","stroke-dasharray":"3,2",transform:`rotate(${c} ${h} ${d})`},children:[],value:""},{name:"rect",type:"element",attributes:{x:(h-5).toString(),y:(d-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${h} ${d})`},children:[],value:""},{name:"text",type:"element",attributes:{x:h.toString(),y:(d-g/2-5).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle"},children:[{type:"text",value:t.message||"Pcb Trace Error",name:"",attributes:{},children:[]}],value:""}])}return[]}function pRe(t){return t.map(e=>({...e,attributes:{...e.attributes??{},"data-type":e.attributes?.["data-type"]??"pcb_trace_error","data-pcb-layer":e.attributes?.["data-pcb-layer"]??"overlay"},children:(e.children??[]).map(n=>n?.type==="element"?{...n,attributes:{...n.attributes??{},"data-type":n.attributes?.["data-type"]??"pcb_trace_error","data-pcb-layer":n.attributes?.["data-pcb-layer"]??"overlay"}}:n)}))}function HUo(t){return t.map(e=>({...e,attributes:{...e.attributes??{},"data-type":e.attributes?.["data-type"]??"pcb_footprint_overlap_error","data-pcb-layer":e.attributes?.["data-pcb-layer"]??"overlay"},children:(e.children??[]).map(n=>n?.type==="element"?{...n,attributes:{...n.attributes??{},"data-type":n.attributes?.["data-type"]??"pcb_footprint_overlap_error","data-pcb-layer":n.attributes?.["data-pcb-layer"]??"overlay"}}:n)}))}function OUo(t,e,n){const{transform:o,shouldDrawErrors:i}=n;if(!i)return[];const r=[],s=[];let a=[];if(t.pcb_smtpad_ids)for(const l of t.pcb_smtpad_ids){const u=e.find(g=>g.type==="pcb_smtpad"&&g.pcb_smtpad_id===l);u&&(s.push({x:u.x,y:u.y,type:"pcb_smtpad",id:l,pcb_port_id:u.pcb_port_id}),u.pcb_port_id&&a.push(u.pcb_port_id))}const A=a.length>1&&a.every(l=>l===a[0]);let c=s;if(A&&(c=s.filter(l=>l.type!=="pcb_smtpad")),t.pcb_plated_hole_ids)for(const l of t.pcb_plated_hole_ids){const u=e.find(g=>g.type==="pcb_plated_hole"&&g.pcb_plated_hole_id===l);u&&c.push({x:u.x,y:u.y,type:"pcb_plated_hole",id:l})}if(t.pcb_hole_ids)for(const l of t.pcb_hole_ids){const u=e.find(g=>g.type==="pcb_hole"&&g.pcb_hole_id===l);u&&c.push({x:u.x,y:u.y,type:"pcb_hole",id:l})}if(c.length>0){const l=c.reduce((h,d)=>h+d.x,0)/c.length,u=c.reduce((h,d)=>h+d.y,0)/c.length,g=hn(o,{x:l,y:u});r.push({name:"rect",type:"element",attributes:{x:(g.x-5).toString(),y:(g.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${g.x} ${g.y})`},children:[],value:""}),r.push({name:"text",type:"element",attributes:{x:g.x.toString(),y:(g.y-15).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle"},children:[{type:"text",value:t.message||"PCB Footprint Overlap Error",name:"",attributes:{},children:[]}],value:""});for(const h of c){const d=hn(o,{x:h.x,y:h.y});r.push({name:"rect",type:"element",attributes:{x:(d.x-5).toString(),y:(d.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${d.x} ${d.y})`},children:[],value:""}),c.length>1&&r.push({name:"line",type:"element",attributes:{x1:g.x.toString(),y1:g.y.toString(),x2:d.x.toString(),y2:d.y.toString(),stroke:"red","stroke-width":"1.5","stroke-dasharray":"2,2"},children:[],value:""})}}return HUo(r)}function GUo(t,e,n){const{transform:o,shouldDrawErrors:i}=n;if(!i)return[];const r=[],s=[];for(const l of t.pcb_component_ids){const u=e.find(g=>g.type==="pcb_component"&&g.pcb_component_id===l);u&&s.push(u.center)}if(s.length===0)return[];const a=s.reduce((l,u)=>l+u.x,0)/s.length,A=s.reduce((l,u)=>l+u.y,0)/s.length,c=hn(o,{x:a,y:A});r.push({name:"rect",type:"element",attributes:{x:(c.x-5).toString(),y:(c.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${c.x} ${c.y})`,"data-type":"pcb_courtyard_overlap_error","data-pcb-layer":"overlay"},children:[],value:""}),r.push({name:"text",type:"element",attributes:{x:c.x.toString(),y:(c.y-15).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle","data-type":"pcb_courtyard_overlap_error","data-pcb-layer":"overlay"},children:[{type:"text",value:t.message||"PCB Courtyard Overlap",name:"",attributes:{},children:[]}],value:""});for(const l of s){const u=hn(o,l);r.push({name:"rect",type:"element",attributes:{x:(u.x-5).toString(),y:(u.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${u.x} ${u.y})`,"data-type":"pcb_courtyard_overlap_error","data-pcb-layer":"overlay"},children:[],value:""})}if(s.length===2){const l=s.map(h=>hn(o,h)),u=l[0],g=l[1];r.push({name:"line",type:"element",attributes:{x1:u.x.toString(),y1:u.y.toString(),x2:g.x.toString(),y2:g.y.toString(),stroke:"red","stroke-width":"1.5","stroke-dasharray":"4,3","data-type":"pcb_courtyard_overlap_error","data-pcb-layer":"overlay"},children:[],value:""})}return r}function YUo(t){return t.map(e=>({...e,attributes:{...e.attributes??{},"data-type":e.attributes?.["data-type"]??"pcb_component_outside_board_error","data-pcb-layer":e.attributes?.["data-pcb-layer"]??"overlay"}}))}function UUo(t,e){const n=t.pcb_component_id;if(!n)return t.component_bounds??null;const o=e.find(i=>i.type==="pcb_component"&&i.pcb_component_id===n);return o?.center&&o?.width&&o?.height?{min_x:o.center.x-o.width/2,max_x:o.center.x+o.width/2,min_y:o.center.y-o.height/2,max_y:o.center.y+o.height/2}:t.component_bounds??null}function KUo(t,e,n){const{shouldDrawErrors:o,transform:i}=n;if(!o)return[];const r=UUo(t,e);if(!r)return[];const s=hn(i,{x:r.min_x,y:r.min_y}),a=hn(i,{x:r.max_x,y:r.max_y}),A=Math.min(s.x,a.x),c=Math.min(s.y,a.y),l=Math.abs(a.x-s.x),u=Math.abs(a.y-s.y),g=A+l/2,h=c+u/2,d=[{type:"element",name:"rect",value:"",attributes:{x:A.toString(),y:c.toString(),width:l.toString(),height:u.toString(),fill:"none",stroke:"red","stroke-width":"1.5","stroke-dasharray":"4,2"},children:[]},{type:"element",name:"rect",value:"",attributes:{x:(g-5).toString(),y:(h-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${g} ${h})`},children:[]},{type:"element",name:"text",value:"",attributes:{x:g.toString(),y:(c-10).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle"},children:[{type:"text",name:"",value:t.message??"PCB component extends outside board boundaries",attributes:{},children:[]}]}];return YUo(d)}function mq(t){return t!==void 0&&typeof t.x=="number"&&Number.isFinite(t.x)&&typeof t.y=="number"&&Number.isFinite(t.y)}function VUo(t,e){return t.type==="pcb_via_trace_clearance_error"?e.find(n=>n.type==="pcb_via"&&n.pcb_via_id===t.pcb_via_id):e.find(n=>n.type==="pcb_smtpad"&&n.pcb_smtpad_id===t.pcb_pad_id||n.type==="pcb_plated_hole"&&n.pcb_plated_hole_id===t.pcb_pad_id)}function zUo(t){if(t){if("x"in t&&"y"in t&&mq(t))return{x:t.x,y:t.y};if(t.type==="pcb_smtpad"&&t.shape==="polygon"&&t.points.length>0){const e=t.points.filter(mq);if(e.length===0)return;const n=e.map(i=>i.x),o=e.map(i=>i.y);return{x:(Math.min(...n)+Math.max(...n))/2,y:(Math.min(...o)+Math.max(...o))/2}}}}function JUo(t){return t.route_type==="through_pad"?[t.start,t.end].filter(mq):mq(t)?[{x:t.x,y:t.y}]:[]}function WUo(t){if(!t)return;let e,n;for(const o of t.route){const i=JUo(o);!e&&i[0]&&(e=i[0]),i.length>0&&(n=i[i.length-1])}return e&&n?{start:e,end:n}:void 0}function jUo(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}function mRe(t,e,n){const o=t.x-e.x,i=t.y-e.y;if(!(o*o+i*i<.25))return{type:"element",name:"line",value:"",attributes:{x1:t.x.toString(),y1:t.y.toString(),x2:e.x.toString(),y2:e.y.toString(),stroke:"red","stroke-width":"1.5","stroke-dasharray":"2,2","data-error-reference":n},children:[]}}function $Uo(t,e){return t.map(n=>({...n,attributes:{...n.attributes??{},"data-type":n.attributes?.["data-type"]??e,"data-pcb-layer":n.attributes?.["data-pcb-layer"]??"overlay"}}))}function qUo(t,e,n){const{shouldDrawErrors:o,transform:i}=n;if(!o)return[];const r=zUo(VUo(t,e)),s=e.find(I=>I.type==="pcb_trace"&&I.pcb_trace_id===t.pcb_trace_id),a=WUo(s),A=mq(t.center)?t.center:r??(a?jUo(a.start,a.end):void 0);if(!A)return[];const c=hn(i,A),l=r?hn(i,r):void 0,u=a?{start:hn(i,a.start),end:hn(i,a.end)}:void 0,g=[u?mRe(u.start,c,"trace-start"):void 0,u?mRe(u.end,c,"trace-end"):void 0,l?mRe(l,c,"obstacle"):void 0].filter(I=>I!==void 0),h=t.type==="pcb_pad_trace_clearance_error"?"Pad/trace":"Via/trace",d=t.actual_clearance,p=t.minimum_clearance,m=d!==void 0&&p!==void 0?`${h} clearance ${d} is below minimum ${p}`:t.type==="pcb_pad_trace_clearance_error"?"Pad and trace too close":"Via and trace too close",_=t.message??m,f=[...g,{type:"element",name:"rect",value:"",attributes:{x:(c.x-5).toString(),y:(c.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${c.x} ${c.y})`},children:[]},{type:"element",name:"text",value:"",attributes:{x:c.x.toString(),y:(c.y-15).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle"},children:[{type:"text",name:"",value:_,attributes:{},children:[]}]}];return $Uo(f,t.type)}function XUo(t,e){const{transform:n,layer:o}=e;if(!t.route||!Array.isArray(t.route))return[];const i=t.route[0],r=t.route[t.route.length-1],s=i.x===r.x&&i.y===r.y,a=t.route.slice(0,s?-1:void 0).map((A,c)=>{const[l,u]=hn(n,[A.x,A.y]);return c===0?`M ${l} ${u}`:`L ${l} ${u}`}).join(" ")+(s?" Z":"");return[{name:"path",type:"element",attributes:{class:"pcb-fabrication-note-path",stroke:t.color||"rgba(255,255,255,0.5)",fill:"none",d:a,"stroke-width":(t.stroke_width*Math.abs(n.a)).toString(),"data-pcb-component-id":t.pcb_component_id,"data-pcb-fabrication-note-path-id":t.pcb_fabrication_note_path_id,"data-type":"pcb_fabrication_note_path","data-pcb-layer":"overlay"},value:"",children:[]}]}var bYt=vc("circuit-to-svg"),cm=bYt.extend("pcb");bYt.extend("sch");function SYt(t){switch(t){case"top_left":return{textAnchor:"start",dominantBaseline:"text-before-edge"};case"top_center":return{textAnchor:"middle",dominantBaseline:"text-before-edge"};case"top_right":return{textAnchor:"end",dominantBaseline:"text-before-edge"};case"center_left":return{textAnchor:"start",dominantBaseline:"central"};case"center_right":return{textAnchor:"end",dominantBaseline:"central"};case"bottom_left":return{textAnchor:"start",dominantBaseline:"text-after-edge"};case"bottom_center":return{textAnchor:"middle",dominantBaseline:"text-after-edge"};case"bottom_right":return{textAnchor:"end",dominantBaseline:"text-after-edge"};default:return{textAnchor:"middle",dominantBaseline:"central"}}}function ZUo(t,e){const{transform:n,layer:o}=e,{anchor_position:i,anchor_alignment:r="center",text:s,font_size:a=1,layer:A="top",color:c,ccw_rotation:l=0}=t;if(o&&A!==o)return[];if(!i||typeof i.x!="number"||typeof i.y!="number")return cm(`[pcb_fabrication_note_text] Invalid anchor_position for "${t.pcb_fabrication_note_text_id}": expected {x: number, y: number}, got ${JSON.stringify(i)}`),[];const[u,g]=hn(n,[i.x,i.y]),h=a*Math.abs(n.a),{textAnchor:d,dominantBaseline:p}=SYt(r),m=m0(of(u,g),jb(-l*Math.PI/180));return[{name:"text",type:"element",attributes:{x:"0",y:"0","font-family":pq,"font-size":h.toString(),"text-anchor":d,"dominant-baseline":p,transform:$b(m),class:"pcb-fabrication-note-text",fill:c||"rgba(255,255,255,0.5)","data-type":"pcb_fabrication_note_text","data-pcb-layer":"overlay"},children:[{type:"text",value:s,name:"",attributes:{},children:[]}],value:""}]}var eKo="rgba(255,255,255,0.5)",tKo="rgba(255,255,255,0.2)";function nKo(t,e){const{transform:n,layer:o}=e,{center:i,width:r,height:s,stroke_width:a,is_filled:A,has_stroke:c,is_stroke_dashed:l,color:u,layer:g="top",pcb_component_id:h,pcb_fabrication_note_rect_id:d,corner_radius:p}=t;if(o&&g!==o)return[];if(!i||typeof i.x!="number"||typeof i.y!="number"||typeof r!="number"||typeof s!="number")return cm(`[pcb_fabrication_note_rect] Invalid data for "${d}": expected center {x: number, y: number}, width: number, height: number, got center=${JSON.stringify(i)}, width=${JSON.stringify(r)}, height=${JSON.stringify(s)}`),[];const m=r/2,_=s/2,[f,I]=hn(n,[i.x-m,i.y+_]),[C,y]=hn(n,[i.x+m,i.y-_]),x=Math.min(f,C),E=Math.min(I,y),B=Math.abs(C-f),S=Math.abs(y-I),w=(typeof a=="number"?a:0)*Math.abs(n.a),M=u??eKo,k=typeof p=="number"&&p>0?p:0,R=k*Math.abs(n.a),F=k*Math.abs(n.d),O={x:x.toString(),y:E.toString(),width:B.toString(),height:S.toString(),class:"pcb-fabrication-note-rect","data-type":"pcb_fabrication_note_rect","data-pcb-fabrication-note-rect-id":d,"data-pcb-layer":"overlay"};if(h!==void 0&&(O["data-pcb-component-id"]=h),R>0&&(O.rx=R.toString()),F>0&&(O.ry=F.toString()),A?O.fill=u??tKo:O.fill="none",c??w>0){if(O.stroke=M,O["stroke-width"]=w.toString(),l){const W=.2*Math.abs(n.a),te=.1*Math.abs(n.a);O["stroke-dasharray"]=`${W} ${te}`}}else O.stroke="none";return[{name:"rect",type:"element",value:"",attributes:O,children:[]}]}function _Re(t){const e=Math.hypot(t.x,t.y)||1;return{x:t.x/e,y:t.y/e}}var oKo=1.5,iKo=.6,rKo=.3;function QYt(t){return t.map((e,n)=>n===0?`M ${e.x} ${e.y}`:`L ${e.x} ${e.y}`).join(" ")}function sKo(t,e){const{transform:n,layer:o}=e,{from:i,to:r,text:s,font_size:a=1,color:A,arrow_size:c,layer:l,pcb_component_id:u,pcb_fabrication_note_dimension_id:g,offset_distance:h,offset_direction:d,text_ccw_rotation:p}=t;if(o&&l&&l!==o)return[];if(!i||!r||typeof i!="object"||typeof r!="object")return cm(`[pcb_fabrication_note_dimension] Invalid endpoints for "${g}": expected {from: {x, y}, to: {x, y}}, got from=${JSON.stringify(i)}, to=${JSON.stringify(r)}`),[];if(typeof i.x!="number"||typeof i.y!="number"||typeof r.x!="number"||typeof r.y!="number")return cm(`[pcb_fabrication_note_dimension] Invalid point values for "${g}": x and y must be numbers, got from=${JSON.stringify(i)}, to=${JSON.stringify(r)}`),[];const m=typeof c=="number"?c:void 0;if(m===void 0||!Number.isFinite(m)||m<=0)return cm(`[pcb_fabrication_note_dimension] Invalid arrow_size for "${g}": expected positive number, got ${JSON.stringify(c)}`),[];const _=m,f=_Re({x:r.x-i.x,y:r.y-i.y});if(Number.isNaN(f.x)||Number.isNaN(f.y))return[];const I={x:-f.y,y:f.x},C=d&&typeof d.x=="number"&&typeof d.y=="number",y=C?_Re({x:d.x,y:d.y}):{x:0,y:0},x=typeof h=="number"?h:0,E={x:y.x*x,y:y.y*x},B=Ce=>({x:Ce.x+E.x,y:Ce.y+E.y}),S=B(i),Q=B(r),w=_/2,M={x:S.x+f.x*_,y:S.y+f.y*_},k={x:Q.x-f.x*_,y:Q.y-f.y*_},R=[ke(S),ke({x:M.x+I.x*w,y:M.y+I.y*w}),ke({x:M.x-I.x*w,y:M.y-I.y*w})],F=[ke(Q),ke({x:k.x+I.x*w,y:k.y+I.y*w}),ke({x:k.x-I.x*w,y:k.y-I.y*w})],[O,U]=hn(n,[M.x,M.y]),[Y,W]=hn(n,[k.x,k.y]),te=_/5*Math.abs(n.a),j=A||"rgba(255,255,255,0.5)",J=C&&(Math.abs(y.x)>Number.EPSILON||Math.abs(y.y)>Number.EPSILON)?y:I,oe=x+_,ie=Ce=>{const Le={x:Ce.x+J.x*oe,y:Ce.y+J.y*oe},[Ye,tt]=hn(n,[Ce.x,Ce.y]),[At,at]=hn(n,[Le.x,Le.y]);return{name:"path",type:"element",value:"",attributes:{d:`M ${Ye} ${tt} L ${At} ${at}`,stroke:j,fill:"none","stroke-width":te.toString(),"stroke-linecap":"round",class:"pcb-fabrication-note-dimension-extension"},children:[]}},ne=[ie(i),ie(r)],le={x:(i.x+r.x)/2+E.x,y:(i.y+r.y)/2+E.y},[ge,_e]=hn(n,[S.x,S.y]),[ue,fe]=hn(n,[Q.x,Q.y]),pe=_Re({x:ue-ge,y:fe-_e});let ye=Math.atan2(pe.y,pe.x)*180/Math.PI;(ye>90||ye<-90)&&(ye+=180);const Me=typeof p=="number"&&Number.isFinite(p)?ye-p:ye;let ve=0;if(s&&typeof p=="number"&&Number.isFinite(p)){const Ce=s.length*a*iKo,Le=a,Ye=p*Math.PI/180,tt=Math.abs(Math.sin(Ye)),At=Math.abs(Math.cos(Ye)),at=Ce/2,nt=Le/2;ve=at*tt+nt*At+a*rKo}const he=_*oKo+ve,Qe={x:le.x+I.x*he,y:le.y+I.y*he},[Pe,we]=hn(n,[Qe.x,Qe.y]),Te=a*Math.abs(n.a),Re=[...ne,{name:"path",type:"element",value:"",attributes:{d:`M ${O} ${U} L ${Y} ${W}`,stroke:j,fill:"none","stroke-width":te.toString(),"stroke-linecap":"round",class:"pcb-fabrication-note-dimension-line"},children:[]},{name:"path",type:"element",value:"",attributes:{d:`${QYt(R)} Z`,fill:j,class:"pcb-fabrication-note-dimension-arrow"},children:[]},{name:"path",type:"element",value:"",attributes:{d:`${QYt(F)} Z`,fill:j,class:"pcb-fabrication-note-dimension-arrow"},children:[]}];s&&Re.push({name:"text",type:"element",value:"",attributes:{x:Pe.toString(),y:we.toString(),fill:j,"font-size":Te.toString(),"font-family":pq,"text-anchor":"middle","dominant-baseline":"central",class:"pcb-fabrication-note-dimension-text",transform:`rotate(${Me} ${Pe} ${we})`},children:[{type:"text",name:"",value:s,attributes:{},children:[]}]});const Ee={class:"pcb-fabrication-note-dimension","data-type":"pcb_fabrication_note_dimension","data-pcb-fabrication-note-dimension-id":g,"data-pcb-layer":l??"overlay"};return u!==void 0&&(Ee["data-pcb-component-id"]=u),[{name:"g",type:"element",value:"",attributes:Ee,children:Re}];function ke(Ce){const[Le,Ye]=hn(n,[Ce.x,Ce.y]);return{x:Le,y:Ye}}}var Lg={"3d_viewer":{background_bottom:"rgb(102, 102, 128)",background_top:"rgb(204, 204, 230)",board:"rgb(51, 43, 23)",copper:"rgb(179, 156, 0)",silkscreen_bottom:"rgb(230, 230, 230)",silkscreen_top:"rgb(230, 230, 230)",soldermask:"rgb(20, 51, 36)",solderpaste:"rgb(128, 128, 128)"},board:{anchor:"rgb(255, 38, 226)",aux_items:"rgb(255, 255, 255)",b_adhes:"rgb(0, 0, 132)",b_crtyd:"rgb(255, 38, 226)",b_fab:"rgb(88, 93, 132)",b_mask:"rgba(2, 255, 238, 0.400)",b_paste:"rgb(0, 194, 194)",b_silks:"rgb(232, 178, 167)",background:"rgb(0, 16, 35)",cmts_user:"rgb(89, 148, 220)",copper:{b:"rgb(77, 127, 196)",f:"rgb(200, 52, 52)",in1:"rgb(127, 200, 127)",in10:"rgb(237, 124, 51)",in11:"rgb(91, 195, 235)",in12:"rgb(247, 111, 142)",in13:"rgb(167, 165, 198)",in14:"rgb(40, 204, 217)",in15:"rgb(232, 178, 167)",in16:"rgb(242, 237, 161)",in17:"rgb(237, 124, 51)",in18:"rgb(91, 195, 235)",in19:"rgb(247, 111, 142)",in2:"rgb(206, 125, 44)",in20:"rgb(167, 165, 198)",in21:"rgb(40, 204, 217)",in22:"rgb(232, 178, 167)",in23:"rgb(242, 237, 161)",in24:"rgb(237, 124, 51)",in25:"rgb(91, 195, 235)",in26:"rgb(247, 111, 142)",in27:"rgb(167, 165, 198)",in28:"rgb(40, 204, 217)",in29:"rgb(232, 178, 167)",in3:"rgb(79, 203, 203)",in30:"rgb(242, 237, 161)",in4:"rgb(219, 98, 139)",in5:"rgb(167, 165, 198)",in6:"rgb(40, 204, 217)",in7:"rgb(232, 178, 167)",in8:"rgb(242, 237, 161)",in9:"rgb(141, 203, 129)"},cursor:"rgb(255, 255, 255)",drc:"rgb(194, 194, 194)",drc_error:"rgba(215, 91, 107, 0.800)",drc_exclusion:"rgb(255, 255, 255)",drc_warning:"rgba(255, 208, 66, 0.902)",dwgs_user:"rgb(194, 194, 194)",eco1_user:"rgb(180, 219, 210)",eco2_user:"rgb(216, 200, 82)",edge_cuts:"rgb(208, 210, 205)",f_adhes:"rgb(132, 0, 132)",f_crtyd:"rgb(255, 0, 245)",f_fab:"rgb(175, 175, 175)",f_mask:"rgba(216, 100, 255, 0.400)",f_paste:"rgba(180, 160, 154, 0.902)",f_silks:"rgb(242, 237, 161)",footprint_text_back:"rgb(0, 0, 132)",footprint_text_front:"rgb(194, 194, 194)",footprint_text_invisible:"rgb(132, 132, 132)",grid:"rgb(132, 132, 132)",grid_axes:"rgb(194, 194, 194)",margin:"rgb(255, 38, 226)",microvia:"rgb(0, 132, 132)",no_connect:"rgb(0, 0, 132)",pad_back:"rgb(77, 127, 196)",pad_front:"rgb(200, 52, 52)",pad_plated_hole:"rgb(194, 194, 0)",pad_through_hole:"rgb(227, 183, 46)",plated_hole:"rgb(26, 196, 210)",ratsnest:"rgba(245, 255, 213, 0.702)",select_overlay:"rgb(4, 255, 67)",through_via:"rgb(236, 236, 236)",user_1:"rgb(194, 194, 194)",user_2:"rgb(89, 148, 220)",user_3:"rgb(180, 219, 210)",user_4:"rgb(216, 200, 82)",user_5:"rgb(194, 194, 194)",user_6:"rgb(89, 148, 220)",user_7:"rgb(180, 219, 210)",user_8:"rgb(216, 200, 82)",user_9:"rgb(232, 178, 167)",via_blind_buried:"rgb(187, 151, 38)",via_hole:"rgb(227, 183, 46)",via_micro:"rgb(0, 132, 132)",via_through:"rgb(236, 236, 236)",worksheet:"rgb(200, 114, 171)"},gerbview:{axes:"rgb(0, 0, 132)",background:"rgb(0, 0, 0)",dcodes:"rgb(255, 255, 255)",grid:"rgb(132, 132, 132)",layers:["rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)","rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)","rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)","rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)"],negative_objects:"rgb(132, 132, 132)",worksheet:"rgb(0, 0, 132)"},meta:{filename:"kicad_2020",name:"KiCad 2020",version:2},simulation_palette:["#1f77b4","#d62728","#2ca02c","#ff7f0e","#9467bd","#17becf","#8c564b","#e377c2","#7f7f7f","#bcbd22"],palette:["rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)"],schematic:{aux_items:"rgb(46, 46, 46)",background:"rgb(245, 241, 237)",brightened:"rgb(255, 0, 255)",bus:"rgb(0, 0, 132)",bus_junction:"rgb(0, 0, 132)",component_body:"rgb(255, 255, 194)",component_outline:"rgb(132, 0, 0)",cursor:"rgb(15, 15, 15)",erc_error:"rgba(230, 9, 13, 0.800)",erc_warning:"rgba(209, 146, 0, 0.800)",fields:"rgb(132, 0, 132)",grid:"rgb(181, 181, 181)",grid_axes:"rgb(0, 0, 132)",hidden:"rgb(194, 194, 194)",junction:"rgb(0, 150, 0)",label_global:"rgb(132, 0, 0)",label_background:"rgba(255, 255, 255, 0.6)",label_hier:"rgb(114, 86, 0)",label_local:"rgb(15, 15, 15)",net_name:"rgb(132, 132, 132)",no_connect:"rgb(132, 0, 0)",note:"rgb(0, 0, 194)",override_item_colors:!1,pin:"rgb(132, 0, 0)",pin_name:"rgb(0, 100, 100)",pin_number:"rgb(169, 0, 0)",reference:"rgb(0, 100, 100)",shadow:"rgba(102, 179, 255, 0.800)",sheet:"rgb(132, 0, 0)",sheet_background:"rgba(253, 255, 231, 0.000)",sheet_fields:"rgb(132, 0, 132)",sheet_filename:"rgb(114, 86, 0)",sheet_label:"rgb(0, 100, 100)",sheet_name:"rgb(0, 100, 100)",table:"rgb(102, 102, 102)",value:"rgb(0, 100, 100)",wire:"rgb(0, 150, 0)",wire_crossing:"rgb(30, 180, 30)",worksheet:"rgb(132, 0, 0)"}};function fRe(t){const e=Math.hypot(t.x,t.y)||1;return{x:t.x/e,y:t.y/e}}function vYt(t){return t.map((e,n)=>n===0?`M ${e.x} ${e.y}`:`L ${e.x} ${e.y}`).join(" ")}function aKo(t,e){const{transform:n}=e,{from:o,to:i,text:r,font_size:s=1,color:a,arrow_size:A,offset_distance:c,offset_direction:l,text_ccw_rotation:u}=t;if(!o||!i)return cm(`[pcb_note_dimension] Invalid endpoints for "${t.pcb_note_dimension_id}": expected {from: {x, y}, to: {x, y}}, got from=${JSON.stringify(o)}, to=${JSON.stringify(i)}`),[];if(!Number.isFinite(A)||A<=0)return cm(`[pcb_note_dimension] Invalid arrow_size for "${t.pcb_note_dimension_id}": expected positive number, got ${JSON.stringify(A)}`),[];const g=fRe({x:i.x-o.x,y:i.y-o.y});if(Number.isNaN(g.x)||Number.isNaN(g.y))return[];const h={x:-g.y,y:g.x},d=l&&typeof l.x=="number"&&typeof l.y=="number",p=d?fRe({x:l.x,y:l.y}):{x:0,y:0},m=typeof c=="number"?c:0,_={x:p.x*m,y:p.y*m},f=Qe=>({x:Qe.x+_.x,y:Qe.y+_.y}),I=f(o),C=f(i),y=A/2,x={x:I.x+g.x*A,y:I.y+g.y*A},E={x:C.x-g.x*A,y:C.y-g.y*A},B=[he(I),he({x:x.x+h.x*y,y:x.y+h.y*y}),he({x:x.x-h.x*y,y:x.y-h.y*y})],S=[he(C),he({x:E.x+h.x*y,y:E.y+h.y*y}),he({x:E.x-h.x*y,y:E.y-h.y*y})],[Q,w]=hn(n,[x.x,x.y]),[M,k]=hn(n,[E.x,E.y]),R=A/5*Math.abs(n.a),F=a||Lg.board.user_2,O=d&&(Math.abs(p.x)>Number.EPSILON||Math.abs(p.y)>Number.EPSILON)?p:h,U=m+A,Y=Qe=>{const Pe={x:Qe.x+O.x*U,y:Qe.y+O.y*U},[we,Te]=hn(n,[Qe.x,Qe.y]),[Re,Ee]=hn(n,[Pe.x,Pe.y]);return{name:"path",type:"element",value:"",attributes:{d:`M ${we} ${Te} L ${Re} ${Ee}`,stroke:F,fill:"none","stroke-width":R.toString(),"stroke-linecap":"round",class:"pcb-note-dimension-extension"},children:[]}},W=[Y(o),Y(i)],te={x:(o.x+i.x)/2+_.x,y:(o.y+i.y)/2+_.y},[j,J]=hn(n,[I.x,I.y]),[oe,ie]=hn(n,[C.x,C.y]),ne=fRe({x:oe-j,y:ie-J});let le=Math.atan2(ne.y,ne.x)*180/Math.PI;(le>90||le<-90)&&(le+=180);const ge=typeof u=="number"&&Number.isFinite(u)?le-u:le;let _e=0;if(r&&typeof u=="number"&&Number.isFinite(u)){const Qe=r.length*s*.6,Pe=s,we=u*Math.PI/180,Te=Math.abs(Math.sin(we)),Re=Math.abs(Math.cos(we)),Ee=Qe/2,ke=Pe/2;_e=Ee*Te+ke*Re+s*.3}const ue=A*1.5+_e,fe={x:te.x+h.x*ue,y:te.y+h.y*ue},[pe,ye]=hn(n,[fe.x,fe.y]),Me=s*Math.abs(n.a),ve=[...W,{name:"path",type:"element",value:"",attributes:{d:`M ${Q} ${w} L ${M} ${k}`,stroke:F,fill:"none","stroke-width":R.toString(),"stroke-linecap":"round",class:"pcb-note-dimension-line"},children:[]},{name:"path",type:"element",value:"",attributes:{d:`${vYt(B)} Z`,fill:F,class:"pcb-note-dimension-arrow"},children:[]},{name:"path",type:"element",value:"",attributes:{d:`${vYt(S)} Z`,fill:F,class:"pcb-note-dimension-arrow"},children:[]}];return r&&ve.push({name:"text",type:"element",value:"",attributes:{x:pe.toString(),y:ye.toString(),fill:F,"font-size":Me.toString(),"font-family":"Arial, sans-serif","text-anchor":"middle","dominant-baseline":"central",class:"pcb-note-dimension-text",transform:`rotate(${ge} ${pe} ${ye})`},children:[{type:"text",name:"",value:r,attributes:{},children:[]}]}),[{name:"g",type:"element",value:"",attributes:{class:"pcb-note-dimension","data-type":"pcb_note_dimension","data-pcb-note-dimension-id":t.pcb_note_dimension_id,"data-pcb-layer":"overlay"},children:ve}];function he(Qe){const[Pe,we]=hn(n,[Qe.x,Qe.y]);return{x:Pe,y:we}}}var AKo=Lg.board.user_2;function cKo(t,e){const{transform:n}=e,{anchor_position:o,text:i,font_size:r=1,anchor_alignment:s="center",color:a}=t;if(!o||typeof o.x!="number"||typeof o.y!="number")return cm(`[pcb_note_text] Invalid anchor_position for "${t.pcb_note_text_id}": expected {x: number, y: number}, got ${JSON.stringify(o)}`),[];if(typeof i!="string"||i.length===0)return cm(`[pcb_note_text] Invalid text for "${t.pcb_note_text_id}": expected non-empty string, got ${JSON.stringify(i)}`),[];const[A,c]=hn(n,[o.x,o.y]),l=r*Math.abs(n.a),{textAnchor:u,dominantBaseline:g}=SYt(s),h=i.split(`
`),d=h.length===1?[{type:"text",name:"",value:i,attributes:{},children:[]}]:h.map((m,_)=>({type:"element",name:"tspan",value:"",attributes:{x:A.toString(),..._>0?{dy:"1em"}:{}},children:[{type:"text",name:"",value:m,attributes:{},children:[]}]}));return[{name:"text",type:"element",value:"",attributes:{x:A.toString(),y:c.toString(),fill:a??AKo,"font-family":"Arial, sans-serif","font-size":l.toString(),"text-anchor":u,"dominant-baseline":g,class:"pcb-note-text","data-type":"pcb_note_text","data-pcb-note-text-id":t.pcb_note_text_id,"data-pcb-layer":"overlay"},children:d}]}var lKo=Lg.board.user_2,uKo=Lg.board.user_2;function gKo(t,e){const{transform:n}=e,{center:o,width:i,height:r,stroke_width:s,is_filled:a,has_stroke:A,is_stroke_dashed:c,color:l,corner_radius:u}=t;if(!o||typeof o.x!="number"||typeof o.y!="number"||typeof i!="number"||typeof r!="number")return cm(`[pcb_note_rect] Invalid data for "${t.pcb_note_rect_id}": expected center {x: number, y: number}, width: number, height: number, got center=${JSON.stringify(o)}, width=${JSON.stringify(i)}, height=${JSON.stringify(r)}`),[];const g=i/2,h=r/2,[d,p]=hn(n,[o.x-g,o.y+h]),[m,_]=hn(n,[o.x+g,o.y-h]),f=Math.min(d,m),I=Math.min(p,_),C=Math.abs(m-d),y=Math.abs(_-p),E=(typeof s=="number"?s:0)*Math.abs(n.a),B=typeof u=="number"&&u>0?u:0,S=B*Math.abs(n.a),Q=B*Math.abs(n.d),w=l??lKo,M={x:f.toString(),y:I.toString(),width:C.toString(),height:y.toString(),class:"pcb-note-rect","data-type":"pcb_note_rect","data-pcb-note-rect-id":t.pcb_note_rect_id,"data-pcb-layer":"overlay"};if(S>0&&(M.rx=S.toString()),Q>0&&(M.ry=Q.toString()),a?M.fill=l??uKo:M.fill="none",A??E>0){if(M.stroke=w,M["stroke-width"]=E.toString(),c){const F=.2*Math.abs(n.a),O=.1*Math.abs(n.a);M["stroke-dasharray"]=`${F} ${O}`}}else M.stroke="none";return[{name:"rect",type:"element",value:"",attributes:M,children:[]}]}var dKo=Lg.board.user_2;function hKo(t,e){const{transform:n}=e;if(!Array.isArray(t.route)||t.route.length===0)return cm(`[pcb_note_path] Invalid route for "${t.pcb_note_path_id}": expected non-empty array of points, got ${JSON.stringify(t.route)}`),[];for(const s of t.route)if(typeof s.x!="number"||typeof s.y!="number")return cm(`[pcb_note_path] Invalid point in route for "${t.pcb_note_path_id}": expected {x: number, y: number}, got ${JSON.stringify(s)}`),[];const o=t.route.map((s,a)=>{const[A,c]=hn(n,[s.x,s.y]);return a===0?`M ${A} ${c}`:`L ${A} ${c}`}).join(" "),i=t.stroke_width*Math.abs(n.a);return[{name:"path",type:"element",value:"",attributes:{d:o,stroke:t.color??dKo,fill:"none","stroke-width":i.toString(),class:"pcb-note-path","data-type":"pcb_note_path","data-pcb-note-path-id":t.pcb_note_path_id,"data-pcb-layer":"overlay"},children:[]}]}var pKo=Lg.board.user_2;function mKo(t,e){const{transform:n}=e,{x1:o,y1:i,x2:r,y2:s,stroke_width:a,color:A,is_dashed:c}=t;if(typeof o!="number"||typeof i!="number"||typeof r!="number"||typeof s!="number")return cm(`[pcb_note_line] Invalid coordinates for "${t.pcb_note_line_id}": expected x1, y1, x2, y2 as numbers, got x1=${JSON.stringify(o)}, y1=${JSON.stringify(i)}, x2=${JSON.stringify(r)}, y2=${JSON.stringify(s)}`),[];const[l,u]=hn(n,[o,i]),[g,h]=hn(n,[r,s]),p=(typeof a=="number"?a:0)*Math.abs(n.a),m={x1:l.toString(),y1:u.toString(),x2:g.toString(),y2:h.toString(),stroke:A??pKo,"stroke-width":p.toString(),"stroke-linecap":"round",class:"pcb-note-line","data-type":"pcb_note_line","data-pcb-note-line-id":t.pcb_note_line_id,"data-pcb-layer":"overlay"};if(c){const f=.2*Math.abs(n.a),I=.1*Math.abs(n.a);m["stroke-dasharray"]=`${f} ${I}`}return[{name:"line",type:"element",value:"",attributes:m,children:[]}]}function wYt(t,e){if(!e)return{};const n=PYt(t,e);if(!n)return{};const o=e.find(a=>a.type==="source_port"&&a.source_port_id===n),i=e.find(a=>a.type==="source_component"&&a.source_component_id===o?.source_component_id),r={};i?.name&&o?.name&&(r["data-pad-name"]=`${i.name}.${o.name}`);const s=fKo(n,e);return s&&(r["data-pad-net-name"]=s),r}function _Ko(t,e){if(e){const i=PYt(t,e),r=e.find(s=>s.type==="source_port"&&s.source_port_id===i);if(r?.type==="source_port"&&r.pin_number!=null)return r.pin_number.toString()}const n=t.port_hints?.find(i=>i.trim().length>0);return n?n.match(/^pin(\d+)$/i)?.[1]??n:void 0}function PYt(t,e){if(t.source_port_id)return t.source_port_id;if(t.pcb_port_id){const i=e.find(r=>r.type==="pcb_port"&&r.pcb_port_id===t.pcb_port_id);if(i?.source_port_id)return i.source_port_id}const n=t.pcb_smtpad_id??t.pcb_plated_hole_id;return n?e.find(i=>{if(i.type!=="pcb_port")return!1;const r=i;return r.pcb_smtpad_id===n||r.pcb_plated_hole_id===n})?.source_port_id:void 0}function fKo(t,e){const o=e.find(r=>r.type!=="source_trace"?!1:r.connected_source_port_ids?.includes(t))?.connected_source_net_ids?.[0];return o?e.find(r=>r.type==="source_net"&&r.source_net_id===o)?.name:void 0}function IKo(t,e){const{transform:n,colorMap:o,showSolderMask:i}=e,[r,s]=hn(n,[t.x,t.y]),a=wYt(t,e.circuitJson),A=Array.isArray(t.layers)&&t.layers[0]||t.layer||"top",c=A,l=!!t.is_covered_with_solder_mask,u=(t.soldermask_margin??0)*Math.abs(n.a),g=i&&l&&u!==0,h=o.soldermaskWithCopperUnderneath.top;if(t.shape==="pill"){const d=t.outer_width*Math.abs(n.a),p=t.outer_height*Math.abs(n.a),m=t.hole_width*Math.abs(n.a),_=t.hole_height*Math.abs(n.a),f=t.ccw_rotation||0,I=f?`translate(${r} ${s}) rotate(${-f})`:`translate(${r} ${s})`,C=f?`translate(${r} ${s}) rotate(${-f})`:`translate(${r} ${s})`,y=(E,B)=>{if(E>B){const S=B/2,Q=E-2*S;return`M${-E/2+S},${-S} h${Q} a${S},${S} 0 0 1 0,${B} h${-Q} a${S},${S} 0 0 1 0,${-B} z`}else if(B>E){const S=E/2,Q=B-2*S;return`M${S},${-B/2+S} v${Q} a${S},${S} 0 0 1 ${-E},0 v${-Q} a${S},${S} 0 0 1 ${E},0 z`}else{const S=E/2;return`M${-S},0 a${S},${S} 0 0 1 ${E},0 a${S},${S} 0 0 1 ${-E},0 z`}};let x=[{name:"path",type:"element",attributes:{class:"pcb-hole-outer",fill:o.copper.top,d:y(d,p),transform:I,"data-type":"pcb_plated_hole","data-pcb-layer":A},value:"",children:[]},{name:"path",type:"element",attributes:{class:"pcb-hole-inner",fill:o.drill,d:y(m,_),transform:C,"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(g){const E=d+2*u,B=p+2*u;u<0?x=[{name:"path",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,d:y(d,p),transform:I,"data-type":"pcb_plated_hole","data-pcb-layer":A},value:"",children:[]},{name:"path",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:o.copper.top,d:y(E,B),transform:I,"data-type":"pcb_soldermask","data-pcb-layer":c},value:"",children:[]},x[1]]:x.unshift({name:"path",type:"element",attributes:{class:"pcb-soldermask-cutout",fill:o.substrate,d:y(E,B),transform:I,"data-type":"pcb_soldermask_opening","data-pcb-layer":c},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through",...a},children:x,value:""}]}if(t.shape==="oval"){const d=t.outer_width*Math.abs(n.a),p=t.outer_height*Math.abs(n.a),m=t.hole_width*Math.abs(n.a),_=t.hole_height*Math.abs(n.a),f=t.ccw_rotation||0,I=f?`translate(${r} ${s}) rotate(${-f})`:`translate(${r} ${s})`,C=[{name:"ellipse",type:"element",attributes:{class:"pcb-hole-outer",fill:o.copper.top,cx:"0",cy:"0",rx:(d/2).toString(),ry:(p/2).toString(),transform:I,"data-type":"pcb_plated_hole","data-pcb-layer":A},value:"",children:[]},{name:"ellipse",type:"element",attributes:{class:"pcb-hole-inner",fill:o.drill,cx:"0",cy:"0",rx:(m/2).toString(),ry:(_/2).toString(),transform:I,"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through",...a},children:C,value:""}]}if(t.shape==="circle"){const d=t.outer_diameter*Math.abs(n.a),p=t.outer_diameter*Math.abs(n.a),m=t.hole_diameter*Math.abs(n.a),_=t.hole_diameter*Math.abs(n.a),f=Math.min(d,p)/2,I=Math.min(m,_)/2;let C=[{name:"circle",type:"element",attributes:{class:"pcb-hole-outer",fill:o.copper.top,cx:r.toString(),cy:s.toString(),r:f.toString(),"data-type":"pcb_plated_hole","data-pcb-layer":A},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pcb-hole-inner",fill:o.drill,cx:r.toString(),cy:s.toString(),r:I.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(g){const y=f+u;u<0?C=[{name:"circle",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,cx:r.toString(),cy:s.toString(),r:f.toString(),"data-type":"pcb_plated_hole","data-pcb-layer":A},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:o.copper.top,cx:r.toString(),cy:s.toString(),r:y.toString(),"data-type":"pcb_soldermask","data-pcb-layer":c},value:"",children:[]},C[1]]:C.unshift({name:"circle",type:"element",attributes:{class:"pcb-soldermask-cutout",fill:o.substrate,cx:r.toString(),cy:s.toString(),r:y.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":c},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through",...a},children:C,value:""}]}if(t.shape==="circular_hole_with_rect_pad"){const d=t,p=t.hole_diameter*Math.abs(n.a),m=t.rect_pad_width*Math.abs(n.a),_=t.rect_pad_height*Math.abs(n.a),f=(t.rect_border_radius??0)*Math.abs(n.a),I=t.rect_ccw_rotation??0,C=d.rect_ccw_rotation??0,y=C?`translate(${r} ${s}) rotate(${-C})`:void 0;C?(-m/2).toString():(r-m/2).toString(),C?(-_/2).toString():(s-_/2).toString();const x=p/2,[E,B]=hn(n,[d.x+(d.hole_offset_x??0),d.y+(d.hole_offset_y??0)]);let S=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-pad",fill:o.copper.top,...I?{x:(-m/2).toString(),y:(-_/2).toString(),transform:`translate(${r} ${s}) rotate(${-I})`}:{x:(r-m/2).toString(),y:(s-_/2).toString()},width:m.toString(),height:_.toString(),...y?{transform:y}:{},...f?{rx:f.toString(),ry:f.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":A},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pcb-hole-inner",fill:o.drill,cx:E.toString(),cy:B.toString(),r:x.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(g){const Q=m+2*u,w=_+2*u,M=f+u;u<0?S=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,...I?{x:(-m/2).toString(),y:(-_/2).toString(),transform:`translate(${r} ${s}) rotate(${-I})`}:{x:(r-m/2).toString(),y:(s-_/2).toString()},width:m.toString(),height:_.toString(),...y?{transform:y}:{},...f?{rx:f.toString(),ry:f.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":A},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:o.copper.top,...I?{x:(-Q/2).toString(),y:(-w/2).toString(),transform:`translate(${r} ${s}) rotate(${-I})`}:{x:(r-Q/2).toString(),y:(s-w/2).toString()},width:Q.toString(),height:w.toString(),...y?{transform:y}:{},...M>0?{rx:M.toString(),ry:M.toString()}:{},"data-type":"pcb_soldermask","data-pcb-layer":c},value:"",children:[]},S[1]]:S.unshift({name:"rect",type:"element",attributes:{class:"pcb-soldermask-cutout",fill:o.substrate,...I?{x:(-Q/2).toString(),y:(-w/2).toString(),transform:`translate(${r} ${s}) rotate(${-I})`}:{x:(r-Q/2).toString(),y:(s-w/2).toString()},width:Q.toString(),height:w.toString(),...y?{transform:y}:{},...f?{rx:M.toString(),ry:M.toString()}:{},"data-type":"pcb_soldermask_opening","data-pcb-layer":c},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through",...a},children:S,value:""}]}if(t.shape==="pill_hole_with_rect_pad"){const d=t,p=d.rect_pad_width*Math.abs(n.a),m=d.rect_pad_height*Math.abs(n.a),_=(d.rect_border_radius??0)*Math.abs(n.a),f=d.hole_height*Math.abs(n.a),I=d.hole_width*Math.abs(n.a),C=d,y=C.hole_offset_x??0,x=C.hole_offset_y??0,[E,B]=hn(n,[d.x+y,d.y+x]),S=Math.min(f,I)/2;let Q=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-pad",fill:o.copper.top,x:(r-p/2).toString(),y:(s-m/2).toString(),width:p.toString(),height:m.toString(),..._?{rx:_.toString(),ry:_.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":A},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-inner",fill:o.drill,x:(E-I/2).toString(),y:(B-f/2).toString(),width:I.toString(),height:f.toString(),rx:S.toString(),ry:S.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(g){const w=p+2*u,M=m+2*u,k=_+u;u<0?Q=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,x:(r-p/2).toString(),y:(s-m/2).toString(),width:p.toString(),height:m.toString(),..._?{rx:_.toString(),ry:_.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":A},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:o.copper.top,x:(r-w/2).toString(),y:(s-M/2).toString(),width:w.toString(),height:M.toString(),...k>0?{rx:k.toString(),ry:k.toString()}:{},"data-type":"pcb_soldermask","data-pcb-layer":c},value:"",children:[]},Q[1]]:Q.unshift({name:"rect",type:"element",attributes:{class:"pcb-soldermask-cutout",fill:o.substrate,x:(r-w/2).toString(),y:(s-M/2).toString(),width:w.toString(),height:M.toString(),..._?{rx:k.toString(),ry:k.toString()}:{},"data-type":"pcb_soldermask_opening","data-pcb-layer":c},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through",...a},children:Q,value:""}]}if(t.shape==="rotated_pill_hole_with_rect_pad"){const d=t,p=d.rect_pad_width*Math.abs(n.a),m=d.rect_pad_height*Math.abs(n.a),_=(d.rect_border_radius??0)*Math.abs(n.a),f=d.hole_height*Math.abs(n.a),I=d.hole_width*Math.abs(n.a),C=d,y=C.hole_offset_x??0,x=C.hole_offset_y??0,[E,B]=hn(n,[d.x+y,d.y+x]),S=Math.min(f,I)/2;let Q=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-pad",fill:o.copper.top,x:(-p/2).toString(),y:(-m/2).toString(),width:p.toString(),height:m.toString(),transform:`translate(${r} ${s}) rotate(${-d.rect_ccw_rotation})`,..._?{rx:_.toString(),ry:_.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":A},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-inner",fill:o.drill,x:(-I/2).toString(),y:(-f/2).toString(),width:I.toString(),height:f.toString(),rx:S.toString(),ry:S.toString(),transform:`translate(${E} ${B}) rotate(${-d.hole_ccw_rotation})`,"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(g){const w=p+2*u,M=m+2*u,k=_+u;u<0?Q=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,x:(-p/2).toString(),y:(-m/2).toString(),width:p.toString(),height:m.toString(),transform:`translate(${r} ${s}) rotate(${-d.rect_ccw_rotation})`,..._?{rx:_.toString(),ry:_.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":A},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:o.copper.top,x:(-w/2).toString(),y:(-M/2).toString(),width:w.toString(),height:M.toString(),transform:`translate(${r} ${s}) rotate(${-d.rect_ccw_rotation})`,...k>0?{rx:k.toString(),ry:k.toString()}:{},"data-type":"pcb_soldermask","data-pcb-layer":c},value:"",children:[]},Q[1]]:Q.push({name:"rect",type:"element",attributes:{class:"pcb-solder-mask",fill:h,x:(-w/2).toString(),y:(-M/2).toString(),width:w.toString(),height:M.toString(),transform:`translate(${r} ${s}) rotate(${-d.rect_ccw_rotation})`,..._?{rx:k.toString(),ry:k.toString()}:{},"data-type":"pcb_soldermask","data-pcb-layer":c},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through",...a},children:Q,value:""}]}if(t.shape==="hole_with_polygon_pad"){const d=t,p=d.pad_outline||[],m=d.x??0,_=d.y??0,I=p.map(E=>hn(n,[m+E.x,_+E.y])).map(E=>E.join(",")).join(" "),[C,y]=hn(n,[m+d.hole_offset_x,_+d.hole_offset_y]),x=()=>{if(d.hole_shape==="circle"){const B=(d.hole_diameter??0)*Math.abs(n.a)/2;return{name:"circle",type:"element",attributes:{class:"pcb-hole-inner",fill:o.drill,cx:C.toString(),cy:y.toString(),r:B.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}}if(d.hole_shape==="oval"){const E=(d.hole_width??0)*Math.abs(n.a),B=(d.hole_height??0)*Math.abs(n.a),S=E/2,Q=B/2;return{name:"ellipse",type:"element",attributes:{class:"pcb-hole-inner",fill:o.drill,cx:C.toString(),cy:y.toString(),rx:S.toString(),ry:Q.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}}if(d.hole_shape==="pill"||d.hole_shape==="rotated_pill"){const E=(d.hole_width??0)*Math.abs(n.a),B=(d.hole_height??0)*Math.abs(n.a),S=E>B,Q=Math.min(E,B)/2,w=Math.abs(S?E-B:B-E),M=S?`M${-w/2},${-Q} h${w} a${Q},${Q} 0 0 1 0,${B} h-${w} a${Q},${Q} 0 0 1 0,-${B} z`:`M${-Q},${-w/2} v${w} a${Q},${Q} 0 0 0 ${E},0 v-${w} a${Q},${Q} 0 0 0 -${E},0 z`;return{name:"path",type:"element",attributes:{class:"pcb-hole-inner",fill:o.drill,d:M,transform:`translate(${C} ${y})`,"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}}return{name:"g",type:"element",attributes:{},value:"",children:[]}};return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through",...a},children:[{name:"polygon",type:"element",attributes:{class:"pcb-hole-outer-pad",fill:o.copper.top,points:I,"data-type":"pcb_plated_hole","data-pcb-layer":A},value:"",children:[]},x()],value:""}]}return[]}function CKo(t,e){const{transform:n,layer:o,colorMap:i}=e;if(!t.route||!Array.isArray(t.route))return[];let r=t.route.map((l,u)=>{const[g,h]=hn(n,[l.x,l.y]);return u===0?`M ${g} ${h}`:`L ${g} ${h}`}).join(" ");const s=t.route[0],a=t.route[t.route.length-1];s&&a&&s.x===a.x&&s.y===a.y&&(r+=" Z");const A=t.layer||"top";if(o&&A!==o)return[];const c=A==="bottom"?i.silkscreen.bottom:i.silkscreen.top;return[{name:"path",type:"element",attributes:{class:`pcb-silkscreen pcb-silkscreen-${A}`,d:r,fill:"none",stroke:c,"stroke-width":(t.stroke_width*Math.abs(n.a)).toString(),"stroke-linecap":"round","stroke-linejoin":"round","data-pcb-component-id":t.pcb_component_id,"data-pcb-silkscreen-path-id":t.pcb_silkscreen_path_id,"data-type":"pcb_silkscreen_path","data-pcb-layer":A},value:"",children:[]}]}function jge(t,e){if(t.length===0)return"";const n=t.map(i=>{const[r,s]=hn(e,[i.x,i.y]);return{...i,x:r,y:s}});let o=`M ${n[0].x} ${n[0].y}`;for(let i=0;i<n.length;i++){const r=n[i],s=n[(i+1)%n.length];if(r.bulge){if(Math.hypot(s.x-r.x,s.y-r.y)<1e-9)continue;const a=r.bulge,A=s.x-r.x,c=s.y-r.y,l=Math.hypot(A,c),u=Math.abs(l/4/a*(a*a+1)),g=a<0?1:0,h=Math.abs(a)>1?1:0;o+=` A ${u} ${u} 0 ${h} ${g} ${s.x} ${s.y}`}else o+=` L ${s.x} ${s.y}`}return o+=" Z",o}function yKo(t,e){const{transform:n,layer:o,colorMap:i}=e,{layer:r="top"}=t;if(o&&r!==o)return[];if(t.shape!=="brep")return[];const s=r==="bottom"?i.silkscreen.bottom:i.silkscreen.top;let a=jge(t.brep_shape.outer_ring.vertices,n);for(const A of t.brep_shape.inner_rings??[])a+=` ${jge(A.vertices,n)}`;return[{name:"path",type:"element",attributes:{class:`pcb-silkscreen pcb-silkscreen-${r}`,d:a,fill:s,"fill-rule":"evenodd",stroke:"none","data-pcb-component-id":t.pcb_component_id,"data-pcb-silkscreen-graphic-id":t.pcb_silkscreen_graphic_id,"data-type":"pcb_silkscreen_graphic","data-pcb-layer":r},value:"",children:[]}]}function MYt(t){const{text:e,anchorAlignment:n,fontSize:o,charAdvance:i,spaceAdvance:r,trailingSpacing:s,lineHeight:a,mapSegment:A}=t,c=e.split(`
`),l=c.length*a,u=c.map(f=>xKo(f,i,r,s)),g=[];let h=-l/2;for(let f=0;f<c.length;f++){const I=c[f]??"";let y=-(u[f]??0)/2;for(const x of I){if(x===" "){y+=r;continue}const E=Ov[x];if(E)for(const B of E)g.push(A(B,y,h,o));y+=i}h+=a}const d=EKo(g);if(!d)return{pathData:"",bounds:null};const p=IRe(n,d),m=SKo(g,p),_=QKo(d,p);return{pathData:vKo(m),bounds:_}}function xKo(t,e,n,o){let i=0;for(const r of t)i+=r===" "?n:e;return i>0?i-o:0}function EKo(t){if(t.length===0)return null;let e=Number.POSITIVE_INFINITY,n=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(const r of t)e=Math.min(e,r.x1,r.x2),n=Math.min(n,r.y1,r.y2),o=Math.max(o,r.x1,r.x2),i=Math.max(i,r.y1,r.y2);return{minX:e,minY:n,maxX:o,maxY:i}}function IRe(t,e){return{x:-BKo(t,e),y:-bKo(t,e)}}function BKo(t,e){return t==="top_left"||t==="center_left"||t==="bottom_left"?e.minX:t==="top_right"||t==="center_right"||t==="bottom_right"?e.maxX:(e.minX+e.maxX)/2}function bKo(t,e){return t==="top_left"||t==="top_center"||t==="top_right"?e.minY:t==="bottom_left"||t==="bottom_center"||t==="bottom_right"?e.maxY:(e.minY+e.maxY)/2}function SKo(t,e){return e.x===0&&e.y===0?t:t.map(n=>({x1:n.x1+e.x,y1:n.y1+e.y,x2:n.x2+e.x,y2:n.y2+e.y}))}function QKo(t,e){return{minX:t.minX+e.x,minY:t.minY+e.y,maxX:t.maxX+e.x,maxY:t.maxY+e.y}}function vKo(t){return t.map(e=>`M${e.x1} ${e.y1}L${e.x2} ${e.y2}`).join(" ")}var DYt=.94,$ge=.09/2,NYt=Object.fromEntries(Object.entries(Ov).map(([t,e])=>{const n=e.flatMap(i=>[i.x1,i.x2]),o=e.flatMap(i=>[i.y1,i.y2]);return[t,e.length?{minX:Math.min(...n)-$ge,maxX:Math.max(...n)+$ge,minY:-(Math.max(...o)+$ge)*DYt,maxY:-(Math.min(...o)-$ge)*DYt}:null]})),RYt=Math.round(Math.max(...Object.values(NYt).map(t=>t?t.maxX-t.minX:0))*1e3)/1e3;function wKo(t,e){let n=null;const i=t.split(`
`).map((r,s)=>{const a=Array.from(r),A=-(a.length*RYt*e)/2,c=s*e*1.1;return a.forEach((l,u)=>{const g=NYt[l];if(!g)return;const h=A+u*RYt*e,d={minX:h+g.minX*e,maxX:h+g.maxX*e,minY:c+g.minY*e,maxY:c+g.maxY*e};n=n?{minX:Math.min(n.minX,d.minX),maxX:Math.max(n.maxX,d.maxX),minY:Math.min(n.minY,d.minY),maxY:Math.max(n.maxY,d.maxY)}:d}),{name:"tspan",type:"element",value:"",attributes:{x:A.toString(),y:c.toString()},children:[{name:"",type:"text",value:r,attributes:{},children:[]}]}});return{bounds:n,textNode:{name:"text",type:"element",value:"",attributes:{"font-family":pq,"font-size":e.toString(),"text-anchor":"start","dominant-baseline":"alphabetic","xml:space":"preserve",fill:"black",stroke:"none"},children:i}}}var PKo=0;function MKo(t,e){const{transform:n,layer:o,colorMap:i}=e,{anchor_position:r,text:s,font_size:a=1,layer:A="top",ccw_rotation:c=0,anchor_alignment:l="center",is_knockout:u=!1,knockout_padding:g,is_mirrored:h=!1}=t;if(o&&A!==o)return[];if(!r||typeof r.x!="number"||typeof r.y!="number")return cm(`[pcb_silkscreen_text] Invalid anchor_position for "${t.pcb_silkscreen_text_id}": expected {x: number, y: number}, got ${JSON.stringify(r)}`),[];if(!s)return[];const[d,p]=hn(n,[r.x,r.y]),m=Math.abs(n.a),_=A==="bottom"?i.silkscreen.bottom:i.silkscreen.top,I=A==="bottom"?!0:h===!0;if(u){const Q=wKo(s,a);if(!Q.bounds)return[];const w=g?.left??a*.5,M=g?.right??a*.5,k=g?.top??a*.3,R=g?.bottom??a*.3,F=Q.bounds.minX-w,O=Q.bounds.minY-k,U=Q.bounds.maxX-Q.bounds.minX+w+M,Y=Q.bounds.maxY-Q.bounds.minY+k+R,W={minX:F,minY:O,maxX:F+U,maxY:O+Y},te=IRe(l,W),j=F+te.x,J=O+te.y,oe=[{name:"rect",type:"element",value:"",attributes:{x:F.toString(),y:O.toString(),width:U.toString(),height:Y.toString(),fill:"white"},children:[]},Q.textNode],ne=te.x!==0||te.y!==0?[{name:"g",type:"element",value:"",attributes:{transform:`translate(${te.x} ${te.y})`},children:oe}]:oe,le=$b(m0(of(d,p),jb(-c*Math.PI/180),...I?[kx(-1,1)]:[],kx(m,m))),ge=`silkscreen-knockout-mask-${t.pcb_silkscreen_text_id}-${PKo++}`;return[{name:"defs",type:"element",value:"",children:[{name:"mask",type:"element",value:"",attributes:{id:ge},children:ne}],attributes:{}},{name:"rect",type:"element",value:"",children:[],attributes:{x:j.toString(),y:J.toString(),width:U.toString(),height:Y.toString(),fill:_,mask:`url(#${ge})`,transform:le,class:`pcb-silkscreen-text-knockout pcb-silkscreen-${A}`,"data-type":"pcb_silkscreen_text","data-pcb-silkscreen-text-id":t.pcb_silkscreen_text_id,"data-pcb-layer":A}}]}const C=a*m;let y="middle",x="central";switch(l){case"top_left":y="start",x="text-before-edge";break;case"top_center":y="middle",x="text-before-edge";break;case"top_right":y="end",x="text-before-edge";break;case"center_left":y="start",x="central";break;case"center_right":y="end",x="central";break;case"bottom_left":y="start",x="text-after-edge";break;case"bottom_center":y="middle",x="text-after-edge";break;case"bottom_right":y="end",x="text-after-edge";break;default:y="middle",x="central";break}const E=m0(of(d,p),jb(-c*Math.PI/180),...I?[kx(-1,1)]:[]),B=s.split(`
`),S=B.length===1?[{type:"text",value:s,name:"",attributes:{},children:[]}]:B.map((Q,w)=>({type:"element",name:"tspan",value:"",attributes:{x:"0",...w>0?{dy:C.toString()}:{}},children:[{type:"text",value:Q,name:"",attributes:{},children:[]}]}));return[{name:"text",type:"element",attributes:{x:"0",y:"0",dx:"0",dy:"0",fill:_,"font-family":pq,"font-size":C.toString(),"text-anchor":y,"dominant-baseline":x,transform:$b(E),class:`pcb-silkscreen-text pcb-silkscreen-${A}`,"data-pcb-silkscreen-text-id":t.pcb_silkscreen_text_id,stroke:"none","data-type":"pcb_silkscreen_text","data-pcb-layer":A},children:S,value:""}]}function DKo(t,e){const{transform:n,layer:o,colorMap:i}=e,{center:r,width:s,height:a,layer:A="top",pcb_silkscreen_rect_id:c,stroke_width:l,is_filled:u,has_stroke:g,is_stroke_dashed:h,corner_radius:d,ccw_rotation:p=0}=t;if(o&&A!==o)return[];if(!r||typeof r.x!="number"||typeof r.y!="number"||typeof s!="number"||typeof a!="number")return cm(`[pcb_silkscreen_rect] Invalid data for "${c}": expected center {x: number, y: number}, width: number, height: number, got center=${JSON.stringify(r)}, width=${JSON.stringify(s)}, height=${JSON.stringify(a)}`),[];const[m,_]=hn(n,[r.x,r.y]),f=typeof d=="number"&&d>0?d:0,I=f*Math.abs(n.a),C=f*Math.abs(n.d),y=s*Math.abs(n.a),x=a*Math.abs(n.d),E=l*Math.abs(n.a),B=A==="bottom"?i.silkscreen.bottom:i.silkscreen.top,S={x:(-y/2).toString(),y:(-x/2).toString(),width:y.toString(),height:x.toString(),class:`pcb-silkscreen-rect pcb-silkscreen-${A}`,"data-pcb-silkscreen-rect-id":c,"data-type":"pcb_silkscreen_rect","data-pcb-layer":A};typeof p=="number"&&p!==0?S.transform=`translate(${m} ${_}) rotate(${-p})`:(S.x=(m-y/2).toString(),S.y=(_-x/2).toString()),I>0&&(S.rx=I.toString()),C>0&&(S.ry=C.toString()),S.fill=u?B:"none";let Q;if(g===void 0?Q=E>0:Q=g,Q){if(S.stroke=B,S["stroke-width"]=E.toString(),h){const M=.1*Math.abs(n.a),k=.05*Math.abs(n.a);S["stroke-dasharray"]=`${M} ${k}`}}else S.stroke="none";return[{name:"rect",type:"element",attributes:S,value:"",children:[]}]}var ch={copper:{top:"rgb(200, 52, 52)",inner1:"rgb(255, 140, 0)",inner2:"rgb(255, 215, 0)",inner3:"rgb(50, 205, 50)",inner4:"rgb(64, 224, 208)",inner5:"rgb(138, 43, 226)",inner6:"rgb(255, 105, 180)",inner7:"rgb(0, 191, 255)",inner8:"rgb(160, 82, 45)",bottom:"rgb(77, 127, 196)"},soldermaskWithCopperUnderneath:{top:"rgb(18, 82, 50)",bottom:"rgb(77, 127, 196)"},soldermask:{top:"rgb(12, 55, 33)",bottom:"rgb(12, 55, 33)"},soldermaskOverCopper:{top:"rgb(52, 135, 73)",bottom:"rgb(52, 135, 73)"},substrate:"rgb(201, 162, 110)",drill:"#FF26E2",silkscreen:{top:"#f2eda1",bottom:"#5da9e9"},boardOutline:"rgba(255, 255, 255, 0.5)",courtyard:{top:"#FF00FF",bottom:"rgb(38, 233, 255)"},keepout:"#FF6B6B",debugComponent:{fill:null,stroke:null}};ch.drill,ch.silkscreen.top,ch.silkscreen.bottom,{...ch.copper};function Fx(t,e=ch){return e.copper[t]??"white"}var NKo={bottom:"rgb(105, 105, 105)",top:"rgb(105, 105, 105)"};function hG(t){return NKo[t]??"rgb(105, 105, 105)"}var qge=1,pG=.2,TYt=1.4,kYt=.53,RKo=0;function TKo(t,e){const{transform:n,layer:o,colorMap:i}=e,{anchor_position:r,text:s,font_size:a="0.2mm",layer:A,ccw_rotation:c=0,anchor_alignment:l="center",is_knockout:u=!1,knockout_padding:g,is_mirrored:h=!1}=t,d=A??"top";if(o&&o!==d)return[];if(!r)return[];if(!s)return[];const[p,m]=hn(n,[r.x,r.y]),_=lt.parse(a)??.2,f=Math.abs(n.a),I=Fx(d,i),y=d==="bottom"?!0:h===!0;if(u){const Q=_*kYt,w=MYt({text:s,anchorAlignment:l,fontSize:Q,charAdvance:(qge+pG)*Q,spaceAdvance:(qge+pG)*Q*.6,trailingSpacing:pG*Q,lineHeight:Q*TYt,mapSegment:(fe,pe,ye,Me)=>({x1:pe+fe.x1*Me,y1:ye+(1-fe.y1)*Me,x2:pe+fe.x2*Me,y2:ye+(1-fe.y2)*Me})});if(!w.bounds||!w.pathData)return[];const M=g?.left??Q*.5,k=g?.right??Q*.5,R=g?.top??Q*.3,F=g?.bottom??Q*.3,O=w.bounds.minX-M,U=w.bounds.minY-R,Y=w.bounds.maxX-w.bounds.minX+M+k,W=w.bounds.maxY-w.bounds.minY+R+F,te=Q*.15,j={minX:O,minY:U,maxX:O+Y,maxY:U+W},J=IRe(l,j),oe=O+J.x,ie=U+J.y,ne=[{name:"rect",type:"element",value:"",attributes:{x:O.toString(),y:U.toString(),width:Y.toString(),height:W.toString(),fill:"white"},children:[]},{name:"path",type:"element",value:"",attributes:{d:w.pathData,fill:"none",stroke:"black","stroke-width":te.toString(),"stroke-linecap":"round","stroke-linejoin":"round"},children:[]}],ge=J.x!==0||J.y!==0?[{name:"g",type:"element",value:"",attributes:{transform:`translate(${J.x} ${J.y})`},children:ne}]:ne,_e=$b(m0(of(p,m),jb(-c*Math.PI/180),...y?[kx(-1,1)]:[],kx(f,f))),ue=`knockout-mask-${t.pcb_copper_text_id}-${RKo++}`;return[{name:"defs",type:"element",value:"",children:[{name:"mask",type:"element",value:"",attributes:{id:ue},children:ge}],attributes:{}},{name:"rect",type:"element",value:"",children:[],attributes:{x:oe.toString(),y:ie.toString(),width:Y.toString(),height:W.toString(),fill:I,mask:`url(#${ue})`,transform:_e,class:`pcb-copper-text-knockout pcb-copper-${d}`,"data-type":"pcb_copper_text","data-pcb-copper-text-id":t.pcb_copper_text_id}}]}const x=_*kYt,E=MYt({text:s,anchorAlignment:l,fontSize:x,charAdvance:(qge+pG)*x,spaceAdvance:(qge+pG)*x*.6,trailingSpacing:pG*x,lineHeight:x*TYt,mapSegment:(Q,w,M,k)=>({x1:w+Q.x1*k,y1:M+(1-Q.y1)*k,x2:w+Q.x2*k,y2:M+(1-Q.y2)*k})});if(!E.pathData)return[];const B=$b(m0(of(p,m),jb(-c*Math.PI/180),...y?[kx(-1,1)]:[],kx(f,f))),S=x*.15;return[{name:"path",type:"element",attributes:{d:E.pathData,fill:"none",stroke:I,"stroke-width":S.toString(),"stroke-linecap":"round","stroke-linejoin":"round",transform:B,class:`pcb-copper-text pcb-copper-${d}`,"data-type":"pcb_copper_text","data-pcb-copper-text-id":t.pcb_copper_text_id},children:[],value:""}]}function kKo(t,e){const{transform:n,layer:o,colorMap:i}=e,{center:r,radius:s,layer:a="top",pcb_silkscreen_circle_id:A,stroke_width:c=1,is_filled:l}=t;if(o&&a!==o)return[];if(!r||typeof r.x!="number"||typeof r.y!="number"||typeof s!="number")return console.error("Invalid PCB Silkscreen Circle data:",{center:r,radius:s}),[];const[u,g]=hn(n,[r.x,r.y]),h=s*Math.abs(n.a),d=c*Math.abs(n.a),p=a==="bottom"?i.silkscreen.bottom:i.silkscreen.top;return[{name:"circle",type:"element",attributes:{cx:u.toString(),cy:g.toString(),r:h.toString(),class:`pcb-silkscreen-circle pcb-silkscreen-${a}`,fill:l?p:"none",stroke:p,"stroke-width":d.toString(),"data-pcb-silkscreen-circle-id":A,"data-type":"pcb_silkscreen_circle","data-pcb-layer":a},value:"",children:[]}]}function FKo(t,e){const{transform:n,layer:o,colorMap:i}=e,{x1:r,y1:s,x2:a,y2:A,stroke_width:c,layer:l="top",pcb_silkscreen_line_id:u}=t;if(o&&l!==o)return[];if(typeof r!="number"||typeof s!="number"||typeof a!="number"||typeof A!="number")return cm(`[pcb_silkscreen_line] Invalid coordinates for "${u}": expected x1, y1, x2, y2 as numbers, got x1=${JSON.stringify(r)}, y1=${JSON.stringify(s)}, x2=${JSON.stringify(a)}, y2=${JSON.stringify(A)}`),[];const[g,h]=hn(n,[r,s]),[d,p]=hn(n,[a,A]),m=c*Math.abs(n.a),_=l==="bottom"?i.silkscreen.bottom:i.silkscreen.top;return[{name:"line",type:"element",attributes:{x1:g.toString(),y1:h.toString(),x2:d.toString(),y2:p.toString(),stroke:_,"stroke-width":m.toString(),class:`pcb-silkscreen-line pcb-silkscreen-${l}`,"data-pcb-silkscreen-line-id":u,"data-type":"pcb_silkscreen_line","data-pcb-layer":l},value:"",children:[]}]}function LKo(t,e){const{transform:n,layer:o,colorMap:i}=e,{center:r,width:s,height:a,layer:A="top",pcb_silkscreen_pill_id:c,ccw_rotation:l=0}=t;if(o&&A!==o)return[];const[u,g]=hn(n,[r.x,r.y]),h=s*Math.abs(n.a),d=a*Math.abs(n.d),m=Math.min(s,a)/2,_=m*Math.abs(n.a),f=m*Math.abs(n.d),I=A==="bottom"?i.silkscreen.bottom:i.silkscreen.top;return[{name:"rect",type:"element",attributes:{x:(u-h/2).toString(),y:(g-d/2).toString(),width:h.toString(),height:d.toString(),rx:_.toString(),ry:f.toString(),fill:"none",stroke:I,"stroke-width":(.1*Math.abs(n.a)).toString(),class:`pcb-silkscreen-pill pcb-silkscreen-${A}`,"data-pcb-silkscreen-pill-id":c,"data-type":"pcb_silkscreen_pill","data-pcb-layer":A,...l!==0&&{transform:`rotate(${-l} ${u} ${g})`}},value:"",children:[]}]}function HKo(t,e){const{transform:n,layer:o,colorMap:i}=e,{center:r,radius_x:s,radius_y:a,layer:A="top",pcb_silkscreen_oval_id:c,ccw_rotation:l=0}=t;if(o&&A!==o)return[];if(!r||typeof r.x!="number"||typeof r.y!="number"||typeof s!="number"||typeof a!="number")return cm(`[pcb_silkscreen_oval] Invalid data for "${c}": expected center {x: number, y: number}, radius_x: number, radius_y: number, got center=${JSON.stringify(r)}, radius_x=${JSON.stringify(s)}, radius_y=${JSON.stringify(a)}`),[];const[u,g]=hn(n,[r.x,r.y]),h=s*Math.abs(n.a),d=a*Math.abs(n.d),p=A==="bottom"?i.silkscreen.bottom:i.silkscreen.top;return[{name:"ellipse",type:"element",attributes:{cx:u.toString(),cy:g.toString(),rx:h.toString(),ry:d.toString(),fill:"none",stroke:p,"stroke-width":(.1*Math.abs(n.a)).toString(),class:`pcb-silkscreen-oval pcb-silkscreen-${A}`,"data-pcb-silkscreen-oval-id":c,"data-type":"pcb_silkscreen_oval","data-pcb-layer":A,...l!==0&&{transform:`rotate(${-l} ${u} ${g})`}},value:"",children:[]}]}function OKo(t,e){const{transform:n,layer:o,colorMap:i}=e,{center:r,width:s,height:a,layer:A="top",pcb_courtyard_rect_id:c,ccw_rotation:l=0}=t;if(o&&A!==o)return[];if(!r||typeof r.x!="number"||typeof r.y!="number"||typeof s!="number"||typeof a!="number")return cm(`[pcb_courtyard_rect] Invalid data for "${c}": expected center {x: number, y: number}, width: number, height: number, got center=${JSON.stringify(r)}, width=${JSON.stringify(s)}, height=${JSON.stringify(a)}`),[];const[u,g]=hn(n,[r.x,r.y]),h=s*Math.abs(n.a),d=a*Math.abs(n.d),p=.05*Math.abs(n.a),m=A==="bottom"?i.courtyard.bottom:i.courtyard.top,_={x:(-h/2).toString(),y:(-d/2).toString(),width:h.toString(),height:d.toString(),class:`pcb-courtyard-rect pcb-courtyard-${A}`,"data-pcb-courtyard-rect-id":c,"data-type":"pcb_courtyard_rect","data-pcb-layer":A,"stroke-linejoin":"round"};return typeof l=="number"&&l!==0?_.transform=`translate(${u} ${g}) rotate(${-l})`:(_.x=(u-h/2).toString(),_.y=(g-d/2).toString()),_.fill="none",_.stroke=m,_["stroke-width"]=p.toString(),[{name:"rect",type:"element",attributes:_,value:"",children:[]}]}function GKo(t,e){const{transform:n,layer:o,colorMap:i}=e,{layer:r="top",pcb_courtyard_polygon_id:s,points:a,color:A}=t;if(o&&r!==o)return[];if(!a||a.length===0)return cm(`[pcb_courtyard_polygon] Invalid data for "${s}": expected non-empty array of points, got ${JSON.stringify(a)}`),[];const l=a.map(p=>hn(n,[p.x,p.y])).map(p=>`${p[0]},${p[1]}`).join(" "),u=.05*Math.abs(n.a),g=A??(r==="bottom"?i.courtyard.bottom:i.courtyard.top);return[{name:"polygon",type:"element",attributes:{points:l,class:`pcb-courtyard-polygon pcb-courtyard-${r}`,"data-pcb-courtyard-polygon-id":s,"data-type":"pcb_courtyard_polygon","data-pcb-layer":r,fill:"none",stroke:g,"stroke-width":u.toString(),"stroke-linejoin":"round"},value:"",children:[]}]}function YKo(t,e){const{transform:n,layer:o,colorMap:i}=e,{layer:r,pcb_courtyard_outline_id:s,outline:a}=t;if(o&&r!==o)return[];if(!a||a.length===0)return cm(`[pcb_courtyard_outline] Invalid data for "${s}": expected non-empty array of points, got ${JSON.stringify(a)}`),[];const c=a.map(d=>hn(n,[d.x,d.y])).map(d=>`${d[0]},${d[1]}`).join(" "),l=.05*Math.abs(n.a),u=r==="bottom"?i.courtyard.bottom:i.courtyard.top;return[{name:"polygon",type:"element",attributes:{points:c,class:`pcb-courtyard-outline pcb-courtyard-${r}`,"data-pcb-courtyard-outline-id":s,"data-type":"pcb_courtyard_outline","data-pcb-layer":r,fill:"none",stroke:u,"stroke-width":l.toString(),"stroke-linejoin":"round"},value:"",children:[]}]}function UKo(t,e){const{transform:n,layer:o,colorMap:i}=e,{center:r,radius:s,layer:a="top",pcb_courtyard_circle_id:A}=t;if(o&&a!==o)return[];if(!r||typeof r.x!="number"||typeof r.y!="number"||typeof s!="number")return console.error(`[pcb_courtyard_circle] Invalid data for "${A}": expected center {x: number, y: number}, radius: number, got center=${JSON.stringify(r)}, radius=${JSON.stringify(s)}`),[];const[c,l]=hn(n,[r.x,r.y]),u=s*Math.abs(n.a),g=.05*Math.abs(n.a),h=a==="bottom"?i.courtyard.bottom:i.courtyard.top,d={cx:c.toString(),cy:l.toString(),r:u.toString(),class:`pcb-courtyard-circle pcb-courtyard-${a}`,"data-pcb-courtyard-circle-id":A,"data-type":"pcb_courtyard_circle","data-pcb-layer":a};return d.fill="none",d.stroke=h,d["stroke-width"]=g.toString(),[{name:"circle",type:"element",attributes:d,value:"",children:[]}]}var Lx=1e-9;function KKo(t,e){const{startIsInsideCopperPour:n,endIsInsideCopperPour:o,start:i,end:r}=t;if(n===o)return t;const s=PR(i),a=PR(r),A=zKo(e).flatMap(h=>WKo(h,s,a));if(A.length===0)return t;const c=o?Math.min(...A):Math.max(...A),l=HYt(s,a,c),u=VKo(t.startWidth,t.endWidth,c),g={...t,start:n?l:i,end:o?l:r,startWidth:n?u:t.startWidth,endWidth:o?u:t.endWidth};return $Ko(g.start,g.end)?null:g}function VKo(t,e,n){return t+(e-t)*n}function zKo(t){switch(t.shape){case"rect":return[JKo(t)];case"polygon":return[t.points.map(PR)];case"brep":return[t.brep_shape.outer_ring.vertices.map(OYt),...t.brep_shape.inner_rings.map(e=>e.vertices.map(OYt))]}}function JKo(t){const e=PR(t.center),n=t.width/2,o=t.height/2,i=(t.rotation??0)*Math.PI/180,r=Math.cos(i),s=Math.sin(i);return[{x:-n,y:-o},{x:n,y:-o},{x:n,y:o},{x:-n,y:o}].map(a=>({x:e.x+a.x*r-a.y*s,y:e.y+a.x*s+a.y*r}))}function WKo(t,e,n){const o=[];for(let i=0;i<t.length;i++){const r=t[i],s=t[(i+1)%t.length];if(!r||!s)continue;if(r.bulge){o.push(...jKo(e,n,r,s,r.bulge));continue}const a=FYt(e,n,r,s);a!==null&&o.push(a)}return o}function jKo(t,e,n,o,i){const r=o.x-n.x,s=o.y-n.y,a=Math.hypot(r,s);if(a<Lx||Math.abs(i)<Lx){const C=FYt(t,e,n,o);return C===null?[]:[C]}const A=a*(1-i**2)/(4*i),c={x:(n.x+o.x)/2-s/a*A,y:(n.y+o.y)/2+r/a*A},l=Math.atan2(n.y-c.y,n.x-c.x),u=4*Math.atan(i),g=Math.hypot(n.x-c.x,n.y-c.y),h={x:e.x-t.x,y:e.y-t.y},d={x:t.x-c.x,y:t.y-c.y},p=yRe(h,h);if(p<Lx)return[];const m=2*yRe(d,h),_=yRe(d,d)-g**2,f=m**2-4*p*_;if(f<-Lx)return[];const I=Math.sqrt(Math.max(0,f));return[(-m-I)/(2*p),(-m+I)/(2*p)].filter(C=>{if(C<-Lx||C>1+Lx)return!1;const y=HYt(t,e,C),x=Math.atan2(y.y-c.y,y.x-c.x);return(u>0?LYt(x-l):LYt(l-x))<=Math.abs(u)+Lx})}function FYt(t,e,n,o){const i={x:e.x-t.x,y:e.y-t.y},r={x:o.x-n.x,y:o.y-n.y},s=CRe(i,r);if(Math.abs(s)<Lx)return null;const a={x:n.x-t.x,y:n.y-t.y},A=CRe(a,r)/s,c=CRe(a,i)/s;return A<-Lx||A>1+Lx||c<-Lx||c>1+Lx?null:Math.min(1,Math.max(0,A))}function CRe(t,e){return t.x*e.y-t.y*e.x}function yRe(t,e){return t.x*e.x+t.y*e.y}function LYt(t){const e=2*Math.PI,n=t%e;return n<0?n+e:n}function HYt(t,e,n){return{x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n}}function PR(t){return{x:lt.parse(t.x),y:lt.parse(t.y)}}function OYt(t){return{...PR(t),bulge:t.bulge}}function $Ko(t,e){const n=PR(t),o=PR(e);return Math.abs(n.x-o.x)<Lx&&Math.abs(n.y-o.y)<Lx}function qKo(t){return t.route_type==="through_pad"?[t.start,t.end]:[t]}function XKo(t){const e=[];for(let n=0;n<t.length-1;n++){const o=t[n],i=t[n+1];if(!o||!i)continue;const r=o.route_type==="through_pad"?o.end:o,s=i.route_type==="through_pad"?i.start:i,a=o.route_type==="wire"?o.layer:o.route_type==="through_pad"?o.end_layer:i.route_type==="wire"?i.layer:i.route_type==="through_pad"?i.start_layer:null;if(!a||ZKo(r,s))continue;const A=GYt(o),c=GYt(i),l=xRe(o)??xRe(i)??0,u=xRe(i)??l;e.push({start:r,end:s,layer:a,width:l,startWidth:l,endWidth:u,isInsideCopperPour:A&&c,startIsInsideCopperPour:A,endIsInsideCopperPour:c,copperPourId:A?YYt(o):c?YYt(i):void 0})}for(const n of t)if(!(!n||n.route_type!=="through_pad"))for(const o of new Set([n.start_layer,n.end_layer]))e.push({start:n.start,end:n.end,layer:o,width:n.width,startWidth:n.width,endWidth:n.width,isInsideCopperPour:!1,startIsInsideCopperPour:!1,endIsInsideCopperPour:!1});return e}function xRe(t){return"width"in t?lt.parse(t.width):void 0}function GYt(t){return"is_inside_copper_pour"in t&&t.is_inside_copper_pour===!0}function YYt(t){if("copper_pour_id"in t)return t.copper_pour_id}function ZKo(t,e){const n=lt.parse(t.x),o=lt.parse(t.y),i=lt.parse(e.x),r=lt.parse(e.y);return n===i&&o===r}function eVo(t){const e=[],n=[];for(let o=0;o<t.length;o++){const i=t[o];if(!i)continue;const r=tVo(t,o),s=ERe(-r.y,r.x),a=i.width/2;e.push({x:i.x+s.x*a,y:i.y+s.y*a}),n.push({x:i.x-s.x*a,y:i.y-s.y*a})}return e.concat(n.reverse())}function tVo(t,e){if(t.length<2)return{x:1,y:0};if(e<=0)return Xge(t[0],t[1]);if(e>=t.length-1)return Xge(t[t.length-2],t[t.length-1]);const n=Xge(t[e-1],t[e]),o=Xge(t[e],t[e+1]),i=ERe(n.x+o.x,n.y+o.y);return i.x!==0||i.y!==0?i:n.x!==0||n.y!==0?n:o.x!==0||o.y!==0?o:{x:1,y:0}}function Xge(t,e){if(!t||!e)return{x:1,y:0};const n=ERe(e.x-t.x,e.y-t.y);return n.x===0&&n.y===0?{x:1,y:0}:n}function ERe(t,e){const n=Math.hypot(t,e);return n<=Number.EPSILON?{x:0,y:0}:{x:t/n,y:e/n}}function UYt({elementType:t,shapeAttributes:e,layer:n,fillColor:o,fillOpacity:i,className:r,additionalAttributes:s}){const a={class:r,fill:o,"fill-opacity":i,"data-type":"pcb_soldermask","data-pcb-layer":n,...e,...s};return{name:t,type:"element",value:"",children:[],attributes:a}}function KYt(t,e){const{transform:n,colorMap:o}=e,i=e.layer??"top",r=e.showSolderMask&&(i==="top"||i==="bottom");if(r&&!t.layers.includes(i))return[];const s=t,a=(i==="top"?s.tented_on_top:s.tented_on_bottom)??s.is_tented,[A,c]=hn(n,[t.x,t.y]),l=t.outer_diameter*Math.abs(n.a),u=t.outer_diameter*Math.abs(n.a),g=t.hole_diameter*Math.abs(n.a),h=t.hole_diameter*Math.abs(n.a),d=Math.min(l,u)/2,p=Math.min(g,h)/2,m={name:"g",type:"element",value:"",attributes:{"data-type":"pcb_via","data-pcb-layer":"through"},children:[{name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-hole-outer",fill:o.copper[r?i:"top"],cx:A.toString(),cy:c.toString(),r:d.toString(),"data-type":"pcb_via","data-pcb-layer":r?i:"top"}},{name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-hole-inner",fill:o.drill,cx:A.toString(),cy:c.toString(),r:p.toString(),"data-type":"pcb_via","data-pcb-layer":"drill"}}]};return r&&a&&m.children.push(UYt({elementType:"circle",shapeAttributes:{cx:A.toString(),cy:c.toString(),r:d.toString()},layer:i,fillColor:o.soldermaskWithCopperUnderneath[i],fillOpacity:"1",className:"pcb-via-tenting"})),[m]}function VYt(t,e){if(t.shape==="rect"){const[n,o]=hn(e,[t.center.x,t.center.y]),i=t.width*Math.abs(e.a),r=t.height*Math.abs(e.d),s=-(t.rotation??0);return{elementType:"rect",shapeAttributes:{x:(-i/2).toString(),y:(-r/2).toString(),width:i.toString(),height:r.toString(),transform:$b(m0(of(n,o),jb(s*Math.PI/180)))}}}if(t.shape==="polygon")return!t.points||t.points.length===0?null:{elementType:"polygon",shapeAttributes:{points:t.points.map(o=>hn(e,[o.x,o.y])).map(o=>`${o[0]},${o[1]}`).join(" ")}};if(t.shape==="brep"){const{brep_shape:n}=t;let o=jge(n.outer_ring.vertices,e);for(const i of n.inner_rings??[])o+=` ${jge(i.vertices,e)}`;return{elementType:"path",shapeAttributes:{d:o,"fill-rule":"evenodd"}}}return null}function zYt(t){return`copper-pour-trace-mask-${t}`.replace(/[^a-zA-Z0-9_-]/g,"_")}function nVo({layer:t,circuitJson:e}){for(const n of e)if(!(n.type!=="pcb_copper_pour"||n.layer!==t))return zYt(t)}function oVo({circuitJson:t,transform:e,svgWidth:n,svgHeight:o,usedMaskIds:i}){if(i.size===0)return null;const r=new Map;for(const a of t){if(a.type!=="pcb_copper_pour")continue;const A=a,c=zYt(A.layer);if(!i.has(c))continue;const l=r.get(c);l?l.push(A):r.set(c,[A])}if(r.size===0)return null;const s=[];for(const[a,A]of r){const c=[{name:"rect",type:"element",value:"",children:[],attributes:{x:"0",y:"0",width:n.toString(),height:o.toString(),fill:"#fff"}}];for(const l of A){const u=VYt(l,e);u&&c.push({name:u.elementType,type:"element",value:"",children:[],attributes:{...u.shapeAttributes,fill:"#000"}})}s.push({name:"mask",type:"element",value:"",children:c,attributes:{id:a,maskUnits:"userSpaceOnUse",x:"0",y:"0",width:n.toString(),height:o.toString()}})}return{name:"defs",type:"element",value:"",children:s,attributes:{class:"copper-pour-trace-mask-defs"}}}function iVo(t){const e=[],n=new Map;for(const o of t){const i=o.attributes?.["data-type"],r=o.attributes?.mask;if(!(i==="pcb_trace"||i==="pcb_trace_soldermask")||!r?.includes("#copper-pour-trace-mask-")){e.push(o);continue}let a=n.get(r);if(!a){const d={name:"g",type:"element",value:"",children:[],attributes:{class:"pcb-trace-mask-group",mask:r}};a={object:d,pathsByAttributes:new Map},n.set(r,a),e.push(d)}const{mask:A,d:c="",...l}=o.attributes,u=JSON.stringify(l),g=a.pathsByAttributes.get(u);if(g){g.attributes.d+=` ${c}`;continue}const h={...o,attributes:{...l,d:c}};a.pathsByAttributes.set(u,h),a.object.children.push(h)}return e}function rVo(t,e){const{transform:n,layer:o,colorMap:i,showSolderMask:r}=e;if(!t.route||!Array.isArray(t.route)||t.route.length<2)return[];const s=[],a=gVo(e),A=new Map,c=[];for(const u of XKo(t.route)){let g=u;if(g.isInsideCopperPour)continue;if(g.copperPourId&&g.startIsInsideCopperPour!==g.endIsInsideCopperPour){const d=e.circuitJson?.find(p=>p.type==="pcb_copper_pour"&&p.pcb_copper_pour_id===g.copperPourId);if(d){const p=KKo(g,d);if(!p)continue;g=p}}const h=g.layer;h&&(o&&h!==o||c.push(g))}const l=u=>{A.has(u)||A.set(u,e.circuitJson?nVo({layer:u,circuitJson:e.circuitJson}):void 0);const g=A.get(u);return g?(e.usedCopperPourTraceMaskIds?.add(g),{mask:`url(#${g})`}):{}};if(t.route_thickness_mode==="interpolated")for(const u of sVo(c)){const g=u[0]?.layer;if(!g)continue;const h=aVo(u,n);if(!h)continue;const d=Fx(g,i),p=i.soldermaskWithCopperUnderneath[g];s.push({name:"path",type:"element",value:"",children:[],attributes:{class:r?"pcb-soldermask":"pcb-trace",fill:r?p:d,stroke:"none",d:h,"shape-rendering":"geometricPrecision","data-type":r?"pcb_trace_soldermask":"pcb_trace","data-pcb-layer":g,...l(g)}})}else for(const u of c){const g=hn(n,[u.start.x,u.start.y]),h=hn(n,[u.end.x,u.end.y]),d=u.layer,p=Fx(d,i),m=i.soldermaskWithCopperUnderneath[d],_=u.width?(u.width*Math.abs(n.a)).toString():"0.3",f=l(d);if(r){const I={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask",stroke:m,fill:"none",d:`M ${g[0]} ${g[1]} L ${h[0]} ${h[1]}`,"stroke-width":_,"stroke-linecap":"round","stroke-linejoin":"round","shape-rendering":"crispEdges","data-type":"pcb_trace_soldermask","data-pcb-layer":d,...f}};s.push(I)}else{const I={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-trace",stroke:p,fill:"none",d:`M ${g[0]} ${g[1]} L ${h[0]} ${h[1]}`,"stroke-width":_,"stroke-linecap":"round","stroke-linejoin":"round","shape-rendering":"crispEdges","data-type":"pcb_trace","data-pcb-layer":d,...f}};s.push(I)}}for(const[u,g]of t.route.entries())!g||g.route_type!=="via"||a.has(WYt(g))||s.push(...KYt(cVo(t,g,u,e),e));return s}function sVo(t){const e=[];for(const n of t){const o=e[e.length-1],i=o?.[o.length-1];o&&i?.layer===n.layer&&AVo(i.end,n.start)?o.push(n):e.push([n])}return e}function aVo(t,e){const n=t[0];if(!n)return"";const o=[{x:lt.parse(n.start.x),y:lt.parse(n.start.y),width:n.startWidth},...t.map(A=>({x:lt.parse(A.end.x),y:lt.parse(A.end.y),width:A.endWidth}))],r=eVo(o).map(A=>hn(e,[A.x,A.y])),[s,...a]=r;return s?[`M ${s[0]} ${s[1]}`,...a.map(A=>`L ${A[0]} ${A[1]}`),"Z"].join(" "):""}function AVo(t,e){return lt.parse(t.x)===lt.parse(e.x)&&lt.parse(t.y)===lt.parse(e.y)}function cVo(t,e,n,o){const i=lVo(t.route,n),{holeDiameter:r,outerDiameter:s}=uVo(o,i);return{type:"pcb_via",pcb_via_id:`${t.pcb_trace_id}_route_via_${n}`,pcb_trace_id:t.pcb_trace_id,x:e.x,y:e.y,outer_diameter:s,hole_diameter:r,layers:[e.from_layer,e.to_layer]}}function lVo(t,e){const n=JYt(t,e,-1),o=JYt(t,e,1);return Math.max(n??0,o??0)}function JYt(t,e,n){for(let o=e+n;o>=0&&o<t.length;o+=n){const i=t[o];if(!(!i||!("width"in i)||typeof i.width!="number"))return i.width}}function uVo(t,e){const n=t.circuitJson?.find(c=>c.type==="pcb_board"),o=Zge(n?.min_via_hole_diameter),i=Zge(n?.min_via_pad_diameter),r=Math.max(e,.3),s=Math.max(r*2,.6);return{holeDiameter:o??r,outerDiameter:i??s}}function gVo(t){return new Set(t.circuitJson?.filter(e=>e.type==="pcb_via").map(e=>WYt(e))??[])}function WYt(t){const e=Zge(t.x),n=Zge(t.y);return e!==void 0&&n!==void 0?`${e}:${n}`:`${String(t.x)}:${String(t.y)}`}function Zge(t){if(t==null)return;const e=lt.safeParse(t);return e.success?e.data:void 0}function dVo(t,e){const{transform:n,layer:o,colorMap:i,showSolderMask:r}=e;if(o&&t.layer!==o)return[];const s=wYt(t,e.circuitJson),a=!!t?.is_covered_with_solder_mask,A=r&&a,c=i.soldermaskWithCopperUnderneath[t.layer]??i.soldermaskWithCopperUnderneath.top,l=(t.soldermask_margin??0)*Math.abs(n.a);if(t.shape==="rect"||t.shape==="rotated_rect"){const u=t.width*Math.abs(n.a),g=t.height*Math.abs(n.d),[h,d]=hn(n,[t.x,t.y]),m=(t.corner_radius??t.rect_border_radius??0)*Math.abs(n.a),_={left:(t.soldermask_margin_left??t.soldermask_margin??0)*Math.abs(n.a),right:(t.soldermask_margin_right??t.soldermask_margin??0)*Math.abs(n.a),top:(t.soldermask_margin_top??t.soldermask_margin??0)*Math.abs(n.a),bottom:(t.soldermask_margin_bottom??t.soldermask_margin??0)*Math.abs(n.a)},f=_.left<0||_.right<0||_.top<0||_.bottom<0,I=_.left===0&&_.right===0&&_.top===0&&_.bottom===0;if(t.shape==="rotated_rect"&&t.ccw_rotation){const S={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad",fill:Fx(t.layer,i),x:(-u/2).toString(),y:(-g/2).toString(),width:u.toString(),height:g.toString(),transform:`translate(${h} ${d}) rotate(${-t.ccw_rotation})`,"data-type":"pcb_smtpad","data-pcb-layer":t.layer,...s,...m?{rx:m.toString(),ry:m.toString()}:{}}};if(!A)return[S];const Q=u+_.left+_.right,w=g+_.top+_.bottom,M=m?m+l:0;if(f){const R={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(-u/2).toString(),y:(-g/2).toString(),width:u.toString(),height:g.toString(),transform:`translate(${h} ${d}) rotate(${-t.ccw_rotation})`,"data-type":"pcb_smtpad","data-pcb-layer":t.layer,...m?{rx:m.toString(),ry:m.toString()}:{}}},F={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-exposed",fill:Fx(t.layer,i),x:(-u/2-_.left).toString(),y:(-g/2-_.top).toString(),width:Q.toString(),height:w.toString(),transform:`translate(${h} ${d}) rotate(${-t.ccw_rotation})`,"data-type":"pcb_soldermask","data-pcb-layer":t.layer,...M>0?{rx:M.toString(),ry:M.toString()}:{}}};return[R,F]}return I?[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(-u/2).toString(),y:(-g/2).toString(),width:u.toString(),height:g.toString(),transform:`translate(${h} ${d}) rotate(${-t.ccw_rotation})`,"data-type":"pcb_smtpad","data-pcb-layer":t.layer,...m?{rx:m.toString(),ry:m.toString()}:{}}}]:[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,x:(-u/2-_.left).toString(),y:(-g/2-_.top).toString(),width:Q.toString(),height:w.toString(),transform:`translate(${h} ${d}) rotate(${-t.ccw_rotation})`,...M>0?{rx:M.toString(),ry:M.toString()}:{},"data-type":"pcb_soldermask_opening","data-pcb-layer":t.layer}},S]}const C={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad",fill:Fx(t.layer,i),x:(h-u/2).toString(),y:(d-g/2).toString(),width:u.toString(),height:g.toString(),"data-type":"pcb_smtpad","data-pcb-layer":t.layer,...s,...m?{rx:m.toString(),ry:m.toString()}:{}}};if(!A)return[C];const y=u+_.left+_.right,x=g+_.top+_.bottom,E=m?m+l:0;if(f){const S={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(h-u/2).toString(),y:(d-g/2).toString(),width:u.toString(),height:g.toString(),"data-type":"pcb_smtpad","data-pcb-layer":t.layer,...m?{rx:m.toString(),ry:m.toString()}:{}}},Q={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-exposed",fill:Fx(t.layer,i),x:(h-u/2-_.left).toString(),y:(d-g/2-_.top).toString(),width:y.toString(),height:x.toString(),"data-type":"pcb_soldermask","data-pcb-layer":t.layer,...E>0?{rx:E.toString(),ry:E.toString()}:{}}};return[S,Q]}return I?[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(h-u/2).toString(),y:(d-g/2).toString(),width:u.toString(),height:g.toString(),...E>0?{rx:m.toString(),ry:m.toString()}:{},"data-type":"pcb_smtpad","data-pcb-layer":t.layer}}]:[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,x:(h-u/2-_.left).toString(),y:(d-g/2-_.top).toString(),width:y.toString(),height:x.toString(),...E>0?{rx:E.toString(),ry:E.toString()}:{},"data-type":"pcb_soldermask_opening","data-pcb-layer":t.layer}},C]}if(t.shape==="pill"||t.shape==="rotated_pill"){const u=t.shape==="rotated_pill",g=t.width*Math.abs(n.a),h=t.height*Math.abs(n.d),d=t.radius*Math.abs(n.a),[p,m]=hn(n,[t.x,t.y]),_=u?{transform:`translate(${p} ${m}) rotate(${-(t.ccw_rotation??0)})`}:void 0,f={class:"pcb-pad",fill:Fx(t.layer,i),x:u?(-g/2).toString():(p-g/2).toString(),y:u?(-h/2).toString():(m-h/2).toString(),width:g.toString(),height:h.toString(),rx:d.toString(),ry:d.toString(),"data-type":"pcb_smtpad","data-pcb-layer":t.layer,...s,..._??{}},I={name:"rect",type:"element",value:"",children:[],attributes:f};if(!A)return[I];const C=g+2*l,y=h+2*l,x=d+l;if(l<0){const S={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:u?(-g/2).toString():(p-g/2).toString(),y:u?(-h/2).toString():(m-h/2).toString(),width:g.toString(),height:h.toString(),rx:d.toString(),ry:d.toString(),"data-type":"pcb_smtpad","data-pcb-layer":t.layer,..._??{}}},Q={class:"pcb-pad-exposed",fill:Fx(t.layer,i),x:u?(-C/2).toString():(p-C/2).toString(),y:u?(-y/2).toString():(m-y/2).toString(),width:C.toString(),height:y.toString(),rx:x.toString(),ry:x.toString(),"data-type":"pcb_soldermask","data-pcb-layer":t.layer,..._??{}};return[S,{name:"rect",type:"element",value:"",children:[],attributes:Q}]}if(l===0)return[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:u?(-g/2).toString():(p-g/2).toString(),y:u?(-h/2).toString():(m-h/2).toString(),width:g.toString(),height:h.toString(),rx:d.toString(),ry:d.toString(),"data-type":"pcb_smtpad","data-pcb-layer":t.layer,..._??{}}}];const E={class:"pcb-soldermask-cutout",fill:i.substrate,x:u?(-C/2).toString():(p-C/2).toString(),y:u?(-y/2).toString():(m-y/2).toString(),width:C.toString(),height:y.toString(),rx:x.toString(),ry:x.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":t.layer,..._??{}};return[{name:"rect",type:"element",value:"",children:[],attributes:E},I]}if(t.shape==="circle"){const u=t.radius*Math.abs(n.a),[g,h]=hn(n,[t.x,t.y]),d={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-pad",fill:Fx(t.layer,i),cx:g.toString(),cy:h.toString(),r:u.toString(),"data-type":"pcb_smtpad","data-pcb-layer":t.layer,...s}};if(!A)return[d];const p=u+l;if(l<0){const _={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,cx:g.toString(),cy:h.toString(),r:u.toString(),"data-type":"pcb_smtpad","data-pcb-layer":t.layer}},f={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-pad-exposed",fill:Fx(t.layer,i),cx:g.toString(),cy:h.toString(),r:p.toString(),"data-type":"pcb_soldermask","data-pcb-layer":t.layer}};return[_,f]}return l===0?[{name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,cx:g.toString(),cy:h.toString(),r:u.toString(),"data-type":"pcb_smtpad","data-pcb-layer":t.layer}}]:[{name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,cx:g.toString(),cy:h.toString(),r:p.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":t.layer}},d]}if(t.shape==="polygon"){const u=(t.points??[]).map(p=>hn(n,[p.x,p.y])),g={name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-pad",fill:Fx(t.layer,i),points:u.map(p=>p.join(",")).join(" "),"data-type":"pcb_smtpad","data-pcb-layer":t.layer,...s}};if(!A)return[g];let h=u;if(l!==0){const p=u.reduce((_,f)=>_+f[0],0)/u.length,m=u.reduce((_,f)=>_+f[1],0)/u.length;h=u.map(([_,f])=>{const I=_-p,C=f-m,y=Math.sqrt(I*I+C*C);if(y===0)return[_,f];const x=I/y,E=C/y;return[_+x*l,f+E*l]})}if(l<0){const p={name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,points:u.map(_=>_.join(",")).join(" "),"data-type":"pcb_smtpad","data-pcb-layer":t.layer}},m={name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-pad-exposed",fill:Fx(t.layer,i),points:h.map(_=>_.join(",")).join(" "),"data-type":"pcb_soldermask","data-pcb-layer":t.layer}};return[p,m]}return l===0?[{name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,points:u.map(m=>m.join(",")).join(" "),"data-type":"pcb_smtpad","data-pcb-layer":t.layer}}]:[{name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,points:h.map(p=>p.join(",")).join(" "),"data-type":"pcb_soldermask_opening","data-pcb-layer":t.layer}},g]}return[]}var jYt=.05,hE=4,$Yt=8,qYt=11,mG=1,_G=5,XYt=1.5,ZYt=2,BRe=_G+2,bRe=ZYt+2,_q=_G+hE+6,hVo=15,pVo=10,mVo=.2,_Vo=50;function SRe(t){const{groupAnchorPosition:e,componentPosition:n,transform:o,componentWidth:i=0,componentHeight:r=0,displayXOffset:s,displayYOffset:a}=t,A=[],[c,l]=hn(o,[e.x,e.y]),[u,g]=hn(o,[n.x,n.y]),h=n.x-e.x,d=n.y-e.y,p=Math.abs(o.a),m=i*p,_=r*p;A.push(IVo(c,l));const f=fVo(c,l,u,g);A.push({name:"line",type:"element",attributes:{x1:f.x1.toString(),y1:f.y1.toString(),x2:f.x2.toString(),y2:f.y2.toString(),stroke:"#ffffff","stroke-width":"0.5","stroke-dasharray":"3,3",opacity:"0.5",class:"anchor-offset-connector"},children:[],value:""}),A.push({name:"circle",type:"element",attributes:{cx:u.toString(),cy:g.toString(),r:ZYt.toString(),fill:"#ffffff",opacity:"0.7",class:"anchor-offset-component-marker"},children:[],value:""});const I=Math.abs(g-l),C=Math.abs(u-c),y=Math.sqrt(C*C+I*I),x=_/2+hVo,E=Math.max(x,Math.min(_Vo,y*mVo));let B=d>0?g-E:g+E;const S=m/2+pVo;let Q=h>0?u+S:u-S;if(ede(B,l)||ede(B,g)){const w=Math.min(l,g),M=Math.max(l,g),k=w-_q,R=M+_q;B=Math.abs(B-k)<Math.abs(B-R)?k:R}if(ede(Q,c)||ede(Q,u)){const w=Math.min(c,u),M=Math.max(c,u),k=w-_q,R=M+_q;Q=Math.abs(Q-k)<Math.abs(Q-R)?k:R}return Math.abs(h)>jYt&&A.push(...CVo({startX:c,endX:u,y:B,offsetMm:h,offsetY:d,displayOffset:s})),Math.abs(d)>jYt&&A.push(...yVo({x:Q,startY:l,endY:g,offsetMm:d,offsetX:h,displayOffset:a})),A}function fVo(t,e,n,o){const i=n-t,r=o-e,s=Math.hypot(i,r),a=BRe+bRe;if(!(s>a))return{x1:t,y1:e,x2:n,y2:o};const A=i/s,c=r/s;return{x1:t+A*BRe,y1:e+c*BRe,x2:n-A*bRe,y2:o-c*bRe}}function ede(t,e){return Math.abs(t-e)<_q}function IVo(t,e){return{name:"g",type:"element",attributes:{class:"anchor-offset-marker","data-type":"anchor_offset_marker"},children:[{name:"line",type:"element",attributes:{x1:t.toString(),y1:(e-_G).toString(),x2:t.toString(),y2:(e+_G).toString(),stroke:"#ffffff","stroke-width":XYt.toString(),"stroke-linecap":"round"},children:[],value:""},{name:"line",type:"element",attributes:{x1:(t-_G).toString(),y1:e.toString(),x2:(t+_G).toString(),y2:e.toString(),stroke:"#ffffff","stroke-width":XYt.toString(),"stroke-linecap":"round"},children:[],value:""}],value:""}}function CVo({startX:t,endX:e,y:n,offsetMm:o,offsetY:i,displayOffset:r}){const s=[];s.push({name:"line",type:"element",attributes:{x1:t.toString(),y1:n.toString(),x2:e.toString(),y2:n.toString(),stroke:"#ffffff","stroke-width":mG.toString(),class:"anchor-offset-dimension-x"},children:[],value:""}),s.push({name:"line",type:"element",attributes:{x1:t.toString(),y1:(n-hE).toString(),x2:t.toString(),y2:(n+hE).toString(),stroke:"#ffffff","stroke-width":mG.toString()},children:[],value:""}),s.push({name:"line",type:"element",attributes:{x1:e.toString(),y1:(n-hE).toString(),x2:e.toString(),y2:(n+hE).toString(),stroke:"#ffffff","stroke-width":mG.toString()},children:[],value:""});const a=(t+e)/2,A=i>0?n-hE-$Yt:n+hE+$Yt;return s.push({name:"text",type:"element",attributes:{x:a.toString(),y:A.toString(),fill:"#ffffff","font-size":qYt.toString(),"font-family":"Arial, sans-serif","text-anchor":"middle","dominant-baseline":i>0?"baseline":"hanging",class:"anchor-offset-label"},children:[{type:"text",value:eUt("X",o,r),name:"",attributes:{},children:[]}],value:""}),s}function yVo({x:t,startY:e,endY:n,offsetMm:o,offsetX:i,displayOffset:r}){const s=[];s.push({name:"line",type:"element",attributes:{x1:t.toString(),y1:e.toString(),x2:t.toString(),y2:n.toString(),stroke:"#ffffff","stroke-width":mG.toString(),class:"anchor-offset-dimension-y"},children:[],value:""}),s.push({name:"line",type:"element",attributes:{x1:(t-hE).toString(),y1:e.toString(),x2:(t+hE).toString(),y2:e.toString(),stroke:"#ffffff","stroke-width":mG.toString()},children:[],value:""}),s.push({name:"line",type:"element",attributes:{x1:(t-hE).toString(),y1:n.toString(),x2:(t+hE).toString(),y2:n.toString(),stroke:"#ffffff","stroke-width":mG.toString()},children:[],value:""});const a=(e+n)/2,A=i<0?t-hE-4:t+hE+4;return s.push({name:"text",type:"element",attributes:{x:A.toString(),y:a.toString(),fill:"#ffffff","font-size":qYt.toString(),"font-family":"Arial, sans-serif","text-anchor":i<0?"end":"start","dominant-baseline":"middle",class:"anchor-offset-label"},children:[{type:"text",value:eUt("Y",o,r),name:"",attributes:{},children:[]}],value:""}),s}function eUt(t,e,n){const o=typeof n=="string"?n:e.toFixed(2),r=typeof o=="string"&&o.trim().endsWith("mm")?"":"mm";return`${t}: ${o}${r}`}function fq(t){const e=t?.anchor_position??t?.center;if(e&&typeof e.x=="number"&&typeof e.y=="number")return{x:e.x,y:e.y}}function tUt(t,e){const{transform:n,colorMap:o,showSolderMask:i,circuitJson:r}=e,{width:s,height:a,center:A,outline:c,position_mode:l,anchor_position:u,display_offset_x:g,display_offset_y:h}=t;let d;if(c&&Array.isArray(c)&&c.length>=3)d=c.map((m,_)=>{const[f,I]=hn(n,[m.x,m.y]);return _===0?`M ${f} ${I}`:`L ${f} ${I}`}).join(" ");else{const m=s/2,_=a/2,f=hn(n,[A.x-m,A.y-_]),I=hn(n,[A.x+m,A.y-_]),C=hn(n,[A.x+m,A.y+_]),y=hn(n,[A.x-m,A.y+_]);d=`M ${f[0]} ${f[1]} L ${I[0]} ${I[1]} L ${C[0]} ${C[1]} L ${y[0]} ${y[1]}`}d+=" Z";const p=[];if(i){const _=(e.layer??"top")==="bottom"?"soldermask-bottom":"soldermask-top";p.push({name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-board-soldermask",d,fill:o.soldermask.top,"fill-opacity":"0.8",stroke:"none","data-type":"pcb_soldermask","data-pcb-layer":_}})}if(p.push({name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-board",d,fill:"none",stroke:o.boardOutline,"stroke-width":(.1*Math.abs(n.a)).toString(),"data-type":"pcb_board","data-pcb-layer":"board"}}),e.showAnchorOffsets&&r&&l==="relative_to_panel_anchor"){const m=r.find(_=>_.type==="pcb_panel");if(m){const _=fq(m);_&&p.push(...SRe({groupAnchorPosition:_,componentPosition:u??A,transform:n,componentWidth:s,componentHeight:a,displayXOffset:g,displayYOffset:h}))}}return p}function xVo(t,e){const{transform:n,colorMap:o,showSolderMask:i}=e,r=Number(t.width),s=Number(t.height),a=t.center??{x:r/2,y:s/2},A=r/2,c=s/2,l=hn(n,[a.x-A,a.y-c]),u=hn(n,[a.x+A,a.y-c]),g=hn(n,[a.x+A,a.y+c]),h=hn(n,[a.x-A,a.y+c]),d=`M ${l[0]} ${l[1]} L ${u[0]} ${u[1]} L ${g[0]} ${g[1]} L ${h[0]} ${h[1]} Z`;return t.covered_with_solder_mask,[{name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-panel",d,fill:"none",stroke:o.boardOutline,"stroke-width":(.1*Math.abs(n.a)).toString(),"data-type":"pcb_panel","data-pcb-layer":"board"}}]}function EVo(t,e){const{transform:n,colorMap:o,showSolderMask:i}=e,r=e.layer??"top",[s,a]=hn(n,[t.x,t.y]),A=!!t.is_covered_with_solder_mask,c=(t.soldermask_margin??0)*Math.abs(n.a),l=i&&A&&c!==0,u=o.soldermask.top;if(t.hole_shape==="circle"||t.hole_shape==="square"){const g=t.hole_diameter*Math.abs(n.a),h=g/2;if(t.hole_shape==="circle"){const _={name:"circle",type:"element",attributes:{class:"pcb-hole",cx:s.toString(),cy:a.toString(),r:h.toString(),fill:o.drill,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[_];const f=h+c;if(c<0){const C={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,cx:s.toString(),cy:a.toString(),r:h.toString(),"data-type":"pcb_hole","data-pcb-layer":"drill"}},y={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:o.drill,cx:s.toString(),cy:a.toString(),r:f.toString(),"data-type":"pcb_soldermask","data-pcb-layer":"drill"}};return[C,y]}return[{name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:o.substrate,cx:s.toString(),cy:a.toString(),r:f.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":r}},_]}const d={name:"rect",type:"element",attributes:{class:"pcb-hole",x:(s-h).toString(),y:(a-h).toString(),width:g.toString(),height:g.toString(),fill:o.drill,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[d];const p=g+2*c;if(c<0){const _={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,x:(s-h).toString(),y:(a-h).toString(),width:g.toString(),height:g.toString(),"data-type":"pcb_hole","data-pcb-layer":"drill"}},f={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:o.drill,x:(s-p/2).toString(),y:(a-p/2).toString(),width:p.toString(),height:p.toString(),"data-type":"pcb_soldermask","data-pcb-layer":"drill"}};return[_,f]}return[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:o.substrate,x:(s-p/2).toString(),y:(a-p/2).toString(),width:p.toString(),height:p.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":r}},d]}if(t.hole_shape==="oval"){const g=t.hole_width*Math.abs(n.a),h=t.hole_height*Math.abs(n.a),d=g/2,p=h/2,m={name:"ellipse",type:"element",attributes:{class:"pcb-hole",cx:s.toString(),cy:a.toString(),rx:d.toString(),ry:p.toString(),fill:o.drill,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[m];const _=d+c,f=p+c;if(c<0){const C={name:"ellipse",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,cx:s.toString(),cy:a.toString(),rx:d.toString(),ry:p.toString(),"data-type":"pcb_hole","data-pcb-layer":"drill"}},y={name:"ellipse",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:o.drill,cx:s.toString(),cy:a.toString(),rx:_.toString(),ry:f.toString(),"data-type":"pcb_soldermask","data-pcb-layer":"drill"}};return[C,y]}return[{name:"ellipse",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:o.substrate,cx:s.toString(),cy:a.toString(),rx:_.toString(),ry:f.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":r}},m]}if(t.hole_shape==="rect"){const g=t.hole_width*Math.abs(n.a),h=t.hole_height*Math.abs(n.a),d={name:"rect",type:"element",attributes:{class:"pcb-hole",x:(s-g/2).toString(),y:(a-h/2).toString(),width:g.toString(),height:h.toString(),fill:o.drill,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[d];const p=g+2*c,m=h+2*c;if(c<0){const f={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,x:(s-g/2).toString(),y:(a-h/2).toString(),width:g.toString(),height:h.toString(),"data-type":"pcb_hole","data-pcb-layer":"drill"}},I={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:o.drill,x:(s-p/2).toString(),y:(a-m/2).toString(),width:p.toString(),height:m.toString(),"data-type":"pcb_soldermask","data-pcb-layer":"drill"}};return[f,I]}return[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:o.substrate,x:(s-p/2).toString(),y:(a-m/2).toString(),width:p.toString(),height:m.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":r}},d]}if(t.hole_shape==="pill"){const g=t.hole_width*Math.abs(n.a),h=t.hole_height*Math.abs(n.a),d=g>h,p=Math.min(g,h)/2,m=Math.abs(d?g-h:h-g),_=d?`M${s-m/2},${a-p} h${m} a${p},${p} 0 0 1 0,${h} h-${m} a${p},${p} 0 0 1 0,-${h} z`:`M${s-p},${a-m/2} v${m} a${p},${p} 0 0 0 ${g},0 v-${m} a${p},${p} 0 0 0 -${g},0 z`,f={name:"path",type:"element",attributes:{class:"pcb-hole",fill:o.drill,d:_,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[f];const I=g+2*c,C=h+2*c,y=I>C,x=Math.min(I,C)/2,E=Math.abs(y?I-C:C-I),B=y?`M${s-E/2},${a-x} h${E} a${x},${x} 0 0 1 0,${C} h-${E} a${x},${x} 0 0 1 0,-${C} z`:`M${s-x},${a-E/2} v${E} a${x},${x} 0 0 0 ${I},0 v-${E} a${x},${x} 0 0 0 -${I},0 z`;if(c<0){const Q={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,d:_,"data-type":"pcb_hole","data-pcb-layer":"drill"}},w={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:o.drill,d:B,"data-type":"pcb_soldermask","data-pcb-layer":"drill"}};return[Q,w]}return[{name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:o.substrate,d:B,"data-type":"pcb_soldermask_opening","data-pcb-layer":r}},f]}if(t.hole_shape==="rotated_pill"){const g=t.hole_width*Math.abs(n.a),h=t.hole_height*Math.abs(n.a),d="ccw_rotation"in t?t.ccw_rotation??0:0,p=g>h,m=Math.min(g,h)/2,_=Math.abs(p?g-h:h-g),f=p?`M${-_/2},${-m} h${_} a${m},${m} 0 0 1 0,${h} h-${_} a${m},${m} 0 0 1 0,-${h} z`:`M${-m},${-_/2} v${_} a${m},${m} 0 0 0 ${g},0 v-${_} a${m},${m} 0 0 0 -${g},0 z`,I={name:"path",type:"element",attributes:{class:"pcb-hole",fill:o.drill,d:f,transform:`translate(${s} ${a}) rotate(${-d})`,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[I];const C=g+2*c,y=h+2*c,x=C>y,E=Math.min(C,y)/2,B=Math.abs(x?C-y:y-C),S=x?`M${-B/2},${-E} h${B} a${E},${E} 0 0 1 0,${y} h-${B} a${E},${E} 0 0 1 0,-${y} z`:`M${-E},${-B/2} v${B} a${E},${E} 0 0 0 ${C},0 v-${B} a${E},${E} 0 0 0 -${C},0 z`;if(c<0){const w={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,d:f,transform:`translate(${s} ${a}) rotate(${-d})`,"data-type":"pcb_hole","data-pcb-layer":"drill"}},M={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:o.drill,d:S,transform:`translate(${s} ${a}) rotate(${-d})`,"data-type":"pcb_soldermask","data-pcb-layer":"drill"}};return[w,M]}return[{name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:o.substrate,d:S,"data-type":"pcb_soldermask_opening","data-pcb-layer":r}},I]}return[]}var BVo=(t,e)=>{const n=Mr(e).pcb_smtpad.get(t);if(n&&"x"in n&&"y"in n)return{x:n.x,y:n.y};const o=Mr(e).pcb_plated_hole.get(t);return o&&"x"in o&&"y"in o?{x:o.x,y:o.y}:null},bVo=(t,e,n,o)=>{const i=n.getIdsConnectedToNet(e);let r=null,s=1/0;for(const a of i){const A=BVo(a,o);if(A){const c=t.x-A.x,l=t.y-A.y,u=Math.sqrt(c*c+l*l);u>0&&u<s&&(s=u,r=A)}}return r};function SVo(t,e){const{transform:n}=e,o=Vf(t),i=t.filter(A=>A.type==="pcb_port"),r=t.filter(A=>A.type==="source_trace"),s=[];i.forEach((A,c)=>{const l=A.pcb_port_id;if(!l)return;const u=o.getNetConnectedToId(l);if(!u)return;let g=!1;const h=Mr(t).source_port.getWhere({pcb_port_id:l});if(h&&h.source_port_id){const m=h.source_port_id;for(const _ of r)if(Array.isArray(_.connected_source_port_ids)&&_.connected_source_port_ids.includes(m)&&Array.isArray(_.connected_source_net_ids)&&_.connected_source_net_ids.length>0){g=!0;break}}const d={x:A.x,y:A.y},p=bVo(d,u,o,t);p&&s.push({key:`${l}-${c}`,startPoint:d,endPoint:p,isInNet:g})});const a=[];for(const A of s){const c=hn(n,[A.startPoint.x,A.startPoint.y]),l=hn(n,[A.endPoint.x,A.endPoint.y]),u={x1:c[0].toString(),y1:c[1].toString(),x2:l[0].toString(),y2:l[1].toString(),stroke:"white","stroke-width":"1","stroke-dasharray":"6,6","data-type":"pcb_rats_nest","data-pcb-layer":"overlay"};a.push({name:"line",type:"element",attributes:u,value:"",children:[]})}return a}function QVo(t,e){const{transform:n,colorMap:o}=e;if(t.shape==="rect"){const i=t,[r,s]=hn(n,[i.center.x,i.center.y]),a=i.width*Math.abs(n.a),A=i.height*Math.abs(n.d),c=-(i.rotation??0),{corner_radius:l}=i,u=typeof l=="number"&&l>0?l:0,g=u*Math.abs(n.a),h=u*Math.abs(n.d),d={class:"pcb-cutout pcb-cutout-rect",x:(-a/2).toString(),y:(-A/2).toString(),width:a.toString(),height:A.toString(),fill:o.drill,transform:$b(m0(of(r,s),jb(c*Math.PI/180))),"data-type":"pcb_cutout","data-pcb-layer":"drill"};return g>0&&(d.rx=g.toString()),h>0&&(d.ry=h.toString()),[{name:"rect",type:"element",attributes:d,children:[],value:""}]}if(t.shape==="circle"){const i=t,[r,s]=hn(n,[i.center.x,i.center.y]),a=i.radius*Math.abs(n.a);return[{name:"circle",type:"element",attributes:{class:"pcb-cutout pcb-cutout-circle",cx:r.toString(),cy:s.toString(),r:a.toString(),fill:o.drill,"data-type":"pcb_cutout","data-pcb-layer":"drill"},children:[],value:""}]}if(t.shape==="polygon"){const i=t;return!i.points||i.points.length===0?[]:[{name:"polygon",type:"element",attributes:{class:"pcb-cutout pcb-cutout-polygon",points:i.points.map(a=>hn(n,[a.x,a.y])).map(a=>`${a[0]},${a[1]}`).join(" "),fill:o.drill,"data-type":"pcb_cutout","data-pcb-layer":"drill"},children:[],value:""}]}return[]}function vVo(t,e){const{transform:n,colorMap:o}=e;if(!t.route||!Array.isArray(t.route))return[];const i=t.route[0],r=t.route[t.route.length-1],s=i&&r&&i.x===r.x&&i.y===r.y;return[{name:"path",type:"element",attributes:{class:"pcb-cutout pcb-cutout-path",d:t.route.slice(0,s?-1:void 0).map((A,c)=>{const[l,u]=hn(n,[A.x,A.y]);return c===0?`M ${l} ${u}`:`L ${l} ${u}`}).join(" ")+(s?" Z":""),fill:o.drill,"data-type":"pcb_cutout_path","data-pcb-cutout-id":t.pcb_cutout_id,"data-pcb-layer":"drill"},value:"",children:[]}]}var nUt="pcb-keepout-pattern",fG=20,wVo=5,oUt="rgba(255, 107, 107, 0.2)";function PVo(t){const e=[];for(let n=-fG;n<=fG;n+=wVo)e.push({name:"line",type:"element",value:"",attributes:{x1:n.toString(),y1:"0",x2:(n+fG).toString(),y2:fG.toString(),stroke:t,"stroke-width":"1"},children:[]});return e}function MVo(t){return{name:"defs",type:"element",value:"",attributes:{},children:[{name:"pattern",type:"element",value:"",attributes:{id:nUt,width:fG.toString(),height:fG.toString(),patternUnits:"userSpaceOnUse"},children:PVo(t)}]}}function iUt(t,e,n,o){const i={class:`pcb-keepout ${n} pcb-keepout-background`,"data-type":"pcb_keepout","data-pcb-layer":e,"data-pcb-keepout-id":t,stroke:"none"};return o&&(i["data-description"]=o),i}function rUt(t,e,n,o){const i={class:`pcb-keepout ${n} pcb-keepout-pattern`,fill:`url(#${nUt})`,"data-type":"pcb_keepout","data-pcb-layer":e,"data-pcb-keepout-id":t,stroke:"none"};return o&&(i["data-description"]=o),i}function DVo(t,e){const{transform:n,layer:o,colorMap:i}=e;if(o&&!t.layers.includes(o))return[];const r=[];i.keepout;for(const s of t.layers)if(!(o&&s!==o)){if(t.shape==="rect"){const a=t,[A,c]=hn(n,[a.center.x,a.center.y]),l=a.width*Math.abs(n.a),u=a.height*Math.abs(n.d),g=$b(m0(of(A,c))),h={...iUt(a.pcb_keepout_id,s,"pcb-keepout-rect",a.description),x:(-l/2).toString(),y:(-u/2).toString(),width:l.toString(),height:u.toString(),fill:oUt,transform:g},d={...rUt(a.pcb_keepout_id,s,"pcb-keepout-rect",a.description),x:(-l/2).toString(),y:(-u/2).toString(),width:l.toString(),height:u.toString(),transform:g};r.push({name:"rect",type:"element",attributes:h,children:[],value:""},{name:"rect",type:"element",attributes:d,children:[],value:""})}else if(t.shape==="circle"){const a=t,[A,c]=hn(n,[a.center.x,a.center.y]),l=a.radius*Math.abs(n.a),u={...iUt(a.pcb_keepout_id,s,"pcb-keepout-circle",a.description),cx:A.toString(),cy:c.toString(),r:l.toString(),fill:oUt},g={...rUt(a.pcb_keepout_id,s,"pcb-keepout-circle",a.description),cx:A.toString(),cy:c.toString(),r:l.toString()};r.push({name:"circle",type:"element",attributes:u,children:[],value:""},{name:"circle",type:"element",attributes:g,children:[],value:""})}}return r}function NVo({elementType:t,shapeAttributes:e,layer:n,colorMap:o,additionalAttributes:i}){const r={class:"pcb-soldermask-cutout",fill:o.substrate,"data-type":"pcb_soldermask_opening","data-pcb-layer":n,...e,...i};return{name:t,type:"element",value:"",children:[],attributes:r}}function RVo(t,e){const{transform:n,layer:o,colorMap:i,showSolderMask:r}=e,{layer:s}=t;if(o&&s!==o)return[];const a=VYt(t,n);if(!a)return[];const{elementType:A,shapeAttributes:c}=a,l=Fx(s,i),u="0.5",g=t.covered_with_solder_mask!==!1,h=s==="bottom"?i.soldermaskOverCopper.bottom:i.soldermaskOverCopper.top,d="0.9",p={name:A,type:"element",value:"",children:[],attributes:{class:`pcb-copper-pour pcb-copper-pour-${t.shape}`,...c,fill:l,"fill-opacity":u,"data-type":"pcb_copper_pour","data-pcb-layer":s}},m=r?g?UYt({elementType:A,shapeAttributes:c,layer:s,fillColor:h,fillOpacity:d,className:"pcb-soldermask-covered-pour"}):NVo({elementType:A,shapeAttributes:c,layer:s,colorMap:i}):null;return m?!g&&t.pcb_copper_pour_id?.includes("substrate_only")?[m]:[p,m]:[p]}function sUt(t,e){const{transform:n,layer:o}=e;if(o&&t.layer!==o)return[];const[i,r]=hn(n,[t.x,t.y]);if(t.shape==="rect"||t.shape==="rotated_rect"){const s=t.width*Math.abs(n.a),a=t.height*Math.abs(n.d);return t.shape==="rotated_rect"&&t.ccw_rotation?[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:hG(t.layer),x:(-s/2).toString(),y:(-a/2).toString(),width:s.toString(),height:a.toString(),transform:`translate(${i} ${r}) rotate(${-t.ccw_rotation})`,"data-type":"pcb_solder_paste","data-pcb-layer":t.layer}}]:[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:hG(t.layer),x:(i-s/2).toString(),y:(r-a/2).toString(),width:s.toString(),height:a.toString(),"data-type":"pcb_solder_paste","data-pcb-layer":t.layer}}]}if(t.shape==="pill"){const s=t.width*Math.abs(n.a),a=t.height*Math.abs(n.d),A=t.radius*Math.abs(n.a);return[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:hG(t.layer),x:(i-s/2).toString(),y:(r-a/2).toString(),width:s.toString(),height:a.toString(),rx:A.toString(),"data-type":"pcb_solder_paste","data-pcb-layer":t.layer}}]}if(t.shape==="rotated_pill"){const s=t.width*Math.abs(n.a),a=t.height*Math.abs(n.d),A=t.radius*Math.abs(n.a);return[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:hG(t.layer),x:(-s/2).toString(),y:(-a/2).toString(),width:s.toString(),height:a.toString(),rx:A.toString(),transform:`translate(${i} ${r}) rotate(${-t.ccw_rotation})`,"data-type":"pcb_solder_paste","data-pcb-layer":t.layer}}]}if(t.shape==="oval"){const s=t.width*Math.abs(n.a),a=t.height*Math.abs(n.d);return[{name:"ellipse",type:"element",attributes:{class:"pcb-solder-paste",fill:hG(t.layer),cx:i.toString(),cy:r.toString(),rx:(s/2).toString(),ry:(a/2).toString(),"data-type":"pcb_solder_paste","data-pcb-layer":t.layer}}]}if(t.shape==="circle"){const s=t.radius*Math.abs(n.a);return[{name:"circle",type:"element",attributes:{class:"pcb-solder-paste",fill:hG(t.layer),cx:i.toString(),cy:r.toString(),r:s.toString(),"data-type":"pcb_solder_paste","data-pcb-layer":t.layer}}]}}var TVo="rgba(255, 255, 255, 0.5)",aUt="pcb-grid-pattern";function kVo({grid:t,svgWidth:e,svgHeight:n}){if(!t)return{};const o=t.lineColor??TVo,i=t.cellSize,r=t.majorCellSize,s=t.majorLineColor??o;if(r!==void 0){if(!i||i<=0)throw new Error("grid.majorCellSize requires a positive grid.cellSize");if(r<=0)throw new Error("grid.majorCellSize must be a positive multiple of grid.cellSize");const u=r/i,g=Math.round(u);if(!Number.isFinite(u)||Math.abs(u-g)>1e-6)throw new Error("grid.majorCellSize must be a positive multiple of grid.cellSize")}if(!i||i<=0)return{};const a=r!==void 0,A=a?FVo(i,r,o,s):[{name:"path",type:"element",value:"",attributes:{d:`M ${i} 0 L 0 0 0 ${i}`,fill:"none",stroke:o,"stroke-width":"1","shape-rendering":"crispEdges"},children:[]}],c={name:"defs",type:"element",value:"",attributes:{},children:[{name:"pattern",type:"element",value:"",attributes:{id:aUt,width:a?r.toString():i.toString(),height:a?r.toString():i.toString(),patternUnits:"userSpaceOnUse"},children:A}]},l={name:"rect",type:"element",value:"",attributes:{x:"0",y:"0",width:e.toString(),height:n.toString(),fill:`url(#${aUt})`,"pointer-events":"none","data-type":"pcb_grid","data-pcb-layer":"global"},children:[]};return{defs:c,rect:l}}function FVo(t,e,n,o){const i=[],r=Math.round(e/t);for(let s=0;s<r;s+=1){const A=Number((s*t).toFixed(6)).toString(),c=s===0?o:n,l=e.toString();i.push({name:"line",type:"element",value:"",attributes:{x1:A,y1:"0",x2:A,y2:l,stroke:c,"stroke-width":"1","shape-rendering":"crispEdges"},children:[]}),i.push({name:"line",type:"element",value:"",attributes:{x1:"0",y1:A,x2:l,y2:A,stroke:c,"stroke-width":"1","shape-rendering":"crispEdges"},children:[]})}return i}function LVo(t,e){const{transform:n,circuitJson:o}=e,{center:i,width:r,height:s,rotation:a=0}=t,[A,c]=hn(n,[i.x,i.y]),l=r*Math.abs(n.a),u=s*Math.abs(n.d),g=`translate(${A}, ${c}) rotate(${-a}) scale(1, -1)`,h=[];if(e.showAnchorOffsets&&o&&t.position_mode==="relative_to_group_anchor"&&(t.positioned_relative_to_pcb_group_id||t.positioned_relative_to_pcb_board_id)){const d=HVo(t,o);d&&h.push(...SRe({groupAnchorPosition:d,componentPosition:i,transform:n,componentWidth:r,componentHeight:s,displayXOffset:t.display_offset_x,displayYOffset:t.display_offset_y}))}return!e.colorMap.debugComponent?.fill&&!e.colorMap.debugComponent?.stroke||h.push({name:"g",type:"element",attributes:{transform:g,"data-type":"pcb_component","data-pcb-layer":t.layer??"top"},children:[{name:"rect",type:"element",attributes:{class:"pcb-component",x:(-l/2).toString(),y:(-u/2).toString(),width:l.toString(),height:u.toString(),fill:e.colorMap.debugComponent.fill??"transparent",stroke:e.colorMap.debugComponent.stroke??"transparent","data-type":"pcb_component","data-pcb-layer":t.layer??"top"}}],value:""}),h}function HVo(t,e){if(t.positioned_relative_to_pcb_group_id){const n=e.find(i=>i.type==="pcb_group"&&i.pcb_group_id===t.positioned_relative_to_pcb_group_id),o=fq(n);if(o)return o}if(t.positioned_relative_to_pcb_board_id){const n=e.find(i=>i.type==="pcb_board"&&i.pcb_board_id===t.positioned_relative_to_pcb_board_id),o=fq(n);if(o)return o}}var AUt=["rgba(100, 200, 255, 0.6)","rgba(255, 150, 100, 0.6)","rgba(100, 255, 150, 0.6)","rgba(200, 100, 255, 0.6)","rgba(255, 220, 100, 0.6)","rgba(255, 100, 200, 0.6)","rgba(100, 255, 255, 0.6)","rgba(180, 255, 100, 0.6)"],OVo=.1;function GVo(t,e){const{transform:n,circuitJson:o}=e,{center:i,width:r,height:s}=t,a=[];if(e.showAnchorOffsets&&t.position_mode==="relative_to_group_anchor"&&o){const B=UVo(t,o);B&&a.push(...SRe({groupAnchorPosition:B,componentPosition:t.anchor_position??t.center,transform:n,componentWidth:t.width,componentHeight:t.height,displayXOffset:t.display_offset_x,displayYOffset:t.display_offset_y}))}const A=Array.isArray(t.outline)?t.outline:void 0,c=OVo*Math.abs(n.a),l=.3*Math.abs(n.a),u=.15*Math.abs(n.a),g={class:"pcb-group",fill:"none",stroke:YVo(t.pcb_group_id),"stroke-width":c.toString(),"stroke-dasharray":`${l} ${u}`,"data-type":"pcb_group","data-pcb-group-id":t.pcb_group_id,"data-pcb-layer":"overlay"};if(t.name&&(g["data-group-name"]=t.name),A&&A.length>=3&&A.every(B=>B&&typeof B.x=="number"&&typeof B.y=="number")){const B=A.map((S,Q)=>{const[w,M]=hn(n,[S.x,S.y]);return Q===0?`M ${w} ${M}`:`L ${w} ${M}`}).join(" ");return a.push({name:"path",type:"element",value:"",children:[],attributes:{...g,d:`${B} Z`}}),a}if(!i||typeof i.x!="number"||typeof i.y!="number"||typeof r!="number"||typeof s!="number")return cm(`[pcb_group] Invalid data for "${t.pcb_group_id}"${t.name?` (name: "${t.name}")`:""}: expected center {x: number, y: number}, width: number, height: number, got center=${JSON.stringify(i)}, width=${JSON.stringify(r)}, height=${JSON.stringify(s)}`),a;const h=r/2,d=s/2,[p,m]=hn(n,[i.x-h,i.y+d]),[_,f]=hn(n,[i.x+h,i.y-d]),I=Math.min(p,_),C=Math.min(m,f),y=Math.abs(_-p),x=Math.abs(f-m),E={name:"rect",type:"element",value:"",attributes:{...g,x:I.toString(),y:C.toString(),width:y.toString(),height:x.toString()},children:[]};return a.push(E),a}function YVo(t){const e=t.match(/(\d+)$/),n=e?Number.parseInt(e[1],10):0;return AUt[n%AUt.length]}function UVo(t,e){if(t.positioned_relative_to_pcb_group_id){const n=e.find(i=>i.type==="pcb_group"&&i.pcb_group_id===t.positioned_relative_to_pcb_group_id),o=fq(n);if(o)return o}if(t.positioned_relative_to_pcb_board_id){const n=e.find(i=>i.type==="pcb_board"&&i.pcb_board_id===t.positioned_relative_to_pcb_board_id),o=fq(n);if(o)return o}}function Gw(t){return t.find(n=>n.type==="project_software_metadata"||n.type==="source_project_metadata")?.software_used_string}var KVo={version:"0.0.420"},Yw=KVo.version,VVo={pcb_background:0,pcb_boundary:1,pcb_panel:5,pcb_board:10,pcb_cutout:15,pcb_cutout_path:15,pcb_keepout:16,pcb_hole:18,pcb_plated_hole_drill:19,pcb_plated_hole:20,pcb_trace_soldermask:25,pcb_trace:30,pcb_smtpad:30,pcb_copper_pour:35,pcb_via:36,pcb_soldermask:40,pcb_soldermask_opening:25,pcb_solder_paste:45,pcb_silkscreen_text:50,pcb_silkscreen_path:50,pcb_silkscreen_graphic:50,pcb_silkscreen_rect:50,pcb_silkscreen_circle:50,pcb_silkscreen_line:50,pcb_silkscreen_oval:50,pcb_silkscreen_pill:50,pcb_component:60,pcb_pad_pin_number:65,pcb_fabrication_note_text:70,pcb_fabrication_note_path:70,pcb_fabrication_note_rect:70,pcb_fabrication_note_dimension:70,pcb_note_dimension:70,pcb_note_text:70,pcb_note_rect:70,pcb_note_path:70,pcb_note_line:70,pcb_trace_error:80,pcb_footprint_overlap_error:80,pcb_component_outside_board_error:80,pcb_pad_trace_clearance_error:80,pcb_via_trace_clearance_error:80,pcb_connector_not_in_accessible_orientation_warning:80,pcb_manual_edit_conflict_warning:80,pcb_rats_nest:85,pcb_debug_object:90},cUt=100;function zVo(t){return t.map((e,n)=>({object:e,index:n,layerPriority:JVo(e.attributes?.["data-pcb-layer"]??void 0),typePriority:WVo(e.attributes?.["data-type"]??void 0)})).sort((e,n)=>e.layerPriority!==n.layerPriority?e.layerPriority-n.layerPriority:e.typePriority!==n.typePriority?e.typePriority-n.typePriority:e.index-n.index).map(({object:e})=>e)}function JVo(t){if(!t)return 500;const e=t.toLowerCase();if(e==="global")return-100;if(e==="bottom")return 4;if(e==="board")return 2;if(e==="soldermask-top"||e==="soldermask-bottom")return 3;if(e.startsWith("inner")){const n=e.match(/\d+/);return 5+(n?Number.parseInt(n[0],10):0)}return e==="through"?18:e==="top"?17:e==="drill"?30:e==="overlay"?40:10}function WVo(t){return t?VVo[t]??cUt:cUt}function IG(t,e="error_text_overlay"){const n=t.filter(r=>r.type.endsWith("_error"));if(n.length===0)return null;const o=n.map(r=>r.message).filter(r=>!!r);return o.length===0?null:{name:"text",type:"element",value:"",attributes:{x:"10",y:"20",fill:"red","font-family":"monospace","font-size":"12px","data-type":e,"data-layer":"global"},children:o.map((r,s)=>({name:"tspan",type:"element",value:"",attributes:{x:"10",dy:s===0?"0":"1.2em"},children:[{type:"text",value:r,name:"",attributes:{},children:[]}]}))}}function jVo({anchorPosition:t,textWidth:e,textHeight:n,anchorAlignment:o}){switch(o){case"top_left":return{x:t.x+e/2,y:t.y+n/2};case"top_center":return{x:t.x,y:t.y+n/2};case"top_right":return{x:t.x-e/2,y:t.y+n/2};case"center_left":return{x:t.x+e/2,y:t.y};case"center_right":return{x:t.x-e/2,y:t.y};case"bottom_left":return{x:t.x+e/2,y:t.y-n/2};case"bottom_center":return{x:t.x,y:t.y-n/2};case"bottom_right":return{x:t.x-e/2,y:t.y-n/2};default:return t}}function $Vo(t){let e=Number.POSITIVE_INFINITY,n=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,r=!1,s=Number.POSITIVE_INFINITY,a=Number.POSITIVE_INFINITY,A=Number.NEGATIVE_INFINITY,c=Number.NEGATIVE_INFINITY,l=!1;for(const I of t)if(I.type==="pcb_panel"){const C=I,y=lt.parse(C.width),x=lt.parse(C.height);if(y===void 0||x===void 0)continue;const E=C.center??{x:y/2,y:x/2};u({center:E,width:y,height:x})}else if(I.type==="pcb_board")I.outline&&Array.isArray(I.outline)&&I.outline.length>=3?(h(I.outline),d(I.outline)):"center"in I&&"width"in I&&"height"in I&&(u({center:I.center,width:I.width,height:I.height}),g({center:I.center,width:I.width,height:I.height}));else if(I.type==="pcb_courtyard_rect")u({center:I.center,width:I.width,height:I.height,ccwRotationDegrees:I.ccw_rotation});else if(I.type==="pcb_smtpad"){const C=I;if(C.shape==="rect"||C.shape==="pill")u({center:{x:C.x,y:C.y},width:C.width,height:C.height});else if(C.shape==="rotated_rect"||C.shape==="rotated_pill")u({center:{x:C.x,y:C.y},width:C.width,height:C.height,ccwRotationDegrees:C.ccw_rotation});else if(C.shape==="circle"){const y=lt.parse(C.radius);y!==void 0&&u({center:{x:C.x,y:C.y},width:y*2,height:y*2})}else C.shape==="polygon"&&p(C.points)}else if(I.type==="pcb_via"){const C=lt.parse(I.outer_diameter);u({center:{x:I.x,y:I.y},width:C??0,height:C??0})}else if(I.type==="pcb_plated_hole"){const C=I,y={x:C.x,y:C.y};if(C.shape==="circle"){const x=lt.parse(C.outer_diameter);u({center:y,width:x??0,height:x??0})}else C.shape==="oval"||C.shape==="pill"?u({center:y,width:C.outer_width,height:C.outer_height}):C.shape==="circular_hole_with_rect_pad"||C.shape==="pill_hole_with_rect_pad"?u({center:y,width:C.rect_pad_width,height:C.rect_pad_height}):C.shape==="rotated_pill_hole_with_rect_pad"?u({center:y,width:C.rect_pad_width,height:C.rect_pad_height,ccwRotationDegrees:C.rect_ccw_rotation}):C.shape==="hole_with_polygon_pad"&&p((C.pad_outline??[]).map(x=>({x:C.x+x.x,y:C.y+x.y})))}else if(I.type==="pcb_hole"){const C=I,y={x:C.x,y:C.y};if(C.hole_shape==="circle"||C.hole_shape==="square"){const x=lt.parse(C.hole_diameter);u({center:y,width:x??0,height:x??0})}else C.hole_shape==="rotated_pill"?u({center:y,width:C.hole_width,height:C.hole_height,ccwRotationDegrees:C.ccw_rotation}):(C.hole_shape==="oval"||C.hole_shape==="rect"||C.hole_shape==="pill")&&u({center:y,width:C.hole_width,height:C.hole_height})}else if(I.type==="pcb_note_line")p([{x:I.x1,y:I.y1},{x:I.x2,y:I.y2}]);else if("x"in I&&"y"in I)u({center:{x:I.x,y:I.y},width:0,height:0});else if("route"in I)p(I.route);else if(I.type==="pcb_note_rect"||I.type==="pcb_fabrication_note_rect")u({center:I.center,width:I.width,height:I.height});else if(I.type==="pcb_note_dimension"||I.type==="pcb_fabrication_note_dimension"){const C=I,{from:y,to:x,text:E,font_size:B=1,arrow_size:S,offset_distance:Q,offset_direction:w}=C;if(!y||!x||!S)continue;u({center:y,width:0,height:0}),u({center:x,width:0,height:0});const M=ye=>{const Me=Math.hypot(ye.x,ye.y)||1;return{x:ye.x/Me,y:ye.y/Me}},k=M({x:x.x-y.x,y:x.y-y.y});if(Number.isNaN(k.x)||Number.isNaN(k.y))continue;const R={x:-k.y,y:k.x},F=w&&typeof w.x=="number"&&typeof w.y=="number",O=F?M(w):{x:0,y:0},U=typeof Q=="number"?Q:0,Y={x:O.x*U,y:O.y*U},W={x:y.x+Y.x,y:y.y+Y.y},te={x:x.x+Y.x,y:x.y+Y.y};u({center:W,width:0,height:0}),u({center:te,width:0,height:0});const j=F&&(Math.abs(O.x)>Number.EPSILON||Math.abs(O.y)>Number.EPSILON)?O:R,J=U+S,oe={x:y.x+j.x*J,y:y.y+j.y*J},ie={x:x.x+j.x*J,y:x.y+j.y*J};u({center:oe,width:0,height:0}),u({center:ie,width:0,height:0});const ne=S/2,le={x:W.x+k.x*S,y:W.y+k.y*S},ge={x:te.x-k.x*S,y:te.y-k.y*S},_e={x:le.x+R.x*ne,y:le.y+R.y*ne},ue={x:le.x-R.x*ne,y:le.y-R.y*ne};u({center:_e,width:0,height:0}),u({center:ue,width:0,height:0});const fe={x:ge.x+R.x*ne,y:ge.y+R.y*ne},pe={x:ge.x-R.x*ne,y:ge.y-R.y*ne};if(u({center:fe,width:0,height:0}),u({center:pe,width:0,height:0}),E){const ye={x:(y.x+x.x)/2+Y.x,y:(y.y+x.y)/2+Y.y},Me=S*1.5,ve={x:ye.x+R.x*Me,y:ye.y+R.y*Me},he=E.length*B*.6;u({center:ve,width:he,height:B})}}else if(I.type==="pcb_note_text"||I.type==="pcb_fabrication_note_text")_({text:I.text,anchorPosition:I.anchor_position,fontSize:I.font_size,anchorAlignment:I.anchor_alignment,ccwRotationDegrees:I.type==="pcb_fabrication_note_text"?I.ccw_rotation??1:0});else if(I.type==="pcb_cutout"){const C=I;if(C.shape==="rect")u({center:C.center,width:C.width,height:C.height,ccwRotationDegrees:C.rotation});else if(C.shape==="circle"){const y=lt.parse(C.radius);y!==void 0&&u({center:C.center,width:y*2,height:y*2})}else if(C.shape==="polygon")p(C.points);else if(C.shape==="path"){const y=C;y.route&&Array.isArray(y.route)&&p(y.route)}}else if(I.type==="pcb_keepout"){const C=I;if(C.shape==="rect")u({center:C.center,width:C.width,height:C.height});else if(C.shape==="circle"){const y=typeof C.radius=="number"?C.radius:lt.parse(C.radius)??0;y>0&&u({center:C.center,width:y*2,height:y*2})}}else I.type==="pcb_silkscreen_graphic"||I.type==="pcb_silkscreen_text"||I.type==="pcb_silkscreen_rect"||I.type==="pcb_silkscreen_circle"||I.type==="pcb_silkscreen_line"||I.type==="pcb_silkscreen_oval"||I.type==="pcb_silkscreen_pill"?f(I):I.type==="pcb_copper_text"?u({center:I.anchor_position,width:0,height:0}):I.type==="pcb_copper_pour"&&(I.shape==="rect"?u({center:I.center,width:I.width,height:I.height,ccwRotationDegrees:I.rotation}):I.shape==="polygon"?p(I.points):I.shape==="brep"&&p(I.brep_shape.outer_ring.vertices));return{minX:e,minY:n,maxX:o,maxY:i,boardMinX:s,boardMinY:a,boardMaxX:A,boardMaxY:c,hasBounds:r,hasBoardBounds:l};function u({center:I,width:C,height:y,ccwRotationDegrees:x}){if(!I)return;const E=lt.parse(I.x),B=lt.parse(I.y);if(E===void 0||B===void 0)return;const S=lt.parse(C)??0,Q=lt.parse(y)??0;let w=S/2,M=Q/2;if(typeof x=="number"&&x!==0){const k=x*Math.PI/180,R=Math.abs(Math.cos(k)),F=Math.abs(Math.sin(k)),O=w*R+M*F,U=w*F+M*R;w=O,M=U}e=Math.min(e,E-w),n=Math.min(n,B-M),o=Math.max(o,E+w),i=Math.max(i,B+M),r=!0}function g({center:I,width:C,height:y}){if(!I)return;const x=lt.parse(I.x),E=lt.parse(I.y);if(x===void 0||E===void 0)return;const B=lt.parse(C)??0,S=lt.parse(y)??0,Q=B/2,w=S/2;s=Math.min(s,x-Q),a=Math.min(a,E-w),A=Math.max(A,x+Q),c=Math.max(c,E+w),r=!0,l=!0}function h(I){let C=!1;for(const y of I){const x=lt.parse(y.x),E=lt.parse(y.y);x===void 0||E===void 0||(e=Math.min(e,x),n=Math.min(n,E),o=Math.max(o,x),i=Math.max(i,E),C=!0)}C&&(r=!0)}function d(I){let C=!1;for(const y of I){const x=lt.parse(y.x),E=lt.parse(y.y);x===void 0||E===void 0||(s=Math.min(s,x),a=Math.min(a,E),A=Math.max(A,x),c=Math.max(c,E),C=!0)}C&&(r=!0,l=!0)}function p(I){let C=!1;for(const y of I)for(const x of m(y)){const E=lt.parse(x.x),B=lt.parse(x.y);E===void 0||B===void 0||(e=Math.min(e,E),n=Math.min(n,B),o=Math.max(o,E),i=Math.max(i,B),C=!0)}C&&(r=!0)}function m(I){return"route_type"in I?qKo(I):[I]}function _({text:I,anchorPosition:C,fontSize:y=1,anchorAlignment:x="center",ccwRotationDegrees:E=0}){if(!I||!C)return;const B=I.split(`
`),Q=Math.max(...B.map(k=>k.length),0)*y*.6,w=Math.max(B.length,1)*y,M=jVo({anchorPosition:C,textWidth:Q,textHeight:w,anchorAlignment:x});u({center:M,width:Q,height:w,ccwRotationDegrees:E})}function f(I){if(I.type==="pcb_silkscreen_text")u({center:I.anchor_position,width:0,height:0});else if(I.type==="pcb_silkscreen_graphic"){for(const C of I.brep_shape.outer_ring.vertices)u({center:{x:C.x,y:C.y},width:0,height:0});for(const C of I.brep_shape.inner_rings??[])for(const y of C.vertices)u({center:{x:y.x,y:y.y},width:0,height:0})}else if(I.type==="pcb_silkscreen_path")p(I.route);else if(I.type==="pcb_silkscreen_rect")u({center:I.center,width:I.width,height:I.height,ccwRotationDegrees:I.ccw_rotation});else if(I.type==="pcb_silkscreen_circle"){const C=lt.parse(I.radius);C!==void 0&&u({center:I.center,width:C*2,height:C*2})}else if(I.type==="pcb_silkscreen_line")u({center:{x:I.x1,y:I.y1},width:0,height:0}),u({center:{x:I.x2,y:I.y2},width:0,height:0});else if(I.type==="pcb_silkscreen_oval"){const C=lt.parse(I.radius_x),y=lt.parse(I.radius_y);C!==void 0&&y!==void 0&&u({center:I.center,width:C*2,height:y*2})}else if(I.type==="pcb_silkscreen_pill")u({center:I.center,width:I.width,height:I.height,ccwRotationDegrees:I.ccw_rotation});else if(I.type==="pcb_cutout"){const C=I;if(C.shape==="rect")u({center:C.center,width:C.width,height:C.height,ccwRotationDegrees:C.rotation});else if(C.shape==="circle"){const y=lt.parse(C.radius);y!==void 0&&u({center:C.center,width:y*2,height:y*2})}else if(C.shape==="polygon")p(C.points);else if(C.shape==="path"){const y=C;y.route&&Array.isArray(y.route)&&p(y.route)}}}}var qVo=({circuitJson:t,drawPaddingOutsideBoard:e,baseBounds:n,viewportOptions:o})=>{let i=e?1:0,r=e||!n.hasBoardBounds?n.minX:n.boardMinX,s=e||!n.hasBoardBounds?n.minY:n.boardMinY,a=e||!n.hasBoardBounds?n.maxX:n.boardMaxX,A=e||!n.hasBoardBounds?n.maxY:n.boardMaxY,c=!1,l=Number.POSITIVE_INFINITY,u=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,h=Number.NEGATIVE_INFINITY;const d=new Map,p=new Map;for(const m of t)if(m.type==="pcb_panel"){const _=m,f=lUt(_.center,_.width,_.height);if(!f)continue;l=Math.min(l,f.minX),u=Math.min(u,f.minY),g=Math.max(g,f.maxX),h=Math.max(h,f.maxY),c=!0,_.pcb_panel_id&&d.set(_.pcb_panel_id,f)}else if(m.type==="pcb_board"){const _=m,I=XVo(_.outline)??lUt(_.center,_.width,_.height);I&&_.pcb_board_id&&p.set(_.pcb_board_id,I)}if(o?.viewport){const{minX:m,minY:_,maxX:f,maxY:I}=o.viewport;r=m,s=_,a=f,A=I,i=0}else if(o?.viewportTarget?.pcb_panel_id){const m=d.get(o.viewportTarget.pcb_panel_id);if(!m)throw new Error(`Viewport target panel '${o.viewportTarget.pcb_panel_id}' not found`);r=m.minX,s=m.minY,a=m.maxX,A=m.maxY,i=0}else if(o?.viewportTarget?.pcb_board_id){const m=p.get(o.viewportTarget.pcb_board_id);if(!m)throw new Error(`Viewport target board '${o.viewportTarget.pcb_board_id}' not found`);r=m.minX,s=m.minY,a=m.maxX,A=m.maxY,i=0}else c&&(r=l,s=u,a=g,A=h);return{boundsMinX:r,boundsMinY:s,boundsMaxX:a,boundsMaxY:A,padding:i}};function lUt(t,e,n){if(!t||e===void 0||n===void 0)return;const o=lt.parse(t.x),i=lt.parse(t.y);if(o===void 0||i===void 0)return;const r=lt.parse(e),s=lt.parse(n);if(r===void 0||s===void 0)return;const a=r/2,A=s/2;return{minX:o-a,minY:i-A,maxX:o+a,maxY:i+A}}function XVo(t){if(!t||t.length<3)return;let e=Number.POSITIVE_INFINITY,n=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(const r of t){const s=lt.parse(r.x),a=lt.parse(r.y);s===void 0||a===void 0||(e=Math.min(e,s),n=Math.min(n,a),o=Math.max(o,s),i=Math.max(i,a))}if(!(!Number.isFinite(e)||!Number.isFinite(n))&&!(!Number.isFinite(o)||!Number.isFinite(i)))return{minX:e,minY:n,maxX:o,maxY:i}}var ZVo=.5,ezo=.42,tzo=.58,nzo=.75;function uUt(t,e){if(!e.showPinNumbers)return[];if(t.type==="pcb_smtpad"){if(e.layer&&t.layer!==e.layer)return[]}else if(e.layer&&!t.layers.includes(e.layer))return[];const n=_Ko(t,e.circuitJson);if(!n)return[];const o=ozo(t);if(!o||o.width<=0||o.height<=0)return[];const i=Math.abs(e.transform.a),r=Math.min(ZVo,o.height*ezo,o.width*nzo/(n.length*tzo));if(r<=0)return[];const[s,a]=hn(e.transform,[o.centerX,o.centerY]),A=t.type==="pcb_smtpad"?t.layer:"through",c=o.ccwRotation?`rotate(${-o.ccwRotation} ${s} ${a})`:void 0;return[{name:"text",type:"element",value:"",attributes:{class:"pcb-pad-pin-number",x:s.toString(),y:a.toString(),fill:"#b0b0b0","font-family":"Arial, sans-serif","font-size":(r*i).toString(),"font-weight":"500","text-anchor":"middle","dominant-baseline":"central","pointer-events":"none","data-type":"pcb_pad_pin_number","data-pcb-layer":A,"data-pin-number":n,...c?{transform:c}:{}},children:[{type:"text",value:n,name:"",attributes:{},children:[]}]}]}function ozo(t){if(t.type==="pcb_smtpad")return t.shape==="polygon"?gUt(t.points):t.shape==="circle"?{centerX:t.x,centerY:t.y,width:t.radius*2,height:t.radius*2,ccwRotation:0}:{centerX:t.x,centerY:t.y,width:t.width,height:t.height,ccwRotation:t.shape==="rotated_rect"||t.shape==="rotated_pill"?t.ccw_rotation:0};if(t.shape==="circle")return{centerX:t.x,centerY:t.y,width:t.outer_diameter,height:t.outer_diameter,ccwRotation:0};if(t.shape==="oval"||t.shape==="pill")return{centerX:t.x,centerY:t.y,width:t.outer_width,height:t.outer_height,ccwRotation:t.ccw_rotation};if(t.shape==="hole_with_polygon_pad"){const e=gUt(t.pad_outline);return e?{...e,centerX:t.x+e.centerX,centerY:t.y+e.centerY,ccwRotation:0}:void 0}if("rect_pad_width"in t)return{centerX:t.x,centerY:t.y,width:t.rect_pad_width,height:t.rect_pad_height,ccwRotation:t.shape==="rotated_pill_hole_with_rect_pad"?t.rect_ccw_rotation:t.shape==="circular_hole_with_rect_pad"?t.rect_ccw_rotation??0:0}}function gUt(t){if(t.length===0)return;const e=t.map(a=>a.x),n=t.map(a=>a.y),o=Math.min(...e),i=Math.max(...e),r=Math.min(...n),s=Math.max(...n);return{centerX:(o+i)/2,centerY:(r+s)/2,width:i-o,height:s-r,ccwRotation:0}}var dUt="rgb(255, 208, 66)";function izo(t,e){return t.map(n=>({...n,attributes:{...n.attributes??{},"data-type":e.type,"data-pcb-layer":"overlay"}}))}function rzo(t,e,n){if(!n.shouldDrawWarnings)return[];const o=e.find(_=>_.type==="pcb_component"&&_.pcb_component_id===t.pcb_component_id);if(!o)return[];const i=(o.rotation??0)*Math.PI/180,r=Math.cos(i),s=Math.sin(i),a=o.width/2,A=o.height/2,c=[{x:-a,y:-A},{x:a,y:-A},{x:a,y:A},{x:-a,y:A}].map(_=>hn(n.transform,{x:o.center.x+_.x*r-_.y*s,y:o.center.y+_.x*s+_.y*r})),l=Math.min(...c.map(_=>_.x)),u=Math.min(...c.map(_=>_.y)),g=Math.max(...c.map(_=>_.x)),h=Math.max(...c.map(_=>_.y)),d=g-l,p=h-u,m=l+d/2;return izo([{name:"rect",type:"element",value:"",attributes:{x:l.toString(),y:u.toString(),width:d.toString(),height:p.toString(),fill:"none",stroke:dUt,"stroke-width":"2","stroke-dasharray":"6,3"},children:[]},{name:"text",type:"element",value:"",attributes:{x:m.toString(),y:(u-10).toString(),fill:dUt,"font-family":"sans-serif","font-size":"12","font-weight":"600","text-anchor":"middle"},children:[{type:"text",name:"",value:t.message,attributes:{},children:[]}]}],t)}var hUt="#ff4d4d",szo=t=>({type:"text",value:t,name:"",attributes:{},children:[]}),QRe=({label:t,x:e,y:n,style:o,anchor:i="start"})=>t?[{name:"text",type:"element",value:"",attributes:{x:e.toString(),y:n.toString(),fill:hUt,"font-family":"monospace","font-size":o.fontSize.toString(),"font-weight":"600","text-anchor":i},children:[szo(t)]}]:[],azo=t=>({"data-type":"pcb_debug_object","data-pcb-layer":"overlay","data-pcb-debug-object-id":t.pcb_debug_object_id,"data-debug-shape":t.shape});function Azo({debugObject:t,transform:e,style:n,labelStackIndex:o=0}){const i=azo(t),r={fill:"none",stroke:hUt,"stroke-width":n.strokeWidth.toString(),"stroke-dasharray":`${n.dashLength},${n.dashLength}`};if(t.shape==="rect"){const A=hn(e,[t.center.x-t.size.width/2,t.center.y-t.size.height/2]),c=hn(e,[t.center.x+t.size.width/2,t.center.y+t.size.height/2]),l=Math.min(A[0],c[0]),u=Math.min(A[1],c[1]),g=Math.abs(c[0]-A[0]),h=Math.abs(c[1]-A[1]);return[{name:"g",type:"element",value:"",attributes:i,children:[{name:"rect",type:"element",value:"",attributes:{x:l.toString(),y:u.toString(),width:g.toString(),height:h.toString(),...r},children:[]},...QRe({label:t.label,x:l,y:u-n.labelGap-o*(n.fontSize+n.labelGap),style:n})]}]}if(t.shape==="line"){const[A,c]=hn(e,[t.start.x,t.start.y]),[l,u]=hn(e,[t.end.x,t.end.y]);return[{name:"g",type:"element",value:"",attributes:i,children:[{name:"line",type:"element",value:"",attributes:{x1:A.toString(),y1:c.toString(),x2:l.toString(),y2:u.toString(),...r},children:[]},...QRe({label:t.label,x:(A+l)/2,y:(c+u)/2-n.labelGap,style:n,anchor:"middle"})]}]}const[s,a]=hn(e,[t.center.x,t.center.y]);return[{name:"g",type:"element",value:"",attributes:i,children:[{name:"circle",type:"element",value:"",attributes:{cx:s.toString(),cy:a.toString(),r:n.pointRadius.toString(),...r},children:[]},...QRe({label:t.label,x:s+n.pointRadius+n.labelGap,y:a-n.pointRadius,style:n})]}]}function pUt(t,e){const n=e?.drawPaddingOutsideBoard??!0,o=e?.layer,i=e?.colorOverrides,r={...ch.copper};if(i?.copper)for(const[fe,pe]of Object.entries(i.copper))pe!==void 0&&(r[fe]=pe);const s={copper:r,drill:i?.drill??ch.drill,silkscreen:{top:i?.silkscreen?.top??ch.silkscreen.top,bottom:i?.silkscreen?.bottom??ch.silkscreen.bottom},boardOutline:i?.boardOutline??ch.boardOutline,soldermask:{top:i?.soldermask?.top??ch.soldermask.top,bottom:i?.soldermask?.bottom??ch.soldermask.bottom},soldermaskOverCopper:{top:i?.soldermaskOverCopper?.top??ch.soldermaskOverCopper.top,bottom:i?.soldermaskOverCopper?.bottom??ch.soldermaskOverCopper.bottom},soldermaskWithCopperUnderneath:{top:i?.soldermaskWithCopperUnderneath?.top??ch.soldermaskWithCopperUnderneath.top,bottom:i?.soldermaskWithCopperUnderneath?.bottom??ch.soldermaskWithCopperUnderneath.bottom},substrate:i?.substrate??ch.substrate,courtyard:{top:i?.courtyard?.top??ch.courtyard.top,bottom:i?.courtyard?.bottom??ch.courtyard.bottom},keepout:i?.keepout??ch.keepout,debugComponent:{fill:i?.debugComponent?.fill??ch.debugComponent.fill,stroke:i?.debugComponent?.stroke??ch.debugComponent.stroke}},a=e?.showCourtyards?t:t.filter(fe=>fe.type!=="pcb_courtyard_rect"),{minX:A,minY:c,maxX:l,maxY:u,boardMinX:g,boardMinY:h,boardMaxX:d,boardMaxY:p,hasBoardBounds:m}=$Vo(a),{boundsMinX:_,boundsMinY:f,boundsMaxX:I,boundsMaxY:C,padding:y}=qVo({circuitJson:t,drawPaddingOutsideBoard:n,baseBounds:{minX:A,minY:c,maxX:l,maxY:u,boardMinX:g,boardMinY:h,boardMaxX:d,boardMaxY:p,hasBoardBounds:m},viewportOptions:{viewport:e?.viewport,viewportTarget:e?.viewportTarget}}),x=I-_+2*y,E=C-f+2*y;let B=e?.width??800,S=e?.height??600;if(e?.matchBoardAspectRatio){const fe=I-_,pe=C-f;if(fe>0&&pe>0){const ye=fe/pe;e?.width&&!e?.height?S=e.width/ye:e?.height&&!e?.width?B=e.height*ye:S=B/ye}}const Q=[];for(const fe of t)"route"in fe&&fe.route!==void 0&&Q.push(fe.route);const w=B/x,M=S/E,k=Math.min(w,M),R=(B-x*k)/2,F=(S-E*k)/2,O=m0(of(R-_*k+y*k,S-F+f*k-y*k),kx(k,-k)),U=Math.min(B,S),Y=Math.max(1,Math.min(2,U*.002)),W=Math.max(10,Math.min(18,U*.02)),te={transform:O,layer:o,shouldDrawErrors:e?.shouldDrawErrors,shouldDrawWarnings:e?.shouldDrawWarnings,showCourtyards:e?.showCourtyards,showPcbGroups:e?.showPcbGroups,drawPaddingOutsideBoard:n,colorMap:s,showSolderMask:e?.showSolderMask,showSolderPaste:e?.showSolderPaste,showPcbNotes:e?.showPcbNotes??!0,showDebugObjects:e?.showDebugObjects,debugObjectStyle:{fontSize:W,strokeWidth:Y,dashLength:Y*4,labelGap:W*.35,pointRadius:Y*3},showAnchorOffsets:e?.showAnchorOffsets,showPinNumbers:e?.showPinNumbers,circuitJson:t,usedCopperPourTraceMaskIds:new Set};let j=t.flatMap(fe=>czo({elm:fe,circuitJson:t,ctx:te}));for(const fe of t)if("stroke_width"in fe){String(k*fe.stroke_width);break}if(e?.shouldDrawRatsNest){const fe=SVo(t,te);j=[...j,...fe]}const J=iVo(zVo(j)),oe=[{name:"style",type:"element",value:"",attributes:{},children:[{type:"text",value:"",name:"",attributes:{},children:[]}]}],ie=kVo({grid:e?.grid,svgWidth:B,svgHeight:S});ie.defs&&oe.push(ie.defs),t.some(fe=>fe.type==="pcb_keepout")&&oe.push(MVo(s.keepout??ch.keepout));const le=oVo({circuitJson:t,transform:O,svgWidth:B,svgHeight:S,usedMaskIds:te.usedCopperPourTraceMaskIds});if(le&&oe.push(le),oe.push({name:"rect",type:"element",value:"",attributes:{class:"boundary",x:"0",y:"0",fill:e?.backgroundColor??"#000",width:B.toString(),height:S.toString(),"data-type":"pcb_background","data-pcb-layer":"global"},children:[]}),n&&oe.push(lzo(O,A,c,l,u)),oe.push(...J),ie.rect&&oe.push(ie.rect),e?.showErrorsInTextOverlay){const fe=IG(t,"pcb_error_text_overlay");fe&&oe.push(fe)}const ge=Gw(t),_e=Yw,ue={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:B.toString(),height:S.toString(),...ge&&{"data-software-used-string":ge},...e?.includeVersion&&{"data-circuit-to-svg-version":_e}},value:"",children:oe.filter(fe=>fe!==null)};try{return Ow(ue)}catch(fe){throw console.error("Error stringifying SVG object:",fe),fe}}function czo({elm:t,circuitJson:e,ctx:n}){switch(t.type){case"pcb_debug_object":return n.showDebugObjects?Azo({debugObject:t,transform:n.transform,style:n.debugObjectStyle,labelStackIndex:t.shape==="rect"?e.slice(0,e.indexOf(t)).filter(i=>i.type==="pcb_debug_object"&&i.shape==="rect"&&i.center.x===t.center.x&&i.center.y===t.center.y&&i.size.width===t.size.width&&i.size.height===t.size.height).length:0}):[];case"pcb_trace_error":return FUo(t,e,n).filter(Boolean);case"pcb_footprint_overlap_error":return OUo(t,e,n).filter(Boolean);case"pcb_courtyard_overlap_error":return GUo(t,e,n).filter(Boolean);case"pcb_component_outside_board_error":return KUo(t,e,n).filter(Boolean);case"pcb_pad_trace_clearance_error":case"pcb_via_trace_clearance_error":return qUo(t,e,n).filter(Boolean);case"pcb_connector_not_in_accessible_orientation_warning":case"pcb_manual_edit_conflict_warning":return rzo(t,e,n);case"pcb_component":return LVo(t,n).filter(Boolean);case"pcb_trace":return rVo(t,n);case"pcb_copper_pour":return RVo(t,n);case"pcb_plated_hole":return[...IKo(t,n).filter(Boolean),...uUt(t,n)];case"pcb_hole":return EVo(t,n);case"pcb_smtpad":return[...dVo(t,n),...uUt(t,n)];case"pcb_solder_paste":return n.showSolderPaste?sUt(t,n):[];case"pcb_silkscreen_text":return MKo(t,n);case"pcb_silkscreen_rect":return DKo(t,n);case"pcb_silkscreen_circle":return kKo(t,n);case"pcb_silkscreen_line":return FKo(t,n);case"pcb_silkscreen_pill":return LKo(t,n);case"pcb_silkscreen_oval":return HKo(t,n);case"pcb_copper_text":return TKo(t,n);case"pcb_courtyard_rect":return n.showCourtyards?OKo(t,n):[];case"pcb_courtyard_polygon":return n.showCourtyards?GKo(t,n):[];case"pcb_courtyard_circle":return n.showCourtyards?UKo(t,n):[];case"pcb_courtyard_outline":return n.showCourtyards?YKo(t,n):[];case"pcb_fabrication_note_path":return XUo(t,n);case"pcb_fabrication_note_text":return ZUo(t,n);case"pcb_fabrication_note_rect":return nKo(t,n);case"pcb_fabrication_note_dimension":return sKo(t,n);case"pcb_note_dimension":return n.showPcbNotes?aKo(t,n):[];case"pcb_note_text":return n.showPcbNotes?cKo(t,n):[];case"pcb_note_rect":return n.showPcbNotes?gKo(t,n):[];case"pcb_note_path":return n.showPcbNotes?hKo(t,n):[];case"pcb_note_line":return n.showPcbNotes?mKo(t,n):[];case"pcb_silkscreen_path":return CKo(t,n);case"pcb_silkscreen_graphic":return yKo(t,n);case"pcb_panel":return n.drawPaddingOutsideBoard?xVo(t,n):[];case"pcb_board":return n.drawPaddingOutsideBoard?tUt(t,n):[];case"pcb_via":return KYt(t,n);case"pcb_cutout":const o=t;return o.shape==="path"?vVo(o,n):QVo(t,n);case"pcb_keepout":return DVo(t,n);case"pcb_group":return n.showPcbGroups?GVo(t,n):[];default:return[]}}function lzo(t,e,n,o,i){const[r,s]=hn(t,[e,n]),[a,A]=hn(t,[o,i]),c=Math.abs(a-r),l=Math.abs(A-s),u=Math.min(r,a),g=Math.min(s,A);return{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-boundary",fill:"none",stroke:"#fff","stroke-width":"0.3",x:u.toString(),y:g.toString(),width:c.toString(),height:l.toString(),"data-type":"pcb_boundary","data-pcb-layer":"global"}}}var uzo=pUt,tde={fill:"none",stroke:"rgb(0,0,0)",strokeOpacity:"0.8",strokeWidthFactor:.2};function gzo(t,e,n={}){const{width:o,height:i,center:r,outline:s}=t;let a;if(s&&Array.isArray(s)&&s.length>=3)a=s.map((A,c)=>{const[l,u]=hn(e,[A.x,A.y]);return c===0?`M ${l} ${u}`:`L ${l} ${u}`}).join(" ");else{const A=o/2,c=i/2,l=hn(e,[r.x-A,r.y-c]),u=hn(e,[r.x+A,r.y-c]),g=hn(e,[r.x+A,r.y+c]),h=hn(e,[r.x-A,r.y+c]);a=`M ${l[0]} ${l[1]} L ${u[0]} ${u[1]} L ${g[0]} ${g[1]} L ${h[0]} ${h[1]}`}return a+=" Z",[{name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-board",d:a,fill:n.fill??tde.fill,stroke:n.stroke??tde.stroke,"stroke-opacity":n.strokeOpacity??tde.strokeOpacity,"stroke-width":((n.strokeWidthFactor??tde.strokeWidthFactor)*Math.abs(e.a)).toString()}}]}var dzo={pin_number:.15,negated_pin_number:.15*.8,reference_designator:.18,manufacturer_number:.18,net_label:.18,error:.05},Uw=(t,e)=>e??dzo[t],pE=(t,e,n)=>Math.abs(t.a)*Uw(e,n);function hzo(t,e){const{elm:n,portPosition:o,name:i,arePinsInterchangeable:r}=t,{transform:s}=e,{center:a,width:A,height:c,rotation:l=0,layer:u="top"}=n;if(!a||typeof A!="number"||typeof c!="number")return null;const[g,h]=hn(s,[a.x,a.y]),[d,p]=hn(s,[o.x,o.y]),m=A*Math.abs(s.a),_=c*Math.abs(s.d),f=p>h,I=d<g,C=[pzo(m,_,l,u),mzo(m,_,i??"")];return r||C.push(_zo(m,_,l,u,f,I)),{name:"g",type:"element",value:"",attributes:{transform:`translate(${g}, ${h}) scale(1, -1)`},children:C}}function pzo(t,e,n,o){const i=t/2,r=e/2;return{name:"path",type:"element",attributes:{class:"assembly-component",d:fzo(i,r,n),"stroke-width":.8.toFixed(2),transform:`rotate(${-n})`,"stroke-dasharray":o==="bottom"?"2,2":""},value:"",children:[]}}function mzo(t,e,n,o){const i=Math.min(t,e),A=Math.min(58,Math.max(3,i*.8)),c=e>t;return{name:"text",type:"element",attributes:{x:"0",y:"0",class:"assembly-component-label","text-anchor":"middle",dy:".10em",style:"pointer-events: none","font-size":`${A.toFixed(1)}px`,transform:c?"rotate(90) scale(1, -1)":"scale(1, -1)"},children:[{type:"text",value:n||"",name:"",attributes:{},children:[]}],value:""}}function _zo(t,e,n,o,i,r){const s=t/2,a=e/2,A=Math.min(s,a)*.5;let c;return i&&r?c=[[-s,-a],[-s+A,-a],[-s,-a+A]]:i&&!r?c=[[s,-a],[s-A,-a],[s,-a+A]]:!i&&r?c=[[-s,a],[-s+A,a],[-s,a-A]]:c=[[s,a],[s-A,a],[s,a-A]],{name:"polygon",type:"element",attributes:{class:"assembly-pin1-indicator",points:c.map(u=>u.join(",")).join(" "),fill:"#333",stroke:"none",transform:`rotate(${-n})`},value:"",children:[]}}function fzo(t,e,n){const o=(a,A,c)=>{const l=Math.PI/180*c,u=Math.cos(l),g=Math.sin(l);return[a*u-A*g,a*g+A*u]};return`${[[-t,-e],[t,-e],[t,e],[-t,e]].map(([a,A])=>o(a,A,n)).map(([a,A],c)=>c===0?`M${a},${A}`:`L${a},${A}`).join(" ")} Z`}var vRe="rgb(190, 190, 190)";function Izo(t,e){const{transform:n}=e,[o,i]=hn(n,[t.x,t.y]);if(t.hole_shape==="circle"||t.hole_shape==="square"){const r=t.hole_diameter*Math.abs(n.a),s=r/2;return t.hole_shape==="circle"?[{name:"circle",type:"element",attributes:{class:"assembly-hole",cx:o.toString(),cy:i.toString(),r:s.toString(),fill:vRe},children:[],value:""}]:[{name:"rect",type:"element",attributes:{class:"assembly-hole",x:(o-s).toString(),y:(i-s).toString(),width:r.toString(),height:r.toString(),fill:vRe},children:[],value:""}]}if(t.hole_shape==="oval"){const r=t.hole_width*Math.abs(n.a),s=t.hole_height*Math.abs(n.a),a=r/2,A=s/2;return[{name:"ellipse",type:"element",attributes:{class:"assembly-hole",cx:o.toString(),cy:i.toString(),rx:a.toString(),ry:A.toString(),fill:vRe},children:[],value:""}]}return[]}var Iq="rgb(210, 210, 210)",Cq="rgb(190, 190, 190)";function Czo(t,e){const{transform:n}=e,[o,i]=hn(n,[t.x,t.y]);if(t.shape==="pill"){const r=t.outer_width*Math.abs(n.a),s=t.outer_height*Math.abs(n.a),a=t.hole_width*Math.abs(n.a),A=t.hole_height*Math.abs(n.a),c=r/2,l=s-r,u=a/2;return[{name:"g",type:"element",children:[{name:"path",type:"element",attributes:{class:"assembly-hole-outer",fill:Iq,d:`M${o-c},${i-l/2} v${l} a${c},${c} 0 0 0 ${r},0 v-${l} a${c},${c} 0 0 0 -${r},0 z`},value:"",children:[]},{name:"path",type:"element",attributes:{class:"assembly-hole-inner",fill:Cq,d:`M${o-u},${i-(A-a)/2} v${A-a} a${u},${u} 0 0 0 ${a},0 v-${A-a} a${u},${u} 0 0 0 -${a},0 z`},value:"",children:[]}],value:"",attributes:{}}]}if(t.shape==="circle"){const r=t.outer_diameter*Math.abs(n.a),s=t.outer_diameter*Math.abs(n.a),a=t.hole_diameter*Math.abs(n.a),A=t.hole_diameter*Math.abs(n.a),c=Math.min(r,s)/2,l=Math.min(a,A)/2;return[{name:"g",type:"element",children:[{name:"circle",type:"element",attributes:{class:"assembly-hole-outer",fill:Iq,cx:o.toString(),cy:i.toString(),r:c.toString()},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"assembly-hole-inner",fill:Cq,cx:o.toString(),cy:i.toString(),r:l.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(t.shape==="circular_hole_with_rect_pad"){const r=t,s=r.hole_diameter*Math.abs(n.a),a=r.rect_pad_width*Math.abs(n.a),A=r.rect_pad_height*Math.abs(n.a),c=(r.rect_border_radius??0)*Math.abs(n.a),l=r.rect_ccw_rotation??0,u=s/2,[g,h]=hn(n,[r.x+r.hole_offset_x,r.y+r.hole_offset_y]);return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"assembly-hole-outer-pad",fill:Iq,...l?{x:(-a/2).toString(),y:(-A/2).toString(),transform:`translate(${o} ${i}) rotate(${-l})`}:{x:(o-a/2).toString(),y:(i-A/2).toString()},width:a.toString(),height:A.toString(),...c?{rx:c.toString(),ry:c.toString()}:{}},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"assembly-hole-inner",fill:Cq,cx:g.toString(),cy:h.toString(),r:u.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(t.shape==="pill_hole_with_rect_pad"){const r=t,s=r.rect_pad_width*Math.abs(n.a),a=r.rect_pad_height*Math.abs(n.a),A=(r.rect_border_radius??0)*Math.abs(n.a),c=r.hole_height*Math.abs(n.a),l=r.hole_width*Math.abs(n.a),u=r,g=u.hole_offset_x??0,h=u.hole_offset_y??0,[d,p]=hn(n,[r.x+g,r.y+h]),m=Math.min(c,l)/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"assembly-hole-outer-pad",fill:Iq,x:(o-s/2).toString(),y:(i-a/2).toString(),width:s.toString(),height:a.toString(),...A?{rx:A.toString(),ry:A.toString()}:{}},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"assembly-hole-inner",fill:Cq,x:(d-l/2).toString(),y:(p-c/2).toString(),width:l.toString(),height:c.toString(),rx:m.toString(),ry:m.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(t.shape==="rotated_pill_hole_with_rect_pad"){const r=t,s=r.rect_pad_width*Math.abs(n.a),a=r.rect_pad_height*Math.abs(n.a),A=(r.rect_border_radius??0)*Math.abs(n.a),c=r.hole_height*Math.abs(n.a),l=r.hole_width*Math.abs(n.a),u=r,g=u.hole_offset_x??0,h=u.hole_offset_y??0,[d,p]=hn(n,[r.x+g,r.y+h]),m=Math.min(c,l)/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"assembly-hole-outer-pad",fill:Iq,x:(-s/2).toString(),y:(-a/2).toString(),width:s.toString(),height:a.toString(),transform:`translate(${o} ${i}) rotate(${-r.rect_ccw_rotation})`,...A?{rx:A.toString(),ry:A.toString()}:{}},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"assembly-hole-inner",fill:Cq,x:(-l/2).toString(),y:(-c/2).toString(),width:l.toString(),height:c.toString(),rx:m.toString(),ry:m.toString(),transform:`translate(${d} ${p}) rotate(${-r.hole_ccw_rotation})`},value:"",children:[]}],value:"",attributes:{}}]}return[]}var yq="rgb(210, 210, 210)";function yzo(t,e){const{transform:n}=e;if(t.shape==="rect"||t.shape==="rotated_rect"){const o=t.width*Math.abs(n.a),i=t.height*Math.abs(n.d),[r,s]=hn(n,[t.x,t.y]),a=(t.rect_border_radius??0)*Math.abs(n.a);return t.shape==="rotated_rect"&&t.ccw_rotation?[{name:"rect",type:"element",attributes:{class:"assembly-pad",fill:yq,x:(-o/2).toString(),y:(-i/2).toString(),width:o.toString(),height:i.toString(),transform:`translate(${r} ${s}) rotate(${-t.ccw_rotation})`,"data-layer":t.layer,...a?{rx:a.toString(),ry:a.toString()}:{}},value:"",children:[]}]:[{name:"rect",type:"element",attributes:{class:"assembly-pad",fill:yq,x:(r-o/2).toString(),y:(s-i/2).toString(),width:o.toString(),height:i.toString(),"data-layer":t.layer,...a?{rx:a.toString(),ry:a.toString()}:{}},value:"",children:[]}]}if(t.shape==="pill"){const o=t.width*Math.abs(n.a),i=t.height*Math.abs(n.d),r=t.radius*Math.abs(n.a),[s,a]=hn(n,[t.x,t.y]);return[{name:"rect",type:"element",attributes:{class:"assembly-pad",fill:yq,x:(s-o/2).toString(),y:(a-i/2).toString(),width:o.toString(),height:i.toString(),rx:r.toString(),ry:r.toString(),"data-layer":t.layer},value:"",children:[]}]}if(t.shape==="circle"){const o=t.radius*Math.abs(n.a),[i,r]=hn(n,[t.x,t.y]);return[{name:"circle",type:"element",attributes:{class:"assembly-pad",fill:yq,cx:i.toString(),cy:r.toString(),r:o.toString(),"data-layer":t.layer},value:"",children:[]}]}if(t.shape==="polygon"){const o=(t.points??[]).map(i=>hn(n,[i.x,i.y]));return[{name:"polygon",type:"element",attributes:{class:"assembly-pad",fill:yq,points:o.map(i=>i.join(",")).join(" "),"data-layer":t.layer},value:"",children:[]}]}return[]}var mUt=["pcb_component","pcb_smtpad","pcb_hole","pcb_plated_hole","pcb_board"];function _Ut(t,e){let n=Number.POSITIVE_INFINITY,o=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(const E of t)if(E.type==="pcb_board"){const B=E.center,S=E.width||0,Q=E.height||0;n=Math.min(n,B.x-S/2),o=Math.min(o,B.y-Q/2),i=Math.max(i,B.x+S/2),r=Math.max(r,B.y+Q/2)}const s=1,a=i-n+2*s,A=r-o+2*s,c=e?.width??800,l=e?.height??600,u=c/a,g=l/A,h=Math.min(u,g),d=(c-a*h)/2,p=(l-A*h)/2,m=m0(of(d-n*h+s*h,l-p+o*h-s*h),kx(h,-h)),_={transform:m},f=t.sort((E,B)=>(mUt.indexOf(B.type)??9999)-(mUt.indexOf(E.type)??9999)).flatMap(E=>xzo(E,_,t)),I=Gw(t),C=Yw,y=[{name:"style",type:"element",children:[{type:"text",value:`
              .assembly-component { 
                fill: none; 
                stroke: #000; 
              }
              .assembly-board { 
                fill: #f2f2f2; 
                stroke: rgb(0,0,0); 
                stroke-opacity: 0.8;
              }
              .assembly-component-label { 
                fill: #000; 
                font-family: Arial, serif;
                font-weight: bold;
                dominant-baseline: middle;
                text-anchor: middle;
              }
              .assembly-boundary { 
                fill: none; 
                stroke: #fff;
                stroke-width: 0.2; 
              }
            `,name:"",attributes:{},children:[]}],value:"",attributes:{}},{name:"rect",type:"element",attributes:{fill:"#fff",x:"0",y:"0",width:c.toString(),height:l.toString()},value:"",children:[]},Ezo(m,n,o,i,r),...f].filter(E=>E!==null);if(e?.showErrorsInTextOverlay){const E=IG(t);E&&y.push(E)}const x={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:c.toString(),height:l.toString(),...I&&{"data-software-used-string":I},...e?.includeVersion&&{"data-circuit-to-svg-version":C}},value:"",children:y};return Ow(x)}function xzo(t,e,n){const o=Mr(n).source_component.list();switch(t.type){case"pcb_board":return gzo(t,e.transform);case"pcb_component":{const i=o.find(a=>a.source_component_id===t.source_component_id),s=Mr(n).pcb_port.list().filter(a=>a.pcb_component_id===t.pcb_component_id)[0];if(i&&s){const a=i.are_pins_interchangeable,A=hzo({elm:t,portPosition:{x:s.x,y:s.y},name:i.name,arePinsInterchangeable:a},e);return A?[A]:[]}return[]}case"pcb_smtpad":return yzo(t,e);case"pcb_hole":return Izo(t,e);case"pcb_plated_hole":return Czo(t,e);default:return[]}}function Ezo(t,e,n,o,i){const[r,s]=hn(t,[e,n]),[a,A]=hn(t,[o,i]),c=Math.abs(a-r),l=Math.abs(A-s),u=Math.min(r,a),g=Math.min(s,A);return{name:"rect",type:"element",value:"",children:[],attributes:{class:"assembly-boundary",x:u.toString(),y:g.toString(),width:c.toString(),height:l.toString()}}}var Bzo="rgb(26, 115, 143)",bzo="rgba(0,0,0,0.9)";function Szo(t,e){const{transform:n,soup:o}=e,{width:i,height:r,center:s,outline:a}=t,c=o.find(h=>h.type==="source_board"&&h.title)?.title;let l;if(a&&Array.isArray(a)&&a.length>=3)l=a.map((h,d)=>{const[p,m]=hn(n,[h.x,h.y]);return d===0?`M ${p} ${m}`:`L ${p} ${m}`}).join(" ");else{const h=i/2,d=r/2,p=hn(n,[s.x-h,s.y-d]),m=hn(n,[s.x+h,s.y-d]),_=hn(n,[s.x+h,s.y+d]),f=hn(n,[s.x-h,s.y+d]);l=`M ${p[0]} ${p[1]} L ${m[0]} ${m[1]} L ${_[0]} ${_[1]} L ${f[0]} ${f[1]}`}l+=" Z";const u=Mr(o).pcb_cutout.list();for(const h of u)if(h.shape==="rect"){const{x:d,y:p,width:m,height:_}=h.center?(()=>{const{x:B,y:S}=h.center,{width:Q,height:w}=h;return{x:B,y:S,width:Q,height:w}})():{x:0,y:0,width:0,height:0},f=m/2,I=_/2,[C,y,x,E]=[hn(n,[d-f,p-I]),hn(n,[d+f,p-I]),hn(n,[d+f,p+I]),hn(n,[d-f,p+I])];l+=` M ${C[0]} ${C[1]} L ${y[0]} ${y[1]} L ${x[0]} ${x[1]} L ${E[0]} ${E[1]} Z`}else h.shape;const g=[{name:"path",type:"element",value:"",children:[],attributes:{class:"pinout-board",d:l,fill:Bzo,stroke:bzo,"fill-rule":"evenodd","stroke-opacity":"0.8","stroke-width":(.2*Math.abs(n.a)).toString()}}];if(c){const h=e.svgWidth/2;g.push({name:"text",type:"element",value:"",children:[{name:"",type:"text",value:c,attributes:{},children:[]}],attributes:{x:h.toString(),y:30 .toString(),"text-anchor":"middle","font-size":"18px","font-weight":"bold","font-family":"Arial, sans-serif",fill:"black",class:"pinout-board-title"}})}return g}var Qzo="rgba(120, 120, 120, 0.6)",vzo="rgba(255, 255, 255, 0.9)";function wzo(t,e){const{transform:n,soup:o}=e,{center:i,width:r,height:s,rotation:a=0,source_component_id:A}=t,c=Mr(o).source_component.get(A);if(!i||typeof r!="number"||typeof s!="number"||r===0||s===0)return[];const[l,u]=hn(n,[i.x,i.y]),g=r*Math.abs(n.a),h=s*Math.abs(n.d),d=`translate(${l}, ${u})`,p=[{name:"rect",type:"element",attributes:{class:"pinout-component-box",x:(-g/2).toString(),y:(-h/2).toString(),width:g.toString(),height:h.toString(),fill:Qzo,transform:`rotate(${a}deg)`},value:"",children:[]}];if(c?.name){const m=Math.min(g,h)*.4;p.push({name:"text",type:"element",attributes:{x:"0",y:"0",fill:vzo,"font-size":`${m}px`,"font-family":"sans-serif","text-anchor":"middle","dominant-baseline":"middle"},children:[{type:"text",value:c.name,name:"",attributes:{},children:[]}],value:""})}return[{name:"g",type:"element",attributes:{transform:d},children:p,value:""}]}var wRe="rgb(50, 50, 50)";function Pzo(t,e){const{transform:n}=e,[o,i]=hn(n,[t.x,t.y]);if(t.hole_shape==="circle"||t.hole_shape==="square"){const r=t.hole_diameter*Math.abs(n.a),s=r/2;return t.hole_shape==="circle"?[{name:"circle",type:"element",attributes:{class:"pinout-hole",cx:o.toString(),cy:i.toString(),r:s.toString(),fill:wRe},children:[],value:""}]:[{name:"rect",type:"element",attributes:{class:"pinout-hole",x:(o-s).toString(),y:(i-s).toString(),width:r.toString(),height:r.toString(),fill:wRe},children:[],value:""}]}if(t.hole_shape==="oval"){const r=t.hole_width*Math.abs(n.a),s=t.hole_height*Math.abs(n.a),a=r/2,A=s/2;return[{name:"ellipse",type:"element",attributes:{class:"pinout-hole",cx:o.toString(),cy:i.toString(),rx:a.toString(),ry:A.toString(),fill:wRe},children:[],value:""}]}return[]}var xq="rgb(218, 165, 32)",Eq="rgb(40, 40, 40)";function Mzo(t,e){const{transform:n}=e,[o,i]=hn(n,[t.x,t.y]);if(t.shape==="pill"){const r=t.outer_width*Math.abs(n.a),s=t.outer_height*Math.abs(n.a),a=t.hole_width*Math.abs(n.a),A=t.hole_height*Math.abs(n.a),c=r/2,l=s-r,u=a/2;return[{name:"g",type:"element",children:[{name:"path",type:"element",attributes:{class:"pinout-hole-outer",fill:xq,d:`M${o-c},${i-l/2} v${l} a${c},${c} 0 0 0 ${r},0 v-${l} a${c},${c} 0 0 0 -${r},0 z`},value:"",children:[]},{name:"path",type:"element",attributes:{class:"pinout-hole-inner",fill:Eq,d:`M${o-u},${i-(A-a)/2} v${A-a} a${u},${u} 0 0 0 ${a},0 v-${A-a} a${u},${u} 0 0 0 -${a},0 z`},value:"",children:[]}],value:"",attributes:{}}]}if(t.shape==="circle"){const r=t.outer_diameter*Math.abs(n.a),s=t.outer_diameter*Math.abs(n.a),a=t.hole_diameter*Math.abs(n.a),A=t.hole_diameter*Math.abs(n.a),c=Math.min(r,s)/2,l=Math.min(a,A)/2;return[{name:"g",type:"element",children:[{name:"circle",type:"element",attributes:{class:"pinout-hole-outer",fill:xq,cx:o.toString(),cy:i.toString(),r:c.toString()},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pinout-hole-inner",fill:Eq,cx:o.toString(),cy:i.toString(),r:l.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(t.shape==="circular_hole_with_rect_pad"){const r=t.hole_diameter*Math.abs(n.a),s=t.rect_pad_width*Math.abs(n.a),a=t.rect_pad_height*Math.abs(n.a),A=r/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"pinout-hole-outer-pad",fill:xq,x:(o-s/2).toString(),y:(i-a/2).toString(),width:s.toString(),height:a.toString()},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pinout-hole-inner",fill:Eq,cx:o.toString(),cy:i.toString(),r:A.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(t.shape==="pill_hole_with_rect_pad"){const r=t.rect_pad_width*Math.abs(n.a),s=t.rect_pad_height*Math.abs(n.a),a=t.hole_height*Math.abs(n.a),A=t.hole_width*Math.abs(n.a),c=Math.min(a,A)/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"pinout-hole-outer-pad",fill:xq,x:(o-r/2).toString(),y:(i-s/2).toString(),width:r.toString(),height:s.toString()},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pinout-hole-inner",fill:Eq,x:(o-A/2).toString(),y:(i-a/2).toString(),width:A.toString(),height:a.toString(),rx:c.toString(),ry:c.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(t.shape==="rotated_pill_hole_with_rect_pad"){const r=t.rect_pad_width*Math.abs(n.a),s=t.rect_pad_height*Math.abs(n.a),a=t.hole_height*Math.abs(n.a),A=t.hole_width*Math.abs(n.a),c=Math.min(a,A)/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"pinout-hole-outer-pad",fill:xq,x:(-r/2).toString(),y:(-s/2).toString(),width:r.toString(),height:s.toString(),transform:`translate(${o} ${i}) rotate(${-t.rect_ccw_rotation})`},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pinout-hole-inner",fill:Eq,x:(-A/2).toString(),y:(-a/2).toString(),width:A.toString(),height:a.toString(),rx:c.toString(),ry:c.toString(),transform:`translate(${o} ${i}) rotate(${-t.hole_ccw_rotation})`},value:"",children:[]}],value:"",attributes:{}}]}return[]}var Bq="rgb(218, 165, 32)";function Dzo(t,e){const{transform:n}=e;if(t.shape==="rect"||t.shape==="rotated_rect"){const o=t.width*Math.abs(n.a),i=t.height*Math.abs(n.d),[r,s]=hn(n,[t.x,t.y]);return t.shape==="rotated_rect"&&t.ccw_rotation?[{name:"rect",type:"element",attributes:{class:"pinout-pad",fill:Bq,x:(-o/2).toString(),y:(-i/2).toString(),width:o.toString(),height:i.toString(),transform:`translate(${r} ${s}) rotate(${-t.ccw_rotation})`,"data-layer":t.layer},value:"",children:[]}]:[{name:"rect",type:"element",attributes:{class:"pinout-pad",fill:Bq,x:(r-o/2).toString(),y:(s-i/2).toString(),width:o.toString(),height:i.toString(),"data-layer":t.layer},value:"",children:[]}]}if(t.shape==="pill"){const o=t.width*Math.abs(n.a),i=t.height*Math.abs(n.d),r=t.radius*Math.abs(n.a),[s,a]=hn(n,[t.x,t.y]);return[{name:"rect",type:"element",attributes:{class:"pinout-pad",fill:Bq,x:(s-o/2).toString(),y:(a-i/2).toString(),width:o.toString(),height:i.toString(),rx:r.toString(),ry:r.toString(),"data-layer":t.layer},value:"",children:[]}]}if(t.shape==="circle"){const o=t.radius*Math.abs(n.a),[i,r]=hn(n,[t.x,t.y]);return[{name:"circle",type:"element",attributes:{class:"pinout-pad",fill:Bq,cx:i.toString(),cy:r.toString(),r:o.toString(),"data-layer":t.layer},value:"",children:[]}]}if(t.shape==="polygon"){const o=(t.points??[]).map(i=>hn(n,[i.x,i.y]));return[{name:"polygon",type:"element",attributes:{class:"pinout-pad",fill:Bq,points:o.map(i=>i.join(",")).join(" "),"data-layer":t.layer},value:"",children:[]}]}return[]}function PRe(t){const{rectX:e,rectY:n,rectWidth:o,rectHeight:i,textX:r,textY:s,text:a,fontSize:A,labelBackground:c,labelColor:l,rx:u=4,ry:g=4,fontFamily:h="Arial, sans-serif",fontWeight:d="bold",textAnchor:p="middle",dominantBaseline:m="middle"}=t;return[{name:"rect",type:"element",attributes:{x:e.toString(),y:n.toString(),width:o.toString(),height:i.toString(),fill:c,rx:typeof u=="number"?u.toString():u,ry:typeof g=="number"?g.toString():g,stroke:"none"},children:[],value:""},{name:"text",type:"element",attributes:{x:r.toString(),y:s.toString(),fill:l,"font-size":`${A}px`,"font-family":h,"font-weight":d,"text-anchor":p,"dominant-baseline":m},children:[{type:"text",value:a,name:"",attributes:{},children:[]}],value:""}]}var fUt="rgb(255, 255, 255)",IUt="rgb(0, 0, 0)",Nzo="rgba(0, 0, 0, 0.6)",Rzo="rgb(200, 200, 200)",Tzo="rgb(0, 0, 0)";function kzo(t,e){const n=e.label_positions.get(t.pcb_port_id);if(!n)return[];const{text:o,aliases:i,elbow_end:r,label_pos:s,edge:a}=n,[A,c]=hn(e.transform,[t.x,t.y]),l=a==="left"?"x-":a==="right"?"x+":a==="top"?"y-":"y+",u=a==="left"?"x+":a==="right"?"x-":a==="top"?"y+":"y-",g=wF({x:A,y:c,facingDirection:l},{x:r.x,y:r.y,facingDirection:u},{}),h=/^pin(\d+)$/i.exec(o),d=[{text:h?h[1]:o,bg:h?Rzo:IUt,color:h?Tzo:fUt},...i.map(F=>({text:F,bg:IUt,color:fUt}))],p=Math.abs(e.transform.a),m=e.styleScale??1,f=1.6*m*p,I=Math.max(.08,.25*m),y=.3*m*p,x=I*p,E={x:s.x+(a==="left"?-x/2:x/2),y:s.y},B=[...g,E].map(F=>`${F.x},${F.y}`).join(" "),S=f*(11/21),Q=(f-S)/2,w=Q,M=d.map(({text:F,bg:O,color:U})=>{const Y=F??"",te=Y.length*S*.6+2*Q;return{text:Y,rectWidth:te,bg:O,color:U}}),k=s.y,R=[{name:"polyline",type:"element",attributes:{points:B,stroke:Nzo,"stroke-width":(I*p).toString(),fill:"none"},children:[],value:""}];if(a==="left"){let F=s.x;for(const{text:O,rectWidth:U,bg:Y,color:W}of M){const te=F-U,j=te+U/2;R.push(...PRe({rectX:te,rectY:k-f/2,rectWidth:U,rectHeight:f,textX:j,textY:k,text:O,fontSize:S,labelBackground:Y,labelColor:W,rx:y,ry:y})),F=te-w}}else if(a==="right"){let F=s.x;for(const{text:O,rectWidth:U,bg:Y,color:W}of M){const te=F,j=te+U/2;R.push(...PRe({rectX:te,rectY:k-f/2,rectWidth:U,rectHeight:f,textX:j,textY:k,text:O,fontSize:S,labelBackground:Y,labelColor:W,rx:y,ry:y})),F=te+U+w}}else{const F=M.reduce((U,Y)=>U+Y.rectWidth,0)+w*Math.max(0,M.length-1);let O=s.x-F/2;for(const{text:U,rectWidth:Y,bg:W,color:te}of M){const j=O,J=j+Y/2;R.push(...PRe({rectX:j,rectY:k-f/2,rectWidth:Y,rectHeight:f,textX:J,textY:k,text:U,fontSize:S,labelBackground:W,labelColor:te,rx:y,ry:y})),O=j+Y+w}}return R}var CUt=1.6,Fzo=11/21,Lzo=.6,yUt=.1,xUt=.1,MRe=3,EUt=.1,Hzo=.8;function BUt(t,e,{transform:n,soup:o,board_bounds:i,svgHeight:r,styleScale:s},a){const A=e.map(R=>R.pcb_port.x),c={};for(const R of A){const F=R.toFixed(1);c[F]=(c[F]||0)+1}let l;if(Object.keys(c).length>1&&e.length>2){const R=Object.entries(c).sort((J,oe)=>oe[1]-J[1]),F=parseFloat(R[0][0]),O=e.filter(J=>Math.abs(J.pcb_port.x-F)<.2),U=e.filter(J=>Math.abs(J.pcb_port.x-F)>=.2),Y=J=>({pcb_port:J.pcb_port,y:hn(n,[J.pcb_port.x,J.pcb_port.y])[1],aliases:J.aliases});O.sort((J,oe)=>oe.pcb_port.y-J.pcb_port.y),U.sort((J,oe)=>oe.pcb_port.y-J.pcb_port.y);const W=O.length>0?Math.max(...O.map(J=>J.pcb_port.y)):-1/0;l=((U.length>0?Math.max(...U.map(J=>J.pcb_port.y)):-1/0)>W?[...U,...O]:[...O,...U]).map(Y)}else l=e.map(R=>({pcb_port:R.pcb_port,y:hn(n,[R.pcb_port.x,R.pcb_port.y])[1],aliases:R.aliases})).sort((R,F)=>R.y-F.y);if(l.length===0)return;const u=hn(n,[t==="left"?i.minX:i.maxX,0])[0],g=l.length,h={};for(const R of e){const F=R.pcb_port.x.toFixed(1);h[F]=(h[F]||0)+1}let d=new Set;if(Object.keys(h).length>1&&e.length>2){const R=Object.entries(h).sort((U,Y)=>Y[1]-U[1]),F=parseFloat(R[0][0]),O=e.filter(U=>Math.abs(U.pcb_port.x-F)<.2);d=new Set(O.map(U=>U.pcb_port.pcb_port_id))}const p=l.map((R,F)=>d.has(R.pcb_port.pcb_port_id)?F:-1).filter(R=>R!==-1),m=(g-1)/2,_=Math.abs(n.a),f=CUt*s*_,C=Math.max(.2*_,.3*s*_),y=Hzo*s*_,x=(yUt+g*xUt)*s*_,B=x+m*(MRe*s*_)+EUt*s*_,S=g-p.length,Q=p.length===0?g:S,w=Q*f+Math.max(0,Q-1)*C;let M;if(p.length>0&&S>0){const R=p.map(j=>l[j].y),F=Math.min(...R),O=Math.max(...R),U=F-f/2,Y=O+f/2;l.map((j,J)=>J).filter(j=>!p.includes(j))[0]<p[0]?M=U-(C*2+y)-w+f/2:M=Y+(C*2+y)+f/2}else M=(r-w)/2+f/2;const k=p.length===g;l.forEach(({pcb_port:R,aliases:F},O)=>{let U;if(p.length>0)if(p.includes(O))U=m;else{const ie=Math.min(...p),ne=Math.max(...p);let le;O<ie?le=ie-O:le=O-ne,U=m-le}else{const ie=Math.abs(O-m);U=m-ie}const Y=x+U*(MRe*s*_),W=t==="left"?-1:1,te=p.includes(O),j=k||p.length>0&&te?l[O].y:M,J={x:u+W*Y,y:j},oe={x:u+W*B,y:j};a.set(R.pcb_port_id,{text:F[0],aliases:F.slice(1),elbow_end:J,label_pos:oe,edge:t}),p.length>0&&te||(M+=f+C)})}var Ozo=({left_labels:t,right_labels:e,transform:n,soup:o,board_bounds:i,svgWidth:r,svgHeight:s,styleScale:a})=>{const A=new Map,c={transform:n,soup:o,board_bounds:i};return BUt("left",t,{...c,svgHeight:s,styleScale:a},A),BUt("right",e,{...c,svgHeight:s,styleScale:a},A),A};function Gzo(t,e){const n=Mr(e).source_port.get(t.source_port_id);if(!n)return null;const o=n.port_hints?.filter(s=>!/^\d+$/.test(s)&&!["left","right","top","bottom"].includes(s))??[];let i=o[0];if(i||(i=n.name),!i)return null;const r=o.filter(s=>s!==i);return{text:i,aliases:r}}function Yzo(t,e){const n={left:t.x-e.minX,right:e.maxX-t.x,top:e.maxY-t.y,bottom:t.y-e.minY};let o="left",i=n.left;return n.right<i&&(i=n.right,o="right"),n.top<i&&(i=n.top,o="top"),n.bottom<i&&(i=n.bottom,o="bottom"),o}var bUt=["pcb_board","pcb_smtpad","pcb_hole","pcb_plated_hole","pcb_component","pcb_port"];function SUt(t,e){let n=Number.POSITIVE_INFINITY,o=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(const pe of t)if(pe.type==="pcb_board")if("outline"in pe&&pe.outline&&Array.isArray(pe.outline)&&pe.outline.length>0)for(const ye of pe.outline)n=Math.min(n,ye.x),o=Math.min(o,ye.y),i=Math.max(i,ye.x),r=Math.max(r,ye.y);else{const ye=pe.center,Me=pe.width||0,ve=pe.height||0;n=Math.min(n,ye.x-Me/2),o=Math.min(o,ye.y-ve/2),i=Math.max(i,ye.x+Me/2),r=Math.max(r,ye.y+ve/2)}const s=2;let a=e?.width??1200,A=e?.height??768;t.find(pe=>pe.type==="source_board"&&!!pe.title)?.title;const c={minX:n,minY:o,maxX:i,maxY:r},l=t.filter(pe=>pe.type==="pcb_port"&&pe.is_board_pinout),u=[];for(const pe of l){const ye=Gzo(pe,t);if(!ye)continue;const Me=Yzo({x:pe.x,y:pe.y},c);u.push({pcb_port:pe,aliases:[ye.text,...ye.aliases],edge:Me})}const g=u.filter(pe=>pe.edge==="left"),h=u.filter(pe=>pe.edge==="right"),d=u.filter(pe=>pe.edge==="top"),p=u.filter(pe=>pe.edge==="bottom"),m=(n+i)/2;d.length>0&&(d.filter(ye=>ye.pcb_port.x<m).length>d.length/2?g.push(...d):h.push(...d)),p.length>0&&(p.filter(ye=>ye.pcb_port.x<m).length>p.length/2?g.push(...p):h.push(...p));const f=t.filter(pe=>pe.type==="pcb_smtpad").map(pe=>{if(typeof pe.height=="number")return pe.height;if(typeof pe.radius=="number")return pe.radius*2}).filter(pe=>Number.isFinite(pe)),I=f.length?f.reduce((pe,ye)=>pe+ye,0)/f.length:void 0,y=I?Math.max(.5,Math.min(1,I/1)):1,x=CUt*y;function E(pe){const ye=[...pe.aliases??[]];if(ye.length===0)return ye;const Me=/^pin(\d+)$/i.exec(ye[0]);return Me&&(ye[0]=Me[1]),ye}function B(pe){if(pe.length===0)return 0;const ye=x,Me=ye*Fzo,ve=(ye-Me)/2,he=ve;return pe.map(we=>(we??"").length*Me*Lzo+2*ve).reduce((we,Te)=>we+Te,0)+he*Math.max(0,pe.length-1)}function S(pe){if(pe<=0)return 0;const ye=(pe-1)/2;return(yUt+pe*xUt)*y+ye*(MRe*y)+EUt*y}const Q=Math.max(0,...g.map(pe=>B(E(pe)))),w=Math.max(0,...h.map(pe=>B(E(pe)))),M=S(g.length)+Q,k=S(h.length)+w,R=n-M,O=i+k-R+2*s,U=r-o+2*s,Y=a/O,W=A/U,te=Math.min(Y,W),j=(a-O*te)/2,J=(A-U*te)/2,oe=m0(of(j-R*te+s*te,A-J+o*te-s*te),kx(te,-te)),ie=Ozo({left_labels:g,right_labels:h,transform:oe,soup:t,board_bounds:c,svgWidth:a,svgHeight:A,styleScale:y}),ne={transform:oe,soup:t,styleScale:y,label_positions:ie,svgWidth:a},le=t.sort((pe,ye)=>(bUt.indexOf(pe.type)??9999)-(bUt.indexOf(ye.type)??9999)).flatMap(pe=>Uzo(pe,ne)),ge=Gw(t),_e=Yw,ue=[{name:"rect",type:"element",attributes:{fill:"rgb(255, 255, 255)",x:"0",y:"0",width:a.toString(),height:A.toString()},value:"",children:[]},...le].filter(pe=>pe!==null);if(e?.showErrorsInTextOverlay){const pe=IG(t);pe&&ue.push(pe)}const fe={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:a.toString(),height:A.toString(),...ge&&{"data-software-used-string":ge},...e?.includeVersion&&{"data-circuit-to-svg-version":_e}},value:"",children:ue};return Ow(fe)}function Uzo(t,e,n){switch(t.type){case"pcb_board":return Szo(t,e);case"pcb_component":return wzo(t,e);case"pcb_smtpad":return Dzo(t,e);case"pcb_hole":return Pzo(t,e);case"pcb_plated_hole":return Mzo(t,e);case"pcb_port":return t.is_board_pinout?kzo(t,e):[];default:return[]}}function Kzo(t){const{minX:e,minY:n,maxX:o,maxY:i}=t.bounds,r=t.cellSize??1,s=t.labelCells??!1,a=[],A=(c,l)=>{const[u,g]=hn(t.transform,[c,l]);return{x:u,y:g}};for(let c=Math.floor(e);c<=Math.ceil(o);c+=r){const l=A(c,n),u=A(c,i);a.push({name:"line",type:"element",attributes:{x1:l.x.toString(),y1:l.y.toString(),x2:u.x.toString(),y2:u.y.toString(),stroke:Lg.schematic.grid,"stroke-width":(.01*Math.abs(t.transform.a)).toString(),"stroke-opacity":"0.5"}})}for(let c=Math.floor(n);c<=Math.ceil(i);c+=r){const l=A(e,c),u=A(o,c);a.push({name:"line",type:"element",attributes:{x1:l.x.toString(),y1:l.y.toString(),x2:u.x.toString(),y2:u.y.toString(),stroke:Lg.schematic.grid,"stroke-width":(.01*Math.abs(t.transform.a)).toString(),"stroke-opacity":"0.5"}})}if(s){const c=(l,u)=>r<=.1?`${l.toFixed(1)},${u.toFixed(1)}`:`${l},${u}`;for(let l=Math.floor(e);l<=Math.ceil(o);l+=r)for(let u=Math.floor(n);u<=Math.ceil(i);u+=r){const g=A(l,u);a.push({name:"text",type:"element",attributes:{x:(g.x-2.5).toString(),y:(g.y-5).toString(),fill:Lg.schematic.grid,"font-size":(r/5*Math.abs(t.transform.a)).toString(),"fill-opacity":"0.5","text-anchor":"middle","dominant-baseline":"middle","font-family":"sans-serif"},children:[{type:"text",value:c(l,u),name:"",attributes:{},children:[]}]})}}return{name:"g",value:"",type:"element",attributes:{class:"grid sch-grid"},children:a}}function Vzo(t){const{points:e,transform:n}=t,o=[];for(const i of e){const[r,s]=hn(n,[i.x-.1,i.y-.1]),[a,A]=hn(n,[i.x+.1,i.y+.1]),[c,l]=hn(n,[i.x-.1,i.y+.1]),[u,g]=hn(n,[i.x+.1,i.y-.1]);o.push({name:"path",type:"element",attributes:{d:`M${r},${s} L${a},${A} M${c},${l} L${u},${g}`,stroke:Lg.schematic.grid,"stroke-width":(.02*Math.abs(n.a)).toString(),"stroke-opacity":"0.7"}});const[h,d]=hn(n,[i.x+.15,i.y-.15]);o.push({name:"text",type:"element",attributes:{x:h.toString(),y:d.toString(),fill:Lg.schematic.grid,"font-size":(.1*Math.abs(n.a)).toString(),"fill-opacity":"0.7","text-anchor":"start","font-family":"sans-serif","dominant-baseline":"middle"},children:[{type:"text",value:i.label||`(${i.x},${i.y})`,name:"",attributes:{},children:[]}]})}return{name:"g",value:"",type:"element",attributes:{class:"labeled-points sch-labeled-points"},children:o}}function zzo(t){return t.reduce((e,n)=>e?n.sheet_index===void 0?e:e.sheet_index===void 0||n.sheet_index<e.sheet_index?n:e:n,void 0)}var QUt={0:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},1:{width:13,height:27,ascent:22,descent:5,left:-3,right:9},2:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},3:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},4:{width:13,height:27,ascent:22,descent:5,left:0,right:12},5:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},6:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},7:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},8:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},9:{width:13,height:27,ascent:22,descent:5,left:-1,right:12}," ":{width:7,height:27,ascent:22,descent:5,left:0,right:0},"!":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},'"':{width:9,height:27,ascent:22,descent:5,left:-1,right:7},"#":{width:13,height:27,ascent:22,descent:5,left:0,right:13},$:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},"%":{width:21,height:27,ascent:22,descent:5,left:-1,right:20},"&":{width:16,height:27,ascent:22,descent:5,left:-1,right:15},"'":{width:5,height:27,ascent:22,descent:5,left:-1,right:3},"(":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},")":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"*":{width:9,height:27,ascent:22,descent:5,left:-1,right:8},"+":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},",":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"-":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},".":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"/":{width:7,height:27,ascent:22,descent:5,left:0,right:7},":":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},";":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"<":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},"=":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},">":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},"?":{width:13,height:27,ascent:22,descent:5,left:-1,right:12},"@":{width:24,height:27,ascent:22,descent:5,left:-1,right:23},A:{width:16,height:27,ascent:22,descent:5,left:0,right:16},B:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},C:{width:17,height:27,ascent:22,descent:5,left:-1,right:16},D:{width:17,height:27,ascent:22,descent:5,left:-2,right:16},E:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},F:{width:15,height:27,ascent:22,descent:5,left:-2,right:14},G:{width:19,height:27,ascent:22,descent:5,left:-1,right:17},H:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},I:{width:7,height:27,ascent:22,descent:5,left:-2,right:5},J:{width:12,height:27,ascent:22,descent:5,left:-1,right:10},K:{width:16,height:27,ascent:22,descent:5,left:-2,right:16},L:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},M:{width:20,height:27,ascent:22,descent:5,left:-2,right:18},N:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},O:{width:19,height:27,ascent:22,descent:5,left:-1,right:18},P:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},Q:{width:19,height:27,ascent:22,descent:5,left:-1,right:18},R:{width:17,height:27,ascent:22,descent:5,left:-2,right:17},S:{width:16,height:27,ascent:22,descent:5,left:-1,right:15},T:{width:15,height:27,ascent:22,descent:5,left:-1,right:14},U:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},V:{width:16,height:27,ascent:22,descent:5,left:0,right:16},W:{width:23,height:27,ascent:22,descent:5,left:0,right:22},X:{width:16,height:27,ascent:22,descent:5,left:0,right:16},Y:{width:16,height:27,ascent:22,descent:5,left:0,right:16},Z:{width:15,height:27,ascent:22,descent:5,left:0,right:14},"[":{width:7,height:27,ascent:22,descent:5,left:-2,right:6},"\\":{width:7,height:27,ascent:22,descent:5,left:0,right:7},"]":{width:7,height:27,ascent:22,descent:5,left:0,right:5},"^":{width:11,height:27,ascent:22,descent:5,left:-1,right:11},_:{width:13,height:27,ascent:22,descent:5,left:0,right:14},"`":{width:8,height:27,ascent:22,descent:5,left:-1,right:5},a:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},b:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},c:{width:12,height:27,ascent:22,descent:5,left:-1,right:12},d:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},e:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},f:{width:7,height:27,ascent:22,descent:5,left:0,right:8},g:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},h:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},i:{width:5,height:27,ascent:22,descent:5,left:-2,right:4},j:{width:5,height:27,ascent:22,descent:5,left:1,right:4},k:{width:12,height:27,ascent:22,descent:5,left:-2,right:12},l:{width:5,height:27,ascent:22,descent:5,left:-2,right:4},m:{width:20,height:27,ascent:22,descent:5,left:-2,right:18},n:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},o:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},p:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},q:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},r:{width:8,height:27,ascent:22,descent:5,left:-2,right:8},s:{width:12,height:27,ascent:22,descent:5,left:-1,right:11},t:{width:7,height:27,ascent:22,descent:5,left:0,right:6},u:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},v:{width:12,height:27,ascent:22,descent:5,left:0,right:12},w:{width:17,height:27,ascent:22,descent:5,left:0,right:17},x:{width:12,height:27,ascent:22,descent:5,left:0,right:12},y:{width:12,height:27,ascent:22,descent:5,left:0,right:12},z:{width:12,height:27,ascent:22,descent:5,left:0,right:11},"{":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"|":{width:6,height:27,ascent:22,descent:5,left:-2,right:4},"}":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"~":{width:14,height:27,ascent:22,descent:5,left:-1,right:13}},bq=t=>{if(!t)return 0;let e=0;for(const n of t){const o=QUt[n];o?e+=o.width:e+=QUt["?"].width}return e/27},vUt=.65,wUt=.08;function nde(t){return bq(t.text||"")+(t.display_superscript?wUt+bq(t.display_superscript)*vUt:0)}function DRe(t,e,n,o="central"){const i=[{type:"text",value:t,name:"",attributes:{},children:[]}];return e&&i.push({type:"element",name:"tspan",value:"",attributes:{class:"sch-net-label-superscript","font-size":`${n*vUt}px`,dx:`${n*wUt}`,dy:`${-n*(o==="ideographic"?.5:.25)}`},children:[{type:"text",value:e,name:"",attributes:{},children:[]}]}),i}var CG=t=>{switch(t){case"top":return{x:0,y:-1};case"bottom":return{x:0,y:1};case"left":return{x:1,y:0};case"right":return{x:-1,y:0}}throw new Error(`Invalid side: ${t}`)},Kw=.3,yG=.3,xG=.06,PUt=.2,MUt=t=>({"data-circuit-json-type":"schematic_net_label","data-schematic-net-label-id":t.schematic_net_label_id}),Jzo={top_left:"start",top_right:"end",middle_left:"start",middle_right:"end",bottom_left:"start",bottom_right:"end",center:"middle",middle_top:"middle",middle_bottom:"middle"},DUt={top_left:"hanging",top_right:"hanging",bottom_left:"ideographic",bottom_right:"ideographic",center:"middle",middle_left:"middle",middle_right:"middle",middle_top:"hanging",middle_bottom:"ideographic"};function Wzo(t){return{left:180,top:90,bottom:-90,right:0}[t]??0}function jzo(t,e,n){const o=n+Kw*2+xG*t.text.length+yG,i=CG(t.anchor_side);return t.anchor_position??{x:t.center.x-i.x*o*e/2,y:t.center.y-i.y*o*e/2}}var $zo=(t,e)=>{const n=t<0?t+2*Math.PI:t,o=e<0?e+2*Math.PI:e;let i=Math.abs(n-o);return i>Math.PI&&(i=2*Math.PI-i),i},NUt=({schPorts:t,symbol:e,schComponent:n})=>{const o=t.map(a=>{const A=a.center.x-n.center.x,c=a.center.y-n.center.y;return{port:a,angle:Math.atan2(c,A)}}),i=e.ports.map(a=>{const A=a.x-e.center.x,c=a.y-e.center.y;return{port:a,angle:Math.atan2(c,A)}});o.sort((a,A)=>a.angle-A.angle),i.sort((a,A)=>a.angle-A.angle);const r=[],s=new Set;for(const a of o){let A=null;for(const c of i){if(s.has(c.port))continue;const l=$zo(a.angle,c.angle);(A===null||l<A.angleDiff)&&(A={symbolPort:c.port,angleDiff:l})}A&&A.angleDiff<Math.PI/4&&(r.push({schPort:a.port,symbolPort:A.symbolPort}),s.add(A.symbolPort))}return r};function RUt(t,e,n,o){const i=e.x-t.x,r=e.y-t.y,s=Math.sqrt((n.x-t.x)**2+(n.y-t.y)**2),A=Math.sqrt((o.x-e.x)**2+(o.y-e.y)**2)/s,c=of(i,r),l=kx(A,A);return m0(c,l)}function qzo(t){const e=[],n=new Map,o=new Map;let i=null;for(const r of t)if(r.type==="schematic_component")e.push(r);else if(r.type==="schematic_port"&&r.schematic_component_id){const s=n.get(r.schematic_component_id)??[];s.push(r),n.set(r.schematic_component_id,s)}else r.type==="source_component"&&o.set(r.source_component_id,r);for(const r of e){const s=Xzo({component:r,schematicPorts:n.get(r.schematic_component_id)??[],sourceComponent:r.source_component_id?o.get(r.source_component_id):void 0});s&&(i=i?TUt(i,s):s)}return i}function Xzo({component:t,schematicPorts:e,sourceComponent:n}){if(!t.symbol_name)return null;const o=Su[t.symbol_name];if(!o)return null;const i=NUt({schPorts:e,symbol:o,schComponent:t});if(!i[0])return null;const r=RUt(i[1]?.symbolPort??o.center,i[1]?.schPort.center??t.center,i[0].symbolPort,i[0].schPort.center);let s=null;for(const a of o.primitives){if(a.type!=="text")continue;const A=Zzo({primitive:a,component:t,sourceComponent:n});if(!A)continue;const c=hn(r,a),l=Uw("reference_designator"),u=eJo({x:c.x,y:c.y,width:bq(A)*l,height:l,anchor:a.anchor});s=s?TUt(s,u):u}return s}function Zzo({primitive:t,component:e,sourceComponent:n}){return t.text==="{REF}"?n?.display_name??n?.name??"":t.text==="{VAL}"?e.symbol_display_value??"":""}function eJo({x:t,y:e,width:n,height:o,anchor:i}){let r=t,s=t,a=e-o/2,A=e+o/2;return i.includes("left")?s=t+n:i.includes("right")?r=t-n:(r=t-n/2,s=t+n/2),i.includes("top")?(a=e-o,A=e):i.includes("bottom")&&(a=e,A=e+o),{minX:r,minY:a,maxX:s,maxY:A}}function TUt(t,e){return{minX:Math.min(t.minX,e.minX),minY:Math.min(t.minY,e.minY),maxX:Math.max(t.maxX,e.maxX),maxY:Math.max(t.maxY,e.maxY)}}var kUt=(t,e)=>{if(t.column_widths&&t.column_widths.length>0&&t.row_heights&&t.row_heights.length>0){const l=u=>typeof u=="number"?u:u.endsWith("mm")?parseFloat(u):u.endsWith("in")?parseFloat(u)*25.4:parseFloat(u);return{column_widths:t.column_widths.map(l),row_heights:t.row_heights.map(l)}}const n=e.filter(l=>l.type==="schematic_table_cell"&&l.schematic_table_id===t.schematic_table_id);if(n.length===0)return{column_widths:[],row_heights:[]};const o=n.reduce((l,u)=>Math.max(l,u.end_column_index),-1)+1,i=n.reduce((l,u)=>Math.max(l,u.end_row_index),-1)+1,{cell_padding:r=.2}=t,s=new Array(o).fill(0),a=new Array(i).fill(0),A={},c={};for(const l of n){const u=Uw("reference_designator",l.font_size),h=bq(l.text??"")*u+2*r,d=u*1.2+2*r,p=`${l.start_row_index}-${l.start_column_index}`;A[p]=h,c[p]=d}for(let l=0;l<i;l++)for(let u=0;u<o;u++){const g=`${l}-${u}`;A[g]&&A[g]>s[u]&&(s[u]=A[g]),c[g]&&c[g]>a[l]&&(a[l]=c[g])}for(const l of n){if(l.start_column_index===l.end_column_index&&l.start_row_index===l.end_row_index)continue;const u=`${l.start_row_index}-${l.start_column_index}`,g=A[u],h=c[u];if(g===void 0||h===void 0)continue;let d=0;for(let m=l.start_column_index;m<=l.end_column_index;m++)d+=s[m];if(g>d){const _=(g-d)/(l.end_column_index-l.start_column_index+1);for(let f=l.start_column_index;f<=l.end_column_index;f++)s[f]+=_}let p=0;for(let m=l.start_row_index;m<=l.end_row_index;m++)p+=a[m];if(h>p){const _=(h-p)/(l.end_row_index-l.start_row_index+1);for(let f=l.start_row_index;f<=l.end_row_index;f++)a[f]+=_}}return{column_widths:s,row_heights:a}},tJo=10.16,nJo=1.1,MR=tJo/nJo,oJo=297/MR,iJo=210/MR,ode=5/MR;function Sq(t={}){const e=t.center??{x:0,y:0},n=t.sheet_width===void 0?oJo:t.sheet_width/MR,o=t.sheet_height===void 0?iJo:t.sheet_height/MR,i=e.x-n/2,r=e.x+n/2,s=e.y-o/2,a=e.y+o/2;return{center:e,width:n,height:o,minX:i,maxX:r,minY:s,maxY:a,innerMinX:i+ode,innerMaxX:r-ode,innerMinY:s+ode,innerMaxY:a-ode}}function rJo(t,e=.5){let n=Number.POSITIVE_INFINITY,o=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,r=Number.NEGATIVE_INFINITY;const s=.2;for(const c of t)if(c.type==="schematic_sheet"){const l=Sq(c);A(l.center,{width:l.width,height:l.height},0)}else if(c.type==="schematic_component")A(c.center,c.size,0);else if(c.type==="schematic_port")A(c.center,{width:s,height:s},0);else if(c.type==="schematic_debug_object")c.shape==="rect"?A(c.center,c.size,0):c.shape==="line"&&(A(c.start,{width:.1,height:.1},0),A(c.end,{width:.1,height:.1},0));else if(c.type==="schematic_net_label"){const l=Uw("net_label"),u=nde(c),h=(u+Kw*2+xG*(c.text?.length||0)+yG)*l,d=PUt,p=Wzo(c.anchor_side)/180*Math.PI,m=jzo(c,l,u),_=CG(c.anchor_side),f={x:m.x+_.x*h/2,y:m.y+_.y*h/2};A(f,{width:h,height:d},p)}else if(c.type==="schematic_trace")for(const l of c.edges)A(l.from,{width:.1,height:.1},0),A(l.to,{width:.1,height:.1},0);else if(c.type==="schematic_text"){const u=Uw("reference_designator",c.font_size)??.18,g=c.text??"",h=c.display_superscript;if(h){const d=g.split(`
`),p=Math.max(...d.map((x,E)=>nde({text:x,display_superscript:E===d.length-1?h:void 0})))*u,m=c.anchor,_=m==="left"||m.endsWith("_left")?p/2:m==="right"||m.endsWith("_right")?-p/2:0,f=m==="top"||m.startsWith("top_")?0:m==="bottom"||m.startsWith("bottom_")?-u:-u/2,I=(d.length+.3)*u,C=-(f-.3*u+I/2),y=-(c.rotation??0)*Math.PI/180;A({x:c.position.x+_*Math.cos(y)-C*Math.sin(y),y:c.position.y+_*Math.sin(y)+C*Math.cos(y)},{width:p,height:I},y)}else{const d=g.length*u,p=u;A(c.position,{width:d,height:p},c.rotation??0)}}else if(c.type==="schematic_voltage_probe"){if(A(c.position,{width:.2,height:.4},0),c.name){const l=Uw("net_label"),u=bq(c.name)*l,g=l,h=.3,d=c.label_alignment??"top_right";let p=c.position.x,m=c.position.y;d.includes("top")?m+=h+g/2:d.includes("bottom")&&(m-=h+g/2),d.includes("right")?p+=h+u/2:d.includes("left")&&(p-=h+u/2),A({x:p,y:m},{width:u,height:g},0)}}else if(c.type==="schematic_box")A({x:c.x+c.width/2,y:c.y+c.height/2},{width:c.width,height:c.height},0);else if(c.type==="schematic_table"){const{column_widths:l,row_heights:u}=kUt(c,t),g=l.reduce((I,C)=>I+C,0),h=u.reduce((I,C)=>I+C,0),d=c.anchor??"center";let p=c.anchor_position.x,m=c.anchor_position.y;d.includes("center")?p-=g/2:d.includes("right")&&(p-=g),d.includes("center")?m+=h/2:d.includes("bottom")&&(m+=h);const _=p+g/2,f=m-h/2;A({x:_,y:f},{width:g,height:h},0)}else if(c.type==="schematic_line")A({x:c.x1,y:c.y1},{width:.02,height:.02},0),A({x:c.x2,y:c.y2},{width:.02,height:.02},0);else if(c.type==="schematic_circle")A(c.center,{width:c.radius*2,height:c.radius*2},0);else if(c.type==="schematic_rect")A(c.center,{width:c.width,height:c.height},c.rotation);else if(c.type==="schematic_arc")A(c.center,{width:c.radius*2,height:c.radius*2},0);else if(c.type==="schematic_path"&&c.points&&c.points.length>0)for(const l of c.points)A(l,{width:.02,height:.02},0);Number.isFinite(n)||(n=-1,o=-1,i=1,r=1),n-=e,o-=e,i+=e,r+=e;const a=qzo(t);return a&&(a.minX<n&&(n=a.minX-e),a.minY<o&&(o=a.minY-e),a.maxX>i&&(i=a.maxX+e),a.maxY>r&&(r=a.maxY+e)),{minX:n,minY:o,maxX:i,maxY:r};function A(c,l,u){const g=[{x:-l.width/2,y:-l.height/2},{x:l.width/2,y:-l.height/2},{x:l.width/2,y:l.height/2},{x:-l.width/2,y:l.height/2}];for(const h of g){const d=h.x*Math.cos(u)-h.y*Math.sin(u)+c.x,p=h.x*Math.sin(u)+h.y*Math.cos(u)+c.y;n=Math.min(n,d),o=Math.min(o,p),i=Math.max(i,d),r=Math.max(r,p)}}}function NRe(t){if(t.type!=="element")throw new Error("Expected SVG root element to be of type 'element'");return t}function FUt(t){return{...t,attributes:{...t.attributes??{}},children:t.children?.map(FUt)??[]}}function Qq(t,e,n,o,i){const r=FUt(t);return r.attributes={...r.attributes,x:lm(e),y:lm(n),width:lm(o),height:lm(i)},delete r.attributes.xmlns,r}function lm(t){return Number.isFinite(t)?Number.parseFloat(t.toFixed(6)).toString():"0"}var vq="image/svg+xml";function sJo({schematicGraphic:t,viewport:e}){const n=aJo(t);return{name:"g",type:"element",value:"",attributes:{class:"schematic-graphic","pointer-events":"none","data-circuit-json-type":"schematic_graphic","data-schematic-graphic-id":t.schematic_graphic_id,...t.schematic_sheet_id?{"data-schematic-sheet-id":t.schematic_sheet_id}:{}},children:[{name:"image",type:"element",value:"",attributes:{href:n,x:lm(e.x),y:lm(e.y),width:lm(e.width),height:lm(e.height),preserveAspectRatio:"xMidYMid meet",overflow:"hidden","pointer-events":"none"},children:[]}]}}function aJo(t){const e=`Unable to render schematic graphic "${t.schematic_graphic_id}"`,{asset:n,svg_content:o}=t;if(!n){if(o!==void 0)return LUt(o);throw new Error(`${e}: asset or svg_content is required`)}if(HUt(n.mimetype)!==vq)throw new Error(`${e}: asset.mimetype must be "${vq}" (received ${JSON.stringify(n.mimetype)})`);const i=n.url.trim();if(i.toLowerCase().startsWith("data:"))return AJo(i,e),i;if(o!==void 0)return LUt(o);throw new Error(`${e}: asset.url must be an inline SVG data URL because circuit-to-svg cannot synchronously load ${JSON.stringify(n.url)}`)}function AJo(t,e){const n=t.match(/^data:([^,]*),(.*)$/is);if(!n)throw new Error(`${e}: asset.url is not a valid SVG data URL`);const o=n[1].split(";").map(A=>A.trim());if(HUt(o.shift()??"")!==vq)throw new Error(`${e}: asset.url must use the "${vq}" media type`);const r=n[2],s=o.findIndex(A=>A.toLowerCase()==="base64"),a=s!==-1;if(a&&s!==o.length-1)throw new Error(`${e}: asset.url must place "base64" as its final metadata token`);if(a){const A=r.replace(/\s+/g,"");if(!/^(?:[a-z\d+/]{4})*(?:[a-z\d+/]{2}==|[a-z\d+/]{3}=)?$/i.test(A))throw new Error(`${e}: asset.url is not a valid SVG data URL`);return}if(r.includes("#"))throw new Error(`${e}: asset.url must percent-encode "#" in a non-base64 SVG data URL`);try{decodeURIComponent(r)}catch(A){throw new Error(`${e}: asset.url is not a valid SVG data URL`,{cause:A})}}function LUt(t){const e=new TextEncoder().encode(t);let n="";const o=32768;for(let i=0;i<e.length;i+=o)n+=String.fromCharCode(...e.subarray(i,i+o));return`data:${vq};base64,${btoa(n)}`}function HUt(t){return(t.split(";",1)[0]??"").trim().toLowerCase()}var i_=t=>Math.abs(t.a)*.02,RRe=({text:t,realCenter:e,realToScreenTransform:n})=>{const o=hn(n,e);return{type:"element",name:"text",value:"",attributes:{x:o.x.toString(),y:o.y.toString(),fill:"red","text-anchor":"middle","dominant-baseline":"middle","font-family":"sans-serif","font-size":`${pE(n,"error")}px`},children:[{type:"text",value:t,name:"",attributes:{},children:[]}]}},cJo=({schNetLabel:t,realToScreenTransform:e,colorMap:n})=>{if(!t.text)return[];const o=t.text.startsWith("N_"),i=o?t.text.slice(2):t.text,r=MUt(t),s=[],a=Su[t.symbol_name];if(!a){const O=RRe({text:`Symbol not found: ${t.symbol_name}`,realCenter:t.center,realToScreenTransform:e});return O.attributes={...O.attributes,...r},s.push(O),s}const A=a.primitives.filter(O=>O.type==="path"),c=a.primitives.filter(O=>O.type==="text"),l=a.primitives.filter(O=>O.type==="circle"),u=a.primitives.filter(O=>O.type==="box"),g={minX:Math.min(...A.flatMap(O=>O.points.map(U=>U.x))),maxX:Math.max(...A.flatMap(O=>O.points.map(U=>U.x))),minY:Math.min(...A.flatMap(O=>O.points.map(U=>U.y))),maxY:Math.max(...A.flatMap(O=>O.points.map(U=>U.y)))},h=Uw("net_label"),p=nde({...t,text:i})+Kw*2+xG*i.length+yG,m=CG(t.anchor_side),_=t.anchor_position??{x:t.center.x-m.x*p*h/2,y:t.center.y-m.y*p*h/2},I=jb(0/180*Math.PI),C={minX:Math.min(...a.primitives.flatMap(O=>O.type==="path"?O.points.map(U=>U.x):[])),maxX:Math.max(...a.primitives.flatMap(O=>O.type==="path"?O.points.map(U=>U.x):[])),minY:Math.min(...a.primitives.flatMap(O=>O.type==="path"?O.points.map(U=>U.y):[])),maxY:Math.max(...a.primitives.flatMap(O=>O.type==="path"?O.points.map(U=>U.y):[]))},y=a.ports?.[0]?{x:a.ports[0].x,y:a.ports[0].y}:{x:C.minX,y:(C.minY+C.maxY)/2},x=hn(I,y),E=m0(of(_.x-x.x,_.y-x.y),I,kx(1)),[B,S]=hn(m0(e,E),[g.minX,g.minY]),[Q,w]=hn(m0(e,E),[g.maxX,g.maxY]),M=Math.abs(w-S),k=Math.min(S,w),R=Math.abs(Q-B),F=Math.min(B,Q);s.push({name:"rect",type:"element",value:"",attributes:{class:"component-overlay sch-component-overlay sch-net-label-overlay",...r,x:F.toString(),y:k.toString(),width:R.toString(),height:M.toString(),fill:"transparent"},children:[]});for(const O of A){const U=O.points.map((Y,W)=>{const[te,j]=hn(m0(e,E),[Y.x,Y.y]);return`${W===0?"M":"L"} ${te} ${j}`}).join(" ");s.push({name:"path",type:"element",attributes:{class:"sch-net-label-symbol-path",...r,d:U+(O.closed?" Z":""),stroke:n.schematic.component_outline,fill:"none","stroke-width":`${i_(e)}px`,"stroke-linecap":"round"},value:"",children:[]})}for(const O of c){const U=hn(m0(e,E),O);let Y=O.text;Y==="{REF}"?Y=i||"":Y==="{VAL}"&&(Y=""),Math.abs(e.a);const W={x:U.x,y:U.y};s.push({name:"text",type:"element",attributes:{class:"sch-net-label-symbol-text",...r,x:W.x.toString(),y:W.y.toString(),fill:n.schematic.label_local,"font-family":"sans-serif","text-anchor":Jzo[O.anchor],"dominant-baseline":DUt[O.anchor],"font-size":`${pE(e,"reference_designator")}px`,...o&&Y===i?{style:"text-decoration: overline;"}:{}},children:DRe(Y,O.text==="{REF}"?t.display_superscript:void 0,pE(e,"reference_designator"),DUt[O.anchor]),value:""})}for(const O of u){const U=hn(m0(e,E),O),Y=m0(e,E).a;s.push({name:"rect",type:"element",attributes:{class:"sch-net-label-symbol-box",...r,x:U.x.toString(),y:U.y.toString(),width:(O.width*Y).toString(),height:(O.height*Y).toString(),fill:"red"},value:"",children:[]})}for(const O of l){const U=hn(m0(e,E),O),Y=m0(e,E).a;s.push({name:"circle",type:"element",attributes:{class:"sch-net-label-symbol-circle",...r,cx:U.x.toString(),cy:U.y.toString(),r:(O.radius*Y).toString(),fill:"none",stroke:n.schematic.component_outline,"stroke-width":`${i_(e)}px`},value:"",children:[]})}return s},lJo=({schNetLabel:t,realToScreenTransform:e,colorMap:n})=>{if(!t.text)return[];const o=t.text;if(t.symbol_name)return cJo({schNetLabel:t,realToScreenTransform:e,colorMap:n});const i=MUt(t),r=[],s=pE(e,"net_label"),a=Uw("net_label"),A=PUt/a/2,c=nde({...t,text:o}),l=hn(e,t.center),u=CG(t.anchor_side),g={...u};g.y*=-1;const h=c+Kw*2+xG*o.length+yG,d=t.anchor_position?hn(e,t.anchor_position):{x:l.x-g.x*h*s/2,y:l.y-g.y*h*s/2},p=t.anchor_position??{x:t.center.x-u.x*h*a/2,y:t.center.y-u.y*h*a/2},m={left:0,top:-90,bottom:90,right:180}[t.anchor_side],_=[{x:0,y:0},{x:Kw,y:A},{x:Kw*2+yG+xG*o.length+c,y:A},{x:Kw*2+yG+xG*o.length+c,y:-A},{x:Kw,y:-A}].map(x=>hn(m0(e,of(p.x,p.y),kx(a),jb(m/180*Math.PI)),x)),f=`
    M ${_[0].x},${_[0].y}
    L ${_[1].x},${_[1].y}
    L ${_[2].x},${_[2].y}
    L ${_[3].x},${_[3].y}
    L ${_[4].x},${_[4].y}
    Z
  `;r.push({name:"path",type:"element",attributes:{class:"net-label sch-net-label",...i,d:f,fill:n.schematic.label_background,stroke:n.schematic.label_global,"stroke-width":`${i_(e)}px`},value:"",children:[]});const I={x:d.x+g.x*s*.5,y:d.y+g.y*s*.5},C={left:"start",top:"start",bottom:"start",right:"end"}[t.anchor_side],y={left:"",right:"",top:`rotate(90 ${I.x} ${I.y})`,bottom:`rotate(-90 ${I.x} ${I.y})`}[t.anchor_side];return r.push({name:"text",type:"element",attributes:{class:"net-label-text sch-net-label-text",...i,x:I.x.toString(),y:I.y.toString(),fill:n.schematic.label_global,"text-anchor":C,"dominant-baseline":"central","font-family":"sans-serif","font-variant-numeric":"tabular-nums","font-size":`${s}px`,transform:y},children:DRe(o,t.display_superscript,s),value:""}),r},uJo=.02,gJo=({schPort:t,transform:e})=>{const n=hn(e,t.center),o=Math.abs(e.a)*uJo*2;return[{name:"g",type:"element",value:"",attributes:{class:"schematic-port-hover sch-port-hover","data-schematic-port-id":t.source_port_id,...t.schematic_sheet_id?{"data-schematic-sheet-id":t.schematic_sheet_id}:{}},children:[{name:"circle",type:"element",value:"",attributes:{cx:n.x.toString(),cy:n.y.toString(),r:o.toString(),fill:"red",opacity:"0"},children:[]}]}]},OUt=({component:t,transform:e,circuitJson:n})=>{const o=Mr(n).schematic_port.list({schematic_component_id:t.schematic_component_id}),i=[];for(const r of o)i.push(...gJo({schPort:r,transform:e}));return i},dJo=({schPort:t,transform:e,colorMap:n})=>{const{x:i,y:r}=t.center,s=[-1,1].map(a=>{const A=hn(e,{x:i-.05,y:r-a*.05}),c=hn(e,{x:i+.05,y:r+a*.05});return`M ${A.x} ${A.y} L ${c.x} ${c.y}`}).join(" ");return{name:"path",type:"element",value:"",attributes:{class:"sch-port-no-connect","data-schematic-port-id":t.schematic_port_id,"data-source-port-id":t.source_port_id,d:s,fill:"none",stroke:n.schematic.no_connect,"stroke-width":`${i_(e)}px`,"stroke-linecap":"round"},children:[]}},GUt=.02,hJo=({schPort:t,transform:e,circuitJson:n,colorMap:o})=>{const i=[],r=Math.abs(e.a)*GUt,s=Math.abs(e.a)*GUt,a=hn(e,t.center),A=n.find(l=>l.type==="source_port"&&l.source_port_id===t.source_port_id);A?.do_not_connect||i.push({name:"circle",type:"element",value:"",attributes:{class:"component-pin sch-component-pin sch-port-indicator",cx:a.x.toString(),cy:a.y.toString(),r:r.toString(),fill:"none",stroke:o.schematic.component_outline,"stroke-width":s.toString(),"data-schematic-port-id":t.schematic_port_id},children:[]});const c=t.display_pin_label??A?.name;if(c){const l={...t.center},u=t.distance_from_component_edge??0,g=.05;let h="middle",d="";switch(t.facing_direction){case"left":l.x+=u/2,l.y+=g,h="start";break;case"right":l.x-=u/2,l.y+=g,h="end";break;case"up":l.y-=u/2,l.x-=g,h="middle";break;case"down":l.y+=u/2,l.x-=g,h="middle";break}const p=hn(e,l),m=pE(e,"pin_number");(t.facing_direction==="up"||t.facing_direction==="down")&&(d=`rotate(-90 ${p.x} ${p.y})`),i.push({name:"text",type:"element",value:"",attributes:{class:"port-indicator-label sch-port-label",x:p.x.toString(),y:p.y.toString(),fill:o.schematic.component_outline,"font-family":"sans-serif","font-size":`${m*.7}px`,"text-anchor":h,"dominant-baseline":"middle",...d&&{transform:d}},children:[{type:"text",value:c,name:"",attributes:{},children:[]}]})}return i},YUt=t=>({type:"element",name:"tspan",value:"",attributes:t.is_overlined?{"text-decoration":"overline"}:{},children:[{type:"text",name:"",value:t.text,attributes:{},children:[]}]}),pJo=t=>t.filter(e=>e.text).map(YUt),mJo=t=>{const e=[[]];for(const n of t)n.text.split(`
`).forEach((o,i)=>{i>0&&e.push([]),o&&e.at(-1).push(YUt({...n,text:o}))});return e},TRe=({elm:t,transform:e,colorMap:n})=>{const o=hn(e,t.position),i={center:"middle",center_right:"end",bottom_left:"start",bottom_center:"middle",bottom_right:"end",left:"start",right:"end",top:"middle",bottom:"middle",top_left:"start",top_center:"middle",top_right:"end",center_left:"start"},r={center:"middle",center_right:"middle",bottom_left:"ideographic",bottom_center:"ideographic",bottom_right:"ideographic",left:"middle",right:"middle",top:"hanging",bottom:"ideographic",top_left:"hanging",top_center:"hanging",top_right:"hanging",center_left:"middle"},s=t.text.split(`
`),a=mJo(t.text_parts??[]),A=s.length===1?t.text_parts?.length?a[0]:[{type:"text",value:t.text,name:t.schematic_text_id,attributes:{},children:[]}]:s.map((c,l)=>({type:"element",name:"tspan",value:"",attributes:{x:o.x.toString(),...l>0?{dy:"1em"}:{}},children:t.text_parts?.length?a[l]??[]:[{type:"text",value:c,name:l===0?t.schematic_text_id:"",attributes:{},children:[]}]}));return t.display_superscript&&(s.length===1?A:A[A.length-1].children).push(...DRe("",t.display_superscript,pE(e,"reference_designator",t.font_size),r[t.anchor]).slice(1)),{type:"element",name:"text",value:"",attributes:{class:"sch-text",x:o.x.toString(),y:o.y.toString(),fill:t.color??n.schematic.sheet_label,"text-anchor":i[t.anchor],"dominant-baseline":r[t.anchor],"font-family":"sans-serif","font-size":`${pE(e,"reference_designator",t.font_size)}px`,transform:`rotate(${t.rotation}, ${o.x}, ${o.y})`},children:A}};function UUt({schArc:t,transform:e,colorMap:n}){const o=hn(e,t.center),i=Math.abs(e.a)*t.radius,r=t.stroke_width??.02,s=Math.abs(e.a)*r,a=t.start_angle_degrees*Math.PI/180,A=t.end_angle_degrees*Math.PI/180,c=o.x+i*Math.cos(a),l=o.y+i*Math.sin(a),u=o.x+i*Math.cos(A),g=o.y+i*Math.sin(A);let h=t.end_angle_degrees-t.start_angle_degrees;t.direction==="clockwise"&&(h=-h),h<0&&(h+=360);const d=h>180?1:0,p=t.direction==="clockwise"?1:0;return[{name:"path",type:"element",attributes:{class:"sch-arc",d:`M ${c} ${l} A ${i} ${i} 0 ${d} ${p} ${u} ${g}`,fill:"none",stroke:t.color,"stroke-width":s.toString(),...t.is_dashed&&{"stroke-dasharray":(s*3).toString()},"data-schematic-arc-id":t.schematic_arc_id,...t.schematic_component_id&&{"data-schematic-component-id":t.schematic_component_id}},children:[],value:""}]}var _Jo=({schematicBox:t,transform:e,colorMap:n})=>{const o=hn(e,{x:t.x,y:t.y}),i=hn(e,{x:t.x+t.width,y:t.y+t.height}),r=Math.min(o.y,i.y),s=Math.max(o.y,i.y),a=Math.min(o.x,i.x),A=Math.max(o.x,i.x),c=i_(e),l={class:"schematic-box sch-box",x:a.toString(),y:r.toString(),width:(A-a).toString(),height:(s-r).toString(),"stroke-width":`${c}px`,stroke:n.schematic.component_outline||"black",fill:"transparent"};if(t.is_dashed){const u=8*c,g=4*c;l["stroke-dasharray"]=`${u} ${g}`}return[{name:"rect",type:"element",value:"",attributes:l,children:[]}]};function KUt({schCircle:t,transform:e,colorMap:n}){const o=hn(e,t.center),i=Math.abs(e.a)*t.radius,r=t.stroke_width??.02,s=Math.abs(e.a)*r;return[{name:"circle",type:"element",attributes:{class:"sch-circle",cx:o.x.toString(),cy:o.y.toString(),r:i.toString(),fill:t.is_filled?t.fill_color??t.color:"none",stroke:t.color,"stroke-width":s.toString(),...t.is_dashed&&{"stroke-dasharray":(s*3).toString()},"data-schematic-circle-id":t.schematic_circle_id,...t.schematic_component_id&&{"data-schematic-component-id":t.schematic_component_id}},children:[],value:""}]}var VUt=(t,e)=>{for(const n of t){if(n.type!=="source_trace")continue;const o=n;if(Array.isArray(o.connected_source_port_ids)&&o.connected_source_port_ids.includes(e))return!0}return!1},fJo={top_left:"start",top_right:"end",middle_left:"start",middle_right:"end",bottom_left:"start",bottom_right:"end",center:"middle",middle_top:"middle",middle_bottom:"middle"},IJo={top_left:"hanging",top_right:"hanging",bottom_left:"ideographic",bottom_right:"ideographic",center:"middle",middle_left:"middle",middle_right:"middle",middle_top:"hanging",middle_bottom:"ideographic"},CJo=({component:t,transform:e,circuitJson:n,colorMap:o})=>{const i=[],r=Su[t.symbol_name];if(!r)return[RRe({text:`Symbol not found: ${t.symbol_name}`,realCenter:t.center,realToScreenTransform:e})];const s=Mr(n).schematic_port.list({schematic_component_id:t.schematic_component_id}),a=Mr(n).source_component.get(t.source_component_id),A=NUt({schPorts:s,symbol:r,schComponent:t});if(!A[0])return[RRe({text:`Could not match ports for symbol ${t.symbol_name}`,realCenter:t.center,realToScreenTransform:e})];const c=RUt(A[1]?.symbolPort??r.center,A[1]?.schPort.center??t.center,A[0].symbolPort,A[0].schPort.center),l=r.primitives.filter(B=>B.type==="path"),u=r.primitives.filter(B=>B.type==="text"),g=r.primitives.filter(B=>B.type==="circle"),h=r.primitives.filter(B=>B.type==="box"),d=new Set;for(const B of A)(VUt(n,B.schPort.source_port_id)||Mr(n).source_port.get(B.schPort.source_port_id)?.do_not_connect)&&d.add(B.symbolPort);const p={minX:Math.min(...l.flatMap(B=>B.points.map(S=>S.x))),maxX:Math.max(...l.flatMap(B=>B.points.map(S=>S.x))),minY:Math.min(...l.flatMap(B=>B.points.map(S=>S.y))),maxY:Math.max(...l.flatMap(B=>B.points.map(S=>S.y)))},[m,_]=hn(m0(e,c),[p.minX,p.minY]),[f,I]=hn(m0(e,c),[p.maxX,p.maxY]),C=Math.abs(I-_),y=Math.min(_,I),x=Math.abs(f-m),E=Math.min(m,f);i.push({name:"rect",type:"element",value:"",attributes:{class:"component-overlay sch-component-overlay",x:E.toString(),y:y.toString(),width:x.toString(),height:C.toString(),fill:"transparent"},children:[]});for(const B of l){const{points:S,color:Q,closed:w,fill:M}=B;i.push({type:"element",name:"path",attributes:{class:"sch-component-symbol-path",d:S.map((k,R)=>{const[F,O]=hn(m0(e,c),[k.x,k.y]);return`${R===0?"M":"L"} ${F} ${O}`}).join(" ")+(w?" Z":""),stroke:o.schematic.component_outline,fill:"none","stroke-width":`${i_(e)}px`,"stroke-linecap":"round"},value:"",children:[]})}for(const B of u){const S=hn(m0(e,c),B);let Q="";const w=B.text==="{REF}";w?Q=a?.display_name??a?.name??"":B.text==="{VAL}"&&(Q=t.symbol_display_value??"");const M=IJo[B.anchor];i.push({name:"text",type:"element",attributes:{class:w?"sch-component-name sch-component-text":"sch-component-text",x:S.x.toString(),y:S.y.toString(),...w?{stroke:o.schematic.background,"stroke-width":`${i_(e)}px`,"paint-order":"stroke"}:{},fill:o.schematic.label_local,"font-family":"sans-serif","text-anchor":fJo[B.anchor],"dominant-baseline":M,"font-size":`${pE(e,"reference_designator")}px`},value:"",children:[{type:"text",value:Q,name:"",attributes:{},children:[]}]})}for(const B of h){const S=hn(m0(e,c),B),Q=m0(e,c).a;i.push({name:"rect",type:"element",attributes:{class:"sch-component-symbol-box",x:S.x.toString(),y:S.y.toString(),width:(B.width*Q).toString(),height:(B.height*Q).toString(),fill:"red"},value:"",children:[]})}for(const B of r.ports){if(d.has(B))continue;const S=hn(m0(e,c),B);i.push({type:"element",name:"circle",attributes:{class:"component-pin sch-component-pin",cx:S.x.toString(),cy:S.y.toString(),r:`${Math.abs(e.a)*.02}px`,"stroke-width":`${i_(e)}px`,fill:"none",stroke:o.schematic.component_outline},value:"",children:[]})}for(const B of g){const S=hn(m0(e,c),B),Q=Math.abs(B.radius*e.a);i.push({type:"element",name:"circle",attributes:{class:"sch-component-symbol-circle",cx:S.x.toString(),cy:S.y.toString(),r:`${Q}px`,"stroke-width":`${i_(e)}px`,fill:"none",stroke:o.schematic.component_outline},value:"",children:[]})}return i},wq=.02,zUt=(t,e,n,o,i)=>{const r=Math.PI/6,s={x:t.x-n*Math.cos(e-r),y:t.y-n*Math.sin(e-r)},a={x:t.x-n*Math.cos(e+r),y:t.y-n*Math.sin(e+r)};return{name:"polygon",type:"element",attributes:{points:`${t.x},${t.y} ${s.x},${s.y} ${a.x},${a.y}`,fill:"white",stroke:o,"stroke-width":`${i}px`},value:"",children:[]}},yJo=({schPort:t,schComponent:e,transform:n,circuitJson:o})=>{const i=[],r=Mr(o).source_port.get(t.source_port_id),s={x:t.center.x,y:t.center.y},a=t.distance_from_component_edge??.4;switch(t.side_of_component){case"left":s.x+=a;break;case"right":s.x-=a;break;case"top":s.y-=a;break;case"bottom":s.y+=a;break}const A=hn(n,t.center),c=hn(n,s),l=r!=null&&r.source_component_id==null&&typeof t.is_connected=="boolean"?t.is_connected:VUt(o,t.source_port_id),u=t.is_drawn_with_inversion_circle??!1,g=.06,h={...t.center};if(!l&&!r?.do_not_connect)switch(t.side_of_component){case"left":h.x+=wq;break;case"right":h.x-=wq;break;case"top":h.y-=wq;break;case"bottom":h.y+=wq;break}const d=hn(n,h);if(u){const I=Math.abs(n.a)*g,C={...c};switch(t.side_of_component){case"left":C.x-=I,c.x-=I*2;break;case"right":C.x+=I,c.x+=I*2;break;case"top":C.y-=I,c.y-=I*2;break;case"bottom":C.y+=I,c.y+=I*2;break}i.push({name:"circle",type:"element",attributes:{class:"component-pin sch-component-pin sch-inversion-bubble",cx:C.x.toString(),cy:C.y.toString(),r:I.toString(),fill:"white",stroke:Lg.schematic.component_outline,"stroke-width":`${i_(n)}px`},value:"",children:[]})}i.push({name:"line",type:"element",attributes:{class:"component-pin sch-component-pin sch-port-line",x1:c.x.toString(),y1:c.y.toString(),x2:d.x.toString(),y2:d.y.toString(),"stroke-width":`${i_(n)}px`},value:"",children:[]});const p=Math.abs(n.a)*wq,m=[];!l&&!r?.do_not_connect&&m.push({name:"circle",type:"element",attributes:{class:"component-pin sch-component-pin sch-port-terminal",cx:A.x.toString(),cy:A.y.toString(),r:p.toString(),"stroke-width":`${i_(n)}px`},value:"",children:[]}),m.push({name:"rect",type:"element",attributes:{x:(A.x-p).toString(),y:(A.y-p).toString(),width:(p*2).toString(),height:(p*2).toString(),opacity:"0"},value:"",children:[]}),i.push({name:"g",type:"element",value:"",attributes:{class:"sch-port","data-schematic-port-id":t.source_port_id},children:m});const{has_input_arrow:_,has_output_arrow:f}=t;if((_||f)&&t.side_of_component){const I=Math.abs(n.a)*.1,C=Lg.schematic.component_outline,y=I*Math.cos(Math.PI/6),x=i_(n)/3;let E=0,B=0;t.side_of_component==="left"?(E=0,B=Math.PI):t.side_of_component==="right"?(E=Math.PI,B=0):t.side_of_component==="top"?(E=Math.PI/2,B=-Math.PI/2):t.side_of_component==="bottom"&&(E=-Math.PI/2,B=Math.PI/2);const S=_&&f;let Q={...c},w={...c};if(S){const M=y;t.side_of_component==="left"?w.x-=M:t.side_of_component==="right"?w.x+=M:t.side_of_component==="top"?w.y-=M:t.side_of_component==="bottom"&&(w.y+=M)}if(_&&i.push(zUt(Q,E,I,C,x)),f){const M={x:w.x+I*Math.cos(B),y:w.y+I*Math.sin(B)};i.push(zUt(M,B,I,C,x))}}return i},xJo=t=>{const e=[],{schPort:n,transform:o}=t,i={x:n.center.x,y:n.center.y};if(!n.side_of_component)return[];const r=CG(n.side_of_component),s=n.distance_from_component_edge??.4;i.x+=r.x*s/2,i.y+=r.y*s/2,n.side_of_component==="top"||n.side_of_component==="bottom"?i.x-=.02:i.y+=.02;const a=hn(o,i);return e.push({name:"text",type:"element",attributes:{class:"pin-number sch-pin-number",x:a.x.toString(),y:a.y.toString(),style:"font-family: sans-serif;",fill:Lg.schematic.pin_number,"text-anchor":"middle","dominant-baseline":"auto","font-size":`${pE(o,"pin_number")}px`,transform:n.side_of_component==="top"||n.side_of_component==="bottom"?`rotate(-90 ${a.x} ${a.y})`:""},children:[{type:"text",value:n.pin_number?.toString()||"",name:"",attributes:{},children:[]}],value:""}),e},JUt=.1,WUt=t=>{const e=[],{schPort:n,schComponent:o,transform:i,labelColor:r=Lg.schematic.pin_number,labelClassName:s="pin-number sch-pin-label"}=t,a={x:n.center.x,y:n.center.y};if(!n.side_of_component)return[];const A=CG(n.side_of_component),c=n.distance_from_component_edge??.4;a.x+=A.x*(c+JUt),a.y+=A.y*(c+JUt);const l=hn(i,a),u=n.display_pin_label??o.port_labels?.[`${n.pin_number}`];if(!u)return[];const g=u.startsWith("N_"),h=g?u.slice(2):u,d=n.display_pin_label_text_parts,p=n.is_drawn_with_inversion_circle??!1,m=pE(i,g||p?"negated_pin_number":"pin_number",n.display_pin_label_font_size);return e.push({name:"text",type:"element",attributes:{class:s,x:l.x.toString(),y:l.y.toString(),style:`font-family: sans-serif;${g&&!d?.length?" text-decoration: overline;":""}`,fill:r,"text-anchor":n.side_of_component==="left"||n.side_of_component==="bottom"?"start":"end","dominant-baseline":"middle","font-size":`${m}px`,transform:n.side_of_component==="top"||n.side_of_component==="bottom"?`rotate(-90 ${l.x} ${l.y})`:""},children:d?.length?pJo(d):[{type:"text",value:h||"",name:"",attributes:{},children:[]}],value:""}),e},EJo=t=>{const e=[];return e.push(...yJo(t)),e.push(...xJo(t)),e.push(...WUt(t)),e},BJo=({component:t,transform:e,circuitJson:n,colorMap:o})=>{const i=[],r=hn(e,{x:t.center.x-t.size.width/2,y:t.center.y+t.size.height/2}),s=hn(e,{x:t.center.x+t.size.width/2,y:t.center.y-t.size.height/2}),a=s.x-r.x,A=s.y-r.y;i.push({name:"rect",type:"element",value:"",attributes:{class:"component chip sch-component-body",x:r.x.toString(),y:r.y.toString(),width:a.toString(),height:A.toString(),"stroke-width":`${i_(e)}px`,fill:o.schematic.component_body,stroke:o.schematic.component_outline},children:[]}),i.push({name:"rect",type:"element",value:"",attributes:{class:"component-overlay sch-component-overlay",x:r.x.toString(),y:r.y.toString(),width:a.toString(),height:A.toString(),fill:"transparent"},children:[]});const c=Mr(n).schematic_text.list();for(const u of c)u.schematic_component_id===t.schematic_component_id&&i.push(TRe({elm:u,transform:e,colorMap:o}));const l=Mr(n).schematic_port.list({schematic_component_id:t.schematic_component_id});for(const u of l)i.push(...EJo({schPort:u,schComponent:t,transform:e,circuitJson:n}));return i};function jUt({isDashed:t,dashLength:e,dashGap:n,strokeWidth:o,transform:i}){if(!t)return;const r=Math.abs(i.a),s=o*r*3,a=e!==void 0?e*r:s,A=n!==void 0?n*r:s;return`${a} ${A}`}function $Ut({schLine:t,transform:e,colorMap:n}){const o=hn(e,{x:t.x1,y:t.y1}),i=hn(e,{x:t.x2,y:t.y2}),r=t.stroke_width??.02,s=Math.abs(e.a)*r,a=jUt({isDashed:t.is_dashed,dashLength:t.dash_length,dashGap:t.dash_gap,strokeWidth:r,transform:e});return[{name:"line",type:"element",attributes:{class:"sch-line",x1:o.x.toString(),y1:o.y.toString(),x2:i.x.toString(),y2:i.y.toString(),stroke:t.color,"stroke-width":s.toString(),...a&&{"stroke-dasharray":a},"data-schematic-line-id":t.schematic_line_id,...t.schematic_component_id&&{"data-schematic-component-id":t.schematic_component_id}},children:[],value:""}]}function qUt({schRect:t,transform:e,colorMap:n}){const o=hn(e,t.center),i=Math.abs(e.a)*t.width,r=Math.abs(e.d)*t.height,s=t.stroke_width??.02,a=Math.abs(e.a)*s,A=o.x-i/2,c=o.y-r/2;return[{name:"rect",type:"element",attributes:{class:"sch-rect",x:A.toString(),y:c.toString(),width:i.toString(),height:r.toString(),fill:t.is_filled?t.fill_color??t.color:"none",stroke:t.color,"stroke-width":a.toString(),...t.is_dashed&&{"stroke-dasharray":(a*3).toString()},...t.rotation!==0&&{transform:`rotate(${t.rotation} ${o.x} ${o.y})`},"data-schematic-rect-id":t.schematic_rect_id,...t.schematic_component_id&&{"data-schematic-component-id":t.schematic_component_id}},children:[],value:""}]}function XUt({schPath:t,transform:e,colorMap:n}){const o=t.stroke_color??n.schematic.component_outline,i=t.fill_color??"none",r=t.stroke_width??.02,s=Math.abs(e.a)*r,a=jUt({isDashed:t.is_dashed,dashLength:t.dash_length,dashGap:t.dash_gap,strokeWidth:r,transform:e});return!t.points||t.points.length<2?[]:[{name:"path",type:"element",attributes:{class:"sch-path",d:t.points.map(l=>hn(e,{x:l.x,y:l.y})).map((l,u)=>`${u===0?"M":"L"} ${l.x} ${l.y}`).join(" "),stroke:o,"stroke-width":s.toString(),fill:t.is_filled?i:"none","stroke-linecap":"round","stroke-linejoin":"round",...a&&{"stroke-dasharray":a},...t.schematic_component_id&&{"data-schematic-component-id":t.schematic_component_id}},children:[],value:""}]}var bJo=({component:t,transform:e,circuitJson:n,colorMap:o})=>{const i=[],r=t.schematic_component_id;for(const s of n)!("schematic_component_id"in s)||s.schematic_component_id!==r||(s.type==="schematic_text"&&t.is_box_with_pins===!1?i.push(TRe({elm:s,transform:e,colorMap:o})):s.type==="schematic_line"?i.push(...$Ut({schLine:s,transform:e,colorMap:o})):s.type==="schematic_circle"?i.push(...KUt({schCircle:s,transform:e,colorMap:o})):s.type==="schematic_rect"?i.push(...qUt({schRect:s,transform:e,colorMap:o})):s.type==="schematic_arc"?i.push(...UUt({schArc:s,transform:e,colorMap:o})):s.type==="schematic_path"&&i.push(...XUt({schPath:s,transform:e,colorMap:o})));if(t.is_box_with_pins===!1){const s=n.filter(A=>A.type==="schematic_line"&&A.schematic_component_id===r),a=n.filter(A=>A.type==="schematic_port"&&A.schematic_component_id===r);for(const A of a){const c=s.find(p=>p.x1===A.center.x&&p.y1===A.center.y||p.x2===A.center.x&&p.y2===A.center.y);if(!c)continue;const l=c.x1===A.center.x&&c.y1===A.center.y?{x:c.x2,y:c.y2}:{x:c.x1,y:c.y1},u=l.x-A.center.x,g=l.y-A.center.y,h=Math.abs(u)>Math.abs(g)?u>0?"left":"right":g>0?"bottom":"top",d=Math.max(Math.abs(u),Math.abs(g));i.push(...WUt({schPort:{...A,side_of_component:h,distance_from_component_edge:d},schComponent:t,transform:e,labelClassName:"port-label sch-pin-label",labelColor:o.schematic.pin_name}))}}return i};function SJo(t){const{component:e}=t;let n=[];e.is_box_with_pins!==!1&&(e.symbol_name?n=CJo(t):n=BJo(t));const o=bJo(t),i=[...n,...o];return[{type:"element",name:"g",attributes:{class:"sch-component","data-circuit-json-type":"schematic_component","data-schematic-component-id":e.schematic_component_id,...e.schematic_sheet_id?{"data-schematic-sheet-id":e.schematic_sheet_id}:{}},children:i,value:""}]}function QJo({debugObject:t,transform:e}){if(t.shape==="rect"){let[n,o]=hn(e,[t.center.x-t.size.width/2,t.center.y-t.size.height/2]),[i,r]=hn(e,[t.center.x+t.size.width/2,t.center.y+t.size.height/2]);[o,r]=[Math.min(o,r),Math.max(o,r)];const s=Math.abs(i-n),a=Math.abs(r-o),[A,c]=hn(e,[t.center.x,t.center.y]);return[{name:"rect",type:"element",value:"",attributes:{x:n.toString(),y:o.toString(),width:s.toString(),height:a.toString(),fill:"none",stroke:"red","stroke-width":(.02*Math.abs(e.a)).toString(),"stroke-dasharray":"5,5"},children:t.label?[{name:"text",type:"element",value:"",attributes:{x:A.toString(),y:(c-10).toString(),"text-anchor":"middle","font-size":(.2*Math.abs(e.a)).toString(),fill:"red"},children:[{type:"text",value:t.label,name:"",attributes:{},children:[]}]}]:[]}]}if(t.shape==="line"){const[n,o]=hn(e,[t.start.x,t.start.y]),[i,r]=hn(e,[t.end.x,t.end.y]),s=(n+i)/2,a=(o+r)/2;return[{name:"line",type:"element",value:"",attributes:{x1:n.toString(),y1:o.toString(),x2:i.toString(),y2:r.toString(),stroke:"red","stroke-width":(.02*Math.abs(e.a)).toString(),"stroke-dasharray":"5,5"},children:t.label?[{name:"text",type:"element",value:"",attributes:{x:s.toString(),y:(a-10).toString(),"text-anchor":"middle","font-size":(.2*Math.abs(e.a)).toString(),fill:"red"},children:[{type:"text",value:t.label,name:"",attributes:{},children:[]}]}]:[]}]}return[]}var ZUt=.2/MR,vJo=3/MR,ide=["1","2","3","4","5","6"],Pq=["A","B","C","D"];function wJo({schematicSheet:t,transform:e,colorMap:n}){const o=Sq(t),i=n.schematic.sheet,r=n.schematic.net_name,s=[eKt({id:`${t.schematic_sheet_id}_outer`,center:o.center,width:o.width,height:o.height,transform:e,color:i}),eKt({id:`${t.schematic_sheet_id}_inner`,center:o.center,width:o.innerMaxX-o.innerMinX,height:o.innerMaxY-o.innerMinY,transform:e,color:i})];for(let a=1;a<ide.length;a++){const A=o.innerMinX+(o.innerMaxX-o.innerMinX)*a/ide.length;s.push(rde({id:`${t.schematic_sheet_id}_top_column_${a}`,x1:A,y1:o.maxY,x2:A,y2:o.innerMaxY,transform:e,color:i}),rde({id:`${t.schematic_sheet_id}_bottom_column_${a}`,x1:A,y1:o.minY,x2:A,y2:o.innerMinY,transform:e,color:i}))}for(let a=1;a<Pq.length;a++){const A=o.innerMinY+(o.innerMaxY-o.innerMinY)*a/Pq.length;s.push(rde({id:`${t.schematic_sheet_id}_left_row_${a}`,x1:o.minX,y1:A,x2:o.innerMinX,y2:A,transform:e,color:i}),rde({id:`${t.schematic_sheet_id}_right_row_${a}`,x1:o.maxX,y1:A,x2:o.innerMaxX,y2:A,transform:e,color:i}))}return ide.forEach((a,A)=>{const c=o.innerMinX+(o.innerMaxX-o.innerMinX)*(A+.5)/ide.length;s.push(sde({text:a,x:c,y:(o.maxY+o.innerMaxY)/2,transform:e,color:r}),sde({text:a,x:c,y:(o.minY+o.innerMinY)/2,transform:e,color:r}))}),Pq.forEach((a,A)=>{const c=o.innerMinY+(o.innerMaxY-o.innerMinY)*(Pq.length-A-.5)/Pq.length;s.push(sde({text:a,x:(o.minX+o.innerMinX)/2,y:c,transform:e,color:r}),sde({text:a,x:(o.maxX+o.innerMaxX)/2,y:c,transform:e,color:r}))}),[{name:"g",type:"element",value:"",attributes:{class:"schematic-sheet","data-circuit-json-type":"schematic_sheet","data-schematic-sheet-id":t.schematic_sheet_id},children:s}]}function eKt({id:t,center:e,width:n,height:o,transform:i,color:r}){const s=hn(i,e),a=Math.abs(i.a)*n,A=Math.abs(i.d)*o;return{name:"rect",type:"element",value:"",attributes:{class:"sch-rect",x:(s.x-a/2).toString(),y:(s.y-A/2).toString(),width:a.toString(),height:A.toString(),fill:"none",stroke:r,"stroke-width":(Math.abs(i.a)*ZUt).toString(),"data-schematic-rect-id":t},children:[]}}function rde({id:t,x1:e,y1:n,x2:o,y2:i,transform:r,color:s}){const a=hn(r,{x:e,y:n}),A=hn(r,{x:o,y:i});return{name:"line",type:"element",value:"",attributes:{class:"sch-line",x1:a.x.toString(),y1:a.y.toString(),x2:A.x.toString(),y2:A.y.toString(),stroke:s,"stroke-width":(Math.abs(r.a)*ZUt).toString(),"data-schematic-line-id":t},children:[]}}function sde({text:t,x:e,y:n,transform:o,color:i}){const r=hn(o,{x:e,y:n});return{type:"element",name:"text",value:"",attributes:{class:"sch-text",x:r.x.toString(),y:r.y.toString(),fill:i,"text-anchor":"middle","dominant-baseline":"middle","font-family":"sans-serif","font-size":`${pE(o,"reference_designator",vJo)}px`,transform:`rotate(0, ${r.x}, ${r.y})`},children:[{type:"text",value:t,name:"",attributes:{},children:[]}]}}var PJo=({schematicTable:t,transform:e,colorMap:n,circuitJson:o})=>{const{anchor_position:i,border_width:r=.05,anchor:s="center"}=t,{column_widths:a,row_heights:A}=kUt(t,o),c=a.reduce((E,B)=>E+B,0),l=A.reduce((E,B)=>E+B,0);let u=i.x,g=i.y;s.includes("center")?u-=c/2:s.includes("right")&&(u-=c),s.includes("center")?g+=l/2:s.includes("bottom")&&(g+=l);const h=[],d=r*Math.abs(e.a),p=i_(e),[m,_]=hn(e,[u,g]),[f,I]=hn(e,[u+c,g-l]);h.push({name:"rect",type:"element",attributes:{class:"sch-table-border",x:m.toString(),y:_.toString(),width:(f-m).toString(),height:(I-_).toString(),fill:"none",stroke:n.schematic.table,"stroke-width":d.toString()},children:[],value:""});const C=o.filter(E=>E.type==="schematic_table_cell"&&E.schematic_table_id===t.schematic_table_id);let y=u;for(let E=0;E<a.length-1;E++){y+=a[E];let B=g;for(let S=0;S<A.length;S++){const Q=B-A[S];if(!C.some(M=>M.start_column_index<=E&&M.end_column_index>E&&M.start_row_index<=S&&M.end_row_index>=S)){const M=hn(e,{x:y,y:B}),k=hn(e,{x:y,y:Q});h.push({name:"line",type:"element",attributes:{class:"sch-table-grid-line",x1:M.x.toString(),y1:M.y.toString(),x2:k.x.toString(),y2:k.y.toString(),stroke:n.schematic.table,"stroke-width":p.toString()},children:[],value:""})}B=Q}}let x=g;for(let E=0;E<A.length-1;E++){x-=A[E];let B=u;for(let S=0;S<a.length;S++){const Q=B+a[S];if(!C.some(M=>M.start_row_index<=E&&M.end_row_index>E&&M.start_column_index<=S&&M.end_column_index>=S)){const M=hn(e,{x:B,y:x}),k=hn(e,{x:Q,y:x});h.push({name:"line",type:"element",attributes:{class:"sch-table-grid-line",x1:M.x.toString(),y1:M.y.toString(),x2:k.x.toString(),y2:k.y.toString(),stroke:n.schematic.table,"stroke-width":p.toString()},children:[],value:""})}B=Q}}for(const E of C)if(E.text){const B=a.slice(E.start_column_index,E.end_column_index+1).reduce((te,j)=>te+j,0),S=A.slice(E.start_row_index,E.end_row_index+1).reduce((te,j)=>te+j,0),Q=u+a.slice(0,E.start_column_index).reduce((te,j)=>te+j,0),w=g-A.slice(0,E.start_row_index).reduce((te,j)=>te+j,0),{cell_padding:M=.2}=t,k=E.horizontal_align??"center",R=E.vertical_align??"middle";let F={x:Q+B/2,y:w-S/2};k==="left"?F.x=Q+M:k==="right"&&(F.x=Q+B-M),R==="top"?F.y=w-M:R==="bottom"&&(F.y=w-S+M);const O=hn(e,F),U=pE(e,"reference_designator",E.font_size),Y={left:"start",center:"middle",right:"end"},W={top:"hanging",middle:"middle",bottom:"ideographic"};h.push({name:"text",type:"element",attributes:{class:"sch-table-text",x:O.x.toString(),y:O.y.toString(),"font-size":`${U}px`,"text-anchor":Y[k],"dominant-baseline":W[R],fill:n.schematic.table,"font-family":"sans-serif"},children:[{type:"text",value:E.text,name:"",attributes:{},children:[]}],value:""})}return[{name:"g",type:"element",attributes:{class:"sch-table","data-schematic-table-id":t.schematic_table_id},children:h,value:""}]};function MJo({trace:t,transform:e,colorMap:n}){const o=t.edges;if(o.length===0)return[];const i=[],r=[];let s="";for(let a=0;a<o.length;a++){const A=o[a];if(A.is_crossing)continue;const[c,l]=hn(e,[A.from.x,A.from.y]),[u,g]=hn(e,[A.to.x,A.to.y]);a===0||o[a-1]?.is_crossing?s+=`M ${c} ${l} L ${u} ${g}`:s+=` L ${u} ${g}`}s&&(i.push({name:"path",type:"element",attributes:{d:s,class:"trace-invisible-hover-outline sch-trace-hitbox",stroke:n.schematic.wire,fill:"none","stroke-width":`${i_(e)*8}px`,"stroke-linecap":"round",opacity:"0","stroke-linejoin":"round"},value:"",children:[]}),i.push({name:"path",type:"element",attributes:{class:"sch-trace-path",d:s,stroke:n.schematic.wire,fill:"none","stroke-width":`${i_(e)}px`,"stroke-linecap":"round","stroke-linejoin":"round"},value:"",children:[]}));for(const a of o){if(!a.is_crossing)continue;const[A,c]=hn(e,[a.from.x,a.from.y]),[l,u]=hn(e,[a.to.x,a.to.y]),g=(A+l)/2,h=(c+u)/2,d=l-A,p=u-c,m=Math.sqrt(d*d+p*p),_=m*.7,f=-p/m*_,I=d/m*_,C=g+f,y=h-Math.abs(I);r.push({name:"path",type:"element",attributes:{class:"trace-crossing-outline sch-trace-crossing-outline",d:`M ${A} ${c} Q ${C} ${y} ${l} ${u}`,stroke:n.schematic.background,fill:"none","stroke-width":`${i_(e)*1.5}px`,"stroke-linecap":"butt"},value:"",children:[]}),r.push({name:"path",type:"element",attributes:{class:"sch-trace-crossing-path",d:`M ${A} ${c} Q ${C} ${y} ${l} ${u}`,stroke:n.schematic.wire,fill:"none","stroke-width":`${i_(e)}px`,"stroke-linecap":"round"},value:"",children:[]})}if(t.junctions)for(const a of t.junctions){const[A,c]=hn(e,[a.x,a.y]);r.push({name:"circle",type:"element",attributes:{cx:A.toString(),cy:c.toString(),r:(Math.abs(e.a)*.03).toString(),class:"trace-junction sch-trace-junction",fill:n.schematic.junction},value:"",children:[]})}return[{name:"g",type:"element",value:"",attributes:{class:"trace sch-trace","data-layer":"base","data-circuit-json-type":"schematic_trace","data-schematic-trace-id":t.schematic_trace_id,...t.subcircuit_connectivity_map_key&&{"data-subcircuit-connectivity-map-key":t.subcircuit_connectivity_map_key}},children:i},{name:"g",type:"element",value:"",attributes:{class:"trace-overlays sch-trace-overlays","data-layer":"overlay","data-circuit-json-type":"schematic_trace","data-schematic-trace-id":t.schematic_trace_id,...t.subcircuit_connectivity_map_key&&{"data-subcircuit-connectivity-map-key":t.subcircuit_connectivity_map_key}},children:r}]}function DJo({probe:t,transform:e,colorMap:n,fallbackColor:o}){const[i,r]=hn(e,[t.position.x,t.position.y]),s=t.color??o??n.schematic.reference,a=Math.abs(e.a)*.6,A=Math.abs(e.a)*.28,c=t.label_alignment??"top_right";let l,u,g,h;switch(c){case"top_left":l=-135*Math.PI/180,u="end",g=-8,h=-8;break;case"top_center":l=-90*Math.PI/180,u="middle",g=0,h=-8;break;case"top_right":l=-45*Math.PI/180,u="start",g=8,h=-8;break;case"center_left":l=180*Math.PI/180,u="end",g=-8,h=0;break;case"center":l=-90*Math.PI/180,u="middle",g=0,h=-8;break;case"center_right":l=0*Math.PI/180,u="start",g=8,h=0;break;case"bottom_left":l=135*Math.PI/180,u="end",g=-8,h=8;break;case"bottom_center":l=90*Math.PI/180,u="middle",g=0,h=8;break;case"bottom_right":l=45*Math.PI/180,u="start",g=8,h=8;break;default:l=-50*Math.PI/180,u="start",g=8,h=0}const d=i+a*Math.cos(l),p=r+a*Math.sin(l),m=i,_=r,f=[`M ${d},${p}`,`L ${m},${_}`,`M ${m},${_}`,`L ${m-A*Math.cos((l*180/Math.PI+150)*Math.PI/180)},${_-A*Math.sin((l*180/Math.PI+150)*Math.PI/180)}`,`L ${m-A*Math.cos((l*180/Math.PI+210)*Math.PI/180)},${_-A*Math.sin((l*180/Math.PI+210)*Math.PI/180)}`,"Z"].join(" "),I=(d+g).toString(),C=(p+h).toString(),y=[];if(t.name&&t.voltage!==void 0)y.push({type:"element",name:"tspan",value:"",attributes:{x:I},children:[{type:"text",value:t.name,name:"",attributes:{},children:[]}]}),y.push({type:"element",name:"tspan",value:"",attributes:{x:I,dy:"1.2em"},children:[{type:"text",value:`${t.voltage}V`,name:"",attributes:{},children:[]}]});else{const x=[];t.name&&x.push(t.name),t.voltage!==void 0&&x.push(`${t.voltage}V`),y.push({type:"text",value:x.join(" "),name:"",attributes:{},children:[]})}return[{name:"path",type:"element",attributes:{class:"sch-voltage-probe",d:f,stroke:s,fill:s,"stroke-width":`${i_(e)}px`},value:"",children:[]},{type:"element",name:"text",value:"",attributes:{class:"sch-voltage-probe-label",x:I,y:C,fill:s,"text-anchor":u,"dominant-baseline":"middle","font-family":"sans-serif","font-size":`${pE(e,"reference_designator")}px`,"font-weight":"bold","data-schematic-voltage-probe-id":t.schematic_voltage_probe_id},children:y}]}var Mq=6,ade=12,lI=12,EG=6,tKt=14,Ade=11,nKt=280,NJo=140,oKt=t=>t.type==="schematic_component_overlap_warning"||t.type==="schematic_component_styling_warning"||t.type==="schematic_element_outside_sheet_warning"||t.type==="schematic_manual_edit_conflict_warning";function RJo({circuitJson:t,transform:e,svgWidth:n,svgHeight:o,colorMap:i}){const r=i.schematic.erc_warning,s=[];return t.filter(oKt).flatMap(a=>{const A=TJo(a,t,e);if(!A)return[];const c=Math.max(1,n-lI*2),l=YJo(a.message,Math.max(12,Math.floor((Math.min(nKt,c)-EG*2)/(Ade*.56)))),u=Math.max(...l.map(I=>I.length)),g=Math.min(nKt,c,Math.max(Math.min(NJo,c),u*Ade*.56+EG*2)),h=EG*2+l.length*tKt,d=HJo({targetBounds:A,calloutWidth:g,calloutHeight:h,svgWidth:n,svgHeight:o,occupiedCalloutBounds:s});s.push(d);const p=GJo(a),m=cde(A,Mq),_=OJo(d,m);return[{name:"g",type:"element",value:"",attributes:{class:"schematic-warning","data-type":a.type,"data-warning-id":p,role:"note","aria-label":a.message},children:[{name:"rect",type:"element",value:"",attributes:{x:m.minX.toString(),y:m.minY.toString(),width:(m.maxX-m.minX).toString(),height:(m.maxY-m.minY).toString(),rx:"6",fill:"none",stroke:r,"stroke-width":"1","stroke-dasharray":"4,3","data-warning-reference":"target"},children:[]},{name:"line",type:"element",value:"",attributes:{x1:_.from.x.toString(),y1:_.from.y.toString(),x2:_.to.x.toString(),y2:_.to.y.toString(),stroke:r,"stroke-width":"1","data-warning-reference":"leader"},children:[]},{name:"rect",type:"element",value:"",attributes:{x:d.minX.toString(),y:d.minY.toString(),width:g.toString(),height:h.toString(),fill:"rgba(255, 250, 235, 0.97)",stroke:r,"stroke-width":"1","data-warning-reference":"callout"},children:[]},{name:"text",type:"element",value:"",attributes:{x:(d.minX+EG).toString(),y:(d.minY+EG+Ade).toString(),fill:"#5c4300","font-family":"sans-serif","font-size":Ade.toString()},children:l.map((I,C)=>({name:"tspan",type:"element",value:"",attributes:{x:(d.minX+EG).toString(),dy:C===0?"0":tKt.toString()},children:[VJo(I)]}))}]}]})}function TJo(t,e,n){const i=kJo(t).map(r=>FJo(e,r)).filter(r=>!!r).map(r=>LJo(r,n)).filter(r=>!!r);return i.length===0?null:i.reduce(UJo)}function kJo(t){switch(t.type){case"schematic_component_overlap_warning":return t.schematic_component_ids;case"schematic_component_styling_warning":return[t.schematic_component_id,...t.schematic_port_ids??[]];case"schematic_manual_edit_conflict_warning":return[t.schematic_component_id];case"schematic_element_outside_sheet_warning":return[t.schematic_element_id]}}function FJo(t,e){return t.find(n=>{if(!n.type.startsWith("schematic_"))return!1;const o=`${n.type}_id`;return n[o]===e})}function LJo(t,e){if(t.type==="schematic_component"){const n=hn(e,{x:t.center.x-t.size.width/2,y:t.center.y+t.size.height/2}),o=hn(e,{x:t.center.x+t.size.width/2,y:t.center.y-t.size.height/2});return kRe([n,o])}if(t.type==="schematic_port"){const n=hn(e,t.center);return cde(kRe([n]),4)}if(t.type==="schematic_net_label"){const n=hn(e,t.anchor_position??t.center),o=Math.max(28,t.text.length*8);return{minX:n.x-o/2,minY:n.y-10,maxX:n.x+o/2,maxY:n.y+10}}if(t.type==="schematic_trace"){const n=t.edges.flatMap(o=>[hn(e,o.from),hn(e,o.to)]);return n.length===0?null:cde(kRe(n),4)}return null}function HJo({targetBounds:t,calloutWidth:e,calloutHeight:n,svgWidth:o,svgHeight:i,occupiedCalloutBounds:r}){const s=(t.minX+t.maxX)/2,a=(t.minY+t.maxY)/2,A=t.minY-Mq-ade-n,c=t.maxY+Mq+ade,l=t.minX-Mq-ade-e,u=t.maxX+Mq+ade,g=[];A>=lI&&g.push(Dq({x:BG(s-e/2,lI,o-lI-e),y:A,width:e,height:n,side:"top"})),c+n<=i-lI&&g.push(Dq({x:BG(s-e/2,lI,o-lI-e),y:c,width:e,height:n,side:"bottom"})),u+e<=o-lI&&g.push(Dq({x:u,y:BG(a-n/2,lI,i-lI-n),width:e,height:n,side:"right"})),l>=lI&&g.push(Dq({x:l,y:BG(a-n/2,lI,i-lI-n),width:e,height:n,side:"left"}));const h=g.find(d=>r.every(p=>!KJo(cde(d,4),p)));return h||(g[0]?g[0]:Dq({x:BG(s-e/2,lI,o-lI-e),y:BG(A,lI,i-lI-n),width:e,height:n,side:"top"}))}function OJo(t,e){const n=(e.minX+e.maxX)/2,o=(e.minY+e.maxY)/2,i=(t.minX+t.maxX)/2,r=(t.minY+t.maxY)/2;switch(t.side){case"top":return{from:{x:i,y:t.maxY},to:{x:n,y:e.minY}};case"bottom":return{from:{x:i,y:t.minY},to:{x:n,y:e.maxY}};case"left":return{from:{x:t.maxX,y:r},to:{x:e.minX,y:o}};case"right":return{from:{x:t.minX,y:r},to:{x:e.maxX,y:o}}}}function GJo(t){switch(t.type){case"schematic_component_overlap_warning":return t.schematic_component_overlap_warning_id;case"schematic_component_styling_warning":return t.schematic_component_styling_warning_id;case"schematic_element_outside_sheet_warning":return t.schematic_element_outside_sheet_warning_id;case"schematic_manual_edit_conflict_warning":return t.schematic_manual_edit_conflict_warning_id}}function YJo(t,e){const n=t.trim().split(/\s+/),o=[];let i="";for(const r of n){const s=i?`${i} ${r}`:r;if(s.length<=e||i.length===0){i=s;continue}o.push(i),i=r}return i&&o.push(i),o.length>0?o:["Warning"]}function kRe(t){return{minX:Math.min(...t.map(e=>e.x)),minY:Math.min(...t.map(e=>e.y)),maxX:Math.max(...t.map(e=>e.x)),maxY:Math.max(...t.map(e=>e.y))}}function UJo(t,e){return{minX:Math.min(t.minX,e.minX),minY:Math.min(t.minY,e.minY),maxX:Math.max(t.maxX,e.maxX),maxY:Math.max(t.maxY,e.maxY)}}function cde(t,e){return{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}}function KJo(t,e){return!(t.maxX<=e.minX||t.minX>=e.maxX||t.maxY<=e.minY||t.minY>=e.maxY)}function Dq({x:t,y:e,width:n,height:o,side:i}){return{minX:t,minY:e,maxX:t+n,maxY:e+o,side:i}}function BG(t,e,n){return n<e?(e+n)/2:Math.min(Math.max(t,e),n)}function VJo(t){return{name:"",type:"text",value:t,attributes:{},children:[]}}function Nq(t,e){const n=t.filter(ge=>ge.type==="schematic_sheet"),o=zzo(n);let i=o;e?.schematicSheetId!==void 0?i=n.find(ge=>ge.schematic_sheet_id===e.schematicSheetId)??o:e?.schematicSheetIndex!==void 0&&(i=n.find(ge=>ge.sheet_index===e.schematicSheetIndex)??o);const r=i?t.filter(ge=>!ge.type.startsWith("schematic_")||oKt(ge)||"schematic_sheet_id"in ge&&ge.schematic_sheet_id===i.schematic_sheet_id):t,s=rJo(r),a=s.maxX-s.minX,A=s.maxY-s.minY,c=e?.width??1200,l=e?.height??600,u=e?.colorOverrides,g={...Lg,schematic:{...Lg.schematic,...u?.schematic??{}}},h=a/A,d=c/l;let p;if(h>d){const ge=c/h;p={x:0,y:(l-ge)/2}}else{const ge=l*h;p={x:(c-ge)/2,y:0}}const m=TUo([{x:s.minX,y:s.maxY},{x:s.maxX,y:s.maxY},{x:s.maxX,y:s.minY}],[{x:p.x,y:p.y},{x:c-p.x,y:p.y},{x:c-p.x,y:l-p.y}]),_=[];if(_.push({name:"rect",type:"element",attributes:{class:"boundary",x:"0",y:"0",width:c.toString(),height:l.toString()},children:[],value:""}),e?.grid){const ge=typeof e.grid=="object"?e.grid:{};_.push(Kzo({bounds:s,transform:m,...ge}))}const f=[],I=[],C=[],y=[],x=[],E=[],B=[],S=[],Q=[],w=[],M=[],k=[],R=[],F=[],O=[],U=[],Y=[],W=JJo({transform:m,svgWidth:c,svgHeight:l,schematicSheet:i}),te=Array.isArray(g.simulation_palette)?g.simulation_palette:Array.isArray(g.palette)?g.palette:[];let j=0;for(const ge of r)if(ge.type==="schematic_sheet")U.push(...wJo({schematicSheet:ge,transform:m,colorMap:g}));else if(ge.type==="schematic_graphic")Y.push(sJo({schematicGraphic:ge,viewport:WJo({availableViewport:W,schematicGraphic:ge,transform:m})}));else if(ge.type==="schematic_debug_object")f.push(...QJo({debugObject:ge,transform:m}));else if(ge.type==="schematic_component")I.push(...SJo({component:ge,transform:m,circuitJson:r,colorMap:g})),Q.push(...OUt({component:ge,transform:m,circuitJson:r}));else if(ge.type==="schematic_box")B.push(..._Jo({schematicBox:ge,transform:m,colorMap:g}));else if(ge.type==="schematic_trace")C.push(...MJo({trace:ge,transform:m,colorMap:g}));else if(ge.type==="schematic_net_label")y.push(...lJo({schNetLabel:ge,realToScreenTransform:m,colorMap:g}));else if(ge.type==="schematic_text"&&!ge.schematic_component_id)x.push(TRe({elm:ge,transform:m,colorMap:g}));else if(ge.type==="schematic_voltage_probe"){const _e=te.length>0?te[j%te.length]:void 0;j+=1,E.push(...DJo({probe:ge,transform:m,colorMap:g,fallbackColor:_e}))}else if(ge.type==="schematic_table")S.push(...PJo({schematicTable:ge,transform:m,colorMap:g,circuitJson:r}));else if(ge.type==="schematic_line"){if(ge.schematic_component_id)continue;M.push(...$Ut({schLine:ge,transform:m,colorMap:g}))}else if(ge.type==="schematic_circle"){if(ge.schematic_component_id)continue;k.push(...KUt({schCircle:ge,transform:m,colorMap:g}))}else if(ge.type==="schematic_rect"){if(ge.schematic_component_id)continue;R.push(...qUt({schRect:ge,transform:m,colorMap:g}))}else if(ge.type==="schematic_arc"){if(ge.schematic_component_id)continue;F.push(...UUt({schArc:ge,transform:m,colorMap:g}))}else if(ge.type==="schematic_path"){if(ge.schematic_component_id)continue;O.push(...XUt({schPath:ge,transform:m,colorMap:g}))}else if(ge.type==="schematic_port"){const _e=r.find(ue=>ue.type==="source_port"&&ue.source_port_id===ge.source_port_id);_e?.type==="source_port"&&_e.do_not_connect===!0&&w.push(dJo({schPort:ge,transform:m,colorMap:g})),e?.drawPorts&&w.push(...hJo({schPort:ge,transform:m,circuitJson:r,colorMap:g}))}const J=C.filter(ge=>ge.attributes?.["data-layer"]!=="overlay"),oe=C.filter(ge=>ge.attributes?.["data-layer"]==="overlay");_.push(...Y,...f,...U,...J,...oe,...M,...k,...R,...F,...O,...I,...Q,...w,...y,...x,...B,...E,...S),e?.labeledPoints&&_.push(Vzo({points:e.labeledPoints,transform:m})),e?.shouldDrawWarnings&&_.push(...RJo({circuitJson:r,transform:m,svgWidth:c,svgHeight:l,colorMap:g}));const ie=Gw(t),ne=Yw;if(e?.showErrorsInTextOverlay){const ge=IG(t);ge&&_.push(ge)}const le={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",class:["tscircuit-schematic",e?.className].filter(Boolean).join(" "),width:c.toString(),height:l.toString(),style:`background-color: ${g.schematic.background}`,"data-real-to-screen-transform":NUo(m),...ie&&{"data-software-used-string":ie},...e?.includeVersion&&{"data-circuit-to-svg-version":ne}},children:[{name:"style",type:"element",children:[{type:"text",value:`
              .boundary { fill: ${g.schematic.background}; }
              .schematic-boundary { fill: none; stroke: #fff; }
              .component { fill: none; stroke: ${g.schematic.component_outline}; }
              .chip { fill: ${g.schematic.component_body}; stroke: ${g.schematic.component_outline}; }
              .component-pin { fill: none; stroke: ${g.schematic.component_outline}; }
              .text { font-family: sans-serif; fill: ${g.schematic.wire}; }
              .pin-number { fill: ${g.schematic.pin_number}; }
              .port-label { fill: ${g.schematic.reference}; }
              .component-name { fill: ${g.schematic.reference}; }
              ${e?.css??""}
            `,name:"",attributes:{},children:[]}],value:"",attributes:{}},..._],value:""};return Ow(le)}var zJo=Nq;function JJo({transform:t,svgWidth:e,svgHeight:n,schematicSheet:o}){if(!o)return{x:0,y:0,width:e,height:n};const i=Sq(o),r=hn(t,{x:i.innerMinX,y:i.innerMaxY}),s=hn(t,{x:i.innerMaxX,y:i.innerMinY});return{x:Math.min(r.x,s.x),y:Math.min(r.y,s.y),width:Math.abs(s.x-r.x),height:Math.abs(s.y-r.y)}}function WJo({availableViewport:t,schematicGraphic:e,transform:n}){if(e.width===void 0&&e.height===void 0)return t;const o=e.width===void 0?t.width:iKt(e.width*Math.hypot(n.a,n.b),t.width),i=e.height===void 0?t.height:iKt(e.height*Math.hypot(n.c,n.d),t.height);return{x:t.x+(t.width-o)/2,y:t.y+(t.height-i)/2,width:o,height:i}}function iKt(t,e){return Number.isFinite(t)?Math.max(0,Math.min(t,e)):e}var jJo=1e3,$Jo=28,qJo=16;function XJo(t,e){const n=t.filter(u=>u.type==="schematic_sheet").slice().sort((u,g)=>(u.sheet_index??0)-(g.sheet_index??0));if(n.length<=1)return Nq(t,e);const o=e?.width??jJo,i=e?.sheetLabelHeight??$Jo,r=e?.sheetGap??qJo,s={...Lg,schematic:{...Lg.schematic,...e?.colorOverrides?.schematic??{}}},a=[];let A=0;n.forEach((u,g)=>{const h=Sq(u),d=e?.height??Math.round(o*h.height/h.width),p=Nq(t,{...e,schematicSheetId:u.schematic_sheet_id,schematicSheetIndex:void 0,width:o,height:d}),m=NRe($W(p)),_=A+i,f=u.display_name??u.name??`Sheet ${u.sheet_index??g+1}`,I=ZJo({transformStr:m.attributes?.["data-real-to-screen-transform"],panelTop:_,labelHeight:i,schematicSheet:u});a.push({name:"text",type:"element",value:"",attributes:{class:"stacked-sheet-label",x:lm(I.x),y:lm(I.y),"font-family":"sans-serif","font-size":`${lm(i*.55)}px`,fill:s.schematic.reference,"data-schematic-sheet-id":u.schematic_sheet_id},children:[{name:"",type:"text",value:f,attributes:{},children:[]}]},Qq(m,0,_,o,d)),A=_+d+r});const c=Math.max(0,A-r),l={name:"svg",type:"element",value:"",attributes:{xmlns:"http://www.w3.org/2000/svg",class:"tscircuit-stacked-schematic",width:lm(o),height:lm(c),viewBox:`0 0 ${lm(o)} ${lm(c)}`,style:`background-color: ${s.schematic.background}`},children:[{name:"rect",type:"element",value:"",attributes:{class:"boundary",x:"0",y:"0",width:lm(o),height:lm(c),fill:s.schematic.background},children:[]},...a]};return Ow(l)}function ZJo({transformStr:t,panelTop:e,labelHeight:n,schematicSheet:o}){const i=e-n*.28;if(!t)return{x:4,y:i};const r=Sq(o),s=hn(wUo(t),{x:r.minX,y:r.maxY});return{x:Math.max(2,s.x),y:i}}var rKt=({simulationResult:t,fallbackName:e})=>{const n=t.name??e,o=t.simulation_parameter_sweep_coordinate;return o?`${n} (${o.parameter_value}${o.parameter_unit})`:n},eWo=t=>{const e=t[0]??0,n=t[1];return{timestamps_ms:t,start_time_ms:e,end_time_ms:t.at(-1)??0,time_per_step:n===void 0?1:Math.abs(n-e)}},tWo=t=>t.type==="simulation_transient_voltage_graph"?t.simulation_transient_voltage_graph_id:t.simulation_transient_current_graph_id,sKt=t=>{switch(t.type){case"simulation_transient_voltage_graph":return t.simulation_transient_voltage_graph_id;case"simulation_transient_current_graph":return t.simulation_transient_current_graph_id;case"simulation_dc_operating_point_voltage":return t.simulation_dc_operating_point_voltage_id;case"simulation_dc_operating_point_current":return t.simulation_dc_operating_point_current_id;case"simulation_dc_sweep_voltage_graph":return t.simulation_dc_sweep_voltage_graph_id;case"simulation_dc_sweep_current_graph":return t.simulation_dc_sweep_current_graph_id;case"simulation_ac_sweep_voltage_graph":return t.simulation_ac_sweep_voltage_graph_id;case"simulation_ac_sweep_current_graph":return t.simulation_ac_sweep_current_graph_id}},nWo=({simulationResult:t,acSweepView:e,usesLogarithmicXValues:n})=>{switch(t.type){case"simulation_dc_operating_point_voltage":return{horizontalCoordinates:[0],measuredLevels:[t.voltage],isCurrent:!1};case"simulation_dc_operating_point_current":return{horizontalCoordinates:[0],measuredLevels:[t.current],isCurrent:!0};case"simulation_dc_sweep_voltage_graph":return{horizontalCoordinates:t.sweep_values,measuredLevels:t.voltage_levels,isCurrent:!1};case"simulation_dc_sweep_current_graph":return{horizontalCoordinates:t.sweep_values,measuredLevels:t.current_levels,isCurrent:!0};case"simulation_ac_sweep_voltage_graph":return{horizontalCoordinates:n?t.frequencies_hz.map(Math.log10):t.frequencies_hz,measuredLevels:t.complex_voltages.map(o=>e==="phase"?Math.atan2(o.im,o.re)*180/Math.PI:Math.hypot(o.re,o.im)),isCurrent:!1};case"simulation_ac_sweep_current_graph":return{horizontalCoordinates:n?t.frequencies_hz.map(Math.log10):t.frequencies_hz,measuredLevels:t.complex_currents.map(o=>e==="phase"?Math.atan2(o.im,o.re)*180/Math.PI:Math.hypot(o.re,o.im)),isCurrent:!0}}},oWo=({simulationResult:t,acSweepView:e,usesLogarithmicXValues:n})=>{if(t.type==="simulation_transient_voltage_graph"||t.type==="simulation_transient_current_graph")return t.simulation_parameter_sweep_coordinate?{...t,name:rKt({simulationResult:t,fallbackName:t.name??tWo(t)})}:t;const o=sKt(t),{horizontalCoordinates:i,measuredLevels:r,isCurrent:s}=nWo({simulationResult:t,acSweepView:e,usesLogarithmicXValues:n}),a={simulation_experiment_id:t.simulation_experiment_id,simulation_parameter_sweep_coordinate:t.simulation_parameter_sweep_coordinate,name:rKt({simulationResult:t,fallbackName:o}),color:t.color,...eWo(i)};return s?{type:"simulation_transient_current_graph",simulation_transient_current_graph_id:o,current_levels:r,...a}:{type:"simulation_transient_voltage_graph",simulation_transient_voltage_graph_id:o,voltage_levels:r,...a}},iWo=({simulationResultType:t,experiment:e})=>t?.startsWith("simulation_ac_sweep_")?"Frequency (Hz)":t?.startsWith("simulation_dc_sweep_")?e?.dc_sweep_unit?`DC Sweep (${e.dc_sweep_unit})`:"DC Sweep":t?.startsWith("simulation_dc_operating_point_")?"Operating Point":"Time (ms)",rWo=({results:t,acSweepView:e,experiment:n})=>{const o=t[0]?.type,i=o?.startsWith("simulation_ac_sweep_")??!1,r=i&&n?.ac_sweep_type!=="linear";return{graphs:t.map(a=>oWo({simulationResult:a,acSweepView:e,usesLogarithmicXValues:r})),xAxisTitle:iWo({simulationResultType:o,experiment:n}),yAxisTitle:i&&e==="phase"?"Phase (deg)":void 0,usesLogarithmicXValues:r}};function Rq(t){return t?.valuePerDiv!==void 0&&Number.isFinite(t.valuePerDiv)&&Math.abs(t.valuePerDiv)>Number.EPSILON}var sWo=1200,aWo=600,um={top:64,right:100,bottom:80,left:100},FRe=24,LRe=56,AWo=56,cWo=8,aKt="#1f77b4";function Hx(t){return t.type==="simulation_transient_current_graph"}function HRe(t){return Hx(t)?t.simulation_transient_current_graph_id:t.simulation_transient_voltage_graph_id}function AKt(t){return Hx(t)?"data-simulation-transient-current-graph-id":"data-simulation-transient-voltage-graph-id"}function cKt(t){return Hx(t)?t.current_levels:t.voltage_levels}function lWo(t){const e=t.some(o=>Hx(o.graph)),n=t.some(o=>!Hx(o.graph));return e&&!n?"Current (A)":n&&!e?"Voltage (V)":"Value"}function uWo(t){return`simulation-graph-${t.replace(/[^a-zA-Z0-9_-]+/g,"-")}`}function ji(t){if(!Number.isFinite(t))return"0";const e=Number.parseFloat(t.toFixed(6));return Number.isInteger(e),e.toString()}function ac(t,e,n=[]){return{name:t,type:"element",value:"",attributes:e,children:n}}function LB(t){return{name:"",type:"text",value:t,attributes:{},children:[]}}function ORe(t,e){if(!Number.isFinite(t))return`0 ${e}`;if(t===0)return`0 ${e}`;const n=Math.abs(t),o=[{threshold:1e6,factor:1e6,prefix:"M"},{threshold:1e3,factor:1e3,prefix:"k"},{threshold:1,factor:1,prefix:""},{threshold:.001,factor:.001,prefix:"m"},{threshold:1e-6,factor:1e-6,prefix:"µ"},{threshold:1e-9,factor:1e-9,prefix:"n"}],i=o.find(s=>n>=s.threshold)??o[o.length-1],r=t/i.factor;return`${lKt(r)} ${i.prefix}${e}`}function gWo(t){return`${lKt(t)} div`}function lKt(t){if(!Number.isFinite(t))return"0";const e=Math.abs(t),n=e>=100?0:e>=10?1:e>=1?2:3;return Number.parseFloat(t.toFixed(n)).toString()}function uKt(t,e){const n=e.tickLabelOverrides?.get(t);if(n!==void 0)return n;const{ticks:o}=e;if(o.length<=1)return ji(t);const i=o[o.length-1]-o[0];if(!Number.isFinite(i)||i===0)return ji(t);const r=dWo(i),s=10**r;return(Math.round(t*s)/s).toFixed(r).replace(/\.0+$/,"").replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function dWo(t){return t>=100?0:t>=10?1:t>=1?2:3}function hWo({graphs:t,valueAxis:e,scaleY:n,plotLeft:o,plotWidth:i,plotHeight:r}){const s=um.top,a=um.top+r,A=o,c=o+i,l=[],u=t.filter(g=>Rq(g.scopeTraceDisplay));for(const[g,h]of u.entries()){const d=g%2===0?"left":"right",p=Math.floor(g/2),m=d==="left"?A-10-p*LRe:c+10+p*LRe,_=d==="left"?m-6:m+6,f=d==="left"?"end":"start",I=d==="left"?m+6:m-6,C=h.scopeTraceDisplay;if(Rq(C)){l.push(ac("line",{class:"axis axis-y axis-y-scope",x1:ji(m),y1:ji(s),x2:ji(m),y2:ji(a),style:`stroke: ${h.color};`}),ac("text",{class:"axis-title axis-title-y axis-title-y-scope",x:ji(m),y:ji(s-12),"text-anchor":"middle",style:`fill: ${h.color}; font-size: 10px;`},[LB(h.label)]));for(const y of e.ticks){const x=n(y),E=(C.center??0)+(y-(C.offsetDivs??0))*C.valuePerDiv;l.push(ac("line",{class:"axis-tick axis-tick-y axis-tick-y-scope",x1:ji(m),y1:ji(x),x2:ji(I),y2:ji(x),style:`stroke: ${h.color};`}),ac("text",{class:"axis-label axis-label-y axis-label-y-scope",x:ji(_),y:ji(x),"text-anchor":f,"dominant-baseline":"middle",style:`fill: ${h.color}; font-size: 10px;`},[LB(ORe(E,Hx(h.graph)?"A":"V"))]))}}}return l}function pWo({timeAxis:t,valueAxis:e,graphs:n,scaleX:o,scaleY:i,plotLeft:r,plotWidth:s,plotHeight:a,yAxisTitle:A,xAxisTitle:c,usesScopeTraceDisplay:l}){const u=um.top+a,g=r,h=r+s,d=[ac("line",{class:"axis axis-x",x1:ji(g),y1:ji(u),x2:ji(h),y2:ji(u)}),...l?[]:[ac("line",{class:"axis axis-y",x1:ji(g),y1:ji(um.top),x2:ji(g),y2:ji(u)})]];for(const p of t.ticks){const m=ji(o(p));d.push(ac("line",{class:"axis-tick axis-tick-x",x1:m,y1:ji(u),x2:m,y2:ji(u+6)}),ac("text",{class:"axis-label axis-label-x",x:m,y:ji(u+22),"text-anchor":"middle"},[LB(uKt(p,t))]))}if(l)d.push(...hWo({graphs:n,valueAxis:e,scaleY:i,plotLeft:r,plotWidth:s,plotHeight:a}));else{for(const p of e.ticks){const m=ji(i(p));d.push(ac("line",{class:"axis-tick axis-tick-y",x1:ji(g-6),y1:m,x2:ji(g),y2:m}),ac("text",{class:"axis-label axis-label-y",x:ji(g-10),y:m,"text-anchor":"end","dominant-baseline":"middle"},[LB(uKt(p,e))]))}d.push(ac("text",{class:"axis-title axis-title-y",x:ji(g-64),y:ji(um.top+a/2),transform:`rotate(-90 ${ji(g-64)} ${ji(um.top+a/2)})`,"text-anchor":"middle"},[LB(A)]))}return d.push(ac("text",{class:"axis-title axis-title-x",x:ji(g+s/2),y:ji(u+48),"text-anchor":"middle"},[LB(c)])),ac("g",{class:"axes"},d)}function lde(t,e=!1){if(t.length===0)return{domainMin:0,domainMax:1,ticks:[0,1]};const n=Math.min(...t),o=Math.max(...t);if(n===o){const A=n===0?1:Math.abs(n)*.1||1;return{domainMin:n-A,domainMax:n+A,ticks:[n-A,n,n+A]}}const i=gKt(n,o),r=i.length>0?[...i]:[n,o];let s=r[0],a=r[r.length-1];if(e&&r.length>1){const A=Math.abs(r[1]-r[0]),c=.1;n<s+A*c&&(s-=A,r.unshift(s)),o>a-A*c&&(a+=A,r.push(a))}return{domainMin:s,domainMax:a,ticks:r}}function mWo({values:t,graphs:e,experiment:n}){const o=ude(n?.start_time_ms),i=ude(n?.end_time_ms),r=e.map(p=>ude(p.start_time_ms)).filter(p=>p!==void 0),s=e.map(p=>ude(p.end_time_ms)).filter(p=>p!==void 0),a=o??(r.length>0?Math.min(...r):void 0),A=i??(s.length>0?Math.max(...s):void 0);if(a===void 0||A===void 0||a===A)return lde(t);const c=Math.min(a,A),l=Math.max(a,A),g=(l-c)*.12,h=gKt(c,l).filter(p=>p>c+g&&p<l-g),d=_Wo([c,...h,l]);return{domainMin:c,domainMax:l,ticks:d,tickLabelOverrides:new Map([[c,ji(c)],[l,ji(l)]])}}function ude(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function _Wo(t){const e=[...t].sort((o,i)=>o-i),n=[];for(const o of e){const i=n[n.length-1];(i===void 0||Math.abs(o-i)>1e-12)&&n.push(o)}return n}function gKt(t,e,n=6){const o=e-t;if(!Number.isFinite(o)||o<=Number.EPSILON)return[t,e];const i=fWo(o/Math.max(1,n-1)),r=Math.floor(t/i)*i,s=Math.ceil(e/i)*i,a=[];for(let A=r;A<=s+i/2;A+=i)a.push(Number.parseFloat(A.toPrecision(12)));return a}function fWo(t){if(!Number.isFinite(t)||t<=0)return 1;const e=Math.floor(Math.log10(t)),n=t/10**e;let o;return n<=1?o=1:n<=2?o=2:n<=5?o=5:o=10,o*10**e}function IWo(t,e){return ac("rect",{class:"background",x:"0",y:"0",width:ji(t),height:ji(e)})}function CWo(t,e,n,o){return ac("defs",{},[ac("clipPath",{id:t},[ac("rect",{x:ji(e),y:ji(um.top),width:ji(n),height:ji(o)})])])}function yWo({timeAxis:t,valueAxis:e,scaleX:n,scaleY:o,plotLeft:i,plotWidth:r,plotHeight:s}){const a=um.top,A=um.top+s,c=i,l=i+r,u=[];for(const g of t.ticks){const h=ji(n(g));u.push(ac("line",{class:"grid-line grid-line-x",x1:h,y1:ji(a),x2:h,y2:ji(A)}))}for(const g of e.ticks){const h=ji(o(g));u.push(ac("line",{class:"grid-line grid-line-y",x1:ji(c),y1:h,x2:ji(l),y2:h}))}return ac("g",{class:"grid"},u)}function dKt(t,e,n,o){if(!Number.isFinite(t)||!Number.isFinite(e)){const r=(n+o)/2;return()=>r}const i=e-t;if(Math.abs(i)<Number.EPSILON){const r=(n+o)/2;return()=>r}return r=>n+(r-t)/i*(o-n)}function xWo(t,e,n){return ac("rect",{class:"plot-background",x:ji(t),y:ji(um.top),width:ji(e),height:ji(n)})}function EWo(){const t=`
:root { color-scheme: light; }
svg { font-family: 'Inter', 'Helvetica Neue', Arial, sans-serif; }
.background { fill: ${Lg.schematic.background}; }
.plot-background { fill: #ffffff; }
.grid-line { stroke: rgba(0, 0, 0, 0.08); stroke-width: 1; }
.axis { stroke: rgba(0, 0, 0, 0.6); stroke-width: 1.5; }
.axis-tick { stroke: rgba(0, 0, 0, 0.6); stroke-width: 1; }
.axis-label { fill: rgba(0, 0, 0, 0.75); font-size: 12px; }
.axis-title { fill: rgba(0, 0, 0, 0.9); font-size: 14px; font-weight: 600; }
.legend-label { fill: rgba(0, 0, 0, 0.75); font-size: 11px; }
.legend-line { stroke-width: 3; }
.scope-channel-card { fill: #ffffff; stroke: rgba(0, 0, 0, 0.22); stroke-width: 1; }
.scope-channel-header-text { fill: #ffffff; font-size: 14px; font-weight: 700; }
.scope-channel-detail { fill: rgba(0, 0, 0, 0.42); font-size: 14px; }
.simulation-line { fill: none; stroke-width: 2.5; }
.simulation-point { stroke-width: 0; }
.chart-title { fill: rgba(0, 0, 0, 0.85); font-size: 18px; font-weight: 600; }
`;return ac("style",{},[LB(t)])}function hKt(t,e){const n=t[e];if(typeof n=="string")return n}function BWo(t,e,n,o){const r=[4,8],s=r.map(g=>ji(g)).join(" "),A=r.reduce((g,h)=>g+h,0)/3,c=[];t.forEach((g,h)=>{if(g.points.length===0)return;const d=[];g.points.forEach((I,C)=>{const y=ji(n(I.timeMs)),x=ji(o(I.displayValue));d.push(`${C===0?"M":"L"} ${y} ${x}`)});const p={class:"simulation-line",d:d.join(" "),stroke:g.color,"clip-path":`url(#${e})`,[AKt(g.graph)]:HRe(g.graph)};g.graph.source_component_id&&(p["data-source-component-id"]=g.graph.source_component_id);const m=hKt(g.graph,"source_probe_id");m&&(p["data-source-probe-id"]=m);const _=hKt(g.graph,"source_probe_name");_&&(p["data-source-probe-name"]=_),g.graph.subcircuit_connectivity_map_key&&(p["data-subcircuit-connectivity-map-key"]=g.graph.subcircuit_connectivity_map_key);const f=g.points.map(I=>{const C=ji(n(I.timeMs)),y=ji(o(I.displayValue));return ac("circle",{class:"simulation-point",cx:C,cy:y,r:"2.5",fill:g.color,"clip-path":`url(#${e})`})});c.push({entry:g,graphIndex:h,pathAttributes:p,pointElements:f})});const l=[];for(let g=0;g<3;g++)for(const h of c){const d=(h.graphIndex+g)%3,p=ji(d*A);l.push(ac("path",{...h.pathAttributes,"stroke-dasharray":s,"stroke-dashoffset":p}))}const u=c.flatMap(g=>g.pointElements);return ac("g",{class:"data-series"},[...l,...u])}function bWo(t,e){return t?.name?ac("text",{class:"chart-title",x:ji(e/2),y:ji(um.top-40),"text-anchor":"middle"},[LB(t.name)]):null}var pKt=16;function SWo(t,e,n,o){const i=o.map((r,s)=>ac("tspan",{x:"20",dy:s===0?"0":String(pKt)},[LB(r)]));return ac("g",{class:"legend-item",transform:`translate(${ji(e)} ${ji(n)})`},[ac("line",{class:"legend-line",x1:"0",y1:"0",x2:"16",y2:"0",stroke:t.color}),ac("text",{class:"legend-label",x:"20",y:"0","dominant-baseline":"middle"},i)])}var QWo=15;function vWo(t){const e=t.split("_");if(e.length<=1)return[t];const n=[];let o=e[0]??"";for(let i=1;i<e.length;i++){const r=e[i]??"",s=`${o}_${r}`;s.length>QWo?(n.push(o),o=r):o=s}return o&&n.push(o),n}var wWo=24;function PWo(t,e){let n=um.top;const o=t.map(i=>{const r=e-um.right+10,s=vWo(i.label),a=SWo(i,r,n,s),A=s.length*pKt;return n+=Math.max(A,wWo),a});return ac("g",{class:"legend"},o)}var DR=118,gde=94,bG=18;function mKt(t,e){const n=Math.floor((e+bG)/(DR+bG)),o=Math.max(1,Math.min(n,t)),i=Math.max(1,Math.ceil(t/o)),r=o*DR+(o-1)*bG,s=i*gde+(i-1)*bG;return{columns:o,rows:i,x:Math.max(0,(e-r)/2),height:s}}var dde=20,GRe=8,MWo=14;function DWo(t,e,n){const o=mKt(t.length,e),i=[];for(const[r,s]of t.entries()){const a=r%o.columns,A=Math.floor(r/o.columns);i.push(NWo(s,r,o.x+a*(DR+bG),n+FRe+A*(gde+bG)))}return ac("g",{class:"scope-legend"},i)}function NWo(t,e,n,o){const i=t.scopeTraceDisplay,r=Hx(t.graph)?"A":"V",s=i&&Rq(i)?ORe(i.valuePerDiv,r):`1 ${r}`,a=ORe(i?.center??0,r),A=gWo(i?.offsetDivs??0),c=`Ch${e+1}`,u=[t.label===c?void 0:t.label,`${s}/div`,A,a].filter(h=>!!h),g=u.length>1?(gde-dde-GRe*2-MWo)/(u.length-1):0;return ac("g",{class:"scope-channel",transform:`translate(${ji(n)} ${ji(o)})`,[AKt(t.graph)]:HRe(t.graph)},[ac("rect",{class:"scope-channel-card",x:"0",y:"0",width:ji(DR),height:ji(gde),rx:"6",ry:"6"}),ac("rect",{x:"0",y:"0",width:ji(DR),height:ji(dde),rx:"6",ry:"6",fill:t.color}),ac("rect",{x:"0",y:ji(dde-6),width:ji(DR),height:"6",fill:t.color}),ac("text",{class:"scope-channel-header-text",x:ji(DR/2),y:"14","text-anchor":"middle"},[LB(c)]),...u.map((h,d)=>ac("text",{class:"scope-channel-detail",x:ji(GRe),y:ji(dde+GRe+d*g),"dominant-baseline":"hanging"},[LB(h)]))])}function RWo(t){const e=Math.ceil(t/2),n=Math.floor(t/2);return{left:_Kt(e),right:_Kt(n)}}function _Kt(t){if(t<=1)return 0;const e=10+(t-1)*LRe+6+AWo+cWo;return Math.max(0,e-um.left)}function hde(t){return t.type==="simulation_transient_voltage_graph"||t.type==="simulation_transient_current_graph"||t.type==="simulation_dc_operating_point_voltage"||t.type==="simulation_dc_operating_point_current"||t.type==="simulation_dc_sweep_voltage_graph"||t.type==="simulation_dc_sweep_current_graph"||t.type==="simulation_ac_sweep_voltage_graph"||t.type==="simulation_ac_sweep_current_graph"}function TWo(t){return t?.type==="simulation_transient_current_graph"}function kWo(t){return t?.type==="simulation_transient_voltage_graph"}function YRe(t){return t?.type==="simulation_experiment"}function fKt(t){return t?.type==="simulation_voltage_probe"}function IKt(t){return t?.type==="simulation_current_probe"}function CKt(t){return t?.type==="simulation_oscilloscope_trace"}function FWo(t,e){const n=HWo(t),o=cKt(t),i=Math.min(n.length,o.length),r=[],s=LWo(e);for(let a=0;a<i;a++){const A=Number(n[a]??Number.NaN),c=Number(o[a]??Number.NaN);!Number.isFinite(A)||!Number.isFinite(c)||r.push({timeMs:A,rawValue:c,displayValue:s(c)})}return r}function LWo(t){if(!Rq(t))return i=>i;const e=t.center??0,n=t.offsetDivs??0,o=t.valuePerDiv;return i=>n+(i-e)/o}function HWo(t){const e=cKt(t);if(Array.isArray(t.timestamps_ms)&&t.timestamps_ms.length===e.length)return t.timestamps_ms.map(r=>Number(r));const n=e.length;if(n===0)return[];const o=[];for(let r=0;r<n;r++)o.push(t.start_time_ms+t.time_per_step*r);const i=o.length>0?o[o.length-1]:void 0;return i!==void 0&&Number.isFinite(t.end_time_ms)&&Number.isFinite(i)&&Math.abs(i-t.end_time_ms)>t.time_per_step/2&&o.push(t.end_time_ms),o}function pde(t,e){const n=t[e];if(typeof n=="string")return n}function OWo(t,e,n,o){const i=Hx(t)?"I":"V";if(n?.displayName)return n.displayName;if(t.simulation_parameter_sweep_coordinate&&t.name)return t.name;if(e?.name)return`${i}(${e.name})`;const r=pde(t,"source_probe_name");if(r)return`${i}(${r})`;if(t.source_component_id){const s=o.get(t.source_component_id);if(s)return`${i}(${s})`}return t.name?t.name:t.source_component_id?`Probe ${t.source_component_id}`:HRe(t)}function GWo(t,e,n,o,i,r){if(Hx(t)){const A=o.get(t.simulation_transient_current_graph_id);if(A)return A;const c=pde(t,"source_probe_id")??(e?.type==="simulation_current_probe"?e.simulation_current_probe_id:void 0);return c?r.get(c):void 0}const s=n.get(t.simulation_transient_voltage_graph_id);if(s)return s;const a=pde(t,"source_probe_id")??(e?.type==="simulation_voltage_probe"?e.simulation_voltage_probe_id:void 0);return a?i.get(a):void 0}function YWo(t,e,n,o,i){const r=pde(t,"source_probe_id");if(r){const s=Hx(t)?n.get(r):e.get(r);if(s)return s}if(t.source_component_id)return Hx(t)?i.get(t.source_component_id):o.get(t.source_component_id)}function UWo(t,e){if(e)return{displayName:e.display_name,color:e.color,center:e.display_center_value,offsetDivs:e.display_center_offset_divs,valuePerDiv:Hx(t)?e.amps_per_div:e.volts_per_div}}function KWo(t,e){const n=Array.isArray(Lg.simulation_palette)?Lg.simulation_palette:Array.isArray(Lg.palette)?Lg.palette:[],o=e.filter(fKt),i=e.filter(IKt),r=e.filter(CKt),s=new Map,a=new Map,A=new Map,c=new Map,l=new Map,u=new Map,g=new Map,h=new Map,d=new Map,p=new Map,m=new Map,_=new Map;for(const f of r)f.simulation_transient_voltage_graph_id&&d.set(f.simulation_transient_voltage_graph_id,f),f.simulation_transient_current_graph_id&&p.set(f.simulation_transient_current_graph_id,f),f.simulation_voltage_probe_id&&m.set(f.simulation_voltage_probe_id,f),f.simulation_current_probe_id&&_.set(f.simulation_current_probe_id,f);for(const f of o)l.set(f.simulation_voltage_probe_id,f),f.name&&f.source_component_id&&s.set(f.source_component_id,f.name),f.color&&f.source_component_id&&a.set(f.source_component_id,f.color),f.source_component_id&&g.set(f.source_component_id,f);for(const f of i)u.set(f.simulation_current_probe_id,f),f.name&&f.source_component_id&&A.set(f.source_component_id,f.name),f.color&&f.source_component_id&&c.set(f.source_component_id,f.color),f.source_component_id&&h.set(f.source_component_id,f);return t.map((f,I)=>{const C=YWo(f,l,u,g,h),y=GWo(f,C,d,p,m,_),x=UWo(f,y),E=FWo(f,x),B=VWo(n,I),S=zWo(f,C,Hx(f)?c:a),Q=f.color??x?.color??S??B,w=OWo(f,C,x,Hx(f)?A:s);return{graph:f,points:E,color:Q,label:w,scopeTraceDisplay:x,usesScopeTraceDisplay:Rq(x)}}).filter(f=>f.points.length>0)}function VWo(t,e){return t.length===0?aKt:t[e%t.length]??aKt}function zWo(t,e,n){if(e?.color)return e.color;if(t.source_component_id)return n.get(t.source_component_id)}function yKt({circuitJson:t,simulation_experiment_id:e,simulation_transient_current_graph_ids:n,simulation_transient_voltage_graph_ids:o,simulation_result_ids:i,ac_sweep_view:r="magnitude",width:s=sWo,height:a=aWo,includeVersion:A}){const c=o?new Set(o):null,l=n?new Set(n):null,u=!!(c||l),g=i?new Set(i):null,h=t.find(J=>YRe(J)&&J.simulation_experiment_id===e),d=t.filter(J=>hde(J)&&J.simulation_experiment_id===e&&(!g||g.has(sKt(J)))&&(!u||J.type==="simulation_transient_voltage_graph"&&(c?.has(J.simulation_transient_voltage_graph_id)??!1)||J.type==="simulation_transient_current_graph"&&(l?.has(J.simulation_transient_current_graph_id)??!1))),p=rWo({results:d,acSweepView:r,experiment:h}),m=p.graphs;if(m.length===0)throw new Error(`No simulation analysis results found for simulation_experiment_id "${e}"`);const _=KWo(m,t),f=_.flatMap(J=>J.points);if(f.length===0)throw new Error(`Simulation results for simulation_experiment_id "${e}" do not contain any datapoints`);const I=f.map(J=>J.timeMs);let C;p.usesLogarithmicXValues?C=JWo(I):p.xAxisTitle==="Time (ms)"?C=mWo({values:I,graphs:m,experiment:h}):C=lde(I);const y=lde(f.map(J=>J.displayValue),!0),x=_.some(J=>J.usesScopeTraceDisplay),E=x?RWo(_.length):{left:0,right:0},B=s+E.left+E.right,S=x?mKt(_.length,B):null,Q=S?a+FRe+S.height+FRe:a,w=Math.max(1,s-um.left-um.right),M=Math.max(1,a-um.top-um.bottom),k=um.left+E.left,R=dKt(C.domainMin,C.domainMax,k,k+w),F=dKt(y.domainMin,y.domainMax,um.top+M,um.top),O=uWo(e),U=Gw(t),Y=Yw,W=bWo(h,B),te=[EWo(),IWo(B,Q),CWo(O,k,w,M),xWo(k,w,M),yWo({timeAxis:C,valueAxis:y,scaleX:R,scaleY:F,plotLeft:k,plotWidth:w,plotHeight:M}),BWo(_,O,R,F),pWo({timeAxis:C,valueAxis:y,graphs:_,scaleX:R,scaleY:F,plotLeft:k,plotWidth:w,plotHeight:M,yAxisTitle:p.yAxisTitle??lWo(_),xAxisTitle:p.xAxisTitle,usesScopeTraceDisplay:x}),x?DWo(_,B,a):PWo(_,B),...W?[W]:[]],j=ac("svg",{xmlns:"http://www.w3.org/2000/svg",width:B.toString(),height:Q.toString(),style:`background-color: ${Lg.schematic.background}`,viewBox:`0 0 ${ji(B)} ${ji(Q)}`,"data-simulation-experiment-id":e,...h?.name&&{"data-simulation-experiment-name":h.name},...U&&{"data-software-used-string":U},...A&&{"data-circuit-to-svg-version":Y}},te);return Ow(j)}var JWo=t=>{const e=lde(t);return{...e,tickLabelOverrides:new Map(e.ticks.map(n=>[n,ji(10**n)]))}},WWo=1200,jWo=1200,xKt=.55;function $Wo({circuitJson:t,simulation_experiment_id:e,simulation_transient_current_graph_ids:n,simulation_transient_voltage_graph_ids:o,simulation_result_ids:i,ac_sweep_view:r,width:s=WWo,height:a=jWo,schematicHeightRatio:A=xKt,schematicOptions:c,includeVersion:l,graphAboveSchematic:u=!1,showErrorsInTextOverlay:g}){const h=t.filter(F=>!YRe(F)&&!hde(F)),d=XWo(A),p=Math.max(1,a*d),m=Math.max(1,a-p),_=p+m,f=_===0?1:a/_,I=p*f,C=m*f,y=Nq(h,{...c,width:s,height:I,includeVersion:!1,showErrorsInTextOverlay:g}),x=yKt({circuitJson:t,simulation_experiment_id:e,simulation_transient_current_graph_ids:n,simulation_transient_voltage_graph_ids:o,simulation_result_ids:i,ac_sweep_view:r,width:s,height:C,includeVersion:!1}),E=NRe($W(y)),B=NRe($W(x)),S=qWo(B)??{width:s,height:C},Q=S.width>0?s*(S.height/S.width):C,w=I+Q,M=[];u?(M.push(Qq(B,0,0,s,Q)),M.push(Qq(E,0,Q,s,I))):(M.push(Qq(E,0,0,s,I)),M.push(Qq(B,0,I,s,Q)));const k=Gw(h),R={name:"svg",type:"element",value:"",attributes:{xmlns:"http://www.w3.org/2000/svg",width:lm(s),height:lm(w),viewBox:`0 0 ${lm(s)} ${lm(w)}`,"data-simulation-experiment-id":e,...k&&{"data-software-used-string":k},...l&&{"data-circuit-to-svg-version":Yw}},children:M};return Ow(R)}function qWo(t){const e=t.attributes?.viewBox;if(typeof e!="string")return null;const n=e.trim().split(/[\s,]+/).map(r=>Number.parseFloat(r));if(n.length!==4)return null;const o=n.at(2),i=n.at(3);return!Number.isFinite(o)||!Number.isFinite(i)||o===void 0||i===void 0||o<=0||i<=0?null:{width:o,height:i}}function XWo(t){return Number.isFinite(t)?t<=0?0:t>=1?1:t:xKt}var EKt=["pcb_board","pcb_solder_paste"];function ZWo(t,e){let n=Number.POSITIVE_INFINITY,o=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,r=Number.NEGATIVE_INFINITY;const s=t.filter(Q=>Q.type==="pcb_board"||Q.type==="pcb_panel"||Q.type==="pcb_solder_paste"&&Q.layer===e.layer);for(const Q of s)if(Q.type==="pcb_board")Q.outline&&Array.isArray(Q.outline)&&Q.outline.length>=3?S(Q.outline):"center"in Q&&"width"in Q&&"height"in Q&&B(Q.center,Q.width,Q.height);else if(Q.type==="pcb_panel"){const w=Q,M=lt.parse(w.width),k=lt.parse(w.height);if(M!==void 0&&k!==void 0){const R=w.center??{x:M/2,y:k/2};B(R,M,k)}}else Q.type==="pcb_solder_paste"&&"x"in Q&&"y"in Q&&B({x:Q.x,y:Q.y},0,0);const a=1,A=i-n+2*a,c=r-o+2*a,l=e.width??800,u=e.height??600,g=l/A,h=u/c,d=Math.min(g,h),p=(l-A*d)/2,m=(u-c*d)/2,_=m0(of(p-n*d+a*d,u-m+o*d-a*d),kx(d,-d)),f={transform:_,layer:e.layer,colorMap:ch},I=s.sort((Q,w)=>(EKt.indexOf(w.type)??9999)-(EKt.indexOf(Q.type)??9999)).flatMap(Q=>ejo({elm:Q,ctx:f})),C=Gw(t),y=Yw,x=[{name:"style",type:"element",children:[{type:"text",value:""}]},{name:"rect",type:"element",attributes:{class:"boundary",x:"0",y:"0",fill:"#000",width:l.toString(),height:u.toString()}},tjo(_,n,o,i,r),...I].filter(Q=>Q!==null);if(e?.showErrorsInTextOverlay){const Q=IG(t);Q&&x.push(Q)}const E={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:l.toString(),height:u.toString(),...C&&{"data-software-used-string":C},...e.includeVersion&&{"data-circuit-to-svg-version":y}},value:"",children:x};try{return Ow(E)}catch(Q){throw console.error("Error stringifying SVG object:",Q),Q}function B(Q,w,M){const k=w/2,R=M/2;n=Math.min(n,Q.x-k),o=Math.min(o,Q.y-R),i=Math.max(i,Q.x+k),r=Math.max(r,Q.y+R)}function S(Q){for(const w of Q)n=Math.min(n,w.x),o=Math.min(o,w.y),i=Math.max(i,w.x),r=Math.max(r,w.y)}}function ejo({elm:t,ctx:e}){const{transform:n}=e;switch(t.type){case"pcb_board":return tUt(t,e);case"pcb_solder_paste":return sUt(t,e);default:return[]}}function tjo(t,e,n,o,i){const[r,s]=hn(t,[e,n]),[a,A]=hn(t,[o,i]),c=Math.abs(a-r),l=Math.abs(A-s),u=Math.min(r,a),g=Math.min(s,A);return{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-boundary",fill:"none",stroke:"#fff","stroke-width":"0.3",x:u.toString(),y:g.toString(),width:c.toString(),height:l.toString()}}}const njo=Object.freeze(Object.defineProperty({__proto__:null,CIRCUIT_TO_SVG_VERSION:Yw,circuitJsonToPcbSvg:uzo,circuitJsonToSchematicSvg:zJo,colorMap:Lg,convertCircuitJsonToAssemblySvg:_Ut,convertCircuitJsonToPcbSvg:pUt,convertCircuitJsonToPinoutSvg:SUt,convertCircuitJsonToSchematicSimulationSvg:$Wo,convertCircuitJsonToSchematicSvg:Nq,convertCircuitJsonToSimulationGraphSvg:yKt,convertCircuitJsonToSolderPasteMask:ZWo,convertCircuitJsonToStackedSchematicSheetsSvg:XJo,createErrorTextOverlay:IG,createSvgObjectsForSchComponentPortHovers:OUt,getSoftwareUsedString:Gw,isSimulationAnalysisResult:hde,isSimulationCurrentProbe:IKt,isSimulationExperiment:YRe,isSimulationOscilloscopeTrace:CKt,isSimulationTransientCurrentGraph:TWo,isSimulationTransientVoltageGraph:kWo,isSimulationVoltageProbe:fKt},Symbol.toStringTag,{value:"Module"})),ojo=t=>t.some(hde);const mde="165",Vw={ROTATE:0,DOLLY:1,PAN:2},SG={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},ijo=0,BKt=1,rjo=2,bKt=1,SKt=2,qb=3,mE=0,uI=1,r_=2,zw=0,QG=1,QKt=2,vKt=3,wKt=4,sjo=5,NR=100,ajo=101,Ajo=102,cjo=103,ljo=104,ujo=200,gjo=201,djo=202,hjo=203,URe=204,KRe=205,pjo=206,mjo=207,_jo=208,fjo=209,Ijo=210,Cjo=211,yjo=212,xjo=213,Ejo=214,Bjo=0,bjo=1,Sjo=2,_de=3,Qjo=4,vjo=5,wjo=6,Pjo=7,VRe=0,Mjo=1,Djo=2,Jw=0,Njo=1,Rjo=2,Tjo=3,PKt=4,kjo=5,Fjo=6,Ljo=7,MKt="attached",Hjo="detached",DKt=300,vG=301,wG=302,fde=303,zRe=304,Ide=306,c4=1e3,Xy=1001,Tq=1002,wC=1003,JRe=1004,PG=1005,Fl=1006,kq=1007,gm=1008,Ww=1009,Ojo=1010,Gjo=1011,Cde=1012,NKt=1013,MG=1014,m6=1015,yde=1016,RKt=1017,TKt=1018,DG=1020,Yjo=35902,Ujo=1021,Kjo=1022,l4=1023,Vjo=1024,zjo=1025,NG=1026,RG=1027,kKt=1028,FKt=1029,Jjo=1030,LKt=1031,HKt=1033,WRe=33776,jRe=33777,$Re=33778,qRe=33779,OKt=35840,GKt=35841,YKt=35842,UKt=35843,KKt=36196,VKt=37492,zKt=37496,JKt=37808,WKt=37809,jKt=37810,$Kt=37811,qKt=37812,XKt=37813,ZKt=37814,eVt=37815,tVt=37816,nVt=37817,oVt=37818,iVt=37819,rVt=37820,sVt=37821,XRe=36492,aVt=36494,AVt=36495,Wjo=36283,cVt=36284,lVt=36285,uVt=36286,TG=2300,kG=2301,ZRe=2302,gVt=2400,dVt=2401,hVt=2402,jjo=2500,$jo=0,pVt=1,eTe=2,qjo=3200,mVt=3201,tTe=0,Xjo=1,_6="",Ox="srgb",jw="srgb-linear",nTe="display-p3",xde="display-p3-linear",Ede="linear",Ed="srgb",Bde="rec709",bde="p3",FG=7680,_Vt=519,Zjo=512,e$o=513,t$o=514,fVt=515,n$o=516,o$o=517,i$o=518,r$o=519,oTe=35044,IVt="300 es",Xb=2e3,Sde=2001;class RR{addEventListener(e,n){this._listeners===void 0&&(this._listeners={});const o=this._listeners;o[e]===void 0&&(o[e]=[]),o[e].indexOf(n)===-1&&o[e].push(n)}hasEventListener(e,n){if(this._listeners===void 0)return!1;const o=this._listeners;return o[e]!==void 0&&o[e].indexOf(n)!==-1}removeEventListener(e,n){if(this._listeners===void 0)return;const i=this._listeners[e];if(i!==void 0){const r=i.indexOf(n);r!==-1&&i.splice(r,1)}}dispatchEvent(e){if(this._listeners===void 0)return;const o=this._listeners[e.type];if(o!==void 0){e.target=this;const i=o.slice(0);for(let r=0,s=i.length;r<s;r++)i[r].call(this,e);e.target=null}}}const PC=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let CVt=1234567;const LG=Math.PI/180,HG=180/Math.PI;function u4(){const t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,n=Math.random()*4294967295|0,o=Math.random()*4294967295|0;return(PC[t&255]+PC[t>>8&255]+PC[t>>16&255]+PC[t>>24&255]+"-"+PC[e&255]+PC[e>>8&255]+"-"+PC[e>>16&15|64]+PC[e>>24&255]+"-"+PC[n&63|128]+PC[n>>8&255]+"-"+PC[n>>16&255]+PC[n>>24&255]+PC[o&255]+PC[o>>8&255]+PC[o>>16&255]+PC[o>>24&255]).toLowerCase()}function rf(t,e,n){return Math.max(e,Math.min(n,t))}function iTe(t,e){return(t%e+e)%e}function s$o(t,e,n,o,i){return o+(t-e)*(i-o)/(n-e)}function a$o(t,e,n){return t!==e?(n-t)/(e-t):0}function Fq(t,e,n){return(1-n)*t+n*e}function A$o(t,e,n,o){return Fq(t,e,1-Math.exp(-n*o))}function c$o(t,e=1){return e-Math.abs(iTe(t,e*2)-e)}function l$o(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*(3-2*t))}function u$o(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*t*(t*(t*6-15)+10))}function g$o(t,e){return t+Math.floor(Math.random()*(e-t+1))}function d$o(t,e){return t+Math.random()*(e-t)}function h$o(t){return t*(.5-Math.random())}function p$o(t){t!==void 0&&(CVt=t);let e=CVt+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function m$o(t){return t*LG}function _$o(t){return t*HG}function f$o(t){return(t&t-1)===0&&t!==0}function I$o(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function C$o(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function y$o(t,e,n,o,i){const r=Math.cos,s=Math.sin,a=r(n/2),A=s(n/2),c=r((e+o)/2),l=s((e+o)/2),u=r((e-o)/2),g=s((e-o)/2),h=r((o-e)/2),d=s((o-e)/2);switch(i){case"XYX":t.set(a*l,A*u,A*g,a*c);break;case"YZY":t.set(A*g,a*l,A*u,a*c);break;case"ZXZ":t.set(A*u,A*g,a*l,a*c);break;case"XZX":t.set(a*l,A*d,A*h,a*c);break;case"YXY":t.set(A*h,a*l,A*d,a*c);break;case"ZYZ":t.set(A*d,A*h,a*l,a*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function HB(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function ou(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(t*4294967295);case Uint16Array:return Math.round(t*65535);case Uint8Array:return Math.round(t*255);case Int32Array:return Math.round(t*2147483647);case Int16Array:return Math.round(t*32767);case Int8Array:return Math.round(t*127);default:throw new Error("Invalid component type.")}}const OG={DEG2RAD:LG,RAD2DEG:HG,generateUUID:u4,clamp:rf,euclideanModulo:iTe,mapLinear:s$o,inverseLerp:a$o,lerp:Fq,damp:A$o,pingpong:c$o,smoothstep:l$o,smootherstep:u$o,randInt:g$o,randFloat:d$o,randFloatSpread:h$o,seededRandom:p$o,degToRad:m$o,radToDeg:_$o,isPowerOfTwo:f$o,ceilPowerOfTwo:I$o,floorPowerOfTwo:C$o,setQuaternionFromProperEuler:y$o,normalize:ou,denormalize:HB};let ni=class _4n{constructor(e=0,n=0){_4n.prototype.isVector2=!0,this.x=e,this.y=n}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,n){return this.x=e,this.y=n,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const n=this.x,o=this.y,i=e.elements;return this.x=i[0]*n+i[3]*o+i[6],this.y=i[1]*n+i[4]*o+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this}clampLength(e,n){const o=this.length();return this.divideScalar(o||1).multiplyScalar(Math.max(e,Math.min(n,o)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const o=this.dot(e)/n;return Math.acos(rf(o,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,o=this.y-e.y;return n*n+o*o}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this}lerpVectors(e,n,o){return this.x=e.x+(n.x-e.x)*o,this.y=e.y+(n.y-e.y)*o,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this}rotateAround(e,n){const o=Math.cos(n),i=Math.sin(n),r=this.x-e.x,s=this.y-e.y;return this.x=r*o-s*i+e.x,this.y=r*i+s*o+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};class HA{constructor(e,n,o,i,r,s,a,A,c){HA.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,n,o,i,r,s,a,A,c)}set(e,n,o,i,r,s,a,A,c){const l=this.elements;return l[0]=e,l[1]=i,l[2]=a,l[3]=n,l[4]=r,l[5]=A,l[6]=o,l[7]=s,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const n=this.elements,o=e.elements;return n[0]=o[0],n[1]=o[1],n[2]=o[2],n[3]=o[3],n[4]=o[4],n[5]=o[5],n[6]=o[6],n[7]=o[7],n[8]=o[8],this}extractBasis(e,n,o){return e.setFromMatrix3Column(this,0),n.setFromMatrix3Column(this,1),o.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const n=e.elements;return this.set(n[0],n[4],n[8],n[1],n[5],n[9],n[2],n[6],n[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const o=e.elements,i=n.elements,r=this.elements,s=o[0],a=o[3],A=o[6],c=o[1],l=o[4],u=o[7],g=o[2],h=o[5],d=o[8],p=i[0],m=i[3],_=i[6],f=i[1],I=i[4],C=i[7],y=i[2],x=i[5],E=i[8];return r[0]=s*p+a*f+A*y,r[3]=s*m+a*I+A*x,r[6]=s*_+a*C+A*E,r[1]=c*p+l*f+u*y,r[4]=c*m+l*I+u*x,r[7]=c*_+l*C+u*E,r[2]=g*p+h*f+d*y,r[5]=g*m+h*I+d*x,r[8]=g*_+h*C+d*E,this}multiplyScalar(e){const n=this.elements;return n[0]*=e,n[3]*=e,n[6]*=e,n[1]*=e,n[4]*=e,n[7]*=e,n[2]*=e,n[5]*=e,n[8]*=e,this}determinant(){const e=this.elements,n=e[0],o=e[1],i=e[2],r=e[3],s=e[4],a=e[5],A=e[6],c=e[7],l=e[8];return n*s*l-n*a*c-o*r*l+o*a*A+i*r*c-i*s*A}invert(){const e=this.elements,n=e[0],o=e[1],i=e[2],r=e[3],s=e[4],a=e[5],A=e[6],c=e[7],l=e[8],u=l*s-a*c,g=a*A-l*r,h=c*r-s*A,d=n*u+o*g+i*h;if(d===0)return this.set(0,0,0,0,0,0,0,0,0);const p=1/d;return e[0]=u*p,e[1]=(i*c-l*o)*p,e[2]=(a*o-i*s)*p,e[3]=g*p,e[4]=(l*n-i*A)*p,e[5]=(i*r-a*n)*p,e[6]=h*p,e[7]=(o*A-c*n)*p,e[8]=(s*n-o*r)*p,this}transpose(){let e;const n=this.elements;return e=n[1],n[1]=n[3],n[3]=e,e=n[2],n[2]=n[6],n[6]=e,e=n[5],n[5]=n[7],n[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const n=this.elements;return e[0]=n[0],e[1]=n[3],e[2]=n[6],e[3]=n[1],e[4]=n[4],e[5]=n[7],e[6]=n[2],e[7]=n[5],e[8]=n[8],this}setUvTransform(e,n,o,i,r,s,a){const A=Math.cos(r),c=Math.sin(r);return this.set(o*A,o*c,-o*(A*s+c*a)+s+e,-i*c,i*A,-i*(-c*s+A*a)+a+n,0,0,1),this}scale(e,n){return this.premultiply(rTe.makeScale(e,n)),this}rotate(e){return this.premultiply(rTe.makeRotation(-e)),this}translate(e,n){return this.premultiply(rTe.makeTranslation(e,n)),this}makeTranslation(e,n){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,n,0,0,1),this}makeRotation(e){const n=Math.cos(e),o=Math.sin(e);return this.set(n,-o,0,o,n,0,0,0,1),this}makeScale(e,n){return this.set(e,0,0,0,n,0,0,0,1),this}equals(e){const n=this.elements,o=e.elements;for(let i=0;i<9;i++)if(n[i]!==o[i])return!1;return!0}fromArray(e,n=0){for(let o=0;o<9;o++)this.elements[o]=e[o+n];return this}toArray(e=[],n=0){const o=this.elements;return e[n]=o[0],e[n+1]=o[1],e[n+2]=o[2],e[n+3]=o[3],e[n+4]=o[4],e[n+5]=o[5],e[n+6]=o[6],e[n+7]=o[7],e[n+8]=o[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const rTe=new HA;function yVt(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}function Lq(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function x$o(){const t=Lq("canvas");return t.style.display="block",t}const xVt={};function sTe(t){t in xVt||(xVt[t]=!0,console.warn(t))}function E$o(t,e,n){return new Promise(function(o,i){function r(){switch(t.clientWaitSync(e,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:i();break;case t.TIMEOUT_EXPIRED:setTimeout(r,n);break;default:o()}}setTimeout(r,n)})}const EVt=new HA().set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),BVt=new HA().set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),Qde={[jw]:{transfer:Ede,primaries:Bde,toReference:t=>t,fromReference:t=>t},[Ox]:{transfer:Ed,primaries:Bde,toReference:t=>t.convertSRGBToLinear(),fromReference:t=>t.convertLinearToSRGB()},[xde]:{transfer:Ede,primaries:bde,toReference:t=>t.applyMatrix3(BVt),fromReference:t=>t.applyMatrix3(EVt)},[nTe]:{transfer:Ed,primaries:bde,toReference:t=>t.convertSRGBToLinear().applyMatrix3(BVt),fromReference:t=>t.applyMatrix3(EVt).convertLinearToSRGB()}},B$o=new Set([jw,xde]),iu={enabled:!0,_workingColorSpace:jw,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(t){if(!B$o.has(t))throw new Error(`Unsupported working color space, "${t}".`);this._workingColorSpace=t},convert:function(t,e,n){if(this.enabled===!1||e===n||!e||!n)return t;const o=Qde[e].toReference,i=Qde[n].fromReference;return i(o(t))},fromWorkingColorSpace:function(t,e){return this.convert(t,this._workingColorSpace,e)},toWorkingColorSpace:function(t,e){return this.convert(t,e,this._workingColorSpace)},getPrimaries:function(t){return Qde[t].primaries},getTransfer:function(t){return t===_6?Ede:Qde[t].transfer}};function GG(t){return t<.04045?t*.0773993808:Math.pow(t*.9478672986+.0521327014,2.4)}function aTe(t){return t<.0031308?t*12.92:1.055*Math.pow(t,.41666)-.055}let YG;class b$o{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{YG===void 0&&(YG=Lq("canvas")),YG.width=e.width,YG.height=e.height;const o=YG.getContext("2d");e instanceof ImageData?o.putImageData(e,0,0):o.drawImage(e,0,0,e.width,e.height),n=YG}return n.width>2048||n.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),n.toDataURL("image/jpeg",.6)):n.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const n=Lq("canvas");n.width=e.width,n.height=e.height;const o=n.getContext("2d");o.drawImage(e,0,0,e.width,e.height);const i=o.getImageData(0,0,e.width,e.height),r=i.data;for(let s=0;s<r.length;s++)r[s]=GG(r[s]/255)*255;return o.putImageData(i,0,0),n}else if(e.data){const n=e.data.slice(0);for(let o=0;o<n.length;o++)n instanceof Uint8Array||n instanceof Uint8ClampedArray?n[o]=Math.floor(GG(n[o]/255)*255):n[o]=GG(n[o]);return{data:n,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let S$o=0;class bVt{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:S$o++}),this.uuid=u4(),this.data=e,this.dataReady=!0,this.version=0}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const n=e===void 0||typeof e=="string";if(!n&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const o={uuid:this.uuid,url:""},i=this.data;if(i!==null){let r;if(Array.isArray(i)){r=[];for(let s=0,a=i.length;s<a;s++)i[s].isDataTexture?r.push(ATe(i[s].image)):r.push(ATe(i[s]))}else r=ATe(i);o.url=r}return n||(e.images[this.uuid]=o),o}}function ATe(t){return typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap?b$o.getDataURL(t):t.data?{data:Array.from(t.data),width:t.width,height:t.height,type:t.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let Q$o=0;class Hg extends RR{constructor(e=Hg.DEFAULT_IMAGE,n=Hg.DEFAULT_MAPPING,o=Xy,i=Xy,r=Fl,s=gm,a=l4,A=Ww,c=Hg.DEFAULT_ANISOTROPY,l=_6){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Q$o++}),this.uuid=u4(),this.name="",this.source=new bVt(e),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=o,this.wrapT=i,this.magFilter=r,this.minFilter=s,this.anisotropy=c,this.format=a,this.internalFormat=null,this.type=A,this.offset=new ni(0,0),this.repeat=new ni(1,1),this.center=new ni(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new HA,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=l,this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1,this.pmremVersion=0}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}toJSON(e){const n=e===void 0||typeof e=="string";if(!n&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const o={metadata:{version:4.6,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(o.userData=this.userData),n||(e.textures[this.uuid]=o),o}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==DKt)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case c4:e.x=e.x-Math.floor(e.x);break;case Xy:e.x=e.x<0?0:1;break;case Tq:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case c4:e.y=e.y-Math.floor(e.y);break;case Xy:e.y=e.y<0?0:1;break;case Tq:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}Hg.DEFAULT_IMAGE=null,Hg.DEFAULT_MAPPING=DKt,Hg.DEFAULT_ANISOTROPY=1;class ru{constructor(e=0,n=0,o=0,i=1){ru.prototype.isVector4=!0,this.x=e,this.y=n,this.z=o,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,n,o,i){return this.x=e,this.y=n,this.z=o,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;case 3:this.w=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this.w=e.w+n.w,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this.w+=e.w*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this.w=e.w-n.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const n=this.x,o=this.y,i=this.z,r=this.w,s=e.elements;return this.x=s[0]*n+s[4]*o+s[8]*i+s[12]*r,this.y=s[1]*n+s[5]*o+s[9]*i+s[13]*r,this.z=s[2]*n+s[6]*o+s[10]*i+s[14]*r,this.w=s[3]*n+s[7]*o+s[11]*i+s[15]*r,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const n=Math.sqrt(1-e.w*e.w);return n<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/n,this.y=e.y/n,this.z=e.z/n),this}setAxisAngleFromRotationMatrix(e){let n,o,i,r;const A=e.elements,c=A[0],l=A[4],u=A[8],g=A[1],h=A[5],d=A[9],p=A[2],m=A[6],_=A[10];if(Math.abs(l-g)<.01&&Math.abs(u-p)<.01&&Math.abs(d-m)<.01){if(Math.abs(l+g)<.1&&Math.abs(u+p)<.1&&Math.abs(d+m)<.1&&Math.abs(c+h+_-3)<.1)return this.set(1,0,0,0),this;n=Math.PI;const I=(c+1)/2,C=(h+1)/2,y=(_+1)/2,x=(l+g)/4,E=(u+p)/4,B=(d+m)/4;return I>C&&I>y?I<.01?(o=0,i=.707106781,r=.707106781):(o=Math.sqrt(I),i=x/o,r=E/o):C>y?C<.01?(o=.707106781,i=0,r=.707106781):(i=Math.sqrt(C),o=x/i,r=B/i):y<.01?(o=.707106781,i=.707106781,r=0):(r=Math.sqrt(y),o=E/r,i=B/r),this.set(o,i,r,n),this}let f=Math.sqrt((m-d)*(m-d)+(u-p)*(u-p)+(g-l)*(g-l));return Math.abs(f)<.001&&(f=1),this.x=(m-d)/f,this.y=(u-p)/f,this.z=(g-l)/f,this.w=Math.acos((c+h+_-1)/2),this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this.z=Math.max(e.z,Math.min(n.z,this.z)),this.w=Math.max(e.w,Math.min(n.w,this.w)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this.z=Math.max(e,Math.min(n,this.z)),this.w=Math.max(e,Math.min(n,this.w)),this}clampLength(e,n){const o=this.length();return this.divideScalar(o||1).multiplyScalar(Math.max(e,Math.min(n,o)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this.w+=(e.w-this.w)*n,this}lerpVectors(e,n,o){return this.x=e.x+(n.x-e.x)*o,this.y=e.y+(n.y-e.y)*o,this.z=e.z+(n.z-e.z)*o,this.w=e.w+(n.w-e.w)*o,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this.w=e[n+3],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e[n+3]=this.w,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this.w=e.getW(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class v$o extends RR{constructor(e=1,n=1,o={}){super(),this.isRenderTarget=!0,this.width=e,this.height=n,this.depth=1,this.scissor=new ru(0,0,e,n),this.scissorTest=!1,this.viewport=new ru(0,0,e,n);const i={width:e,height:n,depth:1};o=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Fl,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},o);const r=new Hg(i,o.mapping,o.wrapS,o.wrapT,o.magFilter,o.minFilter,o.format,o.type,o.anisotropy,o.colorSpace);r.flipY=!1,r.generateMipmaps=o.generateMipmaps,r.internalFormat=o.internalFormat,this.textures=[];const s=o.count;for(let a=0;a<s;a++)this.textures[a]=r.clone(),this.textures[a].isRenderTargetTexture=!0;this.depthBuffer=o.depthBuffer,this.stencilBuffer=o.stencilBuffer,this.resolveDepthBuffer=o.resolveDepthBuffer,this.resolveStencilBuffer=o.resolveStencilBuffer,this.depthTexture=o.depthTexture,this.samples=o.samples}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}setSize(e,n,o=1){if(this.width!==e||this.height!==n||this.depth!==o){this.width=e,this.height=n,this.depth=o;for(let i=0,r=this.textures.length;i<r;i++)this.textures[i].image.width=e,this.textures[i].image.height=n,this.textures[i].image.depth=o;this.dispose()}this.viewport.set(0,0,e,n),this.scissor.set(0,0,e,n)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let o=0,i=e.textures.length;o<i;o++)this.textures[o]=e.textures[o].clone(),this.textures[o].isRenderTargetTexture=!0;const n=Object.assign({},e.texture.image);return this.texture.source=new bVt(n),this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class TR extends v$o{constructor(e=1,n=1,o={}){super(e,n,o),this.isWebGLRenderTarget=!0}}class SVt extends Hg{constructor(e=null,n=1,o=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:n,height:o,depth:i},this.magFilter=wC,this.minFilter=wC,this.wrapR=Xy,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class w$o extends Hg{constructor(e=null,n=1,o=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:n,height:o,depth:i},this.magFilter=wC,this.minFilter=wC,this.wrapR=Xy,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Zy{constructor(e=0,n=0,o=0,i=1){this.isQuaternion=!0,this._x=e,this._y=n,this._z=o,this._w=i}static slerpFlat(e,n,o,i,r,s,a){let A=o[i+0],c=o[i+1],l=o[i+2],u=o[i+3];const g=r[s+0],h=r[s+1],d=r[s+2],p=r[s+3];if(a===0){e[n+0]=A,e[n+1]=c,e[n+2]=l,e[n+3]=u;return}if(a===1){e[n+0]=g,e[n+1]=h,e[n+2]=d,e[n+3]=p;return}if(u!==p||A!==g||c!==h||l!==d){let m=1-a;const _=A*g+c*h+l*d+u*p,f=_>=0?1:-1,I=1-_*_;if(I>Number.EPSILON){const y=Math.sqrt(I),x=Math.atan2(y,_*f);m=Math.sin(m*x)/y,a=Math.sin(a*x)/y}const C=a*f;if(A=A*m+g*C,c=c*m+h*C,l=l*m+d*C,u=u*m+p*C,m===1-a){const y=1/Math.sqrt(A*A+c*c+l*l+u*u);A*=y,c*=y,l*=y,u*=y}}e[n]=A,e[n+1]=c,e[n+2]=l,e[n+3]=u}static multiplyQuaternionsFlat(e,n,o,i,r,s){const a=o[i],A=o[i+1],c=o[i+2],l=o[i+3],u=r[s],g=r[s+1],h=r[s+2],d=r[s+3];return e[n]=a*d+l*u+A*h-c*g,e[n+1]=A*d+l*g+c*u-a*h,e[n+2]=c*d+l*h+a*g-A*u,e[n+3]=l*d-a*u-A*g-c*h,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,n,o,i){return this._x=e,this._y=n,this._z=o,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,n=!0){const o=e._x,i=e._y,r=e._z,s=e._order,a=Math.cos,A=Math.sin,c=a(o/2),l=a(i/2),u=a(r/2),g=A(o/2),h=A(i/2),d=A(r/2);switch(s){case"XYZ":this._x=g*l*u+c*h*d,this._y=c*h*u-g*l*d,this._z=c*l*d+g*h*u,this._w=c*l*u-g*h*d;break;case"YXZ":this._x=g*l*u+c*h*d,this._y=c*h*u-g*l*d,this._z=c*l*d-g*h*u,this._w=c*l*u+g*h*d;break;case"ZXY":this._x=g*l*u-c*h*d,this._y=c*h*u+g*l*d,this._z=c*l*d+g*h*u,this._w=c*l*u-g*h*d;break;case"ZYX":this._x=g*l*u-c*h*d,this._y=c*h*u+g*l*d,this._z=c*l*d-g*h*u,this._w=c*l*u+g*h*d;break;case"YZX":this._x=g*l*u+c*h*d,this._y=c*h*u+g*l*d,this._z=c*l*d-g*h*u,this._w=c*l*u-g*h*d;break;case"XZY":this._x=g*l*u-c*h*d,this._y=c*h*u-g*l*d,this._z=c*l*d+g*h*u,this._w=c*l*u+g*h*d;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return n===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,n){const o=n/2,i=Math.sin(o);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(o),this._onChangeCallback(),this}setFromRotationMatrix(e){const n=e.elements,o=n[0],i=n[4],r=n[8],s=n[1],a=n[5],A=n[9],c=n[2],l=n[6],u=n[10],g=o+a+u;if(g>0){const h=.5/Math.sqrt(g+1);this._w=.25/h,this._x=(l-A)*h,this._y=(r-c)*h,this._z=(s-i)*h}else if(o>a&&o>u){const h=2*Math.sqrt(1+o-a-u);this._w=(l-A)/h,this._x=.25*h,this._y=(i+s)/h,this._z=(r+c)/h}else if(a>u){const h=2*Math.sqrt(1+a-o-u);this._w=(r-c)/h,this._x=(i+s)/h,this._y=.25*h,this._z=(A+l)/h}else{const h=2*Math.sqrt(1+u-o-a);this._w=(s-i)/h,this._x=(r+c)/h,this._y=(A+l)/h,this._z=.25*h}return this._onChangeCallback(),this}setFromUnitVectors(e,n){let o=e.dot(n)+1;return o<Number.EPSILON?(o=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=o):(this._x=0,this._y=-e.z,this._z=e.y,this._w=o)):(this._x=e.y*n.z-e.z*n.y,this._y=e.z*n.x-e.x*n.z,this._z=e.x*n.y-e.y*n.x,this._w=o),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(rf(this.dot(e),-1,1)))}rotateTowards(e,n){const o=this.angleTo(e);if(o===0)return this;const i=Math.min(1,n/o);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,n){const o=e._x,i=e._y,r=e._z,s=e._w,a=n._x,A=n._y,c=n._z,l=n._w;return this._x=o*l+s*a+i*c-r*A,this._y=i*l+s*A+r*a-o*c,this._z=r*l+s*c+o*A-i*a,this._w=s*l-o*a-i*A-r*c,this._onChangeCallback(),this}slerp(e,n){if(n===0)return this;if(n===1)return this.copy(e);const o=this._x,i=this._y,r=this._z,s=this._w;let a=s*e._w+o*e._x+i*e._y+r*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=s,this._x=o,this._y=i,this._z=r,this;const A=1-a*a;if(A<=Number.EPSILON){const h=1-n;return this._w=h*s+n*this._w,this._x=h*o+n*this._x,this._y=h*i+n*this._y,this._z=h*r+n*this._z,this.normalize(),this}const c=Math.sqrt(A),l=Math.atan2(c,a),u=Math.sin((1-n)*l)/c,g=Math.sin(n*l)/c;return this._w=s*u+this._w*g,this._x=o*u+this._x*g,this._y=i*u+this._y*g,this._z=r*u+this._z*g,this._onChangeCallback(),this}slerpQuaternions(e,n,o){return this.copy(e).slerp(n,o)}random(){const e=2*Math.PI*Math.random(),n=2*Math.PI*Math.random(),o=Math.random(),i=Math.sqrt(1-o),r=Math.sqrt(o);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(n),r*Math.cos(n))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,n=0){return this._x=e[n],this._y=e[n+1],this._z=e[n+2],this._w=e[n+3],this._onChangeCallback(),this}toArray(e=[],n=0){return e[n]=this._x,e[n+1]=this._y,e[n+2]=this._z,e[n+3]=this._w,e}fromBufferAttribute(e,n){return this._x=e.getX(n),this._y=e.getY(n),this._z=e.getZ(n),this._w=e.getW(n),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class jt{constructor(e=0,n=0,o=0){jt.prototype.isVector3=!0,this.x=e,this.y=n,this.z=o}set(e,n,o){return o===void 0&&(o=this.z),this.x=e,this.y=n,this.z=o,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,n){return this.x=e.x*n.x,this.y=e.y*n.y,this.z=e.z*n.z,this}applyEuler(e){return this.applyQuaternion(QVt.setFromEuler(e))}applyAxisAngle(e,n){return this.applyQuaternion(QVt.setFromAxisAngle(e,n))}applyMatrix3(e){const n=this.x,o=this.y,i=this.z,r=e.elements;return this.x=r[0]*n+r[3]*o+r[6]*i,this.y=r[1]*n+r[4]*o+r[7]*i,this.z=r[2]*n+r[5]*o+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const n=this.x,o=this.y,i=this.z,r=e.elements,s=1/(r[3]*n+r[7]*o+r[11]*i+r[15]);return this.x=(r[0]*n+r[4]*o+r[8]*i+r[12])*s,this.y=(r[1]*n+r[5]*o+r[9]*i+r[13])*s,this.z=(r[2]*n+r[6]*o+r[10]*i+r[14])*s,this}applyQuaternion(e){const n=this.x,o=this.y,i=this.z,r=e.x,s=e.y,a=e.z,A=e.w,c=2*(s*i-a*o),l=2*(a*n-r*i),u=2*(r*o-s*n);return this.x=n+A*c+s*u-a*l,this.y=o+A*l+a*c-r*u,this.z=i+A*u+r*l-s*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const n=this.x,o=this.y,i=this.z,r=e.elements;return this.x=r[0]*n+r[4]*o+r[8]*i,this.y=r[1]*n+r[5]*o+r[9]*i,this.z=r[2]*n+r[6]*o+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this.z=Math.max(e.z,Math.min(n.z,this.z)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this.z=Math.max(e,Math.min(n,this.z)),this}clampLength(e,n){const o=this.length();return this.divideScalar(o||1).multiplyScalar(Math.max(e,Math.min(n,o)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this}lerpVectors(e,n,o){return this.x=e.x+(n.x-e.x)*o,this.y=e.y+(n.y-e.y)*o,this.z=e.z+(n.z-e.z)*o,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,n){const o=e.x,i=e.y,r=e.z,s=n.x,a=n.y,A=n.z;return this.x=i*A-r*a,this.y=r*s-o*A,this.z=o*a-i*s,this}projectOnVector(e){const n=e.lengthSq();if(n===0)return this.set(0,0,0);const o=e.dot(this)/n;return this.copy(e).multiplyScalar(o)}projectOnPlane(e){return cTe.copy(this).projectOnVector(e),this.sub(cTe)}reflect(e){return this.sub(cTe.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const o=this.dot(e)/n;return Math.acos(rf(o,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,o=this.y-e.y,i=this.z-e.z;return n*n+o*o+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,n,o){const i=Math.sin(n)*e;return this.x=i*Math.sin(o),this.y=Math.cos(n)*e,this.z=i*Math.cos(o),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,n,o){return this.x=e*Math.sin(n),this.y=o,this.z=e*Math.cos(n),this}setFromMatrixPosition(e){const n=e.elements;return this.x=n[12],this.y=n[13],this.z=n[14],this}setFromMatrixScale(e){const n=this.setFromMatrixColumn(e,0).length(),o=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=n,this.y=o,this.z=i,this}setFromMatrixColumn(e,n){return this.fromArray(e.elements,n*4)}setFromMatrix3Column(e,n){return this.fromArray(e.elements,n*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,n=Math.random()*2-1,o=Math.sqrt(1-n*n);return this.x=o*Math.cos(e),this.y=n,this.z=o*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const cTe=new jt,QVt=new Zy;class e2{constructor(e=new jt(1/0,1/0,1/0),n=new jt(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=n}set(e,n){return this.min.copy(e),this.max.copy(n),this}setFromArray(e){this.makeEmpty();for(let n=0,o=e.length;n<o;n+=3)this.expandByPoint(OB.fromArray(e,n));return this}setFromBufferAttribute(e){this.makeEmpty();for(let n=0,o=e.count;n<o;n++)this.expandByPoint(OB.fromBufferAttribute(e,n));return this}setFromPoints(e){this.makeEmpty();for(let n=0,o=e.length;n<o;n++)this.expandByPoint(e[n]);return this}setFromCenterAndSize(e,n){const o=OB.copy(n).multiplyScalar(.5);return this.min.copy(e).sub(o),this.max.copy(e).add(o),this}setFromObject(e,n=!1){return this.makeEmpty(),this.expandByObject(e,n)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,n=!1){e.updateWorldMatrix(!1,!1);const o=e.geometry;if(o!==void 0){const r=o.getAttribute("position");if(n===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let s=0,a=r.count;s<a;s++)e.isMesh===!0?e.getVertexPosition(s,OB):OB.fromBufferAttribute(r,s),OB.applyMatrix4(e.matrixWorld),this.expandByPoint(OB);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),vde.copy(e.boundingBox)):(o.boundingBox===null&&o.computeBoundingBox(),vde.copy(o.boundingBox)),vde.applyMatrix4(e.matrixWorld),this.union(vde)}const i=e.children;for(let r=0,s=i.length;r<s;r++)this.expandByObject(i[r],n);return this}containsPoint(e){return!(e.x<this.min.x||e.x>this.max.x||e.y<this.min.y||e.y>this.max.y||e.z<this.min.z||e.z>this.max.z)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,n){return n.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return!(e.max.x<this.min.x||e.min.x>this.max.x||e.max.y<this.min.y||e.min.y>this.max.y||e.max.z<this.min.z||e.min.z>this.max.z)}intersectsSphere(e){return this.clampPoint(e.center,OB),OB.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let n,o;return e.normal.x>0?(n=e.normal.x*this.min.x,o=e.normal.x*this.max.x):(n=e.normal.x*this.max.x,o=e.normal.x*this.min.x),e.normal.y>0?(n+=e.normal.y*this.min.y,o+=e.normal.y*this.max.y):(n+=e.normal.y*this.max.y,o+=e.normal.y*this.min.y),e.normal.z>0?(n+=e.normal.z*this.min.z,o+=e.normal.z*this.max.z):(n+=e.normal.z*this.max.z,o+=e.normal.z*this.min.z),n<=-e.constant&&o>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Hq),wde.subVectors(this.max,Hq),UG.subVectors(e.a,Hq),KG.subVectors(e.b,Hq),VG.subVectors(e.c,Hq),$w.subVectors(KG,UG),qw.subVectors(VG,KG),kR.subVectors(UG,VG);let n=[0,-$w.z,$w.y,0,-qw.z,qw.y,0,-kR.z,kR.y,$w.z,0,-$w.x,qw.z,0,-qw.x,kR.z,0,-kR.x,-$w.y,$w.x,0,-qw.y,qw.x,0,-kR.y,kR.x,0];return!lTe(n,UG,KG,VG,wde)||(n=[1,0,0,0,1,0,0,0,1],!lTe(n,UG,KG,VG,wde))?!1:(Pde.crossVectors($w,qw),n=[Pde.x,Pde.y,Pde.z],lTe(n,UG,KG,VG,wde))}clampPoint(e,n){return n.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,OB).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(OB).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Zb[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Zb[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Zb[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Zb[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Zb[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Zb[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Zb[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Zb[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Zb),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Zb=[new jt,new jt,new jt,new jt,new jt,new jt,new jt,new jt],OB=new jt,vde=new e2,UG=new jt,KG=new jt,VG=new jt,$w=new jt,qw=new jt,kR=new jt,Hq=new jt,wde=new jt,Pde=new jt,FR=new jt;function lTe(t,e,n,o,i){for(let r=0,s=t.length-3;r<=s;r+=3){FR.fromArray(t,r);const a=i.x*Math.abs(FR.x)+i.y*Math.abs(FR.y)+i.z*Math.abs(FR.z),A=e.dot(FR),c=n.dot(FR),l=o.dot(FR);if(Math.max(-Math.max(A,c,l),Math.min(A,c,l))>a)return!1}return!0}const P$o=new e2,Oq=new jt,uTe=new jt;let GB=class{constructor(e=new jt,n=-1){this.isSphere=!0,this.center=e,this.radius=n}set(e,n){return this.center.copy(e),this.radius=n,this}setFromPoints(e,n){const o=this.center;n!==void 0?o.copy(n):P$o.setFromPoints(e).getCenter(o);let i=0;for(let r=0,s=e.length;r<s;r++)i=Math.max(i,o.distanceToSquared(e[r]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const n=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=n*n}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,n){const o=this.center.distanceToSquared(e);return n.copy(e),o>this.radius*this.radius&&(n.sub(this.center).normalize(),n.multiplyScalar(this.radius).add(this.center)),n}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Oq.subVectors(e,this.center);const n=Oq.lengthSq();if(n>this.radius*this.radius){const o=Math.sqrt(n),i=(o-this.radius)*.5;this.center.addScaledVector(Oq,i/o),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(uTe.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Oq.copy(e.center).add(uTe)),this.expandByPoint(Oq.copy(e.center).sub(uTe))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}};const eS=new jt,gTe=new jt,Mde=new jt,Xw=new jt,dTe=new jt,Dde=new jt,hTe=new jt;let zG=class{constructor(e=new jt,n=new jt(0,0,-1)){this.origin=e,this.direction=n}set(e,n){return this.origin.copy(e),this.direction.copy(n),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,n){return n.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,eS)),this}closestPointToPoint(e,n){n.subVectors(e,this.origin);const o=n.dot(this.direction);return o<0?n.copy(this.origin):n.copy(this.origin).addScaledVector(this.direction,o)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const n=eS.subVectors(e,this.origin).dot(this.direction);return n<0?this.origin.distanceToSquared(e):(eS.copy(this.origin).addScaledVector(this.direction,n),eS.distanceToSquared(e))}distanceSqToSegment(e,n,o,i){gTe.copy(e).add(n).multiplyScalar(.5),Mde.copy(n).sub(e).normalize(),Xw.copy(this.origin).sub(gTe);const r=e.distanceTo(n)*.5,s=-this.direction.dot(Mde),a=Xw.dot(this.direction),A=-Xw.dot(Mde),c=Xw.lengthSq(),l=Math.abs(1-s*s);let u,g,h,d;if(l>0)if(u=s*A-a,g=s*a-A,d=r*l,u>=0)if(g>=-d)if(g<=d){const p=1/l;u*=p,g*=p,h=u*(u+s*g+2*a)+g*(s*u+g+2*A)+c}else g=r,u=Math.max(0,-(s*g+a)),h=-u*u+g*(g+2*A)+c;else g=-r,u=Math.max(0,-(s*g+a)),h=-u*u+g*(g+2*A)+c;else g<=-d?(u=Math.max(0,-(-s*r+a)),g=u>0?-r:Math.min(Math.max(-r,-A),r),h=-u*u+g*(g+2*A)+c):g<=d?(u=0,g=Math.min(Math.max(-r,-A),r),h=g*(g+2*A)+c):(u=Math.max(0,-(s*r+a)),g=u>0?r:Math.min(Math.max(-r,-A),r),h=-u*u+g*(g+2*A)+c);else g=s>0?-r:r,u=Math.max(0,-(s*g+a)),h=-u*u+g*(g+2*A)+c;return o&&o.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(gTe).addScaledVector(Mde,g),h}intersectSphere(e,n){eS.subVectors(e.center,this.origin);const o=eS.dot(this.direction),i=eS.dot(eS)-o*o,r=e.radius*e.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=o-s,A=o+s;return A<0?null:a<0?this.at(A,n):this.at(a,n)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const n=e.normal.dot(this.direction);if(n===0)return e.distanceToPoint(this.origin)===0?0:null;const o=-(this.origin.dot(e.normal)+e.constant)/n;return o>=0?o:null}intersectPlane(e,n){const o=this.distanceToPlane(e);return o===null?null:this.at(o,n)}intersectsPlane(e){const n=e.distanceToPoint(this.origin);return n===0||e.normal.dot(this.direction)*n<0}intersectBox(e,n){let o,i,r,s,a,A;const c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,g=this.origin;return c>=0?(o=(e.min.x-g.x)*c,i=(e.max.x-g.x)*c):(o=(e.max.x-g.x)*c,i=(e.min.x-g.x)*c),l>=0?(r=(e.min.y-g.y)*l,s=(e.max.y-g.y)*l):(r=(e.max.y-g.y)*l,s=(e.min.y-g.y)*l),o>s||r>i||((r>o||isNaN(o))&&(o=r),(s<i||isNaN(i))&&(i=s),u>=0?(a=(e.min.z-g.z)*u,A=(e.max.z-g.z)*u):(a=(e.max.z-g.z)*u,A=(e.min.z-g.z)*u),o>A||a>i)||((a>o||o!==o)&&(o=a),(A<i||i!==i)&&(i=A),i<0)?null:this.at(o>=0?o:i,n)}intersectsBox(e){return this.intersectBox(e,eS)!==null}intersectTriangle(e,n,o,i,r){dTe.subVectors(n,e),Dde.subVectors(o,e),hTe.crossVectors(dTe,Dde);let s=this.direction.dot(hTe),a;if(s>0){if(i)return null;a=1}else if(s<0)a=-1,s=-s;else return null;Xw.subVectors(this.origin,e);const A=a*this.direction.dot(Dde.crossVectors(Xw,Dde));if(A<0)return null;const c=a*this.direction.dot(dTe.cross(Xw));if(c<0||A+c>s)return null;const l=-a*Xw.dot(hTe);return l<0?null:this.at(l/s,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}};class va{constructor(e,n,o,i,r,s,a,A,c,l,u,g,h,d,p,m){va.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,n,o,i,r,s,a,A,c,l,u,g,h,d,p,m)}set(e,n,o,i,r,s,a,A,c,l,u,g,h,d,p,m){const _=this.elements;return _[0]=e,_[4]=n,_[8]=o,_[12]=i,_[1]=r,_[5]=s,_[9]=a,_[13]=A,_[2]=c,_[6]=l,_[10]=u,_[14]=g,_[3]=h,_[7]=d,_[11]=p,_[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new va().fromArray(this.elements)}copy(e){const n=this.elements,o=e.elements;return n[0]=o[0],n[1]=o[1],n[2]=o[2],n[3]=o[3],n[4]=o[4],n[5]=o[5],n[6]=o[6],n[7]=o[7],n[8]=o[8],n[9]=o[9],n[10]=o[10],n[11]=o[11],n[12]=o[12],n[13]=o[13],n[14]=o[14],n[15]=o[15],this}copyPosition(e){const n=this.elements,o=e.elements;return n[12]=o[12],n[13]=o[13],n[14]=o[14],this}setFromMatrix3(e){const n=e.elements;return this.set(n[0],n[3],n[6],0,n[1],n[4],n[7],0,n[2],n[5],n[8],0,0,0,0,1),this}extractBasis(e,n,o){return e.setFromMatrixColumn(this,0),n.setFromMatrixColumn(this,1),o.setFromMatrixColumn(this,2),this}makeBasis(e,n,o){return this.set(e.x,n.x,o.x,0,e.y,n.y,o.y,0,e.z,n.z,o.z,0,0,0,0,1),this}extractRotation(e){const n=this.elements,o=e.elements,i=1/JG.setFromMatrixColumn(e,0).length(),r=1/JG.setFromMatrixColumn(e,1).length(),s=1/JG.setFromMatrixColumn(e,2).length();return n[0]=o[0]*i,n[1]=o[1]*i,n[2]=o[2]*i,n[3]=0,n[4]=o[4]*r,n[5]=o[5]*r,n[6]=o[6]*r,n[7]=0,n[8]=o[8]*s,n[9]=o[9]*s,n[10]=o[10]*s,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromEuler(e){const n=this.elements,o=e.x,i=e.y,r=e.z,s=Math.cos(o),a=Math.sin(o),A=Math.cos(i),c=Math.sin(i),l=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){const g=s*l,h=s*u,d=a*l,p=a*u;n[0]=A*l,n[4]=-A*u,n[8]=c,n[1]=h+d*c,n[5]=g-p*c,n[9]=-a*A,n[2]=p-g*c,n[6]=d+h*c,n[10]=s*A}else if(e.order==="YXZ"){const g=A*l,h=A*u,d=c*l,p=c*u;n[0]=g+p*a,n[4]=d*a-h,n[8]=s*c,n[1]=s*u,n[5]=s*l,n[9]=-a,n[2]=h*a-d,n[6]=p+g*a,n[10]=s*A}else if(e.order==="ZXY"){const g=A*l,h=A*u,d=c*l,p=c*u;n[0]=g-p*a,n[4]=-s*u,n[8]=d+h*a,n[1]=h+d*a,n[5]=s*l,n[9]=p-g*a,n[2]=-s*c,n[6]=a,n[10]=s*A}else if(e.order==="ZYX"){const g=s*l,h=s*u,d=a*l,p=a*u;n[0]=A*l,n[4]=d*c-h,n[8]=g*c+p,n[1]=A*u,n[5]=p*c+g,n[9]=h*c-d,n[2]=-c,n[6]=a*A,n[10]=s*A}else if(e.order==="YZX"){const g=s*A,h=s*c,d=a*A,p=a*c;n[0]=A*l,n[4]=p-g*u,n[8]=d*u+h,n[1]=u,n[5]=s*l,n[9]=-a*l,n[2]=-c*l,n[6]=h*u+d,n[10]=g-p*u}else if(e.order==="XZY"){const g=s*A,h=s*c,d=a*A,p=a*c;n[0]=A*l,n[4]=-u,n[8]=c*l,n[1]=g*u+p,n[5]=s*l,n[9]=h*u-d,n[2]=d*u-h,n[6]=a*l,n[10]=p*u+g}return n[3]=0,n[7]=0,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromQuaternion(e){return this.compose(M$o,e,D$o)}lookAt(e,n,o){const i=this.elements;return _E.subVectors(e,n),_E.lengthSq()===0&&(_E.z=1),_E.normalize(),Zw.crossVectors(o,_E),Zw.lengthSq()===0&&(Math.abs(o.z)===1?_E.x+=1e-4:_E.z+=1e-4,_E.normalize(),Zw.crossVectors(o,_E)),Zw.normalize(),Nde.crossVectors(_E,Zw),i[0]=Zw.x,i[4]=Nde.x,i[8]=_E.x,i[1]=Zw.y,i[5]=Nde.y,i[9]=_E.y,i[2]=Zw.z,i[6]=Nde.z,i[10]=_E.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const o=e.elements,i=n.elements,r=this.elements,s=o[0],a=o[4],A=o[8],c=o[12],l=o[1],u=o[5],g=o[9],h=o[13],d=o[2],p=o[6],m=o[10],_=o[14],f=o[3],I=o[7],C=o[11],y=o[15],x=i[0],E=i[4],B=i[8],S=i[12],Q=i[1],w=i[5],M=i[9],k=i[13],R=i[2],F=i[6],O=i[10],U=i[14],Y=i[3],W=i[7],te=i[11],j=i[15];return r[0]=s*x+a*Q+A*R+c*Y,r[4]=s*E+a*w+A*F+c*W,r[8]=s*B+a*M+A*O+c*te,r[12]=s*S+a*k+A*U+c*j,r[1]=l*x+u*Q+g*R+h*Y,r[5]=l*E+u*w+g*F+h*W,r[9]=l*B+u*M+g*O+h*te,r[13]=l*S+u*k+g*U+h*j,r[2]=d*x+p*Q+m*R+_*Y,r[6]=d*E+p*w+m*F+_*W,r[10]=d*B+p*M+m*O+_*te,r[14]=d*S+p*k+m*U+_*j,r[3]=f*x+I*Q+C*R+y*Y,r[7]=f*E+I*w+C*F+y*W,r[11]=f*B+I*M+C*O+y*te,r[15]=f*S+I*k+C*U+y*j,this}multiplyScalar(e){const n=this.elements;return n[0]*=e,n[4]*=e,n[8]*=e,n[12]*=e,n[1]*=e,n[5]*=e,n[9]*=e,n[13]*=e,n[2]*=e,n[6]*=e,n[10]*=e,n[14]*=e,n[3]*=e,n[7]*=e,n[11]*=e,n[15]*=e,this}determinant(){const e=this.elements,n=e[0],o=e[4],i=e[8],r=e[12],s=e[1],a=e[5],A=e[9],c=e[13],l=e[2],u=e[6],g=e[10],h=e[14],d=e[3],p=e[7],m=e[11],_=e[15];return d*(+r*A*u-i*c*u-r*a*g+o*c*g+i*a*h-o*A*h)+p*(+n*A*h-n*c*g+r*s*g-i*s*h+i*c*l-r*A*l)+m*(+n*c*u-n*a*h-r*s*u+o*s*h+r*a*l-o*c*l)+_*(-i*a*l-n*A*u+n*a*g+i*s*u-o*s*g+o*A*l)}transpose(){const e=this.elements;let n;return n=e[1],e[1]=e[4],e[4]=n,n=e[2],e[2]=e[8],e[8]=n,n=e[6],e[6]=e[9],e[9]=n,n=e[3],e[3]=e[12],e[12]=n,n=e[7],e[7]=e[13],e[13]=n,n=e[11],e[11]=e[14],e[14]=n,this}setPosition(e,n,o){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=n,i[14]=o),this}invert(){const e=this.elements,n=e[0],o=e[1],i=e[2],r=e[3],s=e[4],a=e[5],A=e[6],c=e[7],l=e[8],u=e[9],g=e[10],h=e[11],d=e[12],p=e[13],m=e[14],_=e[15],f=u*m*c-p*g*c+p*A*h-a*m*h-u*A*_+a*g*_,I=d*g*c-l*m*c-d*A*h+s*m*h+l*A*_-s*g*_,C=l*p*c-d*u*c+d*a*h-s*p*h-l*a*_+s*u*_,y=d*u*A-l*p*A-d*a*g+s*p*g+l*a*m-s*u*m,x=n*f+o*I+i*C+r*y;if(x===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const E=1/x;return e[0]=f*E,e[1]=(p*g*r-u*m*r-p*i*h+o*m*h+u*i*_-o*g*_)*E,e[2]=(a*m*r-p*A*r+p*i*c-o*m*c-a*i*_+o*A*_)*E,e[3]=(u*A*r-a*g*r-u*i*c+o*g*c+a*i*h-o*A*h)*E,e[4]=I*E,e[5]=(l*m*r-d*g*r+d*i*h-n*m*h-l*i*_+n*g*_)*E,e[6]=(d*A*r-s*m*r-d*i*c+n*m*c+s*i*_-n*A*_)*E,e[7]=(s*g*r-l*A*r+l*i*c-n*g*c-s*i*h+n*A*h)*E,e[8]=C*E,e[9]=(d*u*r-l*p*r-d*o*h+n*p*h+l*o*_-n*u*_)*E,e[10]=(s*p*r-d*a*r+d*o*c-n*p*c-s*o*_+n*a*_)*E,e[11]=(l*a*r-s*u*r-l*o*c+n*u*c+s*o*h-n*a*h)*E,e[12]=y*E,e[13]=(l*p*i-d*u*i+d*o*g-n*p*g-l*o*m+n*u*m)*E,e[14]=(d*a*i-s*p*i-d*o*A+n*p*A+s*o*m-n*a*m)*E,e[15]=(s*u*i-l*a*i+l*o*A-n*u*A-s*o*g+n*a*g)*E,this}scale(e){const n=this.elements,o=e.x,i=e.y,r=e.z;return n[0]*=o,n[4]*=i,n[8]*=r,n[1]*=o,n[5]*=i,n[9]*=r,n[2]*=o,n[6]*=i,n[10]*=r,n[3]*=o,n[7]*=i,n[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,n=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],o=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(n,o,i))}makeTranslation(e,n,o){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,n,0,0,1,o,0,0,0,1),this}makeRotationX(e){const n=Math.cos(e),o=Math.sin(e);return this.set(1,0,0,0,0,n,-o,0,0,o,n,0,0,0,0,1),this}makeRotationY(e){const n=Math.cos(e),o=Math.sin(e);return this.set(n,0,o,0,0,1,0,0,-o,0,n,0,0,0,0,1),this}makeRotationZ(e){const n=Math.cos(e),o=Math.sin(e);return this.set(n,-o,0,0,o,n,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,n){const o=Math.cos(n),i=Math.sin(n),r=1-o,s=e.x,a=e.y,A=e.z,c=r*s,l=r*a;return this.set(c*s+o,c*a-i*A,c*A+i*a,0,c*a+i*A,l*a+o,l*A-i*s,0,c*A-i*a,l*A+i*s,r*A*A+o,0,0,0,0,1),this}makeScale(e,n,o){return this.set(e,0,0,0,0,n,0,0,0,0,o,0,0,0,0,1),this}makeShear(e,n,o,i,r,s){return this.set(1,o,r,0,e,1,s,0,n,i,1,0,0,0,0,1),this}compose(e,n,o){const i=this.elements,r=n._x,s=n._y,a=n._z,A=n._w,c=r+r,l=s+s,u=a+a,g=r*c,h=r*l,d=r*u,p=s*l,m=s*u,_=a*u,f=A*c,I=A*l,C=A*u,y=o.x,x=o.y,E=o.z;return i[0]=(1-(p+_))*y,i[1]=(h+C)*y,i[2]=(d-I)*y,i[3]=0,i[4]=(h-C)*x,i[5]=(1-(g+_))*x,i[6]=(m+f)*x,i[7]=0,i[8]=(d+I)*E,i[9]=(m-f)*E,i[10]=(1-(g+p))*E,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,n,o){const i=this.elements;let r=JG.set(i[0],i[1],i[2]).length();const s=JG.set(i[4],i[5],i[6]).length(),a=JG.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],YB.copy(this);const c=1/r,l=1/s,u=1/a;return YB.elements[0]*=c,YB.elements[1]*=c,YB.elements[2]*=c,YB.elements[4]*=l,YB.elements[5]*=l,YB.elements[6]*=l,YB.elements[8]*=u,YB.elements[9]*=u,YB.elements[10]*=u,n.setFromRotationMatrix(YB),o.x=r,o.y=s,o.z=a,this}makePerspective(e,n,o,i,r,s,a=Xb){const A=this.elements,c=2*r/(n-e),l=2*r/(o-i),u=(n+e)/(n-e),g=(o+i)/(o-i);let h,d;if(a===Xb)h=-(s+r)/(s-r),d=-2*s*r/(s-r);else if(a===Sde)h=-s/(s-r),d=-s*r/(s-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return A[0]=c,A[4]=0,A[8]=u,A[12]=0,A[1]=0,A[5]=l,A[9]=g,A[13]=0,A[2]=0,A[6]=0,A[10]=h,A[14]=d,A[3]=0,A[7]=0,A[11]=-1,A[15]=0,this}makeOrthographic(e,n,o,i,r,s,a=Xb){const A=this.elements,c=1/(n-e),l=1/(o-i),u=1/(s-r),g=(n+e)*c,h=(o+i)*l;let d,p;if(a===Xb)d=(s+r)*u,p=-2*u;else if(a===Sde)d=r*u,p=-1*u;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return A[0]=2*c,A[4]=0,A[8]=0,A[12]=-g,A[1]=0,A[5]=2*l,A[9]=0,A[13]=-h,A[2]=0,A[6]=0,A[10]=p,A[14]=-d,A[3]=0,A[7]=0,A[11]=0,A[15]=1,this}equals(e){const n=this.elements,o=e.elements;for(let i=0;i<16;i++)if(n[i]!==o[i])return!1;return!0}fromArray(e,n=0){for(let o=0;o<16;o++)this.elements[o]=e[o+n];return this}toArray(e=[],n=0){const o=this.elements;return e[n]=o[0],e[n+1]=o[1],e[n+2]=o[2],e[n+3]=o[3],e[n+4]=o[4],e[n+5]=o[5],e[n+6]=o[6],e[n+7]=o[7],e[n+8]=o[8],e[n+9]=o[9],e[n+10]=o[10],e[n+11]=o[11],e[n+12]=o[12],e[n+13]=o[13],e[n+14]=o[14],e[n+15]=o[15],e}}const JG=new jt,YB=new va,M$o=new jt(0,0,0),D$o=new jt(1,1,1),Zw=new jt,Nde=new jt,_E=new jt,vVt=new va,wVt=new Zy;class t2{constructor(e=0,n=0,o=0,i=t2.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=n,this._z=o,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,n,o,i=this._order){return this._x=e,this._y=n,this._z=o,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,n=this._order,o=!0){const i=e.elements,r=i[0],s=i[4],a=i[8],A=i[1],c=i[5],l=i[9],u=i[2],g=i[6],h=i[10];switch(n){case"XYZ":this._y=Math.asin(rf(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-l,h),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(g,c),this._z=0);break;case"YXZ":this._x=Math.asin(-rf(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(a,h),this._z=Math.atan2(A,c)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(rf(g,-1,1)),Math.abs(g)<.9999999?(this._y=Math.atan2(-u,h),this._z=Math.atan2(-s,c)):(this._y=0,this._z=Math.atan2(A,r));break;case"ZYX":this._y=Math.asin(-rf(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(g,h),this._z=Math.atan2(A,r)):(this._x=0,this._z=Math.atan2(-s,c));break;case"YZX":this._z=Math.asin(rf(A,-1,1)),Math.abs(A)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(a,h));break;case"XZY":this._z=Math.asin(-rf(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(g,c),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-l,h),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+n)}return this._order=n,o===!0&&this._onChangeCallback(),this}setFromQuaternion(e,n,o){return vVt.makeRotationFromQuaternion(e),this.setFromRotationMatrix(vVt,n,o)}setFromVector3(e,n=this._order){return this.set(e.x,e.y,e.z,n)}reorder(e){return wVt.setFromEuler(this),this.setFromQuaternion(wVt,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],n=0){return e[n]=this._x,e[n+1]=this._y,e[n+2]=this._z,e[n+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}t2.DEFAULT_ORDER="XYZ";class pTe{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let N$o=0;const PVt=new jt,WG=new Zy,tS=new va,Rde=new jt,Gq=new jt,R$o=new jt,T$o=new Zy,MVt=new jt(1,0,0),DVt=new jt(0,1,0),NVt=new jt(0,0,1),RVt={type:"added"},k$o={type:"removed"},jG={type:"childadded",child:null},mTe={type:"childremoved",child:null};class T0 extends RR{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:N$o++}),this.uuid=u4(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=T0.DEFAULT_UP.clone();const e=new jt,n=new t2,o=new Zy,i=new jt(1,1,1);function r(){o.setFromEuler(n,!1)}function s(){n.setFromQuaternion(o,void 0,!1)}n._onChange(r),o._onChange(s),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:o},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new va},normalMatrix:{value:new HA}}),this.matrix=new va,this.matrixWorld=new va,this.matrixAutoUpdate=T0.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=T0.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new pTe,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,n){this.quaternion.setFromAxisAngle(e,n)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,n){return WG.setFromAxisAngle(e,n),this.quaternion.multiply(WG),this}rotateOnWorldAxis(e,n){return WG.setFromAxisAngle(e,n),this.quaternion.premultiply(WG),this}rotateX(e){return this.rotateOnAxis(MVt,e)}rotateY(e){return this.rotateOnAxis(DVt,e)}rotateZ(e){return this.rotateOnAxis(NVt,e)}translateOnAxis(e,n){return PVt.copy(e).applyQuaternion(this.quaternion),this.position.add(PVt.multiplyScalar(n)),this}translateX(e){return this.translateOnAxis(MVt,e)}translateY(e){return this.translateOnAxis(DVt,e)}translateZ(e){return this.translateOnAxis(NVt,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(tS.copy(this.matrixWorld).invert())}lookAt(e,n,o){e.isVector3?Rde.copy(e):Rde.set(e,n,o);const i=this.parent;this.updateWorldMatrix(!0,!1),Gq.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?tS.lookAt(Gq,Rde,this.up):tS.lookAt(Rde,Gq,this.up),this.quaternion.setFromRotationMatrix(tS),i&&(tS.extractRotation(i.matrixWorld),WG.setFromRotationMatrix(tS),this.quaternion.premultiply(WG.invert()))}add(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.add(arguments[n]);return this}return e===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(RVt),jG.child=e,this.dispatchEvent(jG),jG.child=null):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let o=0;o<arguments.length;o++)this.remove(arguments[o]);return this}const n=this.children.indexOf(e);return n!==-1&&(e.parent=null,this.children.splice(n,1),e.dispatchEvent(k$o),mTe.child=e,this.dispatchEvent(mTe),mTe.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),tS.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),tS.multiply(e.parent.matrixWorld)),e.applyMatrix4(tS),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(RVt),jG.child=e,this.dispatchEvent(jG),jG.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,n){if(this[e]===n)return this;for(let o=0,i=this.children.length;o<i;o++){const s=this.children[o].getObjectByProperty(e,n);if(s!==void 0)return s}}getObjectsByProperty(e,n,o=[]){this[e]===n&&o.push(this);const i=this.children;for(let r=0,s=i.length;r<s;r++)i[r].getObjectsByProperty(e,n,o);return o}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Gq,e,R$o),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Gq,T$o,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const n=this.matrixWorld.elements;return e.set(n[8],n[9],n[10]).normalize()}raycast(){}traverse(e){e(this);const n=this.children;for(let o=0,i=n.length;o<i;o++)n[o].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const n=this.children;for(let o=0,i=n.length;o<i;o++)n[o].traverseVisible(e)}traverseAncestors(e){const n=this.parent;n!==null&&(e(n),n.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,e=!0);const n=this.children;for(let o=0,i=n.length;o<i;o++){const r=n[o];(r.matrixWorldAutoUpdate===!0||e===!0)&&r.updateMatrixWorld(e)}}updateWorldMatrix(e,n){const o=this.parent;if(e===!0&&o!==null&&o.matrixWorldAutoUpdate===!0&&o.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),n===!0){const i=this.children;for(let r=0,s=i.length;r<s;r++){const a=i[r];a.matrixWorldAutoUpdate===!0&&a.updateWorldMatrix(!1,!0)}}}toJSON(e){const n=e===void 0||typeof e=="string",o={};n&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},o.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});const i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map(a=>({boxInitialized:a.boxInitialized,boxMin:a.box.min.toArray(),boxMax:a.box.max.toArray(),sphereInitialized:a.sphereInitialized,sphereRadius:a.sphere.radius,sphereCenter:a.sphere.center.toArray()})),i.maxGeometryCount=this._maxGeometryCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),this.boundingBox!==null&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()}));function r(a,A){return a[A.uuid]===void 0&&(a[A.uuid]=A.toJSON(e)),A.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const A=a.shapes;if(Array.isArray(A))for(let c=0,l=A.length;c<l;c++){const u=A[c];r(e.shapes,u)}else r(e.shapes,A)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const a=[];for(let A=0,c=this.material.length;A<c;A++)a.push(r(e.materials,this.material[A]));i.material=a}else i.material=r(e.materials,this.material);if(this.children.length>0){i.children=[];for(let a=0;a<this.children.length;a++)i.children.push(this.children[a].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let a=0;a<this.animations.length;a++){const A=this.animations[a];i.animations.push(r(e.animations,A))}}if(n){const a=s(e.geometries),A=s(e.materials),c=s(e.textures),l=s(e.images),u=s(e.shapes),g=s(e.skeletons),h=s(e.animations),d=s(e.nodes);a.length>0&&(o.geometries=a),A.length>0&&(o.materials=A),c.length>0&&(o.textures=c),l.length>0&&(o.images=l),u.length>0&&(o.shapes=u),g.length>0&&(o.skeletons=g),h.length>0&&(o.animations=h),d.length>0&&(o.nodes=d)}return o.object=i,o;function s(a){const A=[];for(const c in a){const l=a[c];delete l.metadata,A.push(l)}return A}}clone(e){return new this.constructor().copy(this,e)}copy(e,n=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),n===!0)for(let o=0;o<e.children.length;o++){const i=e.children[o];this.add(i.clone())}return this}}T0.DEFAULT_UP=new jt(0,1,0),T0.DEFAULT_MATRIX_AUTO_UPDATE=!0,T0.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const UB=new jt,nS=new jt,_Te=new jt,oS=new jt,$G=new jt,qG=new jt,TVt=new jt,fTe=new jt,ITe=new jt,CTe=new jt;class KB{constructor(e=new jt,n=new jt,o=new jt){this.a=e,this.b=n,this.c=o}static getNormal(e,n,o,i){i.subVectors(o,n),UB.subVectors(e,n),i.cross(UB);const r=i.lengthSq();return r>0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,n,o,i,r){UB.subVectors(i,n),nS.subVectors(o,n),_Te.subVectors(e,n);const s=UB.dot(UB),a=UB.dot(nS),A=UB.dot(_Te),c=nS.dot(nS),l=nS.dot(_Te),u=s*c-a*a;if(u===0)return r.set(0,0,0),null;const g=1/u,h=(c*A-a*l)*g,d=(s*l-a*A)*g;return r.set(1-h-d,d,h)}static containsPoint(e,n,o,i){return this.getBarycoord(e,n,o,i,oS)===null?!1:oS.x>=0&&oS.y>=0&&oS.x+oS.y<=1}static getInterpolation(e,n,o,i,r,s,a,A){return this.getBarycoord(e,n,o,i,oS)===null?(A.x=0,A.y=0,"z"in A&&(A.z=0),"w"in A&&(A.w=0),null):(A.setScalar(0),A.addScaledVector(r,oS.x),A.addScaledVector(s,oS.y),A.addScaledVector(a,oS.z),A)}static isFrontFacing(e,n,o,i){return UB.subVectors(o,n),nS.subVectors(e,n),UB.cross(nS).dot(i)<0}set(e,n,o){return this.a.copy(e),this.b.copy(n),this.c.copy(o),this}setFromPointsAndIndices(e,n,o,i){return this.a.copy(e[n]),this.b.copy(e[o]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,n,o,i){return this.a.fromBufferAttribute(e,n),this.b.fromBufferAttribute(e,o),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return UB.subVectors(this.c,this.b),nS.subVectors(this.a,this.b),UB.cross(nS).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return KB.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,n){return KB.getBarycoord(e,this.a,this.b,this.c,n)}getInterpolation(e,n,o,i,r){return KB.getInterpolation(e,this.a,this.b,this.c,n,o,i,r)}containsPoint(e){return KB.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return KB.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,n){const o=this.a,i=this.b,r=this.c;let s,a;$G.subVectors(i,o),qG.subVectors(r,o),fTe.subVectors(e,o);const A=$G.dot(fTe),c=qG.dot(fTe);if(A<=0&&c<=0)return n.copy(o);ITe.subVectors(e,i);const l=$G.dot(ITe),u=qG.dot(ITe);if(l>=0&&u<=l)return n.copy(i);const g=A*u-l*c;if(g<=0&&A>=0&&l<=0)return s=A/(A-l),n.copy(o).addScaledVector($G,s);CTe.subVectors(e,r);const h=$G.dot(CTe),d=qG.dot(CTe);if(d>=0&&h<=d)return n.copy(r);const p=h*c-A*d;if(p<=0&&c>=0&&d<=0)return a=c/(c-d),n.copy(o).addScaledVector(qG,a);const m=l*d-h*u;if(m<=0&&u-l>=0&&h-d>=0)return TVt.subVectors(r,i),a=(u-l)/(u-l+(h-d)),n.copy(i).addScaledVector(TVt,a);const _=1/(m+p+g);return s=p*_,a=g*_,n.copy(o).addScaledVector($G,s).addScaledVector(qG,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const kVt={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},eP={h:0,s:0,l:0},Tde={h:0,s:0,l:0};function yTe(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*6*(2/3-n):t}class Vi{constructor(e,n,o){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,n,o)}set(e,n,o){if(n===void 0&&o===void 0){const i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,n,o);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,n=Ox){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,iu.toWorkingColorSpace(this,n),this}setRGB(e,n,o,i=iu.workingColorSpace){return this.r=e,this.g=n,this.b=o,iu.toWorkingColorSpace(this,i),this}setHSL(e,n,o,i=iu.workingColorSpace){if(e=iTe(e,1),n=rf(n,0,1),o=rf(o,0,1),n===0)this.r=this.g=this.b=o;else{const r=o<=.5?o*(1+n):o+n-o*n,s=2*o-r;this.r=yTe(s,r,e+1/3),this.g=yTe(s,r,e),this.b=yTe(s,r,e-1/3)}return iu.toWorkingColorSpace(this,i),this}setStyle(e,n=Ox){function o(r){r!==void 0&&parseFloat(r)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return o(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,n);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return o(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,n);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return o(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,n);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=i[1],s=r.length;if(s===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,n);if(s===6)return this.setHex(parseInt(r,16),n);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,n);return this}setColorName(e,n=Ox){const o=kVt[e.toLowerCase()];return o!==void 0?this.setHex(o,n):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=GG(e.r),this.g=GG(e.g),this.b=GG(e.b),this}copyLinearToSRGB(e){return this.r=aTe(e.r),this.g=aTe(e.g),this.b=aTe(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Ox){return iu.fromWorkingColorSpace(MC.copy(this),e),Math.round(rf(MC.r*255,0,255))*65536+Math.round(rf(MC.g*255,0,255))*256+Math.round(rf(MC.b*255,0,255))}getHexString(e=Ox){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,n=iu.workingColorSpace){iu.fromWorkingColorSpace(MC.copy(this),n);const o=MC.r,i=MC.g,r=MC.b,s=Math.max(o,i,r),a=Math.min(o,i,r);let A,c;const l=(a+s)/2;if(a===s)A=0,c=0;else{const u=s-a;switch(c=l<=.5?u/(s+a):u/(2-s-a),s){case o:A=(i-r)/u+(i<r?6:0);break;case i:A=(r-o)/u+2;break;case r:A=(o-i)/u+4;break}A/=6}return e.h=A,e.s=c,e.l=l,e}getRGB(e,n=iu.workingColorSpace){return iu.fromWorkingColorSpace(MC.copy(this),n),e.r=MC.r,e.g=MC.g,e.b=MC.b,e}getStyle(e=Ox){iu.fromWorkingColorSpace(MC.copy(this),e);const n=MC.r,o=MC.g,i=MC.b;return e!==Ox?`color(${e} ${n.toFixed(3)} ${o.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(n*255)},${Math.round(o*255)},${Math.round(i*255)})`}offsetHSL(e,n,o){return this.getHSL(eP),this.setHSL(eP.h+e,eP.s+n,eP.l+o)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,n){return this.r=e.r+n.r,this.g=e.g+n.g,this.b=e.b+n.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,n){return this.r+=(e.r-this.r)*n,this.g+=(e.g-this.g)*n,this.b+=(e.b-this.b)*n,this}lerpColors(e,n,o){return this.r=e.r+(n.r-e.r)*o,this.g=e.g+(n.g-e.g)*o,this.b=e.b+(n.b-e.b)*o,this}lerpHSL(e,n){this.getHSL(eP),e.getHSL(Tde);const o=Fq(eP.h,Tde.h,n),i=Fq(eP.s,Tde.s,n),r=Fq(eP.l,Tde.l,n);return this.setHSL(o,i,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const n=this.r,o=this.g,i=this.b,r=e.elements;return this.r=r[0]*n+r[3]*o+r[6]*i,this.g=r[1]*n+r[4]*o+r[7]*i,this.b=r[2]*n+r[5]*o+r[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,n=0){return this.r=e[n],this.g=e[n+1],this.b=e[n+2],this}toArray(e=[],n=0){return e[n]=this.r,e[n+1]=this.g,e[n+2]=this.b,e}fromBufferAttribute(e,n){return this.r=e.getX(n),this.g=e.getY(n),this.b=e.getZ(n),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const MC=new Vi;Vi.NAMES=kVt;let F$o=0;class Gx extends RR{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:F$o++}),this.uuid=u4(),this.name="",this.type="Material",this.blending=QG,this.side=mE,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=URe,this.blendDst=KRe,this.blendEquation=NR,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Vi(0,0,0),this.blendAlpha=0,this.depthFunc=_de,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=_Vt,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=FG,this.stencilZFail=FG,this.stencilZPass=FG,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const n in e){const o=e[n];if(o===void 0){console.warn(`THREE.Material: parameter '${n}' has value of undefined.`);continue}const i=this[n];if(i===void 0){console.warn(`THREE.Material: '${n}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(o):i&&i.isVector3&&o&&o.isVector3?i.copy(o):this[n]=o}}toJSON(e){const n=e===void 0||typeof e=="string";n&&(e={textures:{},images:{}});const o={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};o.uuid=this.uuid,o.type=this.type,this.name!==""&&(o.name=this.name),this.color&&this.color.isColor&&(o.color=this.color.getHex()),this.roughness!==void 0&&(o.roughness=this.roughness),this.metalness!==void 0&&(o.metalness=this.metalness),this.sheen!==void 0&&(o.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(o.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(o.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(o.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(o.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(o.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(o.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(o.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(o.shininess=this.shininess),this.clearcoat!==void 0&&(o.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(o.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(o.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(o.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(o.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,o.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(o.dispersion=this.dispersion),this.iridescence!==void 0&&(o.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(o.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(o.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(o.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(o.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(o.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(o.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(o.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(o.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(o.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(o.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(o.lightMap=this.lightMap.toJSON(e).uuid,o.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(o.aoMap=this.aoMap.toJSON(e).uuid,o.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(o.bumpMap=this.bumpMap.toJSON(e).uuid,o.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(o.normalMap=this.normalMap.toJSON(e).uuid,o.normalMapType=this.normalMapType,o.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(o.displacementMap=this.displacementMap.toJSON(e).uuid,o.displacementScale=this.displacementScale,o.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(o.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(o.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(o.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(o.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(o.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(o.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(o.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(o.combine=this.combine)),this.envMapRotation!==void 0&&(o.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(o.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(o.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(o.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(o.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(o.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(o.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(o.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(o.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(o.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(o.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(o.size=this.size),this.shadowSide!==null&&(o.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(o.sizeAttenuation=this.sizeAttenuation),this.blending!==QG&&(o.blending=this.blending),this.side!==mE&&(o.side=this.side),this.vertexColors===!0&&(o.vertexColors=!0),this.opacity<1&&(o.opacity=this.opacity),this.transparent===!0&&(o.transparent=!0),this.blendSrc!==URe&&(o.blendSrc=this.blendSrc),this.blendDst!==KRe&&(o.blendDst=this.blendDst),this.blendEquation!==NR&&(o.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(o.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(o.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(o.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(o.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(o.blendAlpha=this.blendAlpha),this.depthFunc!==_de&&(o.depthFunc=this.depthFunc),this.depthTest===!1&&(o.depthTest=this.depthTest),this.depthWrite===!1&&(o.depthWrite=this.depthWrite),this.colorWrite===!1&&(o.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(o.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==_Vt&&(o.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(o.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(o.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==FG&&(o.stencilFail=this.stencilFail),this.stencilZFail!==FG&&(o.stencilZFail=this.stencilZFail),this.stencilZPass!==FG&&(o.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(o.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(o.rotation=this.rotation),this.polygonOffset===!0&&(o.polygonOffset=!0),this.polygonOffsetFactor!==0&&(o.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(o.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(o.linewidth=this.linewidth),this.dashSize!==void 0&&(o.dashSize=this.dashSize),this.gapSize!==void 0&&(o.gapSize=this.gapSize),this.scale!==void 0&&(o.scale=this.scale),this.dithering===!0&&(o.dithering=!0),this.alphaTest>0&&(o.alphaTest=this.alphaTest),this.alphaHash===!0&&(o.alphaHash=!0),this.alphaToCoverage===!0&&(o.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(o.premultipliedAlpha=!0),this.forceSinglePass===!0&&(o.forceSinglePass=!0),this.wireframe===!0&&(o.wireframe=!0),this.wireframeLinewidth>1&&(o.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(o.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(o.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(o.flatShading=!0),this.visible===!1&&(o.visible=!1),this.toneMapped===!1&&(o.toneMapped=!1),this.fog===!1&&(o.fog=!1),Object.keys(this.userData).length>0&&(o.userData=this.userData);function i(r){const s=[];for(const a in r){const A=r[a];delete A.metadata,s.push(A)}return s}if(n){const r=i(e.textures),s=i(e.images);r.length>0&&(o.textures=r),s.length>0&&(o.images=s)}return o}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const n=e.clippingPlanes;let o=null;if(n!==null){const i=n.length;o=new Array(i);for(let r=0;r!==i;++r)o[r]=n[r].clone()}return this.clippingPlanes=o,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class fE extends Gx{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Vi(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new t2,this.combine=VRe,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const s_=new jt,kde=new ni;class tg{constructor(e,n,o=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=n,this.count=e!==void 0?e.length/n:0,this.normalized=o,this.usage=oTe,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=m6,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return sTe("THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,n){this.updateRanges.push({start:e,count:n})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,n,o){e*=this.itemSize,o*=n.itemSize;for(let i=0,r=this.itemSize;i<r;i++)this.array[e+i]=n.array[o+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let n=0,o=this.count;n<o;n++)kde.fromBufferAttribute(this,n),kde.applyMatrix3(e),this.setXY(n,kde.x,kde.y);else if(this.itemSize===3)for(let n=0,o=this.count;n<o;n++)s_.fromBufferAttribute(this,n),s_.applyMatrix3(e),this.setXYZ(n,s_.x,s_.y,s_.z);return this}applyMatrix4(e){for(let n=0,o=this.count;n<o;n++)s_.fromBufferAttribute(this,n),s_.applyMatrix4(e),this.setXYZ(n,s_.x,s_.y,s_.z);return this}applyNormalMatrix(e){for(let n=0,o=this.count;n<o;n++)s_.fromBufferAttribute(this,n),s_.applyNormalMatrix(e),this.setXYZ(n,s_.x,s_.y,s_.z);return this}transformDirection(e){for(let n=0,o=this.count;n<o;n++)s_.fromBufferAttribute(this,n),s_.transformDirection(e),this.setXYZ(n,s_.x,s_.y,s_.z);return this}set(e,n=0){return this.array.set(e,n),this}getComponent(e,n){let o=this.array[e*this.itemSize+n];return this.normalized&&(o=HB(o,this.array)),o}setComponent(e,n,o){return this.normalized&&(o=ou(o,this.array)),this.array[e*this.itemSize+n]=o,this}getX(e){let n=this.array[e*this.itemSize];return this.normalized&&(n=HB(n,this.array)),n}setX(e,n){return this.normalized&&(n=ou(n,this.array)),this.array[e*this.itemSize]=n,this}getY(e){let n=this.array[e*this.itemSize+1];return this.normalized&&(n=HB(n,this.array)),n}setY(e,n){return this.normalized&&(n=ou(n,this.array)),this.array[e*this.itemSize+1]=n,this}getZ(e){let n=this.array[e*this.itemSize+2];return this.normalized&&(n=HB(n,this.array)),n}setZ(e,n){return this.normalized&&(n=ou(n,this.array)),this.array[e*this.itemSize+2]=n,this}getW(e){let n=this.array[e*this.itemSize+3];return this.normalized&&(n=HB(n,this.array)),n}setW(e,n){return this.normalized&&(n=ou(n,this.array)),this.array[e*this.itemSize+3]=n,this}setXY(e,n,o){return e*=this.itemSize,this.normalized&&(n=ou(n,this.array),o=ou(o,this.array)),this.array[e+0]=n,this.array[e+1]=o,this}setXYZ(e,n,o,i){return e*=this.itemSize,this.normalized&&(n=ou(n,this.array),o=ou(o,this.array),i=ou(i,this.array)),this.array[e+0]=n,this.array[e+1]=o,this.array[e+2]=i,this}setXYZW(e,n,o,i,r){return e*=this.itemSize,this.normalized&&(n=ou(n,this.array),o=ou(o,this.array),i=ou(i,this.array),r=ou(r,this.array)),this.array[e+0]=n,this.array[e+1]=o,this.array[e+2]=i,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==oTe&&(e.usage=this.usage),e}}class FVt extends tg{constructor(e,n,o){super(new Uint16Array(e),n,o)}}class xTe extends tg{constructor(e,n,o){super(new Uint32Array(e),n,o)}}class Bs extends tg{constructor(e,n,o){super(new Float32Array(e),n,o)}}let L$o=0;const g4=new va,ETe=new T0,XG=new jt,IE=new e2,Yq=new e2,r1=new jt;class Zl extends RR{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:L$o++}),this.uuid=u4(),this.name="",this.type="BufferGeometry",this.index=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(yVt(e)?xTe:FVt)(e,1):this.index=e,this}getAttribute(e){return this.attributes[e]}setAttribute(e,n){return this.attributes[e]=n,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,n,o=0){this.groups.push({start:e,count:n,materialIndex:o})}clearGroups(){this.groups=[]}setDrawRange(e,n){this.drawRange.start=e,this.drawRange.count=n}applyMatrix4(e){const n=this.attributes.position;n!==void 0&&(n.applyMatrix4(e),n.needsUpdate=!0);const o=this.attributes.normal;if(o!==void 0){const r=new HA().getNormalMatrix(e);o.applyNormalMatrix(r),o.needsUpdate=!0}const i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return g4.makeRotationFromQuaternion(e),this.applyMatrix4(g4),this}rotateX(e){return g4.makeRotationX(e),this.applyMatrix4(g4),this}rotateY(e){return g4.makeRotationY(e),this.applyMatrix4(g4),this}rotateZ(e){return g4.makeRotationZ(e),this.applyMatrix4(g4),this}translate(e,n,o){return g4.makeTranslation(e,n,o),this.applyMatrix4(g4),this}scale(e,n,o){return g4.makeScale(e,n,o),this.applyMatrix4(g4),this}lookAt(e){return ETe.lookAt(e),ETe.updateMatrix(),this.applyMatrix4(ETe.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(XG).negate(),this.translate(XG.x,XG.y,XG.z),this}setFromPoints(e){const n=[];for(let o=0,i=e.length;o<i;o++){const r=e[o];n.push(r.x,r.y,r.z||0)}return this.setAttribute("position",new Bs(n,3)),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new e2);const e=this.attributes.position,n=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new jt(-1/0,-1/0,-1/0),new jt(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),n)for(let o=0,i=n.length;o<i;o++){const r=n[o];IE.setFromBufferAttribute(r),this.morphTargetsRelative?(r1.addVectors(this.boundingBox.min,IE.min),this.boundingBox.expandByPoint(r1),r1.addVectors(this.boundingBox.max,IE.max),this.boundingBox.expandByPoint(r1)):(this.boundingBox.expandByPoint(IE.min),this.boundingBox.expandByPoint(IE.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new GB);const e=this.attributes.position,n=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new jt,1/0);return}if(e){const o=this.boundingSphere.center;if(IE.setFromBufferAttribute(e),n)for(let r=0,s=n.length;r<s;r++){const a=n[r];Yq.setFromBufferAttribute(a),this.morphTargetsRelative?(r1.addVectors(IE.min,Yq.min),IE.expandByPoint(r1),r1.addVectors(IE.max,Yq.max),IE.expandByPoint(r1)):(IE.expandByPoint(Yq.min),IE.expandByPoint(Yq.max))}IE.getCenter(o);let i=0;for(let r=0,s=e.count;r<s;r++)r1.fromBufferAttribute(e,r),i=Math.max(i,o.distanceToSquared(r1));if(n)for(let r=0,s=n.length;r<s;r++){const a=n[r],A=this.morphTargetsRelative;for(let c=0,l=a.count;c<l;c++)r1.fromBufferAttribute(a,c),A&&(XG.fromBufferAttribute(e,c),r1.add(XG)),i=Math.max(i,o.distanceToSquared(r1))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,n=this.attributes;if(e===null||n.position===void 0||n.normal===void 0||n.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const o=n.position,i=n.normal,r=n.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new tg(new Float32Array(4*o.count),4));const s=this.getAttribute("tangent"),a=[],A=[];for(let B=0;B<o.count;B++)a[B]=new jt,A[B]=new jt;const c=new jt,l=new jt,u=new jt,g=new ni,h=new ni,d=new ni,p=new jt,m=new jt;function _(B,S,Q){c.fromBufferAttribute(o,B),l.fromBufferAttribute(o,S),u.fromBufferAttribute(o,Q),g.fromBufferAttribute(r,B),h.fromBufferAttribute(r,S),d.fromBufferAttribute(r,Q),l.sub(c),u.sub(c),h.sub(g),d.sub(g);const w=1/(h.x*d.y-d.x*h.y);isFinite(w)&&(p.copy(l).multiplyScalar(d.y).addScaledVector(u,-h.y).multiplyScalar(w),m.copy(u).multiplyScalar(h.x).addScaledVector(l,-d.x).multiplyScalar(w),a[B].add(p),a[S].add(p),a[Q].add(p),A[B].add(m),A[S].add(m),A[Q].add(m))}let f=this.groups;f.length===0&&(f=[{start:0,count:e.count}]);for(let B=0,S=f.length;B<S;++B){const Q=f[B],w=Q.start,M=Q.count;for(let k=w,R=w+M;k<R;k+=3)_(e.getX(k+0),e.getX(k+1),e.getX(k+2))}const I=new jt,C=new jt,y=new jt,x=new jt;function E(B){y.fromBufferAttribute(i,B),x.copy(y);const S=a[B];I.copy(S),I.sub(y.multiplyScalar(y.dot(S))).normalize(),C.crossVectors(x,S);const w=C.dot(A[B])<0?-1:1;s.setXYZW(B,I.x,I.y,I.z,w)}for(let B=0,S=f.length;B<S;++B){const Q=f[B],w=Q.start,M=Q.count;for(let k=w,R=w+M;k<R;k+=3)E(e.getX(k+0)),E(e.getX(k+1)),E(e.getX(k+2))}}computeVertexNormals(){const e=this.index,n=this.getAttribute("position");if(n!==void 0){let o=this.getAttribute("normal");if(o===void 0)o=new tg(new Float32Array(n.count*3),3),this.setAttribute("normal",o);else for(let g=0,h=o.count;g<h;g++)o.setXYZ(g,0,0,0);const i=new jt,r=new jt,s=new jt,a=new jt,A=new jt,c=new jt,l=new jt,u=new jt;if(e)for(let g=0,h=e.count;g<h;g+=3){const d=e.getX(g+0),p=e.getX(g+1),m=e.getX(g+2);i.fromBufferAttribute(n,d),r.fromBufferAttribute(n,p),s.fromBufferAttribute(n,m),l.subVectors(s,r),u.subVectors(i,r),l.cross(u),a.fromBufferAttribute(o,d),A.fromBufferAttribute(o,p),c.fromBufferAttribute(o,m),a.add(l),A.add(l),c.add(l),o.setXYZ(d,a.x,a.y,a.z),o.setXYZ(p,A.x,A.y,A.z),o.setXYZ(m,c.x,c.y,c.z)}else for(let g=0,h=n.count;g<h;g+=3)i.fromBufferAttribute(n,g+0),r.fromBufferAttribute(n,g+1),s.fromBufferAttribute(n,g+2),l.subVectors(s,r),u.subVectors(i,r),l.cross(u),o.setXYZ(g+0,l.x,l.y,l.z),o.setXYZ(g+1,l.x,l.y,l.z),o.setXYZ(g+2,l.x,l.y,l.z);this.normalizeNormals(),o.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let n=0,o=e.count;n<o;n++)r1.fromBufferAttribute(e,n),r1.normalize(),e.setXYZ(n,r1.x,r1.y,r1.z)}toNonIndexed(){function e(a,A){const c=a.array,l=a.itemSize,u=a.normalized,g=new c.constructor(A.length*l);let h=0,d=0;for(let p=0,m=A.length;p<m;p++){a.isInterleavedBufferAttribute?h=A[p]*a.data.stride+a.offset:h=A[p]*l;for(let _=0;_<l;_++)g[d++]=c[h++]}return new tg(g,l,u)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const n=new Zl,o=this.index.array,i=this.attributes;for(const a in i){const A=i[a],c=e(A,o);n.setAttribute(a,c)}const r=this.morphAttributes;for(const a in r){const A=[],c=r[a];for(let l=0,u=c.length;l<u;l++){const g=c[l],h=e(g,o);A.push(h)}n.morphAttributes[a]=A}n.morphTargetsRelative=this.morphTargetsRelative;const s=this.groups;for(let a=0,A=s.length;a<A;a++){const c=s[a];n.addGroup(c.start,c.count,c.materialIndex)}return n}toJSON(){const e={metadata:{version:4.6,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const A=this.parameters;for(const c in A)A[c]!==void 0&&(e[c]=A[c]);return e}e.data={attributes:{}};const n=this.index;n!==null&&(e.data.index={type:n.array.constructor.name,array:Array.prototype.slice.call(n.array)});const o=this.attributes;for(const A in o){const c=o[A];e.data.attributes[A]=c.toJSON(e.data)}const i={};let r=!1;for(const A in this.morphAttributes){const c=this.morphAttributes[A],l=[];for(let u=0,g=c.length;u<g;u++){const h=c[u];l.push(h.toJSON(e.data))}l.length>0&&(i[A]=l,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return a!==null&&(e.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const n={};this.name=e.name;const o=e.index;o!==null&&this.setIndex(o.clone(n));const i=e.attributes;for(const c in i){const l=i[c];this.setAttribute(c,l.clone(n))}const r=e.morphAttributes;for(const c in r){const l=[],u=r[c];for(let g=0,h=u.length;g<h;g++)l.push(u[g].clone(n));this.morphAttributes[c]=l}this.morphTargetsRelative=e.morphTargetsRelative;const s=e.groups;for(let c=0,l=s.length;c<l;c++){const u=s[c];this.addGroup(u.start,u.count,u.materialIndex)}const a=e.boundingBox;a!==null&&(this.boundingBox=a.clone());const A=e.boundingSphere;return A!==null&&(this.boundingSphere=A.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const LVt=new va,LR=new zG,Fde=new GB,HVt=new jt,ZG=new jt,eY=new jt,tY=new jt,BTe=new jt,Lde=new jt,Hde=new ni,Ode=new ni,Gde=new ni,OVt=new jt,GVt=new jt,YVt=new jt,Yde=new jt,Ude=new jt;class Er extends T0{constructor(e=new Zl,n=new fE){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=n,this.updateMorphTargets()}copy(e,n){return super.copy(e,n),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const n=this.geometry.morphAttributes,o=Object.keys(n);if(o.length>0){const i=n[o[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,s=i.length;r<s;r++){const a=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}getVertexPosition(e,n){const o=this.geometry,i=o.attributes.position,r=o.morphAttributes.position,s=o.morphTargetsRelative;n.fromBufferAttribute(i,e);const a=this.morphTargetInfluences;if(r&&a){Lde.set(0,0,0);for(let A=0,c=r.length;A<c;A++){const l=a[A],u=r[A];l!==0&&(BTe.fromBufferAttribute(u,e),s?Lde.addScaledVector(BTe,l):Lde.addScaledVector(BTe.sub(n),l))}n.add(Lde)}return n}raycast(e,n){const o=this.geometry,i=this.material,r=this.matrixWorld;i!==void 0&&(o.boundingSphere===null&&o.computeBoundingSphere(),Fde.copy(o.boundingSphere),Fde.applyMatrix4(r),LR.copy(e.ray).recast(e.near),!(Fde.containsPoint(LR.origin)===!1&&(LR.intersectSphere(Fde,HVt)===null||LR.origin.distanceToSquared(HVt)>(e.far-e.near)**2))&&(LVt.copy(r).invert(),LR.copy(e.ray).applyMatrix4(LVt),!(o.boundingBox!==null&&LR.intersectsBox(o.boundingBox)===!1)&&this._computeIntersections(e,n,LR)))}_computeIntersections(e,n,o){let i;const r=this.geometry,s=this.material,a=r.index,A=r.attributes.position,c=r.attributes.uv,l=r.attributes.uv1,u=r.attributes.normal,g=r.groups,h=r.drawRange;if(a!==null)if(Array.isArray(s))for(let d=0,p=g.length;d<p;d++){const m=g[d],_=s[m.materialIndex],f=Math.max(m.start,h.start),I=Math.min(a.count,Math.min(m.start+m.count,h.start+h.count));for(let C=f,y=I;C<y;C+=3){const x=a.getX(C),E=a.getX(C+1),B=a.getX(C+2);i=Kde(this,_,e,o,c,l,u,x,E,B),i&&(i.faceIndex=Math.floor(C/3),i.face.materialIndex=m.materialIndex,n.push(i))}}else{const d=Math.max(0,h.start),p=Math.min(a.count,h.start+h.count);for(let m=d,_=p;m<_;m+=3){const f=a.getX(m),I=a.getX(m+1),C=a.getX(m+2);i=Kde(this,s,e,o,c,l,u,f,I,C),i&&(i.faceIndex=Math.floor(m/3),n.push(i))}}else if(A!==void 0)if(Array.isArray(s))for(let d=0,p=g.length;d<p;d++){const m=g[d],_=s[m.materialIndex],f=Math.max(m.start,h.start),I=Math.min(A.count,Math.min(m.start+m.count,h.start+h.count));for(let C=f,y=I;C<y;C+=3){const x=C,E=C+1,B=C+2;i=Kde(this,_,e,o,c,l,u,x,E,B),i&&(i.faceIndex=Math.floor(C/3),i.face.materialIndex=m.materialIndex,n.push(i))}}else{const d=Math.max(0,h.start),p=Math.min(A.count,h.start+h.count);for(let m=d,_=p;m<_;m+=3){const f=m,I=m+1,C=m+2;i=Kde(this,s,e,o,c,l,u,f,I,C),i&&(i.faceIndex=Math.floor(m/3),n.push(i))}}}}function H$o(t,e,n,o,i,r,s,a){let A;if(e.side===uI?A=o.intersectTriangle(s,r,i,!0,a):A=o.intersectTriangle(i,r,s,e.side===mE,a),A===null)return null;Ude.copy(a),Ude.applyMatrix4(t.matrixWorld);const c=n.ray.origin.distanceTo(Ude);return c<n.near||c>n.far?null:{distance:c,point:Ude.clone(),object:t}}function Kde(t,e,n,o,i,r,s,a,A,c){t.getVertexPosition(a,ZG),t.getVertexPosition(A,eY),t.getVertexPosition(c,tY);const l=H$o(t,e,n,o,ZG,eY,tY,Yde);if(l){i&&(Hde.fromBufferAttribute(i,a),Ode.fromBufferAttribute(i,A),Gde.fromBufferAttribute(i,c),l.uv=KB.getInterpolation(Yde,ZG,eY,tY,Hde,Ode,Gde,new ni)),r&&(Hde.fromBufferAttribute(r,a),Ode.fromBufferAttribute(r,A),Gde.fromBufferAttribute(r,c),l.uv1=KB.getInterpolation(Yde,ZG,eY,tY,Hde,Ode,Gde,new ni)),s&&(OVt.fromBufferAttribute(s,a),GVt.fromBufferAttribute(s,A),YVt.fromBufferAttribute(s,c),l.normal=KB.getInterpolation(Yde,ZG,eY,tY,OVt,GVt,YVt,new jt),l.normal.dot(o.direction)>0&&l.normal.multiplyScalar(-1));const u={a,b:A,c,normal:new jt,materialIndex:0};KB.getNormal(ZG,eY,tY,u.normal),l.face=u}return l}class Yx extends Zl{constructor(e=1,n=1,o=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:n,depth:o,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const A=[],c=[],l=[],u=[];let g=0,h=0;d("z","y","x",-1,-1,o,n,e,s,r,0),d("z","y","x",1,-1,o,n,-e,s,r,1),d("x","z","y",1,1,e,o,n,i,s,2),d("x","z","y",1,-1,e,o,-n,i,s,3),d("x","y","z",1,-1,e,n,o,i,r,4),d("x","y","z",-1,-1,e,n,-o,i,r,5),this.setIndex(A),this.setAttribute("position",new Bs(c,3)),this.setAttribute("normal",new Bs(l,3)),this.setAttribute("uv",new Bs(u,2));function d(p,m,_,f,I,C,y,x,E,B,S){const Q=C/E,w=y/B,M=C/2,k=y/2,R=x/2,F=E+1,O=B+1;let U=0,Y=0;const W=new jt;for(let te=0;te<O;te++){const j=te*w-k;for(let J=0;J<F;J++){const oe=J*Q-M;W[p]=oe*f,W[m]=j*I,W[_]=R,c.push(W.x,W.y,W.z),W[p]=0,W[m]=0,W[_]=x>0?1:-1,l.push(W.x,W.y,W.z),u.push(J/E),u.push(1-te/B),U+=1}}for(let te=0;te<B;te++)for(let j=0;j<E;j++){const J=g+j+F*te,oe=g+j+F*(te+1),ie=g+(j+1)+F*(te+1),ne=g+(j+1)+F*te;A.push(J,oe,ne),A.push(oe,ie,ne),Y+=6}a.addGroup(h,Y,S),h+=Y,g+=U}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Yx(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function nY(t){const e={};for(const n in t){e[n]={};for(const o in t[n]){const i=t[n][o];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[n][o]=null):e[n][o]=i.clone():Array.isArray(i)?e[n][o]=i.slice():e[n][o]=i}}return e}function n2(t){const e={};for(let n=0;n<t.length;n++){const o=nY(t[n]);for(const i in o)e[i]=o[i]}return e}function O$o(t){const e=[];for(let n=0;n<t.length;n++)e.push(t[n].clone());return e}function UVt(t){const e=t.getRenderTarget();return e===null?t.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:iu.workingColorSpace}const KVt={clone:nY,merge:n2};var G$o=`void main() {
	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,Y$o=`void main() {
	gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`;class f6 extends Gx{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=G$o,this.fragmentShader=Y$o,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=nY(e.uniforms),this.uniformsGroups=O$o(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const n=super.toJSON(e);n.glslVersion=this.glslVersion,n.uniforms={};for(const i in this.uniforms){const s=this.uniforms[i].value;s&&s.isTexture?n.uniforms[i]={type:"t",value:s.toJSON(e).uuid}:s&&s.isColor?n.uniforms[i]={type:"c",value:s.getHex()}:s&&s.isVector2?n.uniforms[i]={type:"v2",value:s.toArray()}:s&&s.isVector3?n.uniforms[i]={type:"v3",value:s.toArray()}:s&&s.isVector4?n.uniforms[i]={type:"v4",value:s.toArray()}:s&&s.isMatrix3?n.uniforms[i]={type:"m3",value:s.toArray()}:s&&s.isMatrix4?n.uniforms[i]={type:"m4",value:s.toArray()}:n.uniforms[i]={value:s}}Object.keys(this.defines).length>0&&(n.defines=this.defines),n.vertexShader=this.vertexShader,n.fragmentShader=this.fragmentShader,n.lights=this.lights,n.clipping=this.clipping;const o={};for(const i in this.extensions)this.extensions[i]===!0&&(o[i]=!0);return Object.keys(o).length>0&&(n.extensions=o),n}}class VVt extends T0{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new va,this.projectionMatrix=new va,this.projectionMatrixInverse=new va,this.coordinateSystem=Xb}copy(e,n){return super.copy(e,n),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,n){super.updateWorldMatrix(e,n),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const tP=new jt,zVt=new ni,JVt=new ni;class sf extends VVt{constructor(e=50,n=1,o=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=o,this.far=i,this.focus=10,this.aspect=n,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const n=.5*this.getFilmHeight()/e;this.fov=HG*2*Math.atan(n),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(LG*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return HG*2*Math.atan(Math.tan(LG*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,n,o){tP.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(tP.x,tP.y).multiplyScalar(-e/tP.z),tP.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),o.set(tP.x,tP.y).multiplyScalar(-e/tP.z)}getViewSize(e,n){return this.getViewBounds(e,zVt,JVt),n.subVectors(JVt,zVt)}setViewOffset(e,n,o,i,r,s){this.aspect=e/n,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=o,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let n=e*Math.tan(LG*.5*this.fov)/this.zoom,o=2*n,i=this.aspect*o,r=-.5*i;const s=this.view;if(this.view!==null&&this.view.enabled){const A=s.fullWidth,c=s.fullHeight;r+=s.offsetX*i/A,n-=s.offsetY*o/c,i*=s.width/A,o*=s.height/c}const a=this.filmOffset;a!==0&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,n,n-o,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.fov=this.fov,n.object.zoom=this.zoom,n.object.near=this.near,n.object.far=this.far,n.object.focus=this.focus,n.object.aspect=this.aspect,this.view!==null&&(n.object.view=Object.assign({},this.view)),n.object.filmGauge=this.filmGauge,n.object.filmOffset=this.filmOffset,n}}const oY=-90,iY=1;class U$o extends T0{constructor(e,n,o){super(),this.type="CubeCamera",this.renderTarget=o,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new sf(oY,iY,e,n);i.layers=this.layers,this.add(i);const r=new sf(oY,iY,e,n);r.layers=this.layers,this.add(r);const s=new sf(oY,iY,e,n);s.layers=this.layers,this.add(s);const a=new sf(oY,iY,e,n);a.layers=this.layers,this.add(a);const A=new sf(oY,iY,e,n);A.layers=this.layers,this.add(A);const c=new sf(oY,iY,e,n);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,n=this.children.concat(),[o,i,r,s,a,A]=n;for(const c of n)this.remove(c);if(e===Xb)o.up.set(0,1,0),o.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),A.up.set(0,1,0),A.lookAt(0,0,-1);else if(e===Sde)o.up.set(0,-1,0),o.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),A.up.set(0,-1,0),A.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of n)this.add(c),c.updateMatrixWorld()}update(e,n){this.parent===null&&this.updateMatrixWorld();const{renderTarget:o,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,A,c,l]=this.children,u=e.getRenderTarget(),g=e.getActiveCubeFace(),h=e.getActiveMipmapLevel(),d=e.xr.enabled;e.xr.enabled=!1;const p=o.texture.generateMipmaps;o.texture.generateMipmaps=!1,e.setRenderTarget(o,0,i),e.render(n,r),e.setRenderTarget(o,1,i),e.render(n,s),e.setRenderTarget(o,2,i),e.render(n,a),e.setRenderTarget(o,3,i),e.render(n,A),e.setRenderTarget(o,4,i),e.render(n,c),o.texture.generateMipmaps=p,e.setRenderTarget(o,5,i),e.render(n,l),e.setRenderTarget(u,g,h),e.xr.enabled=d,o.texture.needsPMREMUpdate=!0}}class WVt extends Hg{constructor(e,n,o,i,r,s,a,A,c,l){e=e!==void 0?e:[],n=n!==void 0?n:vG,super(e,n,o,i,r,s,a,A,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class K$o extends TR{constructor(e=1,n={}){super(e,e,n),this.isWebGLCubeRenderTarget=!0;const o={width:e,height:e,depth:1},i=[o,o,o,o,o,o];this.texture=new WVt(i,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=n.generateMipmaps!==void 0?n.generateMipmaps:!1,this.texture.minFilter=n.minFilter!==void 0?n.minFilter:Fl}fromEquirectangularTexture(e,n){this.texture.type=n.type,this.texture.colorSpace=n.colorSpace,this.texture.generateMipmaps=n.generateMipmaps,this.texture.minFilter=n.minFilter,this.texture.magFilter=n.magFilter;const o={uniforms:{tEquirect:{value:null}},vertexShader:`

				varying vec3 vWorldDirection;

				vec3 transformDirection( in vec3 dir, in mat4 matrix ) {

					return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );

				}

				void main() {

					vWorldDirection = transformDirection( position, modelMatrix );

					#include <begin_vertex>
					#include <project_vertex>

				}
			`,fragmentShader:`

				uniform sampler2D tEquirect;

				varying vec3 vWorldDirection;

				#include <common>

				void main() {

					vec3 direction = normalize( vWorldDirection );

					vec2 sampleUV = equirectUv( direction );

					gl_FragColor = texture2D( tEquirect, sampleUV );

				}
			`},i=new Yx(5,5,5),r=new f6({name:"CubemapFromEquirect",uniforms:nY(o.uniforms),vertexShader:o.vertexShader,fragmentShader:o.fragmentShader,side:uI,blending:zw});r.uniforms.tEquirect.value=n;const s=new Er(i,r),a=n.minFilter;return n.minFilter===gm&&(n.minFilter=Fl),new U$o(1,10,this).update(e,s),n.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(e,n,o,i){const r=e.getRenderTarget();for(let s=0;s<6;s++)e.setRenderTarget(this,s),e.clear(n,o,i);e.setRenderTarget(r)}}const bTe=new jt,V$o=new jt,z$o=new HA;class nP{constructor(e=new jt(1,0,0),n=0){this.isPlane=!0,this.normal=e,this.constant=n}set(e,n){return this.normal.copy(e),this.constant=n,this}setComponents(e,n,o,i){return this.normal.set(e,n,o),this.constant=i,this}setFromNormalAndCoplanarPoint(e,n){return this.normal.copy(e),this.constant=-n.dot(this.normal),this}setFromCoplanarPoints(e,n,o){const i=bTe.subVectors(o,n).cross(V$o.subVectors(e,n)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,n){return n.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,n){const o=e.delta(bTe),i=this.normal.dot(o);if(i===0)return this.distanceToPoint(e.start)===0?n.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:n.copy(e.start).addScaledVector(o,r)}intersectsLine(e){const n=this.distanceToPoint(e.start),o=this.distanceToPoint(e.end);return n<0&&o>0||o<0&&n>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,n){const o=n||z$o.getNormalMatrix(e),i=this.coplanarPoint(bTe).applyMatrix4(e),r=this.normal.applyMatrix3(o).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const HR=new GB,Vde=new jt;class STe{constructor(e=new nP,n=new nP,o=new nP,i=new nP,r=new nP,s=new nP){this.planes=[e,n,o,i,r,s]}set(e,n,o,i,r,s){const a=this.planes;return a[0].copy(e),a[1].copy(n),a[2].copy(o),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(e){const n=this.planes;for(let o=0;o<6;o++)n[o].copy(e.planes[o]);return this}setFromProjectionMatrix(e,n=Xb){const o=this.planes,i=e.elements,r=i[0],s=i[1],a=i[2],A=i[3],c=i[4],l=i[5],u=i[6],g=i[7],h=i[8],d=i[9],p=i[10],m=i[11],_=i[12],f=i[13],I=i[14],C=i[15];if(o[0].setComponents(A-r,g-c,m-h,C-_).normalize(),o[1].setComponents(A+r,g+c,m+h,C+_).normalize(),o[2].setComponents(A+s,g+l,m+d,C+f).normalize(),o[3].setComponents(A-s,g-l,m-d,C-f).normalize(),o[4].setComponents(A-a,g-u,m-p,C-I).normalize(),n===Xb)o[5].setComponents(A+a,g+u,m+p,C+I).normalize();else if(n===Sde)o[5].setComponents(a,u,p,I).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+n);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),HR.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const n=e.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),HR.copy(n.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(HR)}intersectsSprite(e){return HR.center.set(0,0,0),HR.radius=.7071067811865476,HR.applyMatrix4(e.matrixWorld),this.intersectsSphere(HR)}intersectsSphere(e){const n=this.planes,o=e.center,i=-e.radius;for(let r=0;r<6;r++)if(n[r].distanceToPoint(o)<i)return!1;return!0}intersectsBox(e){const n=this.planes;for(let o=0;o<6;o++){const i=n[o];if(Vde.x=i.normal.x>0?e.max.x:e.min.x,Vde.y=i.normal.y>0?e.max.y:e.min.y,Vde.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Vde)<0)return!1}return!0}containsPoint(e){const n=this.planes;for(let o=0;o<6;o++)if(n[o].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function jVt(){let t=null,e=!1,n=null,o=null;function i(r,s){n(r,s),o=t.requestAnimationFrame(i)}return{start:function(){e!==!0&&n!==null&&(o=t.requestAnimationFrame(i),e=!0)},stop:function(){t.cancelAnimationFrame(o),e=!1},setAnimationLoop:function(r){n=r},setContext:function(r){t=r}}}function J$o(t){const e=new WeakMap;function n(a,A){const c=a.array,l=a.usage,u=c.byteLength,g=t.createBuffer();t.bindBuffer(A,g),t.bufferData(A,c,l),a.onUploadCallback();let h;if(c instanceof Float32Array)h=t.FLOAT;else if(c instanceof Uint16Array)a.isFloat16BufferAttribute?h=t.HALF_FLOAT:h=t.UNSIGNED_SHORT;else if(c instanceof Int16Array)h=t.SHORT;else if(c instanceof Uint32Array)h=t.UNSIGNED_INT;else if(c instanceof Int32Array)h=t.INT;else if(c instanceof Int8Array)h=t.BYTE;else if(c instanceof Uint8Array)h=t.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)h=t.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:g,type:h,bytesPerElement:c.BYTES_PER_ELEMENT,version:a.version,size:u}}function o(a,A,c){const l=A.array,u=A._updateRange,g=A.updateRanges;if(t.bindBuffer(c,a),u.count===-1&&g.length===0&&t.bufferSubData(c,0,l),g.length!==0){for(let h=0,d=g.length;h<d;h++){const p=g[h];t.bufferSubData(c,p.start*l.BYTES_PER_ELEMENT,l,p.start,p.count)}A.clearUpdateRanges()}u.count!==-1&&(t.bufferSubData(c,u.offset*l.BYTES_PER_ELEMENT,l,u.offset,u.count),u.count=-1),A.onUploadCallback()}function i(a){return a.isInterleavedBufferAttribute&&(a=a.data),e.get(a)}function r(a){a.isInterleavedBufferAttribute&&(a=a.data);const A=e.get(a);A&&(t.deleteBuffer(A.buffer),e.delete(a))}function s(a,A){if(a.isGLBufferAttribute){const l=e.get(a);(!l||l.version<a.version)&&e.set(a,{buffer:a.buffer,type:a.type,bytesPerElement:a.elementSize,version:a.version});return}a.isInterleavedBufferAttribute&&(a=a.data);const c=e.get(a);if(c===void 0)e.set(a,n(a,A));else if(c.version<a.version){if(c.size!==a.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");o(c.buffer,a,A),c.version=a.version}}return{get:i,remove:r,update:s}}class VB extends Zl{constructor(e=1,n=1,o=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:n,widthSegments:o,heightSegments:i};const r=e/2,s=n/2,a=Math.floor(o),A=Math.floor(i),c=a+1,l=A+1,u=e/a,g=n/A,h=[],d=[],p=[],m=[];for(let _=0;_<l;_++){const f=_*g-s;for(let I=0;I<c;I++){const C=I*u-r;d.push(C,-f,0),p.push(0,0,1),m.push(I/a),m.push(1-_/A)}}for(let _=0;_<A;_++)for(let f=0;f<a;f++){const I=f+c*_,C=f+c*(_+1),y=f+1+c*(_+1),x=f+1+c*_;h.push(I,C,x),h.push(C,y,x)}this.setIndex(h),this.setAttribute("position",new Bs(d,3)),this.setAttribute("normal",new Bs(p,3)),this.setAttribute("uv",new Bs(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new VB(e.width,e.height,e.widthSegments,e.heightSegments)}}var W$o=`#ifdef USE_ALPHAHASH
	if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`,j$o=`#ifdef USE_ALPHAHASH
	const float ALPHA_HASH_SCALE = 0.05;
	float hash2D( vec2 value ) {
		return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
	}
	float hash3D( vec3 value ) {
		return hash2D( vec2( hash2D( value.xy ), value.z ) );
	}
	float getAlphaHashThreshold( vec3 position ) {
		float maxDeriv = max(
			length( dFdx( position.xyz ) ),
			length( dFdy( position.xyz ) )
		);
		float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
		vec2 pixScales = vec2(
			exp2( floor( log2( pixScale ) ) ),
			exp2( ceil( log2( pixScale ) ) )
		);
		vec2 alpha = vec2(
			hash3D( floor( pixScales.x * position.xyz ) ),
			hash3D( floor( pixScales.y * position.xyz ) )
		);
		float lerpFactor = fract( log2( pixScale ) );
		float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
		float a = min( lerpFactor, 1.0 - lerpFactor );
		vec3 cases = vec3(
			x * x / ( 2.0 * a * ( 1.0 - a ) ),
			( x - 0.5 * a ) / ( 1.0 - a ),
			1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
		);
		float threshold = ( x < ( 1.0 - a ) )
			? ( ( x < a ) ? cases.x : cases.y )
			: cases.z;
		return clamp( threshold , 1.0e-6, 1.0 );
	}
#endif`,$$o=`#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
#endif`,q$o=`#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`,X$o=`#ifdef USE_ALPHATEST
	#ifdef ALPHA_TO_COVERAGE
	diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
	if ( diffuseColor.a == 0.0 ) discard;
	#else
	if ( diffuseColor.a < alphaTest ) discard;
	#endif
#endif`,Z$o=`#ifdef USE_ALPHATEST
	uniform float alphaTest;
#endif`,eqo=`#ifdef USE_AOMAP
	float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
	reflectedLight.indirectDiffuse *= ambientOcclusion;
	#if defined( USE_CLEARCOAT ) 
		clearcoatSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_SHEEN ) 
		sheenSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD )
		float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
		reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
	#endif
#endif`,tqo=`#ifdef USE_AOMAP
	uniform sampler2D aoMap;
	uniform float aoMapIntensity;
#endif`,nqo=`#ifdef USE_BATCHING
	attribute float batchId;
	uniform highp sampler2D batchingTexture;
	mat4 getBatchingMatrix( const in float i ) {
		int size = textureSize( batchingTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
#endif
#ifdef USE_BATCHING_COLOR
	uniform sampler2D batchingColorTexture;
	vec3 getBatchingColor( const in float i ) {
		int size = textureSize( batchingColorTexture, 0 ).x;
		int j = int( i );
		int x = j % size;
		int y = j / size;
		return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;
	}
#endif`,oqo=`#ifdef USE_BATCHING
	mat4 batchingMatrix = getBatchingMatrix( batchId );
#endif`,iqo=`vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
	vPosition = vec3( position );
#endif`,rqo=`vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
	vec3 objectTangent = vec3( tangent.xyz );
#endif`,sqo=`float G_BlinnPhong_Implicit( ) {
	return 0.25;
}
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
	return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
}
vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( specularColor, 1.0, dotVH );
	float G = G_BlinnPhong_Implicit( );
	float D = D_BlinnPhong( shininess, dotNH );
	return F * ( G * D );
} // validated`,aqo=`#ifdef USE_IRIDESCENCE
	const mat3 XYZ_TO_REC709 = mat3(
		 3.2404542, -0.9692660,  0.0556434,
		-1.5371385,  1.8760108, -0.2040259,
		-0.4985314,  0.0415560,  1.0572252
	);
	vec3 Fresnel0ToIor( vec3 fresnel0 ) {
		vec3 sqrtF0 = sqrt( fresnel0 );
		return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
	}
	vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
	}
	float IorToFresnel0( float transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
	}
	vec3 evalSensitivity( float OPD, vec3 shift ) {
		float phase = 2.0 * PI * OPD * 1.0e-9;
		vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
		vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
		vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
		vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
		xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
		xyz /= 1.0685e-7;
		vec3 rgb = XYZ_TO_REC709 * xyz;
		return rgb;
	}
	vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
		vec3 I;
		float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
		float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
		float cosTheta2Sq = 1.0 - sinTheta2Sq;
		if ( cosTheta2Sq < 0.0 ) {
			return vec3( 1.0 );
		}
		float cosTheta2 = sqrt( cosTheta2Sq );
		float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
		float R12 = F_Schlick( R0, 1.0, cosTheta1 );
		float T121 = 1.0 - R12;
		float phi12 = 0.0;
		if ( iridescenceIOR < outsideIOR ) phi12 = PI;
		float phi21 = PI - phi12;
		vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );		vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
		vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
		vec3 phi23 = vec3( 0.0 );
		if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
		if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
		if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
		float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
		vec3 phi = vec3( phi21 ) + phi23;
		vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
		vec3 r123 = sqrt( R123 );
		vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
		vec3 C0 = R12 + Rs;
		I = C0;
		vec3 Cm = Rs - T121;
		for ( int m = 1; m <= 2; ++ m ) {
			Cm *= r123;
			vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
			I += Cm * Sm;
		}
		return max( I, vec3( 0.0 ) );
	}
#endif`,Aqo=`#ifdef USE_BUMPMAP
	uniform sampler2D bumpMap;
	uniform float bumpScale;
	vec2 dHdxy_fwd() {
		vec2 dSTdx = dFdx( vBumpMapUv );
		vec2 dSTdy = dFdy( vBumpMapUv );
		float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
		float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
		float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
		return vec2( dBx, dBy );
	}
	vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
		vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
		vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
		vec3 vN = surf_norm;
		vec3 R1 = cross( vSigmaY, vN );
		vec3 R2 = cross( vN, vSigmaX );
		float fDet = dot( vSigmaX, R1 ) * faceDirection;
		vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
		return normalize( abs( fDet ) * surf_norm - vGrad );
	}
#endif`,cqo=`#if NUM_CLIPPING_PLANES > 0
	vec4 plane;
	#ifdef ALPHA_TO_COVERAGE
		float distanceToPlane, distanceGradient;
		float clipOpacity = 1.0;
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
			distanceGradient = fwidth( distanceToPlane ) / 2.0;
			clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			if ( clipOpacity == 0.0 ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			float unionClipOpacity = 1.0;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
				distanceGradient = fwidth( distanceToPlane ) / 2.0;
				unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			}
			#pragma unroll_loop_end
			clipOpacity *= 1.0 - unionClipOpacity;
		#endif
		diffuseColor.a *= clipOpacity;
		if ( diffuseColor.a == 0.0 ) discard;
	#else
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			bool clipped = true;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
			}
			#pragma unroll_loop_end
			if ( clipped ) discard;
		#endif
	#endif
#endif`,lqo=`#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
	uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`,uqo=`#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
#endif`,gqo=`#if NUM_CLIPPING_PLANES > 0
	vClipPosition = - mvPosition.xyz;
#endif`,dqo=`#if defined( USE_COLOR_ALPHA )
	diffuseColor *= vColor;
#elif defined( USE_COLOR )
	diffuseColor.rgb *= vColor;
#endif`,hqo=`#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR )
	varying vec3 vColor;
#endif`,pqo=`#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	varying vec3 vColor;
#endif`,mqo=`#if defined( USE_COLOR_ALPHA )
	vColor = vec4( 1.0 );
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	vColor = vec3( 1.0 );
#endif
#ifdef USE_COLOR
	vColor *= color;
#endif
#ifdef USE_INSTANCING_COLOR
	vColor.xyz *= instanceColor.xyz;
#endif
#ifdef USE_BATCHING_COLOR
	vec3 batchingColor = getBatchingColor( batchId );
	vColor.xyz *= batchingColor.xyz;
#endif`,_qo=`#define PI 3.141592653589793
#define PI2 6.283185307179586
#define PI_HALF 1.5707963267948966
#define RECIPROCAL_PI 0.3183098861837907
#define RECIPROCAL_PI2 0.15915494309189535
#define EPSILON 1e-6
#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
#define whiteComplement( a ) ( 1.0 - saturate( a ) )
float pow2( const in float x ) { return x*x; }
vec3 pow2( const in vec3 x ) { return x*x; }
float pow3( const in float x ) { return x*x*x; }
float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
highp float rand( const in vec2 uv ) {
	const highp float a = 12.9898, b = 78.233, c = 43758.5453;
	highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
	return fract( sin( sn ) * c );
}
#ifdef HIGH_PRECISION
	float precisionSafeLength( vec3 v ) { return length( v ); }
#else
	float precisionSafeLength( vec3 v ) {
		float maxComponent = max3( abs( v ) );
		return length( v / maxComponent ) * maxComponent;
	}
#endif
struct IncidentLight {
	vec3 color;
	vec3 direction;
	bool visible;
};
struct ReflectedLight {
	vec3 directDiffuse;
	vec3 directSpecular;
	vec3 indirectDiffuse;
	vec3 indirectSpecular;
};
#ifdef USE_ALPHAHASH
	varying vec3 vPosition;
#endif
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
}
mat3 transposeMat3( const in mat3 m ) {
	mat3 tmp;
	tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
	tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
	tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
	return tmp;
}
float luminance( const in vec3 rgb ) {
	const vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );
	return dot( weights, rgb );
}
bool isPerspectiveMatrix( mat4 m ) {
	return m[ 2 ][ 3 ] == - 1.0;
}
vec2 equirectUv( in vec3 dir ) {
	float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
	float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
	return vec2( u, v );
}
vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
	return RECIPROCAL_PI * diffuseColor;
}
vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
}
float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
} // validated`,fqo=`#ifdef ENVMAP_TYPE_CUBE_UV
	#define cubeUV_minMipLevel 4.0
	#define cubeUV_minTileSize 16.0
	float getFace( vec3 direction ) {
		vec3 absDirection = abs( direction );
		float face = - 1.0;
		if ( absDirection.x > absDirection.z ) {
			if ( absDirection.x > absDirection.y )
				face = direction.x > 0.0 ? 0.0 : 3.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		} else {
			if ( absDirection.z > absDirection.y )
				face = direction.z > 0.0 ? 2.0 : 5.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		}
		return face;
	}
	vec2 getUV( vec3 direction, float face ) {
		vec2 uv;
		if ( face == 0.0 ) {
			uv = vec2( direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 1.0 ) {
			uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
		} else if ( face == 2.0 ) {
			uv = vec2( - direction.x, direction.y ) / abs( direction.z );
		} else if ( face == 3.0 ) {
			uv = vec2( - direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 4.0 ) {
			uv = vec2( - direction.x, direction.z ) / abs( direction.y );
		} else {
			uv = vec2( direction.x, direction.y ) / abs( direction.z );
		}
		return 0.5 * ( uv + 1.0 );
	}
	vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
		float face = getFace( direction );
		float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
		mipInt = max( mipInt, cubeUV_minMipLevel );
		float faceSize = exp2( mipInt );
		highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
		if ( face > 2.0 ) {
			uv.y += faceSize;
			face -= 3.0;
		}
		uv.x += face * faceSize;
		uv.x += filterInt * 3.0 * cubeUV_minTileSize;
		uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
		uv.x *= CUBEUV_TEXEL_WIDTH;
		uv.y *= CUBEUV_TEXEL_HEIGHT;
		#ifdef texture2DGradEXT
			return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
		#else
			return texture2D( envMap, uv ).rgb;
		#endif
	}
	#define cubeUV_r0 1.0
	#define cubeUV_m0 - 2.0
	#define cubeUV_r1 0.8
	#define cubeUV_m1 - 1.0
	#define cubeUV_r4 0.4
	#define cubeUV_m4 2.0
	#define cubeUV_r5 0.305
	#define cubeUV_m5 3.0
	#define cubeUV_r6 0.21
	#define cubeUV_m6 4.0
	float roughnessToMip( float roughness ) {
		float mip = 0.0;
		if ( roughness >= cubeUV_r1 ) {
			mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
		} else if ( roughness >= cubeUV_r4 ) {
			mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
		} else if ( roughness >= cubeUV_r5 ) {
			mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
		} else if ( roughness >= cubeUV_r6 ) {
			mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
		} else {
			mip = - 2.0 * log2( 1.16 * roughness );		}
		return mip;
	}
	vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
		float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
		float mipF = fract( mip );
		float mipInt = floor( mip );
		vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
		if ( mipF == 0.0 ) {
			return vec4( color0, 1.0 );
		} else {
			vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
			return vec4( mix( color0, color1, mipF ), 1.0 );
		}
	}
#endif`,Iqo=`vec3 transformedNormal = objectNormal;
#ifdef USE_TANGENT
	vec3 transformedTangent = objectTangent;
#endif
#ifdef USE_BATCHING
	mat3 bm = mat3( batchingMatrix );
	transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
	transformedNormal = bm * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = bm * transformedTangent;
	#endif
#endif
#ifdef USE_INSTANCING
	mat3 im = mat3( instanceMatrix );
	transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
	transformedNormal = im * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = im * transformedTangent;
	#endif
#endif
transformedNormal = normalMatrix * transformedNormal;
#ifdef FLIP_SIDED
	transformedNormal = - transformedNormal;
#endif
#ifdef USE_TANGENT
	transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
	#ifdef FLIP_SIDED
		transformedTangent = - transformedTangent;
	#endif
#endif`,Cqo=`#ifdef USE_DISPLACEMENTMAP
	uniform sampler2D displacementMap;
	uniform float displacementScale;
	uniform float displacementBias;
#endif`,yqo=`#ifdef USE_DISPLACEMENTMAP
	transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`,xqo=`#ifdef USE_EMISSIVEMAP
	vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
	totalEmissiveRadiance *= emissiveColor.rgb;
#endif`,Eqo=`#ifdef USE_EMISSIVEMAP
	uniform sampler2D emissiveMap;
#endif`,Bqo="gl_FragColor = linearToOutputTexel( gl_FragColor );",bqo=`
const mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(
	vec3( 0.8224621, 0.177538, 0.0 ),
	vec3( 0.0331941, 0.9668058, 0.0 ),
	vec3( 0.0170827, 0.0723974, 0.9105199 )
);
const mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(
	vec3( 1.2249401, - 0.2249404, 0.0 ),
	vec3( - 0.0420569, 1.0420571, 0.0 ),
	vec3( - 0.0196376, - 0.0786361, 1.0982735 )
);
vec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {
	return vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );
}
vec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {
	return vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );
}
vec4 LinearTransferOETF( in vec4 value ) {
	return value;
}
vec4 sRGBTransferOETF( in vec4 value ) {
	return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
}
vec4 LinearToLinear( in vec4 value ) {
	return value;
}
vec4 LinearTosRGB( in vec4 value ) {
	return sRGBTransferOETF( value );
}`,Sqo=`#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vec3 cameraToFrag;
		if ( isOrthographic ) {
			cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToFrag = normalize( vWorldPosition - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vec3 reflectVec = reflect( cameraToFrag, worldNormal );
		#else
			vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
		#endif
	#else
		vec3 reflectVec = vReflect;
	#endif
	#ifdef ENVMAP_TYPE_CUBE
		vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
	#else
		vec4 envColor = vec4( 0.0 );
	#endif
	#ifdef ENVMAP_BLENDING_MULTIPLY
		outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_MIX )
		outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_ADD )
		outgoingLight += envColor.xyz * specularStrength * reflectivity;
	#endif
#endif`,Qqo=`#ifdef USE_ENVMAP
	uniform float envMapIntensity;
	uniform float flipEnvMap;
	uniform mat3 envMapRotation;
	#ifdef ENVMAP_TYPE_CUBE
		uniform samplerCube envMap;
	#else
		uniform sampler2D envMap;
	#endif
	
#endif`,vqo=`#ifdef USE_ENVMAP
	uniform float reflectivity;
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		varying vec3 vWorldPosition;
		uniform float refractionRatio;
	#else
		varying vec3 vReflect;
	#endif
#endif`,wqo=`#ifdef USE_ENVMAP
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		
		varying vec3 vWorldPosition;
	#else
		varying vec3 vReflect;
		uniform float refractionRatio;
	#endif
#endif`,Pqo=`#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vWorldPosition = worldPosition.xyz;
	#else
		vec3 cameraToVertex;
		if ( isOrthographic ) {
			cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vReflect = reflect( cameraToVertex, worldNormal );
		#else
			vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
		#endif
	#endif
#endif`,Mqo=`#ifdef USE_FOG
	vFogDepth = - mvPosition.z;
#endif`,Dqo=`#ifdef USE_FOG
	varying float vFogDepth;
#endif`,Nqo=`#ifdef USE_FOG
	#ifdef FOG_EXP2
		float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
	#else
		float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
	#endif
	gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
#endif`,Rqo=`#ifdef USE_FOG
	uniform vec3 fogColor;
	varying float vFogDepth;
	#ifdef FOG_EXP2
		uniform float fogDensity;
	#else
		uniform float fogNear;
		uniform float fogFar;
	#endif
#endif`,Tqo=`#ifdef USE_GRADIENTMAP
	uniform sampler2D gradientMap;
#endif
vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
	float dotNL = dot( normal, lightDirection );
	vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
	#ifdef USE_GRADIENTMAP
		return vec3( texture2D( gradientMap, coord ).r );
	#else
		vec2 fw = fwidth( coord ) * 0.5;
		return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
	#endif
}`,kqo=`#ifdef USE_LIGHTMAP
	uniform sampler2D lightMap;
	uniform float lightMapIntensity;
#endif`,Fqo=`LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`,Lqo=`varying vec3 vViewPosition;
struct LambertMaterial {
	vec3 diffuseColor;
	float specularStrength;
};
void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Lambert
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Lambert`,Hqo=`uniform bool receiveShadow;
uniform vec3 ambientLightColor;
#if defined( USE_LIGHT_PROBES )
	uniform vec3 lightProbe[ 9 ];
#endif
vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
	float x = normal.x, y = normal.y, z = normal.z;
	vec3 result = shCoefficients[ 0 ] * 0.886227;
	result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
	result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
	result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
	result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
	result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
	result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
	result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
	result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
	return result;
}
vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
	vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
	vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
	return irradiance;
}
vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
	vec3 irradiance = ambientLightColor;
	return irradiance;
}
float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
	float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
	if ( cutoffDistance > 0.0 ) {
		distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
	}
	return distanceFalloff;
}
float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
	return smoothstep( coneCosine, penumbraCosine, angleCosine );
}
#if NUM_DIR_LIGHTS > 0
	struct DirectionalLight {
		vec3 direction;
		vec3 color;
	};
	uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
	void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
		light.color = directionalLight.color;
		light.direction = directionalLight.direction;
		light.visible = true;
	}
#endif
#if NUM_POINT_LIGHTS > 0
	struct PointLight {
		vec3 position;
		vec3 color;
		float distance;
		float decay;
	};
	uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
	void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = pointLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float lightDistance = length( lVector );
		light.color = pointLight.color;
		light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
		light.visible = ( light.color != vec3( 0.0 ) );
	}
#endif
#if NUM_SPOT_LIGHTS > 0
	struct SpotLight {
		vec3 position;
		vec3 direction;
		vec3 color;
		float distance;
		float decay;
		float coneCos;
		float penumbraCos;
	};
	uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
	void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = spotLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float angleCos = dot( light.direction, spotLight.direction );
		float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
		if ( spotAttenuation > 0.0 ) {
			float lightDistance = length( lVector );
			light.color = spotLight.color * spotAttenuation;
			light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
			light.visible = ( light.color != vec3( 0.0 ) );
		} else {
			light.color = vec3( 0.0 );
			light.visible = false;
		}
	}
#endif
#if NUM_RECT_AREA_LIGHTS > 0
	struct RectAreaLight {
		vec3 color;
		vec3 position;
		vec3 halfWidth;
		vec3 halfHeight;
	};
	uniform sampler2D ltc_1;	uniform sampler2D ltc_2;
	uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
#endif
#if NUM_HEMI_LIGHTS > 0
	struct HemisphereLight {
		vec3 direction;
		vec3 skyColor;
		vec3 groundColor;
	};
	uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
	vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
		float dotNL = dot( normal, hemiLight.direction );
		float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
		vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
		return irradiance;
	}
#endif`,Oqo=`#ifdef USE_ENVMAP
	vec3 getIBLIrradiance( const in vec3 normal ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
			return PI * envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 reflectVec = reflect( - viewDir, normal );
			reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
			reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
			return envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	#ifdef USE_ANISOTROPY
		vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
			#ifdef ENVMAP_TYPE_CUBE_UV
				vec3 bentNormal = cross( bitangent, viewDir );
				bentNormal = normalize( cross( bentNormal, bitangent ) );
				bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
				return getIBLRadiance( viewDir, bentNormal, roughness );
			#else
				return vec3( 0.0 );
			#endif
		}
	#endif
#endif`,Gqo=`ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`,Yqo=`varying vec3 vViewPosition;
struct ToonMaterial {
	vec3 diffuseColor;
};
void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
	vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Toon
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Toon`,Uqo=`BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`,Kqo=`varying vec3 vViewPosition;
struct BlinnPhongMaterial {
	vec3 diffuseColor;
	vec3 specularColor;
	float specularShininess;
	float specularStrength;
};
void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
	reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
}
void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_BlinnPhong
#define RE_IndirectDiffuse		RE_IndirectDiffuse_BlinnPhong`,Vqo=`PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
material.roughness = min( material.roughness, 1.0 );
#ifdef IOR
	material.ior = ior;
	#ifdef USE_SPECULAR
		float specularIntensityFactor = specularIntensity;
		vec3 specularColorFactor = specularColor;
		#ifdef USE_SPECULAR_COLORMAP
			specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
		#endif
		#ifdef USE_SPECULAR_INTENSITYMAP
			specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
		#endif
		material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
	#else
		float specularIntensityFactor = 1.0;
		vec3 specularColorFactor = vec3( 1.0 );
		material.specularF90 = 1.0;
	#endif
	material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
#else
	material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
	material.specularF90 = 1.0;
#endif
#ifdef USE_CLEARCOAT
	material.clearcoat = clearcoat;
	material.clearcoatRoughness = clearcoatRoughness;
	material.clearcoatF0 = vec3( 0.04 );
	material.clearcoatF90 = 1.0;
	#ifdef USE_CLEARCOATMAP
		material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
	#endif
	#ifdef USE_CLEARCOAT_ROUGHNESSMAP
		material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
	#endif
	material.clearcoat = saturate( material.clearcoat );	material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
	material.clearcoatRoughness += geometryRoughness;
	material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
#endif
#ifdef USE_DISPERSION
	material.dispersion = dispersion;
#endif
#ifdef USE_IRIDESCENCE
	material.iridescence = iridescence;
	material.iridescenceIOR = iridescenceIOR;
	#ifdef USE_IRIDESCENCEMAP
		material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
	#endif
	#ifdef USE_IRIDESCENCE_THICKNESSMAP
		material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
	#else
		material.iridescenceThickness = iridescenceThicknessMaximum;
	#endif
#endif
#ifdef USE_SHEEN
	material.sheenColor = sheenColor;
	#ifdef USE_SHEEN_COLORMAP
		material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
	#endif
	material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
	#ifdef USE_SHEEN_ROUGHNESSMAP
		material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
	#endif
#endif
#ifdef USE_ANISOTROPY
	#ifdef USE_ANISOTROPYMAP
		mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
		vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
		vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
	#else
		vec2 anisotropyV = anisotropyVector;
	#endif
	material.anisotropy = length( anisotropyV );
	if( material.anisotropy == 0.0 ) {
		anisotropyV = vec2( 1.0, 0.0 );
	} else {
		anisotropyV /= material.anisotropy;
		material.anisotropy = saturate( material.anisotropy );
	}
	material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
	material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
	material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
#endif`,zqo=`struct PhysicalMaterial {
	vec3 diffuseColor;
	float roughness;
	vec3 specularColor;
	float specularF90;
	float dispersion;
	#ifdef USE_CLEARCOAT
		float clearcoat;
		float clearcoatRoughness;
		vec3 clearcoatF0;
		float clearcoatF90;
	#endif
	#ifdef USE_IRIDESCENCE
		float iridescence;
		float iridescenceIOR;
		float iridescenceThickness;
		vec3 iridescenceFresnel;
		vec3 iridescenceF0;
	#endif
	#ifdef USE_SHEEN
		vec3 sheenColor;
		float sheenRoughness;
	#endif
	#ifdef IOR
		float ior;
	#endif
	#ifdef USE_TRANSMISSION
		float transmission;
		float transmissionAlpha;
		float thickness;
		float attenuationDistance;
		vec3 attenuationColor;
	#endif
	#ifdef USE_ANISOTROPY
		float anisotropy;
		float alphaT;
		vec3 anisotropyT;
		vec3 anisotropyB;
	#endif
};
vec3 clearcoatSpecularDirect = vec3( 0.0 );
vec3 clearcoatSpecularIndirect = vec3( 0.0 );
vec3 sheenSpecularDirect = vec3( 0.0 );
vec3 sheenSpecularIndirect = vec3(0.0 );
vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
    float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
    float x2 = x * x;
    float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
    return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
}
float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
	float a2 = pow2( alpha );
	float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
	float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
	return 0.5 / max( gv + gl, EPSILON );
}
float D_GGX( const in float alpha, const in float dotNH ) {
	float a2 = pow2( alpha );
	float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
	return RECIPROCAL_PI * a2 / pow2( denom );
}
#ifdef USE_ANISOTROPY
	float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {
		float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
		float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
		float v = 0.5 / ( gv + gl );
		return saturate(v);
	}
	float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
		float a2 = alphaT * alphaB;
		highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
		highp float v2 = dot( v, v );
		float w2 = a2 / v2;
		return RECIPROCAL_PI * a2 * pow2 ( w2 );
	}
#endif
#ifdef USE_CLEARCOAT
	vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
		vec3 f0 = material.clearcoatF0;
		float f90 = material.clearcoatF90;
		float roughness = material.clearcoatRoughness;
		float alpha = pow2( roughness );
		vec3 halfDir = normalize( lightDir + viewDir );
		float dotNL = saturate( dot( normal, lightDir ) );
		float dotNV = saturate( dot( normal, viewDir ) );
		float dotNH = saturate( dot( normal, halfDir ) );
		float dotVH = saturate( dot( viewDir, halfDir ) );
		vec3 F = F_Schlick( f0, f90, dotVH );
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
		return F * ( V * D );
	}
#endif
vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
	vec3 f0 = material.specularColor;
	float f90 = material.specularF90;
	float roughness = material.roughness;
	float alpha = pow2( roughness );
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( f0, f90, dotVH );
	#ifdef USE_IRIDESCENCE
		F = mix( F, material.iridescenceFresnel, material.iridescence );
	#endif
	#ifdef USE_ANISOTROPY
		float dotTL = dot( material.anisotropyT, lightDir );
		float dotTV = dot( material.anisotropyT, viewDir );
		float dotTH = dot( material.anisotropyT, halfDir );
		float dotBL = dot( material.anisotropyB, lightDir );
		float dotBV = dot( material.anisotropyB, viewDir );
		float dotBH = dot( material.anisotropyB, halfDir );
		float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
		float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
	#else
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
	#endif
	return F * ( V * D );
}
vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
	const float LUT_SIZE = 64.0;
	const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
	const float LUT_BIAS = 0.5 / LUT_SIZE;
	float dotNV = saturate( dot( N, V ) );
	vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
	uv = uv * LUT_SCALE + LUT_BIAS;
	return uv;
}
float LTC_ClippedSphereFormFactor( const in vec3 f ) {
	float l = length( f );
	return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
}
vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
	float x = dot( v1, v2 );
	float y = abs( x );
	float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
	float b = 3.4175940 + ( 4.1616724 + y ) * y;
	float v = a / b;
	float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
	return cross( v1, v2 ) * theta_sintheta;
}
vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
	vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
	vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
	vec3 lightNormal = cross( v1, v2 );
	if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
	vec3 T1, T2;
	T1 = normalize( V - N * dot( V, N ) );
	T2 = - cross( N, T1 );
	mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
	vec3 coords[ 4 ];
	coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
	coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
	coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
	coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
	coords[ 0 ] = normalize( coords[ 0 ] );
	coords[ 1 ] = normalize( coords[ 1 ] );
	coords[ 2 ] = normalize( coords[ 2 ] );
	coords[ 3 ] = normalize( coords[ 3 ] );
	vec3 vectorFormFactor = vec3( 0.0 );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
	float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
	return vec3( result );
}
#if defined( USE_SHEEN )
float D_Charlie( float roughness, float dotNH ) {
	float alpha = pow2( roughness );
	float invAlpha = 1.0 / alpha;
	float cos2h = dotNH * dotNH;
	float sin2h = max( 1.0 - cos2h, 0.0078125 );
	return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
}
float V_Neubelt( float dotNV, float dotNL ) {
	return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
}
vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float D = D_Charlie( sheenRoughness, dotNH );
	float V = V_Neubelt( dotNV, dotNL );
	return sheenColor * ( D * V );
}
#endif
float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	float r2 = roughness * roughness;
	float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
	float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
	float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
	return saturate( DG * RECIPROCAL_PI );
}
vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
	const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
	vec4 r = roughness * c0 + c1;
	float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
	vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;
	return fab;
}
vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	return specularColor * fab.x + specularF90 * fab.y;
}
#ifdef USE_IRIDESCENCE
void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#else
void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#endif
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	#ifdef USE_IRIDESCENCE
		vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
	#else
		vec3 Fr = specularColor;
	#endif
	vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
	float Ess = fab.x + fab.y;
	float Ems = 1.0 - Ess;
	vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;	vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
	singleScatter += FssEss;
	multiScatter += Fms * Ems;
}
#if NUM_RECT_AREA_LIGHTS > 0
	void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
		vec3 normal = geometryNormal;
		vec3 viewDir = geometryViewDir;
		vec3 position = geometryPosition;
		vec3 lightPos = rectAreaLight.position;
		vec3 halfWidth = rectAreaLight.halfWidth;
		vec3 halfHeight = rectAreaLight.halfHeight;
		vec3 lightColor = rectAreaLight.color;
		float roughness = material.roughness;
		vec3 rectCoords[ 4 ];
		rectCoords[ 0 ] = lightPos + halfWidth - halfHeight;		rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
		rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
		rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
		vec2 uv = LTC_Uv( normal, viewDir, roughness );
		vec4 t1 = texture2D( ltc_1, uv );
		vec4 t2 = texture2D( ltc_2, uv );
		mat3 mInv = mat3(
			vec3( t1.x, 0, t1.y ),
			vec3(    0, 1,    0 ),
			vec3( t1.z, 0, t1.w )
		);
		vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
		reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
		reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
	}
#endif
void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	#ifdef USE_CLEARCOAT
		float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
		vec3 ccIrradiance = dotNLcc * directLight.color;
		clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
	#endif
	reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {
	#ifdef USE_CLEARCOAT
		clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
	#endif
	vec3 singleScattering = vec3( 0.0 );
	vec3 multiScattering = vec3( 0.0 );
	vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
	#ifdef USE_IRIDESCENCE
		computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
	#else
		computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
	#endif
	vec3 totalScattering = singleScattering + multiScattering;
	vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
	reflectedLight.indirectSpecular += radiance * singleScattering;
	reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
	reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
}
#define RE_Direct				RE_Direct_Physical
#define RE_Direct_RectArea		RE_Direct_RectArea_Physical
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Physical
#define RE_IndirectSpecular		RE_IndirectSpecular_Physical
float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
	return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
}`,Jqo=`
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
vec3 geometryClearcoatNormal = vec3( 0.0 );
#ifdef USE_CLEARCOAT
	geometryClearcoatNormal = clearcoatNormal;
#endif
#ifdef USE_IRIDESCENCE
	float dotNVi = saturate( dot( normal, geometryViewDir ) );
	if ( material.iridescenceThickness == 0.0 ) {
		material.iridescence = 0.0;
	} else {
		material.iridescence = saturate( material.iridescence );
	}
	if ( material.iridescence > 0.0 ) {
		material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
		material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
	}
#endif
IncidentLight directLight;
#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
	PointLight pointLight;
	#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
		pointLight = pointLights[ i ];
		getPointLightInfo( pointLight, geometryPosition, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
		pointLightShadow = pointLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
	SpotLight spotLight;
	vec4 spotColor;
	vec3 spotLightCoord;
	bool inSpotLightMap;
	#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
		spotLight = spotLights[ i ];
		getSpotLightInfo( spotLight, geometryPosition, directLight );
		#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
		#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
		#else
		#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#endif
		#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
			spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
			inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
			spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
			directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
		#endif
		#undef SPOT_LIGHT_MAP_INDEX
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		spotLightShadow = spotLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
	DirectionalLight directionalLight;
	#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
		directionalLight = directionalLights[ i ];
		getDirectionalLightInfo( directionalLight, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
		directionalLightShadow = directionalLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
	RectAreaLight rectAreaLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
		rectAreaLight = rectAreaLights[ i ];
		RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if defined( RE_IndirectDiffuse )
	vec3 iblIrradiance = vec3( 0.0 );
	vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
	#if defined( USE_LIGHT_PROBES )
		irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
	#endif
	#if ( NUM_HEMI_LIGHTS > 0 )
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
			irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
		}
		#pragma unroll_loop_end
	#endif
#endif
#if defined( RE_IndirectSpecular )
	vec3 radiance = vec3( 0.0 );
	vec3 clearcoatRadiance = vec3( 0.0 );
#endif`,Wqo=`#if defined( RE_IndirectDiffuse )
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
		irradiance += lightMapIrradiance;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
		iblIrradiance += getIBLIrradiance( geometryNormal );
	#endif
#endif
#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
	#ifdef USE_ANISOTROPY
		radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
	#else
		radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
	#endif
	#ifdef USE_CLEARCOAT
		clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
	#endif
#endif`,jqo=`#if defined( RE_IndirectDiffuse )
	RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif
#if defined( RE_IndirectSpecular )
	RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif`,$qo=`#if defined( USE_LOGDEPTHBUF )
	gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`,qqo=`#if defined( USE_LOGDEPTHBUF )
	uniform float logDepthBufFC;
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`,Xqo=`#ifdef USE_LOGDEPTHBUF
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`,Zqo=`#ifdef USE_LOGDEPTHBUF
	vFragDepth = 1.0 + gl_Position.w;
	vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`,eXo=`#ifdef USE_MAP
	vec4 sampledDiffuseColor = texture2D( map, vMapUv );
	#ifdef DECODE_VIDEO_TEXTURE
		sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );
	
	#endif
	diffuseColor *= sampledDiffuseColor;
#endif`,tXo=`#ifdef USE_MAP
	uniform sampler2D map;
#endif`,nXo=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
	#if defined( USE_POINTS_UV )
		vec2 uv = vUv;
	#else
		vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
	#endif
#endif
#ifdef USE_MAP
	diffuseColor *= texture2D( map, uv );
#endif
#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, uv ).g;
#endif`,oXo=`#if defined( USE_POINTS_UV )
	varying vec2 vUv;
#else
	#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
		uniform mat3 uvTransform;
	#endif
#endif
#ifdef USE_MAP
	uniform sampler2D map;
#endif
#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`,iXo=`float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
	vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
	metalnessFactor *= texelMetalness.b;
#endif`,rXo=`#ifdef USE_METALNESSMAP
	uniform sampler2D metalnessMap;
#endif`,sXo=`#ifdef USE_INSTANCING_MORPH
	float morphTargetInfluences[ MORPHTARGETS_COUNT ];
	float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		morphTargetInfluences[i] =  texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
	}
#endif`,aXo=`#if defined( USE_MORPHCOLORS )
	vColor *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		#if defined( USE_COLOR_ALPHA )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
		#elif defined( USE_COLOR )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
		#endif
	}
#endif`,AXo=`#ifdef USE_MORPHNORMALS
	objectNormal *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
	}
#endif`,cXo=`#ifdef USE_MORPHTARGETS
	#ifndef USE_INSTANCING_MORPH
		uniform float morphTargetBaseInfluence;
		uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
	#endif
	uniform sampler2DArray morphTargetsTexture;
	uniform ivec2 morphTargetsTextureSize;
	vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
		int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
		int y = texelIndex / morphTargetsTextureSize.x;
		int x = texelIndex - y * morphTargetsTextureSize.x;
		ivec3 morphUV = ivec3( x, y, morphTargetIndex );
		return texelFetch( morphTargetsTexture, morphUV, 0 );
	}
#endif`,lXo=`#ifdef USE_MORPHTARGETS
	transformed *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
	}
#endif`,uXo=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
#ifdef FLAT_SHADED
	vec3 fdx = dFdx( vViewPosition );
	vec3 fdy = dFdy( vViewPosition );
	vec3 normal = normalize( cross( fdx, fdy ) );
#else
	vec3 normal = normalize( vNormal );
	#ifdef DOUBLE_SIDED
		normal *= faceDirection;
	#endif
#endif
#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
	#ifdef USE_TANGENT
		mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn = getTangentFrame( - vViewPosition, normal,
		#if defined( USE_NORMALMAP )
			vNormalMapUv
		#elif defined( USE_CLEARCOAT_NORMALMAP )
			vClearcoatNormalMapUv
		#else
			vUv
		#endif
		);
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn[0] *= faceDirection;
		tbn[1] *= faceDirection;
	#endif
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	#ifdef USE_TANGENT
		mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn2[0] *= faceDirection;
		tbn2[1] *= faceDirection;
	#endif
#endif
vec3 nonPerturbedNormal = normal;`,gXo=`#ifdef USE_NORMALMAP_OBJECTSPACE
	normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	#ifdef FLIP_SIDED
		normal = - normal;
	#endif
	#ifdef DOUBLE_SIDED
		normal = normal * faceDirection;
	#endif
	normal = normalize( normalMatrix * normal );
#elif defined( USE_NORMALMAP_TANGENTSPACE )
	vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	mapN.xy *= normalScale;
	normal = normalize( tbn * mapN );
#elif defined( USE_BUMPMAP )
	normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
#endif`,dXo=`#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`,hXo=`#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`,pXo=`#ifndef FLAT_SHADED
	vNormal = normalize( transformedNormal );
	#ifdef USE_TANGENT
		vTangent = normalize( transformedTangent );
		vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
	#endif
#endif`,mXo=`#ifdef USE_NORMALMAP
	uniform sampler2D normalMap;
	uniform vec2 normalScale;
#endif
#ifdef USE_NORMALMAP_OBJECTSPACE
	uniform mat3 normalMatrix;
#endif
#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
	mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
		vec3 q0 = dFdx( eye_pos.xyz );
		vec3 q1 = dFdy( eye_pos.xyz );
		vec2 st0 = dFdx( uv.st );
		vec2 st1 = dFdy( uv.st );
		vec3 N = surf_norm;
		vec3 q1perp = cross( q1, N );
		vec3 q0perp = cross( N, q0 );
		vec3 T = q1perp * st0.x + q0perp * st1.x;
		vec3 B = q1perp * st0.y + q0perp * st1.y;
		float det = max( dot( T, T ), dot( B, B ) );
		float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
		return mat3( T * scale, B * scale, N );
	}
#endif`,_Xo=`#ifdef USE_CLEARCOAT
	vec3 clearcoatNormal = nonPerturbedNormal;
#endif`,fXo=`#ifdef USE_CLEARCOAT_NORMALMAP
	vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
	clearcoatMapN.xy *= clearcoatNormalScale;
	clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`,IXo=`#ifdef USE_CLEARCOATMAP
	uniform sampler2D clearcoatMap;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform sampler2D clearcoatNormalMap;
	uniform vec2 clearcoatNormalScale;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform sampler2D clearcoatRoughnessMap;
#endif`,CXo=`#ifdef USE_IRIDESCENCEMAP
	uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform sampler2D iridescenceThicknessMap;
#endif`,yXo=`#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,xXo=`vec3 packNormalToRGB( const in vec3 normal ) {
	return normalize( normal ) * 0.5 + 0.5;
}
vec3 unpackRGBToNormal( const in vec3 rgb ) {
	return 2.0 * rgb.xyz - 1.0;
}
const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;
const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );
const vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );
const float ShiftRight8 = 1. / 256.;
vec4 packDepthToRGBA( const in float v ) {
	vec4 r = vec4( fract( v * PackFactors ), v );
	r.yzw -= r.xyz * ShiftRight8;	return r * PackUpscale;
}
float unpackRGBAToDepth( const in vec4 v ) {
	return dot( v, UnpackFactors );
}
vec2 packDepthToRG( in highp float v ) {
	return packDepthToRGBA( v ).yx;
}
float unpackRGToDepth( const in highp vec2 v ) {
	return unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );
}
vec4 pack2HalfToRGBA( vec2 v ) {
	vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
	return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
}
vec2 unpackRGBATo2Half( vec4 v ) {
	return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
}
float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
	return ( viewZ + near ) / ( near - far );
}
float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return depth * ( near - far ) - near;
}
float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
	return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
}
float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return ( near * far ) / ( ( far - near ) * depth - far );
}`,EXo=`#ifdef PREMULTIPLIED_ALPHA
	gl_FragColor.rgb *= gl_FragColor.a;
#endif`,BXo=`vec4 mvPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
	mvPosition = batchingMatrix * mvPosition;
#endif
#ifdef USE_INSTANCING
	mvPosition = instanceMatrix * mvPosition;
#endif
mvPosition = modelViewMatrix * mvPosition;
gl_Position = projectionMatrix * mvPosition;`,bXo=`#ifdef DITHERING
	gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`,SXo=`#ifdef DITHERING
	vec3 dithering( vec3 color ) {
		float grid_position = rand( gl_FragCoord.xy );
		vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
		dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
		return color + dither_shift_RGB;
	}
#endif`,QXo=`float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
	vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
	roughnessFactor *= texelRoughness.g;
#endif`,vXo=`#ifdef USE_ROUGHNESSMAP
	uniform sampler2D roughnessMap;
#endif`,wXo=`#if NUM_SPOT_LIGHT_COORDS > 0
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#if NUM_SPOT_LIGHT_MAPS > 0
	uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
		struct SpotLightShadow {
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
	float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
		return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );
	}
	vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
		return unpackRGBATo2Half( texture2D( shadow, uv ) );
	}
	float VSMShadow (sampler2D shadow, vec2 uv, float compare ){
		float occlusion = 1.0;
		vec2 distribution = texture2DDistribution( shadow, uv );
		float hard_shadow = step( compare , distribution.x );
		if (hard_shadow != 1.0 ) {
			float distance = compare - distribution.x ;
			float variance = max( 0.00000, distribution.y * distribution.y );
			float softness_probability = variance / (variance + distance * distance );			softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );			occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );
		}
		return occlusion;
	}
	float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
		float shadow = 1.0;
		shadowCoord.xyz /= shadowCoord.w;
		shadowCoord.z += shadowBias;
		bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
		bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
		if ( frustumTest ) {
		#if defined( SHADOWMAP_TYPE_PCF )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx0 = - texelSize.x * shadowRadius;
			float dy0 = - texelSize.y * shadowRadius;
			float dx1 = + texelSize.x * shadowRadius;
			float dy1 = + texelSize.y * shadowRadius;
			float dx2 = dx0 / 2.0;
			float dy2 = dy0 / 2.0;
			float dx3 = dx1 / 2.0;
			float dy3 = dy1 / 2.0;
			shadow = (
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
			) * ( 1.0 / 17.0 );
		#elif defined( SHADOWMAP_TYPE_PCF_SOFT )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx = texelSize.x;
			float dy = texelSize.y;
			vec2 uv = shadowCoord.xy;
			vec2 f = fract( uv * shadowMapSize + 0.5 );
			uv -= f * texelSize;
			shadow = (
				texture2DCompare( shadowMap, uv, shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
						  f.x ),
					 mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
						  f.x ),
					 f.y )
			) * ( 1.0 / 9.0 );
		#elif defined( SHADOWMAP_TYPE_VSM )
			shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
		#else
			shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
		#endif
		}
		return shadow;
	}
	vec2 cubeToUV( vec3 v, float texelSizeY ) {
		vec3 absV = abs( v );
		float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
		absV *= scaleToCube;
		v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
		vec2 planar = v.xy;
		float almostATexel = 1.5 * texelSizeY;
		float almostOne = 1.0 - almostATexel;
		if ( absV.z >= almostOne ) {
			if ( v.z > 0.0 )
				planar.x = 4.0 - v.x;
		} else if ( absV.x >= almostOne ) {
			float signX = sign( v.x );
			planar.x = v.z * signX + 2.0 * signX;
		} else if ( absV.y >= almostOne ) {
			float signY = sign( v.y );
			planar.x = v.x + 2.0 * signY + 2.0;
			planar.y = v.z * signY - 2.0;
		}
		return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
	}
	float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
		float shadow = 1.0;
		vec3 lightToPosition = shadowCoord.xyz;
		
		float lightToPositionLength = length( lightToPosition );
		if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {
			float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );			dp += shadowBias;
			vec3 bd3D = normalize( lightToPosition );
			vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
			#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
				vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
				shadow = (
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
				) * ( 1.0 / 9.0 );
			#else
				shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
			#endif
		}
		return shadow;
	}
#endif`,PXo=`#if NUM_SPOT_LIGHT_COORDS > 0
	uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		struct SpotLightShadow {
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
#endif`,MXo=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
	vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
	vec4 shadowWorldPosition;
#endif
#if defined( USE_SHADOWMAP )
	#if NUM_DIR_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
			vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
			vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
#endif
#if NUM_SPOT_LIGHT_COORDS > 0
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
		shadowWorldPosition = worldPosition;
		#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
			shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
		#endif
		vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
	}
	#pragma unroll_loop_end
#endif`,DXo=`float getShadowMask() {
	float shadow = 1.0;
	#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
		directionalLight = directionalLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
		spotLight = spotLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
		pointLight = pointLightShadows[ i ];
		shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#endif
	return shadow;
}`,NXo=`#ifdef USE_SKINNING
	mat4 boneMatX = getBoneMatrix( skinIndex.x );
	mat4 boneMatY = getBoneMatrix( skinIndex.y );
	mat4 boneMatZ = getBoneMatrix( skinIndex.z );
	mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`,RXo=`#ifdef USE_SKINNING
	uniform mat4 bindMatrix;
	uniform mat4 bindMatrixInverse;
	uniform highp sampler2D boneTexture;
	mat4 getBoneMatrix( const in float i ) {
		int size = textureSize( boneTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
#endif`,TXo=`#ifdef USE_SKINNING
	vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
	vec4 skinned = vec4( 0.0 );
	skinned += boneMatX * skinVertex * skinWeight.x;
	skinned += boneMatY * skinVertex * skinWeight.y;
	skinned += boneMatZ * skinVertex * skinWeight.z;
	skinned += boneMatW * skinVertex * skinWeight.w;
	transformed = ( bindMatrixInverse * skinned ).xyz;
#endif`,kXo=`#ifdef USE_SKINNING
	mat4 skinMatrix = mat4( 0.0 );
	skinMatrix += skinWeight.x * boneMatX;
	skinMatrix += skinWeight.y * boneMatY;
	skinMatrix += skinWeight.z * boneMatZ;
	skinMatrix += skinWeight.w * boneMatW;
	skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
	objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
	#ifdef USE_TANGENT
		objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
	#endif
#endif`,FXo=`float specularStrength;
#ifdef USE_SPECULARMAP
	vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
	specularStrength = texelSpecular.r;
#else
	specularStrength = 1.0;
#endif`,LXo=`#ifdef USE_SPECULARMAP
	uniform sampler2D specularMap;
#endif`,HXo=`#if defined( TONE_MAPPING )
	gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`,OXo=`#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
uniform float toneMappingExposure;
vec3 LinearToneMapping( vec3 color ) {
	return saturate( toneMappingExposure * color );
}
vec3 ReinhardToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	return saturate( color / ( vec3( 1.0 ) + color ) );
}
vec3 OptimizedCineonToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	color = max( vec3( 0.0 ), color - 0.004 );
	return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
}
vec3 RRTAndODTFit( vec3 v ) {
	vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
	vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
	return a / b;
}
vec3 ACESFilmicToneMapping( vec3 color ) {
	const mat3 ACESInputMat = mat3(
		vec3( 0.59719, 0.07600, 0.02840 ),		vec3( 0.35458, 0.90834, 0.13383 ),
		vec3( 0.04823, 0.01566, 0.83777 )
	);
	const mat3 ACESOutputMat = mat3(
		vec3(  1.60475, -0.10208, -0.00327 ),		vec3( -0.53108,  1.10813, -0.07276 ),
		vec3( -0.07367, -0.00605,  1.07602 )
	);
	color *= toneMappingExposure / 0.6;
	color = ACESInputMat * color;
	color = RRTAndODTFit( color );
	color = ACESOutputMat * color;
	return saturate( color );
}
const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
	vec3( 1.6605, - 0.1246, - 0.0182 ),
	vec3( - 0.5876, 1.1329, - 0.1006 ),
	vec3( - 0.0728, - 0.0083, 1.1187 )
);
const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
	vec3( 0.6274, 0.0691, 0.0164 ),
	vec3( 0.3293, 0.9195, 0.0880 ),
	vec3( 0.0433, 0.0113, 0.8956 )
);
vec3 agxDefaultContrastApprox( vec3 x ) {
	vec3 x2 = x * x;
	vec3 x4 = x2 * x2;
	return + 15.5 * x4 * x2
		- 40.14 * x4 * x
		+ 31.96 * x4
		- 6.868 * x2 * x
		+ 0.4298 * x2
		+ 0.1191 * x
		- 0.00232;
}
vec3 AgXToneMapping( vec3 color ) {
	const mat3 AgXInsetMatrix = mat3(
		vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
		vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
		vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
	);
	const mat3 AgXOutsetMatrix = mat3(
		vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
		vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
		vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
	);
	const float AgxMinEv = - 12.47393;	const float AgxMaxEv = 4.026069;
	color *= toneMappingExposure;
	color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
	color = AgXInsetMatrix * color;
	color = max( color, 1e-10 );	color = log2( color );
	color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
	color = clamp( color, 0.0, 1.0 );
	color = agxDefaultContrastApprox( color );
	color = AgXOutsetMatrix * color;
	color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
	color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
	color = clamp( color, 0.0, 1.0 );
	return color;
}
vec3 NeutralToneMapping( vec3 color ) {
	const float StartCompression = 0.8 - 0.04;
	const float Desaturation = 0.15;
	color *= toneMappingExposure;
	float x = min( color.r, min( color.g, color.b ) );
	float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
	color -= offset;
	float peak = max( color.r, max( color.g, color.b ) );
	if ( peak < StartCompression ) return color;
	float d = 1. - StartCompression;
	float newPeak = 1. - d * d / ( peak + d - StartCompression );
	color *= newPeak / peak;
	float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
	return mix( color, vec3( newPeak ), g );
}
vec3 CustomToneMapping( vec3 color ) { return color; }`,GXo=`#ifdef USE_TRANSMISSION
	material.transmission = transmission;
	material.transmissionAlpha = 1.0;
	material.thickness = thickness;
	material.attenuationDistance = attenuationDistance;
	material.attenuationColor = attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
	#endif
	#ifdef USE_THICKNESSMAP
		material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
	#endif
	vec3 pos = vWorldPosition;
	vec3 v = normalize( cameraPosition - pos );
	vec3 n = inverseTransformDirection( normal, viewMatrix );
	vec4 transmitted = getIBLVolumeRefraction(
		n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
		pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,
		material.attenuationColor, material.attenuationDistance );
	material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
	totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
#endif`,YXo=`#ifdef USE_TRANSMISSION
	uniform float transmission;
	uniform float thickness;
	uniform float attenuationDistance;
	uniform vec3 attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		uniform sampler2D transmissionMap;
	#endif
	#ifdef USE_THICKNESSMAP
		uniform sampler2D thicknessMap;
	#endif
	uniform vec2 transmissionSamplerSize;
	uniform sampler2D transmissionSamplerMap;
	uniform mat4 modelMatrix;
	uniform mat4 projectionMatrix;
	varying vec3 vWorldPosition;
	float w0( float a ) {
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
	}
	float w1( float a ) {
		return ( 1.0 / 6.0 ) * ( a *  a * ( 3.0 * a - 6.0 ) + 4.0 );
	}
	float w2( float a ){
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
	}
	float w3( float a ) {
		return ( 1.0 / 6.0 ) * ( a * a * a );
	}
	float g0( float a ) {
		return w0( a ) + w1( a );
	}
	float g1( float a ) {
		return w2( a ) + w3( a );
	}
	float h0( float a ) {
		return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
	}
	float h1( float a ) {
		return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
	}
	vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
		uv = uv * texelSize.zw + 0.5;
		vec2 iuv = floor( uv );
		vec2 fuv = fract( uv );
		float g0x = g0( fuv.x );
		float g1x = g1( fuv.x );
		float h0x = h0( fuv.x );
		float h1x = h1( fuv.x );
		float h0y = h0( fuv.y );
		float h1y = h1( fuv.y );
		vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
			g1( fuv.y ) * ( g0x