@selvajs/compute 4.0.0-beta.4 → 4.0.0-beta.5
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/core-CEa0SxYF.cjs +3 -0
- package/dist/core-CEa0SxYF.cjs.map +1 -0
- package/dist/core-DONB46aK.js +3 -0
- package/dist/core-DONB46aK.js.map +1 -0
- package/dist/core.cjs +1 -2
- package/dist/core.d.cts +2 -219
- package/dist/core.d.ts +2 -219
- package/dist/core.js +1 -2
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.cjs.map +1 -1
- package/dist/grasshopper.d.cts +1214 -1220
- package/dist/grasshopper.d.ts +1214 -1220
- package/dist/grasshopper.js +1 -1
- package/dist/grasshopper.js.map +1 -1
- package/dist/index-BNsid0_9.d.cts +458 -0
- package/dist/index-BNsid0_9.d.ts +458 -0
- package/dist/index.cjs +0 -1
- package/dist/index.d.cts +1 -2
- package/dist/index.d.ts +1 -2
- package/dist/index.js +1 -1
- package/package.json +12 -10
- package/dist/chunk-AYH5O3VG.js +0 -4
- package/dist/chunk-AYH5O3VG.js.map +0 -1
- package/dist/chunk-MLPWPV6F.cjs +0 -4
- package/dist/chunk-MLPWPV6F.cjs.map +0 -1
- package/dist/core.cjs.map +0 -1
- package/dist/core.js.map +0 -1
- package/dist/handle-files-DMK9bCOW.d.cts +0 -231
- package/dist/handle-files-DMK9bCOW.d.ts +0 -231
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
package/dist/grasshopper.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as l,b as y,c as d,d as p,g as c,h as _,j as P,k as se,l as oe,n as ie,o as ae,p as N,q as O,r as S,s as We,t as j}from"./chunk-AYH5O3VG.js";var b=class b{constructor(e,r){l(this,"serverUrl");l(this,"apiKey");l(this,"disposed",!1);l(this,"activeMonitors",new Set);l(this,"activeTimeouts",new Set);this.serverUrl=P(e),this.apiKey=r}buildHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,r={},n=b.DEFAULT_TIMEOUT_MS){let s=new Headers(this.buildHeaders());r.headers&&new Headers(r.headers).forEach((a,u)=>{s.set(u,a)});let o={};s.forEach((a,u)=>{o[u]=a});let i={...r,headers:o};return n>0&&!i.signal&&(i.signal=AbortSignal.timeout(n)),fetch(e,i)}async isServerOnline(e=5e3){this.ensureNotDisposed();let r=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(r,{method:"GET"},e)).ok}catch(n){return p().debug("[ComputeServerStats] Fetch error:",n),!1}}async getActiveChildren(e={}){this.ensureNotDisposed();let{initialize:r=!0}=e,n=r?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,s=r?b.LIFECYCLE_TIMEOUT_MS:b.DEFAULT_TIMEOUT_MS;try{let o=await this.fetchWithTimeout(n,{},s);if(!o.ok)return p().warn("[ComputeServerStats] Failed to fetch active children:",o.status),null;let i=(await o.text()).trim();return/^\d+$/.test(i)?parseInt(i,10):(p().warn("[ComputeServerStats] Invalid active children response:",i),null)}catch(o){return p().warn("[ComputeServerStats] Error fetching active children:",o),null}}async getVersion(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch version:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return{rhino:n.rhino??"",compute:n.compute??"",git_sha:n.git_sha??null}}catch{return{rhino:r,compute:"",git_sha:null}}}catch(e){return p().warn("[ComputeServerStats] Error fetching version:",e),null}}async getInstalledPlugins(e="gh"){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${e}/installed`);if(!r.ok)return p().warn(`[ComputeServerStats] Failed to fetch ${e} plugins:`,r.status),null;let n=await r.text();try{let s=JSON.parse(n);return s&&typeof s=="object"?s:null}catch{return null}}catch(r){return p().warn(`[ComputeServerStats] Error fetching ${e} plugins:`,r),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[r,n]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...r&&{version:r},...n!==null&&{activeChildren:n}}}async purgeCache(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:"POST"});if(!e.ok)return p().warn("[ComputeServerStats] Failed to purge cache:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return typeof n.purged=="number"?n.purged:null}catch{return null}}catch(e){return p().warn("[ComputeServerStats] Error purging cache:",e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return p().warn("[ComputeServerStats] purgeAllChildren: could not read child count"),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let r=e*2,n=0;for(let s=0;s<r;s++){let o=await this.purgeCache();o!==null&&(n+=o)}return{totalPurged:n,calls:r,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch server time:",e.status),null;let r=(await e.text()).trim().replace(/^"|"$/g,""),n=new Date(r);return isNaN(n.getTime())?null:n}catch(e){return p().warn("[ComputeServerStats] Error fetching server time:",e),null}}async getIdleSpan(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch idle span:",e.status),null;let r=parseFloat((await e.text()).trim());return isNaN(r)?null:r}catch(e){return p().warn("[ComputeServerStats] Error fetching idle span:",e),null}}async launchChildren(){return this.postJson("/launch-children")}async launchChild(e){let r=e===void 0?"/launch-child":`/launch-child?port=${e}`;return this.postJson(r)}async shutdownChildren(e){let r=e===void 0?"/shutdown-children":`/shutdown-children?port=${e}`;return this.postJson(r)}async recycleChildren(e){let r=e===void 0?"/recycle-children":`/recycle-children?port=${e}`;return this.postJson(r)}async postJson(e){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}${e}`,{method:"POST"},b.LIFECYCLE_TIMEOUT_MS);if(!r.ok)return p().warn(`[ComputeServerStats] POST ${e} failed:`,r.status),null;let n=await r.text();try{return JSON.parse(n)}catch{return null}}catch(r){return p().warn(`[ComputeServerStats] Error on POST ${e}:`,r),null}}monitor(e,r=5e3){if(this.ensureNotDisposed(),!Number.isFinite(r)||r<b.MIN_MONITOR_INTERVAL_MS)throw new RangeError(`monitor() intervalMs must be a finite number >= ${b.MIN_MONITOR_INTERVAL_MS}ms, got ${r}. Sub-${b.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`);let n=!0,s=null;p().info(`\u{1F504} Starting server stats monitoring every ${r}ms`);let o=async()=>{if(s!==null&&(this.activeTimeouts.delete(s),s=null),!(!n||this.disposed)){try{let a=await this.getServerStats();if(!n||this.disposed)return;try{e(a)}catch(u){p().error("[ComputeServerStats] Monitor callback threw:",u)}}catch(a){!n||this.disposed?p().debug("[ComputeServerStats] Monitor poll cancelled during shutdown:",a):p().error("[ComputeServerStats] Failed to fetch stats during monitor:",a)}n&&!this.disposed&&(s=setTimeout(()=>{o()},r),this.activeTimeouts.add(s))}},i=()=>{n=!1,s!==null&&(clearTimeout(s),this.activeTimeouts.delete(s),s=null),this.activeMonitors.delete(i)};return this.activeMonitors.add(i),o(),i}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new d("ComputeServerStats has been disposed and cannot be used",y.INVALID_STATE,{context:{disposed:this.disposed}})}};l(b,"DEFAULT_TIMEOUT_MS",5e3),l(b,"LIFECYCLE_TIMEOUT_MS",6e4),l(b,"MIN_MONITOR_INTERVAL_MS",100);var I=b;var ue=new Set;function $e(){if(typeof window>"u"||globalThis.process?.versions?.node!=null)return!1;let e=globalThis.navigator,r=typeof e?.userAgent=="string"?e.userAgent:"";return!/jsdom/i.test(r)}function D(t,e){e||$e()&&!ue.has(t)&&(ue.add(t),p().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`))}var _e="Unable to load grasshopper definition",je={definition_not_cached:y.DEFINITION_NOT_CACHED};function B(t){return{...t,serverErrorCodes:{...je,...t.serverErrorCodes}}}function Be(t){return t instanceof d?t.code===y.DEFINITION_NOT_CACHED||t.message.includes(_e):!1}function Ue(t,e){if(!e)return;let r=c(t,"values");if(!Array.isArray(r)||r.length===0)return;let n=[];for(let o of r){let i=c(o,"innerTree");(!i||Object.keys(i).length===0)&&n.push(c(o,"paramName")??"<unnamed>")}if(n.length===0)return;let s=n.length===r.length?"all":`${n.length}/${r.length}`;p().warn(`Solve returned empty output(s) (${s}): ${n.join(", ")}. These parameters produced no data \u2014 check the definition's inputs and the branch feeding each.`)}async function k(t,e,r){D("solveGrasshopperDefinition",r.suppressBrowserWarning);let n=await U(e),{response:s}=await M(E(n,t),r);return s}async function le(t,e,r){D("solveGrasshopperDefinitionWithCacheKey",r.suppressBrowserWarning);let n=await U(e);return M(E(n,t),r)}async function pe(t,e,r,n){D("solveByCacheKey",n.suppressBrowserWarning);let s={algo:null,pointer:e,values:t};try{return{...await M(s,n),missed:!1}}catch(o){if(!Be(o))throw o;let i=await U(r);return{...await M(E(i,t),n),missed:!0}}}async function U(t){if(!S(t))return t;try{return await t.load()}catch(e){throw new d(`Failed to load definition bytes for ref '${t.key}'`,y.INVALID_INPUT,{context:{definitionKey:t.key},originalError:e instanceof Error?e:new Error(String(e))})}}async function M(t,e){ze(t,e);let r=await O("grasshopper",t,B(e)),{pointer:n,algo:s,...o}=r,i=o,a=N(r);if(a!==void 0){let u=typeof s=="string"?s.length:0;ae(i,Math.max(0,a-u))}return Ue(i,e.debug),{response:i,cacheKey:typeof n=="string"?n:null}}function E(t,e){let r={algo:null,pointer:null,values:e};return t instanceof Uint8Array?r.algo=ie(t):/^https?:\/\//i.test(t)?r.pointer=t:r.algo=oe(t)??se(t),r}function ze(t,e){e.cachesolve!=null&&(t.cachesolve=e.cachesolve),e.cacheerroredsolves!=null&&(t.cacheerroredsolves=e.cacheerroredsolves),e.modelunits!=null&&(t.modelunits=e.modelunits),e.angletolerance!=null&&(t.angletolerance=e.angletolerance),e.absolutetolerance!=null&&(t.absolutetolerance=e.absolutetolerance),e.dataversion!=null&&(t.dataversion=e.dataversion)}function ce(t){let e=new WeakSet,r=n=>{if(n===void 0)return"undefined";if(n===null)return"null";if(typeof n=="number")return Number.isFinite(n)?String(n):"null";if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="bigint")return`${n}n`;if(n instanceof Uint8Array)return`{"__u8":${n.length},"hash":"${me(n)}"}`;if(Array.isArray(n)){if(e.has(n))return'"[Circular]"';e.add(n);let s=[];for(let o=0;o<n.length;o++)s.push(r(n[o]));return e.delete(n),`[${s.join(",")}]`}if(typeof n=="object"){if(e.has(n))return'"[Circular]"';e.add(n);let s;return typeof n.toJSON=="function"?s=r(n.toJSON()):n instanceof Map?s=`{"__map":[${[...n.entries()].map(([i,a])=>`[${r(i)},${r(a)}]`).sort().join(",")}]}`:n instanceof Set?s=`{"__set":[${[...n.values()].map(r).sort().join(",")}]}`:s=`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${r(n[a])}`).join(",")}}`,e.delete(n),s}return"null"};return r(t)}function fe(t,e){let r=2166136261;for(let n=0;n<t;n++)r^=e(n),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r.toString(16).padStart(8,"0")}function de(t){return fe(t.length,e=>t.charCodeAt(e))}function me(t){return fe(t.length,e=>t[e])}function qe(t,e){return z(F(t),e)}function z(t,e){let r=ce(e);return`${t}|t:${r.length}:${de(r)}`}function F(t){return S(t)?`r:${t.key}`:typeof t=="string"?`s:${t.length}:${de(t)}`:`u8:${t.length}:${me(t)}`}var Ke=100;function He(t){return typeof t!="string"?!0:!/^https?:\/\//i.test(t)}function Qe(t){try{return JSON.stringify(t)?.length??0}catch{return 0}}var A=class{constructor(e,r,n={},s){l(this,"executor");l(this,"baseConfig");l(this,"mode");l(this,"maxConcurrent");l(this,"maxQueueDepth");l(this,"queueWaitMs");l(this,"timeoutMs");l(this,"retry");l(this,"cacheEnabled");l(this,"cacheMaxBytes");l(this,"cacheTtl");l(this,"cacheErroredSolves");l(this,"cache",new Map);l(this,"cacheBytes",0);l(this,"cacheHits",0);l(this,"cacheMisses",0);l(this,"cacheEvictions",0);l(this,"cacheKeyExecutor");l(this,"reuseServerDefinitionCache");l(this,"serverCacheKeys",new Map);l(this,"onStart");l(this,"onSettle");l(this,"onSuperseded");l(this,"subscribers",new Set);l(this,"inFlight",new Set);l(this,"pendingForLatestWins",null);l(this,"fifoQueue",[]);l(this,"_lastResult",null);l(this,"_lastError",null);l(this,"_lastDurationMs",null);l(this,"solveSeq",0);l(this,"lastStateSeq",0);l(this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=s,this.baseConfig=r,this.mode=n.mode??"latest-wins",this.maxConcurrent=Math.max(1,n.maxConcurrent??(this.mode==="parallel"?4:1)),this.maxQueueDepth=n.maxQueueDepth!==void 0&&n.maxQueueDepth>0?Math.floor(n.maxQueueDepth):void 0,this.queueWaitMs=n.queueWaitMs!==void 0&&n.queueWaitMs>0?n.queueWaitMs:void 0,this.timeoutMs=n.timeoutMs,this.retry=n.retry;let o=n.cache,i=typeof o=="object"?o:null;this.cacheMaxBytes=Math.max(0,i?.maxBytes??0),this.cacheEnabled=this.cacheMaxBytes>0,this.cacheTtl=i?.ttlMs??0,this.cacheErroredSolves=i?.cacheErroredSolves??!0,this.reuseServerDefinitionCache=!!s&&(n.reuseServerDefinitionCache??!0),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+(this.pendingForLatestWins?1:0)}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}setMaxConcurrent(e){let r=Math.max(1,Math.floor(e));if(r===this.maxConcurrent)return;let n=r>this.maxConcurrent;this.maxConcurrent=r,n&&this.drainNext()}getMaxConcurrent(){return this.maxConcurrent}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(r){p().error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new d("SolveScheduler has been disposed and cannot be used",y.INVALID_STATE));let s=F(e),o=z(s,r),i=++this.solveSeq,a={key:o,enqueuedAt:Date.now(),startedAt:null};if(n?.signal?.aborted)return Promise.reject(this.makeAbortError(a));if(this.cacheEnabled){let u=this.readCache(o);if(u){this.mode==="latest-wins"&&this.supersedeCurrent();let m={status:"success",response:u,durationMs:0,fromCache:!0};return this.writeLastState(i,{result:u,durationMs:0}),this.runHook(this.onStart,a),this.runHook(this.onSettle,a,m),this.notify(),Promise.resolve(u)}}return new Promise((u,m)=>{let f={definition:e,dataTree:r,definitionHash:s,ctx:a,seq:i,resolve:u,reject:m,externalSignal:n?.signal};f.externalSignal&&(f.queuedAbortHandler=()=>this.abortQueuedItem(f),f.externalSignal.addEventListener("abort",f.queuedAbortHandler,{once:!0})),this.enqueue(f)})}writeLastState(e,r){return e<this.lastStateSeq?!1:(this.lastStateSeq=e,"result"in r?(this._lastResult=r.result,this._lastError=null):this._lastError=r.error,this._lastDurationMs=r.durationMs,!0)}supersedeCurrent(){this.pendingForLatestWins&&(this.supersede(this.pendingForLatestWins),this.pendingForLatestWins=null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}abortQueuedItem(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null);let r=this.fifoQueue.indexOf(e);r>=0&&this.fifoQueue.splice(r,1),this.rejectAsAborted(e),this.notify()}shedAsQueueFull(e){let r=new d("Solve queue is full; request rejected (backpressure)",y.QUEUE_FULL,{statusCode:503,context:{key:e.ctx.key,queueDepth:this.fifoQueue.length,maxQueueDepth:this.maxQueueDepth}});this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:0}),this.notify()}armQueueWaitTimer(e){if(this.queueWaitMs===void 0)return;let r=this.queueWaitMs;e.queueWaitTimer=setTimeout(()=>{if(e.settled)return;let n=this.fifoQueue.indexOf(e);n>=0&&this.fifoQueue.splice(n,1);let s=new d(`Solve waited longer than ${r}ms in queue; rejected (backpressure)`,y.QUEUE_TIMEOUT,{statusCode:503,context:{key:e.ctx.key,waitedMs:Date.now()-e.ctx.enqueuedAt,queueWaitMs:r}});this.settleError(e,s)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:s,durationMs:0}),this.notify()},r)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case"latest-wins":{this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break}case"queue":case"parallel":{this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifoQueue.length>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifoQueue.push(e));break}}this.notify()}async execute(e){let r=new AbortController,n=e;n.controller=r,this.inFlight.add(n),e.ctx.startedAt=Date.now(),this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e);let s=()=>r.abort();e.externalSignal?.addEventListener("abort",s,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let o=performance.now();try{let i={...this.baseConfig,signal:r.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},{response:a,definitionReuploaded:u}=await this.runExecutor(e.definition,e.dataTree,e.definitionHash,i),m=performance.now()-o;if(this.cacheEnabled&&this.writeCache(e.ctx.key,a),!this.settleSuccess(e,a))return;this.writeLastState(e.seq,{result:a,durationMs:m}),this.runHook(this.onSettle,e.ctx,{status:"success",response:a,durationMs:m,fromCache:!1,definitionReuploaded:u})}catch(i){let a=performance.now()-o,u=this.normalizeExecutionError(i,n);this.writeLastState(e.seq,{error:u,durationMs:a}),this.settleError(e,u)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:u,durationMs:a})}finally{e.externalSignal?.removeEventListener("abort",s),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,r,n,s){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!He(e))return{response:await this.executor(e,r,s)};let o=n,i=this.serverCacheKeys.get(o)??null,a=await this.cacheKeyExecutor(e,r,i,s);if(a.cacheKey)for(this.serverCacheKeys.delete(o),this.serverCacheKeys.set(o,a.cacheKey);this.serverCacheKeys.size>Ke;){let u=this.serverCacheKeys.keys().next().value;if(u===void 0)break;this.serverCacheKeys.delete(u)}else this.serverCacheKeys.delete(o);return{response:a.response,definitionReuploaded:a.missed}}drainNext(){if(!this.disposed){if(this.mode==="latest-wins"){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}return}for(;this.fifoQueue.length>0&&this.inFlight.size<this.maxConcurrent;){let e=this.fifoQueue.shift();this.execute(e)}}}supersede(e){let r=new d("Superseded by newer solve",y.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new d("Request aborted by caller",y.ABORTED,{context:{key:e.key,enqueuedAt:e.enqueuedAt}})}settleError(e,r){return e.settled?!1:(e.settled={error:r},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(r),!0)}settleSuccess(e,r){return e.settled?!1:(e.settled={ok:!0},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.resolve(r),!0)}removeQueuedAbortHandler(e){e.queuedAbortHandler&&e.externalSignal&&e.externalSignal.removeEventListener("abort",e.queuedAbortHandler),e.queuedAbortHandler=void 0}isAbortLikeError(e){if(e instanceof Error){if(e.name==="AbortError")return!0;if(typeof DOMException<"u"&&e instanceof DOMException)return e.name==="AbortError"}return!1}normalizeExecutionError(e,r){return r.settled&&"error"in r.settled?r.settled.error:e instanceof d?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new d(e instanceof Error?e.message:String(e),y.UNKNOWN_ERROR,{originalError:e instanceof Error?e:new Error(String(e))})}cancelAll(){for(this.pendingForLatestWins&&(this.rejectAsAborted(this.pendingForLatestWins),this.pendingForLatestWins=null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:e.ctx.startedAt?Date.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:0})}readCache(e){if(!this.cacheEnabled)return null;let r=this.cache.get(e);return r?this.cacheTtl>0&&Date.now()-r.insertedAt>this.cacheTtl?(this.dropCacheEntry(e),this.cacheMisses+=1,null):(this.cache.delete(e),this.cache.set(e,r),this.cacheHits+=1,r.response):(this.cacheMisses+=1,null)}writeCache(e,r){if(!this.cacheEnabled||!this.cacheErroredSolves&&r.errors&&r.errors.length>0)return;let n=N(r)??Qe(r);if(!(n>this.cacheMaxBytes))for(this.dropCacheEntry(e),this.cache.set(e,{response:r,insertedAt:Date.now(),sizeBytes:n}),this.cacheBytes+=n;this.cacheBytes>this.cacheMaxBytes&&this.cache.size>0;){let s=this.cache.keys().next().value;if(s===void 0)break;this.dropCacheEntry(s),this.cacheEvictions+=1}}dropCacheEntry(e){let r=this.cache.get(e);r&&(this.cache.delete(e),this.cacheBytes-=r.sizeBytes)}clearCache(){this.cache.clear(),this.cacheBytes=0}cacheStats(){return{entries:this.cache.size,bytes:this.cacheBytes,hits:this.cacheHits,misses:this.cacheMisses,evictions:this.cacheEvictions}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(e,...r){if(e)try{e(...r)}catch(n){p().error("[SolveScheduler] hook threw:",n)}}};function he(t){return S(t)?`ref:${t.key}`:typeof t=="string"&&t.length<200?t:"...content..."}function ye(t){return Array.isArray(t)?t.map(e=>{let r=0,n=0,s=c(e,"innerTree");if(s&&typeof s=="object"){for(let o of Object.values(s))if(Array.isArray(o)){r+=o.length;for(let i of o){let a=i?.data;typeof a=="string"&&(n+=a.length)}}}return{param:c(e,"paramName")??"<unnamed>",items:r,bytes:n}}):[]}var L=class t{constructor(e){l(this,"config");l(this,"serverStats");l(this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new I(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e),n=Math.max(1,(e.retry?.attempts??2)+1),s=e.retry?.baseDelayMs??250,o=e.retry?.maxDelayMs??1e3;for(let i=0;i<n;i++){if(await r.serverStats.isServerOnline())return r;if(i<n-1){let a=Math.min(s*2**i,o);await new Promise(u=>setTimeout(u,a))}}throw await r.dispose(),new d("Rhino Compute server is not online",y.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:n}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),q(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),V(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!e?.trim())throw new d("Definition URL/content is required",y.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new d("Definition content is empty",y.INVALID_INPUT);if(S(e)&&!e.key.trim())throw new d("DefinitionRef key is empty",y.INVALID_INPUT);let s={...this.config,...n?.signal!==void 0&&{signal:n.signal},...n?.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs},...n?.retry!==void 0&&{retry:n.retry}},o=await k(r,e,s);if(o?.errors&&o.errors.length>0)throw new d(o.errors.join("; ")||"Computation failed",y.COMPUTATION_ERROR,{context:{definition:he(e),inputSummary:ye(r),errors:o.errors,warnings:o.warnings,values:o.values}});return o}catch(s){throw this.config.debug&&p().error("Compute failed:",s),s instanceof d?s:new d(s instanceof Error?s.message:String(s),y.COMPUTATION_ERROR,{context:{definition:he(e),inputSummary:ye(r)},originalError:s instanceof Error?s:new Error(String(s))})}}createScheduler(e){this.ensureNotDisposed();let r=(s,o,i)=>k(o,s,i),n=(s,o,i,a)=>i===null?le(o,s,a).then(u=>({...u,missed:!1})):pe(o,i,s,a);return new A(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new d("GrasshopperClient has been disposed and cannot be used",y.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:P(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning}}};var G=new Map;function be(t,e){G.set(t,e)}be("Rhino.Geometry.Point3d",(t,e)=>{let r=e;return!r||typeof r.X!="number"?null:new t.Point([r.X,r.Y,r.Z])});be("Rhino.Geometry.Line",(t,e)=>{let r=e;return!r||!r.From||!r.To?null:new t.Line([r.From.X,r.From.Y,r.From.Z],[r.To.X,r.To.Y,r.To.Z])});function Je(t){if(G.has(t))return G.get(t);for(let[e,r]of G)if(t.startsWith(e))return r}function Ye(t){return!!(t&&typeof t=="object"&&typeof t.data=="string")}function ge(t,e){return{__decodeError:!0,type:t,raw:e}}function Te(t,e,r){let n=Je(e),s=!1;if(n)try{let o=n(r,t);if(o!=null)return o}catch(o){p().warn(`Failed to decode Rhino type ${e}:`,o),s=!0}try{if(Ye(t))return r.CommonObject.decode(t)}catch(o){return p().warn(`Failed to decode ${e} with CommonObject:`,o),ge(e,t)}return s?ge(e,t):t}function Se(t){let e=new WeakSet,r=n=>{if(!n||typeof n!="object"||e.has(n))return;e.add(n);let s=n.delete;if(typeof s=="function"){let i=n.isDeleted;(typeof i!="function"||!i.call(n))&&s.call(n);return}if(Array.isArray(n)){for(let i of n)r(i);return}let o=Object.getPrototypeOf(n);if(o===Object.prototype||o===null)for(let i of Object.values(n))r(i)};r(t)}var x={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},Xe="Rhino.Geometry.",Ze=["WebDisplay"],et="FileData";function Ce(t){return Ze.some(e=>t.includes(e))}function tt(t){if(typeof t!="string")return t;let e=t.trim();if(!(e.startsWith("{")||e.startsWith("[")||e.startsWith('"')))return t;try{let n=JSON.parse(e);if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}catch{return t}}function rt(t,e,r){switch(e){case x.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case x.INT:return Number.parseInt(t,10);case x.DOUBLE:return Number.parseFloat(t);case x.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(Xe)?Te(t,e,r):t}}var K=new WeakMap;function ve(t){if(K.has(t))return K.get(t);let e=tt(t.data);return K.set(t,e),e}function Ie(t,e,r,n){if(typeof t.data!="string")return t.data;let s=r?ve(t):t.data;return rt(s,e,n)}function nt(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.fileName=="string"&&typeof e.fileType=="string"&&"data"in e&&typeof e.isBase64Encoded=="boolean"&&typeof e.subFolder=="string"}function H(t){let e=c(t,"values");return Array.isArray(e)?e:[]}function Q(t){return typeof t.type=="string"?t.type:""}function J(t,e){if(!(!t||typeof t!="object")){for(let r of Object.values(t))if(Array.isArray(r))for(let n of r)n&&typeof n=="object"&&e(n)}}function De(t,e=!1,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,i={},a=new Set;for(let u of H(t)){let m=c(u,"paramName");J(c(u,"innerTree"),f=>{let h=Q(f);if(Ce(h)||o&&h!==x.STRING)return;let g=e?f.id:m;if(!g)return;let T=Ie(f,h,n,s);g in i?a.has(g)?i[g].push(T):(i[g]=[i[g],T],a.add(g)):i[g]=T})}return{values:i,dispose:()=>Se(i)}}function xe(t){let e=[];for(let r of H(t))J(c(r,"innerTree"),n=>{if(!Q(n).includes(et))return;let s=ve(n);nt(s)&&e.push(s)});return e}function we(t,e,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r;for(let i of H(t)){let a=c(i,"innerTree"),u=!1;if("byName"in e){if(c(i,"paramName")!==e.byName)continue;u=!0}let m=[];if(J(a,f=>{if("byId"in e){if(f.id!==e.byId)return;u=!0}let h=Q(f);Ce(h)||o&&h!==x.STRING||m.push(Ie(f,h,n,s))}),u)return m.length===0?void 0:m.length===1?m[0]:m}}var W=class{constructor(e,r=!1){l(this,"response",e);l(this,"debug",r)}getValues(e=!1,r={}){return De(this.response,e,r)}getValue(e,r){return we(this.response,e,r)}getFileData(){return xe(this.response)}async getAndDownloadFiles(e,r){let n=this.getFileData();await j(n,e,r)}};var Y=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function w(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.entries(t);return e.length>0&&e.every(([r,n])=>Y.test(r)&&Array.isArray(n))}function X(t,e,r){let n=Number(t.toFixed(e));return Math.abs(t-n)<r?n:t}function Ee(t,e){if(!Number.isFinite(t)||t===0)return .1;let r=Math.abs(t);if(r>=1){let g=String(t).split(".")[1];if(g&&g.length>0){let T=Math.min(g.length,12),v=Math.pow(10,-T),ne=Number(v.toFixed(T));return Math.abs(ne-v)<e?ne:v}return 1}let n=String(t),s=n.toLowerCase().match(/e(-?\d+)/);if(s){let h=Number(s[1]);if(h<0||n.toLowerCase().includes("e-")){let g=Math.abs(h),T=Math.pow(10,-g),v=Number(T.toFixed(g));return Math.abs(v-T)<e?v:T}return .1}let o=12,a=r.toFixed(o).replace(/0+$/,""),u=Math.min((a.split(".")[1]||"").length,o);if(u===0)return .1;let m=Math.pow(10,-u),f=Number(m.toFixed(u));return Math.abs(f-m)<e?f:m}function Z(t){return typeof t.stepSize=="number"&&Number.isFinite(t.stepSize)&&t.stepSize>0?t.stepSize:void 0}function C(t,e,r){if(t==null)return t;if(Array.isArray(t)){let s=t.map(e).filter(o=>o!==null);return s.length>0?s:void 0}let n=e(t);return n!==null?n:r?void 0:t}var R=t=>{if(typeof t=="number")return Number.isFinite(t)?t:null;if(typeof t=="string"){let e=t.trim();if(e===""||/^[+-]?0[xbo]/i.test(e))return null;let r=Number(e);return Number.isFinite(r)?r:null}return null},$=t=>{if(typeof t=="boolean")return t;if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return null},Ae=t=>typeof t=="string"?t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t.startsWith('"')?t.slice(1):t:null,Re=t=>{if(typeof t=="string"){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}return null};function ee(t){return e=>{if(typeof e=="object"&&e!==null)return e;if(typeof e=="string"&&e.trim()!=="")try{let r=JSON.parse(e);return typeof r=="object"&&r!==null?r:(p().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return p().warn(`Failed to parse object value "${e}" for input ${t}`,r),null}return null}}function st(t,e=1e-8){let r=t.paramType==="Integer",n=Z(t);if(w(t.default))return{default:t.default,stepSize:n??(r?1:.1)};if(typeof t.default=="string"&&t.default.trim()!==""&&R(t.default)===null)throw new d(`Invalid numeric default "${t.default}" for input "${t.name||"unknown"}"`,y.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let s=C(t.default,R,!0);if(r)return Array.isArray(s)?s=s.map(h=>typeof h=="number"?Math.round(h):h):typeof s=="number"&&(s=Math.round(s)),{default:s,stepSize:n??1};let o=Array.isArray(s)?s[0]:s,i;typeof o=="number"&&Number.isFinite(o)&&o!==0?i=o:typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum!==0?i=t.minimum:typeof t.maximum=="number"&&Number.isFinite(t.maximum)&&t.maximum!==0&&(i=t.maximum);let a=n??(i!==void 0?Ee(i,e):.1),u=0,m=String(a),f=m.toLowerCase().match(/e(-?\d+)/);if(f?u=Math.abs(Number(f[1])):u=m.split(".")[1]?.length??0,u===0&&typeof o=="number"&&o!==0&&Math.abs(o)<1){let h=Math.ceil(-Math.log10(Math.abs(o)));Number.isFinite(h)&&h>0&&(u=h)}return u=Math.min(Math.max(u,0),12),Array.isArray(s)?s=s.map(h=>typeof h=="number"?X(h,u,e):h):typeof s=="number"&&(s=X(s,u,e)),{default:s,stepSize:a}}var ot={types:["Number","Integer"],parse(t,e){let{default:r,stepSize:n}=st(t);return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:n,default:r}},fallback(t,e){let r=(t.atMost??1)>1,n=typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum>0?t.minimum:0;return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:Z(t)??(t.paramType==="Integer"?1:.1),default:r?[n]:n}}},it={types:["Boolean"],parse(t,e){if(w(t.default))return{...e,paramType:"Boolean",default:t.default};let r=C(t.default,$,!1);if(r!=null&&typeof r!="boolean"&&!Array.isArray(r))throw new d(`Invalid boolean default "${String(r)}" for input "${t.name||"unknown"}"`,y.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});return{...e,paramType:"Boolean",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Boolean",default:r?[!1]:!1}}},at={types:["Text"],parse(t,e){let r=C(t.default,Ae,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Text",default:r?[""]:""}}},ut={types:["ValueList"],parse(t,e){if(!t.values||typeof t.values!="object"||Object.keys(t.values).length===0)throw d.missingValues(t.nickname||"unnamed","ValueList");let r=t.default;if(t.default!==void 0&&t.default!==null){if(typeof t.default=="object")throw new d(`ValueList input "${t.nickname||"unnamed"}" default is not a string-able value`,y.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=String(t.default).toLowerCase(),s=Object.keys(t.values).find(o=>o.toLowerCase()===n);s!==void 0?r=s:p().warn(`ValueList input "${t.nickname||"unnamed"}" default value "${t.default}" is not in available values`)}return{...e,paramType:"ValueList",values:t.values,default:r}},fallback(t,e){return{...e,paramType:"ValueList",values:t.values&&typeof t.values=="object"?t.values:{},default:void 0}}},Pe={types:["Geometry"],parse(t,e){let r=C(t.default,ee(t.nickname||"unnamed"),!0);return{...e,paramType:"Geometry",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Geometry",default:r?[null]:null}}},lt={types:["File"],parse(t,e){let r=C(t.default,ee(t.nickname||"unnamed"),!0);return{...e,paramType:"File",acceptedFormats:t.acceptedFormats,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"File",default:r?[null]:null}}},pt={types:["Color"],parse(t,e){let r=C(t.default,Re,!1);return{...e,paramType:"Color",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Color",default:r?["0, 0, 0"]:"0, 0, 0"}}},ct=[ot,it,at,ut,Pe,lt,pt],te=new Map(ct.flatMap(t=>t.types.map(e=>[e,t]))),Ne=Pe;function Oe(t){return c(t,"data")}function ft(t){return c(t,"type")}var dt=new Set(["System.Double","System.Single","System.Decimal","System.Int32","System.Int64"]),mt=new Set(["System.Int32","System.Int64"]);function Me(t){if(typeof t.default!="object"||t.default===null)return{schema:t};if(Array.isArray(t.default))return{schema:t};if(!_(t.default,"innerTree")){let n=`Input "${t.name??"unknown"}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return p().warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=c(t.default,"innerTree")??{};if(Object.keys(e).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let n={},s=[];for(let[i,a]of Object.entries(e)){if(!Array.isArray(a)){let m=`Input "${t.name??"unknown"}" default had a non-array innerTree branch ("${i}"); the default was dropped.`;return p().warn("Unexpected structure in input.default innerTree:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:m}}}let u=[];for(let m of a){let f=Oe(m),h=ft(m);if(h&&dt.has(h)){if(typeof f=="string"&&f.trim()==="")continue;let g=R(f);if(g===null){s.push(`"${String(f)}" (${h})`);continue}u.push(mt.has(h)?Math.round(g):g);continue}if(h==="System.Boolean"){let g=$(f);if(g===null){s.push(`"${String(f)}" (${h})`);continue}u.push(g);continue}if(typeof f=="string"&&h?.startsWith("Rhino.Geometry")){try{u.push(JSON.parse(f))}catch{u.push(f)}continue}u.push(f)}n[i]=u}let o;if(s.length>0){let i=`Input "${t.name??"unknown"}" default contained ${s.length} tree value(s) that could not be parsed and were dropped: ${s.join(", ")}.`;p().warn(i),o={code:"MALFORMED_DEFAULT",message:i}}return{schema:{...t,default:n},...o&&{warning:o}}}let r=[];for(let n of Object.values(e))Array.isArray(n)&&n.forEach(s=>{s&&typeof s=="object"&&_(s,"data")&&r.push(Oe(s))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}var ht=new Map([...te.keys()].map(t=>[t.toLowerCase(),t]));function yt(t){return ht.get(t?.toLowerCase())??t}function gt(t){return ke(t).input}function ke(t){let e={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??void 0,id:t.id},r=yt(t.paramType),n={...t,paramType:r},s;try{let{schema:i,warning:a}=Me(n);n=i,s=a&&{inputName:t.name||"unknown",paramType:t.paramType,message:a.message,code:a.code}}catch(i){n={...n,default:null},s={inputName:t.name||"unknown",paramType:t.paramType,message:`Input "${t.name??"unknown"}" default could not be normalized and was dropped: ${i instanceof Error?i.message:String(i)}`,code:"MALFORMED_DEFAULT"}}let o=te.get(r);try{if(!o)throw d.unknownParamType(r,t.name);return{input:o.parse(n,e),error:s,...s&&{errors:[s]}}}catch(i){if(i instanceof d){p().error(`Validation error for input ${t.name||"unknown"}:`,i.message);let a={inputName:t.name||"unknown",paramType:t.paramType,message:i.message,code:i.code};return{input:(o??Ne).fallback(n,e),error:a,errors:s?[s,a]:[a]}}throw new d(i instanceof Error?i.message:String(i),"VALIDATION_ERROR",{context:{paramName:t.name,paramType:r},originalError:i instanceof Error?i:new Error(String(i))})}}function Fe(t){let e=[],r=[];for(let n of t){let{input:s,errors:o}=ke(n);e.push(s),o&&r.push(...o)}return{inputs:e,parseErrors:r}}function Le(t){let e=c(t,"stepSize");return{id:c(t,"id")??"",name:c(t,"name")??"",nickname:c(t,"nickname")??null,description:c(t,"description")??"",paramType:c(t,"paramType")??"",treeAccess:c(t,"treeAccess")??!1,minimum:c(t,"minimum")??null,maximum:c(t,"maximum")??null,atLeast:c(t,"atLeast")??1,atMost:c(t,"atMost")??1,stepSize:typeof e=="number"&&Number.isFinite(e)?e:void 0,default:c(t,"default"),values:c(t,"values"),acceptedFormats:c(t,"acceptedFormats"),groupName:c(t,"groupName")??null}}function Ve(t){return{name:c(t,"name")??"",nickname:c(t,"nickname")??null,paramType:c(t,"paramType")??"",id:c(t,"id")??""}}async function V(t,e){let r=E(t,[]),n={};if(r.algo&&(n.algo=r.algo),r.pointer&&(n.pointer=r.pointer),!n.algo&&!n.pointer)throw new d("Definition must resolve to either a URL pointer or base64 algo",y.INVALID_INPUT,{context:{definition:t}});let s=await O("io",n,B(e));if(!s||typeof s!="object")throw new d("Invalid IO response structure",y.INVALID_INPUT,{context:{response:s,definition:t}});let o=Ge(c(s,"warnings")),i=Ge(c(s,"errors")),a=c(s,"inputs"),u=c(s,"outputs");return{inputs:Array.isArray(a)?a.map(Le):[],outputs:Array.isArray(u)?u.map(Ve):[],...o&&{loadWarnings:o},...i&&{loadErrors:i}}}function Ge(t){if(!Array.isArray(t))return;let e=t.map(bt).filter(r=>r!==void 0);return e.length>0?e:void 0}function bt(t){if(t==null)return;let e;if(typeof t=="string")e=t;else if(typeof t=="object"){let r=c(t,"message");if(typeof r=="string"&&r.trim().length>0)e=r;else try{e=JSON.stringify(t)??String(t)}catch{e=String(t)}}else e=String(t);return e.trim().length>0?e:void 0}async function q(t,e){D("fetchParsedDefinitionIO",e.suppressBrowserWarning);let{inputs:r,outputs:n,loadWarnings:s,loadErrors:o}=await V(t,e),{inputs:i,parseErrors:a}=Fe(r);return{inputs:i,outputs:n,...a.length>0&&{parseErrors:a},...s&&{loadWarnings:s},...o&&{loadErrors:o}}}function Tt(t){return(Array.isArray(t)?t:[t]).map(r=>({schemas:c(r,"schemas"),error:c(r,"error")}))}var re=class t{constructor(e){l(this,"innerTree");l(this,"paramName");this.paramName=e,this.innerTree={}}append(e,r){let n=t.formatPathString(e);this.innerTree[n]||(this.innerTree[n]=[]);let s=r.map(o=>({data:t.serializeValue(o)}));return this.innerTree[n].push(...s),this}appendSingle(e,r){return this.append(e,[r])}fromDataTreeDefault(e){this.innerTree={};for(let[r,n]of Object.entries(e)){if(!Array.isArray(n))continue;let s=t.parsePathString(r);this.append(s,n)}return this}appendFlat(e){let r=Array.isArray(e)?e:[e];return this.append([0],r)}flatten(){let e=[];for(let r of Object.values(this.innerTree))if(Array.isArray(r))for(let n of r)e.push(t.deserializeValue(n.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let r=t.formatPathString(e),n=this.innerTree[r];if(n)return n.map(s=>t.deserializeValue(s.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(e){return e.filter(r=>t.hasValidValue(r.default)).map(r=>{let n=new t(r.nickname||"unnamed"),s=r.default;if(r.treeAccess&&w(s))n.fromDataTreeDefault(s),t.isNumericInput(r)&&n.applyNumericConstraints(r.minimum,r.maximum,r.nickname||"unnamed");else{let o=Array.isArray(s)?s:[s],i=t.processValues(o,r);n.appendFlat(i)}return n.toComputeFormat()})}static fromInputParam(e){return t.hasValidValue(e.default)?t.fromInputParams([e])[0]:void 0}static replaceTreeValue(e,r,n){let s=e.length>0&&e[0]instanceof t,o=t.buildFromValue(r,n);if(s){let m=e.slice(),f=m.findIndex(h=>h.getParamName()===r);return f!==-1?m[f]=o:m.push(o),m}let i=e.slice(),a=o.toComputeFormat(),u=i.findIndex(m=>m.ParamName===r);return u!==-1?i[u]=a:i.push(a),i}static buildFromValue(e,r){let n=new t(e);return w(r)?n.fromDataTreeDefault(r):n.appendFlat(r),n}static getTreeValue(e,r){let s=e.length>0&&e[0]instanceof t?t.readFromBuilders(e,r):t.readFromDataTrees(e,r);return s===null||s.length===0?null:s.length===1?s[0]:s}static readFromBuilders(e,r){let n=e.find(s=>s.getParamName()===r);return n?n.flatten():null}static readFromDataTrees(e,r){let n=e.find(i=>i.ParamName===r);if(!n?.InnerTree)return null;let s=Object.keys(n.InnerTree)[0];if(!s)return null;let o=n.InnerTree[s];return Array.isArray(o)?o.map(i=>i?.data!==void 0?t.deserializeValue(i.data):null):o?.data!==void 0?[t.deserializeValue(o.data)]:o!==void 0?[o]:null}static parsePathString(e){let r=e.match(Y);if(!r)throw new Error(`Invalid Grasshopper tree path: "${e}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`);return r[1]?r[1].split(";").map(Number):[]}static formatPathString(e){return`{${e.join(";")}}`}applyNumericConstraints(e,r,n){for(let s of Object.values(this.innerTree))if(Array.isArray(s))for(let o of s){let i=t.deserializeValue(o.data);if(typeof i=="number"){let a=t.clampValue(i,e,r,n);o.data=t.serializeValue(a)}}}static serializeValue(e){return typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:typeof e=="object"&&e!==null?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e=="boolean"||typeof e=="number"||typeof e!="string")return e;if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch{return e}let r=Number(e);return Number.isFinite(r)&&String(r)===e?r:e==="true"?!0:e==="false"?!1:e}static hasValidValue(e){return e==null?!1:typeof e=="string"?!0:!(Array.isArray(e)&&e.length===0||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType==="Number"||e.paramType==="Integer"}static processValues(e,r){return e.map(n=>t.isNumericInput(r)&&typeof n=="number"?t.clampValue(n,r.minimum,r.maximum,r.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(e,r,n,s){let o=e;return r!=null&&o<r&&(p().warn(`${s}: ${e} below min ${r}, clamping`),o=r),n!=null&&o>n&&(p().warn(`${s}: ${e} above max ${n}, clamping`),o=n),o}};export{I as ComputeServerStats,L as GrasshopperClient,W as GrasshopperResponseProcessor,A as SolveScheduler,re as TreeBuilder,j as downloadFileData,We as extractFilesFromComputeResponse,V as fetchDefinitionIO,q as fetchParsedDefinitionIO,F as hashDefinition,qe as hashSolveInput,S as isDefinitionRef,gt as processInput,Tt as readSchemaResults,k as solveGrasshopperDefinition,ce as stableStringify};
|
|
1
|
+
import{a as e,f as t,g as n,i as r,l as i,m as a,n as o,o as s,p as c,r as l,s as u,t as d,u as ee,v as f,y as p}from"./core-DONB46aK.js";var m=class e{serverUrl;apiKey;disposed=!1;activeMonitors=new Set;activeTimeouts=new Set;static DEFAULT_TIMEOUT_MS=5e3;static LIFECYCLE_TIMEOUT_MS=6e4;static MIN_MONITOR_INTERVAL_MS=100;constructor(e,n){this.serverUrl=t(e),this.apiKey=n}buildHeaders(){let e={"Content-Type":`application/json`};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(t,n={},r=e.DEFAULT_TIMEOUT_MS){let i=new Headers(this.buildHeaders());n.headers&&new Headers(n.headers).forEach((e,t)=>{i.set(t,e)});let a={};i.forEach((e,t)=>{a[t]=e});let o={...n,headers:a};return r>0&&!o.signal&&(o.signal=AbortSignal.timeout(r)),fetch(t,o)}async isServerOnline(e=5e3){this.ensureNotDisposed();let t=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(t,{method:`GET`},e)).ok}catch(e){return n().debug(`[ComputeServerStats] Fetch error:`,e),!1}}async getActiveChildren(t={}){this.ensureNotDisposed();let{initialize:r=!0}=t,i=r?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,a=r?e.LIFECYCLE_TIMEOUT_MS:e.DEFAULT_TIMEOUT_MS;try{let e=await this.fetchWithTimeout(i,{},a);if(!e.ok)return n().warn(`[ComputeServerStats] Failed to fetch active children:`,e.status),null;let t=(await e.text()).trim();return/^\d+$/.test(t)?parseInt(t,10):(n().warn(`[ComputeServerStats] Invalid active children response:`,t),null)}catch(e){return n().warn(`[ComputeServerStats] Error fetching active children:`,e),null}}async getVersion(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!e.ok)return n().warn(`[ComputeServerStats] Failed to fetch version:`,e.status),null;let t=await e.text();try{let e=JSON.parse(t);return{rhino:e.rhino??``,compute:e.compute??``,git_sha:e.git_sha??null}}catch{return{rhino:t,compute:``,git_sha:null}}}catch(e){return n().warn(`[ComputeServerStats] Error fetching version:`,e),null}}async getInstalledPlugins(e=`gh`){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${e}/installed`);if(!t.ok)return n().warn(`[ComputeServerStats] Failed to fetch ${e} plugins:`,t.status),null;let r=await t.text();try{let e=JSON.parse(r);return e&&typeof e==`object`?e:null}catch{return null}}catch(t){return n().warn(`[ComputeServerStats] Error fetching ${e} plugins:`,t),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[e,t]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...e&&{version:e},...t!==null&&{activeChildren:t}}}async purgeCache(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:`POST`});if(!e.ok)return n().warn(`[ComputeServerStats] Failed to purge cache:`,e.status),null;let t=await e.text();try{let e=JSON.parse(t);return typeof e.purged==`number`?e.purged:null}catch{return null}}catch(e){return n().warn(`[ComputeServerStats] Error purging cache:`,e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return n().warn(`[ComputeServerStats] purgeAllChildren: could not read child count`),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let t=e*2,r=0;for(let e=0;e<t;e++){let e=await this.purgeCache();e!==null&&(r+=e)}return{totalPurged:r,calls:t,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!e.ok)return n().warn(`[ComputeServerStats] Failed to fetch server time:`,e.status),null;let t=(await e.text()).trim().replace(/^"|"$/g,``),r=new Date(t);return isNaN(r.getTime())?null:r}catch(e){return n().warn(`[ComputeServerStats] Error fetching server time:`,e),null}}async getIdleSpan(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);if(!e.ok)return n().warn(`[ComputeServerStats] Failed to fetch idle span:`,e.status),null;let t=parseFloat((await e.text()).trim());return isNaN(t)?null:t}catch(e){return n().warn(`[ComputeServerStats] Error fetching idle span:`,e),null}}async launchChildren(){return this.postJson(`/launch-children`)}async launchChild(e){let t=e===void 0?`/launch-child`:`/launch-child?port=${e}`;return this.postJson(t)}async shutdownChildren(e){let t=e===void 0?`/shutdown-children`:`/shutdown-children?port=${e}`;return this.postJson(t)}async recycleChildren(e){let t=e===void 0?`/recycle-children`:`/recycle-children?port=${e}`;return this.postJson(t)}async postJson(t){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}${t}`,{method:`POST`},e.LIFECYCLE_TIMEOUT_MS);if(!r.ok)return n().warn(`[ComputeServerStats] POST ${t} failed:`,r.status),null;let i=await r.text();try{return JSON.parse(i)}catch{return null}}catch(e){return n().warn(`[ComputeServerStats] Error on POST ${t}:`,e),null}}monitor(t,r=5e3){if(this.ensureNotDisposed(),!Number.isFinite(r)||r<e.MIN_MONITOR_INTERVAL_MS)throw RangeError(`monitor() intervalMs must be a finite number >= ${e.MIN_MONITOR_INTERVAL_MS}ms, got ${r}. Sub-${e.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`);let i=!0,a=null;n().info(`🔄 Starting server stats monitoring every ${r}ms`);let o=async()=>{if(a!==null&&(this.activeTimeouts.delete(a),a=null),!(!i||this.disposed)){try{let e=await this.getServerStats();if(!i||this.disposed)return;try{t(e)}catch(e){n().error(`[ComputeServerStats] Monitor callback threw:`,e)}}catch(e){!i||this.disposed?n().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,e):n().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,e)}i&&!this.disposed&&(a=setTimeout(()=>void o(),r),this.activeTimeouts.add(a))}},s=()=>{i=!1,a!==null&&(clearTimeout(a),this.activeTimeouts.delete(a),a=null),this.activeMonitors.delete(s)};return this.activeMonitors.add(s),o(),s}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new f(`ComputeServerStats has been disposed and cannot be used`,p.INVALID_STATE,{context:{disposed:this.disposed}})}};const h=new Set;function te(){if(typeof window>`u`||globalThis.process?.versions?.node!=null)return!1;let e=globalThis.navigator,t=typeof e?.userAgent==`string`?e.userAgent:``;return!/jsdom/i.test(t)}function g(e,t){t||te()&&!h.has(e)&&(h.add(e),n().warn(`Warning: ${e} is running on the client side. For better performance and security, consider running this on the server side.`))}const ne={definition_not_cached:p.DEFINITION_NOT_CACHED};function _(e){return{...e,serverErrorCodes:{...ne,...e.serverErrorCodes}}}function re(e){return e instanceof f?e.code===p.DEFINITION_NOT_CACHED||e.message.includes(`Unable to load grasshopper definition`):!1}function ie(e,t){if(!t)return;let r=a(e,`values`);if(!Array.isArray(r)||r.length===0)return;let i=[];for(let e of r){let t=a(e,`innerTree`);(!t||Object.keys(t).length===0)&&i.push(a(e,`paramName`)??`<unnamed>`)}if(i.length===0)return;let o=i.length===r.length?`all`:`${i.length}/${r.length}`;n().warn(`Solve returned empty output(s) (${o}): ${i.join(`, `)}. These parameters produced no data — check the definition's inputs and the branch feeding each.`)}async function v(e,t,n){g(`solveGrasshopperDefinition`,n.suppressBrowserWarning);let{response:r}=await b(x(await y(t),e),n);return r}async function ae(e,t,n){return g(`solveGrasshopperDefinitionWithCacheKey`,n.suppressBrowserWarning),b(x(await y(t),e),n)}async function oe(e,t,n,r){g(`solveByCacheKey`,r.suppressBrowserWarning);let i={algo:null,pointer:t,values:e};try{return{...await b(i,r),missed:!1}}catch(t){if(!re(t))throw t;return{...await b(x(await y(n),e),r),missed:!0}}}async function y(e){if(!l(e))return e;try{return await e.load()}catch(t){throw new f(`Failed to load definition bytes for ref '${e.key}'`,p.INVALID_INPUT,{context:{definitionKey:e.key},originalError:t instanceof Error?t:Error(String(t))})}}async function b(t,n){se(t,n);let i=await r(`grasshopper`,t,_(n)),{pointer:a,algo:o,...c}=i,l=c,u=e(i);if(u!==void 0){let e=typeof o==`string`?o.length:0;s(l,Math.max(0,u-e))}return ie(l,n.debug),{response:l,cacheKey:typeof a==`string`?a:null}}function x(e,t){let n={algo:null,pointer:null,values:t};return e instanceof Uint8Array?n.algo=u(e):/^https?:\/\//i.test(e)?n.pointer=e:n.algo=i(e)??ee(e),n}function se(e,t){t.cachesolve!=null&&(e.cachesolve=t.cachesolve),t.cacheerroredsolves!=null&&(e.cacheerroredsolves=t.cacheerroredsolves),t.modelunits!=null&&(e.modelunits=t.modelunits),t.angletolerance!=null&&(e.angletolerance=t.angletolerance),t.absolutetolerance!=null&&(e.absolutetolerance=t.absolutetolerance),t.dataversion!=null&&(e.dataversion=t.dataversion)}function S(e){let t=new WeakSet,n=e=>{if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`number`)return Number.isFinite(e)?String(e):`null`;if(typeof e==`string`||typeof e==`boolean`)return JSON.stringify(e);if(typeof e==`bigint`)return`${e}n`;if(e instanceof Uint8Array)return`{"__u8":${e.length},"hash":"${T(e)}"}`;if(Array.isArray(e)){if(t.has(e))return`"[Circular]"`;t.add(e);let r=[];for(let t=0;t<e.length;t++)r.push(n(e[t]));return t.delete(e),`[${r.join(`,`)}]`}if(typeof e==`object`){if(t.has(e))return`"[Circular]"`;t.add(e);let r;return r=typeof e.toJSON==`function`?n(e.toJSON()):e instanceof Map?`{"__map":[${[...e.entries()].map(([e,t])=>`[${n(e)},${n(t)}]`).sort().join(`,`)}]}`:e instanceof Set?`{"__set":[${[...e.values()].map(n).sort().join(`,`)}]}`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${n(e[t])}`).join(`,`)}}`,t.delete(e),r}return`null`};return n(e)}function C(e,t){let n=2166136261;for(let r=0;r<e;r++)n^=t(r),n=n+((n<<1)+(n<<4)+(n<<7)+(n<<8)+(n<<24))>>>0;return n.toString(16).padStart(8,`0`)}function w(e){return C(e.length,t=>e.charCodeAt(t))}function T(e){return C(e.length,t=>e[t])}function ce(e,t){return E(D(e),t)}function E(e,t){let n=S(t);return`${e}|t:${n.length}:${w(n)}`}function D(e){return l(e)?`r:${e.key}`:typeof e==`string`?`s:${e.length}:${w(e)}`:`u8:${e.length}:${T(e)}`}function le(e){return typeof e!=`string`||!/^https?:\/\//i.test(e)}function ue(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var O=class{executor;baseConfig;mode;maxConcurrent;maxQueueDepth;queueWaitMs;timeoutMs;retry;cacheEnabled;cacheMaxBytes;cacheTtl;cacheErroredSolves;cache=new Map;cacheBytes=0;cacheHits=0;cacheMisses=0;cacheEvictions=0;cacheKeyExecutor;reuseServerDefinitionCache;serverCacheKeys=new Map;onStart;onSettle;onSuperseded;subscribers=new Set;inFlight=new Set;pendingForLatestWins=null;fifoQueue=[];_lastResult=null;_lastError=null;_lastDurationMs=null;solveSeq=0;lastStateSeq=0;disposed=!1;constructor(e,t,n={},r){this.executor=e,this.cacheKeyExecutor=r,this.baseConfig=t,this.mode=n.mode??`latest-wins`,this.maxConcurrent=Math.max(1,n.maxConcurrent??(this.mode===`parallel`?4:1)),this.maxQueueDepth=n.maxQueueDepth!==void 0&&n.maxQueueDepth>0?Math.floor(n.maxQueueDepth):void 0,this.queueWaitMs=n.queueWaitMs!==void 0&&n.queueWaitMs>0?n.queueWaitMs:void 0,this.timeoutMs=n.timeoutMs,this.retry=n.retry;let i=n.cache,a=typeof i==`object`?i:null;this.cacheMaxBytes=Math.max(0,a?.maxBytes??0),this.cacheEnabled=this.cacheMaxBytes>0,this.cacheTtl=a?.ttlMs??0,this.cacheErroredSolves=a?.cacheErroredSolves??!0,this.reuseServerDefinitionCache=!!r&&(n.reuseServerDefinitionCache??!0),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+ +!!this.pendingForLatestWins}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}setMaxConcurrent(e){let t=Math.max(1,Math.floor(e));if(t===this.maxConcurrent)return;let n=t>this.maxConcurrent;this.maxConcurrent=t,n&&this.drainNext()}getMaxConcurrent(){return this.maxConcurrent}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(e){n().error(`[SolveScheduler] subscriber threw:`,e)}}solve(e,t,n){if(this.disposed)return Promise.reject(new f(`SolveScheduler has been disposed and cannot be used`,p.INVALID_STATE));let r=D(e),i=E(r,t),a=++this.solveSeq,o={key:i,enqueuedAt:Date.now(),startedAt:null};if(n?.signal?.aborted)return Promise.reject(this.makeAbortError(o));if(this.cacheEnabled){let e=this.readCache(i);if(e){this.mode===`latest-wins`&&this.supersedeCurrent();let t={status:`success`,response:e,durationMs:0,fromCache:!0};return this.writeLastState(a,{result:e,durationMs:0}),this.runHook(this.onStart,o),this.runHook(this.onSettle,o,t),this.notify(),Promise.resolve(e)}}return new Promise((i,s)=>{let c={definition:e,dataTree:t,definitionHash:r,ctx:o,seq:a,resolve:i,reject:s,externalSignal:n?.signal};c.externalSignal&&(c.queuedAbortHandler=()=>this.abortQueuedItem(c),c.externalSignal.addEventListener(`abort`,c.queuedAbortHandler,{once:!0})),this.enqueue(c)})}writeLastState(e,t){return e<this.lastStateSeq?!1:(this.lastStateSeq=e,`result`in t?(this._lastResult=t.result,this._lastError=null):this._lastError=t.error,this._lastDurationMs=t.durationMs,!0)}supersedeCurrent(){this.pendingForLatestWins&&=(this.supersede(this.pendingForLatestWins),null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}abortQueuedItem(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null);let t=this.fifoQueue.indexOf(e);t>=0&&this.fifoQueue.splice(t,1),this.rejectAsAborted(e),this.notify()}shedAsQueueFull(e){let t=new f(`Solve queue is full; request rejected (backpressure)`,p.QUEUE_FULL,{statusCode:503,context:{key:e.ctx.key,queueDepth:this.fifoQueue.length,maxQueueDepth:this.maxQueueDepth}});this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:0}),this.notify()}armQueueWaitTimer(e){if(this.queueWaitMs===void 0)return;let t=this.queueWaitMs;e.queueWaitTimer=setTimeout(()=>{if(e.settled)return;let n=this.fifoQueue.indexOf(e);n>=0&&this.fifoQueue.splice(n,1);let r=new f(`Solve waited longer than ${t}ms in queue; rejected (backpressure)`,p.QUEUE_TIMEOUT,{statusCode:503,context:{key:e.ctx.key,waitedMs:Date.now()-e.ctx.enqueuedAt,queueWaitMs:t}});this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:r,durationMs:0}),this.notify()},t)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case`latest-wins`:this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break;case`queue`:case`parallel`:this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifoQueue.length>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifoQueue.push(e))}this.notify()}async execute(e){let t=new AbortController,n=e;n.controller=t,this.inFlight.add(n),e.ctx.startedAt=Date.now(),this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e);let r=()=>t.abort();e.externalSignal?.addEventListener(`abort`,r,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let i=performance.now();try{let n={...this.baseConfig,signal:t.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},{response:r,definitionReuploaded:a}=await this.runExecutor(e.definition,e.dataTree,e.definitionHash,n),o=performance.now()-i;if(this.cacheEnabled&&this.writeCache(e.ctx.key,r),!this.settleSuccess(e,r))return;this.writeLastState(e.seq,{result:r,durationMs:o}),this.runHook(this.onSettle,e.ctx,{status:`success`,response:r,durationMs:o,fromCache:!1,definitionReuploaded:a})}catch(t){let r=performance.now()-i,a=this.normalizeExecutionError(t,n);this.writeLastState(e.seq,{error:a,durationMs:r}),this.settleError(e,a)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:a,durationMs:r})}finally{e.externalSignal?.removeEventListener(`abort`,r),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,t,n,r){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!le(e))return{response:await this.executor(e,t,r)};let i=n,a=this.serverCacheKeys.get(i)??null,o=await this.cacheKeyExecutor(e,t,a,r);if(o.cacheKey)for(this.serverCacheKeys.delete(i),this.serverCacheKeys.set(i,o.cacheKey);this.serverCacheKeys.size>100;){let e=this.serverCacheKeys.keys().next().value;if(e===void 0)break;this.serverCacheKeys.delete(e)}else this.serverCacheKeys.delete(i);return{response:o.response,definitionReuploaded:o.missed}}drainNext(){if(!this.disposed){if(this.mode===`latest-wins`){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}return}for(;this.fifoQueue.length>0&&this.inFlight.size<this.maxConcurrent;){let e=this.fifoQueue.shift();this.execute(e)}}}supersede(e){let t=new f(`Superseded by newer solve`,p.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,t)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new f(`Request aborted by caller`,p.ABORTED,{context:{key:e.key,enqueuedAt:e.enqueuedAt}})}settleError(e,t){return!e.settled&&(e.settled={error:t},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(t),!0)}settleSuccess(e,t){return!e.settled&&(e.settled={ok:!0},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.resolve(t),!0)}removeQueuedAbortHandler(e){e.queuedAbortHandler&&e.externalSignal&&e.externalSignal.removeEventListener(`abort`,e.queuedAbortHandler),e.queuedAbortHandler=void 0}isAbortLikeError(e){if(e instanceof Error){if(e.name===`AbortError`)return!0;if(typeof DOMException<`u`&&e instanceof DOMException)return e.name===`AbortError`}return!1}normalizeExecutionError(e,t){return t.settled&&`error`in t.settled?t.settled.error:e instanceof f?e:this.isAbortLikeError(e)?this.makeAbortError(t.ctx):new f(e instanceof Error?e.message:String(e),p.UNKNOWN_ERROR,{originalError:e instanceof Error?e:Error(String(e))})}cancelAll(){for(this.pendingForLatestWins&&=(this.rejectAsAborted(this.pendingForLatestWins),null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let t=this.makeAbortError(e.ctx);this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:e.ctx.startedAt?Date.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){let t=this.makeAbortError(e.ctx);this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:0})}readCache(e){if(!this.cacheEnabled)return null;let t=this.cache.get(e);return t?this.cacheTtl>0&&Date.now()-t.insertedAt>this.cacheTtl?(this.dropCacheEntry(e),this.cacheMisses+=1,null):(this.cache.delete(e),this.cache.set(e,t),this.cacheHits+=1,t.response):(this.cacheMisses+=1,null)}writeCache(t,n){if(!this.cacheEnabled||!this.cacheErroredSolves&&n.errors&&n.errors.length>0)return;let r=e(n)??ue(n);if(!(r>this.cacheMaxBytes))for(this.dropCacheEntry(t),this.cache.set(t,{response:n,insertedAt:Date.now(),sizeBytes:r}),this.cacheBytes+=r;this.cacheBytes>this.cacheMaxBytes&&this.cache.size>0;){let e=this.cache.keys().next().value;if(e===void 0)break;this.dropCacheEntry(e),this.cacheEvictions+=1}}dropCacheEntry(e){let t=this.cache.get(e);t&&(this.cache.delete(e),this.cacheBytes-=t.sizeBytes)}clearCache(){this.cache.clear(),this.cacheBytes=0}cacheStats(){return{entries:this.cache.size,bytes:this.cacheBytes,hits:this.cacheHits,misses:this.cacheMisses,evictions:this.cacheEvictions}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(e,...t){if(e)try{e(...t)}catch(e){n().error(`[SolveScheduler] hook threw:`,e)}}};function k(e){return l(e)?`ref:${e.key}`:typeof e==`string`&&e.length<200?e:`...content...`}function A(e){return Array.isArray(e)?e.map(e=>{let t=0,n=0,r=a(e,`innerTree`);if(r&&typeof r==`object`){for(let e of Object.values(r))if(Array.isArray(e)){t+=e.length;for(let t of e){let e=t?.data;typeof e==`string`&&(n+=e.length)}}}return{param:a(e,`paramName`)??`<unnamed>`,items:t,bytes:n}}):[]}var de=class e{config;serverStats;disposed=!1;constructor(e){this.config=this.normalizeComputeConfig(e),this.serverStats=new m(this.config.serverUrl,this.config.apiKey)}static async create(t){let n=new e(t),r=Math.max(1,(t.retry?.attempts??2)+1),i=t.retry?.baseDelayMs??250,a=t.retry?.maxDelayMs??1e3;for(let e=0;e<r;e++){if(await n.serverStats.isServerOnline())return n;if(e<r-1){let t=Math.min(i*2**e,a);await new Promise(e=>setTimeout(e,t))}}throw await n.dispose(),new f(`Rhino Compute server is not online`,p.NETWORK_ERROR,{context:{serverUrl:n.config.serverUrl,attempts:r}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),Ke(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),$(e,this.config)}async solve(e,t,r){this.ensureNotDisposed();try{if(typeof e==`string`&&!e?.trim())throw new f(`Definition URL/content is required`,p.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new f(`Definition content is empty`,p.INVALID_INPUT);if(l(e)&&!e.key.trim())throw new f(`DefinitionRef key is empty`,p.INVALID_INPUT);let n=await v(t,e,{...this.config,...r?.signal!==void 0&&{signal:r.signal},...r?.timeoutMs!==void 0&&{timeoutMs:r.timeoutMs},...r?.retry!==void 0&&{retry:r.retry}});if(n?.errors&&n.errors.length>0)throw new f(n.errors.join(`; `)||`Computation failed`,p.COMPUTATION_ERROR,{context:{definition:k(e),inputSummary:A(t),errors:n.errors,warnings:n.warnings,values:n.values}});return n}catch(r){throw this.config.debug&&n().error(`Compute failed:`,r),r instanceof f?r:new f(r instanceof Error?r.message:String(r),p.COMPUTATION_ERROR,{context:{definition:k(e),inputSummary:A(t)},originalError:r instanceof Error?r:Error(String(r))})}}createScheduler(e){return this.ensureNotDisposed(),new O((e,t,n)=>v(t,e,n),this.config,e,(e,t,n,r)=>n===null?ae(t,e,r).then(e=>({...e,missed:!1})):oe(t,n,e,r))}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new f(`GrasshopperClient has been disposed and cannot be used`,p.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:t(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning}}};const j=new Map;function M(e,t){j.set(e,t)}M(`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}),M(`Rhino.Geometry.Line`,(e,t)=>{let n=t;return!n||!n.From||!n.To?null:new e.Line([n.From.X,n.From.Y,n.From.Z],[n.To.X,n.To.Y,n.To.Z])});function fe(e){if(j.has(e))return j.get(e);for(let[t,n]of j)if(e.startsWith(t))return n}function pe(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function N(e,t){return{__decodeError:!0,type:e,raw:t}}function me(e,t,r){let i=fe(t),a=!1;if(i)try{let t=i(r,e);if(t!=null)return t}catch(e){n().warn(`Failed to decode Rhino type ${t}:`,e),a=!0}try{if(pe(e))return r.CommonObject.decode(e)}catch(r){return n().warn(`Failed to decode ${t} with CommonObject:`,r),N(t,e)}return a?N(t,e):e}function he(e){let t=new WeakSet,n=e=>{if(!e||typeof e!=`object`||t.has(e))return;t.add(e);let r=e.delete;if(typeof r==`function`){let t=e.isDeleted;(typeof t!=`function`||!t.call(e))&&r.call(e);return}if(Array.isArray(e)){for(let t of e)n(t);return}let i=Object.getPrototypeOf(e);if(i===Object.prototype||i===null)for(let t of Object.values(e))n(t)};n(e)}const P={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},ge=[`WebDisplay`];function F(e){return ge.some(t=>e.includes(t))}function _e(e){if(typeof e!=`string`)return e;let t=e.trim();if(!(t.startsWith(`{`)||t.startsWith(`[`)||t.startsWith(`"`)))return e;try{let e=JSON.parse(t);if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}catch{return e}}function ve(e,t,n){switch(t){case P.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case P.INT:return Number.parseInt(e,10);case P.DOUBLE:return Number.parseFloat(e);case P.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?me(e,t,n):e}}const I=new WeakMap;function L(e){if(I.has(e))return I.get(e);let t=_e(e.data);return I.set(e,t),t}function R(e,t,n,r){return typeof e.data==`string`?ve(n?L(e):e.data,t,r):e.data}function ye(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.fileName==`string`&&typeof t.fileType==`string`&&`data`in t&&typeof t.isBase64Encoded==`boolean`&&typeof t.subFolder==`string`}function z(e){let t=a(e,`values`);return Array.isArray(t)?t:[]}function B(e){return typeof e.type==`string`?e.type:``}function V(e,t){if(!(!e||typeof e!=`object`)){for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)e&&typeof e==`object`&&t(e)}}function be(e,t=!1,n={}){let{parseValues:r=!0,rhino:i,stringOnly:o=!1}=n,s={},c=new Set;for(let n of z(e)){let e=a(n,`paramName`);V(a(n,`innerTree`),n=>{let a=B(n);if(F(a)||o&&a!==P.STRING)return;let l=t?n.id:e;if(!l)return;let u=R(n,a,r,i);l in s?c.has(l)?s[l].push(u):(s[l]=[s[l],u],c.add(l)):s[l]=u})}return{values:s,dispose:()=>he(s)}}function xe(e){let t=[];for(let n of z(e))V(a(n,`innerTree`),e=>{if(!B(e).includes(`FileData`))return;let n=L(e);ye(n)&&t.push(n)});return t}function Se(e,t,n={}){let{parseValues:r=!0,rhino:i,stringOnly:o=!1}=n;for(let n of z(e)){let e=a(n,`innerTree`),s=!1;if(`byName`in t){if(a(n,`paramName`)!==t.byName)continue;s=!0}let c=[];if(V(e,e=>{if(`byId`in t){if(e.id!==t.byId)return;s=!0}let n=B(e);F(n)||o&&n!==P.STRING||c.push(R(e,n,r,i))}),s)return c.length===0?void 0:c.length===1?c[0]:c}}var Ce=class{response;debug;constructor(e,t=!1){this.response=e,this.debug=t}getValues(e=!1,t={}){return be(this.response,e,t)}getValue(e,t){return Se(this.response,e,t)}getFileData(){return xe(this.response)}async getAndDownloadFiles(e,t){let n=this.getFileData();await d(n,e,t)}};const H=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function U(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>H.test(e)&&Array.isArray(t))}function W(e,t,n){let r=Number(e.toFixed(t));return Math.abs(e-r)<n?r:e}function we(e,t){if(!Number.isFinite(e)||e===0)return .1;let n=Math.abs(e);if(n>=1){let n=String(e).split(`.`)[1];if(n&&n.length>0){let e=Math.min(n.length,12),r=10**-e,i=Number(r.toFixed(e));return Math.abs(i-r)<t?i:r}return 1}let r=String(e),i=r.toLowerCase().match(/e(-?\d+)/);if(i){let e=Number(i[1]);if(e<0||r.toLowerCase().includes(`e-`)){let n=Math.abs(e),r=10**-n,i=Number(r.toFixed(n));return Math.abs(i-r)<t?i:r}return .1}let a=n.toFixed(12).replace(/0+$/,``),o=Math.min((a.split(`.`)[1]||``).length,12);if(o===0)return .1;let s=10**-o,c=Number(s.toFixed(o));return Math.abs(c-s)<t?c:s}function Te(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}function G(e,t,n){if(e==null)return e;if(Array.isArray(e)){let n=e.map(t).filter(e=>e!==null);return n.length>0?n:void 0}let r=t(e);return r===null?n?void 0:e:r}const K=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=e.trim();if(t===``||/^[+-]?0[xbo]/i.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}return null},q=e=>{if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}return null},Ee=e=>typeof e==`string`?e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e.startsWith(`"`)?e.slice(1):e:null,De=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function J(e){return t=>{if(typeof t==`object`&&t)return t;if(typeof t==`string`&&t.trim()!==``)try{let r=JSON.parse(t);return typeof r==`object`&&r?r:(n().warn(`Parsed value for input ${e} is not an object`),null)}catch(r){return n().warn(`Failed to parse object value "${t}" for input ${e}`,r),null}return null}}function Oe(e,t=1e-8){let n=e.paramType===`Integer`,r=Te(e);if(U(e.default))return{default:e.default,stepSize:r??(n?1:.1)};if(typeof e.default==`string`&&e.default.trim()!==``&&K(e.default)===null)throw new f(`Invalid numeric default "${e.default}" for input "${e.name||`unknown`}"`,p.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});let i=G(e.default,K,!0);if(n)return Array.isArray(i)?i=i.map(e=>typeof e==`number`?Math.round(e):e):typeof i==`number`&&(i=Math.round(i)),{default:i,stepSize:r??1};let a=Array.isArray(i)?i[0]:i,o;typeof a==`number`&&Number.isFinite(a)&&a!==0?o=a:typeof e.minimum==`number`&&Number.isFinite(e.minimum)&&e.minimum!==0?o=e.minimum:typeof e.maximum==`number`&&Number.isFinite(e.maximum)&&e.maximum!==0&&(o=e.maximum);let s=r??(o===void 0?.1:we(o,t)),c=0,l=String(s),u=l.toLowerCase().match(/e(-?\d+)/);if(c=u?Math.abs(Number(u[1])):l.split(`.`)[1]?.length??0,c===0&&typeof a==`number`&&a!==0&&Math.abs(a)<1){let e=Math.ceil(-Math.log10(Math.abs(a)));Number.isFinite(e)&&e>0&&(c=e)}return c=Math.min(Math.max(c,0),12),Array.isArray(i)?i=i.map(e=>typeof e==`number`?W(e,c,t):e):typeof i==`number`&&(i=W(i,c,t)),{default:i,stepSize:s}}const ke={types:[`Number`,`Integer`],parse(e,t){let{default:n,stepSize:r}=Oe(e);return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:r,default:n}},fallback(e,t){let n=(e.atMost??1)>1,r=typeof e.minimum==`number`&&Number.isFinite(e.minimum)&&e.minimum>0?e.minimum:0;return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:Te(e)??(e.paramType===`Integer`?1:.1),default:n?[r]:r}}},Ae={types:[`Boolean`],parse(e,t){if(U(e.default))return{...t,paramType:`Boolean`,default:e.default};let n=G(e.default,q,!1);if(n!=null&&typeof n!=`boolean`&&!Array.isArray(n))throw new f(`Invalid boolean default "${String(n)}" for input "${e.name||`unknown`}"`,p.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});return{...t,paramType:`Boolean`,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Boolean`,default:n?[!1]:!1}}},je={types:[`Text`],parse(e,t){let n=G(e.default,Ee,!1);return{...t,paramType:`Text`,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Text`,default:n?[``]:``}}},Me={types:[`ValueList`],parse(e,t){if(!e.values||typeof e.values!=`object`||Object.keys(e.values).length===0)throw f.missingValues(e.nickname||`unnamed`,`ValueList`);let r=e.default;if(e.default!==void 0&&e.default!==null){if(typeof e.default==`object`)throw new f(`ValueList input "${e.nickname||`unnamed`}" default is not a string-able value`,p.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});let t=String(e.default).toLowerCase(),i=Object.keys(e.values).find(e=>e.toLowerCase()===t);i===void 0?n().warn(`ValueList input "${e.nickname||`unnamed`}" default value "${e.default}" is not in available values`):r=i}return{...t,paramType:`ValueList`,values:e.values,default:r}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}},Y={types:[`Geometry`],parse(e,t){let n=G(e.default,J(e.nickname||`unnamed`),!0);return{...t,paramType:`Geometry`,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Geometry`,default:n?[null]:null}}},X=new Map([ke,Ae,je,Me,Y,{types:[`File`],parse(e,t){let n=G(e.default,J(e.nickname||`unnamed`),!0);return{...t,paramType:`File`,acceptedFormats:e.acceptedFormats,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`File`,default:n?[null]:null}}},{types:[`Color`],parse(e,t){let n=G(e.default,De,!1);return{...t,paramType:`Color`,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Color`,default:n?[`0, 0, 0`]:`0, 0, 0`}}}].flatMap(e=>e.types.map(t=>[t,e]))),Ne=Y;function Z(e){return a(e,`data`)}function Pe(e){return a(e,`type`)}const Fe=new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),Ie=new Set([`System.Int32`,`System.Int64`]);function Le(e){if(typeof e.default!=`object`||e.default===null||Array.isArray(e.default))return{schema:e};if(!c(e.default,`innerTree`)){let t=`Input "${e.name??`unknown`}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return n().warn(`Unexpected structure in input.default:`,e.default),{schema:{...e,default:null},warning:{code:`MALFORMED_DEFAULT`,message:t}}}let t=a(e.default,`innerTree`)??{};if(Object.keys(t).length===0)return{schema:{...e,default:void 0}};if(e.treeAccess||e.atMost&&e.atMost>1){let r={},i=[];for(let[a,o]of Object.entries(t)){if(!Array.isArray(o)){let t=`Input "${e.name??`unknown`}" default had a non-array innerTree branch ("${a}"); the default was dropped.`;return n().warn(`Unexpected structure in input.default innerTree:`,e.default),{schema:{...e,default:null},warning:{code:`MALFORMED_DEFAULT`,message:t}}}let t=[];for(let e of o){let n=Z(e),r=Pe(e);if(r&&Fe.has(r)){if(typeof n==`string`&&n.trim()===``)continue;let e=K(n);if(e===null){i.push(`"${String(n)}" (${r})`);continue}t.push(Ie.has(r)?Math.round(e):e);continue}if(r===`System.Boolean`){let e=q(n);if(e===null){i.push(`"${String(n)}" (${r})`);continue}t.push(e);continue}if(typeof n==`string`&&r?.startsWith(`Rhino.Geometry`)){try{t.push(JSON.parse(n))}catch{t.push(n)}continue}t.push(n)}r[a]=t}let a;if(i.length>0){let t=`Input "${e.name??`unknown`}" default contained ${i.length} tree value(s) that could not be parsed and were dropped: ${i.join(`, `)}.`;n().warn(t),a={code:`MALFORMED_DEFAULT`,message:t}}return{schema:{...e,default:r},...a&&{warning:a}}}let r=[];for(let e of Object.values(t))Array.isArray(e)&&e.forEach(e=>{e&&typeof e==`object`&&c(e,`data`)&&r.push(Z(e))});return r.length===0?{schema:{...e,default:void 0}}:r.length===1?{schema:{...e,default:r[0]}}:{schema:{...e,default:r}}}const Re=new Map([...X.keys()].map(e=>[e.toLowerCase(),e]));function ze(e){return Re.get(e?.toLowerCase())??e}function Be(e){return Q(e).input}function Q(e){let t={description:e.description,name:e.name,nickname:e.nickname,treeAccess:e.treeAccess,groupName:e.groupName??void 0,id:e.id},r=ze(e.paramType),i={...e,paramType:r},a;try{let{schema:t,warning:n}=Le(i);i=t,a=n&&{inputName:e.name||`unknown`,paramType:e.paramType,message:n.message,code:n.code}}catch(t){i={...i,default:null},a={inputName:e.name||`unknown`,paramType:e.paramType,message:`Input "${e.name??`unknown`}" default could not be normalized and was dropped: ${t instanceof Error?t.message:String(t)}`,code:`MALFORMED_DEFAULT`}}let o=X.get(r);try{if(!o)throw f.unknownParamType(r,e.name);return{input:o.parse(i,t),error:a,...a&&{errors:[a]}}}catch(s){if(s instanceof f){n().error(`Validation error for input ${e.name||`unknown`}:`,s.message);let r={inputName:e.name||`unknown`,paramType:e.paramType,message:s.message,code:s.code};return{input:(o??Ne).fallback(i,t),error:r,errors:a?[a,r]:[r]}}throw new f(s instanceof Error?s.message:String(s),`VALIDATION_ERROR`,{context:{paramName:e.name,paramType:r},originalError:s instanceof Error?s:Error(String(s))})}}function Ve(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=Q(r);t.push(e),i&&n.push(...i)}return{inputs:t,parseErrors:n}}function He(e){let t=a(e,`stepSize`);return{id:a(e,`id`)??``,name:a(e,`name`)??``,nickname:a(e,`nickname`)??null,description:a(e,`description`)??``,paramType:a(e,`paramType`)??``,treeAccess:a(e,`treeAccess`)??!1,minimum:a(e,`minimum`)??null,maximum:a(e,`maximum`)??null,atLeast:a(e,`atLeast`)??1,atMost:a(e,`atMost`)??1,stepSize:typeof t==`number`&&Number.isFinite(t)?t:void 0,default:a(e,`default`),values:a(e,`values`),acceptedFormats:a(e,`acceptedFormats`),groupName:a(e,`groupName`)??null}}function Ue(e){return{name:a(e,`name`)??``,nickname:a(e,`nickname`)??null,paramType:a(e,`paramType`)??``,id:a(e,`id`)??``}}async function $(e,t){let n=x(e,[]),i={};if(n.algo&&(i.algo=n.algo),n.pointer&&(i.pointer=n.pointer),!i.algo&&!i.pointer)throw new f(`Definition must resolve to either a URL pointer or base64 algo`,p.INVALID_INPUT,{context:{definition:e}});let o=await r(`io`,i,_(t));if(!o||typeof o!=`object`)throw new f(`Invalid IO response structure`,p.INVALID_INPUT,{context:{response:o,definition:e}});let s=We(a(o,`warnings`)),c=We(a(o,`errors`)),l=a(o,`inputs`),u=a(o,`outputs`);return{inputs:Array.isArray(l)?l.map(He):[],outputs:Array.isArray(u)?u.map(Ue):[],...s&&{loadWarnings:s},...c&&{loadErrors:c}}}function We(e){if(!Array.isArray(e))return;let t=e.map(Ge).filter(e=>e!==void 0);return t.length>0?t:void 0}function Ge(e){if(e==null)return;let t;if(typeof e==`string`)t=e;else if(typeof e==`object`){let n=a(e,`message`);if(typeof n==`string`&&n.trim().length>0)t=n;else try{t=JSON.stringify(e)??String(e)}catch{t=String(e)}}else t=String(e);return t.trim().length>0?t:void 0}async function Ke(e,t){g(`fetchParsedDefinitionIO`,t.suppressBrowserWarning);let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await $(e,t),{inputs:o,parseErrors:s}=Ve(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}function qe(e){return(Array.isArray(e)?e:[e]).map(e=>({schemas:a(e,`schemas`),error:a(e,`error`)}))}var Je=class e{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(t,n){let r=e.formatPathString(t);this.innerTree[r]||(this.innerTree[r]=[]);let i=n.map(t=>({data:e.serializeValue(t)}));return this.innerTree[r].push(...i),this}appendSingle(e,t){return this.append(e,[t])}fromDataTreeDefault(t){this.innerTree={};for(let[n,r]of Object.entries(t)){if(!Array.isArray(r))continue;let t=e.parsePathString(n);this.append(t,r)}return this}appendFlat(e){let t=Array.isArray(e)?e:[e];return this.append([0],t)}flatten(){let t=[];for(let n of Object.values(this.innerTree))if(Array.isArray(n))for(let r of n)t.push(e.deserializeValue(r.data));return t}getPaths(){return Object.keys(this.innerTree)}getPath(t){let n=e.formatPathString(t),r=this.innerTree[n];if(r)return r.map(t=>e.deserializeValue(t.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(t){return t.filter(t=>e.hasValidValue(t.default)).map(t=>{let n=new e(t.nickname||`unnamed`),r=t.default;if(t.treeAccess&&U(r))n.fromDataTreeDefault(r),e.isNumericInput(t)&&n.applyNumericConstraints(t.minimum,t.maximum,t.nickname||`unnamed`);else{let i=Array.isArray(r)?r:[r],a=e.processValues(i,t);n.appendFlat(a)}return n.toComputeFormat()})}static fromInputParam(t){if(e.hasValidValue(t.default))return e.fromInputParams([t])[0]}static replaceTreeValue(t,n,r){let i=t.length>0&&t[0]instanceof e,a=e.buildFromValue(n,r);if(i){let e=t.slice(),r=e.findIndex(e=>e.getParamName()===n);return r===-1?e.push(a):e[r]=a,e}let o=t.slice(),s=a.toComputeFormat(),c=o.findIndex(e=>e.ParamName===n);return c===-1?o.push(s):o[c]=s,o}static buildFromValue(t,n){let r=new e(t);return U(n)?r.fromDataTreeDefault(n):r.appendFlat(n),r}static getTreeValue(t,n){let r=t.length>0&&t[0]instanceof e?e.readFromBuilders(t,n):e.readFromDataTrees(t,n);return r===null||r.length===0?null:r.length===1?r[0]:r}static readFromBuilders(e,t){let n=e.find(e=>e.getParamName()===t);return n?n.flatten():null}static readFromDataTrees(t,n){let r=t.find(e=>e.ParamName===n);if(!r?.InnerTree)return null;let i=Object.keys(r.InnerTree)[0];if(!i)return null;let a=r.InnerTree[i];return Array.isArray(a)?a.map(t=>t?.data===void 0?null:e.deserializeValue(t.data)):a?.data===void 0?a===void 0?null:[a]:[e.deserializeValue(a.data)]}static parsePathString(e){let t=e.match(H);if(!t)throw Error(`Invalid Grasshopper tree path: "${e}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`);return t[1]?t[1].split(`;`).map(Number):[]}static formatPathString(e){return`{${e.join(`;`)}}`}applyNumericConstraints(t,n,r){for(let i of Object.values(this.innerTree))if(Array.isArray(i))for(let a of i){let i=e.deserializeValue(a.data);if(typeof i==`number`){let o=e.clampValue(i,t,n,r);a.data=e.serializeValue(o)}}}static serializeValue(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`?e:typeof e==`object`&&e?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e==`boolean`||typeof e==`number`||typeof e!=`string`)return e;if(e.startsWith(`{`)||e.startsWith(`[`))try{return JSON.parse(e)}catch{return e}let t=Number(e);return Number.isFinite(t)&&String(t)===e?t:e===`true`||e!==`false`&&e}static hasValidValue(e){return e==null?!1:typeof e==`string`||!(Array.isArray(e)&&e.length===0||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType===`Number`||e.paramType===`Integer`}static processValues(t,n){return t.map(t=>e.isNumericInput(n)&&typeof t==`number`?e.clampValue(t,n.minimum,n.maximum,n.nickname||`unnamed`):t).filter(e=>e!=null)}static clampValue(e,t,r,i){let a=e;return t!=null&&a<t&&(n().warn(`${i}: ${e} below min ${t}, clamping`),a=t),r!=null&&a>r&&(n().warn(`${i}: ${e} above max ${r}, clamping`),a=r),a}};export{m as ComputeServerStats,de as GrasshopperClient,Ce as GrasshopperResponseProcessor,O as SolveScheduler,Je as TreeBuilder,d as downloadFileData,o as extractFilesFromComputeResponse,$ as fetchDefinitionIO,Ke as fetchParsedDefinitionIO,D as hashDefinition,ce as hashSolveInput,l as isDefinitionRef,Be as processInput,qe as readSchemaResults,v as solveGrasshopperDefinition,S as stableStringify};
|
|
2
2
|
//# sourceMappingURL=grasshopper.js.map
|