@pacedyn/mcp 1.11.0 → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -76,7 +76,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
76
76
|
`)}async close(){if(!this._closed){if(this._closed=!0,this._abortCleanup?.(),this._abortCleanup=void 0,this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),this._sse!==void 0&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}this._deferredResponse!==void 0&&!this._deferredResponse.settled&&(this._deferredResponse.settled=!0,this._deferredResponse.reject(new tt(it.ConnectionClosed,"Connection closed before a response was produced"))),this.onclose?.()}}settleResponse(e){this._deferredResponse===void 0||this._deferredResponse.settled||(this._deferredResponse.settled=!0,this._deferredResponse.resolve(e))}upgradeToSse(){let e,t=new ReadableStream({start:r=>{e=r},cancel:()=>{this.close()}});this._sse={controller:e,encoder:new TextEncoder,closed:!1},this._sse.keepAliveTimer=YI(this._keepAliveMs,()=>this.writeCommentFrame("keepalive")),this.settleResponse(new Response(t,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}))}finalizeStream(){if(this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),this._sse!==void 0&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}queueMicrotask(()=>{this.close()})}writeMessageFrame(e){this.writeFrame(`event: message
|
|
77
77
|
data: ${JSON.stringify(e)}
|
|
78
78
|
|
|
79
|
-
`)}writeFrame(e){if(!(this._sse===void 0||this._sse.closed))try{this._sse.controller.enqueue(this._sse.encoder.encode(e))}catch(t){this.onerror?.(new Error(`Failed to write to the response stream: ${t}`))}}};function dme(e){return e instanceof hU?fU(e):void 0}function pme(e){return typeof e=="object"&&e!==null&&"setScopeChallengeResolver"in e&&typeof e.setScopeChallengeResolver=="function"}var fme=8,hme=6e5;function gme(e){if(e?.maxRounds!==void 0&&(!Number.isInteger(e.maxRounds)||e.maxRounds<1))throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${e.maxRounds})`);if(e?.roundTimeoutMs!==void 0&&(!Number.isFinite(e.roundTimeoutMs)||e.roundTimeoutMs<=0))throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${e.roundTimeoutMs})`);return{maxRounds:e?.maxRounds??fme,roundTimeoutMs:e?.roundTimeoutMs??hme,legacyShim:e?.legacyShim??!0}}function gU(e,t,r){if(r===null||typeof r!="object"||typeof r.method!="string")throw new qe(_e.InternalError,`Handler for ${e} returned an invalid input request '${t}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let o=r,n=s6(o);if(n===void 0)throw new qe(_e.InternalError,`Handler for ${e} returned an input request '${t}' of kind '${o.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:o,required:n}}function bme(){let e=globalThis.crypto;if(e?.randomUUID!==void 0)return e.randomUUID();let t=new Uint8Array(16);e.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let r=[...t].map(o=>o.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function HI(e,t){if(e==="tools/call")return{content:[{type:"text",text:t}],isError:!0};throw new qe(_e.InternalError,t)}var yme=class{constructor(e){this._host=e}async fulfill(e,t,r,o,n){let{maxRounds:a,roundTimeoutMs:i}=this._host,s=o.mcpReq.signal,c=n,l=0;for(;;){if(l+=1,l>a)return HI(e,P6(e,a));let u=c.inputRequests,m=u!=null&&Object.keys(u).length>0,p=typeof c.requestState=="string"?c.requestState:void 0;if(!m&&p===void 0)throw new qe(_e.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let d;if(m){let g=this._host.resolvedClientCapabilities(o),b=[];for(let[v,k]of Object.entries(u)){let{embedded:x,required:S}=gU(e,v,k);if(x.method!=="roots/list"&&x.params===void 0)throw new qe(_e.InternalError,`Handler for ${e} returned an input request '${v}' of kind '${x.method}' without params`);if(OR(S,g)!==void 0)return HI(e,`Cannot request input '${v}' (${x.method}): the client on this 2025-era connection did not declare the required capability${g===void 0?" (no client capabilities are available on this connection \u2014 per-request legacy serving cannot receive server-to-client requests)":""}`);b.push([v,x])}let y=$6(s);try{let v={relatedRequestId:o.mcpReq.id,timeout:i,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:y.signal},k=await Promise.all(b.map(async([x,S])=>{try{return[x,await this._dispatchLeg(S,v)]}catch(R){throw y.abort(R),R}}));d=Object.fromEntries(k)}catch(v){if(s.aborted)throw v;return HI(e,`Fulfilling input required by '${e}' failed: ${v instanceof Error?v.message:String(v)}`)}finally{y.dispose()}}else await F6(T6,s);let f={...o,mcpReq:{...o.mcpReq,inputResponses:d,droppedInputResponseKeys:void 0,requestState:Nh(p)}};if(p!==void 0){let g=await this._host.verifyRequestState(p,f,e);g!==void 0&&(f=II(f,g))}let h=await t(r,f);if(!ui(h))return h;c=h}}async _dispatchLeg(e,t){switch(e.method){case"elicitation/create":{let r=e.params;return r.mode==="url"&&r.elicitationId===void 0&&(r={...r,elicitationId:bme()}),await this._host.sendElicitation(r,t)}case"sampling/createMessage":return await this._host.sendSampling(e.params,t);case"roots/list":return await this._host.listRoots(e.params,t)}}},vme=new Set(["tools/call","prompts/get","resources/read"]),Sme,kme,Rme;var bU=class extends EI{_clientCapabilities;_clientVersion;static{Sme=(e,t)=>{t.clientCapabilities!==void 0&&(e._clientCapabilities=t.clientCapabilities),t.clientInfo!==void 0&&(e._clientVersion=t.clientInfo)},kme=(e,t)=>{let r=t.filter(o=>!e._supportedProtocolVersions.includes(o));r.length>0&&(e._supportedProtocolVersions=[...e._supportedProtocolVersions,...r]),e.setRequestHandler("server/discover",()=>e._ondiscover())},Rme=e=>e._serverInfo}_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_boundFromTransport=!1;_legacyInputRequiredShim(){return this._legacyShim??=new yme({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:e=>this._inputRequestCapabilityView(e),verifyRequestState:(e,t,r)=>this._verifyRequestState(e,t,r),sendElicitation:(e,t)=>this._sendElicitationLeg(e,t,{validateAcceptedContent:!1}),sendSampling:(e,t)=>this.createMessage(e,t),listRoots:(e,t)=>this.listRoots(e,t)})}oninitialized;constructor(e,t){if(super(t),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new JR,this._requestStateVerify=t?.requestState?.verify,this._inputRequiredServing=gme(t?.inputRequired),t?.cacheHints!==void 0){for(let[r,o]of Object.entries(t.cacheHints))o!==void 0&&xI(o,`cacheHints['${r}']`);this._cacheHints=t.cacheHints}this.setRequestHandler("initialize",r=>this._oninitialize(r)),this.setNotificationHandler("notifications/initialized",()=>this.oninitialized?.()),VR(this._supportedProtocolVersions).length>0&&this.setRequestHandler("server/discover",()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}async connect(e){if(this.transport!==void 0)throw new tt(it.AlreadyConnected,"Use a separate Server instance per connection: this instance is already connected to a transport. To connect it to a new transport, call close() first.");this._boundFromTransport&&(this._boundFromTransport=!1,this._negotiatedProtocolVersion=void 0);let t=dme(e)?.revision;t!==void 0&&!this._servedModernEra()&&zR.includes(t)&&VR(this._supportedProtocolVersions).includes(t)&&(this._negotiatedProtocolVersion=t,this._boundFromTransport=!0),await super.connect(e)}_registerLoggingHandler(){this.setRequestHandler("logging/setLevel",async(e,t)=>{let r=t.sessionId||t.http?.req?.headers.get("mcp-session-id")||void 0,{level:o}=e.params,n=GR(Rs,o);return n.success&&this._loggingLevels.set(r,n.data),{}})}buildContext(e,t){let r=e.http||t?.request||t?.closeSSEStream||t?.closeStandaloneSSEStream;return{...e,mcpReq:{...e.mcpReq,log:(o,n,a)=>{if(!this._capabilities.logging)return Promise.resolve();let i;if(this._servedModernEra()){if(i=e.mcpReq.envelope?.[gs],i===void 0)return Promise.resolve()}else i=this._loggingLevels.get(e.sessionId)??this._loggingLevels.get(void 0);return i!==void 0&&this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(i)?Promise.resolve():e.mcpReq.notify({method:"notifications/message",params:{level:o,data:n,logger:a}})},elicitInput:(o,n)=>this.elicitInput(o,n),requestSampling:(o,n)=>this.createMessage(o,n)},http:r?{...e.http,req:t?.request,closeSSE:t?.closeSSEStream,closeStandaloneSSE:t?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Rs.options.map((e,t)=>[e,t]));isMessageIgnored=(e,t)=>{let r=this._loggingLevels.get(t);return r?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r):!1};registerCapabilities(e){if(this.transport)throw new tt(it.AlreadyConnected,"Cannot register capabilities after connecting to transport");let t=!!this._capabilities.logging;this._capabilities=LI(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(e,t){if(e!=="tools/call"){let r=this._cacheHints?.[e],o=vme.has(e);return r===void 0&&!o?async(n,a)=>{let i=await t(n,a);if(ui(i))throw new qe(_e.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return i}:async(n,a)=>{let i=o?await this._invokeInputRequiredCapableHandler(e,t,n,a):await t(n,a);if(ui(i)){if(!o)throw new qe(_e.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return i}return r===void 0?i:jR(i,r)}}return async(r,o)=>{let n=qc(this._negotiatedProtocolVersion),a=n.validateRequest("tools/call",r);if(!a.ok)throw new qe(a.reason==="not-in-era"?_e.InternalError:_e.InvalidParams,a.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call request: ${a.message}`);let i=await this._invokeInputRequiredCapableHandler("tools/call",t,r,o);if(ui(i))return i;let s=yI(i),c=n.validateResult("tools/call",s);if(!c.ok)throw new qe(c.reason==="not-in-era"?_e.InternalError:_e.InvalidParams,c.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call result: ${c.message}`);return c.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&Lh(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(e,t,r,o){let n=this._servedModernEra(),a=o.mcpReq.requestState();if(a!==void 0&&typeof a!="string")throw new qe(_e.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"});let i=o;if(typeof a=="string"){let m=await this._verifyRequestState(a,o,e);m!==void 0&&(i=II(o,m))}let s;try{s=await t(r,i)}catch(m){throw m instanceof qe&&m.code===_e.UrlElicitationRequired&&n?new qe(_e.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { \u2026: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):m}if(!ui(s))return s;if(!n){if(!this._inputRequiredServing.legacyShim)throw new qe(_e.InternalError,`Handler for ${e} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??Vc}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(e,t,r,i,s)}let c=s.inputRequests,l=c!=null&&Object.keys(c).length>0,u=typeof s.requestState=="string";if(!l&&!u)throw new qe(_e.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(l){let m=this._inputRequestCapabilityView(o);for(let[p,d]of Object.entries(c)){let{embedded:f,required:h}=gU(e,p,d),g=OR(h,m);if(g!==void 0)throw new UR({requiredCapabilities:g},`Cannot request input '${p}' (${f.method}): the request's client capabilities do not declare the required capability`)}}return s}async _verifyRequestState(e,t,r){if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(e,t)}catch(o){throw this.onerror?.(new Error(`requestState verification rejected ${r}: ${o instanceof Error?o.message:String(o)}`)),new qe(_e.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"})}}_inputRequestCapabilityView(e){return this._servedModernEra()?e.mcpReq.envelope?.[ci]:this._clientCapabilities}_assertPushApiInServedEra(e){if(this._servedModernEra())throw new tt(it.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${e}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead \u2014 the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:e,era:"2026-07-28"})}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new tt(it.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new tt(it.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new tt(it.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new tt(it.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new tt(it.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new tt(it.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new tt(it.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new tt(it.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"completion/complete":if(!this._capabilities.completions)throw new tt(it.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new tt(it.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new tt(it.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new tt(it.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new tt(it.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo;let r=l6(this._supportedProtocolVersions),o=r.includes(t)?t:r[0]??Vc;return this._negotiatedProtocolVersion=o,this.transport?.setProtocolVersion?.(o),{protocolVersion:o,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:VR(this._supportedProtocolVersions),capabilities:xme(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(e,t){return this._wireCodec().projectCallToolResult(e,t)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra("ping"),this.request({method:"ping"})}async createMessage(e,t){if(this._assertPushApiInServedEra("sampling/createMessage"),(e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new tt(it.CapabilityNotSupported,"Client does not support sampling tools capability.");if(e.messages.length>0){let a=e.messages.at(-1),i=Array.isArray(a.content)?a.content:[a.content],s=i.some(m=>m.type==="tool_result"),c=e.messages.length>1?e.messages.at(-2):void 0,l=c?Array.isArray(c.content)?c.content:[c.content]:[],u=l.some(m=>m.type==="tool_use");if(s){if(i.some(m=>m.type!=="tool_result"))throw new qe(_e.InvalidParams,"The last message must contain only tool_result content if any is present");if(!u)throw new qe(_e.InvalidParams,"tool_result blocks are not matching any tool_use from the previous message")}if(u){let m=new Set(l.filter(d=>d.type==="tool_use").map(d=>d.id)),p=new Set(i.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(m.size!==p.size||![...m].every(d=>p.has(d)))throw new qe(_e.InvalidParams,"ids of tool_result blocks and tool_use blocks from previous message do not match")}}let r=!!(e.tools||e.toolChoice),o=await this.request({method:"sampling/createMessage",params:e},t),n=this._wireCodec().samplingResultVariant(r,o);if(!n.ok)throw new tt(it.InvalidResult,`Invalid sampling/createMessage result: ${n.reason==="invalid"?n.message:n.reason}`);return n.value}async elicitInput(e,t){switch(this._assertPushApiInServedEra("elicitation/create"),e.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw new tt(it.CapabilityNotSupported,"Client does not support url elicitation.");break;case"form":if(!this._clientCapabilities?.elicitation?.form)throw new tt(it.CapabilityNotSupported,"Client does not support form elicitation.");break}return this._sendElicitationLeg(e,t)}async _sendElicitationLeg(e,t,r){let o=e.mode??"form",n=r?.validateAcceptedContent??!0;switch(o){case"url":{let a=e;return this.request({method:"elicitation/create",params:a},t)}case"form":{let a=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:a},t);if(n&&i.action==="accept"&&i.content&&a.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(a.requestedSchema)(i.content);if(!s.valid)throw new qe(_e.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(s){throw s instanceof qe?s:new qe(_e.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new tt(it.CapabilityNotSupported,"Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this._assertPushApiInServedEra("roots/list"),this.request({method:"roots/list",params:e},t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};function xme(e){return{...e}}function wme(e,t){let r=0,o=[e];for(;o.length>0;){let n=o.pop();if(!(n===null||typeof n!="object"))if(Array.isArray(n))for(let a of n){if(++r>t)return r;a!==null&&typeof a=="object"&&o.push(a)}else for(let a in n){if(!Object.prototype.hasOwnProperty.call(n,a))continue;if(++r>t)return r;let i=n[a];i!==null&&typeof i=="object"&&o.push(i)}}return r}function Mme(e){if(!(e===void 0||e===1/0)){if(typeof e!="number"||Number.isNaN(e)||e<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}var QR=class{server;_maxToolInputElements;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(e){let t=this._registeredTools[e];if(!(t===void 0||!t.enabled)){if(Object.hasOwn(this._toolInputSchemaJson,e))return this._toolInputSchemaJson[e];if(t.inputSchema===void 0)return sU;try{let r=Hc(t.inputSchema,"input");return this._toolInputSchemaJson[e]=r,r}catch{return}}}constructor(e,t){this.server=new bU(e,t),this._maxToolInputElements=Mme(t?.maxToolInputElements),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(e){return pme(e)&&e.setScopeChallengeResolver(t=>this.resolveScopeChallenge(t)),await this.server.connect(e)}async close(){await this.server.close()}resolveScopeChallenge=e=>{switch(e.request.method){case"tools/call":{let t=e.request.params?.name;if(typeof t!="string")return;let r=this._registeredTools[t];return r===void 0||!r.enabled?void 0:r.scopeChallenge?.(e)}case"resources/read":{let t=e.request.params?.uri;if(typeof t!="string")return;let r;try{r=new URL(t)}catch{return}let o=this._registeredResources[r.toString()];if(o!==void 0)return o.enabled?o.scopeChallenge?.(e):void 0;for(let n of Object.values(this._registeredResourceTemplates))if(n.resourceTemplate.uriTemplate.match(r.toString()))return n.enabled?n.scopeChallenge?.(e):void 0;return}case"prompts/get":{let t=e.request.params?.name;if(typeof t!="string")return;let r=this._registeredPrompts[t];return r===void 0||!r.enabled?void 0:r.scopeChallenge?.(e)}default:return}};_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler("tools/list"),this.server.assertCanSetRequestHandler("tools/call"),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler("tools/list",()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?_me(e,t.inputSchema):sU,annotations:t.annotations,icons:t.icons,execution:t.execution,_meta:t._meta};return t.outputSchema&&(r.outputSchema=Hc(t.outputSchema,"output")),r})})),this.server.setRequestHandler("tools/call",async(e,t)=>{let r=this._registeredTools[e.params.name];if(!r)throw new qe(_e.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new qe(_e.InvalidParams,`Tool ${e.params.name} disabled`);try{let o=await this.validateToolInput(r,e.params.arguments,e.params.name),n=await this.executeToolHandler(r,o,t);return await this.validateToolOutput(r,n,e.params.name),ui(n)?n:this.server.projectCallToolResult(n,r.outputSchemaJson)}catch(o){if(o instanceof qe&&o.code===_e.UrlElicitationRequired)throw o;return this.createToolError(o instanceof Error?o.message:String(o))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(this._maxToolInputElements!==void 0&&wme(t,this._maxToolInputElements)>this._maxToolInputElements)throw new qe(_e.InvalidParams,`Invalid arguments for tool ${r}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let o=await Gc(e.inputSchema,t??{});if(!o.success)throw new qe(_e.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${o.error}`);return o.data}async validateToolOutput(e,t,r){if(!e.outputSchema||ui(t)||t.isError)return;if(t.structuredContent===void 0)throw new qe(_e.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=await Gc(e.outputSchema,t.structuredContent);if(!o.success)throw new qe(_e.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${o.error}`)}async executeToolHandler(e,t,r){return e.executor(t,r)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler("completion/complete"),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler("completion/complete",async e=>{switch(e.params.ref.type){case"ref/prompt":return TI(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return PI(e),this.handleResourceCompletion(e,e.params.ref);default:throw new qe(_e.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new qe(_e.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new qe(_e.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return zh;let o=dU(mU(r.argsSchema)?.[e.params.argument.name]);if(!KI(o))return zh;let n=ume(o);return n?uU(await n(e.params.argument.value,e.params.context)):zh}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(n=>n.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return zh;throw new qe(_e.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);return o?uU(await o(e.params.argument.value,e.params.context)):zh}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler("resources/list"),this.server.assertCanSetRequestHandler("resources/templates/list"),this.server.assertCanSetRequestHandler("resources/read"),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler("resources/list",async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([n,a])=>a.enabled).map(([n,a])=>({uri:n,name:a.name,...a.metadata})),o=[];for(let n of Object.values(this._registeredResourceTemplates)){if(!n.resourceTemplate.listCallback)continue;let a=await n.resourceTemplate.listCallback(t);for(let i of a.resources)o.push({...n.metadata,...i})}return{resources:[...r,...o]}}),this.server.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler("resources/read",async(e,t)=>{let r;try{r=new URL(e.params.uri)}catch{throw new qe(_e.InvalidParams,`Resource URI ${e.params.uri} is invalid`,{uri:e.params.uri,reason:"invalid_uri"})}let o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new qe(_e.InvalidParams,`Resource ${r} disabled`);return jR(await o.readCallback(r,t),o.cacheHint)}for(let n of Object.values(this._registeredResourceTemplates)){let a=n.resourceTemplate.uriTemplate.match(r.toString());if(a){if(!n.enabled)throw new qe(_e.InvalidParams,`Resource template ${n.resourceTemplate.uriTemplate} disabled`);return jR(await n.readCallback(r,a,t),n.cacheHint)}}throw new BR(e.params.uri)}),this._resourceHandlersInitialized=!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler("prompts/list"),this.server.assertCanSetRequestHandler("prompts/get"),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler("prompts/list",()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?C6(t.argsSchema):void 0,icons:t.icons,_meta:t._meta}))})),this.server.setRequestHandler("prompts/get",async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new qe(_e.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new qe(_e.InvalidParams,`Prompt ${e.params.name} disabled`);return r.handler(e.params.arguments,t)}),this._promptHandlersInitialized=!0)}registerResource(e,t,r,o){let{cacheHint:n,scopeChallenge:a,...i}=r,s=i;if(n!==void 0&&xI(n,`resource ${e}`),typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let c=this._createRegisteredResource(e,r.title,t,s,a,o);return n!==void 0&&(c.cacheHint=n),this.setResourceRequestHandlers(),this.sendResourceListChanged(),c}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let c=this._createRegisteredResourceTemplate(e,r.title,t,s,a,o);return n!==void 0&&(c.cacheHint=n),this.setResourceRequestHandlers(),this.sendResourceListChanged(),c}}_createRegisteredResource(e,t,r,o,n,a){let i={name:e,title:t,metadata:o,readCallback:a,scopeChallenge:n,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:s=>{s.uri!==void 0&&s.uri!==r&&(delete this._registeredResources[r],s.uri&&(this._registeredResources[s.uri]=i)),s.name!==void 0&&(i.name=s.name),s.metadata!==void 0&&(i.metadata=s.metadata),s.title!==void 0&&(i.title=s.title,i.metadata={...i.metadata,title:s.title}),s.callback!==void 0&&(i.readCallback=s.callback),s.scopeChallenge!==void 0&&(i.scopeChallenge=s.scopeChallenge===null?void 0:s.scopeChallenge),s.enabled!==void 0&&(i.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,t,r,o,n,a){let i={resourceTemplate:r,title:t,metadata:o,readCallback:a,scopeChallenge:n,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:c=>{c.name!==void 0&&c.name!==e&&(delete this._registeredResourceTemplates[e],c.name&&(this._registeredResourceTemplates[c.name]=i)),c.template!==void 0&&(i.resourceTemplate=c.template),c.metadata!==void 0&&(i.metadata=c.metadata),c.title!==void 0&&(i.title=c.title,i.metadata={...i.metadata,title:c.title}),c.callback!==void 0&&(i.readCallback=c.callback),c.scopeChallenge!==void 0&&(i.scopeChallenge=c.scopeChallenge===null?void 0:c.scopeChallenge),c.enabled!==void 0&&(i.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let s=r.uriTemplate.variableNames;return Array.isArray(s)&&s.some(c=>!!r.completeCallback(c))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,t,r,o,n,a,i,s){let c=o,l=n,u={title:t,description:r,argsSchema:o,icons:a,scopeChallenge:i,_meta:s,handler:lU(e,o,n),enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:m=>{m.name!==void 0&&m.name!==e&&(delete this._registeredPrompts[e],m.name&&(this._registeredPrompts[m.name]=u)),m.title!==void 0&&(u.title=m.title),m.description!==void 0&&(u.description=m.description),m.icons!==void 0&&(u.icons=m.icons),m.scopeChallenge!==void 0&&(u.scopeChallenge=m.scopeChallenge===null?void 0:m.scopeChallenge),m._meta!==void 0&&(u._meta=m._meta);let p=!1;m.argsSchema!==void 0&&(u.argsSchema=m.argsSchema,c=m.argsSchema,p=!0),m.callback!==void 0&&(l=m.callback,p=!0),p&&(u.handler=lU(e,c,l)),m.enabled!==void 0&&(u.enabled=m.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=u,o){let m=mU(o);m&&Object.values(m).some(p=>KI(dU(p)))&&this.setCompletionRequestHandler()}return u}_createRegisteredTool(e,t,r,o,n,a,i,s,c,l,u){OI(e);let m=u,p,d={title:t,description:r,inputSchema:o,outputSchema:n,get outputSchemaJson(){return p??=cU(d.outputSchema)},set outputSchemaJson(f){p=f},annotations:a,icons:i,execution:s,scopeChallenge:c,_meta:l,handler:u,executor:iU(o,u),enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:f=>{f.name!==void 0&&f.name!==e&&(typeof f.name=="string"&&OI(f.name),delete this._registeredTools[e],delete this._toolInputSchemaJson[e],f.name&&(delete this._toolInputSchemaJson[f.name],this._registeredTools[f.name]=d,e=f.name)),f.title!==void 0&&(d.title=f.title),f.description!==void 0&&(d.description=f.description);let h=!1;f.paramsSchema!==void 0&&(d.inputSchema=f.paramsSchema,delete this._toolInputSchemaJson[e],h=!0),f.callback!==void 0&&(d.handler=f.callback,m=f.callback,h=!0),h&&(d.executor=iU(d.inputSchema,m)),f.outputSchema!==void 0&&(d.outputSchema=f.outputSchema,d.outputSchemaJson=cU(f.outputSchema)),f.annotations!==void 0&&(d.annotations=f.annotations),f.icons!==void 0&&(d.icons=f.icons),f.scopeChallenge!==void 0&&(d.scopeChallenge=f.scopeChallenge===null?void 0:f.scopeChallenge),f._meta!==void 0&&(d._meta=f._meta),f.enabled!==void 0&&(d.enabled=f.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}registerTool(e,t,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:n,inputSchema:a,outputSchema:i,annotations:s,icons:c,scopeChallenge:l,_meta:u}=t;return this._createRegisteredTool(e,o,n,qR(a),qR(i),s,c,void 0,l,u,r)}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:n,argsSchema:a,icons:i,scopeChallenge:s,_meta:c}=t,l=this._createRegisteredPrompt(e,o,n,qR(a),r,i,s,c);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),l}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};function iU(e,t){if(e){let o=t;return async(n,a)=>o(n,a)}let r=t;return async(o,n)=>r(n)}var sU={type:"object",properties:{}};function _me(e,t){let r=Hc(t,"input"),o=FI(r);return o.valid||console.warn(`[mcp-sdk] tool '${e}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${o.reason}`),r}function cU(e){if(e!==void 0)try{return Hc(e,"output")}catch{return}}function lU(e,t,r){if(t){let o=r;return async(n,a)=>{let i=await Gc(t,n??{});if(!i.success)throw new qe(_e.InvalidParams,`Invalid arguments for prompt ${e}: ${i.error}`);return o(i.data,a)}}else{let o=r;return async(n,a)=>o(a)}}function uU(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}var zh={completion:{values:[],hasMore:!1}};function mU(e){let t=e;if(t.shape&&typeof t.shape=="object")return t.shape}function Ame(e){return e?.type==="optional"}function dU(e){return Ame(e)?e.def?.innerType??e:e}var yU=Symbol("swallowsErrorsAfterClose"),vU=class{_readBuffer;_started=!1;_closed=!1;constructor(e=qI.stdin,t=qI.stdout,r){this._stdin=e,this._stdout=t,this._readBuffer=new DI({maxBufferSize:r?.maxBufferSize})}onclose;onerror;onmessage;_ondata=e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(t){this.onerror?.(t),this.close().catch(()=>{})}};_onerror=e=>{this.onerror?.(e)};_onstdouterror=e=>{this._closed||(this.onerror?.(e),this.close().catch(()=>{}))};_onstdinclose=()=>{this.close().catch(()=>{})};async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0;for(let e of this._stdout.listeners("error"))e[yU]&&this._stdout.off("error",e);(this._stdin.readableEnded||this._stdin.destroyed)&&setImmediate(this._onstdinclose),this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror),this._stdin.on("end",this._onstdinclose),this._stdin.on("close",this._onstdinclose),this._stdout.on("error",this._onstdouterror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._closed||(this._closed=!0,this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.off("end",this._onstdinclose),this._stdin.off("close",this._onstdinclose),this._onstdouterror[yU]=!0,this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.())}send(e){return this._closed?Promise.reject(new Error("StdioServerTransport is closed")):new Promise((t,r)=>{let o=NI(e),n=!1,a=s=>{n||(n=!0,this._stdout.off("error",a),this._stdout.off("drain",i),r(s))},i=()=>{n||(n=!0,this._stdout.off("error",a),this._stdout.off("drain",i),t())};if(this._stdout.once("error",a),this._stdout.write(o)){if(n)return;n=!0,this._stdout.off("error",a),t()}else n||this._stdout.once("drain",i)})}};var SU={version:"1.0.0",date:"2026-11-16",headline:"PaceDynamics 1.0: a car from its suspension geometry to its lap time",notes:[{title:"One car, every tool",body:"Draw the suspension, fit the tyres, set up the aero, battery, brakes and powertrain, and drive the car round a track. Each part is edited in one place, and every tool reads the same car.",tool:"garage"},{title:"Lap time, and where it comes from",body:"Run a lap quasi-steady, transient or as the optimal lap, and see where one car or setup gains on another. Studies search the setup for you, and a logged session opens against the car it ran as.",tool:"laptime"},{title:"Release notes start here",body:"Help \u203A What\u2019s new lists every release from 1.0.0 on. The test versions before it are not listed."}]};var kU={version:"1.0.2",date:"2026-11-17",headline:"The website\u2019s opening drawing moves the upper wishbone as an engineer would",notes:[{title:"Down and out, front and rear",body:"The edit at the top of pacedyn.dev now moves the upper wishbone\u2019s two inboard pickups 15 mm down and 15 mm out, and the drawing shows where its instant centre goes. The suspension pictures below show the same edit."},{title:"The lap it moves, from the lap that follows it",body:"The large figure under the drawing is the quasi-steady lap, 0.338 s quicker, and says so. It follows a hardpoint to the hundredth; the driven lap moves in larger steps of pace."}]};var RU={version:"1.0.3",date:"2026-11-17",headline:"The website\u2019s replay loop rides lower behind the car, in daylight",notes:[{title:"Sky, hills and the road ahead",body:"The moving replay on pacedyn.dev follows the hill-climb car through the Pikes Peak hairpin from about a driver\u2019s eye height, in the replay\u2019s Daylight scenery, so the road ahead and the mountain are in the picture with the car."}]};var xU={version:"1.10.0",date:"2026-11-19",headline:"Menus you can scan by icon, and the logo back over the tools on a desktop",notes:[{title:"Find an item at a glance",body:"Every item in the project, Help and Account menus has an icon, related items are grouped, and pages that open on pacedyn.dev say so. The Library button shows its shelf, and Delete account stands out in red."},{title:"The logo stays put on a desktop",body:"On a wide window the logo sits over the tool rail again, and the project name has its room back. Phones and tablets keep it centred."},{title:"See who is who",body:"Avatars are larger in the Account menu, the team panel and the Library; the one in the top bar keeps its size."}]};var wU={version:"1.10.2",date:"2026-11-19",headline:"The terms say how far to trust a result",notes:[{title:"Check before you rely on it",body:"The terms of 19 November 2026 say results are model approximations that can be wrong. Check them for plausibility, and cross-check them independently before a safety-relevant decision, such as a load-bearing part or the brakes."}]};var MU={version:"1.10.3",date:"2026-11-19",headline:"Confirmations and invitations arrive once",notes:[{title:"No more duplicate mails",body:"A purchase or cancellation confirmation, an invitation or a notice could arrive twice when two rounds of sending overlapped. Each mail is now taken by one round only, so it arrives once."}]};var _U={version:"1.11.0",date:"2026-11-19",headline:"When the terms change, the app says what changed and asks you to accept",notes:[{title:"Changed terms, in a band",body:"A band under the top bar names the new version and what changed, with a link to the text. Accept, or choose Later: until you accept, the terms you agreed to apply, and nothing in the app waits for your answer."}]};var AU={version:"1.2.0",date:"2026-11-17",headline:"Work on our server waits its turn, and a cancel before it starts costs nothing",notes:[{title:"One queue",body:"Optimal laps, server runs of a study and fits of many sessions now wait in one queue and are taken up in turn. A job keeps its place however long it waits."},{title:"Cancel before it starts",body:"Cancelling an Optimal lap or a server run that has not started ends it at once and costs nothing. One that is running stops within seconds, counting what it used."},{title:"Restarts",body:"If our server restarts, a server run carries on from the starts it finished. A fit that was running ends without charge and asks to be started again."}]};var CU={version:"1.3.0",date:"2026-11-17",headline:"Transient lap times follow your edits where the line limit sets the pace",notes:[{title:"The lap at the line limit",body:"Where staying within the line limit sets a car\u2019s pace, the Transient lap is now read at the limit itself, between the last run inside it and the first outside. A small edit moves the lap by a small amount, not by a whole step of the search."},{title:"Which run you are watching",body:"The replay plays the quickest run driven, which can be a little slower than the lap shown; the note under it gives both times. Gaps to other cars, in the replay too, are between the laps shown."}]};var TU={version:"1.4.1",date:"2026-11-17",headline:"In Daylight, the ground beside a road climbs as a bank, not a sheer wall",notes:[{title:"Cuttings that look like cuttings",body:"Where the hillside stands above the road, the replay\u2019s Daylight scenery now slopes it back from the road\u2019s edge, steepening as it climbs. It rose as a sheer, pleated wall, as before the Pikes Peak hairpin in the website\u2019s loop."}]};var PU={version:"1.4.2",date:"2026-11-17",headline:"The website quotes the hill climb\u2019s Transient laps as the app now shows them",notes:[{title:"Where does the lap go?",body:"The website\u2019s hill-climb comparison now reads 8:05.702 against 7:59.419 for the big-wing copy, 6.283 s apart: the laps the app shows since it reads them at the line limit. Its Overview and replay pictures are new captures."}]};var FU={version:"1.5.0",date:"2026-11-17",headline:"Work waiting for your team\u2019s own machine says so, and when it was last seen",notes:[{title:"Waiting for your team\u2019s machine",body:"An Optimal lap or a fit of many sessions waiting for your team\u2019s own machine now says which one and when it was last seen, e.g. \u201CWaiting for workshop-pc, last seen 2 h ago\u201D. It runs there once the machine is back."},{title:"Your team\u2019s machines",body:"The Team dialog lists your team\u2019s machines: version, when each was last seen and how much waits for it. Owners and admins can cancel everything waiting for a machine that is away."},{title:"Deleting a fit",body:"Deleting a fit of many sessions that has not started now cancels it too, at no cost. One that is running stops within seconds."}]};var $U={version:"1.5.2",date:"2026-11-17",headline:"Inspect no longer fails when two runs of a long course are shown",notes:[{title:"A saved run beside a long lap",body:"With a saved run opened beside the car on a course as long as Pikes Peak, Laptime \u203A Inspect stopped with \u201CLaptime could not draw this project\u201D. Its g-g card now draws both runs."}]};var IU={version:"1.5.3",date:"2026-11-18",headline:"A study\u2019s roll-centre height curves read the height its target asks for",notes:[{title:"RC height (chassis) on the study\u2019s curves",body:"The roll-centre height curves in Studies \u203A Run were measured from the survey\u2019s ground. They now draw RC height (chassis), as Kinematics names it, so at the design ride they start at the static height the target reads."}]};var EU={version:"1.5.4",date:"2026-11-18",headline:"The wait quoted before an optimal lap is measured with today\u2019s solver",notes:[{title:"An honest wait before a solve",body:"The wait shown before an optimal lap was measured again with today\u2019s solver: about 6\u201312 minutes for one car on FSG, where it said 7\u201311. The car sets most of the spread, so an easy car finishes near the low end."}]};var LU={version:"1.5.5",date:"2026-11-18",headline:"A new privacy notice: who handles your requests to the app",notes:[{title:"Who handles your requests",body:"The privacy notice of 18 November names who now carries every request to the app and keeps its log, still for 30 days. Nothing changes in how you use the app, and you stay signed in."}]};var DU={version:"1.6.0",date:"2026-11-18",headline:"Inspect shows where on its aero map each car runs, weighted by the air it meets",notes:[{title:"Aero map with the lap on it",body:"Inspect \u2192 Aero platform opens with each car\u2019s aero map and its lap drawn on it. Lines hold the densest half and 90 % of the lap\u2019s dynamic pressure \xD7 time, so the slow corners count for little. Hover a point to see it on the track."},{title:"Three numbers per car",body:"Under the map: the CL the lap actually got, how far the aero balance moved (10th to 90th percentile) and how much of the lap ran outside the model\u2019s data. Pick a stretch and they read that stretch."},{title:"Aero balance bands",body:"A second card shows how the front share of the downforce is spread over the lap, weighted the same way, every car on the same bands."}]};var NU={version:"1.6.1",date:"2026-11-18",headline:"The 3-D view keeps its proportions when it leaves Orthographic",notes:[{title:"No stretched car after Orthographic",body:"If the 3-D view changed size while Orthographic was on, for example because the side panels were hidden, turning Orthographic off drew the car stretched sideways until the next resize. It now draws at the view\u2019s size straight away."}]};var OU={version:"1.7.0",date:"2026-11-18",headline:"The aero map in Inspect reads the grip-limited and the power-limited part of a lap apart",notes:[{title:"Grip or power",body:"Inspect\u2019s aero cards can show only the samples where the tyres were the limit, where downforce is speed, or only those where the powertrain was, where the drag is what counts. The map, the numbers and the balance bands follow."},{title:"Drag and the split",body:"Under the map each car now shows its CD, weighted the same way as its CL, and how its lap\u2019s dynamic pressure \xD7 time splits between grip-limited and power-limited."}]};var zU={version:"1.8.0",date:"2026-11-18",headline:"Work on a phone or tablet, and drive with touch controls",notes:[{title:"The workspace fits your screen",body:"A centered logo and compact project menu leave more room in the one-row header. Secondary actions live in More; Laptime\u2019s comparison controls expand from a summary. Charts and dialogs fit the screen."},{title:"Results stay within reach",body:"Tool tabs stay in one scrolling row. Dynamics folds tyre charts below narrow 3-D views, leaving the car full width. Replay stacks its picture, channels and telemetry, with playback controls kept visible."},{title:"Drive with your thumbs",body:"Touchscreens get steering, brake and throttle buttons: hold steering and a pedal together. Cancelling a touch or switching away releases the controls. On phones the Session panel follows the driving scene."}]};var VU={version:"1.9.0",date:"2026-11-19",headline:"Use cases on pacedyn.dev: five common jobs taken through the app, step by step",notes:[{title:"Use cases",body:"A new page on the website takes five jobs through the app, step by step: simulate a hardpoint change, set brake bias with a proportioning valve, choose a final drive ratio, optimise roll centres, fit tyre data."}]};var Eme={"./releases/1.0.0.ts":SU,"./releases/1.0.2.ts":kU,"./releases/1.0.3.ts":RU,"./releases/1.10.0.ts":xU,"./releases/1.10.2.ts":wU,"./releases/1.10.3.ts":MU,"./releases/1.11.0.ts":_U,"./releases/1.2.0.ts":AU,"./releases/1.3.0.ts":CU,"./releases/1.4.1.ts":TU,"./releases/1.4.2.ts":PU,"./releases/1.5.0.ts":FU,"./releases/1.5.2.ts":$U,"./releases/1.5.3.ts":IU,"./releases/1.5.4.ts":EU,"./releases/1.5.5.ts":LU,"./releases/1.6.0.ts":DU,"./releases/1.6.1.ts":NU,"./releases/1.7.0.ts":OU,"./releases/1.8.0.ts":zU,"./releases/1.9.0.ts":VU};var Lme=Object.values(Eme).sort((e,t)=>Dme(t.version,e.version)),jo=Lme[0];function Dme(e,t){let r=e.split(".").map(Number),o=t.split(".").map(Number);for(let n=0;n<Math.max(r.length,o.length);n++){let a=(r[n]??0)-(o[n]??0);if(a!==0)return a<0?-1:1}return 0}import{createHash as Nme,randomBytes as ZI}from"node:crypto";import{createServer as Ome}from"node:http";import{spawn as zme}from"node:child_process";import{chmod as Vme,mkdir as jme,readFile as Bme,rename as Ume,rm as BU,writeFile as Gme}from"node:fs/promises";import{homedir as qme}from"node:os";import{join as Vh}from"node:path";async function jU(e,t={}){let r=e.replace(/\/+$/,""),o=t.fetchImpl??fetch,n=[`${r}/.well-known/oauth-authorization-server/auth/v1`,`${r}/auth/v1/.well-known/oauth-authorization-server`],a=[];for(let i of n){let s=new AbortController,c=setTimeout(()=>s.abort(),t.timeoutMs??8e3);try{let l=await o(i,{signal:s.signal,headers:{accept:"application/json"}});if(!l.ok){a.push(`${i} \u2192 ${l.status}`);continue}let u=await l.json();if(!u?.issuer||!u.authorization_endpoint||!u.token_endpoint){a.push(`${i} \u2192 a document with no issuer or endpoints`);continue}return u}catch(l){a.push(`${i} \u2192 ${l instanceof Error?l.message:String(l)}`)}finally{clearTimeout(c)}}throw new Error(`the account service published no authorization-server metadata (${a.join("; ")}). Enable the OAuth server on the project \u2014 docs/hosting.md has the runbook.`)}var Hme="openid email profile offline_access",Kme=24*3600*1e3,UU=168*3600*1e3,Wme=600*1e3,Bo=class extends Error{};function GU(e=process.env,t=process.platform,r=qme()){return e.PACEDYN_CONFIG_DIR?e.PACEDYN_CONFIG_DIR:t==="win32"?Vh(e.APPDATA||Vh(r,"AppData","Roaming"),"PaceDynamics"):Vh(e.XDG_CONFIG_HOME||Vh(r,".config"),"pacedyn")}var XI=e=>e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function Yme(e){let t=e.split(".")[1];if(!t)return{};try{return JSON.parse(Buffer.from(t.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"))}catch{return{}}}function Zme(e){let[t,r]=process.platform==="darwin"?["open",[e]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{let o=zme(t,r,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}var ex=class{cfg;file;doFetch;now;metadata=null;checking=null;pending=null;constructor(t){this.cfg=t,this.file=Vh(t.dir,"credentials.json"),this.doFetch=t.fetchImpl??fetch,this.now=t.now??Date.now}get redirectUri(){return`http://localhost:${this.cfg.port}/callback`}async stored(){let t;try{t=await Bme(this.file,"utf8")}catch{return null}try{let r=JSON.parse(t);return r.accountUrl!==this.cfg.url||r.clientId!==this.cfg.clientId||!r.refreshToken?null:r}catch{return null}}async save(t){await jme(this.cfg.dir,{recursive:!0,mode:448});let r=`${this.file}.${ZI(4).toString("hex")}.tmp`;await Gme(r,JSON.stringify(t,null,2),{mode:384}),await Vme(r,384),await Ume(r,this.file)}async signOut(){let t=await this.stored()!==null;return await BU(this.file,{force:!0}),t}async server(){return this.metadata||(this.metadata=await jU(this.cfg.url,{fetchImpl:this.doFetch})),this.metadata}credentialsFrom(t,r){if(!t.access_token||!t.refresh_token)throw new Error("the account service answered without tokens");let o=Yme(t.access_token),n=typeof o.exp=="number"?o.exp*1e3:this.now()+1e3*(t.expires_in??3600);return{accountUrl:this.cfg.url,clientId:this.cfg.clientId,accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:n,verifiedAt:this.now(),user:{id:typeof o.sub=="string"?o.sub:r?.user.id??"",email:typeof o.email=="string"?o.email:r?.user.email??null}}}async token(t){let r=await this.server(),o=await this.doFetch(r.token_endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams({...t,client_id:this.cfg.clientId}).toString(),signal:AbortSignal.timeout(15e3)}),n=await o.text(),a={};try{a=n?JSON.parse(n):{}}catch{a={error:`HTTP ${o.status}`}}return{status:o.status,reply:a}}async ensure(){return this.checking??=this.check().finally(()=>{this.checking=null}),this.checking}async check(){let t=await this.stored();if(!t)throw new Bo(jh());let r=this.now();if(r<t.expiresAt-6e4&&r-t.verifiedAt<Kme)return t;let o;try{let n=await this.stored()??t;o=await this.token({grant_type:"refresh_token",refresh_token:n.refreshToken})}catch(n){if(r-t.verifiedAt<UU)return t;throw new Bo(`The account service has not been reachable for over a week (${n instanceof Error?n.message:String(n)}). Connect to the internet, then try again.`)}if(o.status>=200&&o.status<300&&o.reply.access_token){let n=this.credentialsFrom(o.reply,t);return await this.save(n),n}if(o.status===400||o.status===401||o.status===403){let n=await this.stored();if(n&&n.refreshToken!==t.refreshToken&&n.verifiedAt>t.verifiedAt)return n;throw await BU(this.file,{force:!0}),new Bo(`Your PaceDynamics sign-in has ended (${o.reply.error_description??o.reply.error??`HTTP ${o.status}`}). ${jh()}`)}if(r-t.verifiedAt<UU)return t;throw new Bo(`The account service answered HTTP ${o.status} for over a week. ${jh()}`)}async signIn(t,r=Wme){if(this.pending)return t?.(this.pending.url),this.pending;let o=await this.server(),n=XI(ZI(32)),a=XI(Nme("sha256").update(n).digest()),i=XI(ZI(16)),s=new URL(o.authorization_endpoint);s.search=new URLSearchParams({response_type:"code",client_id:this.cfg.clientId,redirect_uri:this.redirectUri,scope:Hme,state:i,code_challenge:a,code_challenge_method:"S256"}).toString();let c,l,u=new Promise((y,v)=>{c=y,l=v}),m=[],p=()=>{for(let y of m)y.close();clearTimeout(d),this.pending=null},d=setTimeout(()=>{p(),l(new Bo("The sign-in was not finished in the browser in time. Try again."))},r);d.unref();let f=(y,v)=>{let k=new URL(y.url??"/",this.redirectUri);if(k.pathname!=="/callback"){v.writeHead(404).end();return}let x=(w,M,T)=>{v.writeHead(w,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),v.end(`<!doctype html><meta charset="utf-8"><title>${M}</title><body style="font:16px system-ui,sans-serif;max-width:32em;margin:15vh auto;padding:0 16px"><h1 style="font-size:20px">${M}</h1><p>${T}</p></body>`)};if(k.searchParams.get("state")!==i){x(400,"This sign-in link is not the one this machine started","Start the sign-in again from your assistant or terminal.");return}let S=k.searchParams.get("error"),R=k.searchParams.get("code");if(S||!R){x(400,"Not signed in",S==="access_denied"?"You declined. Nothing was shared.":"The account service did not send a code."),p(),l(new Bo(S==="access_denied"?"The sign-in was declined in the browser.":`The sign-in failed: ${k.searchParams.get("error_description")??S??"no code"}`));return}this.token({grant_type:"authorization_code",code:R,redirect_uri:this.redirectUri,code_verifier:n}).then(async({status:w,reply:M})=>{if(w<200||w>=300)throw new Error(M.error_description??M.error??`HTTP ${w}`);let T=this.credentialsFrom(M);await this.save(T),x(200,"Signed in to PaceDynamics",`As ${T.user.email??"your account"}. You can close this tab and go back to your assistant.`),p(),c(T)}).catch(w=>{x(500,"Not signed in","The account service did not accept the sign-in. Try again."),p(),l(new Bo(`The sign-in failed: ${w instanceof Error?w.message:String(w)}`))})},h=y=>new Promise(v=>{let k=Ome(f);k.once("error",()=>v(!1)),k.listen(this.cfg.port,y,()=>{m.push(k),v(!0)})}),[g,b]=await Promise.all([h("127.0.0.1"),h("::1")]);if(!g&&!b)throw clearTimeout(d),new Error(`port ${this.cfg.port} on this machine is in use, so the sign-in has nowhere to return to. Close what holds it (another sign-in?) and try again.`);return this.pending={url:s.toString(),done:u},t?.(s.toString()),(this.cfg.openBrowser??Zme)(s.toString()),this.pending}};function jh(e=ro()){return`Sign in to PaceDynamics first: call the account_sign_in tool (it opens your browser), or run \`npx -y ${e} login\` in a terminal.`}function ro(){return"@pacedyn/mcp"}import{randomBytes as Nde}from"node:crypto";import{readdir as Ode,rename as zde,rm as Vde,stat as cE,readFile as SG,writeFile as jde}from"node:fs/promises";import{homedir as Bde}from"node:os";import{basename as lE,dirname as cx,isAbsolute as Ude,join as uE,resolve as kG}from"node:path";var En=(e,t,r)=>{let o=Math.min(t+r,e.length),n=o;for(let i=t;i<o;i++)if(e[i]===0){n=i;break}let a="";for(let i=t;i<n;i++)a+=String.fromCharCode(e[i]);return a.trim()};function JI(e){let t=e.byteLength;if(t<352)throw new Error(`not a MoTeC .ld file: ${t} bytes is shorter than its header`);let r=new DataView(e),o=new Uint8Array(e),n=[],a=r.getUint32(8,!0);if(a===0||a+124>t)throw new Error(`not a MoTeC .ld file: channel list at ${a} is outside a ${t}-byte file`);let i=[],s=new Set,c=a;for(;c!==0;){if(s.has(c)){n.push(`channel list loops back to offset ${c}; stopped there`);break}if(c+124>t){n.push(`channel descriptor at ${c} runs past the end of the file; stopped there`);break}if(s.size>=4096){n.push("stopped after 4096 channels; the list did not end");break}s.add(c);let u=r.getUint32(c+8,!0),m=r.getUint32(c+12,!0),p=r.getUint16(c+18,!0),d=r.getUint16(c+20,!0),f=r.getUint16(c+22,!0),h={family:p,width:d,shift:r.getInt16(c+24,!0),mul:r.getInt16(c+26,!0),scale:r.getInt16(c+28,!0),decimalPlaces:r.getInt16(c+30,!0)},g=En(o,c+32,32),b=r.getUint32(c+4,!0),y=Qme(r,p,d);if(!y)n.push(`channel "${g}": unknown storage (family ${p}, ${d} bytes); skipped`);else if(u+m*d>t)n.push(`channel "${g}": ${m} samples at ${u} run past the end of the file; skipped`);else{let v=new Float64Array(m),k=h.scale===0?1:h.scale,x=(h.mul===0?1:h.mul)/k*10**-h.decimalPlaces,S=p===7&&x===1&&h.shift===0;for(let R=0;R<m;R++){let w=y(u+R*d);v[R]=S?w:w*x+h.shift}i.push({name:g,shortName:En(o,c+64,8),unit:En(o,c+72,12),logRate:f,data:v,storage:h})}c=b}i.length===0&&n.push("the file holds no readable channel");let l=Jme(o,r,a);return{device:En(o,74,8),serial:r.getUint32(66,!0),date:En(o,94,16),time:En(o,126,16),driver:En(o,158,64),vehicle:En(o,222,64),venue:En(o,350,64),channels:i,warnings:n,...l.length?{comments:l}:{}}}var qU=1572,tx=128,Xme=e=>e.length>0&&/^[\x20-\x7e\u00a0-\u00ff\t\r\n]*$/.test(e);function Jme(e,t,r){let o=t.getUint32(12,!0),n=Math.min(r,o||r,e.length),a=[];qU+64<=n&&a.push(En(e,qU,64));let i=t.getUint32(36,!0);return i>=352&&i+tx<=n&&(a.push(En(e,i,64),En(e,i+64,64)),i+tx<n&&a.push(En(e,i+tx,Math.min(1024,n-i-tx)))),a.filter(Xme)}function Qme(e,t,r){return t===7?r===4?o=>e.getFloat32(o,!0):r===2?o=>ede(e.getUint16(o,!0)):r===8?o=>e.getFloat64(o,!0):null:t===0||t===3?r===2?o=>e.getInt16(o,!0):r===4?o=>e.getInt32(o,!0):r===1?o=>e.getInt8(o):null:null}function ede(e){let t=e&32768?-1:1,r=e>>10&31,o=e&1023;return r===0?t*o*2**-24:r===31?o?NaN:t*(1/0):t*(o+1024)*2**(r-25)}var KU={family:7,width:8,shift:0,mul:1,scale:1,decimalPlaces:0},tde={venue:"venue",track:"venue",circuit:"venue",vehicle:"vehicle",car:"vehicle",driver:"driver",racer:"driver",user:"driver",device:"device","data source":"device",logger:"device",date:"date","log date":"date",time:"time","log time":"time","sample rate":"rate","sampling rate":"rate"};function WU(e){let t=Math.min(e.length,4096);if(t===0)return!1;let r=0;for(let o=0;o<t;o++){let n=e[o];if(n===9||n===10||n===13||n>=32&&n<127||n>=160)r++;else if(n===0)return!1}return r/t>.95}function YU(e,t={}){let r=[],n=(e.charCodeAt(0)===65279?e.slice(1):e).split(/\r\n|\n|\r/),a=t.delimiter??rde(n),i=a!==",",s={},c=-1,l=[];for(let R=0;R<n.length&&c<0&&R<400;R++){let w=rx(n[R],a);if(!(w.length===0||w.length===1&&w[0]==="")){if(ade(w,n,R,a,i)){c=R,l=[w];break}for(let M=0;M+1<w.length;M+=1){let T=tde[w[M].trim().toLowerCase()];T&&w[M+1].trim()&&s[T]===void 0&&(s[T]=w[M+1].trim())}}}if(c<0)throw new Error("no row of channel names followed by numbers was found \u2014 is this a logger export?");let u=l[0].map(R=>R.trim());if(u.length>2048)throw new Error(`${u.length} columns is more than this reader takes (2048)`);let m=c+1,p=u.map(()=>""),d=ode(n,m);if(d>=0){let R=rx(n[d],a);R.filter(M=>Bh(M,i)!==null).length<R.length/2&&(p=u.map((M,T)=>(R[T]??"").trim()),m=d+1)}let f=u.map((R,w)=>{let M=/^(.*?)\s*[[(]\s*([^\])]*)\s*[\])]\s*$/.exec(R);return M&&M[1]&&!p[w]?(p[w]=M[2],M[1].trim()):R}),h=f.length,g=f.map(()=>[]),b=new Array(h).fill(NaN),y=0,v=0;for(let R=m;R<n.length;R++){let w=n[R];if(!w||!w.trim())continue;let M=rx(w,a);if(Bh(M[0]??"",i)===null){if(y++,y>5)break;continue}for(let A=0;A<h;A++){let _=Bh(M[A]??"",i);_!==null&&(b[A]=_),g[A].push(b[A])}if(v+=h,v>8e7){r.push(`stopped after ${g[0].length} rows: the table is larger than one import takes`);break}}if((g[0]?.length??0)<2)throw new Error("the table has a header but fewer than two rows of numbers");y>0&&r.push(`${y} row${y===1?"":"s"} after the header did not start with a number and were skipped`);let x=f.findIndex((R,w)=>HU(R)&&w===0)>=0?0:f.findIndex(R=>HU(R)),S=s.rate?Number.parseFloat(s.rate.replace(",",".")):NaN;return Uh({names:f,units:p,values:g,timeCol:x,statedRate:S},{device:s.device??"",date:s.date??"",time:s.time??"",driver:s.driver??"",vehicle:s.vehicle??"",venue:s.venue??""},r)}function Uh(e,t,r=[]){let{names:o,units:n,values:a,timeCol:i}=e,s,c=a;if(i>=0){let m=a[i].map(h=>h*nde(n[i])),p=[];for(let h=1;h<m.length;h++){let g=m[h]-m[h-1];Number.isFinite(g)&&g>0&&p.push(g)}if(p.length<1)throw new Error("the time column never advances");p.sort((h,g)=>h-g);let d=p[Math.floor(p.length/2)];s=QI(1/d);let f=p.filter(h=>Math.abs(h-d)>.25*d).length;(f>p.length*.02||m.length!==p.length+1)&&(c=ide(a,m,s),r.push(`the time column is not evenly spaced (${f} of ${p.length} steps off ${(d*1e3).toFixed(1)} ms); resampled to ${s} Hz by holding each row until the next`))}else{let m=e.statedRate??NaN;if(!(m>0))throw new Error("the table has no time column and states no sample rate");s=QI(m),r.push(`no time column; the stated ${s} Hz is taken as the clock`)}let l=[],u=new Set;return o.forEach((m,p)=>{if(p===i||!m)return;let d=m;for(let h=2;u.has(d.toLowerCase());h++)d=`${m} ${h}`;u.add(d.toLowerCase());let f=Float64Array.from(c[p]);XU(f)&&l.push({name:d,shortName:"",unit:n[p]??"",logRate:s,data:f,storage:KU})}),l.length===0&&r.push("the file holds no readable channel"),{...t,serial:0,channels:l,warnings:r}}function ZU(e,t,r,o,n){let a=[];for(let u=1;u<r.length;u++){let m=r[u]-r[u-1];Number.isFinite(m)&&m>0&&a.push(m)}if(!a.length)return null;a.sort((u,m)=>u-m);let i=QI(1/a[Math.floor(a.length/2)]),s=Math.max(2,Math.floor((r[r.length-1]-n)*i)+1),c=new Float64Array(s).fill(NaN),l=-1;for(let u=0;u<s;u++){let m=n+u/i;for(;l+1<r.length&&r[l+1]<=m+1e-9;)l++;l>=0&&(c[u]=o[l])}return XU(c)?{name:e,shortName:"",unit:t,logRate:i,data:c,storage:KU}:null}function XU(e){let t=-1;for(let r=0;r<e.length;r++)if(Number.isFinite(e[r])){t=r;break}if(t<0)return!1;for(let r=0;r<t;r++)e[r]=e[t];return!0}function rde(e){let t=e.filter(r=>r.trim()).slice(0,60);for(let r of[" ",";"])if(t.filter(n=>n.includes(r)).length>=Math.max(2,t.length*.5))return r;return","}function rx(e,t){let r=[],o="",n=!1;for(let a=0;a<e.length;a++){let i=e[a];n?i==='"'?e[a+1]==='"'?(o+='"',a++):n=!1:o+=i:i==='"'?n=!0:i===t?(r.push(o),o=""):o+=i}return r.push(o),r}function Bh(e,t){let r=e.trim();if(!r)return null;t&&r.includes(",")&&!r.includes(".")&&(r=r.replace(",","."));let o=Number(r);if(Number.isNaN(o))return/^[+-]?nan$/i.test(r)?NaN:null;if(!Number.isFinite(o))return NaN;let n=r.charCodeAt(r[0]==="-"||r[0]==="+"?1:0);return!(n>=48&&n<=57||n===46)||r.length>1&&/^[+-]?0[xXbBoO]/.test(r)?null:o}function HU(e){return/^(time|timestamp|t|elapsed time|session time|sim time|time_s|times)$/i.test(e.trim())}function nde(e){let t=e.trim().toLowerCase();return t==="ms"?.001:t==="us"||t==="\xB5s"?1e-6:t==="min"?60:1}function QI(e){return e>=5?Math.round(e):Math.round(e*100)/100}function ode(e,t){for(let r=t;r<e.length&&r<t+5;r++)if(e[r]&&e[r].trim())return r;return-1}function ade(e,t,r,o,n){if(e.length<2||e.filter(s=>s.trim()&&Bh(s,n)===null).length<Math.max(2,e.length*.6))return!1;let i=0;for(let s=r+1;s<t.length&&i<3;s++){if(!t[s]||!t[s].trim())continue;i++;let c=rx(t[s],o),l=c.filter(m=>Bh(m,n)!==null).length,u=Math.abs(c.length-e.length)<=Math.max(1,.2*e.length);if(l>=Math.max(2,e.length*.6)&&u)return!0}return!1}function ide(e,t,r){let o=t.find(Number.isFinite)??0,n=t[t.length-1],a=Math.max(2,Math.floor((n-o)*r)+1),i=e.map(()=>new Array(a)),s=0;for(let c=0;c<a;c++){let l=o+c/r;for(;s+1<t.length&&t[s+1]<=l+1e-9;)s++;for(let u=0;u<e.length;u++)i[u][c]=e[u][s]}return i}var JU={kmh:"km/h",mph:"mph",knots:"kn","m/s":"m/s",g:"g",m:"m",feet:"ft",ft:"ft","deg/s":"deg/s"},QU={satellites:"",time:"s",latitude:"deg",longitude:"deg",heading:"deg",height:"m","yaw rate":"deg/s",gps_sats:"",glonass_sats:"","solution type":"","dgps status":"",avifileindex:"",avisynctime:"",avitime:""};function sde(e){let t=e.trim().toLowerCase();if(t in QU)return{name:t,unit:QU[t]};let r=/^(.*\S)\s+(\S+)$/.exec(t);return r&&r[2]in JU&&/^(velocity|vertical velocity|lat accel|long accel|distance|[xy] position|velocity quality|vertical velocity quality)/.test(r[1])?{name:r[1],unit:JU[r[2]]}:null}function cde(e){let t=new Map,r=[],o=r;for(let a of e){let i=/^\s*\[([^\]]+)\]\s*$/.exec(a);i?(o=[],t.set(i[1].trim().toLowerCase(),o)):o.push(a)}let n=a=>{for(;a.length&&!a[0].trim();)a.shift();for(;a.length&&!a[a.length-1].trim();)a.pop()};n(r);for(let a of t.values())n(a);return{preamble:r,sections:t}}var lde=e=>{let t=Math.floor(e/1e4),r=Math.floor(e/100)%100;return t*3600+r*60+(e-Math.floor(e/100)*100)};function eG(e){let t=[],r=e.charCodeAt(0)===65279?e.slice(1):e,{preamble:o,sections:n}=cde(r.split(/\r\n|\n|\r/)),a=n.get("data");if(!a?.length)throw new Error("the .vbo has no [data] section");let i=(n.get("header")??[]).map(R=>R.trim()).filter(Boolean),s=(n.get("column names")??[]).join(" ").trim().split(/\s+/).filter(Boolean),c=s.length||i.length;if(!c)throw new Error("the .vbo names none of its columns ([header] and [column names] are empty)");s.length&&i.length&&s.length!==i.length&&t.push(`[header] lists ${i.length} channels and [column names] ${s.length}; the short names are used`);let l=i.length===c?i:s,u=(n.get("channel units")??[]).map(R=>R.trim()),m=0,p=[],d=[];for(let R of l){let w=sde(R);w?(p.push(w.name),d.push(w.unit)):(p.push(R.trim()),d.push(u[m++]??""))}u.length&&m!==u.length&&t.push(`[channel units] holds ${u.length} units for ${m} channels; check the units on the Channels step`);let f=p.map(()=>[]),h=0;for(let R of a){if(!R.trim())continue;let w=R.trim().split(/\s+/);if(w.length<c){h++;continue}for(let M=0;M<c;M++){let T=Number(w[M]);f[M].push(Number.isFinite(T)?T:NaN)}}if(f[0].length<2)throw new Error("the .vbo has fewer than two rows of samples");h&&t.push(`${h} row${h===1?"":"s"} in [data] had fewer than ${c} values and were skipped`);let g=p.indexOf("time");if(g>=0){let R=f[g],w=0,M=-1/0;for(let T=0;T<R.length;T++){let A=lde(R[T])+w;A<M-43200&&(w+=86400,A+=86400),R[T]=A,M=A}}let b=p.indexOf("latitude"),y=p.indexOf("longitude");b>=0&&(f[b]=f[b].map(R=>R/60)),y>=0&&(f[y]=f[y].map(R=>-R/60));let v=o.map(R=>/created on\s+(\S+)\s+(?:@|at)\s+(\S+)/i.exec(R)).find(Boolean),x=(n.get("comments")??[]).find(R=>/vbox|racelogic|racechrono|racebox|performancebox|video ?vbox/i.test(R))?.trim(),S=(n.get("circuit details")??[]).map(R=>/^\s*circuit\s+(.+)$/i.exec(R)).find(Boolean);return Uh({names:p,units:d,values:f,timeCol:g},{device:x||"Racelogic VBO",date:v?.[1]??"",time:v?.[2]??"",driver:"",vehicle:"",venue:S?.[1].trim()??""},t)}var tG={1:"a cell array",2:"a struct",3:"an object",5:"a sparse array"};function mi(e,t,r){if(t<0||t+8>e.byteLength)throw new Error("truncated MAT element tag");let o=e.getUint32(t,r);if(o>>>16!==0){let s=e.getUint16(t,r),c=e.getUint16(t+2,r);if(c>4)throw new Error("invalid MAT small-element length");return{type:s,start:t+4,length:c,next:t+8}}let a=e.getUint32(t+4,r);if(t+8+a>e.byteLength)throw new Error("truncated MAT element payload");let i=o===15||!(a&7)?0:8-(a&7);return{type:o,start:t+8,length:a,next:t+8+a+i}}function nx(e,t,r){let{start:o,length:n}=t,a=(i,s,c)=>{let l=new Float64Array(i);for(let u=0;u<i;u++)l[u]=c(o+u*s);return l};switch(t.type){case 9:return a(n>>3,8,i=>e.getFloat64(i,r));case 7:return a(n>>2,4,i=>e.getFloat32(i,r));case 1:return a(n,1,i=>e.getInt8(i));case 2:return a(n,1,i=>e.getUint8(i));case 3:return a(n>>1,2,i=>e.getInt16(i,r));case 4:return a(n>>1,2,i=>e.getUint16(i,r));case 5:return a(n>>2,4,i=>e.getInt32(i,r));case 6:return a(n>>2,4,i=>e.getUint32(i,r));case 12:return a(n>>3,8,i=>Number(e.getBigInt64(i,r)));case 13:return a(n>>3,8,i=>Number(e.getBigUint64(i,r)));default:throw new Error(`unsupported numeric element type ${t.type}`)}}function eE(e,t,r){if(t.type===16){let i=new Uint8Array(e.buffer,e.byteOffset+t.start,t.length);return new TextDecoder().decode(i)}let o=nx(e,t,r),n="",a=4096;for(let i=0;i<o.length;i+=a)n+=String.fromCharCode(...o.subarray(i,i+a));return n}async function ude(e){if(typeof DecompressionStream>"u")throw new Error("this file is compressed and no DecompressionStream is available to read it");let t=new DecompressionStream("deflate"),r=new Blob([e]).stream().pipeThrough(t),o=[],n=0;for await(let s of r)o.push(s),n+=s.length;let a=new Uint8Array(n),i=0;for(let s of o)a.set(s,i),i+=s.length;return a}function rG(e,t,r,o=!1,n=0,a={nodes:0}){if(n>32||++a.nodes>1e5)throw new Error("MAT nesting exceeds reader limits");let i=t.start,s=t.start+t.length,c=mi(e,i,r),l=e.getUint32(c.start,r),u=l&255,m=(l&2048)!==0;i=c.next;let p=mi(e,i,r),d=Array.from(nx(e,p,r),v=>v|0);if(d.some(v=>v<0))throw new Error("invalid MAT dimensions");i=p.next;let f=mi(e,i,r),h=eE(e,f,r);if(i=f.next,o&&(u===1||u===2||u===3)){let v;if(u===3){let w=mi(e,i,r);v=eE(e,w,r),i=w.next}let k=d.reduce((w,M)=>w*M,1),x=[];if(u!==1){let w=mi(e,i,r),M=nx(e,w,r)[0];i=w.next;let T=mi(e,i,r);if(i=T.next,!(M>0)||!Number.isInteger(M)||T.length%M)throw new Error("invalid MAT struct field table");for(let A=T.start;A<T.start+T.length;A+=M)x.push(new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset+A,M)).replace(/\0.*$/,""))}if(k*Math.max(1,x.length)>1e5-a.nodes)throw new Error("MAT container exceeds reader limits");let S=()=>{if(i+8>s)throw new Error("truncated MAT container");let w=mi(e,i,r);if(w.type!==14||w.start+w.length>s)throw new Error("invalid MAT container entry");i=w.next;let M=rG(e,w,r,!0,n+1,a);return M.value??{kind:"unsupported",why:M.skip??"unrecognised value"}};if(u===1){let w=Array.from({length:k},S);return{name:h,value:{kind:"cell",dims:d,entries:w}}}let R=Array.from({length:k},()=>{let w=new Map;for(let M of x)w.set(M,S());return w});return{name:h,value:{kind:"struct",dims:d,entries:R,...v?{className:v}:{}}}}if(u in tG)return{name:h,skip:tG[u]};if(u>15)return{name:h,skip:`unsupported MATLAB class ${u}`};if(i>=s)return{name:h,skip:"an array with no payload"};let g=mi(e,i,r);if(g.start+g.length>s)throw new Error("truncated MAT matrix");if(u===4){let v=eE(e,g,r);return{name:h,text:v,value:{kind:"text",text:v,dims:d}}}let b=nx(e,g,r);if(m)return{name:h,skip:"a complex array"};if(b.length!==d.reduce((v,k)=>v*k,1))throw new Error(`MAT array ${h} does not match its dimensions`);let y={name:h,dims:d,data:b};return{name:h,array:y,value:{kind:"numeric",array:y}}}async function ox(e,t={}){if(e.byteLength<128)throw new Error("not a MAT-file: shorter than its own header");let r=new DataView(e),o=new TextDecoder().decode(new Uint8Array(e,0,116)).replace(/\0+$/,"").trim(),n=r.getUint16(126,!0);if(n!==19785&&n!==18765)throw new Error("not a MATLAB Level 5 MAT-file (no endian indicator where one belongs)");let a=n===19785,i=new Map,s=new Map,c=[],l=t.nested?new Map:void 0,u=(p,d,f,h)=>{let g=d;for(;g+8<=f;){let b=mi(p,g,a);if(b.next>f||b.length<0)break;if(b.type===15){let y=new Uint8Array(p.buffer,p.byteOffset+b.start,b.length);h.push(ude(y).then(v=>{let k=new DataView(v.buffer,v.byteOffset,v.byteLength);u(k,0,v.byteLength,h)}))}else if(b.type===14){let y=rG(p,b,a,t.nested);l&&l.set(y.name,y.value??{kind:"unsupported",why:y.skip??"unrecognised value"}),y.skip?c.push({name:y.name,why:y.skip}):y.array?i.set(y.name,y.array):y.text!==void 0&&s.set(y.name,y.text)}g=b.next}},m=[];for(u(r,128,e.byteLength,m);m.length;)await m.shift();if(!i.size&&!s.size&&!c.length&&!l?.size)throw new Error("MAT-file contains no variables this reader recognises");return{header:o,numeric:i,text:s,skipped:c,...l?{variables:l}:{}}}var tE=/^(time|t|times|timestamp|time_s|sessiontime|session_time|elapsed_time)$/i,mde=/^(value|values|data|y|signal|samples)$/i,dde=/^(units?|unit_name)$/i,pde=/^(name|channel|channelname|channel_name)$/i,fde=/^(fs|rate|samplerate|sample_rate|samplingrate|frequency)$/i;function hde(e){let[t,r]=e.dims;return e.dims.length!==2||Math.min(t,r)!==1||Math.max(t,r)<2?null:e.data}var ax=e=>e?.kind==="numeric"?hde(e.array):null,Ms=e=>e?.kind==="text"?e.text.trim():void 0,gde=e=>e?.kind==="numeric"&&e.array.data.length===1?e.array.data[0]:void 0,Uo=(e,t)=>[...e].find(([r])=>t.test(r));function nG(e,t){if(t.kind!=="struct")return[];let r=[];return t.entries.forEach((o,n)=>{let a=ax(Uo(o,tE)?.[1]),i=ax(Uo(o,mde)?.[1]);!a||!i||a.length!==i.length||r.push({name:Ms(Uo(o,pde)?.[1])||(t.entries.length>1?`${e}(${n+1})`:e),unit:Ms(Uo(o,dde)?.[1])??"",t:a,v:i})}),r}async function oG(e){let t=await ox(e,{nested:!0}),r=t.variables??new Map,o=[],n=[...r],a=n.filter(([,g])=>ax(g)),i=n.filter(([,g])=>g.kind==="struct"&&g.entries.length===1&&!nG("",g).length);if(!a.length&&i.length===1&&n.every(([,g])=>g.kind!=="struct"||g===i[0][1])){let g=i[0][1].entries[0];r=new Map([...n.filter(([,b])=>b!==i[0][1]),...g])}let s={device:Ms(Uo(r,/^(device|logger|source)$/i)?.[1])||"MATLAB",date:Ms(Uo(r,/^(date|logdate|log_date)$/i)?.[1])??"",time:Ms(Uo(r,/^(time_of_day|logtime|log_time)$/i)?.[1])??"",driver:Ms(Uo(r,/^(driver|racer)$/i)?.[1])??"",vehicle:Ms(Uo(r,/^(vehicle|car)$/i)?.[1])??"",venue:Ms(Uo(r,/^(venue|track|circuit)$/i)?.[1])??""};for(let g of t.skipped)o.push(`${g.name||"a variable"} was not read: ${g.why}`);let c=[...r].flatMap(([g,b])=>nG(g,b));if(c.length){let g=Math.min(...c.map(v=>v.t[0]).filter(Number.isFinite)),b=[],y=new Set;for(let v of c){let k=v.name;for(let S=2;y.has(k.toLowerCase());S++)k=`${v.name} ${S}`;let x=ZU(k,v.unit,v.t,v.v,g);if(!x){o.push(`${v.name}: its time never advances, so it was left out`);continue}y.add(k.toLowerCase()),b.push(x)}return{...s,serial:0,channels:b,warnings:o}}let l=[...r].map(([g,b])=>({name:g,data:ax(b)})).filter(g=>g.data),u=new Map;for(let g of l)u.set(g.data.length,[...u.get(g.data.length)??[],g]);let m=[...u.values()].filter(g=>g.some(b=>tE.test(b.name))),p=gde(Uo(r,fde)?.[1]),d=m.sort((g,b)=>b.length-g.length)[0]??(p?[...u.values()].sort((g,b)=>b.length-g.length)[0]:void 0);if(!d||d.length<(m.length?2:1)){let g=[...r.keys()].slice(0,6).join(", ");throw new Error(`the MATLAB file holds no channels with a clock: neither one struct per channel with a time and a value, nor columns beside a time vector (it holds ${g||"nothing readable"})`)}let f=l.length-d.length;f&&o.push(`${f} vector${f===1?"":"s"} of another length than the clock were left out`);let h=d.map(g=>g.name);return Uh({names:h,units:h.map(()=>""),values:d.map(g=>Array.from(g.data)),timeCol:h.findIndex(g=>tE.test(g)),statedRate:p},s,o)}function aG(e){return/^MATLAB 7\.3 MAT-file/.test(String.fromCharCode(...e.subarray(0,24)))}var bde=e=>e.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi,(t,r)=>{let o=r.toLowerCase();return o.startsWith("#x")?String.fromCodePoint(Number.parseInt(o.slice(2),16)):o.startsWith("#")?String.fromCodePoint(Number.parseInt(o.slice(1),10)):{amp:"&",lt:"<",gt:">",quot:'"',apos:"'"}[o]??""});function iG(e){let t={};for(let r of e.matchAll(/([A-Za-z_][\w.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g))t[r[1]]=bde(r[2]??r[3]??"");return t}function sG(e){let t=[];for(let n of e.matchAll(/<Marker\b([^>]*)>/g)){let a=iG(n[1]);if(a.ClassName!==void 0&&a.ClassName.toUpperCase()!=="BCN")continue;let i=Number(a.Time);Number.isFinite(i)&&i>=0&&t.push(i)}t.sort((n,a)=>n-a);let r={},o=/<Details\b[^>]*>([\s\S]*?)<\/Details>/i.exec(e)?.[1]??"";for(let n of o.matchAll(/<(String|Numeric)\b([^>]*)>/g)){let a=iG(n[2]);!a.Id||a.Value===void 0||(r[a.Id]=a.Unit?`${a.Value} ${a.Unit}`:a.Value)}return{beacons:t,details:r}}var yde=e=>Math.max(0,...e.channels.map(t=>t.data.length/(t.logRate||1)));function cG(e,t){if(Object.keys(t.details).length&&(e.details={...e.details,...t.details}),!t.beacons.length)return;let r=yde(e),o=t.beacons[t.beacons.length-1],n=[1,.001,1e-6].find(a=>o*a<=r+1);if(n===void 0){e.warnings.push(`the .ldx beacons run to ${o}, past the end of the log, and were left out`);return}e.beacons=t.beacons.map(a=>a*n)}var Gh=[".mf4",".mdf",".asc",".blf",".trc",".log",".dbc",".xrk",".drk",".xrz",".ibt"],vde=["ld","csv","vbo","mat"],uG=e=>vde.includes(e),lG=(e,t,r)=>String.fromCharCode(...e.subarray(t,Math.min(r,e.length))),Sde=e=>new TextDecoder("utf-8").decode(e.subarray(0,4096));function kde(e){return e.length<352?!1:new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!0)===64}function rE(e,t=""){let r=t.toLowerCase(),o=WU(e),n=lG(e,0,8);if(n.startsWith("PK")||n.startsWith("PK"))return"zip";if(n==="MDF "||n==="UnFinMF ")return"mdf";if(n.startsWith("LOGG"))return"can";if(/^MATLAB \d\.\d MAT-file/.test(lG(e,0,40)))return"mat";if(r.endsWith(".ld")||kde(e)&&!o)return"ld";if(o){let a=Sde(e),i=a.trimStart();return/<LDXFile[\s>]/i.test(a)?"ldx":/^\s*VERSION\s+"/m.test(a)&&/^\s*(BU_\s*:|BO_\s+\d+)/m.test(a)||/^\s*BO_\s+\d+\s+\w+\s*:/m.test(a)&&/^\s*SG_\s+\w+/m.test(a)?"dbc":/^\s*base\s+(hex|dec)\s+timestamps\s+(absolute|relative)/im.test(a)||/^\s*;\$FILEVERSION=/m.test(a)||/^\s*\(\d+\.\d+\)\s+\w+\s+[0-9A-Fa-f]{3,8}#/m.test(i)?"can":/^\[header\]\s*$/im.test(a)&&/^\[(column names|data)\]\s*$/im.test(a)||/^File created on /i.test(i)&&/^\[header\]/im.test(a)?"vbo":/^[<{]/.test(i)?"other":"csv"}return/\.(xrk|drk|xrz)$/i.test(r)?"xrk":/\.ibt$/i.test(r)?"ibt":/\.(mf4|mdf)$/i.test(r)?"mdf":/\.blf$/i.test(r)?"can":/\.zip$/i.test(r)?"zip":"other"}function nE(e){switch(e){case"mat":return"This is a MATLAB 7.3 file, which is not read here \u2014 save it again with save(\u2026, '-v7') or export the channels as CSV.";case"mdf":return"This is an ASAM MDF file (.mf4), which is not read here yet \u2014 export it as CSV from your logger\u2019s software or asammdf, decoding raw CAN with its DBC.";case"can":return"This is a raw CAN log, which is not read here yet \u2014 decode it with the bus\u2019s DBC to CSV first (your logger\u2019s software, cantools or asammdf).";case"dbc":return"This is a DBC, which describes a CAN bus but holds no samples \u2014 add the logged session as CSV or MoTeC .ld.";case"ldx":return"This is a MoTeC .ldx, the details beside a .ld with no samples in it \u2014 add the .ld itself.";case"xrk":return"AiM\u2019s own .xrk/.drk format cannot be read outside Race Studio \u2014 export the session as CSV there.";case"ibt":return"An iRacing .ibt is not readable here \u2014 export it to MoTeC .ld or CSV first.";case"zip":return"This zip holds no log that reads here \u2014 add the log itself, as .ld, CSV, .vbo or .mat.";default:return"Not a log this reader knows \u2014 add a MoTeC .ld, a CSV, a .vbo or a .mat."}}var di=class extends Error{constructor(r,o,n){super(r);this.kind=o;this.refused=n;this.name="LogReadError"}kind;refused};var oE=e=>e.length>=4&&e[0]===80&&e[1]===75&&(e[2]===3&&e[3]===4||e[2]===5&&e[3]===6),no=e=>e.slice(e.lastIndexOf("/")+1);async function aE(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=Rde(t);if(r<0)throw new Error("This zip is damaged or cut short: its table of contents is missing.");let o=t.getUint16(r+10,!0),n=t.getUint32(r+16,!0);if(o===65535||n===4294967295)throw new Error("This zip is a ZIP64 archive, which is not read here \u2014 unpack it and add the log inside.");let a=[],i=0;for(let s=0;s<o;s++){if(n+46>e.length||t.getUint32(n,!0)!==33639248)throw new Error("This zip is damaged: an entry in its table of contents is unreadable.");let c=t.getUint16(n+8,!0),l=t.getUint16(n+10,!0),u=t.getUint32(n+20,!0),m=t.getUint32(n+24,!0),p=t.getUint16(n+28,!0),d=t.getUint16(n+30,!0),f=t.getUint16(n+32,!0),h=t.getUint32(n+42,!0),g=e.subarray(n+46,n+46+p),b=new TextDecoder(c&2048?"utf-8":"latin1").decode(g).replace(/\\/g,"/");if(n+=46+p+d+f,b.endsWith("/")||b.startsWith("__MACOSX/")||no(b).startsWith("._"))continue;if(c&1)throw new Error(`${no(b)} in this zip is encrypted \u2014 unpack it and add the log inside.`);if(u===4294967295||m===4294967295)throw new Error("This zip is a ZIP64 archive, which is not read here \u2014 unpack it and add the log inside.");if(i+=m,i>1073741824)throw new Error("This zip unpacks to more than one import takes (1 GB).");if(h+30>e.length||t.getUint32(h,!0)!==67324752)throw new Error(`This zip is damaged: ${no(b)} is not where its table of contents says.`);let y=h+30+t.getUint16(h+26,!0)+t.getUint16(h+28,!0),v=e.subarray(y,y+u);if(v.length<u)throw new Error(`This zip is cut short inside ${no(b)}.`);if(l===0)a.push({path:b,bytes:v});else if(l===8)a.push({path:b,bytes:await xde(v)});else throw new Error(`${no(b)} in this zip is packed a way this reader does not unpack (method ${l}) \u2014 unpack it and add the log inside.`)}return a}function Rde(e){let t=e.byteLength-22;for(let r=t;r>=0&&r>=t-65535;r--)if(e.getUint32(r,!0)===101010256)return r;return-1}async function xde(e){let t=new Blob([e]).stream().pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}function mG(e){let t=e.map(m=>new TextEncoder().encode(m.path)),r=e.map(m=>wde(m.bytes)),o=e.reduce((m,p,d)=>m+30+t[d].length+p.bytes.length,0),n=t.reduce((m,p)=>m+46+p.length,0),a=new Uint8Array(o+n+22),i=new DataView(a.buffer),s=33,c=0,l=[];e.forEach((m,p)=>{l.push(c),i.setUint32(c,67324752,!0),i.setUint16(c+4,20,!0),i.setUint16(c+6,2048,!0),i.setUint16(c+8,0,!0),i.setUint16(c+10,0,!0),i.setUint16(c+12,s,!0),i.setUint32(c+14,r[p],!0),i.setUint32(c+18,m.bytes.length,!0),i.setUint32(c+22,m.bytes.length,!0),i.setUint16(c+26,t[p].length,!0),i.setUint16(c+28,0,!0),a.set(t[p],c+30),a.set(m.bytes,c+30+t[p].length),c+=30+t[p].length+m.bytes.length});let u=c;return e.forEach((m,p)=>{i.setUint32(c,33639248,!0),i.setUint16(c+4,20,!0),i.setUint16(c+6,20,!0),i.setUint16(c+8,2048,!0),i.setUint16(c+10,0,!0),i.setUint16(c+12,0,!0),i.setUint16(c+14,s,!0),i.setUint32(c+16,r[p],!0),i.setUint32(c+20,m.bytes.length,!0),i.setUint32(c+24,m.bytes.length,!0),i.setUint16(c+28,t[p].length,!0),i.setUint32(c+42,l[p],!0),a.set(t[p],c+46),c+=46+t[p].length}),i.setUint32(c,101010256,!0),i.setUint16(c+8,e.length,!0),i.setUint16(c+10,e.length,!0),i.setUint32(c+12,c-u,!0),i.setUint32(c+16,u,!0),a}var ix;function wde(e){if(!ix){ix=new Uint32Array(256);for(let r=0;r<256;r++){let o=r;for(let n=0;n<8;n++)o=o&1?3988292384^o>>>1:o>>>1;ix[r]=o>>>0}}let t=4294967295;for(let r=0;r<e.length;r++)t=ix[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}var sx=[".ld",".ldx",".csv",".tsv",".txt",".vbo",".mat",".zip",".gz"],dG=e=>e.length>2&&e[0]===31&&e[1]===139;async function pG(e){let t=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}function iE(e){let t=new TextDecoder("utf-8").decode(e);return(t.match(/�/g)??[]).length>2?new TextDecoder("latin1").decode(e):t}var fG=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer;async function hG(e,t=""){let r=new Uint8Array(e),o=dG(r)?await pG(r):r,n=t.replace(/\.gz$/i,"");return oE(o)?Cde(o):gG(o,n)}async function gG(e,t,r=[]){let o=Mde(e,t);try{let n=o==="mat"?await oG(fG(e)):_de(e,o);for(let a of r)cG(n,sG(iE(a.bytes)));return{file:n,format:o}}catch(n){throw Ade(n,o)}}function Mde(e,t){let r=rE(e,t);if(!uG(r)||r==="mat"&&aG(e))throw new di(nE(r),r,!0);return r}function _de(e,t){return t==="ld"?JI(fG(e)):t==="vbo"?eG(iE(e)):YU(iE(e))}var Ade=(e,t)=>e instanceof di?e:new di(e instanceof Error?e.message:String(e),t,!1);async function Cde(e){let t;try{t=await aE(e),t=await Promise.all(t.map(async a=>dG(a.bytes)?{path:a.path.replace(/\.gz$/i,""),bytes:await pG(a.bytes)}:a))}catch(a){throw new di(a instanceof Error?a.message:String(a),"zip",!1)}let r=t.map(a=>({e:a,kind:rE(a.bytes,no(a.path))})),o=r.filter(a=>a.kind==="ldx").map(a=>a.e),n=r.filter(a=>a.kind!=="ldx"&&a.kind!=="other"&&a.kind!=="zip");if(n.length===1)return gG(n[0].e.bytes,no(n[0].e.path),o);throw n.length>1?new di(`This zip holds ${n.length} logs \u2014 unpack it and add them, and each opens as a session.`,"zip",!0):new di(nE("zip"),"zip",!0)}function Go(e){if(e===null||typeof e!="object")return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map(Go).join(",")}]`;let t=e,r=Object.keys(t).sort(),o=[];for(let n of r)t[n]!==void 0&&o.push(`${JSON.stringify(n)}:${Go(t[n])}`);return`{${o.join(",")}}`}function kn(e){let t=Go(e),r=2166136261;for(let o=0;o<t.length;o++)r^=t.charCodeAt(o),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r.toString(16).padStart(8,"0").slice(-6)}var Tde=["tireModel","tireModelRear","motorModel","aeroModel","batteryModel","brakeModel","damperModel","damperModelRear","heaveDamperModel","rollDamperModel","kinFront","kinRear","steerFront","surveyedRadiusFront","surveyedRadiusRear","readouts","ggvMode","air","airSettled"];function Kc(e){let t={...e.params};for(let o of Tde)delete t[o];delete t.cgReference,delete t.name;let r=e.suspension?{...e.suspension}:null;return r&&(delete r.name,delete r.chassis),kn({params:t,suspension:r,tire:e.tireModel??null,...e.tireModelRear?{tireRear:e.tireModelRear}:{},motor:e.motorModel??null,...e.aeroModel?{aero:e.aeroModel}:{},...e.batteryModel?{battery:e.batteryModel}:{},...e.brakeModel?{brakes:{...e.brakeModel,name:void 0}}:{},...e.damperModel?{dampers:{...e.damperModel,name:void 0}}:{},...e.damperModelRear?{dampersRear:{...e.damperModelRear,name:void 0}}:{},...e.heaveDamperModel?{dampersHeave:{...e.heaveDamperModel,name:void 0}}:{},...e.rollDamperModel?{dampersRoll:{...e.rollDamperModel,name:void 0}}:{}})}function Pde(e){if(!e||typeof e!="object"||"every"in e)return e??null;let{fitSpacing:t,...r}=e;return t===1?{...r,every:10}:e}function Wc(e){return kn({source:e.source,numerics:Pde(e.numerics)})}var Fde="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function $de(e){let t=Go(e),r=2166136261;for(let o=0;o<t.length;o++)r^=t.charCodeAt(o),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r}function bG(e,t,r){let o=$de([e,t,r]),n="";for(let a=0;a<6;a++)n=Fde[o&31]+n,o>>>=5;return`PD-${n}`}function sE(e){let t=/^\s*PD[-_ ]?([0-9A-Z]{6})\s*$/i.exec(e);if(!t)return;let r=t[1].toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1");return/^[0-9A-HJKMNP-TV-Z]{6}$/.test(r)?`PD-${r}`:void 0}var Ide=/(?:^|[^0-9A-Za-z])(PD[-_ ][0-9A-Za-z]{6})(?![0-9A-Za-z])/gi;function Ede(e){let t=[];for(let r of e.matchAll(Ide)){let o=sE(r[1]);o&&!t.includes(o)&&t.push(o)}return t}function yG(e){for(let t of e){if(!t)continue;let[r]=Ede(t);if(r)return r}}var pi=".pdsetup",Lde="pacedyn-setup",Dde=1024*1024;function vG(e){if(e.length>Dde)throw new Error("This is too large to be a setup file.");let t;try{t=JSON.parse(e)}catch{throw new Error("This is not a setup file: it is not the JSON a setup sheet saves.")}let r=t;if(!r||r.format!==Lde||!Array.isArray(r.stamps))throw new Error("This is not a setup file: a setup sheet\u2019s file names its format and holds its cars.");return r.stamps}var RG=64*1024*1024,xG=e=>new RegExp(`(${e.map(t=>t.replace(".","\\.")).join("|")})$`,"i"),wG=[...sx.filter(e=>e!==".ldx"),...Gh],lx={project:{label:"a project (.pace.json or .json)",pattern:/\.json$/i},track:{label:"a track file (.csv, .tsv, .txt, .json, .yaml or .yml)",pattern:/\.(csv|tsv|txt|json|ya?ml)$/i},part:{label:"a part (.tir or .json)",pattern:/\.(tir|json)$/i},log:{label:`a log (${wG.filter(e=>!Gh.includes(e)).join(", ")})`,pattern:xG(wG)},ldx:{label:"a MoTeC .ldx",pattern:/\.ldx$/i},setup:{label:`an issued setup's file (${pi})`,pattern:xG([pi])},page:{label:"a page (.html)",pattern:/\.html?$/i}},Gde={project:"must end in .json (a project is saved as .pace.json)",page:"must end in .html"};function MG(e=process.cwd(),t=Bde()){let r=n=>{let a=n.trim();if(!a)throw new Error("the path is empty");return a==="~"?t:a.startsWith("~/")||a.startsWith("~\\")?uE(t,a.slice(2)):Ude(a)?kG(a):kG(e,a)},o=async(n,a)=>{let i=r(n);if(!lx[a].pattern.test(i))throw new Error(`${i} is not ${lx[a].label}`);let s;try{s=await cE(i)}catch{throw new Error(`there is no file at ${i} (a relative path starts at ${e})`)}if(!s.isFile())throw new Error(`${i} is not a file`);if(s.size>RG)throw new Error(`${i} is ${Math.round(s.size/1024/1024)} MB; the limit is ${RG/1024/1024} MB`);return i};return{cwd:e,resolve:r,async read(n,a){let i=await o(n,a);return{text:await SG(i,"utf8"),path:i,name:lE(i)}},async bytes(n,a){let i=await o(n,a);return{bytes:new Uint8Array(await SG(i)),path:i,name:lE(i)}},async beside(n,a){let i=cx(r(n)),s;try{s=await Ode(i)}catch{return[]}return s.filter(c=>lx[a].pattern.test(c)).sort().map(c=>uE(i,c))},async write(n,a,i,s="project"){let c=r(n);if(!lx[s].pattern.test(c))throw new Error(`${c} ${Gde[s]}`);let l=!1;try{if(!(await cE(c)).isFile())throw new Error(`${c} is not a file`);l=!0}catch(m){if(m instanceof Error&&m.message.endsWith("is not a file"))throw m}if(l&&!i)throw new Error(`${c} already exists. Pass replace: true to overwrite it, or choose another name.`);try{if(!(await cE(cx(c))).isDirectory())throw new Error("not a folder")}catch{throw new Error(`the folder ${cx(c)} does not exist`)}let u=uE(cx(c),`.${lE(c)}.${Nde(4).toString("hex")}.tmp`);try{await jde(u,a,"utf8"),await zde(u,c)}catch(m){throw await Vde(u,{force:!0}),m}return{path:c,bytes:Buffer.byteLength(a),replaced:l}}}}async function qh(e,t,r){let o=typeof t.text=="string",n=typeof t.path=="string"&&t.path.trim()!=="";if(o&&n)throw new Error("pass the file\u2019s text or its path, not both");if(n){if(!e)throw new Error("this server cannot read files on your machine: pass the file\u2019s text instead");let a=await e.read(t.path,r);return{text:a.text,name:t.name??a.name,path:a.path}}if(!o)throw new Error(e?"pass the file\u2019s text, or its path on this machine":"pass the file\u2019s text");return{text:t.text,name:t.name??""}}var Hh="Instead of the text: the file\u2019s path on this machine, absolute, or relative to the folder the assistant started this server in (~ is the home folder). Preferred \u2014 the file then never passes through the conversation.";import{readFileSync as m_}from"node:fs";import{join as d_}from"node:path";var ux=e=>e.format!=="points"&&!e.field;var jr=e=>e?.kind==="ice";var _G={packVoltageMax:600,segmentVoltageMax:120,powerLimitKw:80};var Bt=e=>typeof e=="number"&&Number.isFinite(e);function qde(e){let{soc:t,ocv:r,r0:o}=e;if(!Array.isArray(t)||t.length<2)return"The curve needs at least two state-of-charge points.";if(!t.every(Bt))return"The state-of-charge axis contains a value that is not a number.";if(t[0]<0||t[t.length-1]>1)return`The state-of-charge axis must lie within 0 to 1 (it runs ${t[0]} to ${t[t.length-1]}).`;for(let n=1;n<t.length;n++)if(!(t[n]>t[n-1]))return`The state-of-charge axis must increase (${t[n-1]} then ${t[n]}).`;if(!Array.isArray(r)||r.length!==t.length)return`The curve has ${Array.isArray(r)?r.length:0} voltages against ${t.length} state-of-charge points.`;if(!r.every(Bt))return"The open-circuit voltage contains a value that is not a number.";if(r.some(n=>n<=0))return"The open-circuit voltage must be positive everywhere.";for(let n=1;n<r.length;n++)if(r[n]<r[n-1])return`The open-circuit voltage must rise with state of charge (${r[n-1]} V at ${t[n-1]} then ${r[n]} V at ${t[n]}).`;if(!Array.isArray(o)||o.length!==t.length)return`The curve has ${Array.isArray(o)?o.length:0} resistances against ${t.length} state-of-charge points.`;if(!o.every(Bt))return"The resistance contains a value that is not a number.";if(o.some(n=>n<0))return"The resistance cannot be negative.";if(e.rTempC!==void 0||e.rGrid!==void 0){let n=e.rTempC,a=e.rGrid;if(!Array.isArray(n)||n.length<1)return"The resistance temperature axis needs at least one temperature.";if(!n.every(Bt))return"The resistance temperature axis contains a value that is not a number.";for(let i=1;i<n.length;i++)if(!(n[i]>n[i-1]))return`The temperature axis must increase (${n[i-1]} then ${n[i]} \xB0C).`;if(!Array.isArray(a)||a.length!==n.length)return`The resistance grid has ${Array.isArray(a)?a.length:0} rows against ${n.length} temperatures.`;for(let i=0;i<a.length;i++){let s=a[i];if(!Array.isArray(s)||s.length!==t.length)return`Resistance row ${i+1} has ${Array.isArray(s)?s.length:0} values against ${t.length} state-of-charge points.`;if(!s.every(Bt))return"The resistance grid contains a value that is not a number.";if(s.some(c=>c<0))return"The resistance grid contains a negative resistance."}}return null}function Hde(e){return!e||typeof e!="object"?"The cell has no curve.":e.kind==="table"?qde(e):e.kind==="analytic"?!Bt(e.vCut)||!Bt(e.vNom)||!Bt(e.vFull)?"The cut-off, nominal and full voltages must be numbers.":e.vCut<=0?"The cut-off voltage must be positive.":e.vCut<e.vNom&&e.vNom<e.vFull?!Bt(e.r0)||e.r0<0?"The cell resistance must be a number and cannot be negative.":e.socAtNom!==void 0&&(!Bt(e.socAtNom)||e.socAtNom<=0||e.socAtNom>=1)?"The state of charge the nominal voltage is met at must lie strictly between 0 and 1.":null:`The voltages must order cut-off < nominal < full (given ${e.vCut}, ${e.vNom}, ${e.vFull} V).`:`Unknown cell curve kind "${e.kind}".`}function Kh(e){if(!e||typeof e!="object")return"Not a battery model.";let t=e.cell;if(!t||typeof t!="object")return"The model has no cell.";if(!Bt(t.capacityAh)||t.capacityAh<=0)return"The cell capacity must be a positive number of amp-hours.";if(!Bt(t.vMin)||t.vMin<0)return"The cut-off voltage must be a number and cannot be negative.";if(!Bt(t.vMax)||t.vMax<=0)return"The maximum cell voltage must be a positive number.";if(!(t.vMin<t.vMax))return`The cut-off voltage (${t.vMin} V) must be below the maximum (${t.vMax} V).`;if(!Bt(t.iMaxA)||t.iMaxA<0)return"The discharge current limit must be a number of amps, 0 for no limit.";if(t.iMaxChargeA!==void 0&&(!Bt(t.iMaxChargeA)||t.iMaxChargeA<0))return"The charge current limit must be a number of amps, 0 for no limit.";if(t.massKg!==void 0&&(!Bt(t.massKg)||t.massKg<0))return"The cell mass must be a number and cannot be negative.";let r=Hde(t.curve);if(r)return r;let o=t.curve.kind==="table"?t.curve.ocv[t.curve.ocv.length-1]:t.curve.vFull;if(t.vMin>=o)return`The cut-off voltage (${t.vMin} V) is at or above the cell's voltage at full charge (${o} V), so no power could ever be drawn.`;let n=e.thermal;if(n!==void 0){if(!n||typeof n!="object")return"The thermal model must be an object, or absent.";if(!Bt(n.heatCapacityJPerK)||n.heatCapacityJPerK<=0)return"The cell heat capacity must be a positive number of joules per kelvin.";if(!Bt(n.coolingWPerK)||n.coolingWPerK<0)return"The cooling must be a number of watts per kelvin and cannot be negative.";if(n.startC!==void 0&&!Bt(n.startC))return"The starting temperature must be a number.";if(n.entropicVPerK!==void 0&&!Bt(n.entropicVPerK))return"The entropic coefficient must be a number.";if(n.derateFromC!==void 0){if(!Bt(n.derateFromC))return"The temperature the derate starts at must be a number.";if(n.derateToC!==void 0){if(!Bt(n.derateToC))return"The temperature the derate ends at must be a number.";if(!(n.derateToC>n.derateFromC))return`The derate must end above where it starts (given ${n.derateFromC} then ${n.derateToC} \xB0C).`}}else if(n.derateToC!==void 0)return"The derate has an end temperature but no start; give both or neither."}let a=e.pack;if(!a||typeof a!="object")return"The model has no pack.";if(!Number.isInteger(a.series)||a.series<1)return"The pack needs a whole number of cells in series, at least one.";if(!Number.isInteger(a.parallel)||a.parallel<1)return"The pack needs a whole number of strings in parallel, at least one.";if(!Bt(a.busResistance)||a.busResistance<0)return"The busbar resistance must be a number and cannot be negative.";if(a.seriesPerSegment!==void 0&&a.seriesPerSegment!==0){if(!Number.isInteger(a.seriesPerSegment)||a.seriesPerSegment<1)return"The cells per segment must be a whole number, at least one.";if(a.seriesPerSegment>a.series)return`A segment cannot hold more cells (${a.seriesPerSegment}) than the pack has in series (${a.series}).`}return null}function mE(e,t){let r=[];if(Kh(e))return r;let{cell:o,pack:n}=e,a=o.vMax*n.series;if(t.packVoltageMax!==void 0&&a>t.packVoltageMax&&r.push(`The pack reaches ${a.toFixed(1)} V at full charge, above the ${t.packVoltageMax} V ceiling \u2014 ${n.series} cells in series at ${o.vMax} V each.`),t.segmentVoltageMax!==void 0&&n.seriesPerSegment){let i=o.vMax*n.seriesPerSegment;i>t.segmentVoltageMax&&r.push(`A segment reaches ${i.toFixed(1)} V, above the ${t.segmentVoltageMax} V ceiling \u2014 ${n.seriesPerSegment} cells at ${o.vMax} V each.`)}return t.segmentVoltageMax!==void 0&&!n.seriesPerSegment&&r.push(`The pack does not say how many cells are in a segment \u2014 the ${t.segmentVoltageMax} V segment ceiling cannot be checked.`),r}function Yc(e,t){let r=e.length;if(r<=1)return{i:0,t:0,clamped:!1};if(t<=e[0])return{i:0,t:0,clamped:t<e[0]};if(t>=e[r-1])return{i:r-2,t:1,clamped:t>e[r-1]};let o=0,n=r-1;for(;n-o>1;){let a=o+n>>1;e[a]<=t?o=a:n=a}return{i:o,t:(t-e[o])/(e[n]-e[o]),clamped:!1}}function rr(e,t,r){let o=e.length;if(o===0)return 0;if(r<=e[0])return t[0];if(r>=e[o-1])return t[o-1];let n=0,a=o-1;for(;a-n>1;){let s=n+a>>1;e[s]<=r?n=s:a=s}let i=(r-e[n])/(e[a]-e[n]);return t[n]+i*(t[a]-t[n])}function mx(e,t,r,o,n){let a=e.length,i=t.length;if(a===0||i===0)return 0;let s=Yc(e,o),c=Yc(t,n),l=Math.min(s.i+1,a-1),u=Math.min(c.i+1,i-1),m=r[c.i][s.i],p=r[c.i][l],d=r[u][s.i],f=r[u][l],h=m+s.t*(p-m),g=d+s.t*(f-d);return h+c.t*(g-h)}var Lm=[0,.05,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],dE={nmc:[0,.29,.4,.483,.525,.567,.608,.667,.733,.8,.892,1],lfp:[0,.478,.591,.626,.652,.67,.678,.696,.704,.722,.757,1],lipo:[0,.333,.433,.517,.575,.625,.667,.717,.775,.833,.908,1],other:[0,.05,.1,.2,.3,.4,.5,.6,.7,.8,.9,1]},AG=[0,.05,.1,.2,.5,.8,1],CG=[2.2,1.55,1.3,1.12,1,.97,.98];function TG(e){return rr(AG,CG,e)}var PG=[-20,-10,0,10,25,40,60],FG=[4,2.8,2,1.4,1,.82,.75];function pE(e){return rr(PG,FG,e)}var $G=.5;function fE(e,t){let{vFull:r,vNom:o,vCut:n,r0:a}=e,i=r-n;if(!(i>0))throw new Error(`The full voltage (${r} V) must be above the cut-off (${n} V).`);let s=(o-n)/i;if(!(s>0&&s<1))throw new Error(`The nominal voltage (${o} V) must lie between the cut-off (${n} V) and full (${r} V).`);let c=dE[t]??dE.other,l=e.socAtNom??$G,u=Lm.includes(l)?[...Lm]:[...Lm,l].sort((h,g)=>h-g),m=rr(Lm,c,l),p=m>0&&m<1?Math.log(s)/Math.log(m):1,d=[],f=[];for(let h of u){let g=rr(Lm,c,h);d.push(n+i*Math.pow(g,p)),f.push(e.constantResistance?a:a*TG(h))}return{kind:"table",soc:u,ocv:d,r0:f}}function hE(e){let t=e.soc,r=e.ocv,o=[0,...t.filter(a=>a>0&&a<1),1],n=0;for(let a=1;a<o.length;a++){let i=o[a-1],s=o[a];n+=(rr(t,r,i)+rr(t,r,s))/2*(s-i)}return n}var Dm=25,IG=new WeakMap;function Ln(e){let t=IG.get(e);if(t)return t;let r=Kh(e);if(r)throw new Error(r);let{cell:o,pack:n}=e,a=o.curve.kind==="table"?o.curve:fE(o.curve,o.chemistry),i=n.series,s=n.parallel,c=i/s,l=a.rTempC,u=a.rGrid,m=s*o.capacityAh,p=i*o.vMin,d=o.iMaxA>0?s*o.iMaxA:1/0,f=o.iMaxChargeA!==void 0&&o.iMaxChargeA>0?o.iMaxChargeA:o.iMaxA/4,h=f>0?s*f:1/0,g=w=>i*rr(a.soc,a.ocv,w),b=(w,M=Dm)=>{let T=l&&u?mx(a.soc,l,u,w,M):rr(a.soc,a.r0,w)*pE(M);return c*T+n.busResistance},y=(w,M,T)=>g(w)-M*b(w,T),v=(w,M,T)=>{if(!(w>0))return 0;let A=g(M),_=b(M,T);if(!(_>0))return w/A;let F=A*A-4*_*w;return F<0?NaN:2*w/(A+Math.sqrt(F))},k=(w,M,T)=>{if(!(w>0))return 0;let A=g(M),_=b(M,T);return _>0?2*w/(A+Math.sqrt(A*A+4*_*w)):w/A},x=w=>{let M=e.thermal;if(!M||M.derateFromC===void 0)return 1;let T=M.derateToC??M.derateFromC;return w<=M.derateFromC?1:!(T>M.derateFromC)||w>=T?0:1-(w-M.derateFromC)/(T-M.derateFromC)},S=(w,M,T=0)=>{let A=g(w),_=b(w,M),F=_>0?A/(2*_):1/0,P=L=>{if(!(_>0))return L*A;let j=Math.min(L,F);return j*(A-j*_)},I=_>0?Math.max(0,(A-p)/_):1/0,z=T>0&&Number.isFinite(T)?T:1/0,N=_>0?P(I):1/0,q=Number.isFinite(d)?P(d):1/0,U=_>0?A*A/(4*_):1/0,B=[["rules",z],["voltage-floor",N],["current",q],["matched-load",U]],V=B[0][0],E=B[0][1];for(let[L,j]of B)j<E&&(E=j,V=L);let C=x(M??Dm);C<1&&(E=Number.isFinite(E)?E*C:E,V="temperature");let $=Number.isFinite(E)?v(E,w,M):1/0;return{watts:E,binding:V,rules:z,voltageFloor:N,current:q,matchedLoad:U,derate:C,amps:$,volts:Number.isFinite($)?A-$*_:A}},R={model:e,table:a,capacityAh:m,chargeC:m*3600,energyKwh:m*(i*hE(a))/1e3,socRange:[a.soc[0],a.soc[a.soc.length-1]],voltageAtFull:i*a.ocv[a.ocv.length-1],voltageCeiling:i*o.vMax,voltageFloor:p,currentCeiling:d,chargeCurrentCeiling:h,massKg:o.massKg!==void 0?i*s*o.massKg:null,thermal:e.thermal?{heatCapacityJPerK:i*s*e.thermal.heatCapacityJPerK,coolingWPerK:i*s*e.thermal.coolingWPerK,...e.thermal.startC!==void 0?{startC:e.thermal.startC}:{},entropicVPerK:i*(e.thermal.entropicVPerK??0)}:null,derateAt:x,ocv:g,resistance:b,terminalVoltage:y,currentFor:v,chargeCurrentFor:k,maxPower:S};return IG.set(e,R),R}function gE(e){return{name:e.name,chemistry:e.chemistry,capacityAh:e.capacityAh,curve:{kind:"analytic",vFull:e.vFull,vNom:e.vNom,vCut:e.vCut,r0:e.r0},iMaxA:e.iMaxA,...e.iMaxChargeA!==void 0?{iMaxChargeA:e.iMaxChargeA}:{},vMin:e.vCut,vMax:e.vFull,...e.massKg!==void 0?{massKg:e.massKg}:{}}}var EG={name:"High-power NMC pouch 4.0 Ah",chemistry:"nmc",capacityAh:4,vCut:3,vNom:3.6,vFull:4.2,r0:.0025,iMaxA:100,iMaxChargeA:40,massKg:.09},LG={name:"LFP prismatic 20 Ah",chemistry:"lfp",capacityAh:20,vCut:2.5,vNom:3.2,vFull:3.65,r0:.002,iMaxA:200,iMaxChargeA:60,massKg:.4},DG={name:"NMC cylindrical 3.4 Ah",chemistry:"nmc",capacityAh:3.4,vCut:3,vNom:3.6,vFull:4.2,r0:.03,iMaxA:10,iMaxChargeA:3,massKg:.048};function bE(){return{name:"Formula Student accumulator",cell:gE(EG),pack:{series:140,parallel:2,busResistance:.02,seriesPerSegment:28},provenance:{source:"assumed",note:"Assumed high-power NMC pouch pack sized to the Formula Student rules; the cell curve and resistance are class-level guesses, not a measurement."}}}function yE(){return{name:"LFP pack",cell:gE(LG),pack:{series:160,parallel:1,busResistance:.02,seriesPerSegment:32},provenance:{source:"assumed",note:"Assumed LFP prismatic pack; the flat plateau is the chemistry, the numbers are class-level guesses."}}}function vE(){return{name:"Road car pack",cell:gE(DG),pack:{series:96,parallel:74,busResistance:.01},provenance:{source:"assumed",note:"Assumed road-electric pack of cylindrical energy cells; capacity and voltage are class-typical, the resistance is a guess."}}}function SE(e,t,r="Constant pack"){return{name:r,cell:{name:"Constant cell",chemistry:"other",capacityAh:e,curve:{kind:"table",soc:[0,1],ocv:[t,t],r0:[0,0]},iMaxA:0,vMin:0,vMax:t},pack:{series:1,parallel:1,busResistance:0},provenance:{source:"assumed",note:"The constant pack: one open-circuit voltage, no internal resistance and no current limit \u2014 what a car carried before the battery was a model. It cannot sag, so its power never fades."}}}function dx(e){if(e.kind==="ice"){let o=e.gearbox.efficiency;return{model:e,maxTorque:n=>n>e.limitRpm?0:rr(e.rpm,e.torque,n),efficiency:()=>o}}let t=o=>rr(e.rpm,e.torque,o),r=e.kind==="simple"?()=>e.efficiency:(o,n)=>mx(e.effRpm,e.effTorque,e.effGrid,o,n);return{model:e,maxTorque:t,efficiency:r}}function kE(e){let t=e.resistanceAtC??20,r=e.torqueConstant,o=e.speedLossW??0,n=e.speedLossAtRpm??0,a=e.speedLossExponent??1.5,i=e.derateFromC,s=e.derateToC,c=f=>Math.max(0,e.terminalResistanceOhm*(1+.00393*(f-t))),l=f=>o>0&&n>0?o*Math.pow(Math.max(0,f)/n,a):0,u=(f,h,g)=>{let b=r>0?Math.abs(h)/r:0;return 1.5*c(g)*b*b+l(f)},m=(f,h)=>{let g=e.coolingWPerK*(h-e.coolantC)-l(f);return!(g>0)||r<=0?0:r*Math.sqrt(g/(1.5*c(h)))},p=e.coolingWPerK>0?e.heatCapacityJPerK/e.coolingWPerK:1/0,d=Number.isFinite(p)?.25*p:1/0;return{spec:e,startC:e.startC??e.coolantC,lossW:u,step(f,h,g){if(!(g>0)||!(e.heatCapacityJPerK>0))return f;let b=Number.isFinite(d)?Math.max(1,Math.ceil(g/d)):1,y=g/b,v=f;for(let k=0;k<b;k++)v+=(h-e.coolingWPerK*(v-e.coolantC))*y/e.heatCapacityJPerK;return v},continuousTorque:m,derate(f,h,g){if(i===void 0||s===void 0||!(s>i)||!(g>0)||h<=i)return 1;let b=Math.min(1,m(f,s)/g);return h>=s?b:1-(1-b)*(h-i)/(s-i)},equilibriumC(f){return e.coolingWPerK>0?e.coolantC+f/e.coolingWPerK:1/0}}}function nr(e,t){return t==="rear"&&e.tireRateRear!==void 0?e.tireRateRear:e.tireRate}function Wh(e,t){let r=e.tyreFreeRadiusRear;return(t==="rear"&&r!==void 0?r:e.tyreFreeRadius)??0}var px=9.81,NG=(e,t)=>e*(t*t)/2*(Math.PI/180)/1e3,Yh=(e,t)=>e+t>0?e*t/(e+t):0,OG=.5;function fx(e,t,r){if(!(r>0))return 1;let o=e*px*t*(Math.PI/180)/r;return 1/(1-Math.min(OG,o))}function RE(e,t,r){return r>0?e*px*t/(r*r):0}function zG(e,t,r,o,n){if(!(o>0)||!(n>0))return 1;let a=RE(e,t,r)*(1/o+1/n);return 1/(1-Math.min(OG,a))}function Lt(e){let t=4*e.unsprungPerCorner,r=Math.max(0,e.massTotal-t),o=r*e.frontMassFrac,n=r*(1-e.frontMassFrac),a=nr(e,"front"),i=nr(e,"rear"),s=e.wheelRateFront+(e.heaveSpringFront??0),c=e.wheelRateRear+(e.heaveSpringRear??0),l=Yh(s,a),u=Yh(c,i),m=(q,U)=>{let B=U/2;return B>0?1/(2*Math.PI)*Math.sqrt(q*1e3/B):0},p=m(l,o),d=m(u,n),f=Yh(e.wheelRateFront+e.arbFront,a),h=Yh(e.wheelRateRear+e.arbRear,i),g=NG(f,e.trackFront),b=NG(h,e.trackRear),y=g+b,v=y>0?g/y:.5,k=e.rcHeightFront+(e.rcHeightRear-e.rcHeightFront)*(1-e.frontMassFrac),x=(e.cgHeight-k)/1e3,S=r*px*x,R=fx(r,x,y),w=y>0?S/y*R:0,M=e.massTotal*px*e.cgHeight/e.wheelbase,T=2*l,A=2*u,_=zG(r,e.cgHeight,e.wheelbase,T,A),P=(T>0&&A>0?(M/T+M/A)/e.wheelbase*_:0)*(180/Math.PI),I=e.wheelbase*e.wheelbase*Yh(T,A)*(Math.PI/180)/1e3,z=e.damperFront??2.5,N=e.damperRear??2.5;return{sprungMass:r,sprungFront:o,sprungRear:n,rideRateFront:l,rideRateRear:u,rideFreqFront:p,rideFreqRear:d,rollRateFront:g,rollRateRear:b,rollRateTotal:y,rollWheelRateFront:f,rollWheelRateRear:h,frontRollStiffFrac:v,rollGradient:w,pitchGradient:P,pitchRate:I,cgRollGain:R,cgPitchGain:_,rideDampingFront:z+(e.heaveDamperFront??0),rideDampingRear:N+(e.heaveDamperRear??0),rollDampingFront:z+(e.rollDamperFront??0),rollDampingRear:N+(e.rollDamperRear??0)}}var _s=["clFront","clRear","cd"],As=e=>e.frame?.kind==="pitch";function Nm(e){return As(e)?{x:e.axes.h,y:e.axes.pitch}:{x:e.axes.hFront,y:e.axes.hRear}}var hx=e=>e.frame?.kind==="pitch",VG=e=>e.kind==="map";var gx=45,vr=e=>typeof e=="number"&&Number.isFinite(e);function bx(e,t,r="mm",o="ride height"){if(!Array.isArray(t)||t.length<1)return`The ${e} axis needs at least one ${o}.`;if(!t.every(vr))return`The ${e} axis contains a value that is not a number.`;for(let n=1;n<t.length;n++)if(!(t[n]>t[n-1]))return`The ${e} axis must increase (${t[n-1]} then ${t[n]} ${r}).`;return null}function jG(e,t){if(t===void 0)return null;for(let r of _s){let o=t[r];if(!o||!Array.isArray(o.deg)||!Array.isArray(o.factor))return`The ${e} correction of ${r} needs degrees and factors.`;if(o.deg.length<1)return`The ${e} correction of ${r} needs at least one angle.`;if(o.deg.length!==o.factor.length)return`The ${e} correction of ${r} has ${o.factor.length} factors against ${o.deg.length} angles.`;if(!o.deg.every(vr)||!o.factor.every(vr))return`The ${e} correction of ${r} contains a value that is not a number.`;if(o.deg[0]<0)return`The ${e} correction of ${r} is against the absolute angle; it cannot start below zero.`;for(let n=1;n<o.deg.length;n++)if(!(o.deg[n]>o.deg[n-1]))return`The ${e} correction of ${r} must increase in angle (${o.deg[n-1]} then ${o.deg[n]}\xB0).`;if(o.factor.some(n=>n<0))return`The ${e} correction of ${r} has a negative factor.`}return null}function BG(e,t){return t===void 0?null:!vr(t.dCl)||!vr(t.dBalance)||!vr(t.dCd)?`The ${e} slopes must be numbers.`:!vr(t.maxDeg)||!(t.maxDeg>0)?`The ${e} response needs a positive angle to be valid to.`:null}function Om(e){if(!e||typeof e!="object")return"Not an aero model.";if(!vr(e.area)||e.area<=0)return"The reference area must be a positive number of square metres.";if(e.kind==="map"){let t,r,o,n;if(e.frame==null){let s=bx("front ride-height",e.axes?.hFront);if(s)return s;let c=bx("rear ride-height",e.axes?.hRear);if(c)return c;[t,r,o,n]=[e.axes.hFront,e.axes.hRear,"front ride heights","rear ride heights"]}else if(e.frame?.kind==="pitch"){if(!vr(e.frame.refX))return"The point the ride height is read at must be a number of millimetres aft of the front axle.";let s=bx("ride-height",e.axes?.h);if(s)return s;let c=bx("pitch",e.axes?.pitch,"\xB0","pitch");if(c)return c;let l=e.axes.pitch.find(u=>Math.abs(u)>=gx);if(l!==void 0)return`A pitch of ${l}\xB0 is not a car's attitude \u2014 is the axis a rake in millimetres? Pitch is in degrees.`;[t,r,o,n]=[e.axes.h,e.axes.pitch,"ride heights","pitches"]}else return`Unknown aero map frame "${e.frame.kind}".`;let a=t.length,i=r.length;for(let s of _s){let c=e[s];if(!Array.isArray(c)||c.length!==i)return`${s} has ${Array.isArray(c)?c.length:0} rows against ${i} ${n} \u2014 they must match.`;for(let l=0;l<i;l++){let u=c[l];if(!Array.isArray(u)||u.length!==a)return`${s} row ${l+1} has ${Array.isArray(u)?u.length:0} values against ${a} ${o}.`;if(!u.every(vr))return`${s} contains a value that is not a number.`}}return jG("yaw",e.attitude?.yaw)??jG("roll",e.attitude?.roll)}if(e.kind==="sensitivity"){let t;if(e.frame==null)t=["hFront","hRear"];else if(e.frame?.kind==="pitch"){if(!vr(e.frame.refX))return"The point the ride height is read at must be a number of millimetres aft of the front axle.";t=["h","pitch"]}else return`Unknown aero sensitivity frame "${e.frame.kind}".`;let r=e.ref,o=e.slope,n=e.range,a=i=>i==="pitch"?"\xB0":" mm";if(!r||!vr(r[t[0]])||!vr(r[t[1]]))return e.frame?"The reference ride height and pitch must be numbers.":"The reference ride heights must be numbers.";for(let i of _s){if(!e.at||!vr(e.at[i]))return`${i} at the reference must be a number.`;let s=o?.[i];if(!s||!vr(s[t[0]])||!vr(s[t[1]]))return`The slopes of ${i} must be numbers.`}for(let i of t){let s=n?.[i],c=r[i];if(!s||!vr(s[0])||!vr(s[1]))return`The ${i} range must be two numbers.`;if(!(s[1]>s[0]))return`The ${i} range must run from low to high (${s[0]} to ${s[1]}${a(i)}).`;if(c<s[0]||c>s[1])return`The reference ${i} of ${c}${a(i)} lies outside its range ${s[0]}\u2013${s[1]}${a(i)}.`;if(i==="pitch"&&(Math.abs(s[0])>=gx||Math.abs(s[1])>=gx))return`A pitch range reaching ${Math.abs(s[0])>=gx?s[0]:s[1]}\xB0 is not a car's attitude. Pitch is in degrees.`}return BG("yaw",e.attitude?.yaw)??BG("roll",e.attitude?.roll)}return`Unknown aero model kind "${e.kind}".`}var UG=180/Math.PI;function zm(e,t,r,o){let n=(o-r)/t;return{h:r+e.refX*n,pitch:Math.atan(n)*UG}}function Vm(e,t,r,o){let n=Math.tan(o/UG);return{hFront:r-e.refX*n,hRear:r+(t-e.refX)*n}}var Y2e=180/Math.PI,Kde=["hFront","hRear"],Wde=["h","pitch"],ME=e=>e?.kind==="pitch"?Wde:Kde,Dn=(e,t)=>e[t],yx=(e,t)=>e[t],xE=(e,t)=>({[e[0]]:t(e[0]),[e[1]]:t(e[1])});function Yde(e){if(!(!e.yaw&&!e.roll))return{...e.yaw?{yaw:{...e.yaw}}:{},...e.roll?{roll:{...e.roll}}:{}}}function _E(e){let t=ME(e.frame),r=e.balanceFront,o=e.cl*r,n=e.cl*(1-r),a=xE(t,c=>Dn(e.dCl,c)*r+e.cl*Dn(e.dBalance,c)),i=xE(t,c=>Dn(e.dCl,c)*(1-r)-e.cl*Dn(e.dBalance,c)),s=Yde(e);return{kind:"sensitivity",name:e.name,area:e.area,...e.frame?{frame:{...e.frame}}:{},ref:{...e.ref},at:{clFront:o,clRear:n,cd:e.cd},slope:{clFront:a,clRear:i,cd:xE(t,c=>Dn(e.dCd,c))},range:{[t[0]]:[...yx(e.range,t[0])],[t[1]]:[...yx(e.range,t[1])]},provenance:{...e.provenance},...s?{attitude:s}:{}}}function vx(e,t,r){let o=Math.min(Math.abs(r),t.maxDeg),n=e.clFront+e.clRear,a=n!==0?e.clFront/n:.5,i=n+t.dCl*o,s=a+t.dBalance*o,c=e.clFront!==0?i*s/e.clFront:1,l=e.clRear!==0?i*(1-s)/e.clRear:1,u=e.cd!==0?(e.cd+t.dCd*o)/e.cd:1;return{clFront:c,clRear:l,cd:u}}function wE(e,t,r=11){let o=Array.from({length:r},(a,i)=>t.maxDeg*i/(r-1)),n=o.map(a=>vx(e,t,a));return{clFront:{deg:[...o],factor:n.map(a=>a.clFront)},clRear:{deg:[...o],factor:n.map(a=>a.clRear)},cd:{deg:[...o],factor:n.map(a=>a.cd)}}}function GG(e){if(!(!e.attitude?.yaw&&!e.attitude?.roll))return{...e.attitude.yaw?{yaw:wE(e.at,e.attitude.yaw)}:{},...e.attitude.roll?{roll:wE(e.at,e.attitude.roll)}:{}}}function qG(e,t,r,o=0,n=0){let[a,i]=ME(e.frame),s=t-Dn(e.ref,a),c=r-Dn(e.ref,i),l={clFront:e.at.clFront+Dn(e.slope.clFront,a)*s+Dn(e.slope.clFront,i)*c,clRear:e.at.clRear+Dn(e.slope.clRear,a)*s+Dn(e.slope.clRear,i)*c,cd:e.at.cd+Dn(e.slope.cd,a)*s+Dn(e.slope.cd,i)*c},u=e.attitude?.yaw?vx(e.at,e.attitude.yaw,o):{clFront:1,clRear:1,cd:1},m=e.attitude?.roll?vx(e.at,e.attitude.roll,n):{clFront:1,clRear:1,cd:1};return{clFront:l.clFront*u.clFront*m.clFront,clRear:l.clRear*u.clRear*m.clRear,cd:l.cd*u.cd*m.cd}}function AE(e){let[t,r]=ME(e.frame),o=[...yx(e.range,t)],n=[...yx(e.range,r)],a=s=>n.map(c=>o.map(l=>s(qG(e,l,c)))),i=GG(e);return{kind:"map",name:e.name,area:e.area,...e.frame?{frame:{...e.frame}}:{},axes:{[t]:o,[r]:n},clFront:a(s=>s.clFront),clRear:a(s=>s.clRear),cd:a(s=>s.cd),provenance:{...e.provenance},...i?{attitude:i}:{}}}var CE=180/Math.PI,HG=new WeakMap,KG=new WeakMap,TE=new WeakMap;function Cs(e,t){let r=KG.get(e);if(r)return r;let o=t?.wheelbase,n=o!==void 0?TE.get(e)?.get(o):void 0;if(n)return n;let a=Zde(e),i=a.map;if(!As(i)){let l=Xde(e,a);return KG.set(e,l),l}if(o===void 0||!Number.isFinite(o)||o<=0)throw new Error("A ride-height-and-pitch aero map is read with the car\u2019s wheelbase, and none was given.");let s=Jde(e,a,i.frame,o),c=TE.get(e);return c||(c=new Map,TE.set(e,c)),c.set(o,s),s}function Zde(e){let t=HG.get(e);if(t)return t;let r=Om(e);if(r)throw new Error(r);let o=e.kind==="map"?e:AE(e),{x:n,y:a}=Nm(o),i=n.length,s=a.length,c=o.attitude?.yaw,l=o.attitude?.roll,u=!!(c||l),m={clFront:1,clRear:1,cd:1,clamped:!1},p=(y,v)=>{let k=Math.abs(v),x=y.clFront.deg[y.clFront.deg.length-1];return{clFront:rr(y.clFront.deg,y.clFront.factor,k),clRear:rr(y.clRear.deg,y.clRear.factor,k),cd:rr(y.cd.deg,y.cd.factor,k),clamped:k>x}},d=(y,v)=>{if(!u)return m;let k=c?p(c,y):m,x=l?p(l,v):m;return{clFront:k.clFront*x.clFront,clRear:k.clRear*x.clRear,cd:k.cd*x.cd,clamped:k.clamped||x.clamped}},f=(y,v,k=0,x=0)=>{let S=Yc(n,y),R=Yc(a,v),w=Math.min(S.i+1,i-1),M=Math.min(R.i+1,s-1),T=_=>{let F=_[R.i][S.i],P=_[R.i][w],I=_[M][S.i],z=_[M][w],N=F+S.t*(P-F),q=I+S.t*(z-I);return N+R.t*(q-N)},A=d(k,x);return{clFront:u?T(o.clFront)*A.clFront:T(o.clFront),clRear:u?T(o.clRear)*A.clRear:T(o.clRear),cd:u?T(o.cd)*A.cd:T(o.cd),clampedRide:S.clamped||R.clamped,clampedAttitude:A.clamped}},h={x:[n[0],n[i-1]],y:[a[0],a[s-1]]},g=(y,v,k=!1,x=0,S=0)=>{let R=d(x,S),w=Yc(n,k?Math.min(Math.max(y,h.x[0]),h.x[1]):y),M=Yc(a,k?Math.min(Math.max(v,h.y[0]),h.y[1]):v),T=Math.min(w.i+1,i-1),A=Math.min(M.i+1,s-1),_=T>w.i?n[T]-n[w.i]:0,F=A>M.i?a[A]-a[M.i]:0,P={};for(let I of _s){let z=o[I],N=z[M.i][w.i],q=z[M.i][T],U=z[A][w.i],B=z[A][T],V=w.clamped||_===0?0:((q-N)*(1-M.t)+(B-U)*M.t)/_,E=M.clamped||F===0?0:((U-N)*(1-w.t)+(B-q)*w.t)/F;P[I]=u?{x:V*R[I],y:E*R[I]}:{x:V,y:E}}return P},b={map:o,x:h.x,y:h.y,hasAttitude:u,factors:d,at:f,slopes:g};return HG.set(e,b),b}function Xde(e,t){let r={x:t.x,y:t.y,at:t.at,toAxles:(n,a)=>({hFront:n,hRear:a}),fromAxles:(n,a)=>({x:n,y:a})},o=(n,a,i=!1,s=0,c=0)=>{let l=t.slopes(n,a,i,s,c),u={};for(let m of _s)u[m]={hFront:l[m].x,hRear:l[m].y};return u};return{model:e,map:t.map,area:t.map.area,grid:r,hasAttitude:t.hasAttitude,at:t.at,slopes:o,factors:t.factors}}function Jde(e,t,r,o){let n=r.refX,a=n/o,i=(l,u,m=0,p=0)=>{let d=(u-l)/o;return t.at(l+n*d,Math.atan(d)*CE,m,p)},s=(l,u,m=!1,p=0,d=0)=>{let f=(u-l)/o,h=t.slopes(l+n*f,Math.atan(f)*CE,m,p,d),g=CE/(o*(1+f*f)),b={};for(let y of _s)b[y]={hFront:h[y].x*(1-a)-h[y].y*g,hRear:h[y].x*a+h[y].y*g};return b},c={frame:r,x:t.x,y:t.y,at:t.at,toAxles:(l,u)=>Vm(r,o,l,u),fromAxles:(l,u)=>{let m=zm(r,o,l,u);return{x:m.h,y:m.pitch}}};return{model:e,map:t.map,area:t.map.area,grid:c,hasAttitude:t.hasAttitude,at:i,slopes:s,factors:t.factors}}function PE(e){let t=e.clFront+e.clRear;return{cl:t,balanceFront:t!==0?e.clFront/t:.5}}var ut=(e,t)=>e*t/100,hr=e=>e/100,WG={name:"Formula Student aero",area:1,cl:3,balanceFront:.45,cd:1.3,ref:{hFront:30,hRear:35},range:{hFront:[5,60],hRear:[10,70]},dCl:{hFront:ut(3,-.4),hRear:ut(3,.1)},dBalance:{hFront:hr(-.3),hRear:hr(.15)},dCd:{hFront:ut(1.3,-.1),hRear:ut(1.3,.05)},yaw:{dCl:ut(3,-1),dBalance:hr(-.3),dCd:ut(1.3,.5),maxDeg:10},roll:{dCl:ut(3,-.5),dBalance:0,dCd:0,maxDeg:3},note:"Assumed class-level sensitivities for an undertray-and-wings Formula Student car, ride height, yaw and roll; not measured."},YG={name:"Formula 1 aero",area:1.5,cl:3,balanceFront:.44,cd:.9,ref:{hFront:35,hRear:70},range:{hFront:[0,60],hRear:[20,100]},dCl:{hFront:ut(3,-.3),hRear:ut(3,-.15)},dBalance:{hFront:hr(-.15),hRear:hr(.15)},dCd:{hFront:ut(.9,-.15),hRear:ut(.9,-.05)},yaw:{dCl:ut(3,-1.5),dBalance:hr(.2),dCd:ut(.9,.8),maxDeg:8},roll:{dCl:ut(3,-1),dBalance:hr(-.3),dCd:0,maxDeg:2},note:"Assumed class-level sensitivities for a ground-effect floor, ride height, yaw and roll; not measured."},ZG={name:"GT car aero",area:2,cl:1.4,balanceFront:.42,cd:.42,ref:{hFront:55,hRear:75},range:{hFront:[10,90],hRear:[10,110]},dCl:{hFront:ut(1.4,-.3),hRear:ut(1.4,.05)},dBalance:{hFront:hr(-.25),hRear:hr(.15)},dCd:{hFront:ut(.42,-.1),hRear:0},yaw:{dCl:ut(1.4,-.8),dBalance:hr(-.2),dCd:ut(.42,.6),maxDeg:10},roll:{dCl:ut(1.4,-.3),dBalance:0,dCd:0,maxDeg:3},note:"Assumed class-level sensitivities for a splitter-and-wing GT car, ride height, yaw and roll; not measured."},XG={name:"Sports car aero",area:2.2,cl:-.1,balanceFront:.5,cd:.3,ref:{hFront:130,hRear:140},range:{hFront:[80,180],hRear:[100,200]},dCl:{hFront:-5e-4,hRear:0},dBalance:{hFront:0,hRear:0},dCd:{hFront:2e-4,hRear:0},yaw:{dCl:0,dBalance:0,dCd:ut(.3,.5),maxDeg:10},note:"Assumed class-level sensitivities for a road car with no aero devices; not measured."},JG={name:"Cup car aero",area:2.1,cl:.45,balanceFront:.45,cd:.4,ref:{hFront:64,hRear:78},range:{hFront:[20,100],hRear:[30,120]},dCl:{hFront:ut(.45,-.4),hRear:ut(.45,.05)},dBalance:{hFront:hr(-.25),hRear:hr(.15)},dCd:{hFront:ut(.4,-.1),hRear:0},yaw:{dCl:ut(.45,-1.2),dBalance:hr(-.2),dCd:ut(.4,.6),maxDeg:10},roll:{dCl:ut(.45,-.3),dBalance:0,dCd:0,maxDeg:3},note:"Assumed class-level sensitivities for a splitter-and-wing cup hatchback, ride height, yaw and roll; not measured."},QG={name:"Stock car aero",area:2.2,cl:.6,balanceFront:.45,cd:.45,ref:{hFront:75,hRear:90},range:{hFront:[20,110],hRear:[30,130]},dCl:{hFront:ut(.6,-.35),hRear:ut(.6,.05)},dBalance:{hFront:hr(-.25),hRear:hr(.15)},dCd:{hFront:ut(.45,-.1),hRear:0},yaw:{dCl:ut(.6,-1),dBalance:hr(-.2),dCd:ut(.45,.6),maxDeg:10},roll:{dCl:ut(.6,-.3),dBalance:0,dCd:0,maxDeg:3},note:"Assumed class-level sensitivities for a splitter-and-spoiler stock car, ride height, yaw and roll; not measured."},eq={name:"Hill-climb prototype aero",area:1.2,cl:2.5,balanceFront:.42,cd:.9,ref:{hFront:45,hRear:55},range:{hFront:[10,80],hRear:[15,95]},dCl:{hFront:ut(2.5,-.35),hRear:ut(2.5,.05)},dBalance:{hFront:hr(-.25),hRear:hr(.15)},dCd:{hFront:ut(.9,-.1),hRear:ut(.9,.05)},yaw:{dCl:ut(2.5,-1),dBalance:hr(-.3),dCd:ut(.9,.5),maxDeg:10},roll:{dCl:ut(2.5,-.5),dBalance:0,dCd:0,maxDeg:3},note:"Assumed class-level sensitivities for a winged sports prototype with a flat floor and diffuser, ride height, yaw and roll; not measured."},tq={name:"Race truck aero",area:6.2,cl:-.1,balanceFront:.6,cd:.65,ref:{hFront:110,hRear:240},range:{hFront:[60,160],hRear:[180,300]},dCl:{hFront:-5e-4,hRear:0},dBalance:{hFront:0,hRear:0},dCd:{hFront:2e-4,hRear:0},yaw:{dCl:0,dBalance:0,dCd:ut(.65,.5),maxDeg:10},note:"Assumed class-level sensitivities for a cab-over race truck with a chin spoiler and deflectors, ride height and yaw; not measured."};function fi(e){return _E({name:e.name,area:e.area,cl:e.cl,balanceFront:e.balanceFront,cd:e.cd,ref:e.ref,range:e.range,dCl:e.dCl,dBalance:e.dBalance,dCd:e.dCd,...e.yaw?{yaw:e.yaw}:{},...e.roll?{roll:e.roll}:{},provenance:{source:"assumed",note:e.note}})}var FE=()=>fi(WG),$E=()=>fi(YG),IE=()=>fi(ZG),EE=()=>fi(XG),LE=()=>fi(JG),DE=()=>fi(QG),NE=()=>fi(eq),OE=()=>fi(tq);function Zc(e,t){let r=.5*e.rho*e.area*t*t,o=e.cl*r,n=e.cw*r,a=o*e.copLongFront;return{downforce:o,drag:n,downFront:a,downRear:o-a}}function Sx(e,t){let r=e.massTotal;if(!(r>0))return{front:0,rear:0};let o=Math.max(0,Math.min(1,e.frontMassFrac)),n=2*e.unsprungPerCorner,a=(i,s)=>s>0?Math.min(1,i/s):0;return{front:(t.sprungMass*o+n*a(t.rideRateFront,nr(e,"front")))/r,rear:(t.sprungMass*(1-o)+n*a(t.rideRateRear,nr(e,"rear")))/r}}function kx(e,t,r,o){let n=t.front*r+t.rear*o;return n===0?e:Math.max(Math.min(1,e),e-n)}function zE(e,t){return e.wheelbase>0?e.massTotal*t*9.81/e.wheelbase:0}function jm(e,t,r){let o=2*t.rideRateFront,n=2*t.rideRateRear;return!(o>0)||!(n>0)?0:Math.min(RE(t.sprungMass,r,e.wheelbase),.5*o*n/(o+n))}function Zh(e,t,r,o,n){let a=e.cgHeight,i=zE(e,r);if(o===0&&n===0&&i===0)return{height:a,forward:0,noseLoad:0,dropFront:0,dropRear:0};let s=Sx(e,t),c=2*t.rideRateFront,l=2*t.rideRateRear,u=a,m=0,p=0,d=0;for(let h=0;h<6;h++){d=jm(e,t,u);let g=o-i*u,b=n+i*u;if(d>0){let k=c*l-d*(c+l);m=(g*(l-d)-d*b)/k,p=(b*(c-d)-d*g)/k}else m=c>0?g/c:0,p=l>0?b/l:0;let y=kx(a,s,m,p),v=Math.abs(y-u);if(u=y,v<1e-9)break}let f=m-p;return{height:u,forward:e.wheelbase>0?u*f/e.wheelbase:0,noseLoad:d*f,dropFront:m,dropRear:p}}var VE={yawDeg:0,rollDeg:0},rq=1e-4,Qde=40,nq=50;function hi(e,t,r=0){let o=e.aero?.model;if(!(!o||!Cs(o,e).hasAttitude))return{yawDeg:r,rollDeg:Lt(e).rollGradient*t}}function Bm(e,t){if(e.rideHeightFront!=null&&e.rideHeightRear!=null)return{hFront:e.rideHeightFront,hRear:e.rideHeightRear};let r=e.model,o=(a,i,s)=>{if(t!==void 0&&t>0)return Vm(a,t,i,s);throw new Error("A ride-height-and-pitch aero model is read with the car\u2019s wheelbase, and none was given.")},n={hFront:0,hRear:0};if(r?.kind==="sensitivity")n=hx(r)?o(r.frame,r.ref.h,r.ref.pitch):r.ref;else if(r){let{x:a,y:i}=Nm(r),s=(a[0]+a[a.length-1])/2,c=(i[0]+i[i.length-1])/2;n=As(r)?o(r.frame,s,c):{hFront:s,hRear:c}}return{hFront:e.rideHeightFront??n.hFront,hRear:e.rideHeightRear??n.hRear}}var oq=new WeakMap;function gi(e,t,r=0,o){let n=e.aero;if(!n?.model)return null;let a=oq.get(e);a||(a=new Map,oq.set(e,a));let i=o&&Cs(n.model,e).hasAttitude?o:VE,s=i===VE?`${t}|${r}`:`${t}|${r}|${i.yawDeg.toFixed(3)}|${i.rollDeg.toFixed(3)}`,c=a.get(s);if(c)return c;let l=epe(e,n,t,r,i);return a.size>4096&&a.clear(),a.set(s,l),l}function epe(e,t,r,o,n){let a=Cs(t.model,e),i=Lt(e),s=2*i.rideRateFront,c=2*i.rideRateRear,l=Bm(t,e.wheelbase),u=.5*t.rho*r*r,m=a.area,p=e.wheelbase>0?t.copHeight/e.wheelbase:0,d=Sx(e,i),f=zE(e,o),h=(T,A)=>kx(e.cgHeight,d,l.hFront-T,l.hRear-A),g=(T,A)=>l.hFront-T-(l.hRear-A),b=(T,A)=>{let _=a.at(T,A,n.yawDeg,n.rollDeg),F=u*m*_.clFront,P=u*m*_.clRear,I=u*m*_.cd,z=I*p,N=h(T,A),q=f*N,U=jm(e,i,N)*g(T,A),B=F-q-z+U,V=P+q+z-U,E=T-l.hFront+(s>0?B/s:0),C=A-l.hRear+(c>0?V/c:0);return{c:_,downFront:F,downRear:P,drag:I,rF:E,rR:C,norm:Math.hypot(E,C)}},y=(T,A,_=!1)=>{let F=a.slopes(T,A,_,n.yawDeg,n.rollDeg),P=s>0?u*m/s:0,I=c>0?u*m/c:0;return[[P*(F.clFront.hFront-p*F.cd.hFront),P*(F.clFront.hRear-p*F.cd.hRear)],[I*(F.clRear.hFront+p*F.cd.hFront),I*(F.clRear.hRear+p*F.cd.hRear)]]},v=l.hFront,k=l.hRear,x=b(v,k),S=0;for(;x.norm>=rq&&S<Qde;){S++;let T=y(v,k),A=s>0?f/s:0,_=c>0?f/c:0,F=jm(e,i,h(v,k)),P=s>0?F/s:0,I=c>0?F/c:0,z=1+T[0][0]-A*d.front-P,N=T[0][1]-A*d.rear+P,q=T[1][0]+_*d.front+I,U=1+T[1][1]+_*d.rear-I,B=z*U-N*q,V,E;Math.abs(B)>1e-9?(V=-(U*x.rF-N*x.rR)/B,E=-(-q*x.rF+z*x.rR)/B):(V=-.5*x.rF,E=-.5*x.rR);let C=Math.max(1,Math.abs(V)/nq,Math.abs(E)/nq);V/=C,E/=C;let $=1;for(let L=0;L<6;L++){let j=b(v+$*V,k+$*E);if(j.norm<=x.norm||L===5){v+=$*V,k+=$*E,x=j;break}$*=.5}}let R=y(v,k,!0),w=2+R[0][0]+R[1][1],M=(1+R[0][0])*(1+R[1][1])-R[0][1]*R[1][0];return{v:r,axG:o,hFront:v,hRear:k,cgHeight:h(v,k),cgForward:e.wheelbase>0?h(v,k)*g(v,k)/e.wheelbase:0,cgNoseLoad:jm(e,i,h(v,k))*g(v,k),clFront:x.c.clFront,clRear:x.c.clRear,cd:x.c.cd,area:m,downforce:x.downFront+x.downRear,drag:x.drag,downFront:x.downFront,downRear:x.downRear,gain:tpe(R),stable:M>0&&w>0,converged:x.norm<rq,iterations:S,clampedRide:x.c.clampedRide,yawDeg:n.yawDeg,rollDeg:n.rollDeg,clampedAttitude:x.c.clampedAttitude}}function tpe(e){let t=e[0][0]+e[1][1],r=e[0][0]*e[1][1]-e[0][1]*e[1][0],o=t*t-4*r;if(o>=0){let n=Math.sqrt(o);return Math.max(Math.abs((t+n)/2),Math.abs((t-n)/2))}return Math.sqrt(r)}function Um(e,t,r=0,o){let n=gi(e,t,r,o);return n?{downforce:n.downforce,drag:n.drag,downFront:n.downFront,downRear:n.downRear}:e.aero?Zc(e.aero,t):{downforce:0,drag:0,downFront:0,downRear:0}}function rpe(e,t,r,o){let n=Zc(t,r),a=Lt(e),i=Bm(t,e.wheelbase),s=e.wheelbase>0?n.drag*t.copHeight/e.wheelbase:0,c=Zh(e,a,o,n.downFront-s,n.downRear+s),l=n.downforce;return{v:r,axG:o,hFront:i.hFront-c.dropFront,hRear:i.hRear-c.dropRear,cgHeight:c.height,cgForward:c.forward,cgNoseLoad:c.noseLoad,clFront:t.cl*t.copLongFront,clRear:t.cl*(1-t.copLongFront),cd:t.cw,area:t.area,downforce:l,drag:n.drag,downFront:n.downFront,downRear:n.downRear,gain:0,stable:!0,converged:!0,iterations:0,clampedRide:!1,yawDeg:0,rollDeg:0,clampedAttitude:!1}}function Xh(e,t,r=0,o){let n=gi(e,t,r,o);return n||(e.aero?rpe(e,e.aero,t,r):null)}function Rx(e,t=0,r=0,o,n){if(e.aero&&t>0){if(e.aero.model){let s=gi(e,t,r,o);return{height:s.cgHeight,forward:s.cgForward,noseLoad:s.cgNoseLoad}}let a=Zc(e.aero,t),i=e.wheelbase>0?a.drag*e.aero.copHeight/e.wheelbase:0;return Zh(e,n??Lt(e),r,a.downFront-i,a.downRear+i)}return r===0?{height:e.cgHeight,forward:0,noseLoad:0}:Zh(e,n??Lt(e),r,0,0)}function jE(e,t,r=0){let o=[];for(let n of t){let a=Xh(e,n,r);a&&o.push(a)}return o}var aq=[0,1,0],BE=[0,0,1],Ee=(e,t)=>[e[0]+t[0],e[1]+t[1],e[2]+t[2]],se=(e,t)=>[e[0]-t[0],e[1]-t[1],e[2]-t[2]],ke=(e,t)=>[e[0]*t,e[1]*t,e[2]*t],UE=e=>[-e[0],-e[1],-e[2]],xe=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],Ve=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]],npe=e=>xe(e,e),Ts=e=>Math.sqrt(xe(e,e)),Jh=(e,t)=>npe(se(e,t)),yt=(e,t)=>Ts(se(e,t)),we=e=>{let t=Ts(e);return t<1e-12?[0,0,0]:[e[0]/t,e[1]/t,e[2]/t]};var Ps=(e,t,r)=>{let o=we(r),n=se(e,t);return Ee(t,ke(o,xe(n,o)))},iq=(e,t,r)=>yt(e,Ps(e,t,r));var ape=1e-6;function ipe(e){if(e<ape){let o=e*e;return[1-o/6,.5-o/24]}let t=Math.sin(e),r=Math.cos(e);return[t/e,(1-r)/(e*e)]}function Br(e,t){let r=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);if(r<1e-14)return t;let[o,n]=ipe(r),a=Ve(e,t),i=Ve(e,a);return Ee(t,Ee(ke(a,o),ke(i,n)))}function oo(e,t,r){let o=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);if(o<1e-14)return e;let n=[t[0]/o,t[1]/o,t[2]/o];return Br(ke(n,r),e)}function wa(e,t){let r=t.length,o=e.map(a=>a.slice()),n=t.slice();return cq(o,n,r,new Array(r).fill(0))}function sq(e,t,r){return cq(e,t,t.length,r)}function cq(e,t,r,o){let n=1/0,a=0;for(let i=0;i<r;i++){let s=i,c=Math.abs(e[i][i]);for(let u=i+1;u<r;u++){let m=Math.abs(e[u][i]);m>c&&(c=m,s=u)}if(c<1e-14){for(let u=0;u<r;u++)o[u]=NaN;return{x:o,condProxy:1/0,singular:!0}}if(n=Math.min(n,c),a=Math.max(a,c),s!==i){let u=e[i];e[i]=e[s],e[s]=u;let m=t[i];t[i]=t[s],t[s]=m}let l=e[i][i];for(let u=i+1;u<r;u++){let m=e[u][i]/l;if(m!==0){for(let p=i;p<r;p++)e[u][p]-=m*e[i][p];t[u]-=m*t[i]}}}for(let i=r-1;i>=0;i--){let s=t[i];for(let c=i+1;c<r;c++)s-=e[i][c]*o[c];o[i]=s/e[i][i]}return{x:o,condProxy:a/n,singular:!1}}var lq=e=>{let t=0;for(let r of e)t=Math.max(t,Math.abs(r));return t},uq=e=>{let t=0;for(let r of e)t+=r*r;return t},spe=Math.sqrt(Number.EPSILON);function mq(e,t,r={}){let o=r.maxIter??60,n=r.tol??1e-10,a=t.length,i=r.scales??new Array(a).fill(1),s=t.slice(),c=e(s),l=lq(c),u=uq(c),m=.001,p=1,d=c.length,f=Array.from({length:d},()=>new Array(a).fill(0)),h=Array.from({length:a},()=>new Array(a).fill(0)),g=Array.from({length:a},()=>new Array(a).fill(0)),b=new Array(a).fill(0),y=new Array(a).fill(0),v=new Array(a).fill(0),k=new Array(a).fill(0),x=new Array(a).fill(0);for(let S=0;S<o;S++){if(l<n)return{x:s,residualNorm:l,iterations:S,converged:!0,condProxy:p};for(let T=0;T<a;T++){let A=spe*Math.max(Math.abs(s[T]),i[T]);for(let F=0;F<a;F++)k[F]=s[F];k[T]+=A;let _=e(k);for(let F=0;F<d;F++)f[F][T]=(_[F]-c[F])/A}let R=0;for(let T=0;T<a;T++){for(let _=0;_<a;_++){let F=0;for(let P=0;P<d;P++)F+=f[P][T]*f[P][_];h[T][_]=F}let A=0;for(let _=0;_<d;_++)A+=f[_][T]*c[_];b[T]=A,R=Math.max(R,h[T][T])}let w=Math.max(R,1e-9),M=!1;for(let T=0;T<18;T++){let A=m*w;for(let F=0;F<a;F++){let P=h[F],I=g[F];for(let z=0;z<a;z++)I[z]=F===z?P[z]+A:P[z];y[F]=-b[F]}let _=sq(g,y,v);if(p=Math.max(p,_.condProxy),!_.singular){for(let I=0;I<a;I++)x[I]=s[I]+v[I];let F=e(x),P=uq(F);if(P<u){for(let I=0;I<a;I++)s[I]=x[I];c=F,u=P,l=lq(c),m=Math.max(m*.3,1e-12),M=!0;break}}m=Math.min(m*4,1e12)}if(!M)break}return{x:s,residualNorm:l,iterations:o,converged:l<n,condProxy:p}}function Qh(e,t,r,o){let n=e*e+t*t,a=Math.sqrt(n);if(!(a>1e-12*o))return{c1:1,s1:0,c2:1,s2:0,margin:0,ok:!1,free:!0};let i=Math.abs(r),s=1-i/a;if(s<0){let l=r>=0?1:-1,u=l*e/a,m=l*t/a;return{c1:u,s1:m,c2:u,s2:m,margin:s,ok:s>=-1e-12,free:!1}}let c=Math.sqrt((a-i)*(a+i));return{c1:(e*r-t*c)/n,s1:(t*r+e*c)/n,c2:(e*r+t*c)/n,s2:(t*r-e*c)/n,margin:s,ok:!0,free:!1}}function GE(e,t){return[e[0]*t[0]-e[1]*t[1]-e[2]*t[2]-e[3]*t[3],e[0]*t[1]+e[1]*t[0]+e[2]*t[3]-e[3]*t[2],e[0]*t[2]-e[1]*t[3]+e[2]*t[0]+e[3]*t[1],e[0]*t[3]+e[1]*t[2]-e[2]*t[1]+e[3]*t[0]]}var dq=e=>[e[0],-e[1],-e[2],-e[3]];function pq(e,t){let[r,o,n,a]=e,i=2*(n*t[2]-a*t[1]),s=2*(a*t[0]-o*t[2]),c=2*(o*t[1]-n*t[0]);return[t[0]+r*i+(n*c-a*s),t[1]+r*s+(a*i-o*c),t[2]+r*c+(o*s-n*i)]}function fq(e,t){let r=e[0]*t[0]+e[1]*t[1]+e[2]*t[2];if(1+r<1e-14){let n=Math.abs(e[0])<.6?[1,0,0]:[0,1,0],a=e[1]*n[2]-e[2]*n[1],i=e[2]*n[0]-e[0]*n[2],s=e[0]*n[1]-e[1]*n[0],c=Math.hypot(a,i,s);return[0,a/c,i/c,s/c]}let o=Math.sqrt(2*(1+r));return[(1+r)/o,(e[1]*t[2]-e[2]*t[1])/o,(e[2]*t[0]-e[0]*t[2])/o,(e[0]*t[1]-e[1]*t[0])/o]}function hq(e,t,r){let o,n;return t>=0?(o=Math.sqrt((1+t)/2),n=r/(2*o)):(n=(r>=0?1:-1)*Math.sqrt((1-t)/2),o=r/(2*n)),[o,n*e[0],n*e[1],n*e[2]]}function qE(e,t,r){let o=e[0],n=e[1],a=e[2],i=t[0],s=t[1],c=t[2],l=r[0],u=r[1],m=r[2],p=o+s+m;if(p>=o&&p>=s&&p>=m){let h=Math.sqrt(1+p),g=.5/h;return[.5*h,(c-u)*g,(l-a)*g,(n-i)*g]}if(o>=s&&o>=m){let h=Math.sqrt(1+o-s-m),g=.5/h;return[(c-u)*g,.5*h,(i+n)*g,(l+a)*g]}if(s>=m){let h=Math.sqrt(1-o+s-m),g=.5/h;return[(l-a)*g,(i+n)*g,.5*h,(u+c)*g]}let d=Math.sqrt(1-o-s+m),f=.5/d;return[(n-i)*f,(l+a)*f,(u+c)*f,.5*d]}function gq(e){let t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);if(t===0)return[1,0,0,0];let r=Math.sin(t/2)/t;return[Math.cos(t/2),r*e[0],r*e[1],r*e[2]]}function bq(e){let[t,r,o,n]=e;t<0&&(t=-t,r=-r,o=-o,n=-n);let a=Math.sqrt(r*r+o*o+n*n);if(a===0)return[0,0,0];let i=2*Math.atan2(a,t)/a;return[i*r,i*o,i*n]}function cpe(e){let t=Math.abs(e[0])<.6?[1,0,0]:[0,1,0],r=we(Ve(e,t));return[r,Ve(e,r)]}function lpe(e){let t=e.hardpoints,r=we(se(t.damperChassis,t.pushrodOuter)),[o,n]=cpe(r);return{top:t.damperChassis,lower0:t.pushrodOuter,axis0:r,e1:o,e2:n}}function HE(e){let t=e.hardpoints,r=t.wheelCenter,o=we(se(t.ucaRear,t.ucaFront)),n=se(t.uprightUpper,t.ucaFront),a=xe(n,o),i=se(n,ke(o,a)),s=xe(i,i),c=we(se(t.lcaRear,t.lcaFront)),l=se(t.uprightLower,t.lcaFront),u=Jh(t.tieOuter,t.tieInner);return{c0:r,ucaFront:t.ucaFront,ucaDir:o,ubj0:t.uprightUpper,ubjAxial0:a,ubjRadius2:s,lcaFront:t.lcaFront,lcaDir:c,lbj0:t.uprightLower,lbjRel0:l,tro0:t.tieOuter,tieInner0:t.tieInner,tieLen2:u,rackAxis:we(e.config.rackAxis),steerMovesRack:e.config.steerMode==="rack",ubjRadiusRef:Math.max(1,2*Math.sqrt(s)),tieLenRef:Math.max(1,2*Math.sqrt(u)),...e.config.layout==="mcpherson"?{strut:lpe(e)}:{}}}function ao(e,t,r){let o=[t[3],t[4],t[5]],n=[t[0],t[1],t[2]],a=se(r,e.c0);return Ee(Ee(Br(o,a),e.c0),n)}function KE(e,t){return Ee(e.lcaFront,oo(e.lbjRel0,e.lcaDir,t))}function Xc(e,t){return e.steerMovesRack?Ee(e.tieInner0,ke(e.rackAxis,t)):e.tieInner0}function WE(e,t,r,o){let n=ao(e,t,e.lbj0),a=KE(e,r),i=n[0]-a[0],s=n[1]-a[1],c=n[2]-a[2],l,u;if(e.strut){let f=e.strut,h=[t[3],t[4],t[5]],g=se(f.top,ao(e,t,f.lower0));l=xe(g,Br(h,f.e1)),u=xe(g,Br(h,f.e2))}else{let f=ao(e,t,e.ubj0),h=se(f,e.ucaFront),g=xe(h,e.ucaDir),b=se(h,ke(e.ucaDir,g));l=g-e.ubjAxial0,u=(xe(b,b)-e.ubjRadius2)/e.ubjRadiusRef}let m=ao(e,t,e.tro0),p=Xc(e,o),d=(Jh(m,p)-e.tieLen2)/e.tieLenRef;return[i,s,c,l,u,d]}var eg=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),xx=e=>{let t=eg(e);return[e[0]/t,e[1]/t,e[2]/t]},upe=(e,t)=>se(e,ke(t,xe(e,t))),YE=e=>xx(Ve(e,Math.abs(e[0])<.6?[1,0,0]:[0,1,0]));function mpe(e,t){let r=e.ucaDir,o=Ee(e.ucaFront,ke(r,e.ubjAxial0)),n=Math.sqrt(e.ubjRadius2),a=upe(se(e.ubj0,e.ucaFront),r),i=eg(a)>1e-9?xx(a):YE(r),s=Ve(r,i),c=se(e.ubj0,e.lbj0),l=xe(c,c);if(!(l>1e-18))return"free";let u=se(o,t),m=xe(u,u),p=Qh(2*n*xe(i,u),2*n*xe(s,u),l-m-n*n,2*n*Math.sqrt(m));if(p.free)return"free";let d=xx(c),f=(h,g)=>{let b=Ee(o,Ee(ke(i,n*h),ke(s,n*g))),y=xx(se(b,t));return{q1:fq(d,y),k:y,margin:p.margin,ok:p.ok}};return p.margin>0?[f(p.c1,p.s1),f(p.c2,p.s2)]:[f(p.c1,p.s1)]}function dpe(e,t,r){let o=t.axis0,n=Ee(t.lower0,ke(o,xe(se(e.lbj0,t.lower0),o))),a=se(n,e.lbj0),i=eg(a),s=i>1e-9?ke(a,1/i):YE(o),c=se(t.top,r),l=eg(c);if(!(l>1e-9))return"free";let u=ke(c,1/l),m=i/l,p=1-m,d=p>=0?Math.sqrt((1-m)*(1+m)):0,f=YE(u),h=g=>{let b=g*d,y=Ee(ke(u,b),ke(f,Math.min(m,1))),v=se(ke(u,Math.min(m,1)),ke(f,b));return{q1:GE(qE(v,y,Ve(v,y)),dq(qE(s,o,Ve(s,o)))),k:u,margin:p,ok:p>=0}};return p>0?[h(1),h(-1)]:[h(1)]}function ppe(e,t,r,o){let{k:n}=o,a=pq(o.q1,se(e.tro0,e.lbj0)),i=xe(a,n),s=se(a,ke(n,i)),c=eg(s);if(!(c>1e-9))return"free";let l=ke(s,1/c),u=Ve(n,l),m=Ee(t,ke(n,i)),p=se(m,r),d=xe(p,p),f=Qh(2*c*xe(p,l),2*c*xe(p,u),e.tieLen2-d-c*c,2*c*Math.sqrt(d));if(f.free)return"free";let h=(b,y)=>({q:GE(hq(n,b,y),o.q1)});return{roots:f.margin>0?[h(f.c1,f.s1),h(f.c2,f.s2)]:[h(f.c1,f.s1)],margin:f.margin,ok:f.ok}}function yq(e,t,r,o=[0,0,0,0,0,0]){let n=KE(e,t),a=Xc(e,r),i=gq([o[3],o[4],o[5]]),s=h=>Math.abs(h[0]*i[0]+h[1]*i[1]+h[2]*i[2]+h[3]*i[3]),c=e.strut?dpe(e,e.strut,n):mpe(e,n);if(c==="free")return{x:o.slice(),converged:!1,margin:0,free:!0};let l=null,u=null;for(let h of c){let g=ppe(e,n,a,h);if(g==="free")return{x:o.slice(),converged:!1,margin:0,free:!0};let b=Math.min(h.margin,g.margin),y=g.ok&&h.ok;for(let{q:v}of g.roots){let k=s(v);y&&(!l||k>l.near)&&(l={q:v,margin:b,near:k}),!y&&(!u||k>u.near)&&(u={q:v,margin:b,near:k})}}let{q:m,margin:p}=l??u,d=bq(m),f=se(se(n,e.c0),Br(d,se(e.lbj0,e.c0)));return{x:[f[0],f[1],f[2],d[0],d[1],d[2]],converged:l!==null,margin:p,free:!1}}function Sq(e){let t=we(se(e.rockerPivotB,e.rockerPivotA));return{pivotA:e.rockerPivotA,axis:t,rprRel0:se(e.rockerToPushrod,e.rockerPivotA),rdmRel0:se(e.rockerToDamper,e.rockerPivotA),damperChassis:e.damperChassis,rodLen2:Jh(e.pushrodOuter,e.rockerToPushrod),damperLen0:yt(e.rockerToDamper,e.damperChassis)}}var fpe=(e,t)=>Ee(e.pivotA,oo(e.rprRel0,e.axis,t)),ZE=(e,t)=>Ee(e.pivotA,oo(e.rdmRel0,e.axis,t));function Gm(e,t){return{pushrod:fpe(e,t),damper:ZE(e,t)}}function kq(e,t,r=0){let o=xe(e.rprRel0,e.axis),n=se(e.rprRel0,ke(e.axis,o)),a=Ve(e.axis,n),i=se(Ee(e.pivotA,ke(e.axis,o)),t),s=xe(n,n),c=xe(i,i),l=Qh(2*xe(i,n),2*xe(i,a),e.rodLen2-c-s,2*Math.sqrt(s*c));if(l.free){let d=Math.abs(e.rodLen2-c-s)<=1e-9*e.rodLen2;return{phi:r,damperLength:yt(ZE(e,r),e.damperChassis),converged:d,margin:0}}let u=vq(Math.atan2(l.s1,l.c1),r),m=vq(Math.atan2(l.s2,l.c2),r),p=Math.abs(m-r)<Math.abs(u-r)?m:u;return{phi:p,damperLength:yt(ZE(e,p),e.damperChassis),converged:l.ok,margin:l.margin}}function vq(e,t){let r=2*Math.PI;return e+r*Math.round((t-e)/r)}function Rq(e,t,r,o){return Ee(t,Br(ke(we(r),o),se(e,t)))}function xq(e,t,r,o){let n=we(o),a=p=>{let d=se(p,r);return se(d,ke(n,xe(d,n)))},i=a(e),s=a(t),c=Math.hypot(i[0],i[1],i[2]),l=Math.hypot(s[0],s[1],s[2]);if(c<1e-9||l<1e-9)return 0;let u=Math.min(1,Math.max(-1,xe(i,s)/(c*l))),m=xe(Ve(i,s),n)/(c*l);return Math.atan2(m,u)}function wq(e,t,r,o){return Ee(t,Br(ke(we(r),o),se(e,t)))}var wx=180/Math.PI,hpe=(e,t,r)=>Math.max(t,Math.min(r,e)),Mq=[NaN,NaN,NaN];function tg(e){let t=we(e.spinAxis),r=we(se(e.uprightUpper,e.uprightLower)),o=-Math.asin(hpe(t[2],-1,1))*wx,n=Math.atan2(t[0],t[1])*wx,a=Math.atan2(-r[0],r[2])*wx,i=Math.atan2(-r[1],r[2])*wx,s=we(Ee([0,0,-1],ke(t,t[2]))),c=Ee(e.wheelCenter,ke(s,e.loadedRadius)),l=e.patchShift?[c[0]+e.patchShift.x,c[1]+e.patchShift.y,c[2]]:c,u=e.uprightLower,m=Math.abs(r[2])>1e-9,p=M=>Ee(u,ke(r,(M-u[2])/r[2])),d=m?p(l[2]):Mq,f=m?p(e.wheelCenter[2]):Mq,h=l[1]-d[1],g=d[0]-l[0],b=we(Ve(t,[0,0,1])),y=Ve([0,0,1],b),v=se(l,d),k=xe(v,y),x=-xe(v,b),S=e.wheelCenter[1]-f[1],R=f[0]-e.wheelCenter[0],w=iq(e.tieOuter,u,r);return{camber:o,toe:n,caster:a,kpi:i,scrubRadius:h,mechanicalTrail:g,scrubAtWheel:k,trailAtWheel:x,kingpinOffset:S,casterOffset:R,steeringArm:w,contactPatch:l,kingpinGround:d,kingpinAtHub:f}}function sr(e){return{corner:e,inv:HE(e),rocker:Sq(e.hardpoints)}}var gpe=[20,20,20,.2,.2,.2];function Aq(e,t,r,o=[0,0,0,0,0,0]){let n=yq(e,t,r,o);if(!n.free)return n;let a=bpe(e,t,r,o);return{x:a.x,converged:a.converged,margin:0}}function bpe(e,t,r,o=[0,0,0,0,0,0]){return mq(n=>WE(e,n,t,r),o,{scales:gpe,tol:1e-10,maxIter:40})}var ype=.01,Mx=1.2,Sr=e=>e.ok?e.state:null,Pr=e=>e.ok?e.state:e.nearest;function st(e,t,r,o,n){let a=0,i=zt(e,a,r,o,n);if(Math.abs(i.travel-t)<1e-4)return _q(i,t,!1);let c=(zt(e,.02,r,XE(i),n).travel-i.travel)/.02;(!Number.isFinite(c)||Math.abs(c)<1e-6)&&(c=1);let l=p=>Math.max(-Mx,Math.min(Mx,p)),u=l((t-i.travel)/c),m=zt(e,u,r,XE(i),n);for(let p=0;p<12&&!(Math.abs(m.travel-t)<1e-4);p++){let d=m.travel-i.travel,f=Math.abs(d)<1e-9?u:u-(m.travel-t)*((u-a)/d);a=u,i=m,u=l(f),m=zt(e,u,r,XE(i),n)}return _q(m,t,Math.abs(u)===Mx)}function _q(e,t,r){let o=e.travel-t,n=Math.abs(o)<=ype,a=r&&!n;return e.converged&&n?{ok:!0,reached:!0,travelMiss:o,clamped:!1,state:e}:{ok:!1,why:e.converged?"unreached":"unconverged",reached:n,travelMiss:o,clamped:a,nearest:e}}function XE(e){return{q:[e.pose.t[0],e.pose.t[1],e.pose.t[2],e.pose.omega[0],e.pose.omega[1],e.pose.omega[2]],phi:e.points.rockerAngle}}function vpe(e,t,r,o,n){switch(e){case"upright":return ao(t,r,n.pushrodOuter);case"upperArm":{let a=ao(t,r,t.ubj0),i=xq(t.ubj0,a,t.ucaFront,t.ucaDir);return wq(n.pushrodOuter,t.ucaFront,t.ucaDir,i)}default:return Rq(n.pushrodOuter,t.lcaFront,t.lcaDir,o)}}function zt(e,t,r,o,n){let{inv:a,corner:i}=e,s=o?.q??[0,0,0,0,0,0],c=Aq(a,t,r,s),l=c.x,u=[l[3],l[4],l[5]],m={t:[l[0],l[1],l[2]],omega:u},p=i.hardpoints,d=i.config,f=a.strut,h=f?f.top:ao(a,l,p.uprightUpper),g=ao(a,l,p.uprightLower),b=ao(a,l,p.tieOuter),y=ao(a,l,p.wheelCenter),v=we(Br(u,d.spinAxis)),k=vpe(f?"upright":d.pushrodAttach,a,l,t,p),x=f?f.top:p.damperChassis,S=f||d.actuation==="direct"?{phi:0,damperLength:yt(k,x),converged:!0,margin:1}:kq(e.rocker,k,o?.phi??0),R=tg({uprightUpper:h,uprightLower:g,wheelCenter:y,spinAxis:v,tieOuter:b,loadedRadius:n?.loadedRadius??d.loadedRadius,patchShift:n?.patchShift});return{pose:m,beta:t,travel:l[2],steer:r,points:{uprightUpper:h,uprightLower:g,tieOuter:b,wheelCenter:y,pushrodOuter:k,spinAxis:v,contactPatch:R.contactPatch,kingpinGround:R.kingpinGround,kingpinAtHub:R.kingpinAtHub,rockerAngle:S.phi,damperLength:S.damperLength},metrics:{camber:R.camber,toe:R.toe,caster:R.caster,kpi:R.kpi,scrubRadius:R.scrubRadius,mechanicalTrail:R.mechanicalTrail,scrubAtWheel:R.scrubAtWheel,trailAtWheel:R.trailAtWheel,kingpinOffset:R.kingpinOffset,casterOffset:R.casterOffset,steeringArm:R.steeringArm,damperLength:S.damperLength},converged:c.converged&&S.converged,margin:Math.min(c.margin,S.margin)}}var qm=e=>e==="FL"||e==="FR"?"front":"rear",Tq=e=>e==="FL"||e==="RL"?"left":"right";function Ut(e,t){return e.corners?.[t]??Spe(e[qm(t)],Tq(t))}function Pq(e){let t=e.config.springSplit;return e.config.actuation==="decoupled"||t===void 0||!Number.isFinite(t)||Math.abs(t)>=1?0:t}var Cq=new WeakMap;function Spe(e,t){let r=Pq(e);if(r===0)return e;let o=Cq.get(e);if(!o){let n=a=>{let{springSplit:i,...s}=e.config;return{...e,config:{...s,springRate:e.config.springRate*a},...e.measured?{measured:{...e.measured,springRate:e.measured.springRate*a}}:{}}};o={left:n(1-r),right:n(1+r)},Cq.set(e,o)}return o[t]}var qo=["FL","FR","RL","RR"],Rn=e=>2*e.hardpoints.wheelCenter[1],io=(e,t)=>t?Rn(Ut(e,"FL"))/2+Rn(Ut(e,"FR"))/2:Rn(Ut(e,"RL"))/2+Rn(Ut(e,"RR"))/2;function Zt(e,t){let r=e==="FL"||e==="FR";return{axleX:r?t.frontAxleX:t.frontAxleX-t.wheelbase,sideSign:e==="FR"||e==="RR"?1:-1,isFront:r}}function Nn(e,t){return[t.axleX+e[0],t.sideSign*e[1],e[2]]}function bi(e,t){return[e[0],t.sideSign*e[1],e[2]]}function Fs(e){return e.frontAxleX-e.wheelbase/2}function JE(e,t,r){return t[2]+e.heave+(t[0]-r)*Math.sin(e.pitch)-t[1]*Math.sin(e.roll)}function $s(e,t,r,o){let n=Zt(e,t),a=(o?io(o,n.isFront):n.isFront?t.trackFront:t.trackRear)/2,i=n.sideSign*a,s=n.axleX-Fs(t),c=-r.heave-s*Math.sin(r.pitch)+i*Math.sin(r.roll),l=n.isFront?n.sideSign*r.steer:0;return{travel:c,steer:l}}var kpe={travelMin:-40,travelMax:40,steps:41,steer:0};function rg(e){return{q:[e.pose.t[0],e.pose.t[1],e.pose.t[2],e.pose.omega[0],e.pose.omega[1],e.pose.omega[2]],phi:e.points.rockerAngle}}function Xt(e,t={}){let r={...kpe,...t},o=sr(e);return Hm(o,r)}function Hm(e,t){let r=t.steer,o=.01,n=zt(e,o,r),a=zt(e,-o,r),i=(n.travel-a.travel)/(2*o);(!Number.isFinite(i)||Math.abs(i)<1e-6)&&(i=1);let s=Math.max(Math.abs(t.travelMax),Math.abs(t.travelMin)),c=Math.min(1.2,1.5*s/Math.abs(i)),l=Math.max(20,t.steps*2),u=[],m=zt(e,0,r);u.push({beta:0,travel:m.travel,warm:rg(m),converged:m.converged});let p=rg(m);for(let v=1;v<=l;v++){let k=c*v/l,x=zt(e,k,r,p);p=rg(x),u.push({beta:k,travel:x.travel,warm:p,converged:x.converged})}p=rg(m);for(let v=1;v<=l;v++){let k=-c*v/l,x=zt(e,k,r,p);p=rg(x),u.push({beta:k,travel:x.travel,warm:p,converged:x.converged})}u.sort((v,k)=>v.beta-k.beta);let d=u[u.length-1].travel>=u[0].travel,f=!1;for(let v=1;v<u.length;v++){let k=u[v].travel-u[v-1].travel;(d&&k<-1e-6||!d&&k>1e-6)&&(f=!0)}let h=u.filter(v=>v.converged).map(v=>v.travel),g=h.length?[Math.min(...h),Math.max(...h)]:[0,0],b=h.length>0&&g[0]<=t.travelMin+1e-6&&g[1]>=t.travelMax-1e-6,y=[];for(let v=0;v<t.steps;v++){let k=t.steps===1?t.travelMin:t.travelMin+(t.travelMax-t.travelMin)*v/(t.steps-1),x=Rpe(u,k,d),S=xpe(u,x);y.push(zt(e,x,r,S))}return wpe(y,e.corner.config.actuation==="decoupled"?0:e.corner.config.springRate),{samples:y,covered:b,reach:g,fold:f,unconverged:y.filter(v=>!v.converged).length}}function Rpe(e,t,r){let o=r?e.slice():e.slice().reverse();if(t<=o[0].travel)return o[0].beta;if(t>=o[o.length-1].travel)return o[o.length-1].beta;for(let n=1;n<o.length;n++){let a=o[n-1],i=o[n];if(t>=Math.min(a.travel,i.travel)&&t<=Math.max(a.travel,i.travel)){let s=i.travel-a.travel,c=Math.abs(s)<1e-9?0:(t-a.travel)/s;return a.beta+c*(i.beta-a.beta)}}return o[o.length-1].beta}function xpe(e,t){let r=e[0],o=1/0;for(let n of e){let a=Math.abs(n.beta-t);a<o&&(o=a,r=n)}return r.warm}function QE(e,t,r){return r===0?(e[1]-e[0])/(t[1]-t[0]):r===e.length-1?(e[r]-e[r-1])/(t[r]-t[r-1]):(e[r+1]-e[r-1])/(t[r+1]-t[r-1])}function wpe(e,t){if(e.length<2)return;let r=e.map(i=>i.travel),o=e.map(i=>i.metrics.camber),n=e.map(i=>i.metrics.toe),a=e.map(i=>i.metrics.damperLength);for(let i=0;i<e.length;i++){let s=QE(o,r,i),c=QE(n,r,i),l=-QE(a,r,i);e[i].metrics.camberGain=s,e[i].metrics.bumpSteer=c,e[i].metrics.motionRatio=l,e[i].metrics.wheelRate=t*l*l}}var Is=e=>e!==void 0&&Number.isFinite(e)&&e>0;function Mpe(e){return e&&Is(e.helperRate)&&Is(e.helperTravel)?{rate:e.helperRate,travel:e.helperTravel}:null}function eL(e,t,r){let o=t/e;return r?o+Math.min(t/r.rate,r.travel):o}function ng(e,t,r,o){if(!(e>0)||!Number.isFinite(e)||!(t>0)||!Number.isFinite(t))return null;let n=Mpe(o),a=-eL(e,t,n),i=Km(r,o);return{rate:e,preload:t,helper:n,free:a,pull:null,droop:i.droop??a,droopStated:i.droop!==null,bump:i.bump,holdsLoad:!0}}function Km(e,t){if(!Number.isFinite(e))return{droop:null,bump:null};let r=Is(t?.extended)&&t.extended>e?t.extended:null,o=r!==null&&Is(t?.stroke)?r-t.stroke:null;return{droop:r!==null?e-r:null,bump:o!==null&&o<e?e-o:null}}function tL(e,t){if(!Number.isFinite(e))return[];let r=[],o=t?.extended,n=t?.stroke,a=Is(o)&&o>e?o:null;return Is(o)&&a===null&&r.push("extendedTooShort"),Is(n)&&(a===null?Is(o)||r.push("strokeWithoutExtended"):a-n>=e&&r.push("strokeTooShort")),r}function rL(e,t){if(!(e>0)||!Number.isFinite(e))return null;let r=Km(t.length0,t.coilover),o=t.free===-1/0||t.pull!==null&&t.pull>=t.free;if(o&&r.droop===null&&r.bump===null)return null;let n=o?-1/0:t.free;return{rate:e,preload:n===-1/0?0:-e*n,helper:null,free:n,pull:o?null:t.pull,droop:r.droop??-1/0,droopStated:r.droop!==null,bump:r.bump,holdsLoad:!1}}function _pe(e,t){let{rate:r,preload:o,helper:n}=e;if(!n)return t>e.free-1e-9?o+r*t:e.pull!==null&&t<e.pull+1e-9?r*(t-e.pull):0;let a=eL(r,o,n)+t;if(a<=0)return 0;let i=n.rate*n.travel;return a>=i/r+n.travel?o>=i?o+r*t:r*(a-n.travel):a*r*n.rate/(r+n.rate)}function Ape(e,t){let{rate:r,preload:o,helper:n}=e;if(!n)return t>e.free-1e-9||e.pull!==null&&t<e.pull+1e-9?r:0;let a=eL(r,o,n)+t;return a<=0?0:a>=n.rate*n.travel/r+n.travel?r:r*n.rate/(r+n.rate)}function Wm(e,t){let r=_pe(e,t),o=e.free;return e.holdsLoad&&t<o&&e.droop<o&&(r+=.001*e.rate*(Math.max(t,e.droop)-o)),t<e.droop&&(r+=1e3*e.rate*(t-e.droop)),e.bump!==null&&t>e.bump&&(r+=1e3*e.rate*(t-e.bump)),r}function nL(e,t){let r=Ape(e,t),o=e.free;return e.holdsLoad&&t<o&&t>e.droop&&(r+=.001*e.rate),t<e.droop&&(r+=1e3*e.rate),e.bump!==null&&t>e.bump&&(r+=1e3*e.rate),r}function oL(e){let t=e.free,r=[t,e.droop];return e.helper&&r.push(e.helper.rate*e.helper.travel/e.rate+e.helper.travel+t),e.bump!==null&&r.push(e.bump),e.pull!==null&&r.push(e.pull),[...new Set(r.filter(Number.isFinite))].sort((o,n)=>o-n)}function _x(e){return e.holdsLoad?Math.max(0,e.free-e.droop):0}var Ax={min:-60,max:60,steps:61},aL=e=>({travel:[e.min,e.max],force:[0,0],motionRatio:[0,0],spring:null}),Fq=new WeakMap;function Cpe(e,t){let r=Fq.get(e.corner);r||Fq.set(e.corner,r=new Map);let o=`${t.min}|${t.max}|${t.steps}`,n=r.get(o);return n||r.set(o,n=Hm(e,{travelMin:t.min,travelMax:t.max,steps:t.steps,steer:0})),n}function ag(e,t,r=Ax,o=e.corner.config.coilover){let n=e.corner.config;if(n.actuation==="decoupled")return aL(r);let a=Cpe(e,r),i=Ppe(e,n.springRate,a.samples),s=[];for(let h of a.samples){let g=h.metrics.motionRatio;!h.converged||g===void 0||!Number.isFinite(g)||!Number.isFinite(h.metrics.damperLength)||s.length>0&&h.travel<=s[s.length-1].t+1e-6||s.push({t:h.travel,L:h.metrics.damperLength,mr:g})}if(s.length<2)return aL(r);let c=$pe(s,0);if(!(Math.abs(c.mr)>1e-6))return aL(r);let l=t/c.mr,u=ng(i,l,c.L,o),m=u?Tpe(s,oL(u).map(h=>c.L-h)):s,p=m.map(h=>(u?Wm(u,c.L-h.L):l+i*(c.L-h.L))*h.mr-t),d=h=>h===null?null:m.find(g=>g.L===c.L-h)?.t??null,f=u?oL(u).map(d).filter(h=>h!==null):[];return{travel:m.map(h=>h.t),force:p,motionRatio:m.map(h=>h.mr),spring:{rate:i,preload:l,length0:c.L,law:u},...u?{stops:{droop:d(u.droop),bump:d(u.bump)}}:{},...f.length?{kinks:f}:{},length:m.map(h=>h.L)}}function iL(e,t){if(!e.spring)return null;let r=e.travel.length,o=e.length;if(o&&o.length===r&&r>=2){let i=Ma(e.travel,t),s=(t-e.travel[i])/(e.travel[i+1]-e.travel[i]);return e.spring.length0-(o[i]+s*(o[i+1]-o[i]))}if(r<2)return 0;let n=64,a=0;for(let i=0;i<n;i++){let s=t*i/n,c=t*(i+1)/n;a+=(og(e,s)+og(e,c))/2*(c-s)}return a}function Tpe(e,t){let r=[...e];for(let o of t)for(let n=0;n+1<e.length;n++){let a=e[n],i=e[n+1];if(a.L===o)break;if((a.L-o)*(i.L-o)>=0)continue;let s=(o-a.L)/(i.L-a.L);r.push({t:a.t+s*(i.t-a.t),L:o,mr:a.mr+s*(i.mr-a.mr)});break}return r.sort((o,n)=>o.t-n.t),r.filter((o,n)=>n===0||o.t>r[n-1].t+1e-6)}function Ppe(e,t,r){let o=e.corner.compliance?.links?.pushRod;if(o===void 0||!(o>0)||!Number.isFinite(o)||!(t>0))return t;let n=e.corner.config.actuation==="direct"?o:Fpe(e,o,r);return!(n>0)||!Number.isFinite(n)?t:t*n/(t+n)}function Fpe(e,t,r){let o;for(let m of r)m.converged&&(!o||Math.abs(m.travel)<Math.abs(o.travel))&&(o=m);if(!o)return t;let n=e.corner.hardpoints,a=Gm(e.rocker,o.points.rockerAngle),i=we(se(n.rockerPivotB,n.rockerPivotA)),s=(m,p)=>Math.abs(xe(i,Ve(se(m,n.rockerPivotA),we(se(p,m))))),c=s(a.pushrod,o.points.pushrodOuter),l=s(a.damper,n.damperChassis);if(!(l>1e-9)||!(c>1e-9))return t;let u=c/l;return t*u*u}function og(e,t){let r=e.travel.length;if(r===0)return 0;if(r===1)return e.motionRatio[0];let o=Ma(e.travel,t),n=(t-e.travel[o])/(e.travel[o+1]-e.travel[o]);return e.motionRatio[o]+n*(e.motionRatio[o+1]-e.motionRatio[o])}function yi(e,t,r){if(!e.spring)return Ho(e,t);let{rate:o,preload:n,length0:a,law:i}=e.spring,s=og(e,0),c=a-r;return(i?Wm(i,c):n+o*c)*og(e,t)-n*s}function $pe(e,t){let r=Ma(e.map(i=>i.t),t),o=e[r],n=e[r+1],a=(t-o.t)/(n.t-o.t);return{L:o.L+a*(n.L-o.L),mr:o.mr+a*(n.mr-o.mr)}}function Ma(e,t){let r=e.length;if(t<=e[0])return 0;if(t>=e[r-1])return r-2;let o=0,n=r-1;for(;n-o>1;){let a=o+n>>1;e[a]<=t?o=a:n=a}return o}function Ho(e,t){let r=e.travel.length;if(r===0)return 0;if(r===1)return e.force[0];let o=Ma(e.travel,t),n=(t-e.travel[o])/(e.travel[o+1]-e.travel[o]);return e.force[o]+n*(e.force[o+1]-e.force[o])}function Ym(e,t){let r=e.travel.length;if(r<3)return ig(e,t);let o=Ma(e.travel,t),n=(e.force[o+1]-e.force[o])/(e.travel[o+1]-e.travel[o]),a=s=>s===0||s===r-1||e.kinks?.includes(e.travel[s])?n:(e.force[s+1]-e.force[s-1])/(e.travel[s+1]-e.travel[s-1]),i=Math.max(0,Math.min(1,(t-e.travel[o])/(e.travel[o+1]-e.travel[o])));return a(o)+i*(a(o+1)-a(o))}function ig(e,t){if(e.travel.length<2)return 0;let o=Ma(e.travel,t);return(e.force[o+1]-e.force[o])/(e.travel[o+1]-e.travel[o])}function Nt(e,t,r){let o=e.hardpoints;switch(t.attach){case"upright":{let n=se(t.outer,o.wheelCenter);return Ee(Ee(Br(r.pose.omega,n),o.wheelCenter),r.pose.t)}case"lowerArm":{let n=we(se(o.lcaRear,o.lcaFront));return Ee(o.lcaFront,Br(ke(n,r.beta),se(t.outer,o.lcaFront)))}case"rocker":{let n=we(se(o.rockerPivotB,o.rockerPivotA));return Ee(o.rockerPivotA,oo(se(t.outer,o.rockerPivotA),n,r.points.rockerAngle))}}}function _a(e,t,r){return e.config.actuation==="decoupled"&&t.attach==="rocker"&&r==="coil"}function sL(e,t,r){return _a(e,t,r)?[t.inner[0],-t.inner[1],t.inner[2]]:t.inner}function Zm(e,t,r){let o=r.travelMin??-40,n=r.travelMax??40,a=r.steps??21;return cL(e,t,r.kind,Xt(e,{travelMin:o,travelMax:n,steps:a}).samples)}function cL(e,t,r,o){let n=we(se(t.outer,sL(e,t,r))),a=[],i=[],s=t.outer;for(let d of o)a.push(d.travel),i.push(xe(se(Nt(e,t,d),s),n));let c=a.length,l=new Array(c).fill(0);for(let d=0;d<c;d++){let f=Math.max(0,d-1),h=Math.min(c-1,d+1),g=a[h]-a[f];l[d]=g!==0?(i[h]-i[f])/g:0}let u=l[0];for(let d=1;d<c;d++)if(a[d]>=0){let f=a[d]-a[d-1],h=f!==0?(0-a[d-1])/f:0;u=l[d-1]+h*(l[d]-l[d-1]);break}let m=l.filter(d=>Math.abs(d)>1e-9).map(Math.sign),p=m.length>0&&m.some(d=>d!==m[0]);return{travel:a,ratio:l,linkTravel:i,atDesign:u,reverses:p}}function lL(e,t){let{travel:r,ratio:o}=e,n=r.length;if(n===0)return 0;if(t<=r[0])return o[0];if(t>=r[n-1])return o[n-1];let a=0,i=n-1;for(;i-a>1;){let c=a+i>>1;r[c]<=t?a=c:i=c}let s=(t-r[a])/(r[i]-r[a]);return o[a]+s*(o[i]-o[a])}function uL(e,t){let{travel:r,linkTravel:o}=e,n=r.length;if(n===0)return 0;if(t<=r[0])return o[0];if(t>=r[n-1])return o[n-1];let a=0,i=n-1;for(;i-a>1;){let c=a+i>>1;r[c]<=t?a=c:i=c}let s=(t-r[a])/(r[i]-r[a]);return o[a]+s*(o[i]-o[a])}var sg=e=>e.mount??{kind:"rockerToRocker"},Lq=e=>[e[0],0,e[2]],Ipe=e=>2*Math.abs(e[1]),Epe=(e,t)=>Math.hypot(e[0]-t[0],e[2]-t[2]);function Tx(e,t){return t.kind==="chassis"?Epe(e,t.anchor):Ipe(e)}function cg(e,t,r){if(r.kind==="chassis"){let i=[(e[0]+t[0])/2,(e[1]-t[1])/2,(e[2]+t[2])/2];return Math.hypot(i[0]-r.anchor[0],i[1],i[2]-r.anchor[2])}let o=e[0]-t[0],n=e[1]+t[1],a=e[2]-t[2];return Math.hypot(o,n,a)}function Jc(e,t,r={}){let o=r.travelMin??-40,n=r.travelMax??40,a=r.steps??21;return mL(e,t,Xt(e,{travelMin:o,travelMax:n,steps:a}).samples)}function mL(e,t,r){let o=sg(t),n=f=>Nt(e,{...t,inner:t.outer},r[f]),a=[],i=[],s=[];for(let f=0;f<r.length;f++)a.push(r[f].travel),s.push(Tx(n(f),o));let c=Iq(a,s,0);for(let f of s)i.push(c-f);let l=a.length,u=new Array(l).fill(0);for(let f=0;f<l;f++){let h=Math.max(0,f-1),g=Math.min(l-1,f+1),b=a[g]-a[h];u[f]=b!==0?(i[g]-i[h])/b:0}let m=$q(a,20),p=$q(a,-20),d=cg(n(m),n(p),o);return{travel:a,ratio:u,springTravel:i,atDesign:Iq(a,u,0),installedLength:c,rollSensitivity:c-d}}function $q(e,t){let r=0,o=1/0;for(let n=0;n<e.length;n++){let a=Math.abs(e[n]-t);a<o&&(o=a,r=n)}return r}function Iq(e,t,r){let o=e.length;if(o===0)return 0;if(r<=e[0])return t[0];if(r>=e[o-1])return t[o-1];for(let n=1;n<o;n++)if(e[n]>=r){let a=e[n]-e[n-1],i=a!==0?(r-e[n-1])/a:0;return t[n-1]+i*(t[n]-t[n-1])}return t[o-1]}function dL(e,t,r){let o={outer:t.outer,attach:t.attach},n=Xt(e,{travelMin:-5,travelMax:5,steps:3}),a=f=>Lq(Nt(e,{...o,inner:o.outer},n.samples[f])),i=a(1),s=a(2),c=a(0),l=s[0]-c[0],u=s[2]-c[2],m=Math.hypot(l,u),p=m>1e-9?[l/m,u/m]:[0,1],d=r??Math.max(80,2*Math.abs(t.outer[1])*.5);return[i[0]+p[0]*d,0,i[2]+p[1]*d]}function pL(e,t){let r=e.hardpoints,o=r.rockerPivotA,n=Eq(Cx(r.rockerPivotB,r.rockerPivotA)),a=Math.max(30,.6*Dq(Cx(r.rockerToDamper,o))),i=Cx(r.rockerToDamper,o),s=Eq(Cx(i,Lpe(n,Dpe(i,n)))),c=Npe(n,s),l=null,u=-1/0;for(let m=0;m<360;m+=10){let p=m*Math.PI/180,f={outer:[o[0]+a*(Math.cos(p)*s[0]+Math.sin(p)*c[0]),o[1]+a*(Math.cos(p)*s[1]+Math.sin(p)*c[1]),o[2]+a*(Math.cos(p)*s[2]+Math.sin(p)*c[2])],attach:"rocker"},h=t==="chassis"?{...f,mount:{kind:"chassis",anchor:dL(e,f)}}:f,g;try{g=Jc(e,h,{travelMin:-20,travelMax:20,steps:9})}catch{continue}let b=g.atDesign/(1+4*Math.abs(g.rollSensitivity));Number.isFinite(b)&&b>u&&(u=b,l=h)}return l??{outer:r.rockerToDamper,attach:"rocker"}}var Cx=(e,t)=>[e[0]-t[0],e[1]-t[1],e[2]-t[2]],Lpe=(e,t)=>[e[0]*t,e[1]*t,e[2]*t],Dpe=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],Dq=e=>Math.hypot(e[0],e[1],e[2]),Eq=e=>{let t=Dq(e)||1;return[e[0]/t,e[1]/t,e[2]/t]},Npe=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]];var fL=.001,Ope=e=>({outer:e.outer,inner:e.outer,attach:e.attach}),Gq=(e,t,r)=>(Tx(e.at0,t)-Tx(r,t))/2,zpe=(e,t)=>xe(se(t,e.pickup.at0),e.axis);function hL(e,t){let r=e.length;return t.map((o,n)=>{let a=Math.max(0,n-1),i=Math.min(r-1,n+1);return(t[i]-t[a])/(e[i]-e[a])})}function Nq(e,t){let r=[0,1,2].map(o=>hL(e,t.map(n=>n[o])));return t.map((o,n)=>[r[0][n],r[1][n],r[2][n]])}function gL(e){return{travel:e,heave:e.map(t=>t/2),heaveRatio:e.map(()=>.5),roll:[...e],rollRatio:e.map(()=>1)}}function Oq(e,t,r,o){let n=e.corner;if(!t.heave&&!t.roll)return{side:gL([o.min,o.max]),pickups:{}};let a=Pr(st(e,0,0)),i={};if(t.heave&&r){let h=Ope(t.heave);i.heave={corner:n,link:h,at0:Nt(n,h,a)}}if(t.roll){let h=t.roll;i.roll={pickup:{corner:n,link:h,at0:Nt(n,h,a)},axis:we(se(h.outer,sL(n,h,t.rollKind??"coil")))}}let s=t.roll&&_a(n,t.roll,t.rollKind??"coil")?{near:t.roll,far:{...t.roll,outer:t.roll.inner}}:null,c=Hm(e,{travelMin:o.min,travelMax:o.max,steps:o.steps,steer:0}),l=[],u=[],m=[],p=[],d=[];for(let h of c.samples)!h.converged||l.length>0&&h.travel<=l[l.length-1]+1e-6||(l.push(h.travel),u.push(i.heave&&r?Gq(i.heave,r,Nt(n,i.heave.link,h)):h.travel/2),m.push(i.roll?zpe(i.roll,Nt(n,i.roll.pickup.link,h)):h.travel),s&&(p.push(Nt(n,s.near,h)),d.push(Nt(n,s.far,h))));if(l.length<2)return{side:gL([o.min,o.max]),pickups:{}};let f={travel:l,heave:u,heaveRatio:hL(l,u),roll:m,rollRatio:hL(l,m)};return s&&(f.eyes={near:p,nearRatio:Nq(l,p),far:d,farRatio:Nq(l,d)}),{side:f,pickups:i}}function Px(e,t,r){let o=Ma(e,r);return t[o]+(r-e[o])/(e[o+1]-e[o])*(t[o+1]-t[o])}function zq(e,t,r){let o=Ma(e,r);return(t[o+1]-t[o])/(e[o+1]-e[o])}function Vt(e,t){return{h:Px(e.travel,e.heave,t),dh:Px(e.travel,e.heaveRatio,t),ddh:zq(e.travel,e.heaveRatio,t),r:Px(e.travel,e.roll,t),dr:Px(e.travel,e.rollRatio,t),ddr:zq(e.travel,e.rollRatio,t)}}function Vq(e,t,r,o){let n=Ma(e,o),a=e[n+1]-e[n],i=(o-e[n])/a,s=(u,m)=>[u[0]+i*(m[0]-u[0]),u[1]+i*(m[1]-u[1]),u[2]+i*(m[2]-u[2])],c=r[n],l=r[n+1];return{p:s(t[n],t[n+1]),d:s(c,l),dd:[(l[0]-c[0])/a,(l[1]-c[1])/a,(l[2]-c[2])/a]}}var bL=(e,t)=>Math.hypot(e[0]-t[0],e[1]+t[1],e[2]-t[2]);function lg(e,t){let r=e.side[0].eyes,o=e.side[1].eyes;if(!r||!o)return null;let n=Vq(e.side[0].travel,r.near,r.nearRatio,t[0]),a=Vq(e.side[1].travel,o.far,o.farRatio,t[1]),i=[n.p[0]-a.p[0],n.p[1]+a.p[1],n.p[2]-a.p[2]],s=Math.hypot(i[0],i[1],i[2]),c=[i[0]/s,i[1]/s,i[2]/s],l=n.d,u=[-a.d[0],a.d[1],-a.d[2]],m=[-a.dd[0],a.dd[1],-a.dd[2]],p=xe(c,l),d=xe(c,u),f=(xe(l,u)-p*d)/s;return{L:s,dL:[p,d],ddL:[[(xe(l,l)-p*p)/s+xe(c,n.dd),f],[f,(xe(u,u)-d*d)/s+xe(c,m)]]}}var qq=(e,t)=>e.bump!==null&&t>e.bump?e.rate*(t-e.bump):e.droop!==null&&t<e.droop?e.rate*(t-e.droop):0,Vpe=(e,t)=>e.bump!==null&&t>e.bump||e.droop!==null&&t<e.droop?e.rate:0;function ug(e,t,r,o,n=0){let a=e.rollStop;if(!a)return r;let i=lg(e,t);if(!i)return r;let s=qq(a,a.length0-(o??i.L+n));return s===0?r:[r[0]-s*i.dL[0],r[1]-s*i.dL[1]]}function Fx(e,t){let r=gL(e.travel);return t==="heave"?{...e,heave:r.heave,heaveRatio:r.heaveRatio}:{...e,roll:r.roll,rollRatio:r.rollRatio}}var $x=(e,t)=>e?e.law?Wm(e.law,t):e.preload+e.rate*t:0,jq=(e,t)=>e?e.law?nL(e.law,t):e.rate:0;function mg(e,t,r,o,n){let a=$x(e.heave,o),i=$x(e.roll,n);return[a*t.dh+i*t.dr,a*r.dh-i*r.dr]}var Bq=(e,t)=>Vt(e[0],t).h+Vt(e[1],t).h;function jpe(e,t){let r=e.gap>0?Bq(t,e.gap):0;return e.bothWays?{free:r,pull:e.gap>0?Bq(t,-e.gap):0}:{free:r,pull:null}}function Bpe(e,t,r){let o={...t,outer:t.inner},n=(u,m)=>{let p=Sr(st(e[0],u,0)),d=Sr(st(e[1],m,0));if(!p||!d)return NaN;let f=Nt(e[0].corner,t,p),h=Nt(e[1].corner,o,d);return Math.hypot(f[0]-h[0],f[1]+h[1],f[2]-h[2])},a=1,i=n(0,0),s=n(-a,a)-n(a,-a),c=Vt(r[0],a).r-Vt(r[1],-a).r-(Vt(r[0],-a).r-Vt(r[1],a).r),l=s/c;return Number.isFinite(i)&&i>0&&Number.isFinite(l)&&Math.abs(l)>fL?{length0:i,scale:l}:null}function Hq(e,t,r,o=Ax){let n=r.heave?sg(r.heave):void 0,a=Oq(e[0],r,n,o),i=e[1].corner===e[0].corner?a:Oq(e[1],r,n,o),s=[a.side,i.side],c=!!(a.pickups.heave&&i.pickups.heave),l=!!(a.pickups.roll&&i.pickups.roll),u=r.carriesLoad?void 0:r.heaveSeat,m=u?u.rate:(t[0].heaveRate+t[1].heaveRate)/2,p=(t[0].arbRate+t[1].arbRate)/2,d=s.map(F=>Vt(F,0));c&&!(Math.abs(d[0].dh+d[1].dh)>fL)&&(s=[Fx(s[0],"heave"),Fx(s[1],"heave")],c=!1),l&&!(Math.abs(d[0].dr+d[1].dr)>fL)&&(s=[Fx(s[0],"roll"),Fx(s[1],"roll")],l=!1),d=s.map(F=>Vt(F,0));let f=d[0].dh+d[1].dh,h=d[0].dr+d[1].dr,g=m>0?2*m/(f*f):0,b=p>0?2*p/(h*h):0,y=0,v=0;if(r.carriesLoad){let F=[t[0].springLoad,t[1].springLoad];if(g>0&&b>0){let P=-d[0].dh*d[1].dr-d[1].dh*d[0].dr;Math.abs(P)>1e-12&&(y=(-F[0]*d[1].dr-F[1]*d[0].dr)/P,v=(d[0].dh*F[1]-d[1].dh*F[0])/P)}else g>0?y=(F[0]+F[1])/f:b>0&&(v=(F[0]-F[1])/h)}let k={};if(c&&n){let F=[a.pickups.heave,i.pickups.heave];k.heave={pickups:F,mount:n,span0:cg(F[0].at0,F[1].at0,n)}}let x=k.heave?k.heave.span0:NaN,S=k.heave?r.coilover:void 0,R=r.carriesLoad?ng(g,y,x,S):u?rL(g,{...jpe(u,s),length0:x,coilover:S}):null,w=g>0?{rate:g,preload:y,...R?{law:R}:{}}:null;if(l&&(k.roll={pickups:[a.pickups.roll.pickup,i.pickups.roll.pickup],axes:[a.pickups.roll.axis,i.pickups.roll.axis]},r.roll&&_a(e[0].corner,r.roll,r.rollKind??"coil"))){let F=Bpe(e,r.roll,s);F&&(k.roll.unit=F)}let M=b>0?{rate:b,preload:v}:null,T={side:s,heave:w,roll:M,force0:[0,0],carriesLoad:r.carriesLoad,read:k},A=k.roll?.unit,_=A&&b>0&&s[0].eyes&&s[1].eyes?Km(A.length0,r.rollCoilover):null;return A&&_&&(_.droop!==null||_.bump!==null)&&(T.rollStop={length0:A.length0,rate:1e3*b/(A.scale*A.scale),..._}),T.force0=ug(T,[0,0],mg(T,d[0],d[1],d[0].h+d[1].h,d[0].r-d[1].r)),T}function dg(e,t,r){let o=Vt(e.side[0],t[0]),n=Vt(e.side[1],t[1]),a=r?ug(e,t,mg(e,o,n,o.h+n.h+r.heave,o.r-n.r+r.roll),void 0,r.unit):ug(e,t,mg(e,o,n,o.h+n.h,o.r-n.r));return[a[0]-e.force0[0],a[1]-e.force0[1]]}function yL(e,t,r){let o=Vt(e.side[0],t[0]),n=Vt(e.side[1],t[1]),a=r?o.h+n.h+r.heave:o.h+n.h,i=r?o.r-n.r+r.roll:o.r-n.r,s=jq(e.heave,a),c=jq(e.roll,i),l=$x(e.heave,a),u=$x(e.roll,i),m=s*o.dh*n.dh-c*o.dr*n.dr,p=[[s*o.dh*o.dh+l*o.ddh+c*o.dr*o.dr+u*o.ddr,m],[m,s*n.dh*n.dh+l*n.ddh+c*n.dr*n.dr-u*n.ddr]],d=e.rollStop,f=d?lg(e,t):null;if(!d||!f)return p;let h=d.length0-(r?f.L+r.unit:f.L),g=Vpe(d,h);if(g===0)return p;let b=qq(d,h),y=(k,x)=>g*f.dL[k]*f.dL[x]-b*f.ddL[k][x],v=m+y(0,1);return[[p[0][0]+y(0,0),v],[v,p[1][1]+y(1,1)]]}function vL(e,t,r){let o=yL(e,t);return o[r][0]+o[r][1]}function Upe(e,t,r){let o=e.read.heave;if(!o)return Vt(e.side[0],t[0]).h+Vt(e.side[1],t[1]).h;let[n,a]=o.pickups;return o.span0-cg(Nt(n.corner,n.link,r[0]),Nt(a.corner,a.link,r[1]),o.mount)}function Gpe(e,t,r){let o=e.read.roll;if(!o)return Vt(e.side[0],t[0]).r-Vt(e.side[1],t[1]).r;let n=a=>xe(se(Nt(o.pickups[a].corner,o.pickups[a].link,r[a]),o.pickups[a].at0),o.axes[a]);return n(0)-n(1)}function qpe(e,t){let r=e.read.roll;if(!e.rollStop||!r)return;let[o,n]=r.pickups;return bL(Nt(o.corner,o.link,t[0]),Nt(n.corner,{...n.link,outer:n.link.inner},t[1]))}function pg(e,t,r){let o=Vt(e.side[0],t[0]),n=Vt(e.side[1],t[1]),a=ug(e,t,mg(e,o,n,Upe(e,t,r),Gpe(e,t,r)),qpe(e,r));return[a[0]-e.force0[0],a[1]-e.force0[1]]}function SL(e,t,r,o){let n=Vt(e.side[0],r),a=Vt(e.side[1],r),i=e.read.heave,s=i?.pickups[t],c=i&&s&&o?2*Gq(s,i.mount,Nt(s.corner,s.link,o)):n.h+a.h,l=e.rollStop&&o?e.read.roll?.pickups[t]:void 0,u=l&&o?bL(Nt(l.corner,l.link,o),Nt(l.corner,{...l.link,outer:l.link.inner},o)):void 0;return ug(e,[r,r],mg(e,n,a,c,o?0:n.r-a.r),u)[t]-e.force0[t]}function kL(e,t,r,o){let n=Ym(e,r[o]);return t?.carriesLoad?n+vL(t,r,o):n}function Kq(e,t){return Vt(e.side[0],t[0]).h+Vt(e.side[1],t[1]).h}function Wq(e,t){return lg(e,t)?.L??null}function Ix(e,t){let r=e.side[0].travel,o=n=>Vt(e.side[0],n).h+Vt(e.side[1],n).h-t;for(let n=0;n+1<r.length;n++){let a=o(r[n]),i=o(r[n+1]);if(a===0)return r[n];if(a*i<0)return r[n]+a/(a-i)*(r[n+1]-r[n])}return o(r[r.length-1])===0?r[r.length-1]:null}function Yq(e,t){let r=e.rollStop;if(!r||!lg(e,[0,0]))return[];let o=e.side[1].travel,n=e.side[0].travel.filter(c=>-c>=o[0]&&-c<=o[o.length-1]),a=c=>r.length0-lg(e,[c,-c]).L-t,i=n.map(a),s=[];for(let c=0;c<n.length;c++){if(i[c]===0&&s.push(n[c]),c+1>=n.length||!(i[c]*i[c+1]<0))continue;let l=n[c],u=n[c+1],m=i[c];for(let p=0;p<50;p++){let d=(l+u)/2,f=a(d);m*f<=0?u=d:(l=d,m=f)}s.push((l+u)/2)}return s}var RL=e=>e==="FR"||e==="RR"?1:0,Ex=(e,t)=>e.elements?.[t==="FL"||t==="FR"?"front":"rear"]??null;var Zq=e=>Number.isFinite(e)&&e>0?1/e:0;var Xq=(e,t)=>{let r=e[0][0]*e[1][1]-e[0][1]*e[1][0];return Math.abs(r)>1e-14?[(t[0]*e[1][1]-t[1]*e[0][1])/r,(e[0][0]*t[1]-e[1][0]*t[0])/r]:null},Hpe=(e,t)=>[e[0][0]*t[0]+e[0][1]*t[1],e[1][0]*t[0]+e[1][1]*t[1]],Jq=1e-8,Kpe=40;function Wpe(e,t,r,o){return{force:(i,s)=>{if(r){let u=dg(r,i,o);return[Ho(t[0],i[0])+s[0]+u[0],Ho(t[1],i[1])+s[1]+u[1]]}let c=(i[0]+i[1])/2,l=(i[0]-i[1])/2;return[Ho(t[0],i[0])+s[0]+e[0].heaveRate*c+e[0].arbRate*l,Ho(t[1],i[1])+s[1]+e[1].heaveRate*c-e[1].arbRate*l]},stiffness:(i,s=ig)=>{if(r){let c=yL(r,i,o);return[[s(t[0],i[0])+c[0][0],c[0][1]],[c[1][0],s(t[1],i[1])+c[1][1]]]}return[[s(t[0],i[0])+e[0].heaveRate/2+e[0].arbRate/2,e[0].heaveRate/2-e[0].arbRate/2],[e[1].heaveRate/2-e[1].arbRate/2,s(t[1],i[1])+e[1].heaveRate/2+e[1].arbRate/2]]}}}function Xm(e,t,r,o,n,a=[0,0],i=[0,0],s=null,c){let l=[Zq(r[0].tyreRate),Zq(r[1].tyreRate)],u=[r[0].staticLoad,r[1].staticLoad],m=Wpe(r,o,s,c),p=P=>m.force(P,a),d=m.stiffness([0,0]),f=[l[0]>0?l[0]:1/Math.max(1,Math.abs(d[0][0])),l[1]>0?l[1]:1/Math.max(1,Math.abs(d[1][1]))],h=(P,I)=>{let z=I===1?p(P):m.force(P,[a[0]*I,a[1]*I]),N=[z[0]+i[0]*I,z[1]+i[1]*I],q=[P[0]+t[0]*I+N[0]*l[0]-e[0]*I,P[1]+t[1]*I+N[1]*l[1]-e[1]*I],U=[f[0]*(u[0]+N[0]),f[1]*(u[1]+N[1])],B=[U[0]<q[0],U[1]<q[1]];return{f:N,on:q,off:U,lifted:B,r:[Math.min(q[0],U[0]),Math.min(q[1],U[1])]}},g=(P,I)=>[I[0]?[f[0]*P[0][0],f[0]*P[0][1]]:[1+P[0][0]*l[0],P[0][1]*l[0]],I[1]?[f[1]*P[1][0],f[1]*P[1][1]]:[P[1][0]*l[1],1+P[1][1]*l[1]]],b=P=>Math.max(Math.abs(P[0]),Math.abs(P[1])),y=(P,I)=>{let z=[P[0],P[1]],N=h(z,I),q=!1,U=0;for(;U<Kpe;U++){if(b(N.r)<Jq){q=!0;break}let B=Xq(g(m.stiffness(z),N.lifted),[-N.r[0],-N.r[1]]);if(!B)break;let V=1,E=[z[0]+B[0],z[1]+B[1]],C=h(E,I);for(let $=0;$<8&&b(C.r)>b(N.r);$++)V/=2,E=[z[0]+V*B[0],z[1]+V*B[1]],C=h(E,I);z=E,N=C}return!q&&b(N.r)<Jq&&(q=!0),{t:z,b:N,converged:q,it:U}},v=y(n?[n[0],n[1]]:[e[0]-t[0],e[1]-t[1]],1),k=v.it;if(!v.converged){let P=0,I=[0,0],z=.25;for(;P<1&&z>=1/256;){let N=Math.min(1,P+z),q=y(I,N);k+=q.it,q.converged?(P=N,I=q.t,N===1&&(v=q)):z/=2}}let{t:x,b:S,converged:R}=v,w=S.lifted,M=[w[0]?-u[0]:S.f[0],w[1]?-u[1]:S.f[1]],T=[w[0]?Math.max(0,S.on[0]):0,w[1]?Math.max(0,S.on[1]):0],A=m.stiffness(x,Ym),_=g(A,w);return{t:x,dF:M,lifted:w,clearance:T,converged:R,iterations:k,respond:(P,I,z=[0,0])=>{let N=[w[0]?-f[0]*z[0]:P[0]-I[0]-z[0]*l[0],w[1]?-f[1]*z[1]:P[1]-I[1]-z[1]*l[1]],q=Xq(_,N);if(!q)return[NaN,NaN];let U=Hpe(A,q);return[w[0]?0:U[0]+z[0],w[1]?0:U[1]+z[1]]}}}var Qc=e=>!(Number.isFinite(e.tyreRate)&&e.tyreRate>0);function so(e,t,r){return t?.input.corners[r].staticLoadedRadius??e}var xL=["FL","FR","RL","RR"],tH={front:["FL","FR"],rear:["RL","RR"]},Ype=512,Zpe=5e-4,Xpe=8;function Lx(e,t){let r={},o={},n=new Map;for(let i of xL){let s=e.ctx[i],c=t.corners[i],l=c.staticLoadedRadius;o[i]=Pr(st(s,0,0,void 0,l===void 0?void 0:{loadedRadius:l})).points.contactPatch[2];let u=t.cornerCoilover?.[i==="FL"||i==="FR"?"front":"rear"],m=`${xL.findIndex(d=>Ut(e.vehicle,d)===Ut(e.vehicle,i))}|${c.springLoad}|${u?`${u.extended}/${u.stroke}`:""}`,p=n.get(m);p?r[i]=p:(r[i]=u?ag(s,c.springLoad,void 0,u):ag(s,c.springLoad),n.set(m,r[i]))}let a={front:null,rear:null};for(let i of["front","rear"]){let s=t.elements?.[i];if(!s)continue;let c=tH[i];a[i]=Hq([e.ctx[c[0]],e.ctx[c[1]]],[t.corners[c[0]],t.corners[c[1]]],s)}return{input:t,curve:r,elements:a,ground0:o,memo:new Map}}function rH(e,t,r){if(!(r>0)||!Number.isFinite(r)||!Number.isFinite(t)||t<=0)return 0;let o=Math.min(t/r,e);return 2*Math.sqrt(Math.max(0,2*e*o-o*o))}var Jpe=e=>`${e.heave}|${e.pitch}|${e.roll}|${e.steer}`;function wL(e,t,r){return{travel:r.travel,steer:r.steer,ground:r.travel,tyreDeflection:0,load:NaN,loadedRadius:so(Ut(e.vehicle,t).config.loadedRadius,e.kc,t),lifted:!1,contactLength:0,converged:!0,rigid:!0,rideRate:NaN,wheelRateAtLoad:NaN}}var Qpe=e=>e?{q:[e.pose.t[0],e.pose.t[1],e.pose.t[2],e.pose.omega[0],e.pose.omega[1],e.pose.omega[2]],phi:e.points.rockerAngle}:void 0;function Qq(e,t,r,o){let n=tH[o],a=e.vehicle.config,i=n.map(M=>$s(M,a,r,e.vehicle)),s=[t.input.corners[n[0]],t.input.corners[n[1]]],c=t.loadCase;if(!c&&s.every(Qc))return{corners:[wL(e,n[0],i[0]),wL(e,n[1],i[1])],respond:null};let l=n.map(M=>t.curve[M]),u=t.elements?.[o]??null,m=n.map(M=>so(Ut(e.vehicle,M).config.loadedRadius,t,M)),p=[i[0].travel+(c?.ground[n[0]]??0),i[1].travel+(c?.ground[n[1]]??0)],d=[c?.linkLoad[n[0]]??0,c?.linkLoad[n[1]]??0],f=[c?.patchShift[n[0]],c?.patchShift[n[1]]],h=[0,0],g=[0,0],b,y=Xm(p,h,s,l,void 0,void 0,d,u),v=[void 0,void 0],k=[!0,!0],x=[0,0],S=!1;for(let M=0;M<Xpe;M++){M>0&&(y=Xm(p,h,s,l,b,g,d,u)),x=[Number.isFinite(s[0].tyreRate)&&s[0].tyreRate>0?y.dF[0]/s[0].tyreRate:0,Number.isFinite(s[1].tyreRate)&&s[1].tyreRate>0?y.dF[1]/s[1].tyreRate:0];let T=[0,0],A=[0,0];for(let F=0;F<2;F++){let P=st(e.ctx[n[F]],y.t[F],i[F].steer,Qpe(v[F]),{loadedRadius:m[F]-x[F],patchShift:f[F]}),I=Pr(P);v[F]=I,k[F]=P.ok,T[F]=I.points.contactPatch[2]-t.ground0[n[F]]-y.t[F]-x[F],A[F]=yi(l[F],y.t[F],I.points.damperLength)-Ho(l[F],y.t[F])}if(u){let F=pg(u,y.t,[v[0],v[1]]),P=dg(u,y.t);A[0]+=F[0]-P[0],A[1]+=F[1]-P[1]}let _=Math.max(Math.abs(T[0]-h[0]),Math.abs(T[1]-h[1]),Math.abs(A[0]-g[0])/Math.max(1,s[0].tyreRate),Math.abs(A[1]-g[1])/Math.max(1,s[1].tyreRate));if(h=T,g=A,b=y.t,_<Zpe){S=!0;break}}let R=y.respond([1,1],[0,0]);return{corners:[0,1].map(M=>{let T=v[M];return{travel:y.t[M],steer:i[M].steer,ground:p[M],tyreDeflection:x[M],load:s[M].staticLoad+y.dF[M],loadedRadius:m[M]-x[M],lifted:y.lifted[M],clearance:y.clearance[M],contactLength:rH(m[M]-x[M],s[M].staticLoad+y.dF[M],s[M].tyreRate),converged:y.converged&&S&&k[M],rigid:!1,state:T,solved:k[M],rideRate:R[M],wheelRateAtLoad:kL(l[M],u,y.t,M)}}),respond:y.respond}}function nH(e,t){let r=e.kc,o=Jpe(t),n=r.memo.get(o);if(n)return n;let a=Qq(e,r,t,"front"),i=Qq(e,r,t,"rear"),s={corners:{FL:a.corners[0],FR:a.corners[1],RL:i.corners[0],RR:i.corners[1]},respond:{front:a.respond,rear:i.respond}};return r.memo.size>=Ype&&r.memo.clear(),r.memo.set(o,s),s}function rn(e,t){if(!e.kc){let r={};for(let o of xL)r[o]=wL(e,o,$s(o,e.vehicle.config,t,e.vehicle));return r}return nH(e,t).corners}function Dx(e,t,r){return e.kc?nH(e,t).respond[r]:null}function fg(e,t,r,o=0){let n=e.kc;if(!n)return r;let a=n.input.corners[t];if(Qc(a))return r;let i=$s(t,e.vehicle.config,{heave:0,pitch:0,roll:0,steer:o},e.vehicle).steer,s=so(Ut(e.vehicle,t).config.loadedRadius,n,t),c=n.loadCase,l=c?.linkLoad[t]??0,u=c?.patchShift[t],m=Pr(st(e.ctx[t],r,i,void 0,{loadedRadius:s,patchShift:u})),p=Ex(n,t),d=yi(n.curve[t],r,m.points.damperLength)+(p?SL(p,RL(t),r,m):a.heaveRate*r),h=Math.max(d+l,-a.staticLoad)/a.tyreRate;return(h===0?m:Pr(st(e.ctx[t],r,i,void 0,{loadedRadius:s-h,patchShift:u}))).points.contactPatch[2]-n.ground0[t]-(c?.ground[t]??0)}var efe=180/Math.PI,tfe=[0,0,1];function rfe(e,t){let r=bi(e,t),o=ke(Ve(tfe,r),-t.sideSign);return-Math.atan2(o[1],o[0])*efe}var oH=e=>1/Math.tan(e*Math.PI/180),aH=.05,iH=.001;function sH(e,t,r){if(!Number.isFinite(e)||!Number.isFinite(t))return NaN;if(!(Math.abs(e)<iH&&Math.abs(t)<iH))return e>0&&t>0?100*(oH(t)-oH(e))/r:NaN}function nfe(e,t){let r=io(e.vehicle,!0)/e.vehicle.config.wheelbase,o=t("FL",0).deg,n=t("FR",0).deg,a=(c,l)=>{let u=c+l>=0;return{left:u,inner:u?c:-l,outer:u?l:-c}},i,s=()=>{if(i===void 0){let c=[aH,-aH].map(l=>{let{inner:u,outer:m}=a(t("FL",l).deg-o,t("FR",l).deg-n);return sH(u,m,r)??NaN});i=(c[0]+c[1])/2}return i};return c=>{let l=t("FL",c),u=t("FR",c),{left:m,inner:p,outer:d}=a(l.deg-o,u.deg-n),f=sH(p,d,r);return{steerL:l.deg,steerR:u.deg,inner:p,outer:d,toeDiff:p-d,ackermannPct:f??s(),inside:f===void 0?null:m?"left":"right",converged:l.ok&&u.ok}}}function ML(e,t){let r=e.vehicle.config,o={FL:Zt("FL",r),FR:Zt("FR",r)},n=t.travel??0,a=nfe(e,(s,c)=>{let l=Sr(st(e.ctx[s],n,o[s].sideSign*c));return{deg:l?rfe(l.points.spinAxis,o[s]):NaN,ok:l!==null}}),i=[];for(let s=0;s<t.steps;s++){let c=t.steps===1?0:-t.steerMax+2*t.steerMax*s/(t.steps-1),{inside:l,...u}=a(c);i.push({steerInput:c,...u})}return i}var cH=35,lH=55,Fr=e=>e.rackTravel&&e.rackTravel>0?e.rackTravel:cH,_L=e=>e.rackRatio&&e.rackRatio>0?e.rackRatio:lH;var AL=e=>({q:[e.pose.t[0],e.pose.t[1],e.pose.t[2],e.pose.omega[0],e.pose.omega[1],e.pose.omega[2]],phi:e.points.rockerAngle});function uH(e,t,r,o,n){let a=st(e,o,0,void 0,n),i=Pr(a),s=a.ok?0:1,c=i.points.contactPatch[2],l={steer:i.metrics.toe,camber:i.metrics.camber,lift:0,contactPatch:i.points.contactPatch,spinAxis:i.points.spinAxis,yaw:-i.metrics.toe*Math.PI/180},u=d=>{let f=[l],h=AL(i);for(let g=1;g<=r;g++){let b=d*(t*g)/r,y=zt(e,i.beta,b,h,n),v=Sr(st(e,o,b,AL(y),n));if(!v||!y.converged){s++,f.push({...f[f.length-1]});continue}f.push({steer:v.metrics.toe,camber:v.metrics.camber,lift:-(y.points.contactPatch[2]-c),contactPatch:y.points.contactPatch,spinAxis:y.points.spinAxis,yaw:-y.metrics.toe*Math.PI/180}),h=AL(y)}return f},m=u(1),p=u(-1);return{travelMm:o,unsolved:s,centre:l,positive:m,negative:p}}function ofe(e,t){return e.map((r,o)=>{let n=o===0?0:o-1,a=o===e.length-1?e.length-1:o+1,i=t[a]-t[n];if(!(i>0))return{longitudinal:0,lateral:0,vertical:0,yaw:0};let s=ke(se(e[a].contactPatch,e[n].contactPatch),1/i),c=we(Ve(r.spinAxis,[0,0,1])),l=Ve([0,0,1],c);return{longitudinal:xe(s,c),lateral:xe(s,l),vertical:s[2],yaw:(e[a].yaw-e[n].yaw)/i}})}function mH(e,t,r){let o=n=>({steerDeg:n.map(a=>Math.abs(a.steer-e.centre.steer)),camberDeg:n.map(a=>a.camber-e.centre.camber),liftMm:n.map(a=>a.lift),jacobian:ofe(n,t)});return{travelMm:e.travelMm,inner:o(r?e.positive:e.negative),outer:o(r?e.negative:e.positive)}}function afe(e){return e.positive[1].steer-e.centre.steer<0}function ife(e,t,r){return{meanDeg:t.map((o,n)=>.5*(r.inner.steerDeg[n]+r.outer.steerDeg[n])),innerDeg:r.inner.steerDeg,outerDeg:r.outer.steerDeg,innerCamber:r.inner.camberDeg,outerCamber:r.outer.camberDeg,innerLift:r.inner.liftMm,outerLift:r.outer.liftMm,rackRatioMmPerRev:_L(e.config),innerJacobian:r.inner.jacobian,outerJacobian:r.outer.jacobian}}function CL(e,t,r=13,o=-40,n=40,a=5,i){let s=sr(e),c=Array.from({length:r+1},(g,b)=>t*b/r),l=uH(s,t,r,0,i),u=afe(l),m=mH(l,c,u),p=Math.max(2,Math.floor(a)),d=Array.from({length:p},(g,b)=>o+(n-o)*b/(p-1));d.some(g=>Math.abs(g)<1e-9)||d.push(0),d.sort((g,b)=>g-b);let f=l.unsolved,h=d.map(g=>{if(Math.abs(g)<1e-9)return m;let b=uH(s,t,r,g,i);return f+=b.unsolved,mH(b,c,u)});return{...ife(e,c,m),...dH(l.unsolved),travelSurface:{rackMm:c,rows:h,...dH(f)}}}var dH=e=>e>0?{unsolved:e}:{};function Aa(e,t,r){let o=e.length;if(o===0)return 0;if(r<=e[0])return t[0];if(r>=e[o-1])return t[o-1];let n=0,a=o-1;for(;a-n>1;){let s=n+a>>1;e[s]<=r?n=s:a=s}let i=(r-e[n])/(e[a]-e[n]);return t[n]+i*(t[a]-t[n])}function Nx(e,t,r){let o=e.length;if(o===0)return{longitudinal:0,lateral:0,vertical:0,yaw:0};let n,a;if(r<=e[0])n=a=0;else if(r>=e[o-1])n=a=o-1;else for(n=0,a=o-1;a-n>1;){let l=n+a>>1;e[l]<=r?n=l:a=l}let i=t[n];if(n===a)return{longitudinal:i.longitudinal,lateral:i.lateral,vertical:i.vertical,yaw:i.yaw};let s=t[a],c=(r-e[n])/(e[a]-e[n]);return{longitudinal:i.longitudinal+c*(s.longitudinal-i.longitudinal),lateral:i.lateral+c*(s.lateral-i.lateral),vertical:i.vertical+c*(s.vertical-i.vertical),yaw:i.yaw+c*(s.yaw-i.yaw)}}function pH(e,t){let r=e.rows;if(r.length<=1||t<=r[0].travelMm)return{lo:0,hi:0,t:0};let o=r.length-1;if(t>=r[o].travelMm)return{lo:o,hi:o,t:0};let n=0,a=o;for(;a-n>1;){let i=n+a>>1;r[i].travelMm<=t?n=i:a=i}return{lo:n,hi:a,t:(t-r[n].travelMm)/(r[a].travelMm-r[n].travelMm)}}var el=(e,t,r)=>e+r*(t-e);function Jm(e,t,r,o,n){let a=Aa(e.rackMm,e.rows[o.lo][t][r],n);if(o.lo===o.hi)return a;let i=Aa(e.rackMm,e.rows[o.hi][t][r],n);return el(a,i,o.t)}function fH(e,t,r,o){let n=Nx(e.rackMm,e.rows[r.lo][t].jacobian,o);if(r.lo===r.hi)return n;let a=Nx(e.rackMm,e.rows[r.hi][t].jacobian,o);return{longitudinal:el(n.longitudinal,a.longitudinal,r.t),lateral:el(n.lateral,a.lateral,r.t),vertical:el(n.vertical,a.vertical,r.t),yaw:el(n.yaw,a.yaw,r.t)}}function Qm(e,t,r,o){let n=e.travelSurface;if(!n||n.rackMm.length<2||n.rows.length===0)return ed(e,t);let a=pH(n,r),i=pH(n,o),s=(d,f,h)=>{let g=n.rows[f.lo][d].steerDeg[h];return f.lo===f.hi?g:el(g,n.rows[f.hi][d].steerDeg[h],f.t)},c=new Array(n.rackMm.length);for(let d=0;d<c.length;d++)c[d]=.5*(s("inner",a,d)+s("outer",i,d));let l=Math.max(0,t),u=c.length-1,m=n.rackMm[u],p=l>c[u];if(l<=c[0])m=n.rackMm[0],p=!1;else if(!p){let d=1;for(;d<c.length-1&&c[d]<l;)d++;let f=d-1,h=c[d]-c[f],g=Math.abs(h)>1e-12?(l-c[f])/h:0;m=el(n.rackMm[f],n.rackMm[d],g)}return{innerDeg:Jm(n,"inner","steerDeg",a,m),outerDeg:Jm(n,"outer","steerDeg",i,m),innerCamber:Jm(n,"inner","camberDeg",a,m),outerCamber:Jm(n,"outer","camberDeg",i,m),innerLift:Jm(n,"inner","liftMm",a,m),outerLift:Jm(n,"outer","liftMm",i,m),innerJacobian:fH(n,"inner",a,m),outerJacobian:fH(n,"outer",i,m),atLock:p}}function ed(e,t){let r=e.meanDeg.length-1;return{innerDeg:Aa(e.meanDeg,e.innerDeg,t),outerDeg:Aa(e.meanDeg,e.outerDeg,t),innerCamber:Aa(e.meanDeg,e.innerCamber,t),outerCamber:Aa(e.meanDeg,e.outerCamber,t),innerLift:e.innerLift?Aa(e.meanDeg,e.innerLift,t):0,outerLift:e.outerLift?Aa(e.meanDeg,e.outerLift,t):0,...e.innerJacobian&&e.outerJacobian?{innerJacobian:Nx(e.meanDeg,e.innerJacobian,t),outerJacobian:Nx(e.meanDeg,e.outerJacobian,t)}:{},atLock:r>=0&&t>e.meanDeg[r]}}var sfe=()=>({lift:{FL:0,FR:0,RL:0,RR:0},travel:{FL:0,FR:0,RL:0,RR:0},load:{FL:0,FR:0,RL:0,RR:0},rollDeg:0});function td(e,t,r=Lt(e),o){let n=e.steerFront;if(!n?.innerLift||!n.outerLift||n.meanDeg.length<2||Math.abs(t)<1e-12)return sfe();let a=Math.abs(t),i=t>0,s=o&&n.travelSurface?Qm(n,a,i?o.FL:o.FR,i?o.FR:o.FL):null,c=s?.innerLift??Aa(n.meanDeg,n.innerLift,a),l=s?.outerLift??Aa(n.meanDeg,n.outerLift,a),u=i?c:l,m=i?l:c,p=.5*(u+m),d=r.rollWheelRateFront,f=r.rollWheelRateRear,h=e.trackFront,g=e.trackRear,b=d*h*h+f*g*g,y=b>0?d*h*(m-u)/b:0,v={FL:u-p+.5*h*y,FR:m-p-.5*h*y,RL:.5*g*y,RR:-.5*g*y};return{lift:{FL:u,FR:m,RL:0,RR:0},travel:v,load:{FL:d*v.FL,FR:d*v.FR,RL:f*v.RL,RR:f*v.RR},rollDeg:y===0?0:-Math.atan(y)*180/Math.PI}}function TL(e,t,r){let o=t/r,n=a=>1/Math.tan(a*Math.PI/180);for(let a=0;a<e.meanDeg.length;a++)if(e.outerDeg[a]>.3&&e.innerDeg[a]>.3)return 100*(n(e.outerDeg[a])-n(e.innerDeg[a]))/o;return NaN}var hg=9.81;function rd(e,t,r=0,o=0,n=0){if(!e.aero||t<=0)return{FL:0,FR:0,RL:0,RR:0};let a=e.aero.model?gi(e,t,r,hi(e,o,n)):Zc(e.aero,t),i=a.downFront/2,s=a.downRear/2,c=a.drag*(e.aero.copHeight/1e3)/(e.wheelbase/1e3)/2;return{FL:i-c,FR:i-c,RL:s+c,RR:s+c}}function PL(e,t,r=0,o=0,n=0){if(!e.aero?.model||t<=0)return!1;let a=gi(e,t,r,hi(e,o,n));return a!=null&&(a.clampedRide||a.clampedAttitude)}function Ko(e){let t=e.loadFactor===void 0?e.massTotal*hg:e.massTotal*hg*e.loadFactor,r=t*e.frontMassFrac,o=t*(1-e.frontMassFrac);return{FL:r/2,FR:r/2,RL:o/2,RR:o/2}}function hH(e,t=Lt(e),r=e.cgHeight){let o=e.trackFront/1e3,n=e.trackRear/1e3,a=e.rcHeightFront/1e3,i=e.rcHeightRear/1e3,s=(e.rcHeightFront+(e.rcHeightRear-e.rcHeightFront)*(1-e.frontMassFrac))/1e3,c=r/1e3-s,l=2*e.unsprungPerCorner,u=e.unsprungCgHeight/1e3,m=t.sprungMass*c*fx(t.sprungMass,c,t.rollRateTotal),p=(m*t.frontRollStiffFrac+t.sprungFront*a+l*u)/o,d=(m*(1-t.frontRollStiffFrac)+t.sprungRear*i+l*u)/n;return{cf:p,cr:d}}function FL(e){let{cf:t,cr:r}=hH(e);return t+r>0?t/(t+r):.5}function gH(e,t,r){if(e.FL>=0&&e.FR>=0&&e.RL>=0&&e.RR>=0)return{loads:{FL:Math.max(0,e.FL),FR:Math.max(0,e.FR),RL:Math.max(0,e.RL),RR:Math.max(0,e.RR)},lifted:{FL:!1,FR:!1,RL:!1,RR:!1},overturned:!1};let o=e.FL+e.FR+e.RL+e.RR;if(!(o>0))return{loads:{FL:0,FR:0,RL:0,RR:0},lifted:{FL:!0,FR:!0,RL:!0,RR:!0},overturned:!0};let n=!1,a=e.FL+e.FR,i=e.RL+e.RR;a<0?(a=0,i=o,n=!0):i<0&&(i=0,a=o,n=!0);let s=(e.FR-e.FL)*t+(e.RR-e.RL)*r,c=Math.min(a,Math.max(-a,e.FR-e.FL)),l=Math.min(i,Math.max(-i,e.RR-e.RL)),u=s-(c*t+l*r);if(u!==0){let p=u>0?1:-1,d=(p*a-c)*t;p*u>=p*d?(c=p*a,u-=d):(c+=u/t,u=0);let f=(p*i-l)*r;u!==0&&(p*u>=p*f?(l=p*i,u-=f):(l+=u/r,u=0)),Math.abs(u)>1e-9*(Math.abs(s)+o*(t+r))&&(n=!0)}let m={FL:Math.max(0,(a-c)/2),FR:Math.max(0,(a+c)/2),RL:Math.max(0,(i-l)/2),RR:Math.max(0,(i+l)/2)};return{loads:m,lifted:{FL:m.FL===0,FR:m.FR===0,RL:m.RL===0,RR:m.RR===0},overturned:n}}function kt(e,t,r,o=0,n=0,a=0,i,s){return Ox(e,t,r,o,n,a,i,s).loads}function Ox(e,t,r,o=0,n=0,a=0,i,s){let c=Ko(e),l=Lt(e),u=Rx(e,o,r,hi(e,t,n),l),{cf:m,cr:p}=hH(e,l,u.height),d=m*t*hg,f=p*t*hg,h=e.massTotal*(r*hg)*u.height/e.wheelbase-u.noseLoad,g=rd(e,o,r,t,n),b=(s??td(e,a,l,i)).load,y={FL:c.FL-d-h/2+g.FL+b.FL,FR:c.FR+d-h/2+g.FR+b.FR,RL:c.RL-f+h/2+g.RL+b.RL,RR:c.RR+f+h/2+g.RR+b.RR};return gH(y,e.trackFront,e.trackRear)}var $L=Math.PI/180;function Vx(e,t){let r=8*$L,o=0,n=0;for(let a=1;a<=90;a++){let i=a*.5,s=Math.abs(e.Fy(i*$L,t,0));if(s>o&&(o=s,r=i*$L,n=a),a>n+12&&s<.995*o)break}return{aPeak:r,fyPeak:o}}function bH(e,t,r,o,n){if(o===t)return r;let a=(n-t)/(o-t);return a<=0?e:a>=1?r:e+a*(r-e)}var bg=.999;function On(e,t,r,o,n){if(t<=0)return 0;let{aPeak:a,fyPeak:i}=n??Vx(e,t),s=Math.min(Math.abs(r),bg*i),c=o?-1:1,l=(x,S)=>Math.abs(e.forces({Fz:t,kappa:c*x,alpha:S}).Fy),u=.3,m=u,p=l(u,a);if(p<s){let x=0,S=u,R=NaN,w=p;for(let M=0;M<9;M++){let T=.5*(x+S),A=l(T,a);A>=s?(x=T,R=A):(S=T,w=A)}Number.isNaN(R)&&(R=l(0,a)),m=R<s?0:bH(x,R,S,w,s)}if(m<=0)return 0;let d=x=>{if(s===0)return c*e.forces({Fz:t,kappa:c*x,alpha:0}).Fx;let S=0,R=a,w=NaN,M=NaN;for(let T=0;T<5;T++){let A=.5*(S+R),_=l(x,A);_<s?(S=A,w=_):(R=A,M=_)}return Number.isNaN(w)&&(w=l(x,0)),Number.isNaN(M)&&(M=l(x,a)),c*e.forces({Fz:t,kappa:c*x,alpha:bH(S,w,R,M,s)}).Fx},f=4,h=x=>m*x/f,g=[0],b=1;for(let x=1;x<=f;x++)g.push(d(h(x))),g[x]>g[b]&&(b=x);let[y,v]=b===f?[f-1,f-2]:g[b-1]>=g[b+1]?[b-1,b+1]:[b+1,b-1],k=mfe(d,h(b-1),h(Math.min(f,b+1)),h(b),g[b],h(y),g[y],h(v),g[v],cfe);return c*Math.max(0,k)}var cfe=.01,lfe=20,ufe=(3-Math.sqrt(5))/2;function mfe(e,t,r,o,n,a,i,s,c,l){n=-n,i=-i,c=-c;let u=r-t,m=0;for(let p=0;p<lfe;p++){let d=l*Math.abs(o)+1e-10,f=.5*(t+r);if(Math.abs(o-f)<=2*d-.5*(r-t))break;let h=!0;if(Math.abs(u)>d){let y=(o-a)*(n-c),v=(o-s)*(n-i),k=(o-s)*v-(o-a)*y;v=2*(v-y),v>0&&(k=-k),v=Math.abs(v);let x=u;if(u=m,Math.abs(k)<Math.abs(.5*v*x)&&k>v*(t-o)&&k<v*(r-o)){m=k/v;let S=o+m;(S-t<2*d||r-S<2*d)&&(m=f>=o?d:-d),h=!1}}h&&(u=o>=f?t-o:r-o,m=ufe*u);let g=Math.abs(m)>=d?o+m:o+(m>=0?d:-d),b=-e(g);b<=n?(g>=o?t=o:r=o,s=a,c=i,a=o,i=n,o=g,n=b):(g<o?t=g:r=g,b<=i||a===o?(s=a,c=i,a=g,i=b):(b<=c||s===o||s===a)&&(s=g,c=b))}return-n}function LL(e,t){return e.model?.kind==="simple"?null:SH(e,t)}var yH=new WeakMap,IL=100,vH=1.35,EL=18,Ca=41,zx=41,gg=65;function SH(e,t){let r=yH.get(e);if(r)return r;let o=Math.log(vH),n=(d,f)=>{let h=R=>Math.abs(On(e,d,R,f)),g=h(0),b=t.muY(d)*d,y=new Float64Array(Ca),v=g>0&&b>0?Math.max(1,t.muX(d)*d/g):1;if(!(g>0)||!(b>0))y.fill(1);else{let R=[],w=[];for(let T=0;T<zx;T++){let A=Math.sin(.5*Math.PI*T/(zx-1));R.push(A),w.push(T===0?1:T===zx-1?0:Math.min(w[T-1],h(A*b)/g))}let M=zx-1;for(let T=0;T<Ca;T++){let A=T/(Ca-1);for(;M>0&&w[M-1]<A;)M--;let _=M>0?w[M-1]-w[M]:0;y[T]=M===0?R[0]:R[M]+(_>0?(A-w[M])/_:0)*(R[M-1]-R[M])}y[0]=1,y[Ca-1]=0}let k=new Float64Array(gg),x=R=>Math.atan2(y[R],R/(Ca-1)/v),S=Ca-2;for(let R=0;R<gg;R++){let w=.5*Math.PI*R/(gg-1),M=Math.cos(w),T=Math.sin(w);for(;S>0&&x(S)<w;)S--;let A=S/(Ca-1)/v,_=y[S],F=(S+1)/(Ca-1)/v,P=y[S+1],I=M*(P-_)-T*(F-A),z=Math.abs(I)>1e-12?(A*(P-_)-_*(F-A))/I:Math.hypot(A,_);k[R]=z>0?z:Math.hypot(A,_)}return{room:y,scale:v,edge:k}},a=Array.from({length:EL},(d,f)=>IL*vH**f),i=a.map(d=>n(d,!1)),s=a.map(d=>n(d,!0)),c=(d,f)=>{let h=Math.min(1,Math.abs(f)*d.scale)*(Ca-1),g=Math.min(Ca-2,Math.floor(h));return d.room[g]+(h-g)*(d.room[g+1]-d.room[g])},l=d=>{let f=d>IL?Math.log(d/IL)/o:0;if(f>=EL-1)return[EL-2,1];let h=Math.floor(f);return[h,f-h]},u=(d,f,h)=>{if(h===0)return 1;let g=h<0?s:i,b=c(g[d],h);return f>0?b+f*(c(g[d+1],h)-b):b},m=(d,f,h)=>{let g=f<0?s:i,[b,y]=l(d),v=Math.atan2(Math.abs(h),Math.abs(f))/(.5*Math.PI)*(gg-1),k=Math.min(gg-2,Math.floor(v)),x=R=>R.edge[k]+(v-k)*(R.edge[k+1]-R.edge[k]),S=x(g[b]);return y>0?S+y*(x(g[b+1])-S):S},p={keeps(d,f){if(f===0)return 1;let[h,g]=l(d);return u(h,g,f)},atLoad(d){let[f,h]=l(d);return g=>u(f,h,g)},use(d,f,h){let g=Math.hypot(f,h);return g>0?Math.min(1,g/m(d,f,h)):0},reach:m};return yH.set(e,p),p}var dfe=[["front","FL","FR"],["rear","RL","RR"]];function nd(e,t,r,o){let n={...e},a=0,i=bg;for(let[s,c,l]of dfe){let u=(k,x)=>o(s,Math.max(0,x[k])).fyPeak,m=Math.min(i,e[c]),p=Math.min(i,e[l]),d=m*u(c,r)+p*u(l,r);if(!(d>0))continue;let f=u(c,t),h=u(l,t),g=m*f+p*h,b=g>0?d/g:1/0,y=m*b,v=p*b;y<=i?v<=i||(v=i,y=f>0?(d-i*h)/f:1/0):(y=i,v=h>0?(d-i*f)/h:1/0),(!(y<=i)||!(v<=i))&&(a+=Math.max(0,d-i*(f+h)),y=Math.min(i,y),v=Math.min(i,v)),n[c]=y,n[l]=v}return{util:n,short:a}}var kH=.001,pfe=1e-5,RH=100;function ffe(e,t,r,o){if(!(o>kH))return r;let n=t,a=Math.abs(r-t)<RH?t+Math.sign(r-t)*RH:r;for(let i=0;i<60&&Math.abs(a-n)>pfe;i++){let s=.5*(n+a);e(s)>kH?a=s:n=s}return n}function jx(e,t,r){let o;return{at:n=>{if(o!==void 0)return r<0?Math.max(n,o):Math.min(n,o);if(!((n-t)*r>0))return n;let a=ffe(e,t,n,e(n));return a!==n&&(o=a),a},edge:()=>o}}function vg(e,t){let r=o=>{try{return st(e,0,o).ok}catch{return!1}};for(let o of[1,-1]){if(r(o*t))continue;let n=0;for(let a=1;a<=6;a++){let i=o*t*a/6;if(!r(i))break;n=Math.abs(i)}return{lock:t,reached:n,side:o}}return null}var yg=40,xH=new WeakMap;function DL(e){if(e.measured)return null;let t=xH.get(e);if(t)return t;let r=[-yg,yg],o=Xt(e,{travelMin:r[0],travelMax:r[1],steps:21}),n=o.samples.filter(i=>i.converged),a={travel:r,reach:o.reach,covered:o.covered,samples:o.samples.length,unconverged:o.unconverged,fold:o.fold,minMargin:n.length?Math.min(...n.map(i=>i.margin)):0,lockShort:e.config.steerMode==="rack"?vg(sr(e),Fr(e.config)):null};return xH.set(e,a),a}function Bx(e){return{violation:Math.max(0,e.lock-e.reached),reason:`the steering reaches only ${e.reached.toFixed(0)} mm of the ${e.lock.toFixed(0)} mm rack travel${e.side<0?" (other side)":""}`}}var wH=[0,0,0];function hfe(e,t){let r=we(se(e.rockerPivotB,e.rockerPivotA)),o=we(se(e.rockerToPushrod,e.pushrodOuter)),n=we(se(e.damperChassis,e.rockerToDamper)),a=Math.abs(xe(r,Ve(se(e.rockerToPushrod,e.rockerPivotA),o))),i=Math.abs(xe(r,Ve(se(e.rockerToDamper,e.rockerPivotA),n)));return i<1e-9?0:t*a/i}function od(e,t,r){if(e.mcpherson)return gfe(e,t,r);let o=[{r:e.uprightUpper,c:e.ucaFront},{r:e.uprightUpper,c:e.ucaRear},{r:e.uprightLower,c:e.lcaFront},{r:e.uprightLower,c:e.lcaRear},{r:e.tieOuter,c:e.tieInner},{r:e.pushrodOuter,c:e.direct?e.damperChassis:e.rockerToPushrod}],n=e.wheelCenter,a=[[],[],[],[],[],[]];for(let m=0;m<6;m++){let p=we(se(o[m].c,o[m].r)),d=Ve(se(o[m].r,n),p);a[0][m]=p[0],a[1][m]=p[1],a[2][m]=p[2],a[3][m]=d[0],a[4][m]=d[1],a[5][m]=d[2]}let i=Ve(se(e.contactPatch,n),t),s=r??wH,c=[-t[0],-t[1],-t[2],-(i[0]+s[0]),-(i[1]+s[1]),-(i[2]+s[2])],l=wa(a,c),u=l.x;return{ucaFront:u[0],ucaRear:u[1],lcaFront:u[2],lcaRear:u[3],tieRod:u[4],pushRod:u[5],damper:l.singular||e.decoupled?NaN:e.direct?u[5]:hfe(e,u[5]),condProxy:l.condProxy,singular:l.singular}}function gfe(e,t,r){let o=e.wheelCenter,n=e.damperChassis,a=[{at:e.uprightLower,dir:we(se(e.lcaFront,e.uprightLower))},{at:e.uprightLower,dir:we(se(e.lcaRear,e.uprightLower))},{at:e.tieOuter,dir:we(se(e.tieInner,e.tieOuter))},{at:n,dir:[1,0,0]},{at:n,dir:[0,1,0]},{at:n,dir:[0,0,1]}],i=[[],[],[],[],[],[]];for(let g=0;g<6;g++){let b=a[g].dir,y=Ve(se(a[g].at,o),b);i[0][g]=b[0],i[1][g]=b[1],i[2][g]=b[2],i[3][g]=y[0],i[4][g]=y[1],i[5][g]=y[2]}let s=Ve(se(e.contactPatch,o),t),c=r??wH,l=[-t[0],-t[1],-t[2],-(s[0]+c[0]),-(s[1]+c[1]),-(s[2]+c[2])],u=wa(i,l),m=u.x,p=[m[3],m[4],m[5]],d=we(se(n,e.pushrodOuter)),f=xe(p,d),h=Math.hypot(p[0]-f*d[0],p[1]-f*d[1],p[2]-f*d[2]);return{ucaFront:NaN,ucaRear:NaN,lcaFront:m[0],lcaRear:m[1],tieRod:m[2],pushRod:u.singular?NaN:f,damper:u.singular?NaN:f,condProxy:u.condProxy,singular:u.singular,strutSide:u.singular?NaN:h,topMount:p}}function NL(e,t){let r=we(e.spinAxis),o=Ve(se(e.contactPatch,e.wheelCenter),t),n=xe(o,r);return[-n*r[0],-n*r[1],-n*r[2]]}var bfe=[0,0,0];function tl(e,t,r,o){let n=e.direct?e.damperChassis:e.rockerToPushrod;if(e.mcpherson)return{...od(e,r,o),armResidual:0};if(t==="upright")return{...od(e,r,o),armResidual:0};let a=t==="lowerArm",i=a?{bj:e.uprightUpper,front:e.ucaFront,rear:e.ucaRear}:{bj:e.uprightLower,front:e.lcaFront,rear:e.lcaRear},s=a?{bj:e.uprightLower,front:e.lcaFront,rear:e.lcaRear}:{bj:e.uprightUpper,front:e.ucaFront,rear:e.ucaRear},c=e.wheelCenter,l=we(se(i.front,i.bj)),u=we(se(i.rear,i.bj)),m=we(se(e.tieInner,e.tieOuter)),p=[{at:i.bj,dir:l},{at:i.bj,dir:u},{at:e.tieOuter,dir:m},{at:s.bj,dir:[1,0,0]},{at:s.bj,dir:[0,1,0]},{at:s.bj,dir:[0,0,1]}],d=[[],[],[],[],[],[]];for(let X=0;X<6;X++){let ie=p[X].dir,te=Ve(se(p[X].at,c),ie);d[0][X]=ie[0],d[1][X]=ie[1],d[2][X]=ie[2],d[3][X]=te[0],d[4][X]=te[1],d[5][X]=te[2]}let f=Ve(se(e.contactPatch,c),r),h=o??bfe,g=[-r[0],-r[1],-r[2],-(f[0]+h[0]),-(f[1]+h[1]),-(f[2]+h[2])],b=wa(d,g),y=b.singular,v=b.x,k=v[0],x=v[1],S=v[2],R=[v[3],v[4],v[5]],w=we(se(s.rear,s.front)),M=we(se(n,e.pushrodOuter)),T=ke(R,-1),A=(X,ie)=>xe(w,Ve(se(X,s.front),ie)),_=A(e.pushrodOuter,M),F=Math.abs(_)>1e-9?-A(s.bj,T)/_:NaN,P=Ee(T,ke(M,F)),I=ke(P,-1),z=we(se(s.front,s.bj)),N=we(se(s.rear,s.bj)),q=xe(z,z),U=xe(z,N),B=xe(N,N),V=xe(z,I),E=xe(N,I),C=q*B-U*U,$=NaN,L=NaN,j=NaN;if(Math.abs(C)>1e-12){$=(V*B-E*U)/C,L=(q*E-U*V)/C;let X=Ee(ke(z,$),ke(N,L)),ie=se(I,X);j=Math.hypot(ie[0],ie[1],ie[2])}let K=a?{f:k,r:x}:{f:$,r:L},Y=a?{f:$,r:L}:{f:k,r:x};return{ucaFront:K.f,ucaRear:K.r,lcaFront:Y.f,lcaRear:Y.r,tieRod:S,pushRod:F,damper:y||!Number.isFinite(F)||e.decoupled?NaN:e.direct?F:yfe(e,F),condProxy:b.condProxy,singular:y,armResidual:j}}function yfe(e,t){let r=we(se(e.rockerPivotB,e.rockerPivotA)),o=we(se(e.rockerToPushrod,e.pushrodOuter)),n=we(se(e.damperChassis,e.rockerToDamper)),a=Math.abs(xe(r,Ve(se(e.rockerToPushrod,e.rockerPivotA),o))),i=Math.abs(xe(r,Ve(se(e.rockerToDamper,e.rockerPivotA),n)));return i<1e-9?0:t*a/i}var RVe=Math.PI/180;function Sg(e,t){let r=Math.min(Math.max(t,e.range[0]),e.range[1])-e.reference;return Math.max(.2,1+e.perDegC*r+e.perDegC2*r*r)}var _H=["QSX3","QSX8","QSX13","QSX14"],vfe=["QSX1"],Ux=["PHY1","PHY2","PHY3","PKY6","PKY7","PVY1","PVY2","PVY3","PVY4","PEY3","PEY4","QHZ1","QHZ2","QHZ3","QHZ4","QEZ4","QEZ5","QDZ6","QDZ7","QDZ8","QDZ9","QDZ10","QDZ11","SSZ1","SSZ3","SSZ4","RBY3","RHX1","RVY1","RVY2","RVY3",..._H];function Sfe(e){let t=["PKY6","PKY7","PVY3","PVY4","PHY3","PEY4","RVY3","QHZ3","QHZ4","QEZ5","QDZ8","QDZ9","QDZ10","QDZ11","SSZ3","SSZ4"];return e==="5.2"?[...t,"QBZ4","QDZ3"]:t}function kfe(e){let t=new Set(Sfe(e)),r=Ux.filter(o=>!_H.includes(o));return[...r.filter(o=>!t.has(o)),...[...t].filter(o=>!r.includes(o)),...vfe]}function Rfe(e,t){let r={...e};for(let o of t)r[o]!==void 0&&r[o]!==0&&(r[o]=-r[o]);return r}var vi=(e,t,r)=>Number.isFinite(e[t])?e[t]:r;function AH(e,t){return t!=="5.2"?vi(e,"PKY6",0)*vi(e,"LKYC",1):vi(e,"PKY1",-15)*Math.sin(vi(e,"PKY4",2)*Math.atan(1/vi(e,"PKY2",2)))*vi(e,"LKY",1)*vi(e,"PHY3",0)+vi(e,"PVY3",0)*vi(e,"LMUY",1)}var MH=.1;function CH(e){if(e.fitData)return"sae";let t=AH(e.coeffs,e.version);return t>MH?"sae":t<-MH?"iso":null}function kg(e){return e.axisSystem??CH(e)??"sae"}function Gx(e){let t=new Set,r=o=>{for(let n of o)t.has(n)?t.delete(n):t.add(n)};return kg(e)==="iso"&&r(Ux),e.axisSystem&&e.side==="left"&&r(kfe(e.version)),t.size?Rfe(e.coeffs,t):e.coeffs}var wVe=Math.PI/180;var ae=(e,t)=>Number.isFinite(e)?e:t;function PH(e){let t=Gx(e);return{PCX1:ae(t.PCX1,1.65),PDX1:ae(t.PDX1,1),PDX2:ae(t.PDX2,0),PDX3:ae(t.PDX3,0),PEX1:ae(t.PEX1,0),PEX2:ae(t.PEX2,0),PEX3:ae(t.PEX3,0),PEX4:ae(t.PEX4,0),PHX1:ae(t.PHX1,0),PHX2:ae(t.PHX2,0),PKX1:ae(t.PKX1,20),PKX2:ae(t.PKX2,0),PKX3:ae(t.PKX3,0),PPX1:ae(t.PPX1,0),PPX2:ae(t.PPX2,0),PPX3:ae(t.PPX3,0),PPX4:ae(t.PPX4,0),PVX1:ae(t.PVX1,0),PVX2:ae(t.PVX2,0),PCY1:ae(t.PCY1,1.3),PDY1:ae(t.PDY1,1),PDY2:ae(t.PDY2,0),PDY3:ae(t.PDY3,0),PEY1:ae(t.PEY1,0),PEY2:ae(t.PEY2,0),PEY3:ae(t.PEY3,0),PEY4:ae(t.PEY4,0),PEY5:ae(t.PEY5,0),PHY1:ae(t.PHY1,0),PHY2:ae(t.PHY2,0),PHY3:ae(t.PHY3,0),PKY1:ae(t.PKY1,-15),PKY2:ae(t.PKY2,2),PKY3:ae(t.PKY3,0),PKY4:ae(t.PKY4,2),PKY5:ae(t.PKY5,0),PKY6:ae(t.PKY6,0),PKY7:ae(t.PKY7,0),PPY1:ae(t.PPY1,0),PPY2:ae(t.PPY2,0),PPY3:ae(t.PPY3,0),PPY4:ae(t.PPY4,0),PPY5:ae(t.PPY5,0),PVY1:ae(t.PVY1,0),PVY2:ae(t.PVY2,0),PVY3:ae(t.PVY3,0),PVY4:ae(t.PVY4,0),RBX1:ae(t.RBX1,0),RBX2:ae(t.RBX2,0),RBX3:ae(t.RBX3,0),RBY1:ae(t.RBY1,0),RBY2:ae(t.RBY2,0),RBY3:ae(t.RBY3,0),RBY4:ae(t.RBY4,0),RCX1:ae(t.RCX1,1),RCY1:ae(t.RCY1,1),REX1:ae(t.REX1,0),REX2:ae(t.REX2,0),REY1:ae(t.REY1,0),REY2:ae(t.REY2,0),RHX1:ae(t.RHX1,0),RHY1:ae(t.RHY1,0),RHY2:ae(t.RHY2,0),RVY1:ae(t.RVY1,0),RVY2:ae(t.RVY2,0),RVY3:ae(t.RVY3,0),RVY4:ae(t.RVY4,0),RVY5:ae(t.RVY5,1),RVY6:ae(t.RVY6,0),PPZ1:ae(t.PPZ1,0),PPZ2:ae(t.PPZ2,0),QBZ1:ae(t.QBZ1,8),QBZ2:ae(t.QBZ2,0),QBZ3:ae(t.QBZ3,0),QBZ4:ae(t.QBZ4,0),QBZ5:ae(t.QBZ5,0),QBZ6:ae(t.QBZ6,0),QBZ9:ae(t.QBZ9,0),QBZ10:ae(t.QBZ10,0),QCZ1:ae(t.QCZ1,1.1),QDZ1:ae(t.QDZ1,.1),QDZ2:ae(t.QDZ2,0),QDZ3:ae(t.QDZ3,0),QDZ4:ae(t.QDZ4,0),QDZ6:ae(t.QDZ6,0),QDZ7:ae(t.QDZ7,0),QDZ8:ae(t.QDZ8,0),QDZ9:ae(t.QDZ9,0),QDZ10:ae(t.QDZ10,0),QDZ11:ae(t.QDZ11,0),QEZ1:ae(t.QEZ1,0),QEZ2:ae(t.QEZ2,0),QEZ3:ae(t.QEZ3,0),QEZ4:ae(t.QEZ4,0),QEZ5:ae(t.QEZ5,0),QHZ1:ae(t.QHZ1,0),QHZ2:ae(t.QHZ2,0),QHZ3:ae(t.QHZ3,0),QHZ4:ae(t.QHZ4,0),SSZ1:ae(t.SSZ1,0),SSZ2:ae(t.SSZ2,0),SSZ3:ae(t.SSZ3,0),SSZ4:ae(t.SSZ4,0),QSX1:ae(t.QSX1,0),QSX2:ae(t.QSX2,0),QSX3:ae(t.QSX3,0),QSX4:ae(t.QSX4,0),QSX5:ae(t.QSX5,0),QSX6:ae(t.QSX6,0),QSX7:ae(t.QSX7,0),QSX8:ae(t.QSX8,0),QSX9:ae(t.QSX9,0),QSX10:ae(t.QSX10,0),QSX11:ae(t.QSX11,0),QSX12:ae(t.QSX12,0),QSX13:ae(t.QSX13,0),QSX14:ae(t.QSX14,0),PPMX1:ae(t.PPMX1,0),QSY1:ae(t.QSY1,0),QSY2:ae(t.QSY2,0),QSY3:ae(t.QSY3,0),QSY4:ae(t.QSY4,0),QSY5:ae(t.QSY5,0),QSY6:ae(t.QSY6,0),QSY7:ae(t.QSY7,0),QSY8:ae(t.QSY8,0),LONGVL:t.LONGVL!==void 0&&t.LONGVL>0?t.LONGVL:16.7,LCX:ae(t.LCX,1),LCY:ae(t.LCY,1),LEX:ae(t.LEX,1),LEY:ae(t.LEY,1),LFZO:ae(t.LFZO,1),LHX:ae(t.LHX,1),LHY:ae(t.LHY,1),LKX:ae(t.LKX,1),LKY:ae(t.LKY,1),LKYC:ae(t.LKYC,1),LKZC:ae(t.LKZC,1),LMUX:ae(t.LMUX,1),LMUY:ae(t.LMUY,1),LMX:ae(t.LMX,1),LMY:ae(t.LMY,1),LVMX:ae(t.LVMX,1),LRES:ae(t.LRES,1),LS:ae(t.LS,1),LTR:ae(t.LTR,1),LVX:ae(t.LVX,1),LVY:ae(t.LVY,1),LVYKA:ae(t.LVYKA,1),LXAL:ae(t.LXAL,1),LYKA:ae(t.LYKA,1)}}var TH=new WeakMap;function Rg(e){let t=TH.get(e);return t===void 0&&(t=PH(e),TH.set(e,t)),t}var FH=e=>e>=0?1:-1;function qx(e,t,r=0,o){let n=Rg(e),a=Math.max(1,t),i=r,s=n.LFZO*e.fnomin,c=(a-s)/s,l=e.nomPressure>0&&o?(o-e.nomPressure)/e.nomPressure:0,u=e.unloadedR0,m=(n.PDY1+n.PDY2*c)*(1+n.PPY3*l+n.PPY4*l*l)*(1-n.PDY3*i*i)*n.LMUY,p=n.PCY1*n.LCY,d=m*a,f=n.PKY1*s*(1+n.PPY1*l)*Math.sin(n.PKY4*Math.atan(a/((n.PKY2+n.PKY5*i*i)*(1+n.PPY2*l)*s)))*(1-n.PKY3*Math.abs(i))*n.LKY,h=e.version!=="5.2",g=a*(n.PKY6+n.PKY7*c)*(1+n.PPY5*l)*n.LKYC,b=a*(n.PVY3+n.PVY4*c)*i*n.LKYC*n.LMUY,y=Math.abs(f)>1e-6?f:1e-6*(f<0?-1:1),v=h?(n.PHY1+n.PHY2*c)*n.LHY+(g*i-b)/y:(n.PHY1+n.PHY2*c)*n.LHY+n.PHY3*i,k=h?a*(n.PVY1+n.PVY2*c)*n.LVY*n.LMUY+b:a*((n.PVY1+n.PVY2*c)*n.LVY+(n.PVY3+n.PVY4*c)*i)*n.LMUY,x=p*d!==0?f/(p*d):0;return{Fz:a,g:i,dfz:c,dpi:l,Fz0p:s,R0:u,Cy:p,Dy:d,By:x,SHy:v,SVy:k,Kya:f,muy:m,EyA:n.PEY1+n.PEY2*c,EyG:1+n.PEY5*i*i,EyS:n.PEY3+n.PEY4*i,LEY:n.LEY}}function Hx(e,t,r=0,o){let n=qx(e,t,r,o),a=Rg(e),{Fz:i,g:s,dfz:c,dpi:l,Fz0p:u,R0:m,muy:p,Kya:d,SVy:f,By:h,Cy:g,Dy:b,SHy:y}=n,v=(a.PHX1+a.PHX2*c)*a.LHX,k=(a.PDX1+a.PDX2*c)*(1+a.PPX3*l+a.PPX4*l*l)*(1-a.PDX3*s*s)*a.LMUX,x=a.PCX1*a.LCX,S=k*i,R=i*(a.PKX1+a.PKX2*c)*Math.exp(a.PKX3*c)*(1+a.PPX1*l+a.PPX2*l*l)*a.LKX,w=x*S!==0?R/(x*S):0,M=Math.abs(d)>1e-6?d:1e-6*(d<0?-1:1),T=e.version!=="5.2",A=i*(a.PVX1+a.PVX2*c)*a.LVX*a.LMUX,_=a.REX1+a.REX2*c;_>1&&(_=1);let F=a.REY1+a.REY2*c;return F>1&&(F=1),{Fz:i,g:s,dfz:c,dpi:l,Fz0p:u,R0:m,Cy:g,Dy:b,By:h,SHy:y,SVy:f,Kya:d,muy:p,EyA:n.EyA,EyG:n.EyG,EyS:n.EyS,LEY:n.LEY,SHx:v,Cx:x,Dx:S,Bx:w,SVx:A,ExA:a.PEX1+a.PEX2*c+a.PEX3*c*c,PEX4:a.PEX4,LEX:a.LEX,SHxa:a.RHX1,Bxa0:a.RBX1+a.RBX3*s*s,RBX2:a.RBX2,LXAL:a.LXAL,Cxa:a.RCX1,Exa:_,SHyk:a.RHY1+a.RHY2*c,Byk0:a.RBY1+a.RBY4*s*s,RBY2:a.RBY2,RBY3:a.RBY3,LYKA:a.LYKA,Cyk:a.RCY1,Eyk:F,DVykA:p*i*(a.RVY1+a.RVY2*c+a.RVY3*s),RVY4:a.RVY4,RVY5:a.RVY5,RVY6:a.RVY6,LVYKA:a.LVYKA,SHt:a.QHZ1+a.QHZ2*c+(a.QHZ3+a.QHZ4*c)*s,Bt:T?(a.QBZ1+a.QBZ2*c+a.QBZ3*c*c)*(1+a.QBZ5*Math.abs(s)+a.QBZ6*s*s)*(a.LKY/a.LMUY):(a.QBZ1+a.QBZ2*c+a.QBZ3*c*c)*(1+a.QBZ4*s+a.QBZ5*Math.abs(s))*(a.LKY/a.LMUY),Ct:a.QCZ1,Dt:T?i*(m/u)*(a.QDZ1+a.QDZ2*c)*(1-a.PPZ1*l)*(1+a.QDZ3*Math.abs(s)+a.QDZ4*s*s)*a.LTR:i*(m/u)*(a.QDZ1+a.QDZ2*c)*(1-a.PPZ1*l)*(1+a.QDZ3*s+a.QDZ4*s*s)*a.LTR,EtA:a.QEZ1+a.QEZ2*c+a.QEZ3*c*c,EtG:a.QEZ4+a.QEZ5*s,Br:a.QBZ9*(a.LKY/a.LMUY)+a.QBZ10*h*g,Dr:T?i*m*((a.QDZ6+a.QDZ7*c)*a.LRES+((a.QDZ8+a.QDZ9*c)*(1+a.PPZ2*l)+(a.QDZ10+a.QDZ11*c)*Math.abs(s))*s*a.LKZC)*a.LMUY:i*m*((a.QDZ6+a.QDZ7*c)*a.LRES+(a.QDZ8+a.QDZ9*c)*(1+a.PPZ2*l)*s)*a.LMUY,arOff:d!==0?f/d:0,sixOne:T,kk:R/M*(R/M),sS0:m*(a.SSZ1+(a.SSZ3+a.SSZ4*c)*s)*a.LS,sS2:m*a.SSZ2*a.LS/u}}function xg(e,t){let r=t+e.SHy,o=e.EyA*(e.EyG-e.EyS*FH(r))*e.LEY;o>1&&(o=1);let n=e.By*r;return e.Dy*Math.sin(e.Cy*Math.atan(n-o*(n-Math.atan(n))))+e.SVy}function Kx(e,t){let r=t+e.SHx,o=e.ExA*(1-e.PEX4*FH(r))*e.LEX;o>1&&(o=1);let n=e.Bx*r;return e.Dx*Math.sin(e.Cx*Math.atan(n-o*(n-Math.atan(n))))+e.SVx}function $H(e,t,r){if(r===0)return t;if(e.sixOne)return Math.sqrt(t*t+e.kk*r*r)*Math.sign(t);let o=Math.tan(t);return Math.atan(Math.sqrt(o*o+e.kk*r*r))*Math.sign(t)}function xfe(e,t,r,o){let n=t+e.SHt,a=e.EtA*(1+e.EtG*(2/Math.PI)*Math.atan(e.Bt*e.Ct*n));a>1&&(a=1);let i=$H(e,n,r),s=e.Bt*i;return e.Dt*Math.cos(e.Ct*Math.atan(s-a*(s-Math.atan(s))))*o}function wfe(e,t,r,o){return e.Dr*Math.cos(Math.atan(e.Br*$H(e,t+e.SHy+e.arOff,r)))*o}function IH(e,t,r,o,n,a){let i=Math.cos(t),s=xfe(e,t,r,i),c=wfe(e,t,r,i);return-s*(n-a)+c+(e.sS0+e.sS2*n)*o}function EH(e,t,r){let o=e.Bxa0*Math.cos(Math.atan(e.RBX2*t))*e.LXAL,n=r+e.SHxa,a=Math.cos(e.Cxa*Math.atan(o*e.SHxa-e.Exa*(o*e.SHxa-Math.atan(o*e.SHxa))))||1;return Math.cos(e.Cxa*Math.atan(o*n-e.Exa*(o*n-Math.atan(o*n))))/a*Kx(e,t)}function OL(e,t){let r=e.sS0===0&&e.sS2===0?0:EH(e,0,t);return IH(e,t,0,r,xg(e,t),0)}function Wx(e,t,r){let o=xg(e,r),n=EH(e,t,r),a=e.Byk0*Math.cos(Math.atan(e.RBY2*(r-e.RBY3)))*e.LYKA,i=t+e.SHyk,s=Math.cos(e.Cyk*Math.atan(a*e.SHyk-e.Eyk*(a*e.SHyk-Math.atan(a*e.SHyk))))||1,c=Math.cos(e.Cyk*Math.atan(a*i-e.Eyk*(a*i-Math.atan(a*i))))/s,u=e.DVykA*Math.cos(Math.atan(e.RVY4*r))*Math.sin(e.RVY5*Math.atan(e.RVY6*t))*e.LVYKA,m=c*o+u;return{Fx:n,Fy:m,Mz:IH(e,r,t,n,m,u)}}var wg=(e,t)=>Math.max(.1,e.muY0+e.loadSensY*(t-e.nominalLoad)),Mg=(e,t)=>Math.max(.1,e.muX0+e.loadSensX*(t-e.nominalLoad)),LH=(e,t,r)=>wg(e,Math.max(1,t))*Math.max(1,t)*Math.sin(e.Cy*Math.atan(e.By*r)),DH=(e,t,r)=>Mg(e,Math.max(1,t))*Math.max(1,t)*Math.sin(e.Cx*Math.atan(e.Bx*r));function zL(e,t){let r=Math.max(1,t.Fz),o=wg(e,r)*r,n=Mg(e,r)*r,a=o*Math.sin(e.Cy*Math.atan(e.By*t.alpha)),i=n*Math.sin(e.Cx*Math.atan(e.Bx*t.kappa)),s=Math.hypot(n>0?i/n:0,o>0?a/o:0);return s>1&&(i/=s,a/=s),{Fx:i,Fy:a,Mz:0}}var ad=Math.PI/180;function rl(e){if(e.kind==="simple")return"none";let t=e.missing?.some(o=>/^aligning moment Mz\b/i.test(o))??!1,r=["QBZ1","QCZ1","QDZ1"].every(o=>Number.isFinite(e.coeffs[o]));return t||!r?"assumed":"model"}function NH(e){let t=e.thermal?.operating;if(t===void 0||!e.thermal)return e;let{lateral:r,longitudinal:o,aligning:n}=e.thermal,a=r?Sg(r,t):1,i=o?Sg(o,t):1,s=n?Sg(n,t):1;if(a===1&&i===1&&s===1)return e;if(e.kind==="simple")return{...e,muY0:e.muY0*a,muX0:e.muX0*i};let c={...e.coeffs},l=(u,m)=>{c[u]=(c[u]??1)*m};return l("LMUY",a),l("LMUX",i),l("LTR",s),l("LRES",s),{...e,coeffs:c}}function id(e,t,r){let o=0,n=0;for(let i=r;i<=t;i+=r){let s=Math.abs(e(i));s>n&&(n=s,o=i)}let a=r/10;for(let i=Math.max(a,o-r);i<=o+r;i+=a)n=Math.max(n,Math.abs(e(i)));return n}function bt(e){let t=NH(e),r=t,o=t,n=null,a=NaN,i=NaN,s=NaN,c=(x,S,R)=>(n!==null&&x===a&&S===i&&R===s||(n=Hx(r,x,S,R),a=x,i=S,s=R),n),l=null,u=NaN,m=NaN,p=NaN,d=(x,S,R)=>(l!==null&&x===u&&S===m&&R===p||(l=qx(r,x,S,R),u=x,m=S,p=R),l),f=x=>e.kind==="magic"?Wx(c(x.Fz,x.gamma??0,x.p),x.kappa,x.alpha):zL(o,x),h=(x,S,R=0,w)=>e.kind==="magic"?xg(d(S,R,w),x):LH(o,S,x),g=(x,S,R=0,w)=>e.kind==="magic"?Kx(c(S,R,w),x):DH(o,S,x),b=(x,S,R=0,w)=>e.kind==="magic"?OL(c(S,R,w),x):f({Fz:S,kappa:0,alpha:x,gamma:R,p:w}).Mz,y=x=>e.kind==="simple"?wg(o,x):id(S=>h(S*ad,x),45,1)/Math.max(1,x),v=x=>e.kind==="simple"?Mg(o,x):id(S=>g(S,x),.6,.02)/Math.max(1,x),k=x=>{let S=.1*ad;return Math.abs((h(S,x)-h(-S,x))/(2*S))};return{model:e,forces:f,Fx:g,Fy:h,Mz:b,muX:v,muY:y,corneringStiffness:k,verticalStiffness:()=>e.verticalStiffness,rollingRadius:x=>{if(e.kind==="magic"&&e.missing?.includes("UNLOADED_RADIUS"))return 0;let S=e.unloadedR0??0;if(!(S>0))return 0;let R=e.verticalStiffness*1e3;if(!(R>0))return S;let w=e.rollingFraction??.306;return S-w*Math.max(0,x)/R},relaxationLength:x=>{let S=e.relaxation;if(!S)return 0;let R=S.carcassStiffness??0;if(!(R>0))return S.sigma;let w=k(Math.max(0,x));return w>0?w/(R*1e3):S.sigma}}}function sd(e){let t=Math.max(1,e.model.kind==="magic"?e.model.fnomin:e.model.nominalLoad);return e.Fy(2*ad,t,0)-e.Fy(-2*ad,t,0)>=0?1:-1}function Si(e,t=e.kind==="magic"?e.fnomin:e.nominalLoad){let r=bt(e),o=2*ad,n=3*ad,a=r.Fy(o,t,0),i=r.Fy(o,t,n);return!Number.isFinite(a)||!Number.isFinite(i)?!1:Math.abs(i-a)>1}var Mfe=Math.PI/180;function mt(e,t){return e.axle?e.axle(t):e}function Zx(e,t){if(e===t)return e;let r=sd(e)*sd(t),o=(l,u)=>.5*(l+u),n=(l,u)=>l>0&&u>0?o(l,u):l>0?l:u>0?u:0,a=l=>{let u=e.forces(l),m=t.forces(l);return{Fx:o(u.Fx,m.Fx),Fy:o(u.Fy,r*m.Fy),Mz:o(u.Mz,r*m.Mz)}},i=(l,u,m=0,p)=>o(e.Fx(l,u,m,p),t.Fx(l,u,m,p)),s=(l,u,m=0,p)=>o(e.Fy(l,u,m,p),r*t.Fy(l,u,m,p)),c=(l,u,m=0,p)=>o(e.Mz(l,u,m,p),r*t.Mz(l,u,m,p));return{model:e.model,forces:a,Fx:i,Fy:s,Mz:c,muX:l=>id(u=>i(u,l),.6,.02)/Math.max(1,l),muY:l=>id(u=>s(u*Mfe,l),45,1)/Math.max(1,l),corneringStiffness:l=>o(e.corneringStiffness(l),t.corneringStiffness(l)),verticalStiffness:()=>n(e.verticalStiffness(),t.verticalStiffness()),rollingRadius:l=>n(e.rollingRadius(l),t.rollingRadius(l)),relaxationLength:l=>n(e.relaxationLength(l),t.relaxationLength(l)),axle:l=>l==="front"?e:t}}function nn(e){if(OH.has(e))return e;let t=zH.get(e);if(t)return t;let r;if(e.axle){let o=e.axle("front"),n=e.axle("rear"),a=nn(o),i=nn(n);r=a===o&&i===n?e:Zx(a,i)}else sd(e)>0?r=e:r={...e,forces:o=>{let n=e.forces(o);return{Fx:n.Fx,Fy:-n.Fy,Mz:-n.Mz}},Fy:(o,n,a,i)=>-e.Fy(o,n,a,i),Mz:(o,n,a,i)=>-e.Mz(o,n,a,i)};return OH.add(r),r!==e&&zH.set(e,r),r}var OH=new WeakSet,zH=new WeakMap;var Xx=25*(Math.PI/180);function _fe(e){let t=.6180339887,r=0,o=Xx,n=o-t*(o-r),a=r+t*(o-r),i=e(n),s=e(a);for(let l=0;l<12;l++)i>s?(o=a,a=n,s=i,n=o-t*(o-r),i=e(n)):(r=n,n=a,i=s,a=r+t*(o-r),s=e(a));return{alpha:i>s?n:a,force:Math.max(i,s)}}function _g(e,t,r,o,n=0){let a=Math.abs(t);if(!(a>0))return 0;let i=u=>Math.abs(e.Fy(u,r,0))+Math.abs(e.Fy(u,o,0)),s=0,c=Xx;if(i(Xx)<=a){let u=_fe(i);if(u.force<=a)return u.alpha;c=u.alpha}else if(n>0){let u=Math.max(0,n*.6),m=Math.min(Xx,n*1.6+.001);i(u)<a&&i(m)>=a&&(s=u,c=m)}let l=.001*a;for(let u=0;u<12;u++){let m=.5*(s+c),p=i(m)-a;if(p<0?s=m:c=m,Math.abs(p)<=l)return m}return c}var VL={shaft:!1,trail:0,hub:[0,0,0]};function jH(e){let t=e.spinAxis,r=Math.hypot(t[0],t[1]);if(r<1e-9)return[1,0,0];let o=[-t[1]/r,t[0]/r,0];return o[0]<0?[-o[0],-o[1],0]:o}function jL(e,t,r){let o=r.shaft?NL(e,t):[0,0,0];if(r.trail!==0){let a=jH(e),i=[t[0],t[1],0],s=se(i,ke(a,xe(i,a)));o=Ee(o,Ve(ke(a,-r.trail),s))}let n=r.hub;return(n[0]!==0||n[1]!==0||n[2]!==0)&&(o=se(o,Ve(se(e.contactPatch,e.wheelCenter),n))),{force:Ee(t,n),moment:o}}var Afe=(e,t)=>{let r=e!==void 0&&e>0?1/e:0,o=t!==void 0&&t>0?1/t:0;return r+o},Jx={ucaFront:0,ucaRear:0,lcaFront:0,lcaRear:0,tieRod:0,pushRod:0,rack:0};function nl(e){return!e.measured}function ki(e){if(!e)return!1;let t=r=>!!r&&Object.values(r).some(o=>o!==void 0&&o>0&&Number.isFinite(o));return t(e.links)||t(e.bushings)||e.rack!==void 0&&e.rack>0}function ol(e,t){let r=e.corner.hardpoints,o=Gm(e.rocker,t.points.rockerAngle);return{ucaFront:r.ucaFront,ucaRear:r.ucaRear,lcaFront:r.lcaFront,lcaRear:r.lcaRear,tieInner:Xc(e.inv,t.steer),rockerPivotA:r.rockerPivotA,rockerPivotB:r.rockerPivotB,damperChassis:e.inv.strut?t.points.uprightUpper:r.damperChassis,uprightUpper:t.points.uprightUpper,uprightLower:t.points.uprightLower,tieOuter:t.points.tieOuter,wheelCenter:t.points.wheelCenter,pushrodOuter:t.points.pushrodOuter,contactPatch:t.points.contactPatch,kingpinGround:t.points.kingpinGround,kingpinAtHub:t.points.kingpinAtHub,rockerToPushrod:o.pushrod,rockerToDamper:o.damper,spinAxis:t.points.spinAxis,direct:e.corner.config.actuation==="direct",decoupled:e.corner.config.actuation==="decoupled",mcpherson:e.inv.strut!==void 0,loadedRadius:e.corner.config.loadedRadius,tyreDeflection:0,load:NaN,lifted:!1,clearance:0,contactLength:0}}function BL(e,t,r=0){let o=t.links??{},n=t.bushings??{},a=(l,u,m)=>{let p=Afe(u,m);return p>0&&Number.isFinite(l)?l*p:0},i=n.topMount,s=e.topMount,c=s&&i!==void 0&&i>0&&s.every(Number.isFinite)?[-s[0]/i,-s[1]/i,-s[2]/i]:void 0;return{...c?{topMount:c}:{},ucaFront:a(e.ucaFront,o.ucaFront,n.ucaFront),ucaRear:a(e.ucaRear,o.ucaRear,n.ucaRear),lcaFront:a(e.lcaFront,o.lcaFront,n.lcaFront),lcaRear:a(e.lcaRear,o.lcaRear,n.lcaRear),tieRod:a(e.tieRod,o.tieRod,n.tieInner),pushRod:a(e.pushRod,o.pushRod,void 0),rack:r}}function BH(e,t,r,o){let n=yt(e,t);if(!(n>1e-9))return{axial:r,radius2:0};let a=(r*r-o*o+n*n)/(2*n);return{axial:a,radius2:Math.max(0,r*r-a*a)}}function Ag(e,t){let r=e.corner.hardpoints,o=e.inv,n={...o};if(o.strut&&t.topMount&&t.topMount.some(s=>s!==0)&&(n.strut={...o.strut,top:Ee(o.strut.top,t.topMount)}),t.ucaFront!==0||t.ucaRear!==0){let s=BH(r.ucaFront,r.ucaRear,yt(r.uprightUpper,r.ucaFront)+t.ucaFront,yt(r.uprightUpper,r.ucaRear)+t.ucaRear);n.ubjAxial0=s.axial,n.ubjRadius2=s.radius2}if(t.lcaFront!==0||t.lcaRear!==0){let s=BH(r.lcaFront,r.lcaRear,yt(r.uprightLower,r.lcaFront)+t.lcaFront,yt(r.uprightLower,r.lcaRear)+t.lcaRear),c=xe(o.lbjRel0,o.lcaDir),l=se(o.lbjRel0,ke(o.lcaDir,c)),u=Math.hypot(l[0],l[1],l[2]);n.lbjRel0=u>1e-9?Ee(ke(o.lcaDir,s.axial),ke(l,Math.sqrt(s.radius2)/u)):Ee(ke(o.lcaDir,s.axial),l)}if(t.tieRod!==0){let s=Math.sqrt(o.tieLen2)+t.tieRod;n.tieLen2=s*s}if(t.rack!==0&&(n.tieInner0=Ee(o.tieInner0,ke(o.rackAxis,t.rack))),t.pushRod===0)return{corner:e.corner,inv:n,rocker:e.rocker};let a=Math.sqrt(e.rocker.rodLen2)+t.pushRod,i={...e.rocker,rodLen2:a*a};return{corner:e.corner,inv:n,rocker:i}}var Cfe=8,Tfe=1e-5,Pfe=e=>({q:[e.pose.t[0],e.pose.t[1],e.pose.t[2],e.pose.omega[0],e.pose.omega[1],e.pose.omega[2]],phi:e.points.rockerAngle});function UL(e,t,r){let o=jL(e,r.force,r.extras??VL),n=r.alignMoment?Ee(o.moment,[0,0,r.alignMoment]):o.moment;return tl(e,t,o.force,n)}function ew(e,t,r,o,n,a,i=0){let s=zt(e,t,r,n,a),c=e.corner.compliance;if(!(ki(c)&&nl(e.corner)))return{state:s,forces:UL(ol(e,s),e.corner.config.pushrodAttach,o),deflection:Jx,rigid:s,iterations:0,converged:!0,bypassed:!0};let u=s,m=e,p=e.corner.config.pushrodAttach,d=UL(ol(e,s),p,o),f=Jx,h=!1,g=0;for(;g<Cfe;g++){let b=ol(m,u);if(d=UL(b,p,o),d.singular)break;f=BL(d,c,i),m=Ag(e,f);let y=zt(m,t,r,Pfe(u),a),v=yt(y.points.wheelCenter,u.points.wheelCenter);if(u=y,v<Tfe){h=!0;break}}return{state:u,forces:d,deflection:f,rigid:s,iterations:g+1,converged:h&&u.converged,bypassed:!1}}var Qx=1e3,UH=1e5;function GH(e,t,r,o,n){let a=ew(e,t,r,o,void 0,n);return{toe:a.state.metrics.toe,camber:a.state.metrics.camber,patch:a.state.points.contactPatch,converged:a.converged,bypassed:a.bypassed}}function cd(e,t,r,o,n){let a={force:[0,0,o]},i=(g,b=0)=>GH(e,t,r,{force:g,alignMoment:b},n),s=GH(e,t,r,a,n);if(s.bypassed)return{toePerLateral:0,camberPerLateral:0,toePerLongitudinal:0,camberPerLongitudinal:0,toePerAligning:0,lateralPatch:0,longitudinalPatch:0,bypassed:!0,converged:!0};let c=i([0,Qx,o]),l=i([0,-Qx,o]),u=i([Qx,0,o]),m=i([-Qx,0,o]),p=i([0,0,o],UH),d=i([0,0,o],-UH),f=(g,b)=>(g-b)/2,h=[s,c,l,u,m,p,d].every(g=>g.converged);return{toePerLateral:f(c.toe,l.toe),camberPerLateral:f(c.camber,l.camber),toePerLongitudinal:f(u.toe,m.toe),camberPerLongitudinal:f(u.camber,m.camber),toePerAligning:f(p.toe,d.toe),lateralPatch:f(c.patch[1],l.patch[1]),longitudinalPatch:f(u.patch[0],m.patch[0]),bypassed:!1,converged:h}}var Ffe=1e3;function GL(e,t=Ffe){if(!ki(e.compliance)||!nl(e))return;let r=sr(e),o=zt(r,0,0),n=cd(r,o.beta,0,t);if(!n.bypassed)return{toePerFy:n.toePerLateral/1e3,camberPerFy:n.camberPerLateral/1e3,toePerFx:n.toePerLongitudinal/1e3,camberPerFx:n.camberPerLongitudinal/1e3,toePerMz:n.toePerAligning/1e5}}function ld(e,t=-yg,r=yg,o=21){let n=e.measured;if(n)return{travel:[...n.travel],motionRatio:[...n.motionRatio],camber:[...n.camber],toe:[...n.toe],damperLen:n.damperLen?[...n.damperLen]:n.travel.map(()=>0)};let a=Xt(e,{travelMin:t,travelMax:r,steps:o}),i=GL(e);return{travel:a.samples.map(s=>s.travel),motionRatio:a.samples.map(s=>s.metrics.motionRatio??1),camber:a.samples.map(s=>s.metrics.camber),toe:a.samples.map(s=>s.metrics.toe),damperLen:a.samples.map(s=>s.metrics.damperLength),...i?{compliance:i}:{}}}function tw(e,t,r){let o=e.length;if(o===0)return 0;if(r<=e[0])return t[0];if(r>=e[o-1])return t[o-1];let n=0,a=o-1;for(;a-n>1;){let s=n+a>>1;e[s]<=r?n=s:a=s}let i=(r-e[n])/(e[a]-e[n]);return t[n]+i*(t[a]-t[n])}function Es(e,t){return{motionRatio:tw(e.travel,e.motionRatio,t),camber:tw(e.travel,e.camber,t),toe:tw(e.travel,e.toe,t),damperLen:tw(e.travel,e.damperLen,t)}}var qH=Math.PI/180,$fe=9.81;function Ls(e,t,r,o=0){let n=Lt(e),a=e.wheelbase*(1-e.frontMassFrac),i=e.wheelbase*e.frontMassFrac,s=rd(e,o),c=e.aero?.model?(k,x,S)=>rd(e,o,x,k,S):()=>s,l=Es(t,0),u=Es(r,0),m=e.loadFactor,p=m!==void 0&&m!==1?(m-1)*e.massTotal*$fe:0,d=p*e.frontMassFrac/2,f=p*(1-e.frontMassFrac)/2,h=(k,x)=>x>0&&Number.isFinite(x)&&k+x>0?x/(k+x):1,g=nr(e,"front"),b=nr(e,"rear"),y={F:h(e.wheelRateFront+(e.heaveSpringFront??0),g),R:h(e.wheelRateRear+(e.heaveSpringRear??0),b)},v={F:h(e.wheelRateFront+e.arbFront,g),R:h(e.wheelRateRear+e.arbRear,b)};return(k,x,S=0,R=0)=>{let w=c(k,x,S),M=n.rollGradient*k,T=M*qH,A=n.pitchGradient*x*qH,_=(q,U)=>{let B=U==="F"?e.trackFront:e.trackRear,V=U==="F"?n.rideRateFront:n.rideRateRear,E=(q==="R"?1:-1)*(B/2)*Math.tan(T),C=(U==="R"?i:-a)*Math.tan(A),$=`${U}${q}`,L=p?w[$]+(U==="F"?d:f):w[$],j=V>0?L/V:0;return{anti:E,sym:C+j}},F={FL:_("L","F"),FR:_("R","F"),RL:_("L","R"),RR:_("R","R")},P=q=>{let U=q[0];return F[q].sym*y[U]+F[q].anti*v[U]},I=td(e,R,n,{FL:P("FL"),FR:P("FR")}),z=M+I.rollDeg,N=(q,U)=>{let B=U==="F"?t:r,V=U==="F"?l:u,E=`${U==="F"?"F":"R"}${q}`,C=F[E].sym+F[E].anti+I.travel[E],$=P(E)+I.travel[E]*v[U],L=C-$,j=Es(B,$),K=(q==="R"?1:-1)*j.camber;return{travel:$,tyre:L,ground:C,camber:K,camberRoad:K+z,toe:j.toe,bumpToe:j.toe-V.toe,damperTravel:V.damperLen-j.damperLen}};return{FL:N("L","F"),FR:N("R","F"),RL:N("L","R"),RR:N("R","R"),steeringJacking:I}}}var qL=(e,t)=>{let r=Number(e);return Number.isFinite(r)?r:t};function Ds(e){return{enabled:e?.enabled===!0,roadFeedbackGain:Math.min(2,Math.max(0,qL(e?.roadFeedbackGain,1))),turnInFrictionNm:Math.max(0,qL(e?.turnInFrictionNm,0)),columnStiffnessNmPerRad:Math.max(0,qL(e?.columnStiffnessNmPerRad,0))}}function HL(e,t,r){let o=Ds(r);if(!o.enabled)return{roadNm:e,assistanceNm:0,frictionNm:0,columnTwistDeg:0,driverNm:e};let n=e*(o.roadFeedbackGain-1),a=t===0?0:Math.sign(t)*o.turnInFrictionNm,i=e+n+a,s=o.columnStiffnessNmPerRad>0?i/o.columnStiffnessNmPerRad*(180/Math.PI):0;return{roadNm:e,assistanceNm:n,frictionNm:a,columnTwistDeg:s,driverNm:i}}var HH=()=>({totalNm:0,aligningNm:0,lateralNm:0,longitudinalNm:0,jackingNm:0});function al(e){let t=e.steerFront;return!!(t?.rackRatioMmPerRev&&t.innerJacobian&&t.innerJacobian.length>=2&&t.outerJacobian&&t.outerJacobian.length>=2&&t.meanDeg.length>=2)}function Cg(e,t,r,o="model",n){let a=e.steerFront;if(!al(e)||!a)return null;let i=t<0?-1:1,c=a.rackRatioMmPerRev/(2*Math.PI)/1e3,l=t>=0,u=n&&a.travelSurface?Qm(a,Math.abs(t),l?n.FL:n.FR,l?n.FR:n.FL):ed(a,Math.abs(t));if(!u.innerJacobian||!u.outerJacobian)return null;let m=(g,b)=>{let y=r[g],v=g==="FL"?-1:1,k=-v*y.Fy,S={aligning:1e3*(-v*y.Mz)*b.yaw,lateral:k*b.lateral,longitudinal:y.Fx*b.longitudinal,jacking:y.Fz*b.vertical},R=HH();R.aligningNm=-i*S.aligning*c,R.lateralNm=-i*S.lateral*c,R.longitudinalNm=-i*S.longitudinal*c,R.jackingNm=-i*S.jacking*c,R.totalNm=R.aligningNm+R.lateralNm+R.longitudinalNm+R.jackingNm;let w=-i*(S.aligning+S.lateral+S.longitudinal+S.jacking);return{moment:R,rackN:w}},p=m("FL",l?u.innerJacobian:u.outerJacobian),d=m("FR",l?u.outerJacobian:u.innerJacobian),f=HH();for(let g of[p.moment,d.moment])f.aligningNm+=g.aligningNm,f.lateralNm+=g.lateralNm,f.longitudinalNm+=g.longitudinalNm,f.jackingNm+=g.jackingNm,f.totalNm+=g.totalNm;let h=HL(f.totalNm,t,e.steeringSystem);return f.totalNm=h.driverNm,{...f,roadNm:h.roadNm,assistanceNm:h.assistanceNm,frictionNm:h.frictionNm,columnTwistDeg:h.columnTwistDeg,rackForceN:p.rackN+d.rackN,aligningSource:o,perWheel:{FL:p.moment,FR:d.moment}}}var Ife=e=>"front"in e&&"rear"in e;function ud(e,t){return Ife(e)?e[t]:e}function WL(e,t,r=24){let o=Math.max(1,t),n=o/Math.max(1,r-1),a=[],i=[],s=[];for(let l=0;l<r;l++){let u=l*n;a.push(u),i.push(e.muX(u)),s.push(e.muY(u))}let c=(l,u)=>{if(!(u>0))return l[0];if(u>=o)return l[r-1];let m=Math.min(r-2,Math.floor(u/n)),p=(u-a[m])/n;return l[m]+p*(l[m+1]-l[m])};return{muX:l=>c(i,l),muY:l=>c(s,l)}}function KL(e,t){let r=Math.max(0,t.Fz),o=e.muY(r)*r,n=e.muX(r)*r;if(!(o>0))return{fyUsed:0,fyMax:0,fyRes:0};let a=n>0?Math.min(1,Math.abs(t.Fx)/n):0,i=o*Math.sqrt(Math.max(0,1-a*a)),s=Math.abs(t.Fy);return{fyUsed:s,fyMax:i,fyRes:Math.max(0,i-s)}}function KH(e,t,r){let o=KL(e,t),n=KL(e,r);return{left:o,right:n,fyRes:o.fyRes+n.fyRes}}function Ri(e,t,r){let o=KH(ud(e,"front"),t.FL,t.FR),n=KH(ud(e,"rear"),t.RL,t.RR),a=r.lf>0&&Number.isFinite(r.lf)?r.lf:0,i=r.lr>0&&Number.isFinite(r.lr)?r.lr:0,s=n.fyRes*i,c=o.fyRes*a,l=s-c,u=Math.max(Math.abs(s),Math.abs(c));return{stabil:s,agil:c,diff:l,rel:u>0?l/u:0,front:o,rear:n}}var Tg=[{q:"p",section:"INFLATION_PRESSURE_RANGE",min:"PRESMIN",max:"PRESMAX",what:"pressure"},{q:"fz",section:"VERTICAL_FORCE_RANGE",min:"FZMIN",max:"FZMAX",what:"load"},{q:"kappa",section:"LONG_SLIP_RANGE",min:"KPUMIN",max:"KPUMAX",what:"slip ratio"},{q:"alpha",section:"SLIP_ANGLE_RANGE",min:"ALPMIN",max:"ALPMAX",what:"slip angle"},{q:"gamma",section:"INCLINATION_ANGLE_RANGE",min:"CAMMIN",max:"CAMMAX",what:"inclination"}],Lfe=Tg.flatMap(e=>[e.min,e.max]);function Dfe(e){let t={};for(let r of Tg){let o=e[r.min],n=e[r.max],a={};Number.isFinite(o)&&(a.min=o),Number.isFinite(n)&&(a.max=n),(a.min!==void 0||a.max!==void 0)&&(t[r.q]=a)}return Object.keys(t).length?t:void 0}function Pg(e){if(e.kind==="magic")return e.range??Dfe(e.coeffs)}function YL(e){let t=Pg(e)?.fz?.max;return t!==void 0&&Number.isFinite(t)&&t>0?t:null}function il(e){return Math.max(1,e.kind==="magic"?e.fnomin:e.nominalLoad)}function WH(e,t,r,o,n){let a=(r-t)/o,i=t,s=e(t);for(let c=t+a;c<=r;c+=a){let l=e(c);n(l,s)&&(s=l,i=c)}return i}function rw(e,t=10*il(e)){let{turnover:r,collapse:o}=ZH(bt(e),t),n=[r,o].filter(a=>a!=null);return{turnover:r,collapse:o,declared:YL(e),limit:n.length?Math.min(...n):null}}function Wo(e){let t=YH.get(e);if(t!==void 0)return t;let r=10*il(e.model),{turnover:o,collapse:n}=ZH(e,r),a=o??n??r;return YH.set(e,a),a}var YH=new WeakMap;function ZH(e,t){let r=il(e.model),o=m=>e.muY(m),n=m=>o(m)*m,a=80,i=t/a,s=null,c=n(i);for(let m=2;m<=a;m++){let p=n(m*i);if(p<c){s=WH(n,(m-2)*i,m*i,20,(d,f)=>d>f);break}c=p}let l=null,u=o(i);for(let m=2;m<=a;m++){let p=o(m*i);if(p>u){let d=WH(o,(m-2)*i,m*i,40,(f,h)=>f<h);o(d)<.05*o(r)&&(l=d);break}u=p}return{turnover:s,collapse:l}}function ZL(e,t=il(e)){let r=bt(e),o=6*(Math.PI/180),n=r.forces({Fz:t,kappa:0,alpha:o,gamma:0}).Fy,a=r.forces({Fz:t,kappa:.15,alpha:o,gamma:0}).Fy,i=Math.abs(n)>1?Math.abs(a/n):1;return{kept:i,coupled:i<.97}}function sl(e,t=2.5*il(e)){let r=bt(e),o=0,n=il(e),a=10;for(let i=1;i<=a;i++){let s=t*i/a,c=Math.abs(r.forces({Fz:s,kappa:0,alpha:0,gamma:0}).Fx);s>0&&c/s>o/n&&(o=c,n=s)}return{ghostFx:o,atLoad:n,ratio:o/n,trustworthy:o/n<=.03}}var XH=.1;function cl(e,t=il(e)){let r=bt(e).muX(t);return{muX:r,none:Number.isFinite(r)&&r<XH}}function XL(e,t){return t?e.trustworthy!==t.trustworthy?e.trustworthy?t:e:t.ratio>e.ratio?t:e:e}var JH=["FL","FR","RL","RR"],Nfe=e=>e==="FL"||e==="RL",Ofe=e=>e==="FL"||e==="FR"?"front":"rear";function nw(e,t,r,o){if(!(e.full>e.open)||o.ayDir===0)return e.full;let n=o.halfTrack[e.axle],a={};for(let l of JH)a[l]={...t[l]};let i=l=>{let u=0;for(let p of JH)Ofe(p)===e.axle&&(a[p].Fx=e.sense*(p===e.strong?l-e.open/2:e.open/2),u-=(Nfe(p)?n:-n)*a[p].Fx);let m=Ri(r,a,o.arms);return u*o.ayDir>=0?Math.abs(u)<=m.stabil:Math.abs(u)<=m.agil};if(i(e.full))return e.full;let s=e.open,c=e.full;for(let l=0;l<20&&c-s>.001*e.full;l++){let u=.5*(s+c);i(u)?s=u:c=u}return s}var zfe=[["PCY1","Shape factor Cfy for lateral forces",1.3],["PDY1","Lateral friction Muy",1],["PDY2","Variation of friction Muy with load",0],["PDY3","Variation of friction Muy with squared camber",0],["PEY1","Lateral curvature Efy at Fznom",0],["PEY2","Variation of curvature Efy with load",0],["PEY3","Zero order camber dependency of curvature Efy",0],["PEY4","Variation of curvature Efy with camber",0],["PEY5","Variation of curvature Efy with camber squared",0],["PKY1","Maximum value of stiffness Kfy/Fznom",-15],["PKY2","Load at which Kfy reaches maximum value",2],["PKY3","Variation of Kfy/Fznom with camber",0],["PKY4","Curvature of stiffness Kfy",2],["PKY5","Peak stiffness variation with camber squared",0],["PKY6","Fy camber stiffness factor",0],["PKY7","Vertical load dependency of camber stiffness",0],["PHY1","Horizontal shift Shy at Fznom",0],["PHY2","Variation of shift Shy with load",0],["PHY3","Variation of shift Shy with camber",0],["PVY1","Vertical shift in Svy/Fz at Fznom",0],["PVY2","Variation of shift Svy/Fz with load",0],["PVY3","Variation of shift Svy/Fz with camber",0],["PVY4","Variation of shift Svy/Fz with camber and load",0],["PPY1","Influence of inflation pressure on cornering stiffness",0],["PPY2","Influence of inflation pressure on dependency of nominal tyre load on cornering stiffness",0],["PPY3","Linear influence of inflation pressure on lateral peak friction",0],["PPY4","Quadratic influence of inflation pressure on lateral peak friction",0],["PPY5","Influence of inflation pressure on camber stiffness",0]],Vfe=[["PCX1","Shape factor Cfx for longitudinal force",1.65],["PDX1","Longitudinal friction Mux at Fznom",1],["PDX2","Variation of friction Mux with load",0],["PDX3","Variation of friction Mux with camber squared",0],["PEX1","Longitudinal curvature Efx at Fznom",0],["PEX2","Variation of curvature Efx with load",0],["PEX3","Variation of curvature Efx with load squared",0],["PEX4","Factor in curvature Efx while driving",0],["PKX1","Longitudinal slip stiffness Kfx/Fz at Fznom",20],["PKX2","Variation of slip stiffness Kfx/Fz with load",0],["PKX3","Exponent in slip stiffness Kfx/Fz with load",0],["PHX1","Horizontal shift Shx at Fznom",0],["PHX2","Variation of shift Shx with load",0],["PVX1","Vertical shift Svx/Fz at Fznom",0],["PVX2","Variation of shift Svx/Fz with load",0],["PPX1","Linear influence of inflation pressure on longitudinal slip stiffness",0],["PPX2","Quadratic influence of inflation pressure on longitudinal slip stiffness",0],["PPX3","Linear influence of inflation pressure on peak longitudinal friction",0],["PPX4","Quadratic influence of inflation pressure on peak longitudinal friction",0]],jfe=[["QBZ1","Trail slope factor for trail Bpt at Fznom",8],["QBZ2","Variation of slope Bpt with load",0],["QBZ3","Variation of slope Bpt with load squared",0],["QBZ4","Variation of slope Bpt with camber",0],["QBZ5","Variation of slope Bpt with absolute camber",0],["QBZ6","Camber influence Bt",0],["QBZ9","Factor for scaling factors of slope factor Br of Mzr",0],["QBZ10","Factor for dimensionless cornering stiffness of Br of Mzr",0],["QCZ1","Shape factor Cpt for pneumatic trail",1.1],["QDZ1","Peak trail Dpt = Dpt*(Fz/Fznom*R0)",.1],["QDZ2","Variation of peak Dpt with load",0],["QDZ3","Variation of peak Dpt with camber",0],["QDZ4","Variation of peak Dpt with camber squared",0],["QDZ6","Peak residual torque Dmr = Dmr/(Fz*R0)",0],["QDZ7","Variation of peak factor Dmr with load",0],["QDZ8","Variation of peak factor Dmr with camber",0],["QDZ9","Variation of peak factor Dmr with camber and load",0],["QDZ10","Variation of peak factor Dmr with camber squared",0],["QDZ11","Variation of Dmr with camber squared and load",0],["QEZ1","Trail curvature Ept at Fznom",0],["QEZ2","Variation of curvature Ept with load",0],["QEZ3","Variation of curvature Ept with load squared",0],["QEZ4","Variation of curvature Ept with sign of Alpha-t",0],["QEZ5","Variation of Ept with camber and sign Alpha-t",0],["QHZ1","Trail horizontal shift Sht at Fznom",0],["QHZ2","Variation of shift Sht with load",0],["QHZ3","Variation of shift Sht with camber",0],["QHZ4","Variation of shift Sht with camber and load",0],["PPZ1","Effect of inflation pressure on length of pneumatic trail",0],["PPZ2","Influence of inflation pressure on residual aligning torque",0],["SSZ1","Nominal value of s/R0: effect of Fx on Mz",0],["SSZ2","Variation of distance s/R0 with Fy/Fznom",0],["SSZ3","Variation of distance s/R0 with camber",0],["SSZ4","Variation of distance s/R0 with load and camber",0]],Bfe=[["RBX1","Slope factor for combined slip Fx reduction",0],["RBX2","Variation of slope Fx reduction with kappa",0],["RBX3","Influence of camber on stiffness for Fx combined",0],["RCX1","Shape factor for combined slip Fx reduction",1],["REX1","Curvature factor of combined Fx",0],["REX2","Curvature factor of combined Fx with load",0],["RHX1","Shift factor for combined slip Fx reduction",0],["RBY1","Slope factor for combined Fy reduction",0],["RBY2","Variation of slope Fy reduction with alpha",0],["RBY3","Shift term for alpha in slope Fy reduction",0],["RBY4","Influence of camber on stiffness of Fy combined",0],["RCY1","Shape factor for combined Fy reduction",1],["REY1","Curvature factor of combined Fy",0],["REY2","Curvature factor of combined Fy with load",0],["RHY1","Shift factor for combined Fy reduction",0],["RHY2","Shift factor for combined Fy reduction with load",0],["RVY1","Kappa induced side force Svyk/Muy*Fz at Fznom",0],["RVY2","Variation of Svyk/Muy*Fz with load",0],["RVY3","Variation of Svyk/Muy*Fz with camber",0],["RVY4","Variation of Svyk/Muy*Fz with alpha",0],["RVY5","Variation of Svyk/Muy*Fz with kappa",1],["RVY6","Variation of Svyk/Muy*Fz with atan(kappa)",0]],Ufe=[["LFZO","Scale factor of nominal (rated) load",1],["LCX","Scale factor of Fx shape factor",1],["LMUX","Scale factor of Fx peak friction coefficient",1],["LEX","Scale factor of Fx curvature factor",1],["LKX","Scale factor of Fx slip stiffness",1],["LHX","Scale factor of Fx horizontal shift",1],["LVX","Scale factor of Fx vertical shift",1],["LCY","Scale factor of Fy shape factor",1],["LMUY","Scale factor of Fy peak friction coefficient",1],["LEY","Scale factor of Fy curvature factor",1],["LKY","Scale factor of Fy cornering stiffness",1],["LKYC","Scale factor of camber force stiffness",1],["LKZC","Scale factor of camber torque stiffness",1],["LHY","Scale factor of Fy horizontal shift",1],["LVY","Scale factor of Fy vertical shift",1],["LTR","Scale factor of peak of pneumatic trail",1],["LRES","Scale factor for offset of residual torque",1],["LXAL","Scale factor of alpha influence on Fx",1],["LYKA","Scale factor of kappa influence on Fy",1],["LVYKA","Scale factor of kappa induced Fy",1],["LS","Scale factor of moment arm of Fx",1]],eK=[["lateral",zfe],["longitudinal",Vfe],["aligning",jfe],["combined",Bfe],["scaling",Ufe]].flatMap(([e,t])=>t.map(([r,o,n])=>({key:r,section:e,text:o,fallback:n}))),Aje=new Map(eK.map(e=>[e.key,e]));var Gfe=/^\$\s*EDITED\s+([A-Z][A-Z0-9_]*)\s+was\s+(absent|[-+0-9.eE]+)\s*$/;function tK(e){let t={};for(let r of e.split(/\r?\n/)){let o=r.trim().match(Gfe);if(!o)continue;let n=o[2]==="absent"?null:parseFloat(o[2]);(n===null||Number.isFinite(n))&&(t[o[1]]=n)}return Object.keys(t).length?t:void 0}var Hfe=/^\s*\$\s*UNLOADED_RADIUS_STAND_IN\s*=\s*([0-9.eE+-]+)/,Kfe=/^\$-+ written by (?:PaceDynamics|PaceLab)\b/m,Wfe=/^\$\s*AXIS_SYSTEM\s*=\s*(ISO-W|SAE)\b/m;function Yfe(e){let t=e.match(Wfe);return t?{axisSystem:t[1]==="SAE"?"sae":"iso",trustSide:!0}:Kfe.test(e)?{axisSystem:"sae",trustSide:!1}:{axisSystem:"iso",trustSide:!0}}function Zfe(e){return e>=62?"6.2":e>=61?"6.1":"5.2"}var rK=new Map([["pa",1],["pascal",1],["kpa",1e3],["kilopascal",1e3],["mpa",1e6],["megapascal",1e6],["bar",1e5],["psi",6894.757293168]]);function Xfe(e,t,r){let o=r.PRESSURE?.trim().toLowerCase(),n=o===void 0?1:rK.get(o);if(n===void 0)return;let a=(c,l)=>l===1?c:Number((c*l).toPrecision(12)),i=e.NOMPRES??e.INFLPRES;if(i!==void 0)return a(i,n);let s=e.INFLATION_PRESSURE;if(s!==void 0)return o!==void 0?a(s,n):t.PROPERTY_FILE_FORMAT?.trim().toUpperCase()==="MF_05"?a(s,1e5):void 0}var Jfe=new Map([["radians",1],["radian",1],["rad",1],["degrees",Math.PI/180],["degree",Math.PI/180],["deg",Math.PI/180]]);function Qfe(e,t){let r=(i,s)=>i===void 0?1:s.get(i.trim().toLowerCase()),o=r(t.ANGLE,Jfe),n={fz:1,kappa:1,alpha:o,gamma:o,p:r(t.PRESSURE,rK)},a={};for(let i of Tg){let s=n[i.q];if(s===void 0)continue;let c={};for(let[l,u]of[["min",i.min],["max",i.max]]){let m=e[u];Number.isFinite(m)&&(c[l]=s===1?m:Number((m*s).toPrecision(12)),delete e[u])}(c.min!==void 0||c.max!==void 0)&&(a[i.q]=c)}return Object.keys(a).length?a:void 0}function ll(e,t="imported",r={}){let o=Yfe(e),n=r.axisSystem??o.axisSystem,a={},i={},s={},c="",l;for(let b of e.split(/\r?\n/)){let y=b.match(Hfe);y&&(l=parseFloat(y[1]));let v=b.replace(/[$!].*$/,"").trim();if(!v)continue;if(v.startsWith("[")){c=(v.match(/^\[([^\]]*)/)?.[1]??"").trim().toUpperCase();continue}let k=v.indexOf("=");if(k<0)continue;let x=v.slice(0,k).trim().toUpperCase(),S=v.slice(k+1).trim(),R=S.match(/^'([^']*)'|^"([^"]*)"/);if(R){i[x]=R[1]??R[2]??"",c==="UNITS"&&(s[x]=i[x]);continue}let w=parseFloat(S);Number.isFinite(w)&&(a[x]=w)}let u=Zfe(a.FITTYP??62),m=tK(e),p=m?Object.fromEntries(Object.entries(m).filter(([b])=>a[b]!==void 0)):void 0,d=a.VERTICAL_STIFFNESS??a.KZ??0,f=Xfe(a,i,s),h=Qfe(a,s),g=[];return a.UNLOADED_RADIUS===void 0&&a.R0===void 0&&g.push("UNLOADED_RADIUS"),d<=0&&g.push("VERTICAL_STIFFNESS"),a.FNOMIN===void 0&&g.push("FNOMIN"),f===void 0&&g.push("NOMPRES"),{kind:"magic",name:t,version:u,coeffs:a,axisSystem:n,side:o.trustSide?i.TYRESIDE==="RIGHT"?"right":i.TYRESIDE==="LEFT"?"left":void 0:void 0,fnomin:a.FNOMIN??5e3,unloadedR0:a.UNLOADED_RADIUS??a.R0??(l!==void 0&&l>0?l:.3),...a.WIDTH!==void 0&&a.WIDTH>0?{sectionWidth:a.WIDTH}:{},verticalStiffness:d>0?d/1e3:0,...a.FREFF!==void 0&&!a.DREFF?{rollingFraction:a.FREFF}:{},...a.LATERAL_STIFFNESS!==void 0&&a.LATERAL_STIFFNESS>0?{relaxation:{sigma:0,carcassStiffness:a.LATERAL_STIFFNESS/1e3,source:"fitted"}}:{},nomPressure:f??0,missing:g,...p&&Object.keys(p).length?{edited:p}:{},...h?{range:h}:{}}}function zn(e){if(!e)return null;let t=e.unloadedR0;return t===void 0||!(t>0)||e.kind==="magic"&&e.missing?.includes("UNLOADED_RADIUS")?null:t*1e3}function Fg(e){if(!e)return null;let t=e.sectionWidth;return t!==void 0&&t>0?t:null}var Lje=Math.PI/180;var JL=Math.PI/180,ehe=180/Math.PI,QL=[{key:"muY",group:"grip",label:"Peak \u03BCy",unit:"",decimals:2,better:"high",about:"Peak lateral grip at the reference load \u2014 the most side force this tyre makes, per newton of load on it."},{key:"muYLow",group:"grip",label:"\u03BCy light",unit:"",decimals:2,better:"high",about:"Peak lateral grip at the light load \u2014 an inside wheel in a corner."},{key:"muYHigh",group:"grip",label:"\u03BCy loaded",unit:"",decimals:2,better:"high",about:"Peak lateral grip at the most any wheel carries on this car. The gap to the light figure is the load sensitivity."},{key:"loadSens",group:"grip",label:"\u0394\u03BCy",unit:"/kN",decimals:3,better:"high",about:"How much peak lateral grip is lost per kilonewton of extra load. Always negative; nearer zero is a tyre that repays load transfer instead of punishing it."},{key:"muX",group:"grip",label:"Peak \u03BCx",unit:"",decimals:2,better:"high",about:"Peak longitudinal grip at the reference load \u2014 braking and traction."},{key:"kept",group:"grip",label:"Fy kept",unit:"%",decimals:0,better:"high",about:"How much of the side force at 6\xB0 of slip survives a slip ratio of 0.15. A tyre has one contact patch, so this should be well under 100 %; exactly 100 % means the fit never determined its combined-slip weights and its friction envelope is a box."},{key:"cornering",group:"response",label:"C\u03B1",unit:"N/\xB0",decimals:0,better:"high",about:"Cornering stiffness at the reference load: how hard the tyre pushes back for the first degree of slip."},{key:"peakSlip",group:"response",label:"\u03B1 at peak",unit:"\xB0",decimals:1,better:"none",about:"The slip angle where the side force peaks. A low figure is a sharp tyre that gives its grip early and lets go quickly; a high one is forgiving and slower to build. Neither is better, and a driver has an opinion."},{key:"bestCamber",group:"response",label:"Wants camber",unit:"\xB0",decimals:1,better:"none",about:"The inclination at which peak side force is greatest \u2014 what the tyre asks the suspension to deliver at the contact patch. Blank for a model with no camber term at all. Read it as what the FIT says: TTC cornering runs hold 0, 2 and 4\xB0 of camber, so for a tyre fitted from them everything at negative camber is the model extrapolating."},{key:"vertical",group:"response",label:"Vertical rate",unit:"N/mm",decimals:0,better:"none",about:"The tyre spring, for ride. Blank when the file did not measure one, in which case the car\u2019s own rate stands in."},{key:"limit",group:"trust",label:"Good to",unit:"N",decimals:0,better:"none",about:"The load above which this fit stops behaving like a tyre \u2014 more load buys less force. The lap holds its grip there. Below what the car reaches, and everything above it is extrapolation."},{key:"tested",group:"trust",label:"Tested to",unit:"N",decimals:0,better:"none",about:"The highest load in the rig data behind this fit (FZMAX). Above it the fit extends its load trend, up to Good to. Blank when the file does not say."},{key:"ghost",group:"trust",label:"Ghost Fx",unit:"%",decimals:1,better:"low",about:"Longitudinal force the fit produces while rolling straight at zero slip ratio, as a fraction of load. Real rolling resistance is 1\u20132 %; anything above 3 % is a longitudinal block that was never determined by data."}];function ow(e,t,r=0){let o=0,n=0;for(let s=0;s<=45;s+=1){let c=Math.abs(e(s*JL,t,r));c>o&&(o=c,n=s)}let a=Math.max(0,n-1),i=n+1;for(let s=a;s<=i;s+=.1){let c=Math.abs(e(s*JL,t,r));c>o&&(o=c,n=s)}return{peak:o,atDeg:n}}function nK(e,t){let r=ow(e,t,0).peak,o=0;for(let n=-6;n<=6;n+=1){if(n===0)continue;let{peak:a}=ow(e,t,n*JL);a>r&&(r=a,o=n)}return o}function eD(e,t,r){let o=bt(t),n=rw(t),a=sl(t),i=ZL(t,r.ref),s=o.muY(r.low),c=o.muY(r.ref),l=o.muY(r.high),u=(r.high-r.low)/1e3,m=ow(o.Fy,r.ref),p=o.verticalStiffness(),d=Si(t,r.ref),f=cl(t,r.ref).none,h={muY:c,muYLow:s,muYHigh:l,loadSens:u>=.1?(l-s)/u:null,muX:f?null:o.muX(r.ref),kept:f?null:100*i.kept,cornering:o.corneringStiffness(r.ref)/ehe,peakSlip:m.atDeg,bestCamber:d?nK(o.Fy,r.ref):null,vertical:p>0?p:null,limit:n.limit,tested:n.declared,ghost:100*a.ratio},g=x=>n.limit!=null&&n.limit<x?"extrapolated":"measured",b=f?"absent":a.trustworthy?g(r.ref):"assumed",y={muY:g(r.ref),muYLow:g(r.low),muYHigh:g(r.high),loadSens:g(r.high),muX:b,kept:f?"absent":i.coupled?g(r.ref):"assumed",cornering:g(r.ref),peakSlip:g(r.ref),bestCamber:d?g(r.ref):"absent",vertical:p>0?"measured":"absent",limit:"measured",tested:n.declared!=null?"measured":"absent",ghost:"measured"},v=[];f?v.push({kind:"noFx",level:"warn",text:"No drive or braking grip in this file: its longitudinal block is zero, as a cornering-only fit writes it. A car on it cannot accelerate or brake."}):i.coupled||v.push({kind:"box",level:"warn",text:"No combined-slip weights in this fit: its friction envelope is a box, so it will brake at full grip while cornering at full grip."}),a.trustworthy||v.push({kind:"ghost",level:"warn",text:`Rolling straight at zero slip ratio this fit makes ${a.ghostFx.toFixed(0)} N \u2014 ${(100*a.ratio).toFixed(0)} % of the load at ${a.atLoad.toFixed(0)} N. Its longitudinal block was not determined by data.`}),n.limit!=null&&n.limit<r.high&&v.push({kind:"beyond",level:"warn",text:`The fit stops behaving like a tyre at ${n.limit.toFixed(0)} N, below the ${r.high.toFixed(0)} N this car puts on its most loaded wheel. Everything at that load is extrapolation.`}),p<=0&&v.push({kind:"noRate",level:"note",text:"No vertical stiffness in this file, so the car\u2019s own tyre rate stands in. Changing to this tyre will not change the ride rate."});let k=t.kind==="magic"?(t.missing??[]).filter(x=>x!=="VERTICAL_STIFFNESS"):[];return k.length>0&&v.push({kind:"missing",level:"note",text:`Not in this file: ${k.join(", ")}.`}),{id:e,name:t.name,kind:t.kind,values:h,trust:y,flags:v}}function $g(){return{kind:"simple",name:"Simple (default)",Bx:11,Cx:1.6,muX0:1.7,loadSensX:-8e-5,By:9,Cy:1.4,muY0:1.6,loadSensY:-1e-4,nominalLoad:1500,verticalStiffness:120}}var oK=`$ AXIS_SYSTEM = SAE (authored in the evaluation frame: y right)
|
|
79
|
+
`)}writeFrame(e){if(!(this._sse===void 0||this._sse.closed))try{this._sse.controller.enqueue(this._sse.encoder.encode(e))}catch(t){this.onerror?.(new Error(`Failed to write to the response stream: ${t}`))}}};function dme(e){return e instanceof hU?fU(e):void 0}function pme(e){return typeof e=="object"&&e!==null&&"setScopeChallengeResolver"in e&&typeof e.setScopeChallengeResolver=="function"}var fme=8,hme=6e5;function gme(e){if(e?.maxRounds!==void 0&&(!Number.isInteger(e.maxRounds)||e.maxRounds<1))throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${e.maxRounds})`);if(e?.roundTimeoutMs!==void 0&&(!Number.isFinite(e.roundTimeoutMs)||e.roundTimeoutMs<=0))throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${e.roundTimeoutMs})`);return{maxRounds:e?.maxRounds??fme,roundTimeoutMs:e?.roundTimeoutMs??hme,legacyShim:e?.legacyShim??!0}}function gU(e,t,r){if(r===null||typeof r!="object"||typeof r.method!="string")throw new qe(_e.InternalError,`Handler for ${e} returned an invalid input request '${t}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let o=r,n=s6(o);if(n===void 0)throw new qe(_e.InternalError,`Handler for ${e} returned an input request '${t}' of kind '${o.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:o,required:n}}function bme(){let e=globalThis.crypto;if(e?.randomUUID!==void 0)return e.randomUUID();let t=new Uint8Array(16);e.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let r=[...t].map(o=>o.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function HI(e,t){if(e==="tools/call")return{content:[{type:"text",text:t}],isError:!0};throw new qe(_e.InternalError,t)}var yme=class{constructor(e){this._host=e}async fulfill(e,t,r,o,n){let{maxRounds:a,roundTimeoutMs:i}=this._host,s=o.mcpReq.signal,c=n,l=0;for(;;){if(l+=1,l>a)return HI(e,P6(e,a));let u=c.inputRequests,m=u!=null&&Object.keys(u).length>0,p=typeof c.requestState=="string"?c.requestState:void 0;if(!m&&p===void 0)throw new qe(_e.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let d;if(m){let g=this._host.resolvedClientCapabilities(o),b=[];for(let[v,k]of Object.entries(u)){let{embedded:x,required:S}=gU(e,v,k);if(x.method!=="roots/list"&&x.params===void 0)throw new qe(_e.InternalError,`Handler for ${e} returned an input request '${v}' of kind '${x.method}' without params`);if(OR(S,g)!==void 0)return HI(e,`Cannot request input '${v}' (${x.method}): the client on this 2025-era connection did not declare the required capability${g===void 0?" (no client capabilities are available on this connection \u2014 per-request legacy serving cannot receive server-to-client requests)":""}`);b.push([v,x])}let y=$6(s);try{let v={relatedRequestId:o.mcpReq.id,timeout:i,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:y.signal},k=await Promise.all(b.map(async([x,S])=>{try{return[x,await this._dispatchLeg(S,v)]}catch(R){throw y.abort(R),R}}));d=Object.fromEntries(k)}catch(v){if(s.aborted)throw v;return HI(e,`Fulfilling input required by '${e}' failed: ${v instanceof Error?v.message:String(v)}`)}finally{y.dispose()}}else await F6(T6,s);let f={...o,mcpReq:{...o.mcpReq,inputResponses:d,droppedInputResponseKeys:void 0,requestState:Nh(p)}};if(p!==void 0){let g=await this._host.verifyRequestState(p,f,e);g!==void 0&&(f=II(f,g))}let h=await t(r,f);if(!ui(h))return h;c=h}}async _dispatchLeg(e,t){switch(e.method){case"elicitation/create":{let r=e.params;return r.mode==="url"&&r.elicitationId===void 0&&(r={...r,elicitationId:bme()}),await this._host.sendElicitation(r,t)}case"sampling/createMessage":return await this._host.sendSampling(e.params,t);case"roots/list":return await this._host.listRoots(e.params,t)}}},vme=new Set(["tools/call","prompts/get","resources/read"]),Sme,kme,Rme;var bU=class extends EI{_clientCapabilities;_clientVersion;static{Sme=(e,t)=>{t.clientCapabilities!==void 0&&(e._clientCapabilities=t.clientCapabilities),t.clientInfo!==void 0&&(e._clientVersion=t.clientInfo)},kme=(e,t)=>{let r=t.filter(o=>!e._supportedProtocolVersions.includes(o));r.length>0&&(e._supportedProtocolVersions=[...e._supportedProtocolVersions,...r]),e.setRequestHandler("server/discover",()=>e._ondiscover())},Rme=e=>e._serverInfo}_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_boundFromTransport=!1;_legacyInputRequiredShim(){return this._legacyShim??=new yme({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:e=>this._inputRequestCapabilityView(e),verifyRequestState:(e,t,r)=>this._verifyRequestState(e,t,r),sendElicitation:(e,t)=>this._sendElicitationLeg(e,t,{validateAcceptedContent:!1}),sendSampling:(e,t)=>this.createMessage(e,t),listRoots:(e,t)=>this.listRoots(e,t)})}oninitialized;constructor(e,t){if(super(t),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new JR,this._requestStateVerify=t?.requestState?.verify,this._inputRequiredServing=gme(t?.inputRequired),t?.cacheHints!==void 0){for(let[r,o]of Object.entries(t.cacheHints))o!==void 0&&xI(o,`cacheHints['${r}']`);this._cacheHints=t.cacheHints}this.setRequestHandler("initialize",r=>this._oninitialize(r)),this.setNotificationHandler("notifications/initialized",()=>this.oninitialized?.()),VR(this._supportedProtocolVersions).length>0&&this.setRequestHandler("server/discover",()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}async connect(e){if(this.transport!==void 0)throw new tt(it.AlreadyConnected,"Use a separate Server instance per connection: this instance is already connected to a transport. To connect it to a new transport, call close() first.");this._boundFromTransport&&(this._boundFromTransport=!1,this._negotiatedProtocolVersion=void 0);let t=dme(e)?.revision;t!==void 0&&!this._servedModernEra()&&zR.includes(t)&&VR(this._supportedProtocolVersions).includes(t)&&(this._negotiatedProtocolVersion=t,this._boundFromTransport=!0),await super.connect(e)}_registerLoggingHandler(){this.setRequestHandler("logging/setLevel",async(e,t)=>{let r=t.sessionId||t.http?.req?.headers.get("mcp-session-id")||void 0,{level:o}=e.params,n=GR(Rs,o);return n.success&&this._loggingLevels.set(r,n.data),{}})}buildContext(e,t){let r=e.http||t?.request||t?.closeSSEStream||t?.closeStandaloneSSEStream;return{...e,mcpReq:{...e.mcpReq,log:(o,n,a)=>{if(!this._capabilities.logging)return Promise.resolve();let i;if(this._servedModernEra()){if(i=e.mcpReq.envelope?.[gs],i===void 0)return Promise.resolve()}else i=this._loggingLevels.get(e.sessionId)??this._loggingLevels.get(void 0);return i!==void 0&&this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(i)?Promise.resolve():e.mcpReq.notify({method:"notifications/message",params:{level:o,data:n,logger:a}})},elicitInput:(o,n)=>this.elicitInput(o,n),requestSampling:(o,n)=>this.createMessage(o,n)},http:r?{...e.http,req:t?.request,closeSSE:t?.closeSSEStream,closeStandaloneSSE:t?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Rs.options.map((e,t)=>[e,t]));isMessageIgnored=(e,t)=>{let r=this._loggingLevels.get(t);return r?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r):!1};registerCapabilities(e){if(this.transport)throw new tt(it.AlreadyConnected,"Cannot register capabilities after connecting to transport");let t=!!this._capabilities.logging;this._capabilities=LI(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(e,t){if(e!=="tools/call"){let r=this._cacheHints?.[e],o=vme.has(e);return r===void 0&&!o?async(n,a)=>{let i=await t(n,a);if(ui(i))throw new qe(_e.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return i}:async(n,a)=>{let i=o?await this._invokeInputRequiredCapableHandler(e,t,n,a):await t(n,a);if(ui(i)){if(!o)throw new qe(_e.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return i}return r===void 0?i:jR(i,r)}}return async(r,o)=>{let n=qc(this._negotiatedProtocolVersion),a=n.validateRequest("tools/call",r);if(!a.ok)throw new qe(a.reason==="not-in-era"?_e.InternalError:_e.InvalidParams,a.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call request: ${a.message}`);let i=await this._invokeInputRequiredCapableHandler("tools/call",t,r,o);if(ui(i))return i;let s=yI(i),c=n.validateResult("tools/call",s);if(!c.ok)throw new qe(c.reason==="not-in-era"?_e.InternalError:_e.InvalidParams,c.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call result: ${c.message}`);return c.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&Lh(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(e,t,r,o){let n=this._servedModernEra(),a=o.mcpReq.requestState();if(a!==void 0&&typeof a!="string")throw new qe(_e.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"});let i=o;if(typeof a=="string"){let m=await this._verifyRequestState(a,o,e);m!==void 0&&(i=II(o,m))}let s;try{s=await t(r,i)}catch(m){throw m instanceof qe&&m.code===_e.UrlElicitationRequired&&n?new qe(_e.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { \u2026: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):m}if(!ui(s))return s;if(!n){if(!this._inputRequiredServing.legacyShim)throw new qe(_e.InternalError,`Handler for ${e} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??Vc}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(e,t,r,i,s)}let c=s.inputRequests,l=c!=null&&Object.keys(c).length>0,u=typeof s.requestState=="string";if(!l&&!u)throw new qe(_e.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(l){let m=this._inputRequestCapabilityView(o);for(let[p,d]of Object.entries(c)){let{embedded:f,required:h}=gU(e,p,d),g=OR(h,m);if(g!==void 0)throw new UR({requiredCapabilities:g},`Cannot request input '${p}' (${f.method}): the request's client capabilities do not declare the required capability`)}}return s}async _verifyRequestState(e,t,r){if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(e,t)}catch(o){throw this.onerror?.(new Error(`requestState verification rejected ${r}: ${o instanceof Error?o.message:String(o)}`)),new qe(_e.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"})}}_inputRequestCapabilityView(e){return this._servedModernEra()?e.mcpReq.envelope?.[ci]:this._clientCapabilities}_assertPushApiInServedEra(e){if(this._servedModernEra())throw new tt(it.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${e}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead \u2014 the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:e,era:"2026-07-28"})}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new tt(it.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new tt(it.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new tt(it.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new tt(it.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new tt(it.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new tt(it.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new tt(it.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new tt(it.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"completion/complete":if(!this._capabilities.completions)throw new tt(it.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new tt(it.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new tt(it.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new tt(it.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new tt(it.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo;let r=l6(this._supportedProtocolVersions),o=r.includes(t)?t:r[0]??Vc;return this._negotiatedProtocolVersion=o,this.transport?.setProtocolVersion?.(o),{protocolVersion:o,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:VR(this._supportedProtocolVersions),capabilities:xme(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(e,t){return this._wireCodec().projectCallToolResult(e,t)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra("ping"),this.request({method:"ping"})}async createMessage(e,t){if(this._assertPushApiInServedEra("sampling/createMessage"),(e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new tt(it.CapabilityNotSupported,"Client does not support sampling tools capability.");if(e.messages.length>0){let a=e.messages.at(-1),i=Array.isArray(a.content)?a.content:[a.content],s=i.some(m=>m.type==="tool_result"),c=e.messages.length>1?e.messages.at(-2):void 0,l=c?Array.isArray(c.content)?c.content:[c.content]:[],u=l.some(m=>m.type==="tool_use");if(s){if(i.some(m=>m.type!=="tool_result"))throw new qe(_e.InvalidParams,"The last message must contain only tool_result content if any is present");if(!u)throw new qe(_e.InvalidParams,"tool_result blocks are not matching any tool_use from the previous message")}if(u){let m=new Set(l.filter(d=>d.type==="tool_use").map(d=>d.id)),p=new Set(i.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(m.size!==p.size||![...m].every(d=>p.has(d)))throw new qe(_e.InvalidParams,"ids of tool_result blocks and tool_use blocks from previous message do not match")}}let r=!!(e.tools||e.toolChoice),o=await this.request({method:"sampling/createMessage",params:e},t),n=this._wireCodec().samplingResultVariant(r,o);if(!n.ok)throw new tt(it.InvalidResult,`Invalid sampling/createMessage result: ${n.reason==="invalid"?n.message:n.reason}`);return n.value}async elicitInput(e,t){switch(this._assertPushApiInServedEra("elicitation/create"),e.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw new tt(it.CapabilityNotSupported,"Client does not support url elicitation.");break;case"form":if(!this._clientCapabilities?.elicitation?.form)throw new tt(it.CapabilityNotSupported,"Client does not support form elicitation.");break}return this._sendElicitationLeg(e,t)}async _sendElicitationLeg(e,t,r){let o=e.mode??"form",n=r?.validateAcceptedContent??!0;switch(o){case"url":{let a=e;return this.request({method:"elicitation/create",params:a},t)}case"form":{let a=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:a},t);if(n&&i.action==="accept"&&i.content&&a.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(a.requestedSchema)(i.content);if(!s.valid)throw new qe(_e.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(s){throw s instanceof qe?s:new qe(_e.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new tt(it.CapabilityNotSupported,"Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this._assertPushApiInServedEra("roots/list"),this.request({method:"roots/list",params:e},t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};function xme(e){return{...e}}function wme(e,t){let r=0,o=[e];for(;o.length>0;){let n=o.pop();if(!(n===null||typeof n!="object"))if(Array.isArray(n))for(let a of n){if(++r>t)return r;a!==null&&typeof a=="object"&&o.push(a)}else for(let a in n){if(!Object.prototype.hasOwnProperty.call(n,a))continue;if(++r>t)return r;let i=n[a];i!==null&&typeof i=="object"&&o.push(i)}}return r}function Mme(e){if(!(e===void 0||e===1/0)){if(typeof e!="number"||Number.isNaN(e)||e<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}var QR=class{server;_maxToolInputElements;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(e){let t=this._registeredTools[e];if(!(t===void 0||!t.enabled)){if(Object.hasOwn(this._toolInputSchemaJson,e))return this._toolInputSchemaJson[e];if(t.inputSchema===void 0)return sU;try{let r=Hc(t.inputSchema,"input");return this._toolInputSchemaJson[e]=r,r}catch{return}}}constructor(e,t){this.server=new bU(e,t),this._maxToolInputElements=Mme(t?.maxToolInputElements),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(e){return pme(e)&&e.setScopeChallengeResolver(t=>this.resolveScopeChallenge(t)),await this.server.connect(e)}async close(){await this.server.close()}resolveScopeChallenge=e=>{switch(e.request.method){case"tools/call":{let t=e.request.params?.name;if(typeof t!="string")return;let r=this._registeredTools[t];return r===void 0||!r.enabled?void 0:r.scopeChallenge?.(e)}case"resources/read":{let t=e.request.params?.uri;if(typeof t!="string")return;let r;try{r=new URL(t)}catch{return}let o=this._registeredResources[r.toString()];if(o!==void 0)return o.enabled?o.scopeChallenge?.(e):void 0;for(let n of Object.values(this._registeredResourceTemplates))if(n.resourceTemplate.uriTemplate.match(r.toString()))return n.enabled?n.scopeChallenge?.(e):void 0;return}case"prompts/get":{let t=e.request.params?.name;if(typeof t!="string")return;let r=this._registeredPrompts[t];return r===void 0||!r.enabled?void 0:r.scopeChallenge?.(e)}default:return}};_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler("tools/list"),this.server.assertCanSetRequestHandler("tools/call"),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler("tools/list",()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?_me(e,t.inputSchema):sU,annotations:t.annotations,icons:t.icons,execution:t.execution,_meta:t._meta};return t.outputSchema&&(r.outputSchema=Hc(t.outputSchema,"output")),r})})),this.server.setRequestHandler("tools/call",async(e,t)=>{let r=this._registeredTools[e.params.name];if(!r)throw new qe(_e.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new qe(_e.InvalidParams,`Tool ${e.params.name} disabled`);try{let o=await this.validateToolInput(r,e.params.arguments,e.params.name),n=await this.executeToolHandler(r,o,t);return await this.validateToolOutput(r,n,e.params.name),ui(n)?n:this.server.projectCallToolResult(n,r.outputSchemaJson)}catch(o){if(o instanceof qe&&o.code===_e.UrlElicitationRequired)throw o;return this.createToolError(o instanceof Error?o.message:String(o))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(this._maxToolInputElements!==void 0&&wme(t,this._maxToolInputElements)>this._maxToolInputElements)throw new qe(_e.InvalidParams,`Invalid arguments for tool ${r}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let o=await Gc(e.inputSchema,t??{});if(!o.success)throw new qe(_e.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${o.error}`);return o.data}async validateToolOutput(e,t,r){if(!e.outputSchema||ui(t)||t.isError)return;if(t.structuredContent===void 0)throw new qe(_e.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=await Gc(e.outputSchema,t.structuredContent);if(!o.success)throw new qe(_e.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${o.error}`)}async executeToolHandler(e,t,r){return e.executor(t,r)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler("completion/complete"),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler("completion/complete",async e=>{switch(e.params.ref.type){case"ref/prompt":return TI(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return PI(e),this.handleResourceCompletion(e,e.params.ref);default:throw new qe(_e.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new qe(_e.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new qe(_e.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return zh;let o=dU(mU(r.argsSchema)?.[e.params.argument.name]);if(!KI(o))return zh;let n=ume(o);return n?uU(await n(e.params.argument.value,e.params.context)):zh}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(n=>n.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return zh;throw new qe(_e.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);return o?uU(await o(e.params.argument.value,e.params.context)):zh}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler("resources/list"),this.server.assertCanSetRequestHandler("resources/templates/list"),this.server.assertCanSetRequestHandler("resources/read"),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler("resources/list",async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([n,a])=>a.enabled).map(([n,a])=>({uri:n,name:a.name,...a.metadata})),o=[];for(let n of Object.values(this._registeredResourceTemplates)){if(!n.resourceTemplate.listCallback)continue;let a=await n.resourceTemplate.listCallback(t);for(let i of a.resources)o.push({...n.metadata,...i})}return{resources:[...r,...o]}}),this.server.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler("resources/read",async(e,t)=>{let r;try{r=new URL(e.params.uri)}catch{throw new qe(_e.InvalidParams,`Resource URI ${e.params.uri} is invalid`,{uri:e.params.uri,reason:"invalid_uri"})}let o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new qe(_e.InvalidParams,`Resource ${r} disabled`);return jR(await o.readCallback(r,t),o.cacheHint)}for(let n of Object.values(this._registeredResourceTemplates)){let a=n.resourceTemplate.uriTemplate.match(r.toString());if(a){if(!n.enabled)throw new qe(_e.InvalidParams,`Resource template ${n.resourceTemplate.uriTemplate} disabled`);return jR(await n.readCallback(r,a,t),n.cacheHint)}}throw new BR(e.params.uri)}),this._resourceHandlersInitialized=!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler("prompts/list"),this.server.assertCanSetRequestHandler("prompts/get"),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler("prompts/list",()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?C6(t.argsSchema):void 0,icons:t.icons,_meta:t._meta}))})),this.server.setRequestHandler("prompts/get",async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new qe(_e.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new qe(_e.InvalidParams,`Prompt ${e.params.name} disabled`);return r.handler(e.params.arguments,t)}),this._promptHandlersInitialized=!0)}registerResource(e,t,r,o){let{cacheHint:n,scopeChallenge:a,...i}=r,s=i;if(n!==void 0&&xI(n,`resource ${e}`),typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let c=this._createRegisteredResource(e,r.title,t,s,a,o);return n!==void 0&&(c.cacheHint=n),this.setResourceRequestHandlers(),this.sendResourceListChanged(),c}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let c=this._createRegisteredResourceTemplate(e,r.title,t,s,a,o);return n!==void 0&&(c.cacheHint=n),this.setResourceRequestHandlers(),this.sendResourceListChanged(),c}}_createRegisteredResource(e,t,r,o,n,a){let i={name:e,title:t,metadata:o,readCallback:a,scopeChallenge:n,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:s=>{s.uri!==void 0&&s.uri!==r&&(delete this._registeredResources[r],s.uri&&(this._registeredResources[s.uri]=i)),s.name!==void 0&&(i.name=s.name),s.metadata!==void 0&&(i.metadata=s.metadata),s.title!==void 0&&(i.title=s.title,i.metadata={...i.metadata,title:s.title}),s.callback!==void 0&&(i.readCallback=s.callback),s.scopeChallenge!==void 0&&(i.scopeChallenge=s.scopeChallenge===null?void 0:s.scopeChallenge),s.enabled!==void 0&&(i.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,t,r,o,n,a){let i={resourceTemplate:r,title:t,metadata:o,readCallback:a,scopeChallenge:n,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:c=>{c.name!==void 0&&c.name!==e&&(delete this._registeredResourceTemplates[e],c.name&&(this._registeredResourceTemplates[c.name]=i)),c.template!==void 0&&(i.resourceTemplate=c.template),c.metadata!==void 0&&(i.metadata=c.metadata),c.title!==void 0&&(i.title=c.title,i.metadata={...i.metadata,title:c.title}),c.callback!==void 0&&(i.readCallback=c.callback),c.scopeChallenge!==void 0&&(i.scopeChallenge=c.scopeChallenge===null?void 0:c.scopeChallenge),c.enabled!==void 0&&(i.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let s=r.uriTemplate.variableNames;return Array.isArray(s)&&s.some(c=>!!r.completeCallback(c))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,t,r,o,n,a,i,s){let c=o,l=n,u={title:t,description:r,argsSchema:o,icons:a,scopeChallenge:i,_meta:s,handler:lU(e,o,n),enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:m=>{m.name!==void 0&&m.name!==e&&(delete this._registeredPrompts[e],m.name&&(this._registeredPrompts[m.name]=u)),m.title!==void 0&&(u.title=m.title),m.description!==void 0&&(u.description=m.description),m.icons!==void 0&&(u.icons=m.icons),m.scopeChallenge!==void 0&&(u.scopeChallenge=m.scopeChallenge===null?void 0:m.scopeChallenge),m._meta!==void 0&&(u._meta=m._meta);let p=!1;m.argsSchema!==void 0&&(u.argsSchema=m.argsSchema,c=m.argsSchema,p=!0),m.callback!==void 0&&(l=m.callback,p=!0),p&&(u.handler=lU(e,c,l)),m.enabled!==void 0&&(u.enabled=m.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=u,o){let m=mU(o);m&&Object.values(m).some(p=>KI(dU(p)))&&this.setCompletionRequestHandler()}return u}_createRegisteredTool(e,t,r,o,n,a,i,s,c,l,u){OI(e);let m=u,p,d={title:t,description:r,inputSchema:o,outputSchema:n,get outputSchemaJson(){return p??=cU(d.outputSchema)},set outputSchemaJson(f){p=f},annotations:a,icons:i,execution:s,scopeChallenge:c,_meta:l,handler:u,executor:iU(o,u),enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:f=>{f.name!==void 0&&f.name!==e&&(typeof f.name=="string"&&OI(f.name),delete this._registeredTools[e],delete this._toolInputSchemaJson[e],f.name&&(delete this._toolInputSchemaJson[f.name],this._registeredTools[f.name]=d,e=f.name)),f.title!==void 0&&(d.title=f.title),f.description!==void 0&&(d.description=f.description);let h=!1;f.paramsSchema!==void 0&&(d.inputSchema=f.paramsSchema,delete this._toolInputSchemaJson[e],h=!0),f.callback!==void 0&&(d.handler=f.callback,m=f.callback,h=!0),h&&(d.executor=iU(d.inputSchema,m)),f.outputSchema!==void 0&&(d.outputSchema=f.outputSchema,d.outputSchemaJson=cU(f.outputSchema)),f.annotations!==void 0&&(d.annotations=f.annotations),f.icons!==void 0&&(d.icons=f.icons),f.scopeChallenge!==void 0&&(d.scopeChallenge=f.scopeChallenge===null?void 0:f.scopeChallenge),f._meta!==void 0&&(d._meta=f._meta),f.enabled!==void 0&&(d.enabled=f.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}registerTool(e,t,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:n,inputSchema:a,outputSchema:i,annotations:s,icons:c,scopeChallenge:l,_meta:u}=t;return this._createRegisteredTool(e,o,n,qR(a),qR(i),s,c,void 0,l,u,r)}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:n,argsSchema:a,icons:i,scopeChallenge:s,_meta:c}=t,l=this._createRegisteredPrompt(e,o,n,qR(a),r,i,s,c);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),l}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};function iU(e,t){if(e){let o=t;return async(n,a)=>o(n,a)}let r=t;return async(o,n)=>r(n)}var sU={type:"object",properties:{}};function _me(e,t){let r=Hc(t,"input"),o=FI(r);return o.valid||console.warn(`[mcp-sdk] tool '${e}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${o.reason}`),r}function cU(e){if(e!==void 0)try{return Hc(e,"output")}catch{return}}function lU(e,t,r){if(t){let o=r;return async(n,a)=>{let i=await Gc(t,n??{});if(!i.success)throw new qe(_e.InvalidParams,`Invalid arguments for prompt ${e}: ${i.error}`);return o(i.data,a)}}else{let o=r;return async(n,a)=>o(a)}}function uU(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}var zh={completion:{values:[],hasMore:!1}};function mU(e){let t=e;if(t.shape&&typeof t.shape=="object")return t.shape}function Ame(e){return e?.type==="optional"}function dU(e){return Ame(e)?e.def?.innerType??e:e}var yU=Symbol("swallowsErrorsAfterClose"),vU=class{_readBuffer;_started=!1;_closed=!1;constructor(e=qI.stdin,t=qI.stdout,r){this._stdin=e,this._stdout=t,this._readBuffer=new DI({maxBufferSize:r?.maxBufferSize})}onclose;onerror;onmessage;_ondata=e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(t){this.onerror?.(t),this.close().catch(()=>{})}};_onerror=e=>{this.onerror?.(e)};_onstdouterror=e=>{this._closed||(this.onerror?.(e),this.close().catch(()=>{}))};_onstdinclose=()=>{this.close().catch(()=>{})};async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0;for(let e of this._stdout.listeners("error"))e[yU]&&this._stdout.off("error",e);(this._stdin.readableEnded||this._stdin.destroyed)&&setImmediate(this._onstdinclose),this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror),this._stdin.on("end",this._onstdinclose),this._stdin.on("close",this._onstdinclose),this._stdout.on("error",this._onstdouterror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._closed||(this._closed=!0,this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.off("end",this._onstdinclose),this._stdin.off("close",this._onstdinclose),this._onstdouterror[yU]=!0,this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.())}send(e){return this._closed?Promise.reject(new Error("StdioServerTransport is closed")):new Promise((t,r)=>{let o=NI(e),n=!1,a=s=>{n||(n=!0,this._stdout.off("error",a),this._stdout.off("drain",i),r(s))},i=()=>{n||(n=!0,this._stdout.off("error",a),this._stdout.off("drain",i),t())};if(this._stdout.once("error",a),this._stdout.write(o)){if(n)return;n=!0,this._stdout.off("error",a),t()}else n||this._stdout.once("drain",i)})}};var SU={version:"1.0.0",date:"2026-11-16",headline:"PaceDynamics 1.0: a car from its suspension geometry to its lap time",notes:[{title:"One car, every tool",body:"Draw the suspension, fit the tyres, set up the aero, battery, brakes and powertrain, and drive the car round a track. Each part is edited in one place, and every tool reads the same car.",tool:"garage"},{title:"Lap time, and where it comes from",body:"Run a lap quasi-steady, transient or as the optimal lap, and see where one car or setup gains on another. Studies search the setup for you, and a logged session opens against the car it ran as.",tool:"laptime"},{title:"Release notes start here",body:"Help \u203A What\u2019s new lists every release from 1.0.0 on. The test versions before it are not listed."}]};var kU={version:"1.0.2",date:"2026-11-17",headline:"The website\u2019s opening drawing moves the upper wishbone as an engineer would",notes:[{title:"Down and out, front and rear",body:"The edit at the top of pacedyn.dev now moves the upper wishbone\u2019s two inboard pickups 15 mm down and 15 mm out, and the drawing shows where its instant centre goes. The suspension pictures below show the same edit."},{title:"The lap it moves, from the lap that follows it",body:"The large figure under the drawing is the quasi-steady lap, 0.338 s quicker, and says so. It follows a hardpoint to the hundredth; the driven lap moves in larger steps of pace."}]};var RU={version:"1.0.3",date:"2026-11-17",headline:"The website\u2019s replay loop rides lower behind the car, in daylight",notes:[{title:"Sky, hills and the road ahead",body:"The moving replay on pacedyn.dev follows the hill-climb car through the Pikes Peak hairpin from about a driver\u2019s eye height, in the replay\u2019s Daylight scenery, so the road ahead and the mountain are in the picture with the car."}]};var xU={version:"1.10.2",date:"2026-11-19",headline:"The terms say how far to trust a result",notes:[{title:"Check before you rely on it",body:"The terms of 19 November 2026 say results are model approximations that can be wrong. Check them for plausibility, and cross-check them independently before a safety-relevant decision, such as a load-bearing part or the brakes."}]};var wU={version:"1.10.3",date:"2026-11-19",headline:"Confirmations and invitations arrive once",notes:[{title:"No more duplicate mails",body:"A purchase or cancellation confirmation, an invitation or a notice could arrive twice when two rounds of sending overlapped. Each mail is now taken by one round only, so it arrives once."}]};var MU={version:"1.11.0",date:"2026-11-19",headline:"When the terms change, the app says what changed and asks you to accept",notes:[{title:"Changed terms, in a band",body:"A band under the top bar names the new version and what changed, with a link to the text. Accept, or choose Later: until you accept, the terms you agreed to apply, and nothing in the app waits for your answer."}]};var _U={version:"1.12.0",date:"2026-11-19",headline:"Use cases on pacedyn.dev: five common jobs taken through the app, step by step",notes:[{title:"Use cases",body:"A new page on the website takes five jobs through the app, step by step: simulate a hardpoint change, set brake bias with a proportioning valve, choose a final drive ratio, optimise roll centres, fit tyre data."}]};var AU={version:"1.13.0",date:"2026-11-19",headline:"Menus you can scan by icon, and the logo back over the tools on a desktop",notes:[{title:"Find an item at a glance",body:"Every item in the project, Help and Account menus has an icon, related items are grouped, and pages that open on pacedyn.dev say so. The Library button shows its shelf, and Delete account stands out in red."},{title:"The logo stays put on a desktop",body:"On a wide window the logo sits over the tool rail again, and the project name has its room back. Phones and tablets keep it centred."},{title:"See who is who",body:"Avatars are larger in the Account menu, the team panel and the Library; the one in the top bar keeps its size."}]};var CU={version:"1.2.0",date:"2026-11-17",headline:"Work on our server waits its turn, and a cancel before it starts costs nothing",notes:[{title:"One queue",body:"Optimal laps, server runs of a study and fits of many sessions now wait in one queue and are taken up in turn. A job keeps its place however long it waits."},{title:"Cancel before it starts",body:"Cancelling an Optimal lap or a server run that has not started ends it at once and costs nothing. One that is running stops within seconds, counting what it used."},{title:"Restarts",body:"If our server restarts, a server run carries on from the starts it finished. A fit that was running ends without charge and asks to be started again."}]};var TU={version:"1.3.0",date:"2026-11-17",headline:"Transient lap times follow your edits where the line limit sets the pace",notes:[{title:"The lap at the line limit",body:"Where staying within the line limit sets a car\u2019s pace, the Transient lap is now read at the limit itself, between the last run inside it and the first outside. A small edit moves the lap by a small amount, not by a whole step of the search."},{title:"Which run you are watching",body:"The replay plays the quickest run driven, which can be a little slower than the lap shown; the note under it gives both times. Gaps to other cars, in the replay too, are between the laps shown."}]};var PU={version:"1.4.1",date:"2026-11-17",headline:"In Daylight, the ground beside a road climbs as a bank, not a sheer wall",notes:[{title:"Cuttings that look like cuttings",body:"Where the hillside stands above the road, the replay\u2019s Daylight scenery now slopes it back from the road\u2019s edge, steepening as it climbs. It rose as a sheer, pleated wall, as before the Pikes Peak hairpin in the website\u2019s loop."}]};var FU={version:"1.4.2",date:"2026-11-17",headline:"The website quotes the hill climb\u2019s Transient laps as the app now shows them",notes:[{title:"Where does the lap go?",body:"The website\u2019s hill-climb comparison now reads 8:05.702 against 7:59.419 for the big-wing copy, 6.283 s apart: the laps the app shows since it reads them at the line limit. Its Overview and replay pictures are new captures."}]};var $U={version:"1.5.0",date:"2026-11-17",headline:"Work waiting for your team\u2019s own machine says so, and when it was last seen",notes:[{title:"Waiting for your team\u2019s machine",body:"An Optimal lap or a fit of many sessions waiting for your team\u2019s own machine now says which one and when it was last seen, e.g. \u201CWaiting for workshop-pc, last seen 2 h ago\u201D. It runs there once the machine is back."},{title:"Your team\u2019s machines",body:"The Team dialog lists your team\u2019s machines: version, when each was last seen and how much waits for it. Owners and admins can cancel everything waiting for a machine that is away."},{title:"Deleting a fit",body:"Deleting a fit of many sessions that has not started now cancels it too, at no cost. One that is running stops within seconds."}]};var IU={version:"1.5.2",date:"2026-11-17",headline:"Inspect no longer fails when two runs of a long course are shown",notes:[{title:"A saved run beside a long lap",body:"With a saved run opened beside the car on a course as long as Pikes Peak, Laptime \u203A Inspect stopped with \u201CLaptime could not draw this project\u201D. Its g-g card now draws both runs."}]};var EU={version:"1.5.3",date:"2026-11-18",headline:"A study\u2019s roll-centre height curves read the height its target asks for",notes:[{title:"RC height (chassis) on the study\u2019s curves",body:"The roll-centre height curves in Studies \u203A Run were measured from the survey\u2019s ground. They now draw RC height (chassis), as Kinematics names it, so at the design ride they start at the static height the target reads."}]};var LU={version:"1.5.4",date:"2026-11-18",headline:"The wait quoted before an optimal lap is measured with today\u2019s solver",notes:[{title:"An honest wait before a solve",body:"The wait shown before an optimal lap was measured again with today\u2019s solver: about 6\u201312 minutes for one car on FSG, where it said 7\u201311. The car sets most of the spread, so an easy car finishes near the low end."}]};var DU={version:"1.5.5",date:"2026-11-18",headline:"A new privacy notice: who handles your requests to the app",notes:[{title:"Who handles your requests",body:"The privacy notice of 18 November names who now carries every request to the app and keeps its log, still for 30 days. Nothing changes in how you use the app, and you stay signed in."}]};var NU={version:"1.6.0",date:"2026-11-18",headline:"Inspect shows where on its aero map each car runs, weighted by the air it meets",notes:[{title:"Aero map with the lap on it",body:"Inspect \u2192 Aero platform opens with each car\u2019s aero map and its lap drawn on it. Lines hold the densest half and 90 % of the lap\u2019s dynamic pressure \xD7 time, so the slow corners count for little. Hover a point to see it on the track."},{title:"Three numbers per car",body:"Under the map: the CL the lap actually got, how far the aero balance moved (10th to 90th percentile) and how much of the lap ran outside the model\u2019s data. Pick a stretch and they read that stretch."},{title:"Aero balance bands",body:"A second card shows how the front share of the downforce is spread over the lap, weighted the same way, every car on the same bands."}]};var OU={version:"1.6.1",date:"2026-11-18",headline:"The 3-D view keeps its proportions when it leaves Orthographic",notes:[{title:"No stretched car after Orthographic",body:"If the 3-D view changed size while Orthographic was on, for example because the side panels were hidden, turning Orthographic off drew the car stretched sideways until the next resize. It now draws at the view\u2019s size straight away."}]};var zU={version:"1.7.0",date:"2026-11-18",headline:"The aero map in Inspect reads the grip-limited and the power-limited part of a lap apart",notes:[{title:"Grip or power",body:"Inspect\u2019s aero cards can show only the samples where the tyres were the limit, where downforce is speed, or only those where the powertrain was, where the drag is what counts. The map, the numbers and the balance bands follow."},{title:"Drag and the split",body:"Under the map each car now shows its CD, weighted the same way as its CL, and how its lap\u2019s dynamic pressure \xD7 time splits between grip-limited and power-limited."}]};var VU={version:"1.8.0",date:"2026-11-18",headline:"Work on a phone or tablet, and drive with touch controls",notes:[{title:"The workspace fits your screen",body:"A centered logo and compact project menu leave more room in the one-row header. Secondary actions live in More; Laptime\u2019s comparison controls expand from a summary. Charts and dialogs fit the screen."},{title:"Results stay within reach",body:"Tool tabs stay in one scrolling row. Dynamics folds tyre charts below narrow 3-D views, leaving the car full width. Replay stacks its picture, channels and telemetry, with playback controls kept visible."},{title:"Drive with your thumbs",body:"Touchscreens get steering, brake and throttle buttons: hold steering and a pedal together. Cancelling a touch or switching away releases the controls. On phones the Session panel follows the driving scene."}]};var Eme={"./releases/1.0.0.ts":SU,"./releases/1.0.2.ts":kU,"./releases/1.0.3.ts":RU,"./releases/1.10.2.ts":xU,"./releases/1.10.3.ts":wU,"./releases/1.11.0.ts":MU,"./releases/1.12.0.ts":_U,"./releases/1.13.0.ts":AU,"./releases/1.2.0.ts":CU,"./releases/1.3.0.ts":TU,"./releases/1.4.1.ts":PU,"./releases/1.4.2.ts":FU,"./releases/1.5.0.ts":$U,"./releases/1.5.2.ts":IU,"./releases/1.5.3.ts":EU,"./releases/1.5.4.ts":LU,"./releases/1.5.5.ts":DU,"./releases/1.6.0.ts":NU,"./releases/1.6.1.ts":OU,"./releases/1.7.0.ts":zU,"./releases/1.8.0.ts":VU};var Lme=Object.values(Eme).sort((e,t)=>Dme(t.version,e.version)),jo=Lme[0];function Dme(e,t){let r=e.split(".").map(Number),o=t.split(".").map(Number);for(let n=0;n<Math.max(r.length,o.length);n++){let a=(r[n]??0)-(o[n]??0);if(a!==0)return a<0?-1:1}return 0}import{createHash as Nme,randomBytes as ZI}from"node:crypto";import{createServer as Ome}from"node:http";import{spawn as zme}from"node:child_process";import{chmod as Vme,mkdir as jme,readFile as Bme,rename as Ume,rm as BU,writeFile as Gme}from"node:fs/promises";import{homedir as qme}from"node:os";import{join as Vh}from"node:path";async function jU(e,t={}){let r=e.replace(/\/+$/,""),o=t.fetchImpl??fetch,n=[`${r}/.well-known/oauth-authorization-server/auth/v1`,`${r}/auth/v1/.well-known/oauth-authorization-server`],a=[];for(let i of n){let s=new AbortController,c=setTimeout(()=>s.abort(),t.timeoutMs??8e3);try{let l=await o(i,{signal:s.signal,headers:{accept:"application/json"}});if(!l.ok){a.push(`${i} \u2192 ${l.status}`);continue}let u=await l.json();if(!u?.issuer||!u.authorization_endpoint||!u.token_endpoint){a.push(`${i} \u2192 a document with no issuer or endpoints`);continue}return u}catch(l){a.push(`${i} \u2192 ${l instanceof Error?l.message:String(l)}`)}finally{clearTimeout(c)}}throw new Error(`the account service published no authorization-server metadata (${a.join("; ")}). Enable the OAuth server on the project \u2014 docs/hosting.md has the runbook.`)}var Hme="openid email profile offline_access",Kme=24*3600*1e3,UU=168*3600*1e3,Wme=600*1e3,Bo=class extends Error{};function GU(e=process.env,t=process.platform,r=qme()){return e.PACEDYN_CONFIG_DIR?e.PACEDYN_CONFIG_DIR:t==="win32"?Vh(e.APPDATA||Vh(r,"AppData","Roaming"),"PaceDynamics"):Vh(e.XDG_CONFIG_HOME||Vh(r,".config"),"pacedyn")}var XI=e=>e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function Yme(e){let t=e.split(".")[1];if(!t)return{};try{return JSON.parse(Buffer.from(t.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"))}catch{return{}}}function Zme(e){let[t,r]=process.platform==="darwin"?["open",[e]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{let o=zme(t,r,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}var ex=class{cfg;file;doFetch;now;metadata=null;checking=null;pending=null;constructor(t){this.cfg=t,this.file=Vh(t.dir,"credentials.json"),this.doFetch=t.fetchImpl??fetch,this.now=t.now??Date.now}get redirectUri(){return`http://localhost:${this.cfg.port}/callback`}async stored(){let t;try{t=await Bme(this.file,"utf8")}catch{return null}try{let r=JSON.parse(t);return r.accountUrl!==this.cfg.url||r.clientId!==this.cfg.clientId||!r.refreshToken?null:r}catch{return null}}async save(t){await jme(this.cfg.dir,{recursive:!0,mode:448});let r=`${this.file}.${ZI(4).toString("hex")}.tmp`;await Gme(r,JSON.stringify(t,null,2),{mode:384}),await Vme(r,384),await Ume(r,this.file)}async signOut(){let t=await this.stored()!==null;return await BU(this.file,{force:!0}),t}async server(){return this.metadata||(this.metadata=await jU(this.cfg.url,{fetchImpl:this.doFetch})),this.metadata}credentialsFrom(t,r){if(!t.access_token||!t.refresh_token)throw new Error("the account service answered without tokens");let o=Yme(t.access_token),n=typeof o.exp=="number"?o.exp*1e3:this.now()+1e3*(t.expires_in??3600);return{accountUrl:this.cfg.url,clientId:this.cfg.clientId,accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:n,verifiedAt:this.now(),user:{id:typeof o.sub=="string"?o.sub:r?.user.id??"",email:typeof o.email=="string"?o.email:r?.user.email??null}}}async token(t){let r=await this.server(),o=await this.doFetch(r.token_endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams({...t,client_id:this.cfg.clientId}).toString(),signal:AbortSignal.timeout(15e3)}),n=await o.text(),a={};try{a=n?JSON.parse(n):{}}catch{a={error:`HTTP ${o.status}`}}return{status:o.status,reply:a}}async ensure(){return this.checking??=this.check().finally(()=>{this.checking=null}),this.checking}async check(){let t=await this.stored();if(!t)throw new Bo(jh());let r=this.now();if(r<t.expiresAt-6e4&&r-t.verifiedAt<Kme)return t;let o;try{let n=await this.stored()??t;o=await this.token({grant_type:"refresh_token",refresh_token:n.refreshToken})}catch(n){if(r-t.verifiedAt<UU)return t;throw new Bo(`The account service has not been reachable for over a week (${n instanceof Error?n.message:String(n)}). Connect to the internet, then try again.`)}if(o.status>=200&&o.status<300&&o.reply.access_token){let n=this.credentialsFrom(o.reply,t);return await this.save(n),n}if(o.status===400||o.status===401||o.status===403){let n=await this.stored();if(n&&n.refreshToken!==t.refreshToken&&n.verifiedAt>t.verifiedAt)return n;throw await BU(this.file,{force:!0}),new Bo(`Your PaceDynamics sign-in has ended (${o.reply.error_description??o.reply.error??`HTTP ${o.status}`}). ${jh()}`)}if(r-t.verifiedAt<UU)return t;throw new Bo(`The account service answered HTTP ${o.status} for over a week. ${jh()}`)}async signIn(t,r=Wme){if(this.pending)return t?.(this.pending.url),this.pending;let o=await this.server(),n=XI(ZI(32)),a=XI(Nme("sha256").update(n).digest()),i=XI(ZI(16)),s=new URL(o.authorization_endpoint);s.search=new URLSearchParams({response_type:"code",client_id:this.cfg.clientId,redirect_uri:this.redirectUri,scope:Hme,state:i,code_challenge:a,code_challenge_method:"S256"}).toString();let c,l,u=new Promise((y,v)=>{c=y,l=v}),m=[],p=()=>{for(let y of m)y.close();clearTimeout(d),this.pending=null},d=setTimeout(()=>{p(),l(new Bo("The sign-in was not finished in the browser in time. Try again."))},r);d.unref();let f=(y,v)=>{let k=new URL(y.url??"/",this.redirectUri);if(k.pathname!=="/callback"){v.writeHead(404).end();return}let x=(w,M,T)=>{v.writeHead(w,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),v.end(`<!doctype html><meta charset="utf-8"><title>${M}</title><body style="font:16px system-ui,sans-serif;max-width:32em;margin:15vh auto;padding:0 16px"><h1 style="font-size:20px">${M}</h1><p>${T}</p></body>`)};if(k.searchParams.get("state")!==i){x(400,"This sign-in link is not the one this machine started","Start the sign-in again from your assistant or terminal.");return}let S=k.searchParams.get("error"),R=k.searchParams.get("code");if(S||!R){x(400,"Not signed in",S==="access_denied"?"You declined. Nothing was shared.":"The account service did not send a code."),p(),l(new Bo(S==="access_denied"?"The sign-in was declined in the browser.":`The sign-in failed: ${k.searchParams.get("error_description")??S??"no code"}`));return}this.token({grant_type:"authorization_code",code:R,redirect_uri:this.redirectUri,code_verifier:n}).then(async({status:w,reply:M})=>{if(w<200||w>=300)throw new Error(M.error_description??M.error??`HTTP ${w}`);let T=this.credentialsFrom(M);await this.save(T),x(200,"Signed in to PaceDynamics",`As ${T.user.email??"your account"}. You can close this tab and go back to your assistant.`),p(),c(T)}).catch(w=>{x(500,"Not signed in","The account service did not accept the sign-in. Try again."),p(),l(new Bo(`The sign-in failed: ${w instanceof Error?w.message:String(w)}`))})},h=y=>new Promise(v=>{let k=Ome(f);k.once("error",()=>v(!1)),k.listen(this.cfg.port,y,()=>{m.push(k),v(!0)})}),[g,b]=await Promise.all([h("127.0.0.1"),h("::1")]);if(!g&&!b)throw clearTimeout(d),new Error(`port ${this.cfg.port} on this machine is in use, so the sign-in has nowhere to return to. Close what holds it (another sign-in?) and try again.`);return this.pending={url:s.toString(),done:u},t?.(s.toString()),(this.cfg.openBrowser??Zme)(s.toString()),this.pending}};function jh(e=ro()){return`Sign in to PaceDynamics first: call the account_sign_in tool (it opens your browser), or run \`npx -y ${e} login\` in a terminal.`}function ro(){return"@pacedyn/mcp"}import{randomBytes as Nde}from"node:crypto";import{readdir as Ode,rename as zde,rm as Vde,stat as cE,readFile as SG,writeFile as jde}from"node:fs/promises";import{homedir as Bde}from"node:os";import{basename as lE,dirname as cx,isAbsolute as Ude,join as uE,resolve as kG}from"node:path";var En=(e,t,r)=>{let o=Math.min(t+r,e.length),n=o;for(let i=t;i<o;i++)if(e[i]===0){n=i;break}let a="";for(let i=t;i<n;i++)a+=String.fromCharCode(e[i]);return a.trim()};function JI(e){let t=e.byteLength;if(t<352)throw new Error(`not a MoTeC .ld file: ${t} bytes is shorter than its header`);let r=new DataView(e),o=new Uint8Array(e),n=[],a=r.getUint32(8,!0);if(a===0||a+124>t)throw new Error(`not a MoTeC .ld file: channel list at ${a} is outside a ${t}-byte file`);let i=[],s=new Set,c=a;for(;c!==0;){if(s.has(c)){n.push(`channel list loops back to offset ${c}; stopped there`);break}if(c+124>t){n.push(`channel descriptor at ${c} runs past the end of the file; stopped there`);break}if(s.size>=4096){n.push("stopped after 4096 channels; the list did not end");break}s.add(c);let u=r.getUint32(c+8,!0),m=r.getUint32(c+12,!0),p=r.getUint16(c+18,!0),d=r.getUint16(c+20,!0),f=r.getUint16(c+22,!0),h={family:p,width:d,shift:r.getInt16(c+24,!0),mul:r.getInt16(c+26,!0),scale:r.getInt16(c+28,!0),decimalPlaces:r.getInt16(c+30,!0)},g=En(o,c+32,32),b=r.getUint32(c+4,!0),y=Qme(r,p,d);if(!y)n.push(`channel "${g}": unknown storage (family ${p}, ${d} bytes); skipped`);else if(u+m*d>t)n.push(`channel "${g}": ${m} samples at ${u} run past the end of the file; skipped`);else{let v=new Float64Array(m),k=h.scale===0?1:h.scale,x=(h.mul===0?1:h.mul)/k*10**-h.decimalPlaces,S=p===7&&x===1&&h.shift===0;for(let R=0;R<m;R++){let w=y(u+R*d);v[R]=S?w:w*x+h.shift}i.push({name:g,shortName:En(o,c+64,8),unit:En(o,c+72,12),logRate:f,data:v,storage:h})}c=b}i.length===0&&n.push("the file holds no readable channel");let l=Jme(o,r,a);return{device:En(o,74,8),serial:r.getUint32(66,!0),date:En(o,94,16),time:En(o,126,16),driver:En(o,158,64),vehicle:En(o,222,64),venue:En(o,350,64),channels:i,warnings:n,...l.length?{comments:l}:{}}}var qU=1572,tx=128,Xme=e=>e.length>0&&/^[\x20-\x7e\u00a0-\u00ff\t\r\n]*$/.test(e);function Jme(e,t,r){let o=t.getUint32(12,!0),n=Math.min(r,o||r,e.length),a=[];qU+64<=n&&a.push(En(e,qU,64));let i=t.getUint32(36,!0);return i>=352&&i+tx<=n&&(a.push(En(e,i,64),En(e,i+64,64)),i+tx<n&&a.push(En(e,i+tx,Math.min(1024,n-i-tx)))),a.filter(Xme)}function Qme(e,t,r){return t===7?r===4?o=>e.getFloat32(o,!0):r===2?o=>ede(e.getUint16(o,!0)):r===8?o=>e.getFloat64(o,!0):null:t===0||t===3?r===2?o=>e.getInt16(o,!0):r===4?o=>e.getInt32(o,!0):r===1?o=>e.getInt8(o):null:null}function ede(e){let t=e&32768?-1:1,r=e>>10&31,o=e&1023;return r===0?t*o*2**-24:r===31?o?NaN:t*(1/0):t*(o+1024)*2**(r-25)}var KU={family:7,width:8,shift:0,mul:1,scale:1,decimalPlaces:0},tde={venue:"venue",track:"venue",circuit:"venue",vehicle:"vehicle",car:"vehicle",driver:"driver",racer:"driver",user:"driver",device:"device","data source":"device",logger:"device",date:"date","log date":"date",time:"time","log time":"time","sample rate":"rate","sampling rate":"rate"};function WU(e){let t=Math.min(e.length,4096);if(t===0)return!1;let r=0;for(let o=0;o<t;o++){let n=e[o];if(n===9||n===10||n===13||n>=32&&n<127||n>=160)r++;else if(n===0)return!1}return r/t>.95}function YU(e,t={}){let r=[],n=(e.charCodeAt(0)===65279?e.slice(1):e).split(/\r\n|\n|\r/),a=t.delimiter??rde(n),i=a!==",",s={},c=-1,l=[];for(let R=0;R<n.length&&c<0&&R<400;R++){let w=rx(n[R],a);if(!(w.length===0||w.length===1&&w[0]==="")){if(ade(w,n,R,a,i)){c=R,l=[w];break}for(let M=0;M+1<w.length;M+=1){let T=tde[w[M].trim().toLowerCase()];T&&w[M+1].trim()&&s[T]===void 0&&(s[T]=w[M+1].trim())}}}if(c<0)throw new Error("no row of channel names followed by numbers was found \u2014 is this a logger export?");let u=l[0].map(R=>R.trim());if(u.length>2048)throw new Error(`${u.length} columns is more than this reader takes (2048)`);let m=c+1,p=u.map(()=>""),d=ode(n,m);if(d>=0){let R=rx(n[d],a);R.filter(M=>Bh(M,i)!==null).length<R.length/2&&(p=u.map((M,T)=>(R[T]??"").trim()),m=d+1)}let f=u.map((R,w)=>{let M=/^(.*?)\s*[[(]\s*([^\])]*)\s*[\])]\s*$/.exec(R);return M&&M[1]&&!p[w]?(p[w]=M[2],M[1].trim()):R}),h=f.length,g=f.map(()=>[]),b=new Array(h).fill(NaN),y=0,v=0;for(let R=m;R<n.length;R++){let w=n[R];if(!w||!w.trim())continue;let M=rx(w,a);if(Bh(M[0]??"",i)===null){if(y++,y>5)break;continue}for(let A=0;A<h;A++){let _=Bh(M[A]??"",i);_!==null&&(b[A]=_),g[A].push(b[A])}if(v+=h,v>8e7){r.push(`stopped after ${g[0].length} rows: the table is larger than one import takes`);break}}if((g[0]?.length??0)<2)throw new Error("the table has a header but fewer than two rows of numbers");y>0&&r.push(`${y} row${y===1?"":"s"} after the header did not start with a number and were skipped`);let x=f.findIndex((R,w)=>HU(R)&&w===0)>=0?0:f.findIndex(R=>HU(R)),S=s.rate?Number.parseFloat(s.rate.replace(",",".")):NaN;return Uh({names:f,units:p,values:g,timeCol:x,statedRate:S},{device:s.device??"",date:s.date??"",time:s.time??"",driver:s.driver??"",vehicle:s.vehicle??"",venue:s.venue??""},r)}function Uh(e,t,r=[]){let{names:o,units:n,values:a,timeCol:i}=e,s,c=a;if(i>=0){let m=a[i].map(h=>h*nde(n[i])),p=[];for(let h=1;h<m.length;h++){let g=m[h]-m[h-1];Number.isFinite(g)&&g>0&&p.push(g)}if(p.length<1)throw new Error("the time column never advances");p.sort((h,g)=>h-g);let d=p[Math.floor(p.length/2)];s=QI(1/d);let f=p.filter(h=>Math.abs(h-d)>.25*d).length;(f>p.length*.02||m.length!==p.length+1)&&(c=ide(a,m,s),r.push(`the time column is not evenly spaced (${f} of ${p.length} steps off ${(d*1e3).toFixed(1)} ms); resampled to ${s} Hz by holding each row until the next`))}else{let m=e.statedRate??NaN;if(!(m>0))throw new Error("the table has no time column and states no sample rate");s=QI(m),r.push(`no time column; the stated ${s} Hz is taken as the clock`)}let l=[],u=new Set;return o.forEach((m,p)=>{if(p===i||!m)return;let d=m;for(let h=2;u.has(d.toLowerCase());h++)d=`${m} ${h}`;u.add(d.toLowerCase());let f=Float64Array.from(c[p]);XU(f)&&l.push({name:d,shortName:"",unit:n[p]??"",logRate:s,data:f,storage:KU})}),l.length===0&&r.push("the file holds no readable channel"),{...t,serial:0,channels:l,warnings:r}}function ZU(e,t,r,o,n){let a=[];for(let u=1;u<r.length;u++){let m=r[u]-r[u-1];Number.isFinite(m)&&m>0&&a.push(m)}if(!a.length)return null;a.sort((u,m)=>u-m);let i=QI(1/a[Math.floor(a.length/2)]),s=Math.max(2,Math.floor((r[r.length-1]-n)*i)+1),c=new Float64Array(s).fill(NaN),l=-1;for(let u=0;u<s;u++){let m=n+u/i;for(;l+1<r.length&&r[l+1]<=m+1e-9;)l++;l>=0&&(c[u]=o[l])}return XU(c)?{name:e,shortName:"",unit:t,logRate:i,data:c,storage:KU}:null}function XU(e){let t=-1;for(let r=0;r<e.length;r++)if(Number.isFinite(e[r])){t=r;break}if(t<0)return!1;for(let r=0;r<t;r++)e[r]=e[t];return!0}function rde(e){let t=e.filter(r=>r.trim()).slice(0,60);for(let r of[" ",";"])if(t.filter(n=>n.includes(r)).length>=Math.max(2,t.length*.5))return r;return","}function rx(e,t){let r=[],o="",n=!1;for(let a=0;a<e.length;a++){let i=e[a];n?i==='"'?e[a+1]==='"'?(o+='"',a++):n=!1:o+=i:i==='"'?n=!0:i===t?(r.push(o),o=""):o+=i}return r.push(o),r}function Bh(e,t){let r=e.trim();if(!r)return null;t&&r.includes(",")&&!r.includes(".")&&(r=r.replace(",","."));let o=Number(r);if(Number.isNaN(o))return/^[+-]?nan$/i.test(r)?NaN:null;if(!Number.isFinite(o))return NaN;let n=r.charCodeAt(r[0]==="-"||r[0]==="+"?1:0);return!(n>=48&&n<=57||n===46)||r.length>1&&/^[+-]?0[xXbBoO]/.test(r)?null:o}function HU(e){return/^(time|timestamp|t|elapsed time|session time|sim time|time_s|times)$/i.test(e.trim())}function nde(e){let t=e.trim().toLowerCase();return t==="ms"?.001:t==="us"||t==="\xB5s"?1e-6:t==="min"?60:1}function QI(e){return e>=5?Math.round(e):Math.round(e*100)/100}function ode(e,t){for(let r=t;r<e.length&&r<t+5;r++)if(e[r]&&e[r].trim())return r;return-1}function ade(e,t,r,o,n){if(e.length<2||e.filter(s=>s.trim()&&Bh(s,n)===null).length<Math.max(2,e.length*.6))return!1;let i=0;for(let s=r+1;s<t.length&&i<3;s++){if(!t[s]||!t[s].trim())continue;i++;let c=rx(t[s],o),l=c.filter(m=>Bh(m,n)!==null).length,u=Math.abs(c.length-e.length)<=Math.max(1,.2*e.length);if(l>=Math.max(2,e.length*.6)&&u)return!0}return!1}function ide(e,t,r){let o=t.find(Number.isFinite)??0,n=t[t.length-1],a=Math.max(2,Math.floor((n-o)*r)+1),i=e.map(()=>new Array(a)),s=0;for(let c=0;c<a;c++){let l=o+c/r;for(;s+1<t.length&&t[s+1]<=l+1e-9;)s++;for(let u=0;u<e.length;u++)i[u][c]=e[u][s]}return i}var JU={kmh:"km/h",mph:"mph",knots:"kn","m/s":"m/s",g:"g",m:"m",feet:"ft",ft:"ft","deg/s":"deg/s"},QU={satellites:"",time:"s",latitude:"deg",longitude:"deg",heading:"deg",height:"m","yaw rate":"deg/s",gps_sats:"",glonass_sats:"","solution type":"","dgps status":"",avifileindex:"",avisynctime:"",avitime:""};function sde(e){let t=e.trim().toLowerCase();if(t in QU)return{name:t,unit:QU[t]};let r=/^(.*\S)\s+(\S+)$/.exec(t);return r&&r[2]in JU&&/^(velocity|vertical velocity|lat accel|long accel|distance|[xy] position|velocity quality|vertical velocity quality)/.test(r[1])?{name:r[1],unit:JU[r[2]]}:null}function cde(e){let t=new Map,r=[],o=r;for(let a of e){let i=/^\s*\[([^\]]+)\]\s*$/.exec(a);i?(o=[],t.set(i[1].trim().toLowerCase(),o)):o.push(a)}let n=a=>{for(;a.length&&!a[0].trim();)a.shift();for(;a.length&&!a[a.length-1].trim();)a.pop()};n(r);for(let a of t.values())n(a);return{preamble:r,sections:t}}var lde=e=>{let t=Math.floor(e/1e4),r=Math.floor(e/100)%100;return t*3600+r*60+(e-Math.floor(e/100)*100)};function eG(e){let t=[],r=e.charCodeAt(0)===65279?e.slice(1):e,{preamble:o,sections:n}=cde(r.split(/\r\n|\n|\r/)),a=n.get("data");if(!a?.length)throw new Error("the .vbo has no [data] section");let i=(n.get("header")??[]).map(R=>R.trim()).filter(Boolean),s=(n.get("column names")??[]).join(" ").trim().split(/\s+/).filter(Boolean),c=s.length||i.length;if(!c)throw new Error("the .vbo names none of its columns ([header] and [column names] are empty)");s.length&&i.length&&s.length!==i.length&&t.push(`[header] lists ${i.length} channels and [column names] ${s.length}; the short names are used`);let l=i.length===c?i:s,u=(n.get("channel units")??[]).map(R=>R.trim()),m=0,p=[],d=[];for(let R of l){let w=sde(R);w?(p.push(w.name),d.push(w.unit)):(p.push(R.trim()),d.push(u[m++]??""))}u.length&&m!==u.length&&t.push(`[channel units] holds ${u.length} units for ${m} channels; check the units on the Channels step`);let f=p.map(()=>[]),h=0;for(let R of a){if(!R.trim())continue;let w=R.trim().split(/\s+/);if(w.length<c){h++;continue}for(let M=0;M<c;M++){let T=Number(w[M]);f[M].push(Number.isFinite(T)?T:NaN)}}if(f[0].length<2)throw new Error("the .vbo has fewer than two rows of samples");h&&t.push(`${h} row${h===1?"":"s"} in [data] had fewer than ${c} values and were skipped`);let g=p.indexOf("time");if(g>=0){let R=f[g],w=0,M=-1/0;for(let T=0;T<R.length;T++){let A=lde(R[T])+w;A<M-43200&&(w+=86400,A+=86400),R[T]=A,M=A}}let b=p.indexOf("latitude"),y=p.indexOf("longitude");b>=0&&(f[b]=f[b].map(R=>R/60)),y>=0&&(f[y]=f[y].map(R=>-R/60));let v=o.map(R=>/created on\s+(\S+)\s+(?:@|at)\s+(\S+)/i.exec(R)).find(Boolean),x=(n.get("comments")??[]).find(R=>/vbox|racelogic|racechrono|racebox|performancebox|video ?vbox/i.test(R))?.trim(),S=(n.get("circuit details")??[]).map(R=>/^\s*circuit\s+(.+)$/i.exec(R)).find(Boolean);return Uh({names:p,units:d,values:f,timeCol:g},{device:x||"Racelogic VBO",date:v?.[1]??"",time:v?.[2]??"",driver:"",vehicle:"",venue:S?.[1].trim()??""},t)}var tG={1:"a cell array",2:"a struct",3:"an object",5:"a sparse array"};function mi(e,t,r){if(t<0||t+8>e.byteLength)throw new Error("truncated MAT element tag");let o=e.getUint32(t,r);if(o>>>16!==0){let s=e.getUint16(t,r),c=e.getUint16(t+2,r);if(c>4)throw new Error("invalid MAT small-element length");return{type:s,start:t+4,length:c,next:t+8}}let a=e.getUint32(t+4,r);if(t+8+a>e.byteLength)throw new Error("truncated MAT element payload");let i=o===15||!(a&7)?0:8-(a&7);return{type:o,start:t+8,length:a,next:t+8+a+i}}function nx(e,t,r){let{start:o,length:n}=t,a=(i,s,c)=>{let l=new Float64Array(i);for(let u=0;u<i;u++)l[u]=c(o+u*s);return l};switch(t.type){case 9:return a(n>>3,8,i=>e.getFloat64(i,r));case 7:return a(n>>2,4,i=>e.getFloat32(i,r));case 1:return a(n,1,i=>e.getInt8(i));case 2:return a(n,1,i=>e.getUint8(i));case 3:return a(n>>1,2,i=>e.getInt16(i,r));case 4:return a(n>>1,2,i=>e.getUint16(i,r));case 5:return a(n>>2,4,i=>e.getInt32(i,r));case 6:return a(n>>2,4,i=>e.getUint32(i,r));case 12:return a(n>>3,8,i=>Number(e.getBigInt64(i,r)));case 13:return a(n>>3,8,i=>Number(e.getBigUint64(i,r)));default:throw new Error(`unsupported numeric element type ${t.type}`)}}function eE(e,t,r){if(t.type===16){let i=new Uint8Array(e.buffer,e.byteOffset+t.start,t.length);return new TextDecoder().decode(i)}let o=nx(e,t,r),n="",a=4096;for(let i=0;i<o.length;i+=a)n+=String.fromCharCode(...o.subarray(i,i+a));return n}async function ude(e){if(typeof DecompressionStream>"u")throw new Error("this file is compressed and no DecompressionStream is available to read it");let t=new DecompressionStream("deflate"),r=new Blob([e]).stream().pipeThrough(t),o=[],n=0;for await(let s of r)o.push(s),n+=s.length;let a=new Uint8Array(n),i=0;for(let s of o)a.set(s,i),i+=s.length;return a}function rG(e,t,r,o=!1,n=0,a={nodes:0}){if(n>32||++a.nodes>1e5)throw new Error("MAT nesting exceeds reader limits");let i=t.start,s=t.start+t.length,c=mi(e,i,r),l=e.getUint32(c.start,r),u=l&255,m=(l&2048)!==0;i=c.next;let p=mi(e,i,r),d=Array.from(nx(e,p,r),v=>v|0);if(d.some(v=>v<0))throw new Error("invalid MAT dimensions");i=p.next;let f=mi(e,i,r),h=eE(e,f,r);if(i=f.next,o&&(u===1||u===2||u===3)){let v;if(u===3){let w=mi(e,i,r);v=eE(e,w,r),i=w.next}let k=d.reduce((w,M)=>w*M,1),x=[];if(u!==1){let w=mi(e,i,r),M=nx(e,w,r)[0];i=w.next;let T=mi(e,i,r);if(i=T.next,!(M>0)||!Number.isInteger(M)||T.length%M)throw new Error("invalid MAT struct field table");for(let A=T.start;A<T.start+T.length;A+=M)x.push(new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset+A,M)).replace(/\0.*$/,""))}if(k*Math.max(1,x.length)>1e5-a.nodes)throw new Error("MAT container exceeds reader limits");let S=()=>{if(i+8>s)throw new Error("truncated MAT container");let w=mi(e,i,r);if(w.type!==14||w.start+w.length>s)throw new Error("invalid MAT container entry");i=w.next;let M=rG(e,w,r,!0,n+1,a);return M.value??{kind:"unsupported",why:M.skip??"unrecognised value"}};if(u===1){let w=Array.from({length:k},S);return{name:h,value:{kind:"cell",dims:d,entries:w}}}let R=Array.from({length:k},()=>{let w=new Map;for(let M of x)w.set(M,S());return w});return{name:h,value:{kind:"struct",dims:d,entries:R,...v?{className:v}:{}}}}if(u in tG)return{name:h,skip:tG[u]};if(u>15)return{name:h,skip:`unsupported MATLAB class ${u}`};if(i>=s)return{name:h,skip:"an array with no payload"};let g=mi(e,i,r);if(g.start+g.length>s)throw new Error("truncated MAT matrix");if(u===4){let v=eE(e,g,r);return{name:h,text:v,value:{kind:"text",text:v,dims:d}}}let b=nx(e,g,r);if(m)return{name:h,skip:"a complex array"};if(b.length!==d.reduce((v,k)=>v*k,1))throw new Error(`MAT array ${h} does not match its dimensions`);let y={name:h,dims:d,data:b};return{name:h,array:y,value:{kind:"numeric",array:y}}}async function ox(e,t={}){if(e.byteLength<128)throw new Error("not a MAT-file: shorter than its own header");let r=new DataView(e),o=new TextDecoder().decode(new Uint8Array(e,0,116)).replace(/\0+$/,"").trim(),n=r.getUint16(126,!0);if(n!==19785&&n!==18765)throw new Error("not a MATLAB Level 5 MAT-file (no endian indicator where one belongs)");let a=n===19785,i=new Map,s=new Map,c=[],l=t.nested?new Map:void 0,u=(p,d,f,h)=>{let g=d;for(;g+8<=f;){let b=mi(p,g,a);if(b.next>f||b.length<0)break;if(b.type===15){let y=new Uint8Array(p.buffer,p.byteOffset+b.start,b.length);h.push(ude(y).then(v=>{let k=new DataView(v.buffer,v.byteOffset,v.byteLength);u(k,0,v.byteLength,h)}))}else if(b.type===14){let y=rG(p,b,a,t.nested);l&&l.set(y.name,y.value??{kind:"unsupported",why:y.skip??"unrecognised value"}),y.skip?c.push({name:y.name,why:y.skip}):y.array?i.set(y.name,y.array):y.text!==void 0&&s.set(y.name,y.text)}g=b.next}},m=[];for(u(r,128,e.byteLength,m);m.length;)await m.shift();if(!i.size&&!s.size&&!c.length&&!l?.size)throw new Error("MAT-file contains no variables this reader recognises");return{header:o,numeric:i,text:s,skipped:c,...l?{variables:l}:{}}}var tE=/^(time|t|times|timestamp|time_s|sessiontime|session_time|elapsed_time)$/i,mde=/^(value|values|data|y|signal|samples)$/i,dde=/^(units?|unit_name)$/i,pde=/^(name|channel|channelname|channel_name)$/i,fde=/^(fs|rate|samplerate|sample_rate|samplingrate|frequency)$/i;function hde(e){let[t,r]=e.dims;return e.dims.length!==2||Math.min(t,r)!==1||Math.max(t,r)<2?null:e.data}var ax=e=>e?.kind==="numeric"?hde(e.array):null,Ms=e=>e?.kind==="text"?e.text.trim():void 0,gde=e=>e?.kind==="numeric"&&e.array.data.length===1?e.array.data[0]:void 0,Uo=(e,t)=>[...e].find(([r])=>t.test(r));function nG(e,t){if(t.kind!=="struct")return[];let r=[];return t.entries.forEach((o,n)=>{let a=ax(Uo(o,tE)?.[1]),i=ax(Uo(o,mde)?.[1]);!a||!i||a.length!==i.length||r.push({name:Ms(Uo(o,pde)?.[1])||(t.entries.length>1?`${e}(${n+1})`:e),unit:Ms(Uo(o,dde)?.[1])??"",t:a,v:i})}),r}async function oG(e){let t=await ox(e,{nested:!0}),r=t.variables??new Map,o=[],n=[...r],a=n.filter(([,g])=>ax(g)),i=n.filter(([,g])=>g.kind==="struct"&&g.entries.length===1&&!nG("",g).length);if(!a.length&&i.length===1&&n.every(([,g])=>g.kind!=="struct"||g===i[0][1])){let g=i[0][1].entries[0];r=new Map([...n.filter(([,b])=>b!==i[0][1]),...g])}let s={device:Ms(Uo(r,/^(device|logger|source)$/i)?.[1])||"MATLAB",date:Ms(Uo(r,/^(date|logdate|log_date)$/i)?.[1])??"",time:Ms(Uo(r,/^(time_of_day|logtime|log_time)$/i)?.[1])??"",driver:Ms(Uo(r,/^(driver|racer)$/i)?.[1])??"",vehicle:Ms(Uo(r,/^(vehicle|car)$/i)?.[1])??"",venue:Ms(Uo(r,/^(venue|track|circuit)$/i)?.[1])??""};for(let g of t.skipped)o.push(`${g.name||"a variable"} was not read: ${g.why}`);let c=[...r].flatMap(([g,b])=>nG(g,b));if(c.length){let g=Math.min(...c.map(v=>v.t[0]).filter(Number.isFinite)),b=[],y=new Set;for(let v of c){let k=v.name;for(let S=2;y.has(k.toLowerCase());S++)k=`${v.name} ${S}`;let x=ZU(k,v.unit,v.t,v.v,g);if(!x){o.push(`${v.name}: its time never advances, so it was left out`);continue}y.add(k.toLowerCase()),b.push(x)}return{...s,serial:0,channels:b,warnings:o}}let l=[...r].map(([g,b])=>({name:g,data:ax(b)})).filter(g=>g.data),u=new Map;for(let g of l)u.set(g.data.length,[...u.get(g.data.length)??[],g]);let m=[...u.values()].filter(g=>g.some(b=>tE.test(b.name))),p=gde(Uo(r,fde)?.[1]),d=m.sort((g,b)=>b.length-g.length)[0]??(p?[...u.values()].sort((g,b)=>b.length-g.length)[0]:void 0);if(!d||d.length<(m.length?2:1)){let g=[...r.keys()].slice(0,6).join(", ");throw new Error(`the MATLAB file holds no channels with a clock: neither one struct per channel with a time and a value, nor columns beside a time vector (it holds ${g||"nothing readable"})`)}let f=l.length-d.length;f&&o.push(`${f} vector${f===1?"":"s"} of another length than the clock were left out`);let h=d.map(g=>g.name);return Uh({names:h,units:h.map(()=>""),values:d.map(g=>Array.from(g.data)),timeCol:h.findIndex(g=>tE.test(g)),statedRate:p},s,o)}function aG(e){return/^MATLAB 7\.3 MAT-file/.test(String.fromCharCode(...e.subarray(0,24)))}var bde=e=>e.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi,(t,r)=>{let o=r.toLowerCase();return o.startsWith("#x")?String.fromCodePoint(Number.parseInt(o.slice(2),16)):o.startsWith("#")?String.fromCodePoint(Number.parseInt(o.slice(1),10)):{amp:"&",lt:"<",gt:">",quot:'"',apos:"'"}[o]??""});function iG(e){let t={};for(let r of e.matchAll(/([A-Za-z_][\w.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g))t[r[1]]=bde(r[2]??r[3]??"");return t}function sG(e){let t=[];for(let n of e.matchAll(/<Marker\b([^>]*)>/g)){let a=iG(n[1]);if(a.ClassName!==void 0&&a.ClassName.toUpperCase()!=="BCN")continue;let i=Number(a.Time);Number.isFinite(i)&&i>=0&&t.push(i)}t.sort((n,a)=>n-a);let r={},o=/<Details\b[^>]*>([\s\S]*?)<\/Details>/i.exec(e)?.[1]??"";for(let n of o.matchAll(/<(String|Numeric)\b([^>]*)>/g)){let a=iG(n[2]);!a.Id||a.Value===void 0||(r[a.Id]=a.Unit?`${a.Value} ${a.Unit}`:a.Value)}return{beacons:t,details:r}}var yde=e=>Math.max(0,...e.channels.map(t=>t.data.length/(t.logRate||1)));function cG(e,t){if(Object.keys(t.details).length&&(e.details={...e.details,...t.details}),!t.beacons.length)return;let r=yde(e),o=t.beacons[t.beacons.length-1],n=[1,.001,1e-6].find(a=>o*a<=r+1);if(n===void 0){e.warnings.push(`the .ldx beacons run to ${o}, past the end of the log, and were left out`);return}e.beacons=t.beacons.map(a=>a*n)}var Gh=[".mf4",".mdf",".asc",".blf",".trc",".log",".dbc",".xrk",".drk",".xrz",".ibt"],vde=["ld","csv","vbo","mat"],uG=e=>vde.includes(e),lG=(e,t,r)=>String.fromCharCode(...e.subarray(t,Math.min(r,e.length))),Sde=e=>new TextDecoder("utf-8").decode(e.subarray(0,4096));function kde(e){return e.length<352?!1:new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!0)===64}function rE(e,t=""){let r=t.toLowerCase(),o=WU(e),n=lG(e,0,8);if(n.startsWith("PK")||n.startsWith("PK"))return"zip";if(n==="MDF "||n==="UnFinMF ")return"mdf";if(n.startsWith("LOGG"))return"can";if(/^MATLAB \d\.\d MAT-file/.test(lG(e,0,40)))return"mat";if(r.endsWith(".ld")||kde(e)&&!o)return"ld";if(o){let a=Sde(e),i=a.trimStart();return/<LDXFile[\s>]/i.test(a)?"ldx":/^\s*VERSION\s+"/m.test(a)&&/^\s*(BU_\s*:|BO_\s+\d+)/m.test(a)||/^\s*BO_\s+\d+\s+\w+\s*:/m.test(a)&&/^\s*SG_\s+\w+/m.test(a)?"dbc":/^\s*base\s+(hex|dec)\s+timestamps\s+(absolute|relative)/im.test(a)||/^\s*;\$FILEVERSION=/m.test(a)||/^\s*\(\d+\.\d+\)\s+\w+\s+[0-9A-Fa-f]{3,8}#/m.test(i)?"can":/^\[header\]\s*$/im.test(a)&&/^\[(column names|data)\]\s*$/im.test(a)||/^File created on /i.test(i)&&/^\[header\]/im.test(a)?"vbo":/^[<{]/.test(i)?"other":"csv"}return/\.(xrk|drk|xrz)$/i.test(r)?"xrk":/\.ibt$/i.test(r)?"ibt":/\.(mf4|mdf)$/i.test(r)?"mdf":/\.blf$/i.test(r)?"can":/\.zip$/i.test(r)?"zip":"other"}function nE(e){switch(e){case"mat":return"This is a MATLAB 7.3 file, which is not read here \u2014 save it again with save(\u2026, '-v7') or export the channels as CSV.";case"mdf":return"This is an ASAM MDF file (.mf4), which is not read here yet \u2014 export it as CSV from your logger\u2019s software or asammdf, decoding raw CAN with its DBC.";case"can":return"This is a raw CAN log, which is not read here yet \u2014 decode it with the bus\u2019s DBC to CSV first (your logger\u2019s software, cantools or asammdf).";case"dbc":return"This is a DBC, which describes a CAN bus but holds no samples \u2014 add the logged session as CSV or MoTeC .ld.";case"ldx":return"This is a MoTeC .ldx, the details beside a .ld with no samples in it \u2014 add the .ld itself.";case"xrk":return"AiM\u2019s own .xrk/.drk format cannot be read outside Race Studio \u2014 export the session as CSV there.";case"ibt":return"An iRacing .ibt is not readable here \u2014 export it to MoTeC .ld or CSV first.";case"zip":return"This zip holds no log that reads here \u2014 add the log itself, as .ld, CSV, .vbo or .mat.";default:return"Not a log this reader knows \u2014 add a MoTeC .ld, a CSV, a .vbo or a .mat."}}var di=class extends Error{constructor(r,o,n){super(r);this.kind=o;this.refused=n;this.name="LogReadError"}kind;refused};var oE=e=>e.length>=4&&e[0]===80&&e[1]===75&&(e[2]===3&&e[3]===4||e[2]===5&&e[3]===6),no=e=>e.slice(e.lastIndexOf("/")+1);async function aE(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=Rde(t);if(r<0)throw new Error("This zip is damaged or cut short: its table of contents is missing.");let o=t.getUint16(r+10,!0),n=t.getUint32(r+16,!0);if(o===65535||n===4294967295)throw new Error("This zip is a ZIP64 archive, which is not read here \u2014 unpack it and add the log inside.");let a=[],i=0;for(let s=0;s<o;s++){if(n+46>e.length||t.getUint32(n,!0)!==33639248)throw new Error("This zip is damaged: an entry in its table of contents is unreadable.");let c=t.getUint16(n+8,!0),l=t.getUint16(n+10,!0),u=t.getUint32(n+20,!0),m=t.getUint32(n+24,!0),p=t.getUint16(n+28,!0),d=t.getUint16(n+30,!0),f=t.getUint16(n+32,!0),h=t.getUint32(n+42,!0),g=e.subarray(n+46,n+46+p),b=new TextDecoder(c&2048?"utf-8":"latin1").decode(g).replace(/\\/g,"/");if(n+=46+p+d+f,b.endsWith("/")||b.startsWith("__MACOSX/")||no(b).startsWith("._"))continue;if(c&1)throw new Error(`${no(b)} in this zip is encrypted \u2014 unpack it and add the log inside.`);if(u===4294967295||m===4294967295)throw new Error("This zip is a ZIP64 archive, which is not read here \u2014 unpack it and add the log inside.");if(i+=m,i>1073741824)throw new Error("This zip unpacks to more than one import takes (1 GB).");if(h+30>e.length||t.getUint32(h,!0)!==67324752)throw new Error(`This zip is damaged: ${no(b)} is not where its table of contents says.`);let y=h+30+t.getUint16(h+26,!0)+t.getUint16(h+28,!0),v=e.subarray(y,y+u);if(v.length<u)throw new Error(`This zip is cut short inside ${no(b)}.`);if(l===0)a.push({path:b,bytes:v});else if(l===8)a.push({path:b,bytes:await xde(v)});else throw new Error(`${no(b)} in this zip is packed a way this reader does not unpack (method ${l}) \u2014 unpack it and add the log inside.`)}return a}function Rde(e){let t=e.byteLength-22;for(let r=t;r>=0&&r>=t-65535;r--)if(e.getUint32(r,!0)===101010256)return r;return-1}async function xde(e){let t=new Blob([e]).stream().pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}function mG(e){let t=e.map(m=>new TextEncoder().encode(m.path)),r=e.map(m=>wde(m.bytes)),o=e.reduce((m,p,d)=>m+30+t[d].length+p.bytes.length,0),n=t.reduce((m,p)=>m+46+p.length,0),a=new Uint8Array(o+n+22),i=new DataView(a.buffer),s=33,c=0,l=[];e.forEach((m,p)=>{l.push(c),i.setUint32(c,67324752,!0),i.setUint16(c+4,20,!0),i.setUint16(c+6,2048,!0),i.setUint16(c+8,0,!0),i.setUint16(c+10,0,!0),i.setUint16(c+12,s,!0),i.setUint32(c+14,r[p],!0),i.setUint32(c+18,m.bytes.length,!0),i.setUint32(c+22,m.bytes.length,!0),i.setUint16(c+26,t[p].length,!0),i.setUint16(c+28,0,!0),a.set(t[p],c+30),a.set(m.bytes,c+30+t[p].length),c+=30+t[p].length+m.bytes.length});let u=c;return e.forEach((m,p)=>{i.setUint32(c,33639248,!0),i.setUint16(c+4,20,!0),i.setUint16(c+6,20,!0),i.setUint16(c+8,2048,!0),i.setUint16(c+10,0,!0),i.setUint16(c+12,0,!0),i.setUint16(c+14,s,!0),i.setUint32(c+16,r[p],!0),i.setUint32(c+20,m.bytes.length,!0),i.setUint32(c+24,m.bytes.length,!0),i.setUint16(c+28,t[p].length,!0),i.setUint32(c+42,l[p],!0),a.set(t[p],c+46),c+=46+t[p].length}),i.setUint32(c,101010256,!0),i.setUint16(c+8,e.length,!0),i.setUint16(c+10,e.length,!0),i.setUint32(c+12,c-u,!0),i.setUint32(c+16,u,!0),a}var ix;function wde(e){if(!ix){ix=new Uint32Array(256);for(let r=0;r<256;r++){let o=r;for(let n=0;n<8;n++)o=o&1?3988292384^o>>>1:o>>>1;ix[r]=o>>>0}}let t=4294967295;for(let r=0;r<e.length;r++)t=ix[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}var sx=[".ld",".ldx",".csv",".tsv",".txt",".vbo",".mat",".zip",".gz"],dG=e=>e.length>2&&e[0]===31&&e[1]===139;async function pG(e){let t=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}function iE(e){let t=new TextDecoder("utf-8").decode(e);return(t.match(/�/g)??[]).length>2?new TextDecoder("latin1").decode(e):t}var fG=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer;async function hG(e,t=""){let r=new Uint8Array(e),o=dG(r)?await pG(r):r,n=t.replace(/\.gz$/i,"");return oE(o)?Cde(o):gG(o,n)}async function gG(e,t,r=[]){let o=Mde(e,t);try{let n=o==="mat"?await oG(fG(e)):_de(e,o);for(let a of r)cG(n,sG(iE(a.bytes)));return{file:n,format:o}}catch(n){throw Ade(n,o)}}function Mde(e,t){let r=rE(e,t);if(!uG(r)||r==="mat"&&aG(e))throw new di(nE(r),r,!0);return r}function _de(e,t){return t==="ld"?JI(fG(e)):t==="vbo"?eG(iE(e)):YU(iE(e))}var Ade=(e,t)=>e instanceof di?e:new di(e instanceof Error?e.message:String(e),t,!1);async function Cde(e){let t;try{t=await aE(e),t=await Promise.all(t.map(async a=>dG(a.bytes)?{path:a.path.replace(/\.gz$/i,""),bytes:await pG(a.bytes)}:a))}catch(a){throw new di(a instanceof Error?a.message:String(a),"zip",!1)}let r=t.map(a=>({e:a,kind:rE(a.bytes,no(a.path))})),o=r.filter(a=>a.kind==="ldx").map(a=>a.e),n=r.filter(a=>a.kind!=="ldx"&&a.kind!=="other"&&a.kind!=="zip");if(n.length===1)return gG(n[0].e.bytes,no(n[0].e.path),o);throw n.length>1?new di(`This zip holds ${n.length} logs \u2014 unpack it and add them, and each opens as a session.`,"zip",!0):new di(nE("zip"),"zip",!0)}function Go(e){if(e===null||typeof e!="object")return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map(Go).join(",")}]`;let t=e,r=Object.keys(t).sort(),o=[];for(let n of r)t[n]!==void 0&&o.push(`${JSON.stringify(n)}:${Go(t[n])}`);return`{${o.join(",")}}`}function kn(e){let t=Go(e),r=2166136261;for(let o=0;o<t.length;o++)r^=t.charCodeAt(o),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r.toString(16).padStart(8,"0").slice(-6)}var Tde=["tireModel","tireModelRear","motorModel","aeroModel","batteryModel","brakeModel","damperModel","damperModelRear","heaveDamperModel","rollDamperModel","kinFront","kinRear","steerFront","surveyedRadiusFront","surveyedRadiusRear","readouts","ggvMode","air","airSettled"];function Kc(e){let t={...e.params};for(let o of Tde)delete t[o];delete t.cgReference,delete t.name;let r=e.suspension?{...e.suspension}:null;return r&&(delete r.name,delete r.chassis),kn({params:t,suspension:r,tire:e.tireModel??null,...e.tireModelRear?{tireRear:e.tireModelRear}:{},motor:e.motorModel??null,...e.aeroModel?{aero:e.aeroModel}:{},...e.batteryModel?{battery:e.batteryModel}:{},...e.brakeModel?{brakes:{...e.brakeModel,name:void 0}}:{},...e.damperModel?{dampers:{...e.damperModel,name:void 0}}:{},...e.damperModelRear?{dampersRear:{...e.damperModelRear,name:void 0}}:{},...e.heaveDamperModel?{dampersHeave:{...e.heaveDamperModel,name:void 0}}:{},...e.rollDamperModel?{dampersRoll:{...e.rollDamperModel,name:void 0}}:{}})}function Pde(e){if(!e||typeof e!="object"||"every"in e)return e??null;let{fitSpacing:t,...r}=e;return t===1?{...r,every:10}:e}function Wc(e){return kn({source:e.source,numerics:Pde(e.numerics)})}var Fde="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function $de(e){let t=Go(e),r=2166136261;for(let o=0;o<t.length;o++)r^=t.charCodeAt(o),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r}function bG(e,t,r){let o=$de([e,t,r]),n="";for(let a=0;a<6;a++)n=Fde[o&31]+n,o>>>=5;return`PD-${n}`}function sE(e){let t=/^\s*PD[-_ ]?([0-9A-Z]{6})\s*$/i.exec(e);if(!t)return;let r=t[1].toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1");return/^[0-9A-HJKMNP-TV-Z]{6}$/.test(r)?`PD-${r}`:void 0}var Ide=/(?:^|[^0-9A-Za-z])(PD[-_ ][0-9A-Za-z]{6})(?![0-9A-Za-z])/gi;function Ede(e){let t=[];for(let r of e.matchAll(Ide)){let o=sE(r[1]);o&&!t.includes(o)&&t.push(o)}return t}function yG(e){for(let t of e){if(!t)continue;let[r]=Ede(t);if(r)return r}}var pi=".pdsetup",Lde="pacedyn-setup",Dde=1024*1024;function vG(e){if(e.length>Dde)throw new Error("This is too large to be a setup file.");let t;try{t=JSON.parse(e)}catch{throw new Error("This is not a setup file: it is not the JSON a setup sheet saves.")}let r=t;if(!r||r.format!==Lde||!Array.isArray(r.stamps))throw new Error("This is not a setup file: a setup sheet\u2019s file names its format and holds its cars.");return r.stamps}var RG=64*1024*1024,xG=e=>new RegExp(`(${e.map(t=>t.replace(".","\\.")).join("|")})$`,"i"),wG=[...sx.filter(e=>e!==".ldx"),...Gh],lx={project:{label:"a project (.pace.json or .json)",pattern:/\.json$/i},track:{label:"a track file (.csv, .tsv, .txt, .json, .yaml or .yml)",pattern:/\.(csv|tsv|txt|json|ya?ml)$/i},part:{label:"a part (.tir or .json)",pattern:/\.(tir|json)$/i},log:{label:`a log (${wG.filter(e=>!Gh.includes(e)).join(", ")})`,pattern:xG(wG)},ldx:{label:"a MoTeC .ldx",pattern:/\.ldx$/i},setup:{label:`an issued setup's file (${pi})`,pattern:xG([pi])},page:{label:"a page (.html)",pattern:/\.html?$/i}},Gde={project:"must end in .json (a project is saved as .pace.json)",page:"must end in .html"};function MG(e=process.cwd(),t=Bde()){let r=n=>{let a=n.trim();if(!a)throw new Error("the path is empty");return a==="~"?t:a.startsWith("~/")||a.startsWith("~\\")?uE(t,a.slice(2)):Ude(a)?kG(a):kG(e,a)},o=async(n,a)=>{let i=r(n);if(!lx[a].pattern.test(i))throw new Error(`${i} is not ${lx[a].label}`);let s;try{s=await cE(i)}catch{throw new Error(`there is no file at ${i} (a relative path starts at ${e})`)}if(!s.isFile())throw new Error(`${i} is not a file`);if(s.size>RG)throw new Error(`${i} is ${Math.round(s.size/1024/1024)} MB; the limit is ${RG/1024/1024} MB`);return i};return{cwd:e,resolve:r,async read(n,a){let i=await o(n,a);return{text:await SG(i,"utf8"),path:i,name:lE(i)}},async bytes(n,a){let i=await o(n,a);return{bytes:new Uint8Array(await SG(i)),path:i,name:lE(i)}},async beside(n,a){let i=cx(r(n)),s;try{s=await Ode(i)}catch{return[]}return s.filter(c=>lx[a].pattern.test(c)).sort().map(c=>uE(i,c))},async write(n,a,i,s="project"){let c=r(n);if(!lx[s].pattern.test(c))throw new Error(`${c} ${Gde[s]}`);let l=!1;try{if(!(await cE(c)).isFile())throw new Error(`${c} is not a file`);l=!0}catch(m){if(m instanceof Error&&m.message.endsWith("is not a file"))throw m}if(l&&!i)throw new Error(`${c} already exists. Pass replace: true to overwrite it, or choose another name.`);try{if(!(await cE(cx(c))).isDirectory())throw new Error("not a folder")}catch{throw new Error(`the folder ${cx(c)} does not exist`)}let u=uE(cx(c),`.${lE(c)}.${Nde(4).toString("hex")}.tmp`);try{await jde(u,a,"utf8"),await zde(u,c)}catch(m){throw await Vde(u,{force:!0}),m}return{path:c,bytes:Buffer.byteLength(a),replaced:l}}}}async function qh(e,t,r){let o=typeof t.text=="string",n=typeof t.path=="string"&&t.path.trim()!=="";if(o&&n)throw new Error("pass the file\u2019s text or its path, not both");if(n){if(!e)throw new Error("this server cannot read files on your machine: pass the file\u2019s text instead");let a=await e.read(t.path,r);return{text:a.text,name:t.name??a.name,path:a.path}}if(!o)throw new Error(e?"pass the file\u2019s text, or its path on this machine":"pass the file\u2019s text");return{text:t.text,name:t.name??""}}var Hh="Instead of the text: the file\u2019s path on this machine, absolute, or relative to the folder the assistant started this server in (~ is the home folder). Preferred \u2014 the file then never passes through the conversation.";import{readFileSync as m_}from"node:fs";import{join as d_}from"node:path";var ux=e=>e.format!=="points"&&!e.field;var jr=e=>e?.kind==="ice";var _G={packVoltageMax:600,segmentVoltageMax:120,powerLimitKw:80};var Bt=e=>typeof e=="number"&&Number.isFinite(e);function qde(e){let{soc:t,ocv:r,r0:o}=e;if(!Array.isArray(t)||t.length<2)return"The curve needs at least two state-of-charge points.";if(!t.every(Bt))return"The state-of-charge axis contains a value that is not a number.";if(t[0]<0||t[t.length-1]>1)return`The state-of-charge axis must lie within 0 to 1 (it runs ${t[0]} to ${t[t.length-1]}).`;for(let n=1;n<t.length;n++)if(!(t[n]>t[n-1]))return`The state-of-charge axis must increase (${t[n-1]} then ${t[n]}).`;if(!Array.isArray(r)||r.length!==t.length)return`The curve has ${Array.isArray(r)?r.length:0} voltages against ${t.length} state-of-charge points.`;if(!r.every(Bt))return"The open-circuit voltage contains a value that is not a number.";if(r.some(n=>n<=0))return"The open-circuit voltage must be positive everywhere.";for(let n=1;n<r.length;n++)if(r[n]<r[n-1])return`The open-circuit voltage must rise with state of charge (${r[n-1]} V at ${t[n-1]} then ${r[n]} V at ${t[n]}).`;if(!Array.isArray(o)||o.length!==t.length)return`The curve has ${Array.isArray(o)?o.length:0} resistances against ${t.length} state-of-charge points.`;if(!o.every(Bt))return"The resistance contains a value that is not a number.";if(o.some(n=>n<0))return"The resistance cannot be negative.";if(e.rTempC!==void 0||e.rGrid!==void 0){let n=e.rTempC,a=e.rGrid;if(!Array.isArray(n)||n.length<1)return"The resistance temperature axis needs at least one temperature.";if(!n.every(Bt))return"The resistance temperature axis contains a value that is not a number.";for(let i=1;i<n.length;i++)if(!(n[i]>n[i-1]))return`The temperature axis must increase (${n[i-1]} then ${n[i]} \xB0C).`;if(!Array.isArray(a)||a.length!==n.length)return`The resistance grid has ${Array.isArray(a)?a.length:0} rows against ${n.length} temperatures.`;for(let i=0;i<a.length;i++){let s=a[i];if(!Array.isArray(s)||s.length!==t.length)return`Resistance row ${i+1} has ${Array.isArray(s)?s.length:0} values against ${t.length} state-of-charge points.`;if(!s.every(Bt))return"The resistance grid contains a value that is not a number.";if(s.some(c=>c<0))return"The resistance grid contains a negative resistance."}}return null}function Hde(e){return!e||typeof e!="object"?"The cell has no curve.":e.kind==="table"?qde(e):e.kind==="analytic"?!Bt(e.vCut)||!Bt(e.vNom)||!Bt(e.vFull)?"The cut-off, nominal and full voltages must be numbers.":e.vCut<=0?"The cut-off voltage must be positive.":e.vCut<e.vNom&&e.vNom<e.vFull?!Bt(e.r0)||e.r0<0?"The cell resistance must be a number and cannot be negative.":e.socAtNom!==void 0&&(!Bt(e.socAtNom)||e.socAtNom<=0||e.socAtNom>=1)?"The state of charge the nominal voltage is met at must lie strictly between 0 and 1.":null:`The voltages must order cut-off < nominal < full (given ${e.vCut}, ${e.vNom}, ${e.vFull} V).`:`Unknown cell curve kind "${e.kind}".`}function Kh(e){if(!e||typeof e!="object")return"Not a battery model.";let t=e.cell;if(!t||typeof t!="object")return"The model has no cell.";if(!Bt(t.capacityAh)||t.capacityAh<=0)return"The cell capacity must be a positive number of amp-hours.";if(!Bt(t.vMin)||t.vMin<0)return"The cut-off voltage must be a number and cannot be negative.";if(!Bt(t.vMax)||t.vMax<=0)return"The maximum cell voltage must be a positive number.";if(!(t.vMin<t.vMax))return`The cut-off voltage (${t.vMin} V) must be below the maximum (${t.vMax} V).`;if(!Bt(t.iMaxA)||t.iMaxA<0)return"The discharge current limit must be a number of amps, 0 for no limit.";if(t.iMaxChargeA!==void 0&&(!Bt(t.iMaxChargeA)||t.iMaxChargeA<0))return"The charge current limit must be a number of amps, 0 for no limit.";if(t.massKg!==void 0&&(!Bt(t.massKg)||t.massKg<0))return"The cell mass must be a number and cannot be negative.";let r=Hde(t.curve);if(r)return r;let o=t.curve.kind==="table"?t.curve.ocv[t.curve.ocv.length-1]:t.curve.vFull;if(t.vMin>=o)return`The cut-off voltage (${t.vMin} V) is at or above the cell's voltage at full charge (${o} V), so no power could ever be drawn.`;let n=e.thermal;if(n!==void 0){if(!n||typeof n!="object")return"The thermal model must be an object, or absent.";if(!Bt(n.heatCapacityJPerK)||n.heatCapacityJPerK<=0)return"The cell heat capacity must be a positive number of joules per kelvin.";if(!Bt(n.coolingWPerK)||n.coolingWPerK<0)return"The cooling must be a number of watts per kelvin and cannot be negative.";if(n.startC!==void 0&&!Bt(n.startC))return"The starting temperature must be a number.";if(n.entropicVPerK!==void 0&&!Bt(n.entropicVPerK))return"The entropic coefficient must be a number.";if(n.derateFromC!==void 0){if(!Bt(n.derateFromC))return"The temperature the derate starts at must be a number.";if(n.derateToC!==void 0){if(!Bt(n.derateToC))return"The temperature the derate ends at must be a number.";if(!(n.derateToC>n.derateFromC))return`The derate must end above where it starts (given ${n.derateFromC} then ${n.derateToC} \xB0C).`}}else if(n.derateToC!==void 0)return"The derate has an end temperature but no start; give both or neither."}let a=e.pack;if(!a||typeof a!="object")return"The model has no pack.";if(!Number.isInteger(a.series)||a.series<1)return"The pack needs a whole number of cells in series, at least one.";if(!Number.isInteger(a.parallel)||a.parallel<1)return"The pack needs a whole number of strings in parallel, at least one.";if(!Bt(a.busResistance)||a.busResistance<0)return"The busbar resistance must be a number and cannot be negative.";if(a.seriesPerSegment!==void 0&&a.seriesPerSegment!==0){if(!Number.isInteger(a.seriesPerSegment)||a.seriesPerSegment<1)return"The cells per segment must be a whole number, at least one.";if(a.seriesPerSegment>a.series)return`A segment cannot hold more cells (${a.seriesPerSegment}) than the pack has in series (${a.series}).`}return null}function mE(e,t){let r=[];if(Kh(e))return r;let{cell:o,pack:n}=e,a=o.vMax*n.series;if(t.packVoltageMax!==void 0&&a>t.packVoltageMax&&r.push(`The pack reaches ${a.toFixed(1)} V at full charge, above the ${t.packVoltageMax} V ceiling \u2014 ${n.series} cells in series at ${o.vMax} V each.`),t.segmentVoltageMax!==void 0&&n.seriesPerSegment){let i=o.vMax*n.seriesPerSegment;i>t.segmentVoltageMax&&r.push(`A segment reaches ${i.toFixed(1)} V, above the ${t.segmentVoltageMax} V ceiling \u2014 ${n.seriesPerSegment} cells at ${o.vMax} V each.`)}return t.segmentVoltageMax!==void 0&&!n.seriesPerSegment&&r.push(`The pack does not say how many cells are in a segment \u2014 the ${t.segmentVoltageMax} V segment ceiling cannot be checked.`),r}function Yc(e,t){let r=e.length;if(r<=1)return{i:0,t:0,clamped:!1};if(t<=e[0])return{i:0,t:0,clamped:t<e[0]};if(t>=e[r-1])return{i:r-2,t:1,clamped:t>e[r-1]};let o=0,n=r-1;for(;n-o>1;){let a=o+n>>1;e[a]<=t?o=a:n=a}return{i:o,t:(t-e[o])/(e[n]-e[o]),clamped:!1}}function rr(e,t,r){let o=e.length;if(o===0)return 0;if(r<=e[0])return t[0];if(r>=e[o-1])return t[o-1];let n=0,a=o-1;for(;a-n>1;){let s=n+a>>1;e[s]<=r?n=s:a=s}let i=(r-e[n])/(e[a]-e[n]);return t[n]+i*(t[a]-t[n])}function mx(e,t,r,o,n){let a=e.length,i=t.length;if(a===0||i===0)return 0;let s=Yc(e,o),c=Yc(t,n),l=Math.min(s.i+1,a-1),u=Math.min(c.i+1,i-1),m=r[c.i][s.i],p=r[c.i][l],d=r[u][s.i],f=r[u][l],h=m+s.t*(p-m),g=d+s.t*(f-d);return h+c.t*(g-h)}var Lm=[0,.05,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],dE={nmc:[0,.29,.4,.483,.525,.567,.608,.667,.733,.8,.892,1],lfp:[0,.478,.591,.626,.652,.67,.678,.696,.704,.722,.757,1],lipo:[0,.333,.433,.517,.575,.625,.667,.717,.775,.833,.908,1],other:[0,.05,.1,.2,.3,.4,.5,.6,.7,.8,.9,1]},AG=[0,.05,.1,.2,.5,.8,1],CG=[2.2,1.55,1.3,1.12,1,.97,.98];function TG(e){return rr(AG,CG,e)}var PG=[-20,-10,0,10,25,40,60],FG=[4,2.8,2,1.4,1,.82,.75];function pE(e){return rr(PG,FG,e)}var $G=.5;function fE(e,t){let{vFull:r,vNom:o,vCut:n,r0:a}=e,i=r-n;if(!(i>0))throw new Error(`The full voltage (${r} V) must be above the cut-off (${n} V).`);let s=(o-n)/i;if(!(s>0&&s<1))throw new Error(`The nominal voltage (${o} V) must lie between the cut-off (${n} V) and full (${r} V).`);let c=dE[t]??dE.other,l=e.socAtNom??$G,u=Lm.includes(l)?[...Lm]:[...Lm,l].sort((h,g)=>h-g),m=rr(Lm,c,l),p=m>0&&m<1?Math.log(s)/Math.log(m):1,d=[],f=[];for(let h of u){let g=rr(Lm,c,h);d.push(n+i*Math.pow(g,p)),f.push(e.constantResistance?a:a*TG(h))}return{kind:"table",soc:u,ocv:d,r0:f}}function hE(e){let t=e.soc,r=e.ocv,o=[0,...t.filter(a=>a>0&&a<1),1],n=0;for(let a=1;a<o.length;a++){let i=o[a-1],s=o[a];n+=(rr(t,r,i)+rr(t,r,s))/2*(s-i)}return n}var Dm=25,IG=new WeakMap;function Ln(e){let t=IG.get(e);if(t)return t;let r=Kh(e);if(r)throw new Error(r);let{cell:o,pack:n}=e,a=o.curve.kind==="table"?o.curve:fE(o.curve,o.chemistry),i=n.series,s=n.parallel,c=i/s,l=a.rTempC,u=a.rGrid,m=s*o.capacityAh,p=i*o.vMin,d=o.iMaxA>0?s*o.iMaxA:1/0,f=o.iMaxChargeA!==void 0&&o.iMaxChargeA>0?o.iMaxChargeA:o.iMaxA/4,h=f>0?s*f:1/0,g=w=>i*rr(a.soc,a.ocv,w),b=(w,M=Dm)=>{let T=l&&u?mx(a.soc,l,u,w,M):rr(a.soc,a.r0,w)*pE(M);return c*T+n.busResistance},y=(w,M,T)=>g(w)-M*b(w,T),v=(w,M,T)=>{if(!(w>0))return 0;let A=g(M),_=b(M,T);if(!(_>0))return w/A;let F=A*A-4*_*w;return F<0?NaN:2*w/(A+Math.sqrt(F))},k=(w,M,T)=>{if(!(w>0))return 0;let A=g(M),_=b(M,T);return _>0?2*w/(A+Math.sqrt(A*A+4*_*w)):w/A},x=w=>{let M=e.thermal;if(!M||M.derateFromC===void 0)return 1;let T=M.derateToC??M.derateFromC;return w<=M.derateFromC?1:!(T>M.derateFromC)||w>=T?0:1-(w-M.derateFromC)/(T-M.derateFromC)},S=(w,M,T=0)=>{let A=g(w),_=b(w,M),F=_>0?A/(2*_):1/0,P=L=>{if(!(_>0))return L*A;let j=Math.min(L,F);return j*(A-j*_)},I=_>0?Math.max(0,(A-p)/_):1/0,z=T>0&&Number.isFinite(T)?T:1/0,N=_>0?P(I):1/0,q=Number.isFinite(d)?P(d):1/0,U=_>0?A*A/(4*_):1/0,B=[["rules",z],["voltage-floor",N],["current",q],["matched-load",U]],V=B[0][0],E=B[0][1];for(let[L,j]of B)j<E&&(E=j,V=L);let C=x(M??Dm);C<1&&(E=Number.isFinite(E)?E*C:E,V="temperature");let $=Number.isFinite(E)?v(E,w,M):1/0;return{watts:E,binding:V,rules:z,voltageFloor:N,current:q,matchedLoad:U,derate:C,amps:$,volts:Number.isFinite($)?A-$*_:A}},R={model:e,table:a,capacityAh:m,chargeC:m*3600,energyKwh:m*(i*hE(a))/1e3,socRange:[a.soc[0],a.soc[a.soc.length-1]],voltageAtFull:i*a.ocv[a.ocv.length-1],voltageCeiling:i*o.vMax,voltageFloor:p,currentCeiling:d,chargeCurrentCeiling:h,massKg:o.massKg!==void 0?i*s*o.massKg:null,thermal:e.thermal?{heatCapacityJPerK:i*s*e.thermal.heatCapacityJPerK,coolingWPerK:i*s*e.thermal.coolingWPerK,...e.thermal.startC!==void 0?{startC:e.thermal.startC}:{},entropicVPerK:i*(e.thermal.entropicVPerK??0)}:null,derateAt:x,ocv:g,resistance:b,terminalVoltage:y,currentFor:v,chargeCurrentFor:k,maxPower:S};return IG.set(e,R),R}function gE(e){return{name:e.name,chemistry:e.chemistry,capacityAh:e.capacityAh,curve:{kind:"analytic",vFull:e.vFull,vNom:e.vNom,vCut:e.vCut,r0:e.r0},iMaxA:e.iMaxA,...e.iMaxChargeA!==void 0?{iMaxChargeA:e.iMaxChargeA}:{},vMin:e.vCut,vMax:e.vFull,...e.massKg!==void 0?{massKg:e.massKg}:{}}}var EG={name:"High-power NMC pouch 4.0 Ah",chemistry:"nmc",capacityAh:4,vCut:3,vNom:3.6,vFull:4.2,r0:.0025,iMaxA:100,iMaxChargeA:40,massKg:.09},LG={name:"LFP prismatic 20 Ah",chemistry:"lfp",capacityAh:20,vCut:2.5,vNom:3.2,vFull:3.65,r0:.002,iMaxA:200,iMaxChargeA:60,massKg:.4},DG={name:"NMC cylindrical 3.4 Ah",chemistry:"nmc",capacityAh:3.4,vCut:3,vNom:3.6,vFull:4.2,r0:.03,iMaxA:10,iMaxChargeA:3,massKg:.048};function bE(){return{name:"Formula Student accumulator",cell:gE(EG),pack:{series:140,parallel:2,busResistance:.02,seriesPerSegment:28},provenance:{source:"assumed",note:"Assumed high-power NMC pouch pack sized to the Formula Student rules; the cell curve and resistance are class-level guesses, not a measurement."}}}function yE(){return{name:"LFP pack",cell:gE(LG),pack:{series:160,parallel:1,busResistance:.02,seriesPerSegment:32},provenance:{source:"assumed",note:"Assumed LFP prismatic pack; the flat plateau is the chemistry, the numbers are class-level guesses."}}}function vE(){return{name:"Road car pack",cell:gE(DG),pack:{series:96,parallel:74,busResistance:.01},provenance:{source:"assumed",note:"Assumed road-electric pack of cylindrical energy cells; capacity and voltage are class-typical, the resistance is a guess."}}}function SE(e,t,r="Constant pack"){return{name:r,cell:{name:"Constant cell",chemistry:"other",capacityAh:e,curve:{kind:"table",soc:[0,1],ocv:[t,t],r0:[0,0]},iMaxA:0,vMin:0,vMax:t},pack:{series:1,parallel:1,busResistance:0},provenance:{source:"assumed",note:"The constant pack: one open-circuit voltage, no internal resistance and no current limit \u2014 what a car carried before the battery was a model. It cannot sag, so its power never fades."}}}function dx(e){if(e.kind==="ice"){let o=e.gearbox.efficiency;return{model:e,maxTorque:n=>n>e.limitRpm?0:rr(e.rpm,e.torque,n),efficiency:()=>o}}let t=o=>rr(e.rpm,e.torque,o),r=e.kind==="simple"?()=>e.efficiency:(o,n)=>mx(e.effRpm,e.effTorque,e.effGrid,o,n);return{model:e,maxTorque:t,efficiency:r}}function kE(e){let t=e.resistanceAtC??20,r=e.torqueConstant,o=e.speedLossW??0,n=e.speedLossAtRpm??0,a=e.speedLossExponent??1.5,i=e.derateFromC,s=e.derateToC,c=f=>Math.max(0,e.terminalResistanceOhm*(1+.00393*(f-t))),l=f=>o>0&&n>0?o*Math.pow(Math.max(0,f)/n,a):0,u=(f,h,g)=>{let b=r>0?Math.abs(h)/r:0;return 1.5*c(g)*b*b+l(f)},m=(f,h)=>{let g=e.coolingWPerK*(h-e.coolantC)-l(f);return!(g>0)||r<=0?0:r*Math.sqrt(g/(1.5*c(h)))},p=e.coolingWPerK>0?e.heatCapacityJPerK/e.coolingWPerK:1/0,d=Number.isFinite(p)?.25*p:1/0;return{spec:e,startC:e.startC??e.coolantC,lossW:u,step(f,h,g){if(!(g>0)||!(e.heatCapacityJPerK>0))return f;let b=Number.isFinite(d)?Math.max(1,Math.ceil(g/d)):1,y=g/b,v=f;for(let k=0;k<b;k++)v+=(h-e.coolingWPerK*(v-e.coolantC))*y/e.heatCapacityJPerK;return v},continuousTorque:m,derate(f,h,g){if(i===void 0||s===void 0||!(s>i)||!(g>0)||h<=i)return 1;let b=Math.min(1,m(f,s)/g);return h>=s?b:1-(1-b)*(h-i)/(s-i)},equilibriumC(f){return e.coolingWPerK>0?e.coolantC+f/e.coolingWPerK:1/0}}}function nr(e,t){return t==="rear"&&e.tireRateRear!==void 0?e.tireRateRear:e.tireRate}function Wh(e,t){let r=e.tyreFreeRadiusRear;return(t==="rear"&&r!==void 0?r:e.tyreFreeRadius)??0}var px=9.81,NG=(e,t)=>e*(t*t)/2*(Math.PI/180)/1e3,Yh=(e,t)=>e+t>0?e*t/(e+t):0,OG=.5;function fx(e,t,r){if(!(r>0))return 1;let o=e*px*t*(Math.PI/180)/r;return 1/(1-Math.min(OG,o))}function RE(e,t,r){return r>0?e*px*t/(r*r):0}function zG(e,t,r,o,n){if(!(o>0)||!(n>0))return 1;let a=RE(e,t,r)*(1/o+1/n);return 1/(1-Math.min(OG,a))}function Lt(e){let t=4*e.unsprungPerCorner,r=Math.max(0,e.massTotal-t),o=r*e.frontMassFrac,n=r*(1-e.frontMassFrac),a=nr(e,"front"),i=nr(e,"rear"),s=e.wheelRateFront+(e.heaveSpringFront??0),c=e.wheelRateRear+(e.heaveSpringRear??0),l=Yh(s,a),u=Yh(c,i),m=(q,U)=>{let B=U/2;return B>0?1/(2*Math.PI)*Math.sqrt(q*1e3/B):0},p=m(l,o),d=m(u,n),f=Yh(e.wheelRateFront+e.arbFront,a),h=Yh(e.wheelRateRear+e.arbRear,i),g=NG(f,e.trackFront),b=NG(h,e.trackRear),y=g+b,v=y>0?g/y:.5,k=e.rcHeightFront+(e.rcHeightRear-e.rcHeightFront)*(1-e.frontMassFrac),x=(e.cgHeight-k)/1e3,S=r*px*x,R=fx(r,x,y),w=y>0?S/y*R:0,M=e.massTotal*px*e.cgHeight/e.wheelbase,T=2*l,A=2*u,_=zG(r,e.cgHeight,e.wheelbase,T,A),P=(T>0&&A>0?(M/T+M/A)/e.wheelbase*_:0)*(180/Math.PI),I=e.wheelbase*e.wheelbase*Yh(T,A)*(Math.PI/180)/1e3,z=e.damperFront??2.5,N=e.damperRear??2.5;return{sprungMass:r,sprungFront:o,sprungRear:n,rideRateFront:l,rideRateRear:u,rideFreqFront:p,rideFreqRear:d,rollRateFront:g,rollRateRear:b,rollRateTotal:y,rollWheelRateFront:f,rollWheelRateRear:h,frontRollStiffFrac:v,rollGradient:w,pitchGradient:P,pitchRate:I,cgRollGain:R,cgPitchGain:_,rideDampingFront:z+(e.heaveDamperFront??0),rideDampingRear:N+(e.heaveDamperRear??0),rollDampingFront:z+(e.rollDamperFront??0),rollDampingRear:N+(e.rollDamperRear??0)}}var _s=["clFront","clRear","cd"],As=e=>e.frame?.kind==="pitch";function Nm(e){return As(e)?{x:e.axes.h,y:e.axes.pitch}:{x:e.axes.hFront,y:e.axes.hRear}}var hx=e=>e.frame?.kind==="pitch",VG=e=>e.kind==="map";var gx=45,vr=e=>typeof e=="number"&&Number.isFinite(e);function bx(e,t,r="mm",o="ride height"){if(!Array.isArray(t)||t.length<1)return`The ${e} axis needs at least one ${o}.`;if(!t.every(vr))return`The ${e} axis contains a value that is not a number.`;for(let n=1;n<t.length;n++)if(!(t[n]>t[n-1]))return`The ${e} axis must increase (${t[n-1]} then ${t[n]} ${r}).`;return null}function jG(e,t){if(t===void 0)return null;for(let r of _s){let o=t[r];if(!o||!Array.isArray(o.deg)||!Array.isArray(o.factor))return`The ${e} correction of ${r} needs degrees and factors.`;if(o.deg.length<1)return`The ${e} correction of ${r} needs at least one angle.`;if(o.deg.length!==o.factor.length)return`The ${e} correction of ${r} has ${o.factor.length} factors against ${o.deg.length} angles.`;if(!o.deg.every(vr)||!o.factor.every(vr))return`The ${e} correction of ${r} contains a value that is not a number.`;if(o.deg[0]<0)return`The ${e} correction of ${r} is against the absolute angle; it cannot start below zero.`;for(let n=1;n<o.deg.length;n++)if(!(o.deg[n]>o.deg[n-1]))return`The ${e} correction of ${r} must increase in angle (${o.deg[n-1]} then ${o.deg[n]}\xB0).`;if(o.factor.some(n=>n<0))return`The ${e} correction of ${r} has a negative factor.`}return null}function BG(e,t){return t===void 0?null:!vr(t.dCl)||!vr(t.dBalance)||!vr(t.dCd)?`The ${e} slopes must be numbers.`:!vr(t.maxDeg)||!(t.maxDeg>0)?`The ${e} response needs a positive angle to be valid to.`:null}function Om(e){if(!e||typeof e!="object")return"Not an aero model.";if(!vr(e.area)||e.area<=0)return"The reference area must be a positive number of square metres.";if(e.kind==="map"){let t,r,o,n;if(e.frame==null){let s=bx("front ride-height",e.axes?.hFront);if(s)return s;let c=bx("rear ride-height",e.axes?.hRear);if(c)return c;[t,r,o,n]=[e.axes.hFront,e.axes.hRear,"front ride heights","rear ride heights"]}else if(e.frame?.kind==="pitch"){if(!vr(e.frame.refX))return"The point the ride height is read at must be a number of millimetres aft of the front axle.";let s=bx("ride-height",e.axes?.h);if(s)return s;let c=bx("pitch",e.axes?.pitch,"\xB0","pitch");if(c)return c;let l=e.axes.pitch.find(u=>Math.abs(u)>=gx);if(l!==void 0)return`A pitch of ${l}\xB0 is not a car's attitude \u2014 is the axis a rake in millimetres? Pitch is in degrees.`;[t,r,o,n]=[e.axes.h,e.axes.pitch,"ride heights","pitches"]}else return`Unknown aero map frame "${e.frame.kind}".`;let a=t.length,i=r.length;for(let s of _s){let c=e[s];if(!Array.isArray(c)||c.length!==i)return`${s} has ${Array.isArray(c)?c.length:0} rows against ${i} ${n} \u2014 they must match.`;for(let l=0;l<i;l++){let u=c[l];if(!Array.isArray(u)||u.length!==a)return`${s} row ${l+1} has ${Array.isArray(u)?u.length:0} values against ${a} ${o}.`;if(!u.every(vr))return`${s} contains a value that is not a number.`}}return jG("yaw",e.attitude?.yaw)??jG("roll",e.attitude?.roll)}if(e.kind==="sensitivity"){let t;if(e.frame==null)t=["hFront","hRear"];else if(e.frame?.kind==="pitch"){if(!vr(e.frame.refX))return"The point the ride height is read at must be a number of millimetres aft of the front axle.";t=["h","pitch"]}else return`Unknown aero sensitivity frame "${e.frame.kind}".`;let r=e.ref,o=e.slope,n=e.range,a=i=>i==="pitch"?"\xB0":" mm";if(!r||!vr(r[t[0]])||!vr(r[t[1]]))return e.frame?"The reference ride height and pitch must be numbers.":"The reference ride heights must be numbers.";for(let i of _s){if(!e.at||!vr(e.at[i]))return`${i} at the reference must be a number.`;let s=o?.[i];if(!s||!vr(s[t[0]])||!vr(s[t[1]]))return`The slopes of ${i} must be numbers.`}for(let i of t){let s=n?.[i],c=r[i];if(!s||!vr(s[0])||!vr(s[1]))return`The ${i} range must be two numbers.`;if(!(s[1]>s[0]))return`The ${i} range must run from low to high (${s[0]} to ${s[1]}${a(i)}).`;if(c<s[0]||c>s[1])return`The reference ${i} of ${c}${a(i)} lies outside its range ${s[0]}\u2013${s[1]}${a(i)}.`;if(i==="pitch"&&(Math.abs(s[0])>=gx||Math.abs(s[1])>=gx))return`A pitch range reaching ${Math.abs(s[0])>=gx?s[0]:s[1]}\xB0 is not a car's attitude. Pitch is in degrees.`}return BG("yaw",e.attitude?.yaw)??BG("roll",e.attitude?.roll)}return`Unknown aero model kind "${e.kind}".`}var UG=180/Math.PI;function zm(e,t,r,o){let n=(o-r)/t;return{h:r+e.refX*n,pitch:Math.atan(n)*UG}}function Vm(e,t,r,o){let n=Math.tan(o/UG);return{hFront:r-e.refX*n,hRear:r+(t-e.refX)*n}}var Y2e=180/Math.PI,Kde=["hFront","hRear"],Wde=["h","pitch"],ME=e=>e?.kind==="pitch"?Wde:Kde,Dn=(e,t)=>e[t],yx=(e,t)=>e[t],xE=(e,t)=>({[e[0]]:t(e[0]),[e[1]]:t(e[1])});function Yde(e){if(!(!e.yaw&&!e.roll))return{...e.yaw?{yaw:{...e.yaw}}:{},...e.roll?{roll:{...e.roll}}:{}}}function _E(e){let t=ME(e.frame),r=e.balanceFront,o=e.cl*r,n=e.cl*(1-r),a=xE(t,c=>Dn(e.dCl,c)*r+e.cl*Dn(e.dBalance,c)),i=xE(t,c=>Dn(e.dCl,c)*(1-r)-e.cl*Dn(e.dBalance,c)),s=Yde(e);return{kind:"sensitivity",name:e.name,area:e.area,...e.frame?{frame:{...e.frame}}:{},ref:{...e.ref},at:{clFront:o,clRear:n,cd:e.cd},slope:{clFront:a,clRear:i,cd:xE(t,c=>Dn(e.dCd,c))},range:{[t[0]]:[...yx(e.range,t[0])],[t[1]]:[...yx(e.range,t[1])]},provenance:{...e.provenance},...s?{attitude:s}:{}}}function vx(e,t,r){let o=Math.min(Math.abs(r),t.maxDeg),n=e.clFront+e.clRear,a=n!==0?e.clFront/n:.5,i=n+t.dCl*o,s=a+t.dBalance*o,c=e.clFront!==0?i*s/e.clFront:1,l=e.clRear!==0?i*(1-s)/e.clRear:1,u=e.cd!==0?(e.cd+t.dCd*o)/e.cd:1;return{clFront:c,clRear:l,cd:u}}function wE(e,t,r=11){let o=Array.from({length:r},(a,i)=>t.maxDeg*i/(r-1)),n=o.map(a=>vx(e,t,a));return{clFront:{deg:[...o],factor:n.map(a=>a.clFront)},clRear:{deg:[...o],factor:n.map(a=>a.clRear)},cd:{deg:[...o],factor:n.map(a=>a.cd)}}}function GG(e){if(!(!e.attitude?.yaw&&!e.attitude?.roll))return{...e.attitude.yaw?{yaw:wE(e.at,e.attitude.yaw)}:{},...e.attitude.roll?{roll:wE(e.at,e.attitude.roll)}:{}}}function qG(e,t,r,o=0,n=0){let[a,i]=ME(e.frame),s=t-Dn(e.ref,a),c=r-Dn(e.ref,i),l={clFront:e.at.clFront+Dn(e.slope.clFront,a)*s+Dn(e.slope.clFront,i)*c,clRear:e.at.clRear+Dn(e.slope.clRear,a)*s+Dn(e.slope.clRear,i)*c,cd:e.at.cd+Dn(e.slope.cd,a)*s+Dn(e.slope.cd,i)*c},u=e.attitude?.yaw?vx(e.at,e.attitude.yaw,o):{clFront:1,clRear:1,cd:1},m=e.attitude?.roll?vx(e.at,e.attitude.roll,n):{clFront:1,clRear:1,cd:1};return{clFront:l.clFront*u.clFront*m.clFront,clRear:l.clRear*u.clRear*m.clRear,cd:l.cd*u.cd*m.cd}}function AE(e){let[t,r]=ME(e.frame),o=[...yx(e.range,t)],n=[...yx(e.range,r)],a=s=>n.map(c=>o.map(l=>s(qG(e,l,c)))),i=GG(e);return{kind:"map",name:e.name,area:e.area,...e.frame?{frame:{...e.frame}}:{},axes:{[t]:o,[r]:n},clFront:a(s=>s.clFront),clRear:a(s=>s.clRear),cd:a(s=>s.cd),provenance:{...e.provenance},...i?{attitude:i}:{}}}var CE=180/Math.PI,HG=new WeakMap,KG=new WeakMap,TE=new WeakMap;function Cs(e,t){let r=KG.get(e);if(r)return r;let o=t?.wheelbase,n=o!==void 0?TE.get(e)?.get(o):void 0;if(n)return n;let a=Zde(e),i=a.map;if(!As(i)){let l=Xde(e,a);return KG.set(e,l),l}if(o===void 0||!Number.isFinite(o)||o<=0)throw new Error("A ride-height-and-pitch aero map is read with the car\u2019s wheelbase, and none was given.");let s=Jde(e,a,i.frame,o),c=TE.get(e);return c||(c=new Map,TE.set(e,c)),c.set(o,s),s}function Zde(e){let t=HG.get(e);if(t)return t;let r=Om(e);if(r)throw new Error(r);let o=e.kind==="map"?e:AE(e),{x:n,y:a}=Nm(o),i=n.length,s=a.length,c=o.attitude?.yaw,l=o.attitude?.roll,u=!!(c||l),m={clFront:1,clRear:1,cd:1,clamped:!1},p=(y,v)=>{let k=Math.abs(v),x=y.clFront.deg[y.clFront.deg.length-1];return{clFront:rr(y.clFront.deg,y.clFront.factor,k),clRear:rr(y.clRear.deg,y.clRear.factor,k),cd:rr(y.cd.deg,y.cd.factor,k),clamped:k>x}},d=(y,v)=>{if(!u)return m;let k=c?p(c,y):m,x=l?p(l,v):m;return{clFront:k.clFront*x.clFront,clRear:k.clRear*x.clRear,cd:k.cd*x.cd,clamped:k.clamped||x.clamped}},f=(y,v,k=0,x=0)=>{let S=Yc(n,y),R=Yc(a,v),w=Math.min(S.i+1,i-1),M=Math.min(R.i+1,s-1),T=_=>{let F=_[R.i][S.i],P=_[R.i][w],I=_[M][S.i],z=_[M][w],N=F+S.t*(P-F),q=I+S.t*(z-I);return N+R.t*(q-N)},A=d(k,x);return{clFront:u?T(o.clFront)*A.clFront:T(o.clFront),clRear:u?T(o.clRear)*A.clRear:T(o.clRear),cd:u?T(o.cd)*A.cd:T(o.cd),clampedRide:S.clamped||R.clamped,clampedAttitude:A.clamped}},h={x:[n[0],n[i-1]],y:[a[0],a[s-1]]},g=(y,v,k=!1,x=0,S=0)=>{let R=d(x,S),w=Yc(n,k?Math.min(Math.max(y,h.x[0]),h.x[1]):y),M=Yc(a,k?Math.min(Math.max(v,h.y[0]),h.y[1]):v),T=Math.min(w.i+1,i-1),A=Math.min(M.i+1,s-1),_=T>w.i?n[T]-n[w.i]:0,F=A>M.i?a[A]-a[M.i]:0,P={};for(let I of _s){let z=o[I],N=z[M.i][w.i],q=z[M.i][T],U=z[A][w.i],B=z[A][T],V=w.clamped||_===0?0:((q-N)*(1-M.t)+(B-U)*M.t)/_,E=M.clamped||F===0?0:((U-N)*(1-w.t)+(B-q)*w.t)/F;P[I]=u?{x:V*R[I],y:E*R[I]}:{x:V,y:E}}return P},b={map:o,x:h.x,y:h.y,hasAttitude:u,factors:d,at:f,slopes:g};return HG.set(e,b),b}function Xde(e,t){let r={x:t.x,y:t.y,at:t.at,toAxles:(n,a)=>({hFront:n,hRear:a}),fromAxles:(n,a)=>({x:n,y:a})},o=(n,a,i=!1,s=0,c=0)=>{let l=t.slopes(n,a,i,s,c),u={};for(let m of _s)u[m]={hFront:l[m].x,hRear:l[m].y};return u};return{model:e,map:t.map,area:t.map.area,grid:r,hasAttitude:t.hasAttitude,at:t.at,slopes:o,factors:t.factors}}function Jde(e,t,r,o){let n=r.refX,a=n/o,i=(l,u,m=0,p=0)=>{let d=(u-l)/o;return t.at(l+n*d,Math.atan(d)*CE,m,p)},s=(l,u,m=!1,p=0,d=0)=>{let f=(u-l)/o,h=t.slopes(l+n*f,Math.atan(f)*CE,m,p,d),g=CE/(o*(1+f*f)),b={};for(let y of _s)b[y]={hFront:h[y].x*(1-a)-h[y].y*g,hRear:h[y].x*a+h[y].y*g};return b},c={frame:r,x:t.x,y:t.y,at:t.at,toAxles:(l,u)=>Vm(r,o,l,u),fromAxles:(l,u)=>{let m=zm(r,o,l,u);return{x:m.h,y:m.pitch}}};return{model:e,map:t.map,area:t.map.area,grid:c,hasAttitude:t.hasAttitude,at:i,slopes:s,factors:t.factors}}function PE(e){let t=e.clFront+e.clRear;return{cl:t,balanceFront:t!==0?e.clFront/t:.5}}var ut=(e,t)=>e*t/100,hr=e=>e/100,WG={name:"Formula Student aero",area:1,cl:3,balanceFront:.45,cd:1.3,ref:{hFront:30,hRear:35},range:{hFront:[5,60],hRear:[10,70]},dCl:{hFront:ut(3,-.4),hRear:ut(3,.1)},dBalance:{hFront:hr(-.3),hRear:hr(.15)},dCd:{hFront:ut(1.3,-.1),hRear:ut(1.3,.05)},yaw:{dCl:ut(3,-1),dBalance:hr(-.3),dCd:ut(1.3,.5),maxDeg:10},roll:{dCl:ut(3,-.5),dBalance:0,dCd:0,maxDeg:3},note:"Assumed class-level sensitivities for an undertray-and-wings Formula Student car, ride height, yaw and roll; not measured."},YG={name:"Formula 1 aero",area:1.5,cl:3,balanceFront:.44,cd:.9,ref:{hFront:35,hRear:70},range:{hFront:[0,60],hRear:[20,100]},dCl:{hFront:ut(3,-.3),hRear:ut(3,-.15)},dBalance:{hFront:hr(-.15),hRear:hr(.15)},dCd:{hFront:ut(.9,-.15),hRear:ut(.9,-.05)},yaw:{dCl:ut(3,-1.5),dBalance:hr(.2),dCd:ut(.9,.8),maxDeg:8},roll:{dCl:ut(3,-1),dBalance:hr(-.3),dCd:0,maxDeg:2},note:"Assumed class-level sensitivities for a ground-effect floor, ride height, yaw and roll; not measured."},ZG={name:"GT car aero",area:2,cl:1.4,balanceFront:.42,cd:.42,ref:{hFront:55,hRear:75},range:{hFront:[10,90],hRear:[10,110]},dCl:{hFront:ut(1.4,-.3),hRear:ut(1.4,.05)},dBalance:{hFront:hr(-.25),hRear:hr(.15)},dCd:{hFront:ut(.42,-.1),hRear:0},yaw:{dCl:ut(1.4,-.8),dBalance:hr(-.2),dCd:ut(.42,.6),maxDeg:10},roll:{dCl:ut(1.4,-.3),dBalance:0,dCd:0,maxDeg:3},note:"Assumed class-level sensitivities for a splitter-and-wing GT car, ride height, yaw and roll; not measured."},XG={name:"Sports car aero",area:2.2,cl:-.1,balanceFront:.5,cd:.3,ref:{hFront:130,hRear:140},range:{hFront:[80,180],hRear:[100,200]},dCl:{hFront:-5e-4,hRear:0},dBalance:{hFront:0,hRear:0},dCd:{hFront:2e-4,hRear:0},yaw:{dCl:0,dBalance:0,dCd:ut(.3,.5),maxDeg:10},note:"Assumed class-level sensitivities for a road car with no aero devices; not measured."},JG={name:"Cup car aero",area:2.1,cl:.45,balanceFront:.45,cd:.4,ref:{hFront:64,hRear:78},range:{hFront:[20,100],hRear:[30,120]},dCl:{hFront:ut(.45,-.4),hRear:ut(.45,.05)},dBalance:{hFront:hr(-.25),hRear:hr(.15)},dCd:{hFront:ut(.4,-.1),hRear:0},yaw:{dCl:ut(.45,-1.2),dBalance:hr(-.2),dCd:ut(.4,.6),maxDeg:10},roll:{dCl:ut(.45,-.3),dBalance:0,dCd:0,maxDeg:3},note:"Assumed class-level sensitivities for a splitter-and-wing cup hatchback, ride height, yaw and roll; not measured."},QG={name:"Stock car aero",area:2.2,cl:.6,balanceFront:.45,cd:.45,ref:{hFront:75,hRear:90},range:{hFront:[20,110],hRear:[30,130]},dCl:{hFront:ut(.6,-.35),hRear:ut(.6,.05)},dBalance:{hFront:hr(-.25),hRear:hr(.15)},dCd:{hFront:ut(.45,-.1),hRear:0},yaw:{dCl:ut(.6,-1),dBalance:hr(-.2),dCd:ut(.45,.6),maxDeg:10},roll:{dCl:ut(.6,-.3),dBalance:0,dCd:0,maxDeg:3},note:"Assumed class-level sensitivities for a splitter-and-spoiler stock car, ride height, yaw and roll; not measured."},eq={name:"Hill-climb prototype aero",area:1.2,cl:2.5,balanceFront:.42,cd:.9,ref:{hFront:45,hRear:55},range:{hFront:[10,80],hRear:[15,95]},dCl:{hFront:ut(2.5,-.35),hRear:ut(2.5,.05)},dBalance:{hFront:hr(-.25),hRear:hr(.15)},dCd:{hFront:ut(.9,-.1),hRear:ut(.9,.05)},yaw:{dCl:ut(2.5,-1),dBalance:hr(-.3),dCd:ut(.9,.5),maxDeg:10},roll:{dCl:ut(2.5,-.5),dBalance:0,dCd:0,maxDeg:3},note:"Assumed class-level sensitivities for a winged sports prototype with a flat floor and diffuser, ride height, yaw and roll; not measured."},tq={name:"Race truck aero",area:6.2,cl:-.1,balanceFront:.6,cd:.65,ref:{hFront:110,hRear:240},range:{hFront:[60,160],hRear:[180,300]},dCl:{hFront:-5e-4,hRear:0},dBalance:{hFront:0,hRear:0},dCd:{hFront:2e-4,hRear:0},yaw:{dCl:0,dBalance:0,dCd:ut(.65,.5),maxDeg:10},note:"Assumed class-level sensitivities for a cab-over race truck with a chin spoiler and deflectors, ride height and yaw; not measured."};function fi(e){return _E({name:e.name,area:e.area,cl:e.cl,balanceFront:e.balanceFront,cd:e.cd,ref:e.ref,range:e.range,dCl:e.dCl,dBalance:e.dBalance,dCd:e.dCd,...e.yaw?{yaw:e.yaw}:{},...e.roll?{roll:e.roll}:{},provenance:{source:"assumed",note:e.note}})}var FE=()=>fi(WG),$E=()=>fi(YG),IE=()=>fi(ZG),EE=()=>fi(XG),LE=()=>fi(JG),DE=()=>fi(QG),NE=()=>fi(eq),OE=()=>fi(tq);function Zc(e,t){let r=.5*e.rho*e.area*t*t,o=e.cl*r,n=e.cw*r,a=o*e.copLongFront;return{downforce:o,drag:n,downFront:a,downRear:o-a}}function Sx(e,t){let r=e.massTotal;if(!(r>0))return{front:0,rear:0};let o=Math.max(0,Math.min(1,e.frontMassFrac)),n=2*e.unsprungPerCorner,a=(i,s)=>s>0?Math.min(1,i/s):0;return{front:(t.sprungMass*o+n*a(t.rideRateFront,nr(e,"front")))/r,rear:(t.sprungMass*(1-o)+n*a(t.rideRateRear,nr(e,"rear")))/r}}function kx(e,t,r,o){let n=t.front*r+t.rear*o;return n===0?e:Math.max(Math.min(1,e),e-n)}function zE(e,t){return e.wheelbase>0?e.massTotal*t*9.81/e.wheelbase:0}function jm(e,t,r){let o=2*t.rideRateFront,n=2*t.rideRateRear;return!(o>0)||!(n>0)?0:Math.min(RE(t.sprungMass,r,e.wheelbase),.5*o*n/(o+n))}function Zh(e,t,r,o,n){let a=e.cgHeight,i=zE(e,r);if(o===0&&n===0&&i===0)return{height:a,forward:0,noseLoad:0,dropFront:0,dropRear:0};let s=Sx(e,t),c=2*t.rideRateFront,l=2*t.rideRateRear,u=a,m=0,p=0,d=0;for(let h=0;h<6;h++){d=jm(e,t,u);let g=o-i*u,b=n+i*u;if(d>0){let k=c*l-d*(c+l);m=(g*(l-d)-d*b)/k,p=(b*(c-d)-d*g)/k}else m=c>0?g/c:0,p=l>0?b/l:0;let y=kx(a,s,m,p),v=Math.abs(y-u);if(u=y,v<1e-9)break}let f=m-p;return{height:u,forward:e.wheelbase>0?u*f/e.wheelbase:0,noseLoad:d*f,dropFront:m,dropRear:p}}var VE={yawDeg:0,rollDeg:0},rq=1e-4,Qde=40,nq=50;function hi(e,t,r=0){let o=e.aero?.model;if(!(!o||!Cs(o,e).hasAttitude))return{yawDeg:r,rollDeg:Lt(e).rollGradient*t}}function Bm(e,t){if(e.rideHeightFront!=null&&e.rideHeightRear!=null)return{hFront:e.rideHeightFront,hRear:e.rideHeightRear};let r=e.model,o=(a,i,s)=>{if(t!==void 0&&t>0)return Vm(a,t,i,s);throw new Error("A ride-height-and-pitch aero model is read with the car\u2019s wheelbase, and none was given.")},n={hFront:0,hRear:0};if(r?.kind==="sensitivity")n=hx(r)?o(r.frame,r.ref.h,r.ref.pitch):r.ref;else if(r){let{x:a,y:i}=Nm(r),s=(a[0]+a[a.length-1])/2,c=(i[0]+i[i.length-1])/2;n=As(r)?o(r.frame,s,c):{hFront:s,hRear:c}}return{hFront:e.rideHeightFront??n.hFront,hRear:e.rideHeightRear??n.hRear}}var oq=new WeakMap;function gi(e,t,r=0,o){let n=e.aero;if(!n?.model)return null;let a=oq.get(e);a||(a=new Map,oq.set(e,a));let i=o&&Cs(n.model,e).hasAttitude?o:VE,s=i===VE?`${t}|${r}`:`${t}|${r}|${i.yawDeg.toFixed(3)}|${i.rollDeg.toFixed(3)}`,c=a.get(s);if(c)return c;let l=epe(e,n,t,r,i);return a.size>4096&&a.clear(),a.set(s,l),l}function epe(e,t,r,o,n){let a=Cs(t.model,e),i=Lt(e),s=2*i.rideRateFront,c=2*i.rideRateRear,l=Bm(t,e.wheelbase),u=.5*t.rho*r*r,m=a.area,p=e.wheelbase>0?t.copHeight/e.wheelbase:0,d=Sx(e,i),f=zE(e,o),h=(T,A)=>kx(e.cgHeight,d,l.hFront-T,l.hRear-A),g=(T,A)=>l.hFront-T-(l.hRear-A),b=(T,A)=>{let _=a.at(T,A,n.yawDeg,n.rollDeg),F=u*m*_.clFront,P=u*m*_.clRear,I=u*m*_.cd,z=I*p,N=h(T,A),q=f*N,U=jm(e,i,N)*g(T,A),B=F-q-z+U,V=P+q+z-U,E=T-l.hFront+(s>0?B/s:0),C=A-l.hRear+(c>0?V/c:0);return{c:_,downFront:F,downRear:P,drag:I,rF:E,rR:C,norm:Math.hypot(E,C)}},y=(T,A,_=!1)=>{let F=a.slopes(T,A,_,n.yawDeg,n.rollDeg),P=s>0?u*m/s:0,I=c>0?u*m/c:0;return[[P*(F.clFront.hFront-p*F.cd.hFront),P*(F.clFront.hRear-p*F.cd.hRear)],[I*(F.clRear.hFront+p*F.cd.hFront),I*(F.clRear.hRear+p*F.cd.hRear)]]},v=l.hFront,k=l.hRear,x=b(v,k),S=0;for(;x.norm>=rq&&S<Qde;){S++;let T=y(v,k),A=s>0?f/s:0,_=c>0?f/c:0,F=jm(e,i,h(v,k)),P=s>0?F/s:0,I=c>0?F/c:0,z=1+T[0][0]-A*d.front-P,N=T[0][1]-A*d.rear+P,q=T[1][0]+_*d.front+I,U=1+T[1][1]+_*d.rear-I,B=z*U-N*q,V,E;Math.abs(B)>1e-9?(V=-(U*x.rF-N*x.rR)/B,E=-(-q*x.rF+z*x.rR)/B):(V=-.5*x.rF,E=-.5*x.rR);let C=Math.max(1,Math.abs(V)/nq,Math.abs(E)/nq);V/=C,E/=C;let $=1;for(let L=0;L<6;L++){let j=b(v+$*V,k+$*E);if(j.norm<=x.norm||L===5){v+=$*V,k+=$*E,x=j;break}$*=.5}}let R=y(v,k,!0),w=2+R[0][0]+R[1][1],M=(1+R[0][0])*(1+R[1][1])-R[0][1]*R[1][0];return{v:r,axG:o,hFront:v,hRear:k,cgHeight:h(v,k),cgForward:e.wheelbase>0?h(v,k)*g(v,k)/e.wheelbase:0,cgNoseLoad:jm(e,i,h(v,k))*g(v,k),clFront:x.c.clFront,clRear:x.c.clRear,cd:x.c.cd,area:m,downforce:x.downFront+x.downRear,drag:x.drag,downFront:x.downFront,downRear:x.downRear,gain:tpe(R),stable:M>0&&w>0,converged:x.norm<rq,iterations:S,clampedRide:x.c.clampedRide,yawDeg:n.yawDeg,rollDeg:n.rollDeg,clampedAttitude:x.c.clampedAttitude}}function tpe(e){let t=e[0][0]+e[1][1],r=e[0][0]*e[1][1]-e[0][1]*e[1][0],o=t*t-4*r;if(o>=0){let n=Math.sqrt(o);return Math.max(Math.abs((t+n)/2),Math.abs((t-n)/2))}return Math.sqrt(r)}function Um(e,t,r=0,o){let n=gi(e,t,r,o);return n?{downforce:n.downforce,drag:n.drag,downFront:n.downFront,downRear:n.downRear}:e.aero?Zc(e.aero,t):{downforce:0,drag:0,downFront:0,downRear:0}}function rpe(e,t,r,o){let n=Zc(t,r),a=Lt(e),i=Bm(t,e.wheelbase),s=e.wheelbase>0?n.drag*t.copHeight/e.wheelbase:0,c=Zh(e,a,o,n.downFront-s,n.downRear+s),l=n.downforce;return{v:r,axG:o,hFront:i.hFront-c.dropFront,hRear:i.hRear-c.dropRear,cgHeight:c.height,cgForward:c.forward,cgNoseLoad:c.noseLoad,clFront:t.cl*t.copLongFront,clRear:t.cl*(1-t.copLongFront),cd:t.cw,area:t.area,downforce:l,drag:n.drag,downFront:n.downFront,downRear:n.downRear,gain:0,stable:!0,converged:!0,iterations:0,clampedRide:!1,yawDeg:0,rollDeg:0,clampedAttitude:!1}}function Xh(e,t,r=0,o){let n=gi(e,t,r,o);return n||(e.aero?rpe(e,e.aero,t,r):null)}function Rx(e,t=0,r=0,o,n){if(e.aero&&t>0){if(e.aero.model){let s=gi(e,t,r,o);return{height:s.cgHeight,forward:s.cgForward,noseLoad:s.cgNoseLoad}}let a=Zc(e.aero,t),i=e.wheelbase>0?a.drag*e.aero.copHeight/e.wheelbase:0;return Zh(e,n??Lt(e),r,a.downFront-i,a.downRear+i)}return r===0?{height:e.cgHeight,forward:0,noseLoad:0}:Zh(e,n??Lt(e),r,0,0)}function jE(e,t,r=0){let o=[];for(let n of t){let a=Xh(e,n,r);a&&o.push(a)}return o}var aq=[0,1,0],BE=[0,0,1],Ee=(e,t)=>[e[0]+t[0],e[1]+t[1],e[2]+t[2]],se=(e,t)=>[e[0]-t[0],e[1]-t[1],e[2]-t[2]],ke=(e,t)=>[e[0]*t,e[1]*t,e[2]*t],UE=e=>[-e[0],-e[1],-e[2]],xe=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],Ve=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]],npe=e=>xe(e,e),Ts=e=>Math.sqrt(xe(e,e)),Jh=(e,t)=>npe(se(e,t)),yt=(e,t)=>Ts(se(e,t)),we=e=>{let t=Ts(e);return t<1e-12?[0,0,0]:[e[0]/t,e[1]/t,e[2]/t]};var Ps=(e,t,r)=>{let o=we(r),n=se(e,t);return Ee(t,ke(o,xe(n,o)))},iq=(e,t,r)=>yt(e,Ps(e,t,r));var ape=1e-6;function ipe(e){if(e<ape){let o=e*e;return[1-o/6,.5-o/24]}let t=Math.sin(e),r=Math.cos(e);return[t/e,(1-r)/(e*e)]}function Br(e,t){let r=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);if(r<1e-14)return t;let[o,n]=ipe(r),a=Ve(e,t),i=Ve(e,a);return Ee(t,Ee(ke(a,o),ke(i,n)))}function oo(e,t,r){let o=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);if(o<1e-14)return e;let n=[t[0]/o,t[1]/o,t[2]/o];return Br(ke(n,r),e)}function wa(e,t){let r=t.length,o=e.map(a=>a.slice()),n=t.slice();return cq(o,n,r,new Array(r).fill(0))}function sq(e,t,r){return cq(e,t,t.length,r)}function cq(e,t,r,o){let n=1/0,a=0;for(let i=0;i<r;i++){let s=i,c=Math.abs(e[i][i]);for(let u=i+1;u<r;u++){let m=Math.abs(e[u][i]);m>c&&(c=m,s=u)}if(c<1e-14){for(let u=0;u<r;u++)o[u]=NaN;return{x:o,condProxy:1/0,singular:!0}}if(n=Math.min(n,c),a=Math.max(a,c),s!==i){let u=e[i];e[i]=e[s],e[s]=u;let m=t[i];t[i]=t[s],t[s]=m}let l=e[i][i];for(let u=i+1;u<r;u++){let m=e[u][i]/l;if(m!==0){for(let p=i;p<r;p++)e[u][p]-=m*e[i][p];t[u]-=m*t[i]}}}for(let i=r-1;i>=0;i--){let s=t[i];for(let c=i+1;c<r;c++)s-=e[i][c]*o[c];o[i]=s/e[i][i]}return{x:o,condProxy:a/n,singular:!1}}var lq=e=>{let t=0;for(let r of e)t=Math.max(t,Math.abs(r));return t},uq=e=>{let t=0;for(let r of e)t+=r*r;return t},spe=Math.sqrt(Number.EPSILON);function mq(e,t,r={}){let o=r.maxIter??60,n=r.tol??1e-10,a=t.length,i=r.scales??new Array(a).fill(1),s=t.slice(),c=e(s),l=lq(c),u=uq(c),m=.001,p=1,d=c.length,f=Array.from({length:d},()=>new Array(a).fill(0)),h=Array.from({length:a},()=>new Array(a).fill(0)),g=Array.from({length:a},()=>new Array(a).fill(0)),b=new Array(a).fill(0),y=new Array(a).fill(0),v=new Array(a).fill(0),k=new Array(a).fill(0),x=new Array(a).fill(0);for(let S=0;S<o;S++){if(l<n)return{x:s,residualNorm:l,iterations:S,converged:!0,condProxy:p};for(let T=0;T<a;T++){let A=spe*Math.max(Math.abs(s[T]),i[T]);for(let F=0;F<a;F++)k[F]=s[F];k[T]+=A;let _=e(k);for(let F=0;F<d;F++)f[F][T]=(_[F]-c[F])/A}let R=0;for(let T=0;T<a;T++){for(let _=0;_<a;_++){let F=0;for(let P=0;P<d;P++)F+=f[P][T]*f[P][_];h[T][_]=F}let A=0;for(let _=0;_<d;_++)A+=f[_][T]*c[_];b[T]=A,R=Math.max(R,h[T][T])}let w=Math.max(R,1e-9),M=!1;for(let T=0;T<18;T++){let A=m*w;for(let F=0;F<a;F++){let P=h[F],I=g[F];for(let z=0;z<a;z++)I[z]=F===z?P[z]+A:P[z];y[F]=-b[F]}let _=sq(g,y,v);if(p=Math.max(p,_.condProxy),!_.singular){for(let I=0;I<a;I++)x[I]=s[I]+v[I];let F=e(x),P=uq(F);if(P<u){for(let I=0;I<a;I++)s[I]=x[I];c=F,u=P,l=lq(c),m=Math.max(m*.3,1e-12),M=!0;break}}m=Math.min(m*4,1e12)}if(!M)break}return{x:s,residualNorm:l,iterations:o,converged:l<n,condProxy:p}}function Qh(e,t,r,o){let n=e*e+t*t,a=Math.sqrt(n);if(!(a>1e-12*o))return{c1:1,s1:0,c2:1,s2:0,margin:0,ok:!1,free:!0};let i=Math.abs(r),s=1-i/a;if(s<0){let l=r>=0?1:-1,u=l*e/a,m=l*t/a;return{c1:u,s1:m,c2:u,s2:m,margin:s,ok:s>=-1e-12,free:!1}}let c=Math.sqrt((a-i)*(a+i));return{c1:(e*r-t*c)/n,s1:(t*r+e*c)/n,c2:(e*r+t*c)/n,s2:(t*r-e*c)/n,margin:s,ok:!0,free:!1}}function GE(e,t){return[e[0]*t[0]-e[1]*t[1]-e[2]*t[2]-e[3]*t[3],e[0]*t[1]+e[1]*t[0]+e[2]*t[3]-e[3]*t[2],e[0]*t[2]-e[1]*t[3]+e[2]*t[0]+e[3]*t[1],e[0]*t[3]+e[1]*t[2]-e[2]*t[1]+e[3]*t[0]]}var dq=e=>[e[0],-e[1],-e[2],-e[3]];function pq(e,t){let[r,o,n,a]=e,i=2*(n*t[2]-a*t[1]),s=2*(a*t[0]-o*t[2]),c=2*(o*t[1]-n*t[0]);return[t[0]+r*i+(n*c-a*s),t[1]+r*s+(a*i-o*c),t[2]+r*c+(o*s-n*i)]}function fq(e,t){let r=e[0]*t[0]+e[1]*t[1]+e[2]*t[2];if(1+r<1e-14){let n=Math.abs(e[0])<.6?[1,0,0]:[0,1,0],a=e[1]*n[2]-e[2]*n[1],i=e[2]*n[0]-e[0]*n[2],s=e[0]*n[1]-e[1]*n[0],c=Math.hypot(a,i,s);return[0,a/c,i/c,s/c]}let o=Math.sqrt(2*(1+r));return[(1+r)/o,(e[1]*t[2]-e[2]*t[1])/o,(e[2]*t[0]-e[0]*t[2])/o,(e[0]*t[1]-e[1]*t[0])/o]}function hq(e,t,r){let o,n;return t>=0?(o=Math.sqrt((1+t)/2),n=r/(2*o)):(n=(r>=0?1:-1)*Math.sqrt((1-t)/2),o=r/(2*n)),[o,n*e[0],n*e[1],n*e[2]]}function qE(e,t,r){let o=e[0],n=e[1],a=e[2],i=t[0],s=t[1],c=t[2],l=r[0],u=r[1],m=r[2],p=o+s+m;if(p>=o&&p>=s&&p>=m){let h=Math.sqrt(1+p),g=.5/h;return[.5*h,(c-u)*g,(l-a)*g,(n-i)*g]}if(o>=s&&o>=m){let h=Math.sqrt(1+o-s-m),g=.5/h;return[(c-u)*g,.5*h,(i+n)*g,(l+a)*g]}if(s>=m){let h=Math.sqrt(1-o+s-m),g=.5/h;return[(l-a)*g,(i+n)*g,.5*h,(u+c)*g]}let d=Math.sqrt(1-o-s+m),f=.5/d;return[(n-i)*f,(l+a)*f,(u+c)*f,.5*d]}function gq(e){let t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);if(t===0)return[1,0,0,0];let r=Math.sin(t/2)/t;return[Math.cos(t/2),r*e[0],r*e[1],r*e[2]]}function bq(e){let[t,r,o,n]=e;t<0&&(t=-t,r=-r,o=-o,n=-n);let a=Math.sqrt(r*r+o*o+n*n);if(a===0)return[0,0,0];let i=2*Math.atan2(a,t)/a;return[i*r,i*o,i*n]}function cpe(e){let t=Math.abs(e[0])<.6?[1,0,0]:[0,1,0],r=we(Ve(e,t));return[r,Ve(e,r)]}function lpe(e){let t=e.hardpoints,r=we(se(t.damperChassis,t.pushrodOuter)),[o,n]=cpe(r);return{top:t.damperChassis,lower0:t.pushrodOuter,axis0:r,e1:o,e2:n}}function HE(e){let t=e.hardpoints,r=t.wheelCenter,o=we(se(t.ucaRear,t.ucaFront)),n=se(t.uprightUpper,t.ucaFront),a=xe(n,o),i=se(n,ke(o,a)),s=xe(i,i),c=we(se(t.lcaRear,t.lcaFront)),l=se(t.uprightLower,t.lcaFront),u=Jh(t.tieOuter,t.tieInner);return{c0:r,ucaFront:t.ucaFront,ucaDir:o,ubj0:t.uprightUpper,ubjAxial0:a,ubjRadius2:s,lcaFront:t.lcaFront,lcaDir:c,lbj0:t.uprightLower,lbjRel0:l,tro0:t.tieOuter,tieInner0:t.tieInner,tieLen2:u,rackAxis:we(e.config.rackAxis),steerMovesRack:e.config.steerMode==="rack",ubjRadiusRef:Math.max(1,2*Math.sqrt(s)),tieLenRef:Math.max(1,2*Math.sqrt(u)),...e.config.layout==="mcpherson"?{strut:lpe(e)}:{}}}function ao(e,t,r){let o=[t[3],t[4],t[5]],n=[t[0],t[1],t[2]],a=se(r,e.c0);return Ee(Ee(Br(o,a),e.c0),n)}function KE(e,t){return Ee(e.lcaFront,oo(e.lbjRel0,e.lcaDir,t))}function Xc(e,t){return e.steerMovesRack?Ee(e.tieInner0,ke(e.rackAxis,t)):e.tieInner0}function WE(e,t,r,o){let n=ao(e,t,e.lbj0),a=KE(e,r),i=n[0]-a[0],s=n[1]-a[1],c=n[2]-a[2],l,u;if(e.strut){let f=e.strut,h=[t[3],t[4],t[5]],g=se(f.top,ao(e,t,f.lower0));l=xe(g,Br(h,f.e1)),u=xe(g,Br(h,f.e2))}else{let f=ao(e,t,e.ubj0),h=se(f,e.ucaFront),g=xe(h,e.ucaDir),b=se(h,ke(e.ucaDir,g));l=g-e.ubjAxial0,u=(xe(b,b)-e.ubjRadius2)/e.ubjRadiusRef}let m=ao(e,t,e.tro0),p=Xc(e,o),d=(Jh(m,p)-e.tieLen2)/e.tieLenRef;return[i,s,c,l,u,d]}var eg=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),xx=e=>{let t=eg(e);return[e[0]/t,e[1]/t,e[2]/t]},upe=(e,t)=>se(e,ke(t,xe(e,t))),YE=e=>xx(Ve(e,Math.abs(e[0])<.6?[1,0,0]:[0,1,0]));function mpe(e,t){let r=e.ucaDir,o=Ee(e.ucaFront,ke(r,e.ubjAxial0)),n=Math.sqrt(e.ubjRadius2),a=upe(se(e.ubj0,e.ucaFront),r),i=eg(a)>1e-9?xx(a):YE(r),s=Ve(r,i),c=se(e.ubj0,e.lbj0),l=xe(c,c);if(!(l>1e-18))return"free";let u=se(o,t),m=xe(u,u),p=Qh(2*n*xe(i,u),2*n*xe(s,u),l-m-n*n,2*n*Math.sqrt(m));if(p.free)return"free";let d=xx(c),f=(h,g)=>{let b=Ee(o,Ee(ke(i,n*h),ke(s,n*g))),y=xx(se(b,t));return{q1:fq(d,y),k:y,margin:p.margin,ok:p.ok}};return p.margin>0?[f(p.c1,p.s1),f(p.c2,p.s2)]:[f(p.c1,p.s1)]}function dpe(e,t,r){let o=t.axis0,n=Ee(t.lower0,ke(o,xe(se(e.lbj0,t.lower0),o))),a=se(n,e.lbj0),i=eg(a),s=i>1e-9?ke(a,1/i):YE(o),c=se(t.top,r),l=eg(c);if(!(l>1e-9))return"free";let u=ke(c,1/l),m=i/l,p=1-m,d=p>=0?Math.sqrt((1-m)*(1+m)):0,f=YE(u),h=g=>{let b=g*d,y=Ee(ke(u,b),ke(f,Math.min(m,1))),v=se(ke(u,Math.min(m,1)),ke(f,b));return{q1:GE(qE(v,y,Ve(v,y)),dq(qE(s,o,Ve(s,o)))),k:u,margin:p,ok:p>=0}};return p>0?[h(1),h(-1)]:[h(1)]}function ppe(e,t,r,o){let{k:n}=o,a=pq(o.q1,se(e.tro0,e.lbj0)),i=xe(a,n),s=se(a,ke(n,i)),c=eg(s);if(!(c>1e-9))return"free";let l=ke(s,1/c),u=Ve(n,l),m=Ee(t,ke(n,i)),p=se(m,r),d=xe(p,p),f=Qh(2*c*xe(p,l),2*c*xe(p,u),e.tieLen2-d-c*c,2*c*Math.sqrt(d));if(f.free)return"free";let h=(b,y)=>({q:GE(hq(n,b,y),o.q1)});return{roots:f.margin>0?[h(f.c1,f.s1),h(f.c2,f.s2)]:[h(f.c1,f.s1)],margin:f.margin,ok:f.ok}}function yq(e,t,r,o=[0,0,0,0,0,0]){let n=KE(e,t),a=Xc(e,r),i=gq([o[3],o[4],o[5]]),s=h=>Math.abs(h[0]*i[0]+h[1]*i[1]+h[2]*i[2]+h[3]*i[3]),c=e.strut?dpe(e,e.strut,n):mpe(e,n);if(c==="free")return{x:o.slice(),converged:!1,margin:0,free:!0};let l=null,u=null;for(let h of c){let g=ppe(e,n,a,h);if(g==="free")return{x:o.slice(),converged:!1,margin:0,free:!0};let b=Math.min(h.margin,g.margin),y=g.ok&&h.ok;for(let{q:v}of g.roots){let k=s(v);y&&(!l||k>l.near)&&(l={q:v,margin:b,near:k}),!y&&(!u||k>u.near)&&(u={q:v,margin:b,near:k})}}let{q:m,margin:p}=l??u,d=bq(m),f=se(se(n,e.c0),Br(d,se(e.lbj0,e.c0)));return{x:[f[0],f[1],f[2],d[0],d[1],d[2]],converged:l!==null,margin:p,free:!1}}function Sq(e){let t=we(se(e.rockerPivotB,e.rockerPivotA));return{pivotA:e.rockerPivotA,axis:t,rprRel0:se(e.rockerToPushrod,e.rockerPivotA),rdmRel0:se(e.rockerToDamper,e.rockerPivotA),damperChassis:e.damperChassis,rodLen2:Jh(e.pushrodOuter,e.rockerToPushrod),damperLen0:yt(e.rockerToDamper,e.damperChassis)}}var fpe=(e,t)=>Ee(e.pivotA,oo(e.rprRel0,e.axis,t)),ZE=(e,t)=>Ee(e.pivotA,oo(e.rdmRel0,e.axis,t));function Gm(e,t){return{pushrod:fpe(e,t),damper:ZE(e,t)}}function kq(e,t,r=0){let o=xe(e.rprRel0,e.axis),n=se(e.rprRel0,ke(e.axis,o)),a=Ve(e.axis,n),i=se(Ee(e.pivotA,ke(e.axis,o)),t),s=xe(n,n),c=xe(i,i),l=Qh(2*xe(i,n),2*xe(i,a),e.rodLen2-c-s,2*Math.sqrt(s*c));if(l.free){let d=Math.abs(e.rodLen2-c-s)<=1e-9*e.rodLen2;return{phi:r,damperLength:yt(ZE(e,r),e.damperChassis),converged:d,margin:0}}let u=vq(Math.atan2(l.s1,l.c1),r),m=vq(Math.atan2(l.s2,l.c2),r),p=Math.abs(m-r)<Math.abs(u-r)?m:u;return{phi:p,damperLength:yt(ZE(e,p),e.damperChassis),converged:l.ok,margin:l.margin}}function vq(e,t){let r=2*Math.PI;return e+r*Math.round((t-e)/r)}function Rq(e,t,r,o){return Ee(t,Br(ke(we(r),o),se(e,t)))}function xq(e,t,r,o){let n=we(o),a=p=>{let d=se(p,r);return se(d,ke(n,xe(d,n)))},i=a(e),s=a(t),c=Math.hypot(i[0],i[1],i[2]),l=Math.hypot(s[0],s[1],s[2]);if(c<1e-9||l<1e-9)return 0;let u=Math.min(1,Math.max(-1,xe(i,s)/(c*l))),m=xe(Ve(i,s),n)/(c*l);return Math.atan2(m,u)}function wq(e,t,r,o){return Ee(t,Br(ke(we(r),o),se(e,t)))}var wx=180/Math.PI,hpe=(e,t,r)=>Math.max(t,Math.min(r,e)),Mq=[NaN,NaN,NaN];function tg(e){let t=we(e.spinAxis),r=we(se(e.uprightUpper,e.uprightLower)),o=-Math.asin(hpe(t[2],-1,1))*wx,n=Math.atan2(t[0],t[1])*wx,a=Math.atan2(-r[0],r[2])*wx,i=Math.atan2(-r[1],r[2])*wx,s=we(Ee([0,0,-1],ke(t,t[2]))),c=Ee(e.wheelCenter,ke(s,e.loadedRadius)),l=e.patchShift?[c[0]+e.patchShift.x,c[1]+e.patchShift.y,c[2]]:c,u=e.uprightLower,m=Math.abs(r[2])>1e-9,p=M=>Ee(u,ke(r,(M-u[2])/r[2])),d=m?p(l[2]):Mq,f=m?p(e.wheelCenter[2]):Mq,h=l[1]-d[1],g=d[0]-l[0],b=we(Ve(t,[0,0,1])),y=Ve([0,0,1],b),v=se(l,d),k=xe(v,y),x=-xe(v,b),S=e.wheelCenter[1]-f[1],R=f[0]-e.wheelCenter[0],w=iq(e.tieOuter,u,r);return{camber:o,toe:n,caster:a,kpi:i,scrubRadius:h,mechanicalTrail:g,scrubAtWheel:k,trailAtWheel:x,kingpinOffset:S,casterOffset:R,steeringArm:w,contactPatch:l,kingpinGround:d,kingpinAtHub:f}}function sr(e){return{corner:e,inv:HE(e),rocker:Sq(e.hardpoints)}}var gpe=[20,20,20,.2,.2,.2];function Aq(e,t,r,o=[0,0,0,0,0,0]){let n=yq(e,t,r,o);if(!n.free)return n;let a=bpe(e,t,r,o);return{x:a.x,converged:a.converged,margin:0}}function bpe(e,t,r,o=[0,0,0,0,0,0]){return mq(n=>WE(e,n,t,r),o,{scales:gpe,tol:1e-10,maxIter:40})}var ype=.01,Mx=1.2,Sr=e=>e.ok?e.state:null,Pr=e=>e.ok?e.state:e.nearest;function st(e,t,r,o,n){let a=0,i=zt(e,a,r,o,n);if(Math.abs(i.travel-t)<1e-4)return _q(i,t,!1);let c=(zt(e,.02,r,XE(i),n).travel-i.travel)/.02;(!Number.isFinite(c)||Math.abs(c)<1e-6)&&(c=1);let l=p=>Math.max(-Mx,Math.min(Mx,p)),u=l((t-i.travel)/c),m=zt(e,u,r,XE(i),n);for(let p=0;p<12&&!(Math.abs(m.travel-t)<1e-4);p++){let d=m.travel-i.travel,f=Math.abs(d)<1e-9?u:u-(m.travel-t)*((u-a)/d);a=u,i=m,u=l(f),m=zt(e,u,r,XE(i),n)}return _q(m,t,Math.abs(u)===Mx)}function _q(e,t,r){let o=e.travel-t,n=Math.abs(o)<=ype,a=r&&!n;return e.converged&&n?{ok:!0,reached:!0,travelMiss:o,clamped:!1,state:e}:{ok:!1,why:e.converged?"unreached":"unconverged",reached:n,travelMiss:o,clamped:a,nearest:e}}function XE(e){return{q:[e.pose.t[0],e.pose.t[1],e.pose.t[2],e.pose.omega[0],e.pose.omega[1],e.pose.omega[2]],phi:e.points.rockerAngle}}function vpe(e,t,r,o,n){switch(e){case"upright":return ao(t,r,n.pushrodOuter);case"upperArm":{let a=ao(t,r,t.ubj0),i=xq(t.ubj0,a,t.ucaFront,t.ucaDir);return wq(n.pushrodOuter,t.ucaFront,t.ucaDir,i)}default:return Rq(n.pushrodOuter,t.lcaFront,t.lcaDir,o)}}function zt(e,t,r,o,n){let{inv:a,corner:i}=e,s=o?.q??[0,0,0,0,0,0],c=Aq(a,t,r,s),l=c.x,u=[l[3],l[4],l[5]],m={t:[l[0],l[1],l[2]],omega:u},p=i.hardpoints,d=i.config,f=a.strut,h=f?f.top:ao(a,l,p.uprightUpper),g=ao(a,l,p.uprightLower),b=ao(a,l,p.tieOuter),y=ao(a,l,p.wheelCenter),v=we(Br(u,d.spinAxis)),k=vpe(f?"upright":d.pushrodAttach,a,l,t,p),x=f?f.top:p.damperChassis,S=f||d.actuation==="direct"?{phi:0,damperLength:yt(k,x),converged:!0,margin:1}:kq(e.rocker,k,o?.phi??0),R=tg({uprightUpper:h,uprightLower:g,wheelCenter:y,spinAxis:v,tieOuter:b,loadedRadius:n?.loadedRadius??d.loadedRadius,patchShift:n?.patchShift});return{pose:m,beta:t,travel:l[2],steer:r,points:{uprightUpper:h,uprightLower:g,tieOuter:b,wheelCenter:y,pushrodOuter:k,spinAxis:v,contactPatch:R.contactPatch,kingpinGround:R.kingpinGround,kingpinAtHub:R.kingpinAtHub,rockerAngle:S.phi,damperLength:S.damperLength},metrics:{camber:R.camber,toe:R.toe,caster:R.caster,kpi:R.kpi,scrubRadius:R.scrubRadius,mechanicalTrail:R.mechanicalTrail,scrubAtWheel:R.scrubAtWheel,trailAtWheel:R.trailAtWheel,kingpinOffset:R.kingpinOffset,casterOffset:R.casterOffset,steeringArm:R.steeringArm,damperLength:S.damperLength},converged:c.converged&&S.converged,margin:Math.min(c.margin,S.margin)}}var qm=e=>e==="FL"||e==="FR"?"front":"rear",Tq=e=>e==="FL"||e==="RL"?"left":"right";function Ut(e,t){return e.corners?.[t]??Spe(e[qm(t)],Tq(t))}function Pq(e){let t=e.config.springSplit;return e.config.actuation==="decoupled"||t===void 0||!Number.isFinite(t)||Math.abs(t)>=1?0:t}var Cq=new WeakMap;function Spe(e,t){let r=Pq(e);if(r===0)return e;let o=Cq.get(e);if(!o){let n=a=>{let{springSplit:i,...s}=e.config;return{...e,config:{...s,springRate:e.config.springRate*a},...e.measured?{measured:{...e.measured,springRate:e.measured.springRate*a}}:{}}};o={left:n(1-r),right:n(1+r)},Cq.set(e,o)}return o[t]}var qo=["FL","FR","RL","RR"],Rn=e=>2*e.hardpoints.wheelCenter[1],io=(e,t)=>t?Rn(Ut(e,"FL"))/2+Rn(Ut(e,"FR"))/2:Rn(Ut(e,"RL"))/2+Rn(Ut(e,"RR"))/2;function Zt(e,t){let r=e==="FL"||e==="FR";return{axleX:r?t.frontAxleX:t.frontAxleX-t.wheelbase,sideSign:e==="FR"||e==="RR"?1:-1,isFront:r}}function Nn(e,t){return[t.axleX+e[0],t.sideSign*e[1],e[2]]}function bi(e,t){return[e[0],t.sideSign*e[1],e[2]]}function Fs(e){return e.frontAxleX-e.wheelbase/2}function JE(e,t,r){return t[2]+e.heave+(t[0]-r)*Math.sin(e.pitch)-t[1]*Math.sin(e.roll)}function $s(e,t,r,o){let n=Zt(e,t),a=(o?io(o,n.isFront):n.isFront?t.trackFront:t.trackRear)/2,i=n.sideSign*a,s=n.axleX-Fs(t),c=-r.heave-s*Math.sin(r.pitch)+i*Math.sin(r.roll),l=n.isFront?n.sideSign*r.steer:0;return{travel:c,steer:l}}var kpe={travelMin:-40,travelMax:40,steps:41,steer:0};function rg(e){return{q:[e.pose.t[0],e.pose.t[1],e.pose.t[2],e.pose.omega[0],e.pose.omega[1],e.pose.omega[2]],phi:e.points.rockerAngle}}function Xt(e,t={}){let r={...kpe,...t},o=sr(e);return Hm(o,r)}function Hm(e,t){let r=t.steer,o=.01,n=zt(e,o,r),a=zt(e,-o,r),i=(n.travel-a.travel)/(2*o);(!Number.isFinite(i)||Math.abs(i)<1e-6)&&(i=1);let s=Math.max(Math.abs(t.travelMax),Math.abs(t.travelMin)),c=Math.min(1.2,1.5*s/Math.abs(i)),l=Math.max(20,t.steps*2),u=[],m=zt(e,0,r);u.push({beta:0,travel:m.travel,warm:rg(m),converged:m.converged});let p=rg(m);for(let v=1;v<=l;v++){let k=c*v/l,x=zt(e,k,r,p);p=rg(x),u.push({beta:k,travel:x.travel,warm:p,converged:x.converged})}p=rg(m);for(let v=1;v<=l;v++){let k=-c*v/l,x=zt(e,k,r,p);p=rg(x),u.push({beta:k,travel:x.travel,warm:p,converged:x.converged})}u.sort((v,k)=>v.beta-k.beta);let d=u[u.length-1].travel>=u[0].travel,f=!1;for(let v=1;v<u.length;v++){let k=u[v].travel-u[v-1].travel;(d&&k<-1e-6||!d&&k>1e-6)&&(f=!0)}let h=u.filter(v=>v.converged).map(v=>v.travel),g=h.length?[Math.min(...h),Math.max(...h)]:[0,0],b=h.length>0&&g[0]<=t.travelMin+1e-6&&g[1]>=t.travelMax-1e-6,y=[];for(let v=0;v<t.steps;v++){let k=t.steps===1?t.travelMin:t.travelMin+(t.travelMax-t.travelMin)*v/(t.steps-1),x=Rpe(u,k,d),S=xpe(u,x);y.push(zt(e,x,r,S))}return wpe(y,e.corner.config.actuation==="decoupled"?0:e.corner.config.springRate),{samples:y,covered:b,reach:g,fold:f,unconverged:y.filter(v=>!v.converged).length}}function Rpe(e,t,r){let o=r?e.slice():e.slice().reverse();if(t<=o[0].travel)return o[0].beta;if(t>=o[o.length-1].travel)return o[o.length-1].beta;for(let n=1;n<o.length;n++){let a=o[n-1],i=o[n];if(t>=Math.min(a.travel,i.travel)&&t<=Math.max(a.travel,i.travel)){let s=i.travel-a.travel,c=Math.abs(s)<1e-9?0:(t-a.travel)/s;return a.beta+c*(i.beta-a.beta)}}return o[o.length-1].beta}function xpe(e,t){let r=e[0],o=1/0;for(let n of e){let a=Math.abs(n.beta-t);a<o&&(o=a,r=n)}return r.warm}function QE(e,t,r){return r===0?(e[1]-e[0])/(t[1]-t[0]):r===e.length-1?(e[r]-e[r-1])/(t[r]-t[r-1]):(e[r+1]-e[r-1])/(t[r+1]-t[r-1])}function wpe(e,t){if(e.length<2)return;let r=e.map(i=>i.travel),o=e.map(i=>i.metrics.camber),n=e.map(i=>i.metrics.toe),a=e.map(i=>i.metrics.damperLength);for(let i=0;i<e.length;i++){let s=QE(o,r,i),c=QE(n,r,i),l=-QE(a,r,i);e[i].metrics.camberGain=s,e[i].metrics.bumpSteer=c,e[i].metrics.motionRatio=l,e[i].metrics.wheelRate=t*l*l}}var Is=e=>e!==void 0&&Number.isFinite(e)&&e>0;function Mpe(e){return e&&Is(e.helperRate)&&Is(e.helperTravel)?{rate:e.helperRate,travel:e.helperTravel}:null}function eL(e,t,r){let o=t/e;return r?o+Math.min(t/r.rate,r.travel):o}function ng(e,t,r,o){if(!(e>0)||!Number.isFinite(e)||!(t>0)||!Number.isFinite(t))return null;let n=Mpe(o),a=-eL(e,t,n),i=Km(r,o);return{rate:e,preload:t,helper:n,free:a,pull:null,droop:i.droop??a,droopStated:i.droop!==null,bump:i.bump,holdsLoad:!0}}function Km(e,t){if(!Number.isFinite(e))return{droop:null,bump:null};let r=Is(t?.extended)&&t.extended>e?t.extended:null,o=r!==null&&Is(t?.stroke)?r-t.stroke:null;return{droop:r!==null?e-r:null,bump:o!==null&&o<e?e-o:null}}function tL(e,t){if(!Number.isFinite(e))return[];let r=[],o=t?.extended,n=t?.stroke,a=Is(o)&&o>e?o:null;return Is(o)&&a===null&&r.push("extendedTooShort"),Is(n)&&(a===null?Is(o)||r.push("strokeWithoutExtended"):a-n>=e&&r.push("strokeTooShort")),r}function rL(e,t){if(!(e>0)||!Number.isFinite(e))return null;let r=Km(t.length0,t.coilover),o=t.free===-1/0||t.pull!==null&&t.pull>=t.free;if(o&&r.droop===null&&r.bump===null)return null;let n=o?-1/0:t.free;return{rate:e,preload:n===-1/0?0:-e*n,helper:null,free:n,pull:o?null:t.pull,droop:r.droop??-1/0,droopStated:r.droop!==null,bump:r.bump,holdsLoad:!1}}function _pe(e,t){let{rate:r,preload:o,helper:n}=e;if(!n)return t>e.free-1e-9?o+r*t:e.pull!==null&&t<e.pull+1e-9?r*(t-e.pull):0;let a=eL(r,o,n)+t;if(a<=0)return 0;let i=n.rate*n.travel;return a>=i/r+n.travel?o>=i?o+r*t:r*(a-n.travel):a*r*n.rate/(r+n.rate)}function Ape(e,t){let{rate:r,preload:o,helper:n}=e;if(!n)return t>e.free-1e-9||e.pull!==null&&t<e.pull+1e-9?r:0;let a=eL(r,o,n)+t;return a<=0?0:a>=n.rate*n.travel/r+n.travel?r:r*n.rate/(r+n.rate)}function Wm(e,t){let r=_pe(e,t),o=e.free;return e.holdsLoad&&t<o&&e.droop<o&&(r+=.001*e.rate*(Math.max(t,e.droop)-o)),t<e.droop&&(r+=1e3*e.rate*(t-e.droop)),e.bump!==null&&t>e.bump&&(r+=1e3*e.rate*(t-e.bump)),r}function nL(e,t){let r=Ape(e,t),o=e.free;return e.holdsLoad&&t<o&&t>e.droop&&(r+=.001*e.rate),t<e.droop&&(r+=1e3*e.rate),e.bump!==null&&t>e.bump&&(r+=1e3*e.rate),r}function oL(e){let t=e.free,r=[t,e.droop];return e.helper&&r.push(e.helper.rate*e.helper.travel/e.rate+e.helper.travel+t),e.bump!==null&&r.push(e.bump),e.pull!==null&&r.push(e.pull),[...new Set(r.filter(Number.isFinite))].sort((o,n)=>o-n)}function _x(e){return e.holdsLoad?Math.max(0,e.free-e.droop):0}var Ax={min:-60,max:60,steps:61},aL=e=>({travel:[e.min,e.max],force:[0,0],motionRatio:[0,0],spring:null}),Fq=new WeakMap;function Cpe(e,t){let r=Fq.get(e.corner);r||Fq.set(e.corner,r=new Map);let o=`${t.min}|${t.max}|${t.steps}`,n=r.get(o);return n||r.set(o,n=Hm(e,{travelMin:t.min,travelMax:t.max,steps:t.steps,steer:0})),n}function ag(e,t,r=Ax,o=e.corner.config.coilover){let n=e.corner.config;if(n.actuation==="decoupled")return aL(r);let a=Cpe(e,r),i=Ppe(e,n.springRate,a.samples),s=[];for(let h of a.samples){let g=h.metrics.motionRatio;!h.converged||g===void 0||!Number.isFinite(g)||!Number.isFinite(h.metrics.damperLength)||s.length>0&&h.travel<=s[s.length-1].t+1e-6||s.push({t:h.travel,L:h.metrics.damperLength,mr:g})}if(s.length<2)return aL(r);let c=$pe(s,0);if(!(Math.abs(c.mr)>1e-6))return aL(r);let l=t/c.mr,u=ng(i,l,c.L,o),m=u?Tpe(s,oL(u).map(h=>c.L-h)):s,p=m.map(h=>(u?Wm(u,c.L-h.L):l+i*(c.L-h.L))*h.mr-t),d=h=>h===null?null:m.find(g=>g.L===c.L-h)?.t??null,f=u?oL(u).map(d).filter(h=>h!==null):[];return{travel:m.map(h=>h.t),force:p,motionRatio:m.map(h=>h.mr),spring:{rate:i,preload:l,length0:c.L,law:u},...u?{stops:{droop:d(u.droop),bump:d(u.bump)}}:{},...f.length?{kinks:f}:{},length:m.map(h=>h.L)}}function iL(e,t){if(!e.spring)return null;let r=e.travel.length,o=e.length;if(o&&o.length===r&&r>=2){let i=Ma(e.travel,t),s=(t-e.travel[i])/(e.travel[i+1]-e.travel[i]);return e.spring.length0-(o[i]+s*(o[i+1]-o[i]))}if(r<2)return 0;let n=64,a=0;for(let i=0;i<n;i++){let s=t*i/n,c=t*(i+1)/n;a+=(og(e,s)+og(e,c))/2*(c-s)}return a}function Tpe(e,t){let r=[...e];for(let o of t)for(let n=0;n+1<e.length;n++){let a=e[n],i=e[n+1];if(a.L===o)break;if((a.L-o)*(i.L-o)>=0)continue;let s=(o-a.L)/(i.L-a.L);r.push({t:a.t+s*(i.t-a.t),L:o,mr:a.mr+s*(i.mr-a.mr)});break}return r.sort((o,n)=>o.t-n.t),r.filter((o,n)=>n===0||o.t>r[n-1].t+1e-6)}function Ppe(e,t,r){let o=e.corner.compliance?.links?.pushRod;if(o===void 0||!(o>0)||!Number.isFinite(o)||!(t>0))return t;let n=e.corner.config.actuation==="direct"?o:Fpe(e,o,r);return!(n>0)||!Number.isFinite(n)?t:t*n/(t+n)}function Fpe(e,t,r){let o;for(let m of r)m.converged&&(!o||Math.abs(m.travel)<Math.abs(o.travel))&&(o=m);if(!o)return t;let n=e.corner.hardpoints,a=Gm(e.rocker,o.points.rockerAngle),i=we(se(n.rockerPivotB,n.rockerPivotA)),s=(m,p)=>Math.abs(xe(i,Ve(se(m,n.rockerPivotA),we(se(p,m))))),c=s(a.pushrod,o.points.pushrodOuter),l=s(a.damper,n.damperChassis);if(!(l>1e-9)||!(c>1e-9))return t;let u=c/l;return t*u*u}function og(e,t){let r=e.travel.length;if(r===0)return 0;if(r===1)return e.motionRatio[0];let o=Ma(e.travel,t),n=(t-e.travel[o])/(e.travel[o+1]-e.travel[o]);return e.motionRatio[o]+n*(e.motionRatio[o+1]-e.motionRatio[o])}function yi(e,t,r){if(!e.spring)return Ho(e,t);let{rate:o,preload:n,length0:a,law:i}=e.spring,s=og(e,0),c=a-r;return(i?Wm(i,c):n+o*c)*og(e,t)-n*s}function $pe(e,t){let r=Ma(e.map(i=>i.t),t),o=e[r],n=e[r+1],a=(t-o.t)/(n.t-o.t);return{L:o.L+a*(n.L-o.L),mr:o.mr+a*(n.mr-o.mr)}}function Ma(e,t){let r=e.length;if(t<=e[0])return 0;if(t>=e[r-1])return r-2;let o=0,n=r-1;for(;n-o>1;){let a=o+n>>1;e[a]<=t?o=a:n=a}return o}function Ho(e,t){let r=e.travel.length;if(r===0)return 0;if(r===1)return e.force[0];let o=Ma(e.travel,t),n=(t-e.travel[o])/(e.travel[o+1]-e.travel[o]);return e.force[o]+n*(e.force[o+1]-e.force[o])}function Ym(e,t){let r=e.travel.length;if(r<3)return ig(e,t);let o=Ma(e.travel,t),n=(e.force[o+1]-e.force[o])/(e.travel[o+1]-e.travel[o]),a=s=>s===0||s===r-1||e.kinks?.includes(e.travel[s])?n:(e.force[s+1]-e.force[s-1])/(e.travel[s+1]-e.travel[s-1]),i=Math.max(0,Math.min(1,(t-e.travel[o])/(e.travel[o+1]-e.travel[o])));return a(o)+i*(a(o+1)-a(o))}function ig(e,t){if(e.travel.length<2)return 0;let o=Ma(e.travel,t);return(e.force[o+1]-e.force[o])/(e.travel[o+1]-e.travel[o])}function Nt(e,t,r){let o=e.hardpoints;switch(t.attach){case"upright":{let n=se(t.outer,o.wheelCenter);return Ee(Ee(Br(r.pose.omega,n),o.wheelCenter),r.pose.t)}case"lowerArm":{let n=we(se(o.lcaRear,o.lcaFront));return Ee(o.lcaFront,Br(ke(n,r.beta),se(t.outer,o.lcaFront)))}case"rocker":{let n=we(se(o.rockerPivotB,o.rockerPivotA));return Ee(o.rockerPivotA,oo(se(t.outer,o.rockerPivotA),n,r.points.rockerAngle))}}}function _a(e,t,r){return e.config.actuation==="decoupled"&&t.attach==="rocker"&&r==="coil"}function sL(e,t,r){return _a(e,t,r)?[t.inner[0],-t.inner[1],t.inner[2]]:t.inner}function Zm(e,t,r){let o=r.travelMin??-40,n=r.travelMax??40,a=r.steps??21;return cL(e,t,r.kind,Xt(e,{travelMin:o,travelMax:n,steps:a}).samples)}function cL(e,t,r,o){let n=we(se(t.outer,sL(e,t,r))),a=[],i=[],s=t.outer;for(let d of o)a.push(d.travel),i.push(xe(se(Nt(e,t,d),s),n));let c=a.length,l=new Array(c).fill(0);for(let d=0;d<c;d++){let f=Math.max(0,d-1),h=Math.min(c-1,d+1),g=a[h]-a[f];l[d]=g!==0?(i[h]-i[f])/g:0}let u=l[0];for(let d=1;d<c;d++)if(a[d]>=0){let f=a[d]-a[d-1],h=f!==0?(0-a[d-1])/f:0;u=l[d-1]+h*(l[d]-l[d-1]);break}let m=l.filter(d=>Math.abs(d)>1e-9).map(Math.sign),p=m.length>0&&m.some(d=>d!==m[0]);return{travel:a,ratio:l,linkTravel:i,atDesign:u,reverses:p}}function lL(e,t){let{travel:r,ratio:o}=e,n=r.length;if(n===0)return 0;if(t<=r[0])return o[0];if(t>=r[n-1])return o[n-1];let a=0,i=n-1;for(;i-a>1;){let c=a+i>>1;r[c]<=t?a=c:i=c}let s=(t-r[a])/(r[i]-r[a]);return o[a]+s*(o[i]-o[a])}function uL(e,t){let{travel:r,linkTravel:o}=e,n=r.length;if(n===0)return 0;if(t<=r[0])return o[0];if(t>=r[n-1])return o[n-1];let a=0,i=n-1;for(;i-a>1;){let c=a+i>>1;r[c]<=t?a=c:i=c}let s=(t-r[a])/(r[i]-r[a]);return o[a]+s*(o[i]-o[a])}var sg=e=>e.mount??{kind:"rockerToRocker"},Lq=e=>[e[0],0,e[2]],Ipe=e=>2*Math.abs(e[1]),Epe=(e,t)=>Math.hypot(e[0]-t[0],e[2]-t[2]);function Tx(e,t){return t.kind==="chassis"?Epe(e,t.anchor):Ipe(e)}function cg(e,t,r){if(r.kind==="chassis"){let i=[(e[0]+t[0])/2,(e[1]-t[1])/2,(e[2]+t[2])/2];return Math.hypot(i[0]-r.anchor[0],i[1],i[2]-r.anchor[2])}let o=e[0]-t[0],n=e[1]+t[1],a=e[2]-t[2];return Math.hypot(o,n,a)}function Jc(e,t,r={}){let o=r.travelMin??-40,n=r.travelMax??40,a=r.steps??21;return mL(e,t,Xt(e,{travelMin:o,travelMax:n,steps:a}).samples)}function mL(e,t,r){let o=sg(t),n=f=>Nt(e,{...t,inner:t.outer},r[f]),a=[],i=[],s=[];for(let f=0;f<r.length;f++)a.push(r[f].travel),s.push(Tx(n(f),o));let c=Iq(a,s,0);for(let f of s)i.push(c-f);let l=a.length,u=new Array(l).fill(0);for(let f=0;f<l;f++){let h=Math.max(0,f-1),g=Math.min(l-1,f+1),b=a[g]-a[h];u[f]=b!==0?(i[g]-i[h])/b:0}let m=$q(a,20),p=$q(a,-20),d=cg(n(m),n(p),o);return{travel:a,ratio:u,springTravel:i,atDesign:Iq(a,u,0),installedLength:c,rollSensitivity:c-d}}function $q(e,t){let r=0,o=1/0;for(let n=0;n<e.length;n++){let a=Math.abs(e[n]-t);a<o&&(o=a,r=n)}return r}function Iq(e,t,r){let o=e.length;if(o===0)return 0;if(r<=e[0])return t[0];if(r>=e[o-1])return t[o-1];for(let n=1;n<o;n++)if(e[n]>=r){let a=e[n]-e[n-1],i=a!==0?(r-e[n-1])/a:0;return t[n-1]+i*(t[n]-t[n-1])}return t[o-1]}function dL(e,t,r){let o={outer:t.outer,attach:t.attach},n=Xt(e,{travelMin:-5,travelMax:5,steps:3}),a=f=>Lq(Nt(e,{...o,inner:o.outer},n.samples[f])),i=a(1),s=a(2),c=a(0),l=s[0]-c[0],u=s[2]-c[2],m=Math.hypot(l,u),p=m>1e-9?[l/m,u/m]:[0,1],d=r??Math.max(80,2*Math.abs(t.outer[1])*.5);return[i[0]+p[0]*d,0,i[2]+p[1]*d]}function pL(e,t){let r=e.hardpoints,o=r.rockerPivotA,n=Eq(Cx(r.rockerPivotB,r.rockerPivotA)),a=Math.max(30,.6*Dq(Cx(r.rockerToDamper,o))),i=Cx(r.rockerToDamper,o),s=Eq(Cx(i,Lpe(n,Dpe(i,n)))),c=Npe(n,s),l=null,u=-1/0;for(let m=0;m<360;m+=10){let p=m*Math.PI/180,f={outer:[o[0]+a*(Math.cos(p)*s[0]+Math.sin(p)*c[0]),o[1]+a*(Math.cos(p)*s[1]+Math.sin(p)*c[1]),o[2]+a*(Math.cos(p)*s[2]+Math.sin(p)*c[2])],attach:"rocker"},h=t==="chassis"?{...f,mount:{kind:"chassis",anchor:dL(e,f)}}:f,g;try{g=Jc(e,h,{travelMin:-20,travelMax:20,steps:9})}catch{continue}let b=g.atDesign/(1+4*Math.abs(g.rollSensitivity));Number.isFinite(b)&&b>u&&(u=b,l=h)}return l??{outer:r.rockerToDamper,attach:"rocker"}}var Cx=(e,t)=>[e[0]-t[0],e[1]-t[1],e[2]-t[2]],Lpe=(e,t)=>[e[0]*t,e[1]*t,e[2]*t],Dpe=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],Dq=e=>Math.hypot(e[0],e[1],e[2]),Eq=e=>{let t=Dq(e)||1;return[e[0]/t,e[1]/t,e[2]/t]},Npe=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]];var fL=.001,Ope=e=>({outer:e.outer,inner:e.outer,attach:e.attach}),Gq=(e,t,r)=>(Tx(e.at0,t)-Tx(r,t))/2,zpe=(e,t)=>xe(se(t,e.pickup.at0),e.axis);function hL(e,t){let r=e.length;return t.map((o,n)=>{let a=Math.max(0,n-1),i=Math.min(r-1,n+1);return(t[i]-t[a])/(e[i]-e[a])})}function Nq(e,t){let r=[0,1,2].map(o=>hL(e,t.map(n=>n[o])));return t.map((o,n)=>[r[0][n],r[1][n],r[2][n]])}function gL(e){return{travel:e,heave:e.map(t=>t/2),heaveRatio:e.map(()=>.5),roll:[...e],rollRatio:e.map(()=>1)}}function Oq(e,t,r,o){let n=e.corner;if(!t.heave&&!t.roll)return{side:gL([o.min,o.max]),pickups:{}};let a=Pr(st(e,0,0)),i={};if(t.heave&&r){let h=Ope(t.heave);i.heave={corner:n,link:h,at0:Nt(n,h,a)}}if(t.roll){let h=t.roll;i.roll={pickup:{corner:n,link:h,at0:Nt(n,h,a)},axis:we(se(h.outer,sL(n,h,t.rollKind??"coil")))}}let s=t.roll&&_a(n,t.roll,t.rollKind??"coil")?{near:t.roll,far:{...t.roll,outer:t.roll.inner}}:null,c=Hm(e,{travelMin:o.min,travelMax:o.max,steps:o.steps,steer:0}),l=[],u=[],m=[],p=[],d=[];for(let h of c.samples)!h.converged||l.length>0&&h.travel<=l[l.length-1]+1e-6||(l.push(h.travel),u.push(i.heave&&r?Gq(i.heave,r,Nt(n,i.heave.link,h)):h.travel/2),m.push(i.roll?zpe(i.roll,Nt(n,i.roll.pickup.link,h)):h.travel),s&&(p.push(Nt(n,s.near,h)),d.push(Nt(n,s.far,h))));if(l.length<2)return{side:gL([o.min,o.max]),pickups:{}};let f={travel:l,heave:u,heaveRatio:hL(l,u),roll:m,rollRatio:hL(l,m)};return s&&(f.eyes={near:p,nearRatio:Nq(l,p),far:d,farRatio:Nq(l,d)}),{side:f,pickups:i}}function Px(e,t,r){let o=Ma(e,r);return t[o]+(r-e[o])/(e[o+1]-e[o])*(t[o+1]-t[o])}function zq(e,t,r){let o=Ma(e,r);return(t[o+1]-t[o])/(e[o+1]-e[o])}function Vt(e,t){return{h:Px(e.travel,e.heave,t),dh:Px(e.travel,e.heaveRatio,t),ddh:zq(e.travel,e.heaveRatio,t),r:Px(e.travel,e.roll,t),dr:Px(e.travel,e.rollRatio,t),ddr:zq(e.travel,e.rollRatio,t)}}function Vq(e,t,r,o){let n=Ma(e,o),a=e[n+1]-e[n],i=(o-e[n])/a,s=(u,m)=>[u[0]+i*(m[0]-u[0]),u[1]+i*(m[1]-u[1]),u[2]+i*(m[2]-u[2])],c=r[n],l=r[n+1];return{p:s(t[n],t[n+1]),d:s(c,l),dd:[(l[0]-c[0])/a,(l[1]-c[1])/a,(l[2]-c[2])/a]}}var bL=(e,t)=>Math.hypot(e[0]-t[0],e[1]+t[1],e[2]-t[2]);function lg(e,t){let r=e.side[0].eyes,o=e.side[1].eyes;if(!r||!o)return null;let n=Vq(e.side[0].travel,r.near,r.nearRatio,t[0]),a=Vq(e.side[1].travel,o.far,o.farRatio,t[1]),i=[n.p[0]-a.p[0],n.p[1]+a.p[1],n.p[2]-a.p[2]],s=Math.hypot(i[0],i[1],i[2]),c=[i[0]/s,i[1]/s,i[2]/s],l=n.d,u=[-a.d[0],a.d[1],-a.d[2]],m=[-a.dd[0],a.dd[1],-a.dd[2]],p=xe(c,l),d=xe(c,u),f=(xe(l,u)-p*d)/s;return{L:s,dL:[p,d],ddL:[[(xe(l,l)-p*p)/s+xe(c,n.dd),f],[f,(xe(u,u)-d*d)/s+xe(c,m)]]}}var qq=(e,t)=>e.bump!==null&&t>e.bump?e.rate*(t-e.bump):e.droop!==null&&t<e.droop?e.rate*(t-e.droop):0,Vpe=(e,t)=>e.bump!==null&&t>e.bump||e.droop!==null&&t<e.droop?e.rate:0;function ug(e,t,r,o,n=0){let a=e.rollStop;if(!a)return r;let i=lg(e,t);if(!i)return r;let s=qq(a,a.length0-(o??i.L+n));return s===0?r:[r[0]-s*i.dL[0],r[1]-s*i.dL[1]]}function Fx(e,t){let r=gL(e.travel);return t==="heave"?{...e,heave:r.heave,heaveRatio:r.heaveRatio}:{...e,roll:r.roll,rollRatio:r.rollRatio}}var $x=(e,t)=>e?e.law?Wm(e.law,t):e.preload+e.rate*t:0,jq=(e,t)=>e?e.law?nL(e.law,t):e.rate:0;function mg(e,t,r,o,n){let a=$x(e.heave,o),i=$x(e.roll,n);return[a*t.dh+i*t.dr,a*r.dh-i*r.dr]}var Bq=(e,t)=>Vt(e[0],t).h+Vt(e[1],t).h;function jpe(e,t){let r=e.gap>0?Bq(t,e.gap):0;return e.bothWays?{free:r,pull:e.gap>0?Bq(t,-e.gap):0}:{free:r,pull:null}}function Bpe(e,t,r){let o={...t,outer:t.inner},n=(u,m)=>{let p=Sr(st(e[0],u,0)),d=Sr(st(e[1],m,0));if(!p||!d)return NaN;let f=Nt(e[0].corner,t,p),h=Nt(e[1].corner,o,d);return Math.hypot(f[0]-h[0],f[1]+h[1],f[2]-h[2])},a=1,i=n(0,0),s=n(-a,a)-n(a,-a),c=Vt(r[0],a).r-Vt(r[1],-a).r-(Vt(r[0],-a).r-Vt(r[1],a).r),l=s/c;return Number.isFinite(i)&&i>0&&Number.isFinite(l)&&Math.abs(l)>fL?{length0:i,scale:l}:null}function Hq(e,t,r,o=Ax){let n=r.heave?sg(r.heave):void 0,a=Oq(e[0],r,n,o),i=e[1].corner===e[0].corner?a:Oq(e[1],r,n,o),s=[a.side,i.side],c=!!(a.pickups.heave&&i.pickups.heave),l=!!(a.pickups.roll&&i.pickups.roll),u=r.carriesLoad?void 0:r.heaveSeat,m=u?u.rate:(t[0].heaveRate+t[1].heaveRate)/2,p=(t[0].arbRate+t[1].arbRate)/2,d=s.map(F=>Vt(F,0));c&&!(Math.abs(d[0].dh+d[1].dh)>fL)&&(s=[Fx(s[0],"heave"),Fx(s[1],"heave")],c=!1),l&&!(Math.abs(d[0].dr+d[1].dr)>fL)&&(s=[Fx(s[0],"roll"),Fx(s[1],"roll")],l=!1),d=s.map(F=>Vt(F,0));let f=d[0].dh+d[1].dh,h=d[0].dr+d[1].dr,g=m>0?2*m/(f*f):0,b=p>0?2*p/(h*h):0,y=0,v=0;if(r.carriesLoad){let F=[t[0].springLoad,t[1].springLoad];if(g>0&&b>0){let P=-d[0].dh*d[1].dr-d[1].dh*d[0].dr;Math.abs(P)>1e-12&&(y=(-F[0]*d[1].dr-F[1]*d[0].dr)/P,v=(d[0].dh*F[1]-d[1].dh*F[0])/P)}else g>0?y=(F[0]+F[1])/f:b>0&&(v=(F[0]-F[1])/h)}let k={};if(c&&n){let F=[a.pickups.heave,i.pickups.heave];k.heave={pickups:F,mount:n,span0:cg(F[0].at0,F[1].at0,n)}}let x=k.heave?k.heave.span0:NaN,S=k.heave?r.coilover:void 0,R=r.carriesLoad?ng(g,y,x,S):u?rL(g,{...jpe(u,s),length0:x,coilover:S}):null,w=g>0?{rate:g,preload:y,...R?{law:R}:{}}:null;if(l&&(k.roll={pickups:[a.pickups.roll.pickup,i.pickups.roll.pickup],axes:[a.pickups.roll.axis,i.pickups.roll.axis]},r.roll&&_a(e[0].corner,r.roll,r.rollKind??"coil"))){let F=Bpe(e,r.roll,s);F&&(k.roll.unit=F)}let M=b>0?{rate:b,preload:v}:null,T={side:s,heave:w,roll:M,force0:[0,0],carriesLoad:r.carriesLoad,read:k},A=k.roll?.unit,_=A&&b>0&&s[0].eyes&&s[1].eyes?Km(A.length0,r.rollCoilover):null;return A&&_&&(_.droop!==null||_.bump!==null)&&(T.rollStop={length0:A.length0,rate:1e3*b/(A.scale*A.scale),..._}),T.force0=ug(T,[0,0],mg(T,d[0],d[1],d[0].h+d[1].h,d[0].r-d[1].r)),T}function dg(e,t,r){let o=Vt(e.side[0],t[0]),n=Vt(e.side[1],t[1]),a=r?ug(e,t,mg(e,o,n,o.h+n.h+r.heave,o.r-n.r+r.roll),void 0,r.unit):ug(e,t,mg(e,o,n,o.h+n.h,o.r-n.r));return[a[0]-e.force0[0],a[1]-e.force0[1]]}function yL(e,t,r){let o=Vt(e.side[0],t[0]),n=Vt(e.side[1],t[1]),a=r?o.h+n.h+r.heave:o.h+n.h,i=r?o.r-n.r+r.roll:o.r-n.r,s=jq(e.heave,a),c=jq(e.roll,i),l=$x(e.heave,a),u=$x(e.roll,i),m=s*o.dh*n.dh-c*o.dr*n.dr,p=[[s*o.dh*o.dh+l*o.ddh+c*o.dr*o.dr+u*o.ddr,m],[m,s*n.dh*n.dh+l*n.ddh+c*n.dr*n.dr-u*n.ddr]],d=e.rollStop,f=d?lg(e,t):null;if(!d||!f)return p;let h=d.length0-(r?f.L+r.unit:f.L),g=Vpe(d,h);if(g===0)return p;let b=qq(d,h),y=(k,x)=>g*f.dL[k]*f.dL[x]-b*f.ddL[k][x],v=m+y(0,1);return[[p[0][0]+y(0,0),v],[v,p[1][1]+y(1,1)]]}function vL(e,t,r){let o=yL(e,t);return o[r][0]+o[r][1]}function Upe(e,t,r){let o=e.read.heave;if(!o)return Vt(e.side[0],t[0]).h+Vt(e.side[1],t[1]).h;let[n,a]=o.pickups;return o.span0-cg(Nt(n.corner,n.link,r[0]),Nt(a.corner,a.link,r[1]),o.mount)}function Gpe(e,t,r){let o=e.read.roll;if(!o)return Vt(e.side[0],t[0]).r-Vt(e.side[1],t[1]).r;let n=a=>xe(se(Nt(o.pickups[a].corner,o.pickups[a].link,r[a]),o.pickups[a].at0),o.axes[a]);return n(0)-n(1)}function qpe(e,t){let r=e.read.roll;if(!e.rollStop||!r)return;let[o,n]=r.pickups;return bL(Nt(o.corner,o.link,t[0]),Nt(n.corner,{...n.link,outer:n.link.inner},t[1]))}function pg(e,t,r){let o=Vt(e.side[0],t[0]),n=Vt(e.side[1],t[1]),a=ug(e,t,mg(e,o,n,Upe(e,t,r),Gpe(e,t,r)),qpe(e,r));return[a[0]-e.force0[0],a[1]-e.force0[1]]}function SL(e,t,r,o){let n=Vt(e.side[0],r),a=Vt(e.side[1],r),i=e.read.heave,s=i?.pickups[t],c=i&&s&&o?2*Gq(s,i.mount,Nt(s.corner,s.link,o)):n.h+a.h,l=e.rollStop&&o?e.read.roll?.pickups[t]:void 0,u=l&&o?bL(Nt(l.corner,l.link,o),Nt(l.corner,{...l.link,outer:l.link.inner},o)):void 0;return ug(e,[r,r],mg(e,n,a,c,o?0:n.r-a.r),u)[t]-e.force0[t]}function kL(e,t,r,o){let n=Ym(e,r[o]);return t?.carriesLoad?n+vL(t,r,o):n}function Kq(e,t){return Vt(e.side[0],t[0]).h+Vt(e.side[1],t[1]).h}function Wq(e,t){return lg(e,t)?.L??null}function Ix(e,t){let r=e.side[0].travel,o=n=>Vt(e.side[0],n).h+Vt(e.side[1],n).h-t;for(let n=0;n+1<r.length;n++){let a=o(r[n]),i=o(r[n+1]);if(a===0)return r[n];if(a*i<0)return r[n]+a/(a-i)*(r[n+1]-r[n])}return o(r[r.length-1])===0?r[r.length-1]:null}function Yq(e,t){let r=e.rollStop;if(!r||!lg(e,[0,0]))return[];let o=e.side[1].travel,n=e.side[0].travel.filter(c=>-c>=o[0]&&-c<=o[o.length-1]),a=c=>r.length0-lg(e,[c,-c]).L-t,i=n.map(a),s=[];for(let c=0;c<n.length;c++){if(i[c]===0&&s.push(n[c]),c+1>=n.length||!(i[c]*i[c+1]<0))continue;let l=n[c],u=n[c+1],m=i[c];for(let p=0;p<50;p++){let d=(l+u)/2,f=a(d);m*f<=0?u=d:(l=d,m=f)}s.push((l+u)/2)}return s}var RL=e=>e==="FR"||e==="RR"?1:0,Ex=(e,t)=>e.elements?.[t==="FL"||t==="FR"?"front":"rear"]??null;var Zq=e=>Number.isFinite(e)&&e>0?1/e:0;var Xq=(e,t)=>{let r=e[0][0]*e[1][1]-e[0][1]*e[1][0];return Math.abs(r)>1e-14?[(t[0]*e[1][1]-t[1]*e[0][1])/r,(e[0][0]*t[1]-e[1][0]*t[0])/r]:null},Hpe=(e,t)=>[e[0][0]*t[0]+e[0][1]*t[1],e[1][0]*t[0]+e[1][1]*t[1]],Jq=1e-8,Kpe=40;function Wpe(e,t,r,o){return{force:(i,s)=>{if(r){let u=dg(r,i,o);return[Ho(t[0],i[0])+s[0]+u[0],Ho(t[1],i[1])+s[1]+u[1]]}let c=(i[0]+i[1])/2,l=(i[0]-i[1])/2;return[Ho(t[0],i[0])+s[0]+e[0].heaveRate*c+e[0].arbRate*l,Ho(t[1],i[1])+s[1]+e[1].heaveRate*c-e[1].arbRate*l]},stiffness:(i,s=ig)=>{if(r){let c=yL(r,i,o);return[[s(t[0],i[0])+c[0][0],c[0][1]],[c[1][0],s(t[1],i[1])+c[1][1]]]}return[[s(t[0],i[0])+e[0].heaveRate/2+e[0].arbRate/2,e[0].heaveRate/2-e[0].arbRate/2],[e[1].heaveRate/2-e[1].arbRate/2,s(t[1],i[1])+e[1].heaveRate/2+e[1].arbRate/2]]}}}function Xm(e,t,r,o,n,a=[0,0],i=[0,0],s=null,c){let l=[Zq(r[0].tyreRate),Zq(r[1].tyreRate)],u=[r[0].staticLoad,r[1].staticLoad],m=Wpe(r,o,s,c),p=P=>m.force(P,a),d=m.stiffness([0,0]),f=[l[0]>0?l[0]:1/Math.max(1,Math.abs(d[0][0])),l[1]>0?l[1]:1/Math.max(1,Math.abs(d[1][1]))],h=(P,I)=>{let z=I===1?p(P):m.force(P,[a[0]*I,a[1]*I]),N=[z[0]+i[0]*I,z[1]+i[1]*I],q=[P[0]+t[0]*I+N[0]*l[0]-e[0]*I,P[1]+t[1]*I+N[1]*l[1]-e[1]*I],U=[f[0]*(u[0]+N[0]),f[1]*(u[1]+N[1])],B=[U[0]<q[0],U[1]<q[1]];return{f:N,on:q,off:U,lifted:B,r:[Math.min(q[0],U[0]),Math.min(q[1],U[1])]}},g=(P,I)=>[I[0]?[f[0]*P[0][0],f[0]*P[0][1]]:[1+P[0][0]*l[0],P[0][1]*l[0]],I[1]?[f[1]*P[1][0],f[1]*P[1][1]]:[P[1][0]*l[1],1+P[1][1]*l[1]]],b=P=>Math.max(Math.abs(P[0]),Math.abs(P[1])),y=(P,I)=>{let z=[P[0],P[1]],N=h(z,I),q=!1,U=0;for(;U<Kpe;U++){if(b(N.r)<Jq){q=!0;break}let B=Xq(g(m.stiffness(z),N.lifted),[-N.r[0],-N.r[1]]);if(!B)break;let V=1,E=[z[0]+B[0],z[1]+B[1]],C=h(E,I);for(let $=0;$<8&&b(C.r)>b(N.r);$++)V/=2,E=[z[0]+V*B[0],z[1]+V*B[1]],C=h(E,I);z=E,N=C}return!q&&b(N.r)<Jq&&(q=!0),{t:z,b:N,converged:q,it:U}},v=y(n?[n[0],n[1]]:[e[0]-t[0],e[1]-t[1]],1),k=v.it;if(!v.converged){let P=0,I=[0,0],z=.25;for(;P<1&&z>=1/256;){let N=Math.min(1,P+z),q=y(I,N);k+=q.it,q.converged?(P=N,I=q.t,N===1&&(v=q)):z/=2}}let{t:x,b:S,converged:R}=v,w=S.lifted,M=[w[0]?-u[0]:S.f[0],w[1]?-u[1]:S.f[1]],T=[w[0]?Math.max(0,S.on[0]):0,w[1]?Math.max(0,S.on[1]):0],A=m.stiffness(x,Ym),_=g(A,w);return{t:x,dF:M,lifted:w,clearance:T,converged:R,iterations:k,respond:(P,I,z=[0,0])=>{let N=[w[0]?-f[0]*z[0]:P[0]-I[0]-z[0]*l[0],w[1]?-f[1]*z[1]:P[1]-I[1]-z[1]*l[1]],q=Xq(_,N);if(!q)return[NaN,NaN];let U=Hpe(A,q);return[w[0]?0:U[0]+z[0],w[1]?0:U[1]+z[1]]}}}var Qc=e=>!(Number.isFinite(e.tyreRate)&&e.tyreRate>0);function so(e,t,r){return t?.input.corners[r].staticLoadedRadius??e}var xL=["FL","FR","RL","RR"],tH={front:["FL","FR"],rear:["RL","RR"]},Ype=512,Zpe=5e-4,Xpe=8;function Lx(e,t){let r={},o={},n=new Map;for(let i of xL){let s=e.ctx[i],c=t.corners[i],l=c.staticLoadedRadius;o[i]=Pr(st(s,0,0,void 0,l===void 0?void 0:{loadedRadius:l})).points.contactPatch[2];let u=t.cornerCoilover?.[i==="FL"||i==="FR"?"front":"rear"],m=`${xL.findIndex(d=>Ut(e.vehicle,d)===Ut(e.vehicle,i))}|${c.springLoad}|${u?`${u.extended}/${u.stroke}`:""}`,p=n.get(m);p?r[i]=p:(r[i]=u?ag(s,c.springLoad,void 0,u):ag(s,c.springLoad),n.set(m,r[i]))}let a={front:null,rear:null};for(let i of["front","rear"]){let s=t.elements?.[i];if(!s)continue;let c=tH[i];a[i]=Hq([e.ctx[c[0]],e.ctx[c[1]]],[t.corners[c[0]],t.corners[c[1]]],s)}return{input:t,curve:r,elements:a,ground0:o,memo:new Map}}function rH(e,t,r){if(!(r>0)||!Number.isFinite(r)||!Number.isFinite(t)||t<=0)return 0;let o=Math.min(t/r,e);return 2*Math.sqrt(Math.max(0,2*e*o-o*o))}var Jpe=e=>`${e.heave}|${e.pitch}|${e.roll}|${e.steer}`;function wL(e,t,r){return{travel:r.travel,steer:r.steer,ground:r.travel,tyreDeflection:0,load:NaN,loadedRadius:so(Ut(e.vehicle,t).config.loadedRadius,e.kc,t),lifted:!1,contactLength:0,converged:!0,rigid:!0,rideRate:NaN,wheelRateAtLoad:NaN}}var Qpe=e=>e?{q:[e.pose.t[0],e.pose.t[1],e.pose.t[2],e.pose.omega[0],e.pose.omega[1],e.pose.omega[2]],phi:e.points.rockerAngle}:void 0;function Qq(e,t,r,o){let n=tH[o],a=e.vehicle.config,i=n.map(M=>$s(M,a,r,e.vehicle)),s=[t.input.corners[n[0]],t.input.corners[n[1]]],c=t.loadCase;if(!c&&s.every(Qc))return{corners:[wL(e,n[0],i[0]),wL(e,n[1],i[1])],respond:null};let l=n.map(M=>t.curve[M]),u=t.elements?.[o]??null,m=n.map(M=>so(Ut(e.vehicle,M).config.loadedRadius,t,M)),p=[i[0].travel+(c?.ground[n[0]]??0),i[1].travel+(c?.ground[n[1]]??0)],d=[c?.linkLoad[n[0]]??0,c?.linkLoad[n[1]]??0],f=[c?.patchShift[n[0]],c?.patchShift[n[1]]],h=[0,0],g=[0,0],b,y=Xm(p,h,s,l,void 0,void 0,d,u),v=[void 0,void 0],k=[!0,!0],x=[0,0],S=!1;for(let M=0;M<Xpe;M++){M>0&&(y=Xm(p,h,s,l,b,g,d,u)),x=[Number.isFinite(s[0].tyreRate)&&s[0].tyreRate>0?y.dF[0]/s[0].tyreRate:0,Number.isFinite(s[1].tyreRate)&&s[1].tyreRate>0?y.dF[1]/s[1].tyreRate:0];let T=[0,0],A=[0,0];for(let F=0;F<2;F++){let P=st(e.ctx[n[F]],y.t[F],i[F].steer,Qpe(v[F]),{loadedRadius:m[F]-x[F],patchShift:f[F]}),I=Pr(P);v[F]=I,k[F]=P.ok,T[F]=I.points.contactPatch[2]-t.ground0[n[F]]-y.t[F]-x[F],A[F]=yi(l[F],y.t[F],I.points.damperLength)-Ho(l[F],y.t[F])}if(u){let F=pg(u,y.t,[v[0],v[1]]),P=dg(u,y.t);A[0]+=F[0]-P[0],A[1]+=F[1]-P[1]}let _=Math.max(Math.abs(T[0]-h[0]),Math.abs(T[1]-h[1]),Math.abs(A[0]-g[0])/Math.max(1,s[0].tyreRate),Math.abs(A[1]-g[1])/Math.max(1,s[1].tyreRate));if(h=T,g=A,b=y.t,_<Zpe){S=!0;break}}let R=y.respond([1,1],[0,0]);return{corners:[0,1].map(M=>{let T=v[M];return{travel:y.t[M],steer:i[M].steer,ground:p[M],tyreDeflection:x[M],load:s[M].staticLoad+y.dF[M],loadedRadius:m[M]-x[M],lifted:y.lifted[M],clearance:y.clearance[M],contactLength:rH(m[M]-x[M],s[M].staticLoad+y.dF[M],s[M].tyreRate),converged:y.converged&&S&&k[M],rigid:!1,state:T,solved:k[M],rideRate:R[M],wheelRateAtLoad:kL(l[M],u,y.t,M)}}),respond:y.respond}}function nH(e,t){let r=e.kc,o=Jpe(t),n=r.memo.get(o);if(n)return n;let a=Qq(e,r,t,"front"),i=Qq(e,r,t,"rear"),s={corners:{FL:a.corners[0],FR:a.corners[1],RL:i.corners[0],RR:i.corners[1]},respond:{front:a.respond,rear:i.respond}};return r.memo.size>=Ype&&r.memo.clear(),r.memo.set(o,s),s}function rn(e,t){if(!e.kc){let r={};for(let o of xL)r[o]=wL(e,o,$s(o,e.vehicle.config,t,e.vehicle));return r}return nH(e,t).corners}function Dx(e,t,r){return e.kc?nH(e,t).respond[r]:null}function fg(e,t,r,o=0){let n=e.kc;if(!n)return r;let a=n.input.corners[t];if(Qc(a))return r;let i=$s(t,e.vehicle.config,{heave:0,pitch:0,roll:0,steer:o},e.vehicle).steer,s=so(Ut(e.vehicle,t).config.loadedRadius,n,t),c=n.loadCase,l=c?.linkLoad[t]??0,u=c?.patchShift[t],m=Pr(st(e.ctx[t],r,i,void 0,{loadedRadius:s,patchShift:u})),p=Ex(n,t),d=yi(n.curve[t],r,m.points.damperLength)+(p?SL(p,RL(t),r,m):a.heaveRate*r),h=Math.max(d+l,-a.staticLoad)/a.tyreRate;return(h===0?m:Pr(st(e.ctx[t],r,i,void 0,{loadedRadius:s-h,patchShift:u}))).points.contactPatch[2]-n.ground0[t]-(c?.ground[t]??0)}var efe=180/Math.PI,tfe=[0,0,1];function rfe(e,t){let r=bi(e,t),o=ke(Ve(tfe,r),-t.sideSign);return-Math.atan2(o[1],o[0])*efe}var oH=e=>1/Math.tan(e*Math.PI/180),aH=.05,iH=.001;function sH(e,t,r){if(!Number.isFinite(e)||!Number.isFinite(t))return NaN;if(!(Math.abs(e)<iH&&Math.abs(t)<iH))return e>0&&t>0?100*(oH(t)-oH(e))/r:NaN}function nfe(e,t){let r=io(e.vehicle,!0)/e.vehicle.config.wheelbase,o=t("FL",0).deg,n=t("FR",0).deg,a=(c,l)=>{let u=c+l>=0;return{left:u,inner:u?c:-l,outer:u?l:-c}},i,s=()=>{if(i===void 0){let c=[aH,-aH].map(l=>{let{inner:u,outer:m}=a(t("FL",l).deg-o,t("FR",l).deg-n);return sH(u,m,r)??NaN});i=(c[0]+c[1])/2}return i};return c=>{let l=t("FL",c),u=t("FR",c),{left:m,inner:p,outer:d}=a(l.deg-o,u.deg-n),f=sH(p,d,r);return{steerL:l.deg,steerR:u.deg,inner:p,outer:d,toeDiff:p-d,ackermannPct:f??s(),inside:f===void 0?null:m?"left":"right",converged:l.ok&&u.ok}}}function ML(e,t){let r=e.vehicle.config,o={FL:Zt("FL",r),FR:Zt("FR",r)},n=t.travel??0,a=nfe(e,(s,c)=>{let l=Sr(st(e.ctx[s],n,o[s].sideSign*c));return{deg:l?rfe(l.points.spinAxis,o[s]):NaN,ok:l!==null}}),i=[];for(let s=0;s<t.steps;s++){let c=t.steps===1?0:-t.steerMax+2*t.steerMax*s/(t.steps-1),{inside:l,...u}=a(c);i.push({steerInput:c,...u})}return i}var cH=35,lH=55,Fr=e=>e.rackTravel&&e.rackTravel>0?e.rackTravel:cH,_L=e=>e.rackRatio&&e.rackRatio>0?e.rackRatio:lH;var AL=e=>({q:[e.pose.t[0],e.pose.t[1],e.pose.t[2],e.pose.omega[0],e.pose.omega[1],e.pose.omega[2]],phi:e.points.rockerAngle});function uH(e,t,r,o,n){let a=st(e,o,0,void 0,n),i=Pr(a),s=a.ok?0:1,c=i.points.contactPatch[2],l={steer:i.metrics.toe,camber:i.metrics.camber,lift:0,contactPatch:i.points.contactPatch,spinAxis:i.points.spinAxis,yaw:-i.metrics.toe*Math.PI/180},u=d=>{let f=[l],h=AL(i);for(let g=1;g<=r;g++){let b=d*(t*g)/r,y=zt(e,i.beta,b,h,n),v=Sr(st(e,o,b,AL(y),n));if(!v||!y.converged){s++,f.push({...f[f.length-1]});continue}f.push({steer:v.metrics.toe,camber:v.metrics.camber,lift:-(y.points.contactPatch[2]-c),contactPatch:y.points.contactPatch,spinAxis:y.points.spinAxis,yaw:-y.metrics.toe*Math.PI/180}),h=AL(y)}return f},m=u(1),p=u(-1);return{travelMm:o,unsolved:s,centre:l,positive:m,negative:p}}function ofe(e,t){return e.map((r,o)=>{let n=o===0?0:o-1,a=o===e.length-1?e.length-1:o+1,i=t[a]-t[n];if(!(i>0))return{longitudinal:0,lateral:0,vertical:0,yaw:0};let s=ke(se(e[a].contactPatch,e[n].contactPatch),1/i),c=we(Ve(r.spinAxis,[0,0,1])),l=Ve([0,0,1],c);return{longitudinal:xe(s,c),lateral:xe(s,l),vertical:s[2],yaw:(e[a].yaw-e[n].yaw)/i}})}function mH(e,t,r){let o=n=>({steerDeg:n.map(a=>Math.abs(a.steer-e.centre.steer)),camberDeg:n.map(a=>a.camber-e.centre.camber),liftMm:n.map(a=>a.lift),jacobian:ofe(n,t)});return{travelMm:e.travelMm,inner:o(r?e.positive:e.negative),outer:o(r?e.negative:e.positive)}}function afe(e){return e.positive[1].steer-e.centre.steer<0}function ife(e,t,r){return{meanDeg:t.map((o,n)=>.5*(r.inner.steerDeg[n]+r.outer.steerDeg[n])),innerDeg:r.inner.steerDeg,outerDeg:r.outer.steerDeg,innerCamber:r.inner.camberDeg,outerCamber:r.outer.camberDeg,innerLift:r.inner.liftMm,outerLift:r.outer.liftMm,rackRatioMmPerRev:_L(e.config),innerJacobian:r.inner.jacobian,outerJacobian:r.outer.jacobian}}function CL(e,t,r=13,o=-40,n=40,a=5,i){let s=sr(e),c=Array.from({length:r+1},(g,b)=>t*b/r),l=uH(s,t,r,0,i),u=afe(l),m=mH(l,c,u),p=Math.max(2,Math.floor(a)),d=Array.from({length:p},(g,b)=>o+(n-o)*b/(p-1));d.some(g=>Math.abs(g)<1e-9)||d.push(0),d.sort((g,b)=>g-b);let f=l.unsolved,h=d.map(g=>{if(Math.abs(g)<1e-9)return m;let b=uH(s,t,r,g,i);return f+=b.unsolved,mH(b,c,u)});return{...ife(e,c,m),...dH(l.unsolved),travelSurface:{rackMm:c,rows:h,...dH(f)}}}var dH=e=>e>0?{unsolved:e}:{};function Aa(e,t,r){let o=e.length;if(o===0)return 0;if(r<=e[0])return t[0];if(r>=e[o-1])return t[o-1];let n=0,a=o-1;for(;a-n>1;){let s=n+a>>1;e[s]<=r?n=s:a=s}let i=(r-e[n])/(e[a]-e[n]);return t[n]+i*(t[a]-t[n])}function Nx(e,t,r){let o=e.length;if(o===0)return{longitudinal:0,lateral:0,vertical:0,yaw:0};let n,a;if(r<=e[0])n=a=0;else if(r>=e[o-1])n=a=o-1;else for(n=0,a=o-1;a-n>1;){let l=n+a>>1;e[l]<=r?n=l:a=l}let i=t[n];if(n===a)return{longitudinal:i.longitudinal,lateral:i.lateral,vertical:i.vertical,yaw:i.yaw};let s=t[a],c=(r-e[n])/(e[a]-e[n]);return{longitudinal:i.longitudinal+c*(s.longitudinal-i.longitudinal),lateral:i.lateral+c*(s.lateral-i.lateral),vertical:i.vertical+c*(s.vertical-i.vertical),yaw:i.yaw+c*(s.yaw-i.yaw)}}function pH(e,t){let r=e.rows;if(r.length<=1||t<=r[0].travelMm)return{lo:0,hi:0,t:0};let o=r.length-1;if(t>=r[o].travelMm)return{lo:o,hi:o,t:0};let n=0,a=o;for(;a-n>1;){let i=n+a>>1;r[i].travelMm<=t?n=i:a=i}return{lo:n,hi:a,t:(t-r[n].travelMm)/(r[a].travelMm-r[n].travelMm)}}var el=(e,t,r)=>e+r*(t-e);function Jm(e,t,r,o,n){let a=Aa(e.rackMm,e.rows[o.lo][t][r],n);if(o.lo===o.hi)return a;let i=Aa(e.rackMm,e.rows[o.hi][t][r],n);return el(a,i,o.t)}function fH(e,t,r,o){let n=Nx(e.rackMm,e.rows[r.lo][t].jacobian,o);if(r.lo===r.hi)return n;let a=Nx(e.rackMm,e.rows[r.hi][t].jacobian,o);return{longitudinal:el(n.longitudinal,a.longitudinal,r.t),lateral:el(n.lateral,a.lateral,r.t),vertical:el(n.vertical,a.vertical,r.t),yaw:el(n.yaw,a.yaw,r.t)}}function Qm(e,t,r,o){let n=e.travelSurface;if(!n||n.rackMm.length<2||n.rows.length===0)return ed(e,t);let a=pH(n,r),i=pH(n,o),s=(d,f,h)=>{let g=n.rows[f.lo][d].steerDeg[h];return f.lo===f.hi?g:el(g,n.rows[f.hi][d].steerDeg[h],f.t)},c=new Array(n.rackMm.length);for(let d=0;d<c.length;d++)c[d]=.5*(s("inner",a,d)+s("outer",i,d));let l=Math.max(0,t),u=c.length-1,m=n.rackMm[u],p=l>c[u];if(l<=c[0])m=n.rackMm[0],p=!1;else if(!p){let d=1;for(;d<c.length-1&&c[d]<l;)d++;let f=d-1,h=c[d]-c[f],g=Math.abs(h)>1e-12?(l-c[f])/h:0;m=el(n.rackMm[f],n.rackMm[d],g)}return{innerDeg:Jm(n,"inner","steerDeg",a,m),outerDeg:Jm(n,"outer","steerDeg",i,m),innerCamber:Jm(n,"inner","camberDeg",a,m),outerCamber:Jm(n,"outer","camberDeg",i,m),innerLift:Jm(n,"inner","liftMm",a,m),outerLift:Jm(n,"outer","liftMm",i,m),innerJacobian:fH(n,"inner",a,m),outerJacobian:fH(n,"outer",i,m),atLock:p}}function ed(e,t){let r=e.meanDeg.length-1;return{innerDeg:Aa(e.meanDeg,e.innerDeg,t),outerDeg:Aa(e.meanDeg,e.outerDeg,t),innerCamber:Aa(e.meanDeg,e.innerCamber,t),outerCamber:Aa(e.meanDeg,e.outerCamber,t),innerLift:e.innerLift?Aa(e.meanDeg,e.innerLift,t):0,outerLift:e.outerLift?Aa(e.meanDeg,e.outerLift,t):0,...e.innerJacobian&&e.outerJacobian?{innerJacobian:Nx(e.meanDeg,e.innerJacobian,t),outerJacobian:Nx(e.meanDeg,e.outerJacobian,t)}:{},atLock:r>=0&&t>e.meanDeg[r]}}var sfe=()=>({lift:{FL:0,FR:0,RL:0,RR:0},travel:{FL:0,FR:0,RL:0,RR:0},load:{FL:0,FR:0,RL:0,RR:0},rollDeg:0});function td(e,t,r=Lt(e),o){let n=e.steerFront;if(!n?.innerLift||!n.outerLift||n.meanDeg.length<2||Math.abs(t)<1e-12)return sfe();let a=Math.abs(t),i=t>0,s=o&&n.travelSurface?Qm(n,a,i?o.FL:o.FR,i?o.FR:o.FL):null,c=s?.innerLift??Aa(n.meanDeg,n.innerLift,a),l=s?.outerLift??Aa(n.meanDeg,n.outerLift,a),u=i?c:l,m=i?l:c,p=.5*(u+m),d=r.rollWheelRateFront,f=r.rollWheelRateRear,h=e.trackFront,g=e.trackRear,b=d*h*h+f*g*g,y=b>0?d*h*(m-u)/b:0,v={FL:u-p+.5*h*y,FR:m-p-.5*h*y,RL:.5*g*y,RR:-.5*g*y};return{lift:{FL:u,FR:m,RL:0,RR:0},travel:v,load:{FL:d*v.FL,FR:d*v.FR,RL:f*v.RL,RR:f*v.RR},rollDeg:y===0?0:-Math.atan(y)*180/Math.PI}}function TL(e,t,r){let o=t/r,n=a=>1/Math.tan(a*Math.PI/180);for(let a=0;a<e.meanDeg.length;a++)if(e.outerDeg[a]>.3&&e.innerDeg[a]>.3)return 100*(n(e.outerDeg[a])-n(e.innerDeg[a]))/o;return NaN}var hg=9.81;function rd(e,t,r=0,o=0,n=0){if(!e.aero||t<=0)return{FL:0,FR:0,RL:0,RR:0};let a=e.aero.model?gi(e,t,r,hi(e,o,n)):Zc(e.aero,t),i=a.downFront/2,s=a.downRear/2,c=a.drag*(e.aero.copHeight/1e3)/(e.wheelbase/1e3)/2;return{FL:i-c,FR:i-c,RL:s+c,RR:s+c}}function PL(e,t,r=0,o=0,n=0){if(!e.aero?.model||t<=0)return!1;let a=gi(e,t,r,hi(e,o,n));return a!=null&&(a.clampedRide||a.clampedAttitude)}function Ko(e){let t=e.loadFactor===void 0?e.massTotal*hg:e.massTotal*hg*e.loadFactor,r=t*e.frontMassFrac,o=t*(1-e.frontMassFrac);return{FL:r/2,FR:r/2,RL:o/2,RR:o/2}}function hH(e,t=Lt(e),r=e.cgHeight){let o=e.trackFront/1e3,n=e.trackRear/1e3,a=e.rcHeightFront/1e3,i=e.rcHeightRear/1e3,s=(e.rcHeightFront+(e.rcHeightRear-e.rcHeightFront)*(1-e.frontMassFrac))/1e3,c=r/1e3-s,l=2*e.unsprungPerCorner,u=e.unsprungCgHeight/1e3,m=t.sprungMass*c*fx(t.sprungMass,c,t.rollRateTotal),p=(m*t.frontRollStiffFrac+t.sprungFront*a+l*u)/o,d=(m*(1-t.frontRollStiffFrac)+t.sprungRear*i+l*u)/n;return{cf:p,cr:d}}function FL(e){let{cf:t,cr:r}=hH(e);return t+r>0?t/(t+r):.5}function gH(e,t,r){if(e.FL>=0&&e.FR>=0&&e.RL>=0&&e.RR>=0)return{loads:{FL:Math.max(0,e.FL),FR:Math.max(0,e.FR),RL:Math.max(0,e.RL),RR:Math.max(0,e.RR)},lifted:{FL:!1,FR:!1,RL:!1,RR:!1},overturned:!1};let o=e.FL+e.FR+e.RL+e.RR;if(!(o>0))return{loads:{FL:0,FR:0,RL:0,RR:0},lifted:{FL:!0,FR:!0,RL:!0,RR:!0},overturned:!0};let n=!1,a=e.FL+e.FR,i=e.RL+e.RR;a<0?(a=0,i=o,n=!0):i<0&&(i=0,a=o,n=!0);let s=(e.FR-e.FL)*t+(e.RR-e.RL)*r,c=Math.min(a,Math.max(-a,e.FR-e.FL)),l=Math.min(i,Math.max(-i,e.RR-e.RL)),u=s-(c*t+l*r);if(u!==0){let p=u>0?1:-1,d=(p*a-c)*t;p*u>=p*d?(c=p*a,u-=d):(c+=u/t,u=0);let f=(p*i-l)*r;u!==0&&(p*u>=p*f?(l=p*i,u-=f):(l+=u/r,u=0)),Math.abs(u)>1e-9*(Math.abs(s)+o*(t+r))&&(n=!0)}let m={FL:Math.max(0,(a-c)/2),FR:Math.max(0,(a+c)/2),RL:Math.max(0,(i-l)/2),RR:Math.max(0,(i+l)/2)};return{loads:m,lifted:{FL:m.FL===0,FR:m.FR===0,RL:m.RL===0,RR:m.RR===0},overturned:n}}function kt(e,t,r,o=0,n=0,a=0,i,s){return Ox(e,t,r,o,n,a,i,s).loads}function Ox(e,t,r,o=0,n=0,a=0,i,s){let c=Ko(e),l=Lt(e),u=Rx(e,o,r,hi(e,t,n),l),{cf:m,cr:p}=hH(e,l,u.height),d=m*t*hg,f=p*t*hg,h=e.massTotal*(r*hg)*u.height/e.wheelbase-u.noseLoad,g=rd(e,o,r,t,n),b=(s??td(e,a,l,i)).load,y={FL:c.FL-d-h/2+g.FL+b.FL,FR:c.FR+d-h/2+g.FR+b.FR,RL:c.RL-f+h/2+g.RL+b.RL,RR:c.RR+f+h/2+g.RR+b.RR};return gH(y,e.trackFront,e.trackRear)}var $L=Math.PI/180;function Vx(e,t){let r=8*$L,o=0,n=0;for(let a=1;a<=90;a++){let i=a*.5,s=Math.abs(e.Fy(i*$L,t,0));if(s>o&&(o=s,r=i*$L,n=a),a>n+12&&s<.995*o)break}return{aPeak:r,fyPeak:o}}function bH(e,t,r,o,n){if(o===t)return r;let a=(n-t)/(o-t);return a<=0?e:a>=1?r:e+a*(r-e)}var bg=.999;function On(e,t,r,o,n){if(t<=0)return 0;let{aPeak:a,fyPeak:i}=n??Vx(e,t),s=Math.min(Math.abs(r),bg*i),c=o?-1:1,l=(x,S)=>Math.abs(e.forces({Fz:t,kappa:c*x,alpha:S}).Fy),u=.3,m=u,p=l(u,a);if(p<s){let x=0,S=u,R=NaN,w=p;for(let M=0;M<9;M++){let T=.5*(x+S),A=l(T,a);A>=s?(x=T,R=A):(S=T,w=A)}Number.isNaN(R)&&(R=l(0,a)),m=R<s?0:bH(x,R,S,w,s)}if(m<=0)return 0;let d=x=>{if(s===0)return c*e.forces({Fz:t,kappa:c*x,alpha:0}).Fx;let S=0,R=a,w=NaN,M=NaN;for(let T=0;T<5;T++){let A=.5*(S+R),_=l(x,A);_<s?(S=A,w=_):(R=A,M=_)}return Number.isNaN(w)&&(w=l(x,0)),Number.isNaN(M)&&(M=l(x,a)),c*e.forces({Fz:t,kappa:c*x,alpha:bH(S,w,R,M,s)}).Fx},f=4,h=x=>m*x/f,g=[0],b=1;for(let x=1;x<=f;x++)g.push(d(h(x))),g[x]>g[b]&&(b=x);let[y,v]=b===f?[f-1,f-2]:g[b-1]>=g[b+1]?[b-1,b+1]:[b+1,b-1],k=mfe(d,h(b-1),h(Math.min(f,b+1)),h(b),g[b],h(y),g[y],h(v),g[v],cfe);return c*Math.max(0,k)}var cfe=.01,lfe=20,ufe=(3-Math.sqrt(5))/2;function mfe(e,t,r,o,n,a,i,s,c,l){n=-n,i=-i,c=-c;let u=r-t,m=0;for(let p=0;p<lfe;p++){let d=l*Math.abs(o)+1e-10,f=.5*(t+r);if(Math.abs(o-f)<=2*d-.5*(r-t))break;let h=!0;if(Math.abs(u)>d){let y=(o-a)*(n-c),v=(o-s)*(n-i),k=(o-s)*v-(o-a)*y;v=2*(v-y),v>0&&(k=-k),v=Math.abs(v);let x=u;if(u=m,Math.abs(k)<Math.abs(.5*v*x)&&k>v*(t-o)&&k<v*(r-o)){m=k/v;let S=o+m;(S-t<2*d||r-S<2*d)&&(m=f>=o?d:-d),h=!1}}h&&(u=o>=f?t-o:r-o,m=ufe*u);let g=Math.abs(m)>=d?o+m:o+(m>=0?d:-d),b=-e(g);b<=n?(g>=o?t=o:r=o,s=a,c=i,a=o,i=n,o=g,n=b):(g<o?t=g:r=g,b<=i||a===o?(s=a,c=i,a=g,i=b):(b<=c||s===o||s===a)&&(s=g,c=b))}return-n}function LL(e,t){return e.model?.kind==="simple"?null:SH(e,t)}var yH=new WeakMap,IL=100,vH=1.35,EL=18,Ca=41,zx=41,gg=65;function SH(e,t){let r=yH.get(e);if(r)return r;let o=Math.log(vH),n=(d,f)=>{let h=R=>Math.abs(On(e,d,R,f)),g=h(0),b=t.muY(d)*d,y=new Float64Array(Ca),v=g>0&&b>0?Math.max(1,t.muX(d)*d/g):1;if(!(g>0)||!(b>0))y.fill(1);else{let R=[],w=[];for(let T=0;T<zx;T++){let A=Math.sin(.5*Math.PI*T/(zx-1));R.push(A),w.push(T===0?1:T===zx-1?0:Math.min(w[T-1],h(A*b)/g))}let M=zx-1;for(let T=0;T<Ca;T++){let A=T/(Ca-1);for(;M>0&&w[M-1]<A;)M--;let _=M>0?w[M-1]-w[M]:0;y[T]=M===0?R[0]:R[M]+(_>0?(A-w[M])/_:0)*(R[M-1]-R[M])}y[0]=1,y[Ca-1]=0}let k=new Float64Array(gg),x=R=>Math.atan2(y[R],R/(Ca-1)/v),S=Ca-2;for(let R=0;R<gg;R++){let w=.5*Math.PI*R/(gg-1),M=Math.cos(w),T=Math.sin(w);for(;S>0&&x(S)<w;)S--;let A=S/(Ca-1)/v,_=y[S],F=(S+1)/(Ca-1)/v,P=y[S+1],I=M*(P-_)-T*(F-A),z=Math.abs(I)>1e-12?(A*(P-_)-_*(F-A))/I:Math.hypot(A,_);k[R]=z>0?z:Math.hypot(A,_)}return{room:y,scale:v,edge:k}},a=Array.from({length:EL},(d,f)=>IL*vH**f),i=a.map(d=>n(d,!1)),s=a.map(d=>n(d,!0)),c=(d,f)=>{let h=Math.min(1,Math.abs(f)*d.scale)*(Ca-1),g=Math.min(Ca-2,Math.floor(h));return d.room[g]+(h-g)*(d.room[g+1]-d.room[g])},l=d=>{let f=d>IL?Math.log(d/IL)/o:0;if(f>=EL-1)return[EL-2,1];let h=Math.floor(f);return[h,f-h]},u=(d,f,h)=>{if(h===0)return 1;let g=h<0?s:i,b=c(g[d],h);return f>0?b+f*(c(g[d+1],h)-b):b},m=(d,f,h)=>{let g=f<0?s:i,[b,y]=l(d),v=Math.atan2(Math.abs(h),Math.abs(f))/(.5*Math.PI)*(gg-1),k=Math.min(gg-2,Math.floor(v)),x=R=>R.edge[k]+(v-k)*(R.edge[k+1]-R.edge[k]),S=x(g[b]);return y>0?S+y*(x(g[b+1])-S):S},p={keeps(d,f){if(f===0)return 1;let[h,g]=l(d);return u(h,g,f)},atLoad(d){let[f,h]=l(d);return g=>u(f,h,g)},use(d,f,h){let g=Math.hypot(f,h);return g>0?Math.min(1,g/m(d,f,h)):0},reach:m};return yH.set(e,p),p}var dfe=[["front","FL","FR"],["rear","RL","RR"]];function nd(e,t,r,o){let n={...e},a=0,i=bg;for(let[s,c,l]of dfe){let u=(k,x)=>o(s,Math.max(0,x[k])).fyPeak,m=Math.min(i,e[c]),p=Math.min(i,e[l]),d=m*u(c,r)+p*u(l,r);if(!(d>0))continue;let f=u(c,t),h=u(l,t),g=m*f+p*h,b=g>0?d/g:1/0,y=m*b,v=p*b;y<=i?v<=i||(v=i,y=f>0?(d-i*h)/f:1/0):(y=i,v=h>0?(d-i*f)/h:1/0),(!(y<=i)||!(v<=i))&&(a+=Math.max(0,d-i*(f+h)),y=Math.min(i,y),v=Math.min(i,v)),n[c]=y,n[l]=v}return{util:n,short:a}}var kH=.001,pfe=1e-5,RH=100;function ffe(e,t,r,o){if(!(o>kH))return r;let n=t,a=Math.abs(r-t)<RH?t+Math.sign(r-t)*RH:r;for(let i=0;i<60&&Math.abs(a-n)>pfe;i++){let s=.5*(n+a);e(s)>kH?a=s:n=s}return n}function jx(e,t,r){let o;return{at:n=>{if(o!==void 0)return r<0?Math.max(n,o):Math.min(n,o);if(!((n-t)*r>0))return n;let a=ffe(e,t,n,e(n));return a!==n&&(o=a),a},edge:()=>o}}function vg(e,t){let r=o=>{try{return st(e,0,o).ok}catch{return!1}};for(let o of[1,-1]){if(r(o*t))continue;let n=0;for(let a=1;a<=6;a++){let i=o*t*a/6;if(!r(i))break;n=Math.abs(i)}return{lock:t,reached:n,side:o}}return null}var yg=40,xH=new WeakMap;function DL(e){if(e.measured)return null;let t=xH.get(e);if(t)return t;let r=[-yg,yg],o=Xt(e,{travelMin:r[0],travelMax:r[1],steps:21}),n=o.samples.filter(i=>i.converged),a={travel:r,reach:o.reach,covered:o.covered,samples:o.samples.length,unconverged:o.unconverged,fold:o.fold,minMargin:n.length?Math.min(...n.map(i=>i.margin)):0,lockShort:e.config.steerMode==="rack"?vg(sr(e),Fr(e.config)):null};return xH.set(e,a),a}function Bx(e){return{violation:Math.max(0,e.lock-e.reached),reason:`the steering reaches only ${e.reached.toFixed(0)} mm of the ${e.lock.toFixed(0)} mm rack travel${e.side<0?" (other side)":""}`}}var wH=[0,0,0];function hfe(e,t){let r=we(se(e.rockerPivotB,e.rockerPivotA)),o=we(se(e.rockerToPushrod,e.pushrodOuter)),n=we(se(e.damperChassis,e.rockerToDamper)),a=Math.abs(xe(r,Ve(se(e.rockerToPushrod,e.rockerPivotA),o))),i=Math.abs(xe(r,Ve(se(e.rockerToDamper,e.rockerPivotA),n)));return i<1e-9?0:t*a/i}function od(e,t,r){if(e.mcpherson)return gfe(e,t,r);let o=[{r:e.uprightUpper,c:e.ucaFront},{r:e.uprightUpper,c:e.ucaRear},{r:e.uprightLower,c:e.lcaFront},{r:e.uprightLower,c:e.lcaRear},{r:e.tieOuter,c:e.tieInner},{r:e.pushrodOuter,c:e.direct?e.damperChassis:e.rockerToPushrod}],n=e.wheelCenter,a=[[],[],[],[],[],[]];for(let m=0;m<6;m++){let p=we(se(o[m].c,o[m].r)),d=Ve(se(o[m].r,n),p);a[0][m]=p[0],a[1][m]=p[1],a[2][m]=p[2],a[3][m]=d[0],a[4][m]=d[1],a[5][m]=d[2]}let i=Ve(se(e.contactPatch,n),t),s=r??wH,c=[-t[0],-t[1],-t[2],-(i[0]+s[0]),-(i[1]+s[1]),-(i[2]+s[2])],l=wa(a,c),u=l.x;return{ucaFront:u[0],ucaRear:u[1],lcaFront:u[2],lcaRear:u[3],tieRod:u[4],pushRod:u[5],damper:l.singular||e.decoupled?NaN:e.direct?u[5]:hfe(e,u[5]),condProxy:l.condProxy,singular:l.singular}}function gfe(e,t,r){let o=e.wheelCenter,n=e.damperChassis,a=[{at:e.uprightLower,dir:we(se(e.lcaFront,e.uprightLower))},{at:e.uprightLower,dir:we(se(e.lcaRear,e.uprightLower))},{at:e.tieOuter,dir:we(se(e.tieInner,e.tieOuter))},{at:n,dir:[1,0,0]},{at:n,dir:[0,1,0]},{at:n,dir:[0,0,1]}],i=[[],[],[],[],[],[]];for(let g=0;g<6;g++){let b=a[g].dir,y=Ve(se(a[g].at,o),b);i[0][g]=b[0],i[1][g]=b[1],i[2][g]=b[2],i[3][g]=y[0],i[4][g]=y[1],i[5][g]=y[2]}let s=Ve(se(e.contactPatch,o),t),c=r??wH,l=[-t[0],-t[1],-t[2],-(s[0]+c[0]),-(s[1]+c[1]),-(s[2]+c[2])],u=wa(i,l),m=u.x,p=[m[3],m[4],m[5]],d=we(se(n,e.pushrodOuter)),f=xe(p,d),h=Math.hypot(p[0]-f*d[0],p[1]-f*d[1],p[2]-f*d[2]);return{ucaFront:NaN,ucaRear:NaN,lcaFront:m[0],lcaRear:m[1],tieRod:m[2],pushRod:u.singular?NaN:f,damper:u.singular?NaN:f,condProxy:u.condProxy,singular:u.singular,strutSide:u.singular?NaN:h,topMount:p}}function NL(e,t){let r=we(e.spinAxis),o=Ve(se(e.contactPatch,e.wheelCenter),t),n=xe(o,r);return[-n*r[0],-n*r[1],-n*r[2]]}var bfe=[0,0,0];function tl(e,t,r,o){let n=e.direct?e.damperChassis:e.rockerToPushrod;if(e.mcpherson)return{...od(e,r,o),armResidual:0};if(t==="upright")return{...od(e,r,o),armResidual:0};let a=t==="lowerArm",i=a?{bj:e.uprightUpper,front:e.ucaFront,rear:e.ucaRear}:{bj:e.uprightLower,front:e.lcaFront,rear:e.lcaRear},s=a?{bj:e.uprightLower,front:e.lcaFront,rear:e.lcaRear}:{bj:e.uprightUpper,front:e.ucaFront,rear:e.ucaRear},c=e.wheelCenter,l=we(se(i.front,i.bj)),u=we(se(i.rear,i.bj)),m=we(se(e.tieInner,e.tieOuter)),p=[{at:i.bj,dir:l},{at:i.bj,dir:u},{at:e.tieOuter,dir:m},{at:s.bj,dir:[1,0,0]},{at:s.bj,dir:[0,1,0]},{at:s.bj,dir:[0,0,1]}],d=[[],[],[],[],[],[]];for(let X=0;X<6;X++){let ie=p[X].dir,te=Ve(se(p[X].at,c),ie);d[0][X]=ie[0],d[1][X]=ie[1],d[2][X]=ie[2],d[3][X]=te[0],d[4][X]=te[1],d[5][X]=te[2]}let f=Ve(se(e.contactPatch,c),r),h=o??bfe,g=[-r[0],-r[1],-r[2],-(f[0]+h[0]),-(f[1]+h[1]),-(f[2]+h[2])],b=wa(d,g),y=b.singular,v=b.x,k=v[0],x=v[1],S=v[2],R=[v[3],v[4],v[5]],w=we(se(s.rear,s.front)),M=we(se(n,e.pushrodOuter)),T=ke(R,-1),A=(X,ie)=>xe(w,Ve(se(X,s.front),ie)),_=A(e.pushrodOuter,M),F=Math.abs(_)>1e-9?-A(s.bj,T)/_:NaN,P=Ee(T,ke(M,F)),I=ke(P,-1),z=we(se(s.front,s.bj)),N=we(se(s.rear,s.bj)),q=xe(z,z),U=xe(z,N),B=xe(N,N),V=xe(z,I),E=xe(N,I),C=q*B-U*U,$=NaN,L=NaN,j=NaN;if(Math.abs(C)>1e-12){$=(V*B-E*U)/C,L=(q*E-U*V)/C;let X=Ee(ke(z,$),ke(N,L)),ie=se(I,X);j=Math.hypot(ie[0],ie[1],ie[2])}let K=a?{f:k,r:x}:{f:$,r:L},Y=a?{f:$,r:L}:{f:k,r:x};return{ucaFront:K.f,ucaRear:K.r,lcaFront:Y.f,lcaRear:Y.r,tieRod:S,pushRod:F,damper:y||!Number.isFinite(F)||e.decoupled?NaN:e.direct?F:yfe(e,F),condProxy:b.condProxy,singular:y,armResidual:j}}function yfe(e,t){let r=we(se(e.rockerPivotB,e.rockerPivotA)),o=we(se(e.rockerToPushrod,e.pushrodOuter)),n=we(se(e.damperChassis,e.rockerToDamper)),a=Math.abs(xe(r,Ve(se(e.rockerToPushrod,e.rockerPivotA),o))),i=Math.abs(xe(r,Ve(se(e.rockerToDamper,e.rockerPivotA),n)));return i<1e-9?0:t*a/i}var RVe=Math.PI/180;function Sg(e,t){let r=Math.min(Math.max(t,e.range[0]),e.range[1])-e.reference;return Math.max(.2,1+e.perDegC*r+e.perDegC2*r*r)}var _H=["QSX3","QSX8","QSX13","QSX14"],vfe=["QSX1"],Ux=["PHY1","PHY2","PHY3","PKY6","PKY7","PVY1","PVY2","PVY3","PVY4","PEY3","PEY4","QHZ1","QHZ2","QHZ3","QHZ4","QEZ4","QEZ5","QDZ6","QDZ7","QDZ8","QDZ9","QDZ10","QDZ11","SSZ1","SSZ3","SSZ4","RBY3","RHX1","RVY1","RVY2","RVY3",..._H];function Sfe(e){let t=["PKY6","PKY7","PVY3","PVY4","PHY3","PEY4","RVY3","QHZ3","QHZ4","QEZ5","QDZ8","QDZ9","QDZ10","QDZ11","SSZ3","SSZ4"];return e==="5.2"?[...t,"QBZ4","QDZ3"]:t}function kfe(e){let t=new Set(Sfe(e)),r=Ux.filter(o=>!_H.includes(o));return[...r.filter(o=>!t.has(o)),...[...t].filter(o=>!r.includes(o)),...vfe]}function Rfe(e,t){let r={...e};for(let o of t)r[o]!==void 0&&r[o]!==0&&(r[o]=-r[o]);return r}var vi=(e,t,r)=>Number.isFinite(e[t])?e[t]:r;function AH(e,t){return t!=="5.2"?vi(e,"PKY6",0)*vi(e,"LKYC",1):vi(e,"PKY1",-15)*Math.sin(vi(e,"PKY4",2)*Math.atan(1/vi(e,"PKY2",2)))*vi(e,"LKY",1)*vi(e,"PHY3",0)+vi(e,"PVY3",0)*vi(e,"LMUY",1)}var MH=.1;function CH(e){if(e.fitData)return"sae";let t=AH(e.coeffs,e.version);return t>MH?"sae":t<-MH?"iso":null}function kg(e){return e.axisSystem??CH(e)??"sae"}function Gx(e){let t=new Set,r=o=>{for(let n of o)t.has(n)?t.delete(n):t.add(n)};return kg(e)==="iso"&&r(Ux),e.axisSystem&&e.side==="left"&&r(kfe(e.version)),t.size?Rfe(e.coeffs,t):e.coeffs}var wVe=Math.PI/180;var ae=(e,t)=>Number.isFinite(e)?e:t;function PH(e){let t=Gx(e);return{PCX1:ae(t.PCX1,1.65),PDX1:ae(t.PDX1,1),PDX2:ae(t.PDX2,0),PDX3:ae(t.PDX3,0),PEX1:ae(t.PEX1,0),PEX2:ae(t.PEX2,0),PEX3:ae(t.PEX3,0),PEX4:ae(t.PEX4,0),PHX1:ae(t.PHX1,0),PHX2:ae(t.PHX2,0),PKX1:ae(t.PKX1,20),PKX2:ae(t.PKX2,0),PKX3:ae(t.PKX3,0),PPX1:ae(t.PPX1,0),PPX2:ae(t.PPX2,0),PPX3:ae(t.PPX3,0),PPX4:ae(t.PPX4,0),PVX1:ae(t.PVX1,0),PVX2:ae(t.PVX2,0),PCY1:ae(t.PCY1,1.3),PDY1:ae(t.PDY1,1),PDY2:ae(t.PDY2,0),PDY3:ae(t.PDY3,0),PEY1:ae(t.PEY1,0),PEY2:ae(t.PEY2,0),PEY3:ae(t.PEY3,0),PEY4:ae(t.PEY4,0),PEY5:ae(t.PEY5,0),PHY1:ae(t.PHY1,0),PHY2:ae(t.PHY2,0),PHY3:ae(t.PHY3,0),PKY1:ae(t.PKY1,-15),PKY2:ae(t.PKY2,2),PKY3:ae(t.PKY3,0),PKY4:ae(t.PKY4,2),PKY5:ae(t.PKY5,0),PKY6:ae(t.PKY6,0),PKY7:ae(t.PKY7,0),PPY1:ae(t.PPY1,0),PPY2:ae(t.PPY2,0),PPY3:ae(t.PPY3,0),PPY4:ae(t.PPY4,0),PPY5:ae(t.PPY5,0),PVY1:ae(t.PVY1,0),PVY2:ae(t.PVY2,0),PVY3:ae(t.PVY3,0),PVY4:ae(t.PVY4,0),RBX1:ae(t.RBX1,0),RBX2:ae(t.RBX2,0),RBX3:ae(t.RBX3,0),RBY1:ae(t.RBY1,0),RBY2:ae(t.RBY2,0),RBY3:ae(t.RBY3,0),RBY4:ae(t.RBY4,0),RCX1:ae(t.RCX1,1),RCY1:ae(t.RCY1,1),REX1:ae(t.REX1,0),REX2:ae(t.REX2,0),REY1:ae(t.REY1,0),REY2:ae(t.REY2,0),RHX1:ae(t.RHX1,0),RHY1:ae(t.RHY1,0),RHY2:ae(t.RHY2,0),RVY1:ae(t.RVY1,0),RVY2:ae(t.RVY2,0),RVY3:ae(t.RVY3,0),RVY4:ae(t.RVY4,0),RVY5:ae(t.RVY5,1),RVY6:ae(t.RVY6,0),PPZ1:ae(t.PPZ1,0),PPZ2:ae(t.PPZ2,0),QBZ1:ae(t.QBZ1,8),QBZ2:ae(t.QBZ2,0),QBZ3:ae(t.QBZ3,0),QBZ4:ae(t.QBZ4,0),QBZ5:ae(t.QBZ5,0),QBZ6:ae(t.QBZ6,0),QBZ9:ae(t.QBZ9,0),QBZ10:ae(t.QBZ10,0),QCZ1:ae(t.QCZ1,1.1),QDZ1:ae(t.QDZ1,.1),QDZ2:ae(t.QDZ2,0),QDZ3:ae(t.QDZ3,0),QDZ4:ae(t.QDZ4,0),QDZ6:ae(t.QDZ6,0),QDZ7:ae(t.QDZ7,0),QDZ8:ae(t.QDZ8,0),QDZ9:ae(t.QDZ9,0),QDZ10:ae(t.QDZ10,0),QDZ11:ae(t.QDZ11,0),QEZ1:ae(t.QEZ1,0),QEZ2:ae(t.QEZ2,0),QEZ3:ae(t.QEZ3,0),QEZ4:ae(t.QEZ4,0),QEZ5:ae(t.QEZ5,0),QHZ1:ae(t.QHZ1,0),QHZ2:ae(t.QHZ2,0),QHZ3:ae(t.QHZ3,0),QHZ4:ae(t.QHZ4,0),SSZ1:ae(t.SSZ1,0),SSZ2:ae(t.SSZ2,0),SSZ3:ae(t.SSZ3,0),SSZ4:ae(t.SSZ4,0),QSX1:ae(t.QSX1,0),QSX2:ae(t.QSX2,0),QSX3:ae(t.QSX3,0),QSX4:ae(t.QSX4,0),QSX5:ae(t.QSX5,0),QSX6:ae(t.QSX6,0),QSX7:ae(t.QSX7,0),QSX8:ae(t.QSX8,0),QSX9:ae(t.QSX9,0),QSX10:ae(t.QSX10,0),QSX11:ae(t.QSX11,0),QSX12:ae(t.QSX12,0),QSX13:ae(t.QSX13,0),QSX14:ae(t.QSX14,0),PPMX1:ae(t.PPMX1,0),QSY1:ae(t.QSY1,0),QSY2:ae(t.QSY2,0),QSY3:ae(t.QSY3,0),QSY4:ae(t.QSY4,0),QSY5:ae(t.QSY5,0),QSY6:ae(t.QSY6,0),QSY7:ae(t.QSY7,0),QSY8:ae(t.QSY8,0),LONGVL:t.LONGVL!==void 0&&t.LONGVL>0?t.LONGVL:16.7,LCX:ae(t.LCX,1),LCY:ae(t.LCY,1),LEX:ae(t.LEX,1),LEY:ae(t.LEY,1),LFZO:ae(t.LFZO,1),LHX:ae(t.LHX,1),LHY:ae(t.LHY,1),LKX:ae(t.LKX,1),LKY:ae(t.LKY,1),LKYC:ae(t.LKYC,1),LKZC:ae(t.LKZC,1),LMUX:ae(t.LMUX,1),LMUY:ae(t.LMUY,1),LMX:ae(t.LMX,1),LMY:ae(t.LMY,1),LVMX:ae(t.LVMX,1),LRES:ae(t.LRES,1),LS:ae(t.LS,1),LTR:ae(t.LTR,1),LVX:ae(t.LVX,1),LVY:ae(t.LVY,1),LVYKA:ae(t.LVYKA,1),LXAL:ae(t.LXAL,1),LYKA:ae(t.LYKA,1)}}var TH=new WeakMap;function Rg(e){let t=TH.get(e);return t===void 0&&(t=PH(e),TH.set(e,t)),t}var FH=e=>e>=0?1:-1;function qx(e,t,r=0,o){let n=Rg(e),a=Math.max(1,t),i=r,s=n.LFZO*e.fnomin,c=(a-s)/s,l=e.nomPressure>0&&o?(o-e.nomPressure)/e.nomPressure:0,u=e.unloadedR0,m=(n.PDY1+n.PDY2*c)*(1+n.PPY3*l+n.PPY4*l*l)*(1-n.PDY3*i*i)*n.LMUY,p=n.PCY1*n.LCY,d=m*a,f=n.PKY1*s*(1+n.PPY1*l)*Math.sin(n.PKY4*Math.atan(a/((n.PKY2+n.PKY5*i*i)*(1+n.PPY2*l)*s)))*(1-n.PKY3*Math.abs(i))*n.LKY,h=e.version!=="5.2",g=a*(n.PKY6+n.PKY7*c)*(1+n.PPY5*l)*n.LKYC,b=a*(n.PVY3+n.PVY4*c)*i*n.LKYC*n.LMUY,y=Math.abs(f)>1e-6?f:1e-6*(f<0?-1:1),v=h?(n.PHY1+n.PHY2*c)*n.LHY+(g*i-b)/y:(n.PHY1+n.PHY2*c)*n.LHY+n.PHY3*i,k=h?a*(n.PVY1+n.PVY2*c)*n.LVY*n.LMUY+b:a*((n.PVY1+n.PVY2*c)*n.LVY+(n.PVY3+n.PVY4*c)*i)*n.LMUY,x=p*d!==0?f/(p*d):0;return{Fz:a,g:i,dfz:c,dpi:l,Fz0p:s,R0:u,Cy:p,Dy:d,By:x,SHy:v,SVy:k,Kya:f,muy:m,EyA:n.PEY1+n.PEY2*c,EyG:1+n.PEY5*i*i,EyS:n.PEY3+n.PEY4*i,LEY:n.LEY}}function Hx(e,t,r=0,o){let n=qx(e,t,r,o),a=Rg(e),{Fz:i,g:s,dfz:c,dpi:l,Fz0p:u,R0:m,muy:p,Kya:d,SVy:f,By:h,Cy:g,Dy:b,SHy:y}=n,v=(a.PHX1+a.PHX2*c)*a.LHX,k=(a.PDX1+a.PDX2*c)*(1+a.PPX3*l+a.PPX4*l*l)*(1-a.PDX3*s*s)*a.LMUX,x=a.PCX1*a.LCX,S=k*i,R=i*(a.PKX1+a.PKX2*c)*Math.exp(a.PKX3*c)*(1+a.PPX1*l+a.PPX2*l*l)*a.LKX,w=x*S!==0?R/(x*S):0,M=Math.abs(d)>1e-6?d:1e-6*(d<0?-1:1),T=e.version!=="5.2",A=i*(a.PVX1+a.PVX2*c)*a.LVX*a.LMUX,_=a.REX1+a.REX2*c;_>1&&(_=1);let F=a.REY1+a.REY2*c;return F>1&&(F=1),{Fz:i,g:s,dfz:c,dpi:l,Fz0p:u,R0:m,Cy:g,Dy:b,By:h,SHy:y,SVy:f,Kya:d,muy:p,EyA:n.EyA,EyG:n.EyG,EyS:n.EyS,LEY:n.LEY,SHx:v,Cx:x,Dx:S,Bx:w,SVx:A,ExA:a.PEX1+a.PEX2*c+a.PEX3*c*c,PEX4:a.PEX4,LEX:a.LEX,SHxa:a.RHX1,Bxa0:a.RBX1+a.RBX3*s*s,RBX2:a.RBX2,LXAL:a.LXAL,Cxa:a.RCX1,Exa:_,SHyk:a.RHY1+a.RHY2*c,Byk0:a.RBY1+a.RBY4*s*s,RBY2:a.RBY2,RBY3:a.RBY3,LYKA:a.LYKA,Cyk:a.RCY1,Eyk:F,DVykA:p*i*(a.RVY1+a.RVY2*c+a.RVY3*s),RVY4:a.RVY4,RVY5:a.RVY5,RVY6:a.RVY6,LVYKA:a.LVYKA,SHt:a.QHZ1+a.QHZ2*c+(a.QHZ3+a.QHZ4*c)*s,Bt:T?(a.QBZ1+a.QBZ2*c+a.QBZ3*c*c)*(1+a.QBZ5*Math.abs(s)+a.QBZ6*s*s)*(a.LKY/a.LMUY):(a.QBZ1+a.QBZ2*c+a.QBZ3*c*c)*(1+a.QBZ4*s+a.QBZ5*Math.abs(s))*(a.LKY/a.LMUY),Ct:a.QCZ1,Dt:T?i*(m/u)*(a.QDZ1+a.QDZ2*c)*(1-a.PPZ1*l)*(1+a.QDZ3*Math.abs(s)+a.QDZ4*s*s)*a.LTR:i*(m/u)*(a.QDZ1+a.QDZ2*c)*(1-a.PPZ1*l)*(1+a.QDZ3*s+a.QDZ4*s*s)*a.LTR,EtA:a.QEZ1+a.QEZ2*c+a.QEZ3*c*c,EtG:a.QEZ4+a.QEZ5*s,Br:a.QBZ9*(a.LKY/a.LMUY)+a.QBZ10*h*g,Dr:T?i*m*((a.QDZ6+a.QDZ7*c)*a.LRES+((a.QDZ8+a.QDZ9*c)*(1+a.PPZ2*l)+(a.QDZ10+a.QDZ11*c)*Math.abs(s))*s*a.LKZC)*a.LMUY:i*m*((a.QDZ6+a.QDZ7*c)*a.LRES+(a.QDZ8+a.QDZ9*c)*(1+a.PPZ2*l)*s)*a.LMUY,arOff:d!==0?f/d:0,sixOne:T,kk:R/M*(R/M),sS0:m*(a.SSZ1+(a.SSZ3+a.SSZ4*c)*s)*a.LS,sS2:m*a.SSZ2*a.LS/u}}function xg(e,t){let r=t+e.SHy,o=e.EyA*(e.EyG-e.EyS*FH(r))*e.LEY;o>1&&(o=1);let n=e.By*r;return e.Dy*Math.sin(e.Cy*Math.atan(n-o*(n-Math.atan(n))))+e.SVy}function Kx(e,t){let r=t+e.SHx,o=e.ExA*(1-e.PEX4*FH(r))*e.LEX;o>1&&(o=1);let n=e.Bx*r;return e.Dx*Math.sin(e.Cx*Math.atan(n-o*(n-Math.atan(n))))+e.SVx}function $H(e,t,r){if(r===0)return t;if(e.sixOne)return Math.sqrt(t*t+e.kk*r*r)*Math.sign(t);let o=Math.tan(t);return Math.atan(Math.sqrt(o*o+e.kk*r*r))*Math.sign(t)}function xfe(e,t,r,o){let n=t+e.SHt,a=e.EtA*(1+e.EtG*(2/Math.PI)*Math.atan(e.Bt*e.Ct*n));a>1&&(a=1);let i=$H(e,n,r),s=e.Bt*i;return e.Dt*Math.cos(e.Ct*Math.atan(s-a*(s-Math.atan(s))))*o}function wfe(e,t,r,o){return e.Dr*Math.cos(Math.atan(e.Br*$H(e,t+e.SHy+e.arOff,r)))*o}function IH(e,t,r,o,n,a){let i=Math.cos(t),s=xfe(e,t,r,i),c=wfe(e,t,r,i);return-s*(n-a)+c+(e.sS0+e.sS2*n)*o}function EH(e,t,r){let o=e.Bxa0*Math.cos(Math.atan(e.RBX2*t))*e.LXAL,n=r+e.SHxa,a=Math.cos(e.Cxa*Math.atan(o*e.SHxa-e.Exa*(o*e.SHxa-Math.atan(o*e.SHxa))))||1;return Math.cos(e.Cxa*Math.atan(o*n-e.Exa*(o*n-Math.atan(o*n))))/a*Kx(e,t)}function OL(e,t){let r=e.sS0===0&&e.sS2===0?0:EH(e,0,t);return IH(e,t,0,r,xg(e,t),0)}function Wx(e,t,r){let o=xg(e,r),n=EH(e,t,r),a=e.Byk0*Math.cos(Math.atan(e.RBY2*(r-e.RBY3)))*e.LYKA,i=t+e.SHyk,s=Math.cos(e.Cyk*Math.atan(a*e.SHyk-e.Eyk*(a*e.SHyk-Math.atan(a*e.SHyk))))||1,c=Math.cos(e.Cyk*Math.atan(a*i-e.Eyk*(a*i-Math.atan(a*i))))/s,u=e.DVykA*Math.cos(Math.atan(e.RVY4*r))*Math.sin(e.RVY5*Math.atan(e.RVY6*t))*e.LVYKA,m=c*o+u;return{Fx:n,Fy:m,Mz:IH(e,r,t,n,m,u)}}var wg=(e,t)=>Math.max(.1,e.muY0+e.loadSensY*(t-e.nominalLoad)),Mg=(e,t)=>Math.max(.1,e.muX0+e.loadSensX*(t-e.nominalLoad)),LH=(e,t,r)=>wg(e,Math.max(1,t))*Math.max(1,t)*Math.sin(e.Cy*Math.atan(e.By*r)),DH=(e,t,r)=>Mg(e,Math.max(1,t))*Math.max(1,t)*Math.sin(e.Cx*Math.atan(e.Bx*r));function zL(e,t){let r=Math.max(1,t.Fz),o=wg(e,r)*r,n=Mg(e,r)*r,a=o*Math.sin(e.Cy*Math.atan(e.By*t.alpha)),i=n*Math.sin(e.Cx*Math.atan(e.Bx*t.kappa)),s=Math.hypot(n>0?i/n:0,o>0?a/o:0);return s>1&&(i/=s,a/=s),{Fx:i,Fy:a,Mz:0}}var ad=Math.PI/180;function rl(e){if(e.kind==="simple")return"none";let t=e.missing?.some(o=>/^aligning moment Mz\b/i.test(o))??!1,r=["QBZ1","QCZ1","QDZ1"].every(o=>Number.isFinite(e.coeffs[o]));return t||!r?"assumed":"model"}function NH(e){let t=e.thermal?.operating;if(t===void 0||!e.thermal)return e;let{lateral:r,longitudinal:o,aligning:n}=e.thermal,a=r?Sg(r,t):1,i=o?Sg(o,t):1,s=n?Sg(n,t):1;if(a===1&&i===1&&s===1)return e;if(e.kind==="simple")return{...e,muY0:e.muY0*a,muX0:e.muX0*i};let c={...e.coeffs},l=(u,m)=>{c[u]=(c[u]??1)*m};return l("LMUY",a),l("LMUX",i),l("LTR",s),l("LRES",s),{...e,coeffs:c}}function id(e,t,r){let o=0,n=0;for(let i=r;i<=t;i+=r){let s=Math.abs(e(i));s>n&&(n=s,o=i)}let a=r/10;for(let i=Math.max(a,o-r);i<=o+r;i+=a)n=Math.max(n,Math.abs(e(i)));return n}function bt(e){let t=NH(e),r=t,o=t,n=null,a=NaN,i=NaN,s=NaN,c=(x,S,R)=>(n!==null&&x===a&&S===i&&R===s||(n=Hx(r,x,S,R),a=x,i=S,s=R),n),l=null,u=NaN,m=NaN,p=NaN,d=(x,S,R)=>(l!==null&&x===u&&S===m&&R===p||(l=qx(r,x,S,R),u=x,m=S,p=R),l),f=x=>e.kind==="magic"?Wx(c(x.Fz,x.gamma??0,x.p),x.kappa,x.alpha):zL(o,x),h=(x,S,R=0,w)=>e.kind==="magic"?xg(d(S,R,w),x):LH(o,S,x),g=(x,S,R=0,w)=>e.kind==="magic"?Kx(c(S,R,w),x):DH(o,S,x),b=(x,S,R=0,w)=>e.kind==="magic"?OL(c(S,R,w),x):f({Fz:S,kappa:0,alpha:x,gamma:R,p:w}).Mz,y=x=>e.kind==="simple"?wg(o,x):id(S=>h(S*ad,x),45,1)/Math.max(1,x),v=x=>e.kind==="simple"?Mg(o,x):id(S=>g(S,x),.6,.02)/Math.max(1,x),k=x=>{let S=.1*ad;return Math.abs((h(S,x)-h(-S,x))/(2*S))};return{model:e,forces:f,Fx:g,Fy:h,Mz:b,muX:v,muY:y,corneringStiffness:k,verticalStiffness:()=>e.verticalStiffness,rollingRadius:x=>{if(e.kind==="magic"&&e.missing?.includes("UNLOADED_RADIUS"))return 0;let S=e.unloadedR0??0;if(!(S>0))return 0;let R=e.verticalStiffness*1e3;if(!(R>0))return S;let w=e.rollingFraction??.306;return S-w*Math.max(0,x)/R},relaxationLength:x=>{let S=e.relaxation;if(!S)return 0;let R=S.carcassStiffness??0;if(!(R>0))return S.sigma;let w=k(Math.max(0,x));return w>0?w/(R*1e3):S.sigma}}}function sd(e){let t=Math.max(1,e.model.kind==="magic"?e.model.fnomin:e.model.nominalLoad);return e.Fy(2*ad,t,0)-e.Fy(-2*ad,t,0)>=0?1:-1}function Si(e,t=e.kind==="magic"?e.fnomin:e.nominalLoad){let r=bt(e),o=2*ad,n=3*ad,a=r.Fy(o,t,0),i=r.Fy(o,t,n);return!Number.isFinite(a)||!Number.isFinite(i)?!1:Math.abs(i-a)>1}var Mfe=Math.PI/180;function mt(e,t){return e.axle?e.axle(t):e}function Zx(e,t){if(e===t)return e;let r=sd(e)*sd(t),o=(l,u)=>.5*(l+u),n=(l,u)=>l>0&&u>0?o(l,u):l>0?l:u>0?u:0,a=l=>{let u=e.forces(l),m=t.forces(l);return{Fx:o(u.Fx,m.Fx),Fy:o(u.Fy,r*m.Fy),Mz:o(u.Mz,r*m.Mz)}},i=(l,u,m=0,p)=>o(e.Fx(l,u,m,p),t.Fx(l,u,m,p)),s=(l,u,m=0,p)=>o(e.Fy(l,u,m,p),r*t.Fy(l,u,m,p)),c=(l,u,m=0,p)=>o(e.Mz(l,u,m,p),r*t.Mz(l,u,m,p));return{model:e.model,forces:a,Fx:i,Fy:s,Mz:c,muX:l=>id(u=>i(u,l),.6,.02)/Math.max(1,l),muY:l=>id(u=>s(u*Mfe,l),45,1)/Math.max(1,l),corneringStiffness:l=>o(e.corneringStiffness(l),t.corneringStiffness(l)),verticalStiffness:()=>n(e.verticalStiffness(),t.verticalStiffness()),rollingRadius:l=>n(e.rollingRadius(l),t.rollingRadius(l)),relaxationLength:l=>n(e.relaxationLength(l),t.relaxationLength(l)),axle:l=>l==="front"?e:t}}function nn(e){if(OH.has(e))return e;let t=zH.get(e);if(t)return t;let r;if(e.axle){let o=e.axle("front"),n=e.axle("rear"),a=nn(o),i=nn(n);r=a===o&&i===n?e:Zx(a,i)}else sd(e)>0?r=e:r={...e,forces:o=>{let n=e.forces(o);return{Fx:n.Fx,Fy:-n.Fy,Mz:-n.Mz}},Fy:(o,n,a,i)=>-e.Fy(o,n,a,i),Mz:(o,n,a,i)=>-e.Mz(o,n,a,i)};return OH.add(r),r!==e&&zH.set(e,r),r}var OH=new WeakSet,zH=new WeakMap;var Xx=25*(Math.PI/180);function _fe(e){let t=.6180339887,r=0,o=Xx,n=o-t*(o-r),a=r+t*(o-r),i=e(n),s=e(a);for(let l=0;l<12;l++)i>s?(o=a,a=n,s=i,n=o-t*(o-r),i=e(n)):(r=n,n=a,i=s,a=r+t*(o-r),s=e(a));return{alpha:i>s?n:a,force:Math.max(i,s)}}function _g(e,t,r,o,n=0){let a=Math.abs(t);if(!(a>0))return 0;let i=u=>Math.abs(e.Fy(u,r,0))+Math.abs(e.Fy(u,o,0)),s=0,c=Xx;if(i(Xx)<=a){let u=_fe(i);if(u.force<=a)return u.alpha;c=u.alpha}else if(n>0){let u=Math.max(0,n*.6),m=Math.min(Xx,n*1.6+.001);i(u)<a&&i(m)>=a&&(s=u,c=m)}let l=.001*a;for(let u=0;u<12;u++){let m=.5*(s+c),p=i(m)-a;if(p<0?s=m:c=m,Math.abs(p)<=l)return m}return c}var VL={shaft:!1,trail:0,hub:[0,0,0]};function jH(e){let t=e.spinAxis,r=Math.hypot(t[0],t[1]);if(r<1e-9)return[1,0,0];let o=[-t[1]/r,t[0]/r,0];return o[0]<0?[-o[0],-o[1],0]:o}function jL(e,t,r){let o=r.shaft?NL(e,t):[0,0,0];if(r.trail!==0){let a=jH(e),i=[t[0],t[1],0],s=se(i,ke(a,xe(i,a)));o=Ee(o,Ve(ke(a,-r.trail),s))}let n=r.hub;return(n[0]!==0||n[1]!==0||n[2]!==0)&&(o=se(o,Ve(se(e.contactPatch,e.wheelCenter),n))),{force:Ee(t,n),moment:o}}var Afe=(e,t)=>{let r=e!==void 0&&e>0?1/e:0,o=t!==void 0&&t>0?1/t:0;return r+o},Jx={ucaFront:0,ucaRear:0,lcaFront:0,lcaRear:0,tieRod:0,pushRod:0,rack:0};function nl(e){return!e.measured}function ki(e){if(!e)return!1;let t=r=>!!r&&Object.values(r).some(o=>o!==void 0&&o>0&&Number.isFinite(o));return t(e.links)||t(e.bushings)||e.rack!==void 0&&e.rack>0}function ol(e,t){let r=e.corner.hardpoints,o=Gm(e.rocker,t.points.rockerAngle);return{ucaFront:r.ucaFront,ucaRear:r.ucaRear,lcaFront:r.lcaFront,lcaRear:r.lcaRear,tieInner:Xc(e.inv,t.steer),rockerPivotA:r.rockerPivotA,rockerPivotB:r.rockerPivotB,damperChassis:e.inv.strut?t.points.uprightUpper:r.damperChassis,uprightUpper:t.points.uprightUpper,uprightLower:t.points.uprightLower,tieOuter:t.points.tieOuter,wheelCenter:t.points.wheelCenter,pushrodOuter:t.points.pushrodOuter,contactPatch:t.points.contactPatch,kingpinGround:t.points.kingpinGround,kingpinAtHub:t.points.kingpinAtHub,rockerToPushrod:o.pushrod,rockerToDamper:o.damper,spinAxis:t.points.spinAxis,direct:e.corner.config.actuation==="direct",decoupled:e.corner.config.actuation==="decoupled",mcpherson:e.inv.strut!==void 0,loadedRadius:e.corner.config.loadedRadius,tyreDeflection:0,load:NaN,lifted:!1,clearance:0,contactLength:0}}function BL(e,t,r=0){let o=t.links??{},n=t.bushings??{},a=(l,u,m)=>{let p=Afe(u,m);return p>0&&Number.isFinite(l)?l*p:0},i=n.topMount,s=e.topMount,c=s&&i!==void 0&&i>0&&s.every(Number.isFinite)?[-s[0]/i,-s[1]/i,-s[2]/i]:void 0;return{...c?{topMount:c}:{},ucaFront:a(e.ucaFront,o.ucaFront,n.ucaFront),ucaRear:a(e.ucaRear,o.ucaRear,n.ucaRear),lcaFront:a(e.lcaFront,o.lcaFront,n.lcaFront),lcaRear:a(e.lcaRear,o.lcaRear,n.lcaRear),tieRod:a(e.tieRod,o.tieRod,n.tieInner),pushRod:a(e.pushRod,o.pushRod,void 0),rack:r}}function BH(e,t,r,o){let n=yt(e,t);if(!(n>1e-9))return{axial:r,radius2:0};let a=(r*r-o*o+n*n)/(2*n);return{axial:a,radius2:Math.max(0,r*r-a*a)}}function Ag(e,t){let r=e.corner.hardpoints,o=e.inv,n={...o};if(o.strut&&t.topMount&&t.topMount.some(s=>s!==0)&&(n.strut={...o.strut,top:Ee(o.strut.top,t.topMount)}),t.ucaFront!==0||t.ucaRear!==0){let s=BH(r.ucaFront,r.ucaRear,yt(r.uprightUpper,r.ucaFront)+t.ucaFront,yt(r.uprightUpper,r.ucaRear)+t.ucaRear);n.ubjAxial0=s.axial,n.ubjRadius2=s.radius2}if(t.lcaFront!==0||t.lcaRear!==0){let s=BH(r.lcaFront,r.lcaRear,yt(r.uprightLower,r.lcaFront)+t.lcaFront,yt(r.uprightLower,r.lcaRear)+t.lcaRear),c=xe(o.lbjRel0,o.lcaDir),l=se(o.lbjRel0,ke(o.lcaDir,c)),u=Math.hypot(l[0],l[1],l[2]);n.lbjRel0=u>1e-9?Ee(ke(o.lcaDir,s.axial),ke(l,Math.sqrt(s.radius2)/u)):Ee(ke(o.lcaDir,s.axial),l)}if(t.tieRod!==0){let s=Math.sqrt(o.tieLen2)+t.tieRod;n.tieLen2=s*s}if(t.rack!==0&&(n.tieInner0=Ee(o.tieInner0,ke(o.rackAxis,t.rack))),t.pushRod===0)return{corner:e.corner,inv:n,rocker:e.rocker};let a=Math.sqrt(e.rocker.rodLen2)+t.pushRod,i={...e.rocker,rodLen2:a*a};return{corner:e.corner,inv:n,rocker:i}}var Cfe=8,Tfe=1e-5,Pfe=e=>({q:[e.pose.t[0],e.pose.t[1],e.pose.t[2],e.pose.omega[0],e.pose.omega[1],e.pose.omega[2]],phi:e.points.rockerAngle});function UL(e,t,r){let o=jL(e,r.force,r.extras??VL),n=r.alignMoment?Ee(o.moment,[0,0,r.alignMoment]):o.moment;return tl(e,t,o.force,n)}function ew(e,t,r,o,n,a,i=0){let s=zt(e,t,r,n,a),c=e.corner.compliance;if(!(ki(c)&&nl(e.corner)))return{state:s,forces:UL(ol(e,s),e.corner.config.pushrodAttach,o),deflection:Jx,rigid:s,iterations:0,converged:!0,bypassed:!0};let u=s,m=e,p=e.corner.config.pushrodAttach,d=UL(ol(e,s),p,o),f=Jx,h=!1,g=0;for(;g<Cfe;g++){let b=ol(m,u);if(d=UL(b,p,o),d.singular)break;f=BL(d,c,i),m=Ag(e,f);let y=zt(m,t,r,Pfe(u),a),v=yt(y.points.wheelCenter,u.points.wheelCenter);if(u=y,v<Tfe){h=!0;break}}return{state:u,forces:d,deflection:f,rigid:s,iterations:g+1,converged:h&&u.converged,bypassed:!1}}var Qx=1e3,UH=1e5;function GH(e,t,r,o,n){let a=ew(e,t,r,o,void 0,n);return{toe:a.state.metrics.toe,camber:a.state.metrics.camber,patch:a.state.points.contactPatch,converged:a.converged,bypassed:a.bypassed}}function cd(e,t,r,o,n){let a={force:[0,0,o]},i=(g,b=0)=>GH(e,t,r,{force:g,alignMoment:b},n),s=GH(e,t,r,a,n);if(s.bypassed)return{toePerLateral:0,camberPerLateral:0,toePerLongitudinal:0,camberPerLongitudinal:0,toePerAligning:0,lateralPatch:0,longitudinalPatch:0,bypassed:!0,converged:!0};let c=i([0,Qx,o]),l=i([0,-Qx,o]),u=i([Qx,0,o]),m=i([-Qx,0,o]),p=i([0,0,o],UH),d=i([0,0,o],-UH),f=(g,b)=>(g-b)/2,h=[s,c,l,u,m,p,d].every(g=>g.converged);return{toePerLateral:f(c.toe,l.toe),camberPerLateral:f(c.camber,l.camber),toePerLongitudinal:f(u.toe,m.toe),camberPerLongitudinal:f(u.camber,m.camber),toePerAligning:f(p.toe,d.toe),lateralPatch:f(c.patch[1],l.patch[1]),longitudinalPatch:f(u.patch[0],m.patch[0]),bypassed:!1,converged:h}}var Ffe=1e3;function GL(e,t=Ffe){if(!ki(e.compliance)||!nl(e))return;let r=sr(e),o=zt(r,0,0),n=cd(r,o.beta,0,t);if(!n.bypassed)return{toePerFy:n.toePerLateral/1e3,camberPerFy:n.camberPerLateral/1e3,toePerFx:n.toePerLongitudinal/1e3,camberPerFx:n.camberPerLongitudinal/1e3,toePerMz:n.toePerAligning/1e5}}function ld(e,t=-yg,r=yg,o=21){let n=e.measured;if(n)return{travel:[...n.travel],motionRatio:[...n.motionRatio],camber:[...n.camber],toe:[...n.toe],damperLen:n.damperLen?[...n.damperLen]:n.travel.map(()=>0)};let a=Xt(e,{travelMin:t,travelMax:r,steps:o}),i=GL(e);return{travel:a.samples.map(s=>s.travel),motionRatio:a.samples.map(s=>s.metrics.motionRatio??1),camber:a.samples.map(s=>s.metrics.camber),toe:a.samples.map(s=>s.metrics.toe),damperLen:a.samples.map(s=>s.metrics.damperLength),...i?{compliance:i}:{}}}function tw(e,t,r){let o=e.length;if(o===0)return 0;if(r<=e[0])return t[0];if(r>=e[o-1])return t[o-1];let n=0,a=o-1;for(;a-n>1;){let s=n+a>>1;e[s]<=r?n=s:a=s}let i=(r-e[n])/(e[a]-e[n]);return t[n]+i*(t[a]-t[n])}function Es(e,t){return{motionRatio:tw(e.travel,e.motionRatio,t),camber:tw(e.travel,e.camber,t),toe:tw(e.travel,e.toe,t),damperLen:tw(e.travel,e.damperLen,t)}}var qH=Math.PI/180,$fe=9.81;function Ls(e,t,r,o=0){let n=Lt(e),a=e.wheelbase*(1-e.frontMassFrac),i=e.wheelbase*e.frontMassFrac,s=rd(e,o),c=e.aero?.model?(k,x,S)=>rd(e,o,x,k,S):()=>s,l=Es(t,0),u=Es(r,0),m=e.loadFactor,p=m!==void 0&&m!==1?(m-1)*e.massTotal*$fe:0,d=p*e.frontMassFrac/2,f=p*(1-e.frontMassFrac)/2,h=(k,x)=>x>0&&Number.isFinite(x)&&k+x>0?x/(k+x):1,g=nr(e,"front"),b=nr(e,"rear"),y={F:h(e.wheelRateFront+(e.heaveSpringFront??0),g),R:h(e.wheelRateRear+(e.heaveSpringRear??0),b)},v={F:h(e.wheelRateFront+e.arbFront,g),R:h(e.wheelRateRear+e.arbRear,b)};return(k,x,S=0,R=0)=>{let w=c(k,x,S),M=n.rollGradient*k,T=M*qH,A=n.pitchGradient*x*qH,_=(q,U)=>{let B=U==="F"?e.trackFront:e.trackRear,V=U==="F"?n.rideRateFront:n.rideRateRear,E=(q==="R"?1:-1)*(B/2)*Math.tan(T),C=(U==="R"?i:-a)*Math.tan(A),$=`${U}${q}`,L=p?w[$]+(U==="F"?d:f):w[$],j=V>0?L/V:0;return{anti:E,sym:C+j}},F={FL:_("L","F"),FR:_("R","F"),RL:_("L","R"),RR:_("R","R")},P=q=>{let U=q[0];return F[q].sym*y[U]+F[q].anti*v[U]},I=td(e,R,n,{FL:P("FL"),FR:P("FR")}),z=M+I.rollDeg,N=(q,U)=>{let B=U==="F"?t:r,V=U==="F"?l:u,E=`${U==="F"?"F":"R"}${q}`,C=F[E].sym+F[E].anti+I.travel[E],$=P(E)+I.travel[E]*v[U],L=C-$,j=Es(B,$),K=(q==="R"?1:-1)*j.camber;return{travel:$,tyre:L,ground:C,camber:K,camberRoad:K+z,toe:j.toe,bumpToe:j.toe-V.toe,damperTravel:V.damperLen-j.damperLen}};return{FL:N("L","F"),FR:N("R","F"),RL:N("L","R"),RR:N("R","R"),steeringJacking:I}}}var qL=(e,t)=>{let r=Number(e);return Number.isFinite(r)?r:t};function Ds(e){return{enabled:e?.enabled===!0,roadFeedbackGain:Math.min(2,Math.max(0,qL(e?.roadFeedbackGain,1))),turnInFrictionNm:Math.max(0,qL(e?.turnInFrictionNm,0)),columnStiffnessNmPerRad:Math.max(0,qL(e?.columnStiffnessNmPerRad,0))}}function HL(e,t,r){let o=Ds(r);if(!o.enabled)return{roadNm:e,assistanceNm:0,frictionNm:0,columnTwistDeg:0,driverNm:e};let n=e*(o.roadFeedbackGain-1),a=t===0?0:Math.sign(t)*o.turnInFrictionNm,i=e+n+a,s=o.columnStiffnessNmPerRad>0?i/o.columnStiffnessNmPerRad*(180/Math.PI):0;return{roadNm:e,assistanceNm:n,frictionNm:a,columnTwistDeg:s,driverNm:i}}var HH=()=>({totalNm:0,aligningNm:0,lateralNm:0,longitudinalNm:0,jackingNm:0});function al(e){let t=e.steerFront;return!!(t?.rackRatioMmPerRev&&t.innerJacobian&&t.innerJacobian.length>=2&&t.outerJacobian&&t.outerJacobian.length>=2&&t.meanDeg.length>=2)}function Cg(e,t,r,o="model",n){let a=e.steerFront;if(!al(e)||!a)return null;let i=t<0?-1:1,c=a.rackRatioMmPerRev/(2*Math.PI)/1e3,l=t>=0,u=n&&a.travelSurface?Qm(a,Math.abs(t),l?n.FL:n.FR,l?n.FR:n.FL):ed(a,Math.abs(t));if(!u.innerJacobian||!u.outerJacobian)return null;let m=(g,b)=>{let y=r[g],v=g==="FL"?-1:1,k=-v*y.Fy,S={aligning:1e3*(-v*y.Mz)*b.yaw,lateral:k*b.lateral,longitudinal:y.Fx*b.longitudinal,jacking:y.Fz*b.vertical},R=HH();R.aligningNm=-i*S.aligning*c,R.lateralNm=-i*S.lateral*c,R.longitudinalNm=-i*S.longitudinal*c,R.jackingNm=-i*S.jacking*c,R.totalNm=R.aligningNm+R.lateralNm+R.longitudinalNm+R.jackingNm;let w=-i*(S.aligning+S.lateral+S.longitudinal+S.jacking);return{moment:R,rackN:w}},p=m("FL",l?u.innerJacobian:u.outerJacobian),d=m("FR",l?u.outerJacobian:u.innerJacobian),f=HH();for(let g of[p.moment,d.moment])f.aligningNm+=g.aligningNm,f.lateralNm+=g.lateralNm,f.longitudinalNm+=g.longitudinalNm,f.jackingNm+=g.jackingNm,f.totalNm+=g.totalNm;let h=HL(f.totalNm,t,e.steeringSystem);return f.totalNm=h.driverNm,{...f,roadNm:h.roadNm,assistanceNm:h.assistanceNm,frictionNm:h.frictionNm,columnTwistDeg:h.columnTwistDeg,rackForceN:p.rackN+d.rackN,aligningSource:o,perWheel:{FL:p.moment,FR:d.moment}}}var Ife=e=>"front"in e&&"rear"in e;function ud(e,t){return Ife(e)?e[t]:e}function WL(e,t,r=24){let o=Math.max(1,t),n=o/Math.max(1,r-1),a=[],i=[],s=[];for(let l=0;l<r;l++){let u=l*n;a.push(u),i.push(e.muX(u)),s.push(e.muY(u))}let c=(l,u)=>{if(!(u>0))return l[0];if(u>=o)return l[r-1];let m=Math.min(r-2,Math.floor(u/n)),p=(u-a[m])/n;return l[m]+p*(l[m+1]-l[m])};return{muX:l=>c(i,l),muY:l=>c(s,l)}}function KL(e,t){let r=Math.max(0,t.Fz),o=e.muY(r)*r,n=e.muX(r)*r;if(!(o>0))return{fyUsed:0,fyMax:0,fyRes:0};let a=n>0?Math.min(1,Math.abs(t.Fx)/n):0,i=o*Math.sqrt(Math.max(0,1-a*a)),s=Math.abs(t.Fy);return{fyUsed:s,fyMax:i,fyRes:Math.max(0,i-s)}}function KH(e,t,r){let o=KL(e,t),n=KL(e,r);return{left:o,right:n,fyRes:o.fyRes+n.fyRes}}function Ri(e,t,r){let o=KH(ud(e,"front"),t.FL,t.FR),n=KH(ud(e,"rear"),t.RL,t.RR),a=r.lf>0&&Number.isFinite(r.lf)?r.lf:0,i=r.lr>0&&Number.isFinite(r.lr)?r.lr:0,s=n.fyRes*i,c=o.fyRes*a,l=s-c,u=Math.max(Math.abs(s),Math.abs(c));return{stabil:s,agil:c,diff:l,rel:u>0?l/u:0,front:o,rear:n}}var Tg=[{q:"p",section:"INFLATION_PRESSURE_RANGE",min:"PRESMIN",max:"PRESMAX",what:"pressure"},{q:"fz",section:"VERTICAL_FORCE_RANGE",min:"FZMIN",max:"FZMAX",what:"load"},{q:"kappa",section:"LONG_SLIP_RANGE",min:"KPUMIN",max:"KPUMAX",what:"slip ratio"},{q:"alpha",section:"SLIP_ANGLE_RANGE",min:"ALPMIN",max:"ALPMAX",what:"slip angle"},{q:"gamma",section:"INCLINATION_ANGLE_RANGE",min:"CAMMIN",max:"CAMMAX",what:"inclination"}],Lfe=Tg.flatMap(e=>[e.min,e.max]);function Dfe(e){let t={};for(let r of Tg){let o=e[r.min],n=e[r.max],a={};Number.isFinite(o)&&(a.min=o),Number.isFinite(n)&&(a.max=n),(a.min!==void 0||a.max!==void 0)&&(t[r.q]=a)}return Object.keys(t).length?t:void 0}function Pg(e){if(e.kind==="magic")return e.range??Dfe(e.coeffs)}function YL(e){let t=Pg(e)?.fz?.max;return t!==void 0&&Number.isFinite(t)&&t>0?t:null}function il(e){return Math.max(1,e.kind==="magic"?e.fnomin:e.nominalLoad)}function WH(e,t,r,o,n){let a=(r-t)/o,i=t,s=e(t);for(let c=t+a;c<=r;c+=a){let l=e(c);n(l,s)&&(s=l,i=c)}return i}function rw(e,t=10*il(e)){let{turnover:r,collapse:o}=ZH(bt(e),t),n=[r,o].filter(a=>a!=null);return{turnover:r,collapse:o,declared:YL(e),limit:n.length?Math.min(...n):null}}function Wo(e){let t=YH.get(e);if(t!==void 0)return t;let r=10*il(e.model),{turnover:o,collapse:n}=ZH(e,r),a=o??n??r;return YH.set(e,a),a}var YH=new WeakMap;function ZH(e,t){let r=il(e.model),o=m=>e.muY(m),n=m=>o(m)*m,a=80,i=t/a,s=null,c=n(i);for(let m=2;m<=a;m++){let p=n(m*i);if(p<c){s=WH(n,(m-2)*i,m*i,20,(d,f)=>d>f);break}c=p}let l=null,u=o(i);for(let m=2;m<=a;m++){let p=o(m*i);if(p>u){let d=WH(o,(m-2)*i,m*i,40,(f,h)=>f<h);o(d)<.05*o(r)&&(l=d);break}u=p}return{turnover:s,collapse:l}}function ZL(e,t=il(e)){let r=bt(e),o=6*(Math.PI/180),n=r.forces({Fz:t,kappa:0,alpha:o,gamma:0}).Fy,a=r.forces({Fz:t,kappa:.15,alpha:o,gamma:0}).Fy,i=Math.abs(n)>1?Math.abs(a/n):1;return{kept:i,coupled:i<.97}}function sl(e,t=2.5*il(e)){let r=bt(e),o=0,n=il(e),a=10;for(let i=1;i<=a;i++){let s=t*i/a,c=Math.abs(r.forces({Fz:s,kappa:0,alpha:0,gamma:0}).Fx);s>0&&c/s>o/n&&(o=c,n=s)}return{ghostFx:o,atLoad:n,ratio:o/n,trustworthy:o/n<=.03}}var XH=.1;function cl(e,t=il(e)){let r=bt(e).muX(t);return{muX:r,none:Number.isFinite(r)&&r<XH}}function XL(e,t){return t?e.trustworthy!==t.trustworthy?e.trustworthy?t:e:t.ratio>e.ratio?t:e:e}var JH=["FL","FR","RL","RR"],Nfe=e=>e==="FL"||e==="RL",Ofe=e=>e==="FL"||e==="FR"?"front":"rear";function nw(e,t,r,o){if(!(e.full>e.open)||o.ayDir===0)return e.full;let n=o.halfTrack[e.axle],a={};for(let l of JH)a[l]={...t[l]};let i=l=>{let u=0;for(let p of JH)Ofe(p)===e.axle&&(a[p].Fx=e.sense*(p===e.strong?l-e.open/2:e.open/2),u-=(Nfe(p)?n:-n)*a[p].Fx);let m=Ri(r,a,o.arms);return u*o.ayDir>=0?Math.abs(u)<=m.stabil:Math.abs(u)<=m.agil};if(i(e.full))return e.full;let s=e.open,c=e.full;for(let l=0;l<20&&c-s>.001*e.full;l++){let u=.5*(s+c);i(u)?s=u:c=u}return s}var zfe=[["PCY1","Shape factor Cfy for lateral forces",1.3],["PDY1","Lateral friction Muy",1],["PDY2","Variation of friction Muy with load",0],["PDY3","Variation of friction Muy with squared camber",0],["PEY1","Lateral curvature Efy at Fznom",0],["PEY2","Variation of curvature Efy with load",0],["PEY3","Zero order camber dependency of curvature Efy",0],["PEY4","Variation of curvature Efy with camber",0],["PEY5","Variation of curvature Efy with camber squared",0],["PKY1","Maximum value of stiffness Kfy/Fznom",-15],["PKY2","Load at which Kfy reaches maximum value",2],["PKY3","Variation of Kfy/Fznom with camber",0],["PKY4","Curvature of stiffness Kfy",2],["PKY5","Peak stiffness variation with camber squared",0],["PKY6","Fy camber stiffness factor",0],["PKY7","Vertical load dependency of camber stiffness",0],["PHY1","Horizontal shift Shy at Fznom",0],["PHY2","Variation of shift Shy with load",0],["PHY3","Variation of shift Shy with camber",0],["PVY1","Vertical shift in Svy/Fz at Fznom",0],["PVY2","Variation of shift Svy/Fz with load",0],["PVY3","Variation of shift Svy/Fz with camber",0],["PVY4","Variation of shift Svy/Fz with camber and load",0],["PPY1","Influence of inflation pressure on cornering stiffness",0],["PPY2","Influence of inflation pressure on dependency of nominal tyre load on cornering stiffness",0],["PPY3","Linear influence of inflation pressure on lateral peak friction",0],["PPY4","Quadratic influence of inflation pressure on lateral peak friction",0],["PPY5","Influence of inflation pressure on camber stiffness",0]],Vfe=[["PCX1","Shape factor Cfx for longitudinal force",1.65],["PDX1","Longitudinal friction Mux at Fznom",1],["PDX2","Variation of friction Mux with load",0],["PDX3","Variation of friction Mux with camber squared",0],["PEX1","Longitudinal curvature Efx at Fznom",0],["PEX2","Variation of curvature Efx with load",0],["PEX3","Variation of curvature Efx with load squared",0],["PEX4","Factor in curvature Efx while driving",0],["PKX1","Longitudinal slip stiffness Kfx/Fz at Fznom",20],["PKX2","Variation of slip stiffness Kfx/Fz with load",0],["PKX3","Exponent in slip stiffness Kfx/Fz with load",0],["PHX1","Horizontal shift Shx at Fznom",0],["PHX2","Variation of shift Shx with load",0],["PVX1","Vertical shift Svx/Fz at Fznom",0],["PVX2","Variation of shift Svx/Fz with load",0],["PPX1","Linear influence of inflation pressure on longitudinal slip stiffness",0],["PPX2","Quadratic influence of inflation pressure on longitudinal slip stiffness",0],["PPX3","Linear influence of inflation pressure on peak longitudinal friction",0],["PPX4","Quadratic influence of inflation pressure on peak longitudinal friction",0]],jfe=[["QBZ1","Trail slope factor for trail Bpt at Fznom",8],["QBZ2","Variation of slope Bpt with load",0],["QBZ3","Variation of slope Bpt with load squared",0],["QBZ4","Variation of slope Bpt with camber",0],["QBZ5","Variation of slope Bpt with absolute camber",0],["QBZ6","Camber influence Bt",0],["QBZ9","Factor for scaling factors of slope factor Br of Mzr",0],["QBZ10","Factor for dimensionless cornering stiffness of Br of Mzr",0],["QCZ1","Shape factor Cpt for pneumatic trail",1.1],["QDZ1","Peak trail Dpt = Dpt*(Fz/Fznom*R0)",.1],["QDZ2","Variation of peak Dpt with load",0],["QDZ3","Variation of peak Dpt with camber",0],["QDZ4","Variation of peak Dpt with camber squared",0],["QDZ6","Peak residual torque Dmr = Dmr/(Fz*R0)",0],["QDZ7","Variation of peak factor Dmr with load",0],["QDZ8","Variation of peak factor Dmr with camber",0],["QDZ9","Variation of peak factor Dmr with camber and load",0],["QDZ10","Variation of peak factor Dmr with camber squared",0],["QDZ11","Variation of Dmr with camber squared and load",0],["QEZ1","Trail curvature Ept at Fznom",0],["QEZ2","Variation of curvature Ept with load",0],["QEZ3","Variation of curvature Ept with load squared",0],["QEZ4","Variation of curvature Ept with sign of Alpha-t",0],["QEZ5","Variation of Ept with camber and sign Alpha-t",0],["QHZ1","Trail horizontal shift Sht at Fznom",0],["QHZ2","Variation of shift Sht with load",0],["QHZ3","Variation of shift Sht with camber",0],["QHZ4","Variation of shift Sht with camber and load",0],["PPZ1","Effect of inflation pressure on length of pneumatic trail",0],["PPZ2","Influence of inflation pressure on residual aligning torque",0],["SSZ1","Nominal value of s/R0: effect of Fx on Mz",0],["SSZ2","Variation of distance s/R0 with Fy/Fznom",0],["SSZ3","Variation of distance s/R0 with camber",0],["SSZ4","Variation of distance s/R0 with load and camber",0]],Bfe=[["RBX1","Slope factor for combined slip Fx reduction",0],["RBX2","Variation of slope Fx reduction with kappa",0],["RBX3","Influence of camber on stiffness for Fx combined",0],["RCX1","Shape factor for combined slip Fx reduction",1],["REX1","Curvature factor of combined Fx",0],["REX2","Curvature factor of combined Fx with load",0],["RHX1","Shift factor for combined slip Fx reduction",0],["RBY1","Slope factor for combined Fy reduction",0],["RBY2","Variation of slope Fy reduction with alpha",0],["RBY3","Shift term for alpha in slope Fy reduction",0],["RBY4","Influence of camber on stiffness of Fy combined",0],["RCY1","Shape factor for combined Fy reduction",1],["REY1","Curvature factor of combined Fy",0],["REY2","Curvature factor of combined Fy with load",0],["RHY1","Shift factor for combined Fy reduction",0],["RHY2","Shift factor for combined Fy reduction with load",0],["RVY1","Kappa induced side force Svyk/Muy*Fz at Fznom",0],["RVY2","Variation of Svyk/Muy*Fz with load",0],["RVY3","Variation of Svyk/Muy*Fz with camber",0],["RVY4","Variation of Svyk/Muy*Fz with alpha",0],["RVY5","Variation of Svyk/Muy*Fz with kappa",1],["RVY6","Variation of Svyk/Muy*Fz with atan(kappa)",0]],Ufe=[["LFZO","Scale factor of nominal (rated) load",1],["LCX","Scale factor of Fx shape factor",1],["LMUX","Scale factor of Fx peak friction coefficient",1],["LEX","Scale factor of Fx curvature factor",1],["LKX","Scale factor of Fx slip stiffness",1],["LHX","Scale factor of Fx horizontal shift",1],["LVX","Scale factor of Fx vertical shift",1],["LCY","Scale factor of Fy shape factor",1],["LMUY","Scale factor of Fy peak friction coefficient",1],["LEY","Scale factor of Fy curvature factor",1],["LKY","Scale factor of Fy cornering stiffness",1],["LKYC","Scale factor of camber force stiffness",1],["LKZC","Scale factor of camber torque stiffness",1],["LHY","Scale factor of Fy horizontal shift",1],["LVY","Scale factor of Fy vertical shift",1],["LTR","Scale factor of peak of pneumatic trail",1],["LRES","Scale factor for offset of residual torque",1],["LXAL","Scale factor of alpha influence on Fx",1],["LYKA","Scale factor of kappa influence on Fy",1],["LVYKA","Scale factor of kappa induced Fy",1],["LS","Scale factor of moment arm of Fx",1]],eK=[["lateral",zfe],["longitudinal",Vfe],["aligning",jfe],["combined",Bfe],["scaling",Ufe]].flatMap(([e,t])=>t.map(([r,o,n])=>({key:r,section:e,text:o,fallback:n}))),Aje=new Map(eK.map(e=>[e.key,e]));var Gfe=/^\$\s*EDITED\s+([A-Z][A-Z0-9_]*)\s+was\s+(absent|[-+0-9.eE]+)\s*$/;function tK(e){let t={};for(let r of e.split(/\r?\n/)){let o=r.trim().match(Gfe);if(!o)continue;let n=o[2]==="absent"?null:parseFloat(o[2]);(n===null||Number.isFinite(n))&&(t[o[1]]=n)}return Object.keys(t).length?t:void 0}var Hfe=/^\s*\$\s*UNLOADED_RADIUS_STAND_IN\s*=\s*([0-9.eE+-]+)/,Kfe=/^\$-+ written by (?:PaceDynamics|PaceLab)\b/m,Wfe=/^\$\s*AXIS_SYSTEM\s*=\s*(ISO-W|SAE)\b/m;function Yfe(e){let t=e.match(Wfe);return t?{axisSystem:t[1]==="SAE"?"sae":"iso",trustSide:!0}:Kfe.test(e)?{axisSystem:"sae",trustSide:!1}:{axisSystem:"iso",trustSide:!0}}function Zfe(e){return e>=62?"6.2":e>=61?"6.1":"5.2"}var rK=new Map([["pa",1],["pascal",1],["kpa",1e3],["kilopascal",1e3],["mpa",1e6],["megapascal",1e6],["bar",1e5],["psi",6894.757293168]]);function Xfe(e,t,r){let o=r.PRESSURE?.trim().toLowerCase(),n=o===void 0?1:rK.get(o);if(n===void 0)return;let a=(c,l)=>l===1?c:Number((c*l).toPrecision(12)),i=e.NOMPRES??e.INFLPRES;if(i!==void 0)return a(i,n);let s=e.INFLATION_PRESSURE;if(s!==void 0)return o!==void 0?a(s,n):t.PROPERTY_FILE_FORMAT?.trim().toUpperCase()==="MF_05"?a(s,1e5):void 0}var Jfe=new Map([["radians",1],["radian",1],["rad",1],["degrees",Math.PI/180],["degree",Math.PI/180],["deg",Math.PI/180]]);function Qfe(e,t){let r=(i,s)=>i===void 0?1:s.get(i.trim().toLowerCase()),o=r(t.ANGLE,Jfe),n={fz:1,kappa:1,alpha:o,gamma:o,p:r(t.PRESSURE,rK)},a={};for(let i of Tg){let s=n[i.q];if(s===void 0)continue;let c={};for(let[l,u]of[["min",i.min],["max",i.max]]){let m=e[u];Number.isFinite(m)&&(c[l]=s===1?m:Number((m*s).toPrecision(12)),delete e[u])}(c.min!==void 0||c.max!==void 0)&&(a[i.q]=c)}return Object.keys(a).length?a:void 0}function ll(e,t="imported",r={}){let o=Yfe(e),n=r.axisSystem??o.axisSystem,a={},i={},s={},c="",l;for(let b of e.split(/\r?\n/)){let y=b.match(Hfe);y&&(l=parseFloat(y[1]));let v=b.replace(/[$!].*$/,"").trim();if(!v)continue;if(v.startsWith("[")){c=(v.match(/^\[([^\]]*)/)?.[1]??"").trim().toUpperCase();continue}let k=v.indexOf("=");if(k<0)continue;let x=v.slice(0,k).trim().toUpperCase(),S=v.slice(k+1).trim(),R=S.match(/^'([^']*)'|^"([^"]*)"/);if(R){i[x]=R[1]??R[2]??"",c==="UNITS"&&(s[x]=i[x]);continue}let w=parseFloat(S);Number.isFinite(w)&&(a[x]=w)}let u=Zfe(a.FITTYP??62),m=tK(e),p=m?Object.fromEntries(Object.entries(m).filter(([b])=>a[b]!==void 0)):void 0,d=a.VERTICAL_STIFFNESS??a.KZ??0,f=Xfe(a,i,s),h=Qfe(a,s),g=[];return a.UNLOADED_RADIUS===void 0&&a.R0===void 0&&g.push("UNLOADED_RADIUS"),d<=0&&g.push("VERTICAL_STIFFNESS"),a.FNOMIN===void 0&&g.push("FNOMIN"),f===void 0&&g.push("NOMPRES"),{kind:"magic",name:t,version:u,coeffs:a,axisSystem:n,side:o.trustSide?i.TYRESIDE==="RIGHT"?"right":i.TYRESIDE==="LEFT"?"left":void 0:void 0,fnomin:a.FNOMIN??5e3,unloadedR0:a.UNLOADED_RADIUS??a.R0??(l!==void 0&&l>0?l:.3),...a.WIDTH!==void 0&&a.WIDTH>0?{sectionWidth:a.WIDTH}:{},verticalStiffness:d>0?d/1e3:0,...a.FREFF!==void 0&&!a.DREFF?{rollingFraction:a.FREFF}:{},...a.LATERAL_STIFFNESS!==void 0&&a.LATERAL_STIFFNESS>0?{relaxation:{sigma:0,carcassStiffness:a.LATERAL_STIFFNESS/1e3,source:"fitted"}}:{},nomPressure:f??0,missing:g,...p&&Object.keys(p).length?{edited:p}:{},...h?{range:h}:{}}}function zn(e){if(!e)return null;let t=e.unloadedR0;return t===void 0||!(t>0)||e.kind==="magic"&&e.missing?.includes("UNLOADED_RADIUS")?null:t*1e3}function Fg(e){if(!e)return null;let t=e.sectionWidth;return t!==void 0&&t>0?t:null}var Lje=Math.PI/180;var JL=Math.PI/180,ehe=180/Math.PI,QL=[{key:"muY",group:"grip",label:"Peak \u03BCy",unit:"",decimals:2,better:"high",about:"Peak lateral grip at the reference load \u2014 the most side force this tyre makes, per newton of load on it."},{key:"muYLow",group:"grip",label:"\u03BCy light",unit:"",decimals:2,better:"high",about:"Peak lateral grip at the light load \u2014 an inside wheel in a corner."},{key:"muYHigh",group:"grip",label:"\u03BCy loaded",unit:"",decimals:2,better:"high",about:"Peak lateral grip at the most any wheel carries on this car. The gap to the light figure is the load sensitivity."},{key:"loadSens",group:"grip",label:"\u0394\u03BCy",unit:"/kN",decimals:3,better:"high",about:"How much peak lateral grip is lost per kilonewton of extra load. Always negative; nearer zero is a tyre that repays load transfer instead of punishing it."},{key:"muX",group:"grip",label:"Peak \u03BCx",unit:"",decimals:2,better:"high",about:"Peak longitudinal grip at the reference load \u2014 braking and traction."},{key:"kept",group:"grip",label:"Fy kept",unit:"%",decimals:0,better:"high",about:"How much of the side force at 6\xB0 of slip survives a slip ratio of 0.15. A tyre has one contact patch, so this should be well under 100 %; exactly 100 % means the fit never determined its combined-slip weights and its friction envelope is a box."},{key:"cornering",group:"response",label:"C\u03B1",unit:"N/\xB0",decimals:0,better:"high",about:"Cornering stiffness at the reference load: how hard the tyre pushes back for the first degree of slip."},{key:"peakSlip",group:"response",label:"\u03B1 at peak",unit:"\xB0",decimals:1,better:"none",about:"The slip angle where the side force peaks. A low figure is a sharp tyre that gives its grip early and lets go quickly; a high one is forgiving and slower to build. Neither is better, and a driver has an opinion."},{key:"bestCamber",group:"response",label:"Wants camber",unit:"\xB0",decimals:1,better:"none",about:"The inclination at which peak side force is greatest \u2014 what the tyre asks the suspension to deliver at the contact patch. Blank for a model with no camber term at all. Read it as what the FIT says: TTC cornering runs hold 0, 2 and 4\xB0 of camber, so for a tyre fitted from them everything at negative camber is the model extrapolating."},{key:"vertical",group:"response",label:"Vertical rate",unit:"N/mm",decimals:0,better:"none",about:"The tyre spring, for ride. Blank when the file did not measure one, in which case the car\u2019s own rate stands in."},{key:"limit",group:"trust",label:"Good to",unit:"N",decimals:0,better:"none",about:"The load above which this fit stops behaving like a tyre \u2014 more load buys less force. The lap holds its grip there. Below what the car reaches, and everything above it is extrapolation."},{key:"tested",group:"trust",label:"Tested to",unit:"N",decimals:0,better:"none",about:"The highest load in the rig data behind this fit (FZMAX). Above it the fit extends its load trend, up to Good to. Blank when the file does not say."},{key:"ghost",group:"trust",label:"Ghost Fx",unit:"%",decimals:1,better:"low",about:"Longitudinal force the fit produces while rolling straight at zero slip ratio, as a fraction of load. Real rolling resistance is 1\u20132 %; anything above 3 % is a longitudinal block that was never determined by data."}];function ow(e,t,r=0){let o=0,n=0;for(let s=0;s<=45;s+=1){let c=Math.abs(e(s*JL,t,r));c>o&&(o=c,n=s)}let a=Math.max(0,n-1),i=n+1;for(let s=a;s<=i;s+=.1){let c=Math.abs(e(s*JL,t,r));c>o&&(o=c,n=s)}return{peak:o,atDeg:n}}function nK(e,t){let r=ow(e,t,0).peak,o=0;for(let n=-6;n<=6;n+=1){if(n===0)continue;let{peak:a}=ow(e,t,n*JL);a>r&&(r=a,o=n)}return o}function eD(e,t,r){let o=bt(t),n=rw(t),a=sl(t),i=ZL(t,r.ref),s=o.muY(r.low),c=o.muY(r.ref),l=o.muY(r.high),u=(r.high-r.low)/1e3,m=ow(o.Fy,r.ref),p=o.verticalStiffness(),d=Si(t,r.ref),f=cl(t,r.ref).none,h={muY:c,muYLow:s,muYHigh:l,loadSens:u>=.1?(l-s)/u:null,muX:f?null:o.muX(r.ref),kept:f?null:100*i.kept,cornering:o.corneringStiffness(r.ref)/ehe,peakSlip:m.atDeg,bestCamber:d?nK(o.Fy,r.ref):null,vertical:p>0?p:null,limit:n.limit,tested:n.declared,ghost:100*a.ratio},g=x=>n.limit!=null&&n.limit<x?"extrapolated":"measured",b=f?"absent":a.trustworthy?g(r.ref):"assumed",y={muY:g(r.ref),muYLow:g(r.low),muYHigh:g(r.high),loadSens:g(r.high),muX:b,kept:f?"absent":i.coupled?g(r.ref):"assumed",cornering:g(r.ref),peakSlip:g(r.ref),bestCamber:d?g(r.ref):"absent",vertical:p>0?"measured":"absent",limit:"measured",tested:n.declared!=null?"measured":"absent",ghost:"measured"},v=[];f?v.push({kind:"noFx",level:"warn",text:"No drive or braking grip in this file: its longitudinal block is zero, as a cornering-only fit writes it. A car on it cannot accelerate or brake."}):i.coupled||v.push({kind:"box",level:"warn",text:"No combined-slip weights in this fit: its friction envelope is a box, so it will brake at full grip while cornering at full grip."}),a.trustworthy||v.push({kind:"ghost",level:"warn",text:`Rolling straight at zero slip ratio this fit makes ${a.ghostFx.toFixed(0)} N \u2014 ${(100*a.ratio).toFixed(0)} % of the load at ${a.atLoad.toFixed(0)} N. Its longitudinal block was not determined by data.`}),n.limit!=null&&n.limit<r.high&&v.push({kind:"beyond",level:"warn",text:`The fit stops behaving like a tyre at ${n.limit.toFixed(0)} N, below the ${r.high.toFixed(0)} N this car puts on its most loaded wheel. Everything at that load is extrapolation.`}),p<=0&&v.push({kind:"noRate",level:"note",text:"No vertical stiffness in this file, so the car\u2019s own tyre rate stands in. Changing to this tyre will not change the ride rate."});let k=t.kind==="magic"?(t.missing??[]).filter(x=>x!=="VERTICAL_STIFFNESS"):[];return k.length>0&&v.push({kind:"missing",level:"note",text:`Not in this file: ${k.join(", ")}.`}),{id:e,name:t.name,kind:t.kind,values:h,trust:y,flags:v}}function $g(){return{kind:"simple",name:"Simple (default)",Bx:11,Cx:1.6,muX0:1.7,loadSensX:-8e-5,By:9,Cy:1.4,muY0:1.6,loadSensY:-1e-4,nominalLoad:1500,verticalStiffness:120}}var oK=`$ AXIS_SYSTEM = SAE (authored in the evaluation frame: y right)
|
|
80
80
|
[MODEL]
|
|
81
81
|
FITTYP = 62
|
|
82
82
|
[DIMENSION]
|