@selvajs/compute 4.3.0-beta.1 → 5.0.0-beta.2

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