@selvajs/compute 4.0.0-beta.8 → 4.0.1

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
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./core-Bx_1_H10.cjs");var t=class t{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(t,n){this.serverUrl=e.m(t),this.apiKey=n}buildHeaders(){let e={"Content-Type":`application/json`};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,n={},r=t.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(e,o)}async isServerOnline(t=5e3){this.ensureNotDisposed();let n=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(n,{method:`GET`},t)).ok}catch(t){return e.v().debug(`[ComputeServerStats] Fetch error:`,t),!1}}async getActiveChildren(n={}){this.ensureNotDisposed();let{initialize:r=!0}=n,i=r?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,a=r?t.LIFECYCLE_TIMEOUT_MS:t.DEFAULT_TIMEOUT_MS;try{let t=await this.fetchWithTimeout(i,{},a);if(!t.ok)return e.v().warn(`[ComputeServerStats] Failed to fetch active children:`,t.status),null;let n=(await t.text()).trim();return/^\d+$/.test(n)?parseInt(n,10):(e.v().warn(`[ComputeServerStats] Invalid active children response:`,n),null)}catch(t){return e.v().warn(`[ComputeServerStats] Error fetching active children:`,t),null}}async getVersion(){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!t.ok)return e.v().warn(`[ComputeServerStats] Failed to fetch version:`,t.status),null;let n=await t.text();try{let e=JSON.parse(n);return{rhino:e.rhino??``,compute:e.compute??``,git_sha:e.git_sha??null}}catch{return{rhino:n,compute:``,git_sha:null}}}catch(t){return e.v().warn(`[ComputeServerStats] Error fetching version:`,t),null}}async getInstalledPlugins(t=`gh`){this.ensureNotDisposed();try{let n=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${t}/installed`);if(!n.ok)return e.v().warn(`[ComputeServerStats] Failed to fetch ${t} plugins:`,n.status),null;let r=await n.text();try{let e=JSON.parse(r);return e&&typeof e==`object`?e:null}catch{return null}}catch(n){return e.v().warn(`[ComputeServerStats] Error fetching ${t} plugins:`,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(){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:`POST`});if(!t.ok)return e.v().warn(`[ComputeServerStats] Failed to purge cache:`,t.status),null;let n=await t.text();try{let e=JSON.parse(n);return typeof e.purged==`number`?e.purged:null}catch{return null}}catch(t){return e.v().warn(`[ComputeServerStats] Error purging cache:`,t),null}}async purgeAllChildren(){this.ensureNotDisposed();let t=await this.getActiveChildren({initialize:!1});if(t===null)return e.v().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(){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!t.ok)return e.v().warn(`[ComputeServerStats] Failed to fetch server time:`,t.status),null;let n=(await t.text()).trim().replace(/^"|"$/g,``),r=new Date(n);return isNaN(r.getTime())?null:r}catch(t){return e.v().warn(`[ComputeServerStats] Error fetching server time:`,t),null}}async getIdleSpan(){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);if(!t.ok)return e.v().warn(`[ComputeServerStats] Failed to fetch idle span:`,t.status),null;let n=parseFloat((await t.text()).trim());return isNaN(n)?null:n}catch(t){return e.v().warn(`[ComputeServerStats] Error fetching idle span:`,t),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(n){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}${n}`,{method:`POST`},t.LIFECYCLE_TIMEOUT_MS);if(!r.ok)return e.v().warn(`[ComputeServerStats] POST ${n} failed:`,r.status),null;let i=await r.text();try{return JSON.parse(i)}catch{return null}}catch(t){return e.v().warn(`[ComputeServerStats] Error on POST ${n}:`,t),null}}monitor(n,r=5e3){if(this.ensureNotDisposed(),!Number.isFinite(r)||r<t.MIN_MONITOR_INTERVAL_MS)throw RangeError(`monitor() intervalMs must be a finite number >= ${t.MIN_MONITOR_INTERVAL_MS}ms, got ${r}. Sub-${t.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`);let i=!0,a=null;e.v().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 t=await this.getServerStats();if(!i||this.disposed)return;try{n(t)}catch(t){e.v().error(`[ComputeServerStats] Monitor callback threw:`,t)}}catch(t){!i||this.disposed?e.v().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,t):e.v().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,t)}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.b(`ComputeServerStats has been disposed and cannot be used`,e.x.INVALID_STATE,{context:{disposed:this.disposed}})}};const n=new Set;function r(){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 i(t,i){i||r()&&!n.has(t)&&(n.add(t),e.v().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`))}const a={definition_not_cached:e.x.DEFINITION_NOT_CACHED};function o(e){return{...e,serverErrorCodes:{...a,...e.serverErrorCodes}}}function s(t){return t instanceof e.b?t.code===e.x.DEFINITION_NOT_CACHED||t.message.includes(`Unable to load grasshopper definition`):!1}function c(t,n){if(!n)return;let r=e.g(t,`values`);if(!Array.isArray(r)||r.length===0)return;let i=[];for(let t of r){let n=e.g(t,`innerTree`);(!n||Object.keys(n).length===0)&&i.push(e.g(t,`paramName`)??`<unnamed>`)}if(i.length===0)return;let a=i.length===r.length?`all`:`${i.length}/${r.length}`;e.v().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 l(e,t,n){i(`solveGrasshopperDefinition`,n.suppressBrowserWarning);let{response:r}=await p(m(await f(t),e),n);return r}async function u(e,t,n){return i(`solveGrasshopperDefinitionWithCacheKey`,n.suppressBrowserWarning),p(m(await f(t),e),n)}async function d(e,t,n,r){i(`solveByCacheKey`,r.suppressBrowserWarning);let a={algo:null,pointer:t,values:e};try{return{...await p(a,r),missed:!1}}catch(t){if(!s(t))throw t;return{...await p(m(await f(n),e),r),missed:!0}}}async function f(t){if(!e.a(t))return t;try{return await t.load()}catch(n){throw new e.b(`Failed to load definition bytes for ref '${t.key}'`,e.x.INVALID_INPUT,{context:{definitionKey:t.key},originalError:n instanceof Error?n:Error(String(n))})}}async function p(t,n){ee(t,n);let r=await e.o(`grasshopper`,t,o(n)),{pointer:i,algo:a,...s}=r,l=s,u=e.s(r);if(u!==void 0){let t=typeof a==`string`?a.length:0;e.c(l,Math.max(0,u-t))}return c(l,n.debug),{response:l,cacheKey:typeof i==`string`?i:null}}function m(t,n){let r={algo:null,pointer:null,values:n};return t instanceof Uint8Array?r.algo=e.l(t):/^https?:\/\//i.test(t)?r.pointer=t:r.algo=e.d(t)??e.f(t),r}function ee(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 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":"${v(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 g(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 _(e){return g(e.length,t=>e.charCodeAt(t))}function v(e){return g(e.length,t=>e[t])}function te(e,t){return y(b(e),t)}function y(e,t){let n=h(t);return`${e}|t:${n.length}:${_(n)}`}function b(t){return e.a(t)?`r:${t.key}`:typeof t==`string`?`s:${t.length}:${_(t)}`:`u8:${t.length}:${v(t)}`}function x(e){return typeof e!=`string`||!/^https?:\/\//i.test(e)}function ne(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var S=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 t of this.subscribers)try{t()}catch(t){e.v().error(`[SolveScheduler] subscriber threw:`,t)}}solve(t,n,r){if(this.disposed)return Promise.reject(new e.b(`SolveScheduler has been disposed and cannot be used`,e.x.INVALID_STATE));let i=b(t),a=y(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};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.b(`Solve queue is full; request rejected (backpressure)`,e.x.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.b(`Solve waited longer than ${n}ms in queue; rejected (backpressure)`,e.x.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}},{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||!x(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.b(`Superseded by newer solve`,e.x.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.b(`Request aborted by caller`,e.x.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.b?t:this.isAbortLikeError(t)?this.makeAbortError(n.ctx):new e.b(t instanceof Error?t.message:String(t),e.x.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(t,n){if(!this.cacheEnabled||!this.cacheErroredSolves&&n.errors&&n.errors.length>0)return;let r=e.s(n)??ne(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(t,...n){if(t)try{t(...n)}catch(t){e.v().error(`[SolveScheduler] hook threw:`,t)}}};function C(t){return e.a(t)?`ref:${t.key}`:typeof t==`string`&&t.length<200?t:`...content...`}function w(t){return Array.isArray(t)?t.map(t=>{let n=0,r=0,i=e.g(t,`innerTree`);if(i&&typeof i==`object`){for(let e of Object.values(i))if(Array.isArray(e)){n+=e.length;for(let t of e){let e=t?.data;typeof e==`string`&&(r+=e.length)}}}return{param:e.g(t,`paramName`)??`<unnamed>`,items:n,bytes:r}}):[]}var re=class n{config;serverStats;disposed=!1;constructor(e){this.config=this.normalizeComputeConfig(e),this.serverStats=new t(this.config.serverUrl,this.config.apiKey)}static async create(t){let r=new n(t),i=Math.max(1,(t.retry?.attempts??2)+1),a=t.retry?.baseDelayMs??250,o=t.retry?.maxDelayMs??1e3;for(let e=0;e<i;e++){if(await r.serverStats.isServerOnline())return r;if(e<i-1){let t=Math.min(a*2**e,o);await new Promise(e=>setTimeout(e,t))}}throw await r.dispose(),new e.b(`Rhino Compute server is not online`,e.x.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:i}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),$(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),Z(e,this.config)}async solve(t,n,r){this.ensureNotDisposed();try{if(typeof t==`string`&&!t?.trim())throw new e.b(`Definition URL/content is required`,e.x.INVALID_INPUT,{context:{receivedUrl:t}});if(t instanceof Uint8Array&&t.length===0)throw new e.b(`Definition content is empty`,e.x.INVALID_INPUT);if(e.a(t)&&!t.key.trim())throw new e.b(`DefinitionRef key is empty`,e.x.INVALID_INPUT);let i=await l(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}});if(i?.errors&&i.errors.length>0)throw new e.b(i.errors.join(`; `)||`Computation failed`,e.x.COMPUTATION_ERROR,{context:{definition:C(t),inputSummary:w(n),errors:i.errors,warnings:i.warnings,values:i.values}});return i}catch(r){throw this.config.debug&&e.v().error(`Compute failed:`,r),r instanceof e.b?r:new e.b(r instanceof Error?r.message:String(r),e.x.COMPUTATION_ERROR,{context:{definition:C(t),inputSummary:w(n)},originalError:r instanceof Error?r:Error(String(r))})}}createScheduler(e){return this.ensureNotDisposed(),new S((e,t,n)=>l(t,e,n),this.config,e,(e,t,n,r)=>n===null?u(t,e,r).then(e=>({...e,missed:!1})):d(t,n,e,r))}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new e.b(`GrasshopperClient has been disposed and cannot be used`,e.x.INVALID_STATE)}normalizeComputeConfig(t){return{...t,serverUrl:e.m(t.serverUrl),apiKey:t.apiKey,authToken:t.authToken,debug:t.debug??!1,suppressBrowserWarning:t.suppressBrowserWarning}}};const T=new Map;function E(e,t){T.set(e,t)}E(`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}),E(`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 ie(e){if(T.has(e))return T.get(e);for(let[t,n]of T)if(e.startsWith(t))return n}function ae(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function D(e,t){return{__decodeError:!0,type:e,raw:t}}function oe(t,n,r){let i=ie(n),a=!1;if(i)try{let e=i(r,t);if(e!=null)return e}catch(t){e.v().warn(`Failed to decode Rhino type ${n}:`,t),a=!0}try{if(ae(t))return r.CommonObject.decode(t)}catch(r){return e.v().warn(`Failed to decode ${n} with CommonObject:`,r),D(n,t)}return a?D(n,t):t}function O(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 k={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},A=[`WebDisplay`];function j(e){return A.some(t=>e.includes(t))}function se(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 ce(e,t,n){switch(t){case k.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case k.INT:return Number.parseInt(e,10);case k.DOUBLE:return Number.parseFloat(e);case k.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?oe(e,t,n):e}}const M=new WeakMap;function N(e){if(M.has(e))return M.get(e);let t=se(e.data);return M.set(e,t),t}function P(e,t,n,r){return typeof e.data==`string`?ce(n?N(e):e.data,t,r):e.data}function le(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 F(t){let n=e.g(t,`values`);return Array.isArray(n)?n:[]}function I(e){return typeof e.type==`string`?e.type:``}function L(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 ue(t,n=!1,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r,s={},c=new Set;for(let r of F(t)){let t=e.g(r,`paramName`);L(e.g(r,`innerTree`),e=>{let r=I(e);if(j(r)||o&&r!==k.STRING)return;let l=n?e.id:t;if(!l)return;let u=P(e,r,i,a);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:()=>O(s)}}function de(t){let n=[];for(let r of F(t))L(e.g(r,`innerTree`),e=>{if(!I(e).includes(`FileData`))return;let t=N(e);le(t)&&n.push(t)});return n}function fe(t,n,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r;for(let r of F(t)){let t=e.g(r,`innerTree`),s=!1;if(`byName`in n){if(e.g(r,`paramName`)!==n.byName)continue;s=!0}let c=[];if(L(t,e=>{if(`byId`in n){if(e.id!==n.byId)return;s=!0}let t=I(e);j(t)||o&&t!==k.STRING||c.push(P(e,t,i,a))}),s)return c.length===0?void 0:c.length===1?c[0]:c}}var pe=class{response;debug;constructor(e,t=!1){this.response=e,this.debug=t}getValues(e=!1,t={}){return ue(this.response,e,t)}getValue(e,t){return fe(this.response,e,t)}getFileData(){return de(this.response)}async getAndDownloadFiles(t,n){let r=this.getFileData();await e.t(r,t,n)}};const R=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function z(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>R.test(e)&&Array.isArray(t))}function B(e,t,n){let r=Number(e.toFixed(t));return Math.abs(e-r)<n?r:e}function me(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 V(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}function H(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 U=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},W=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},he=e=>typeof e==`string`?e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e.startsWith(`"`)?e.slice(1):e:null,ge=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function G(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.v().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return e.v().warn(`Failed to parse object value "${n}" for input ${t}`,r),null}return null}}function _e(t,n=1e-8){let r=t.paramType===`Integer`,i=V(t);if(z(t.default))return{default:t.default,stepSize:i??(r?1:.1)};if(typeof t.default==`string`&&t.default.trim()!==``&&U(t.default)===null)throw new e.b(`Invalid numeric default "${t.default}" for input "${t.name||`unknown`}"`,e.x.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let a=H(t.default,U,!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:me(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`?B(e,l,n):e):typeof a==`number`&&(a=B(a,l,n)),{default:a,stepSize:c}}const ve={types:[`Number`,`Integer`],parse(e,t){let{default:n,stepSize:r}=_e(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:V(e)??(e.paramType===`Integer`?1:.1),default:n?[r]:r}}},ye={types:[`Boolean`],parse(t,n){if(z(t.default))return{...n,paramType:`Boolean`,default:t.default};let r=H(t.default,W,!1);if(r!=null&&typeof r!=`boolean`&&!Array.isArray(r))throw new e.b(`Invalid boolean default "${String(r)}" for input "${t.name||`unknown`}"`,e.x.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}}},be={types:[`Text`],parse(e,t){let n=H(e.default,he,!1);return{...t,paramType:`Text`,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Text`,default:n?[``]:``}}},xe={types:[`ValueList`],parse(t,n){if(!t.values||typeof t.values!=`object`||Object.keys(t.values).length===0)throw e.b.missingValues(t.nickname||`unnamed`,`ValueList`);let r=t.default;if(t.default!==void 0&&t.default!==null){if(typeof t.default==`object`)throw new e.b(`ValueList input "${t.nickname||`unnamed`}" default is not a string-able value`,e.x.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=String(t.default).toLowerCase(),i=Object.keys(t.values).find(e=>e.toLowerCase()===n);i===void 0?e.v().warn(`ValueList input "${t.nickname||`unnamed`}" default value "${t.default}" is not in available values`):r=i}return{...n,paramType:`ValueList`,values:t.values,default:r}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}},K={types:[`Geometry`],parse(e,t){let n=H(e.default,G(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}}},q=new Map([ve,ye,be,xe,K,{types:[`File`],parse(e,t){let n=H(e.default,G(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=H(e.default,ge,!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]))),Se=K;function J(t){return e.g(t,`data`)}function Ce(t){return e.g(t,`type`)}const we=new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),Te=new Set([`System.Int32`,`System.Int64`]);function Ee(t){if(typeof t.default!=`object`||t.default===null||Array.isArray(t.default))return{schema:t};if(!e.h(t.default,`innerTree`)){let n=`Input "${t.name??`unknown`}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return e.v().warn(`Unexpected structure in input.default:`,t.default),{schema:{...t,default:null},warning:{code:`MALFORMED_DEFAULT`,message:n}}}let n=e.g(t.default,`innerTree`)??{};if(Object.keys(n).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let r={},i=[];for(let[a,o]of Object.entries(n)){if(!Array.isArray(o)){let n=`Input "${t.name??`unknown`}" default had a non-array innerTree branch ("${a}"); the default was dropped.`;return e.v().warn(`Unexpected structure in input.default innerTree:`,t.default),{schema:{...t,default:null},warning:{code:`MALFORMED_DEFAULT`,message:n}}}let n=[];for(let e of o){let t=J(e),r=Ce(e);if(r&&we.has(r)){if(typeof t==`string`&&t.trim()===``)continue;let e=U(t);if(e===null){i.push(`"${String(t)}" (${r})`);continue}n.push(Te.has(r)?Math.round(e):e);continue}if(r===`System.Boolean`){let e=W(t);if(e===null){i.push(`"${String(t)}" (${r})`);continue}n.push(e);continue}if(typeof t==`string`&&r?.startsWith(`Rhino.Geometry`)){try{n.push(JSON.parse(t))}catch{n.push(t)}continue}n.push(t)}r[a]=n}let a;if(i.length>0){let n=`Input "${t.name??`unknown`}" default contained ${i.length} tree value(s) that could not be parsed and were dropped: ${i.join(`, `)}.`;e.v().warn(n),a={code:`MALFORMED_DEFAULT`,message:n}}return{schema:{...t,default:r},...a&&{warning:a}}}let r=[];for(let t of Object.values(n))Array.isArray(t)&&t.forEach(t=>{t&&typeof t==`object`&&e.h(t,`data`)&&r.push(J(t))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}const De=new Map([...q.keys()].map(e=>[e.toLowerCase(),e]));function Oe(e){return De.get(e?.toLowerCase())??e}function ke(e){return Y(e).input}function Y(t){let n={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??void 0,id:t.id},r=Oe(t.paramType),i={...t,paramType:r},a;try{let{schema:e,warning:n}=Ee(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=q.get(r);try{if(!o)throw e.b.unknownParamType(r,t.name);return{input:o.parse(i,n),error:a,...a&&{errors:[a]}}}catch(s){if(s instanceof e.b){e.v().error(`Validation error for input ${t.name||`unknown`}:`,s.message);let r={inputName:t.name||`unknown`,paramType:t.paramType,message:s.message,code:s.code};return{input:(o??Se).fallback(i,n),error:r,errors:a?[a,r]:[r]}}throw new e.b(s instanceof Error?s.message:String(s),`VALIDATION_ERROR`,{context:{paramName:t.name,paramType:r},originalError:s instanceof Error?s:Error(String(s))})}}function Ae(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=Y(r);t.push(e),i&&n.push(...i)}return{inputs:t,parseErrors:n}}function X(t){let n=e.g(t,`stepSize`);return{id:e.g(t,`id`)??``,name:e.g(t,`name`)??``,nickname:e.g(t,`nickname`)??null,description:e.g(t,`description`)??``,paramType:e.g(t,`paramType`)??``,treeAccess:e.g(t,`treeAccess`)??!1,minimum:e.g(t,`minimum`)??null,maximum:e.g(t,`maximum`)??null,atLeast:e.g(t,`atLeast`)??1,atMost:e.g(t,`atMost`)??1,stepSize:typeof n==`number`&&Number.isFinite(n)?n:void 0,default:e.g(t,`default`),values:e.g(t,`values`),acceptedFormats:e.g(t,`acceptedFormats`),groupName:e.g(t,`groupName`)??null}}function je(t){return{name:e.g(t,`name`)??``,nickname:e.g(t,`nickname`)??null,paramType:e.g(t,`paramType`)??``,id:e.g(t,`id`)??``}}async function Z(t,n){let r=m(t,[]),i={};if(r.algo&&(i.algo=r.algo),r.pointer&&(i.pointer=r.pointer),!i.algo&&!i.pointer)throw new e.b(`Definition must resolve to either a URL pointer or base64 algo`,e.x.INVALID_INPUT,{context:{definition:t}});let a=await e.o(`io`,i,o(n));if(!a||typeof a!=`object`)throw new e.b(`Invalid IO response structure`,e.x.INVALID_INPUT,{context:{response:a,definition:t}});let s=Q(e.g(a,`warnings`)),c=Q(e.g(a,`errors`)),l=e.g(a,`inputs`),u=e.g(a,`outputs`);return{inputs:Array.isArray(l)?l.map(X):[],outputs:Array.isArray(u)?u.map(je):[],...s&&{loadWarnings:s},...c&&{loadErrors:c}}}function Q(e){if(!Array.isArray(e))return;let t=e.map(Me).filter(e=>e!==void 0);return t.length>0?t:void 0}function Me(t){if(t==null)return;let n;if(typeof t==`string`)n=t;else if(typeof t==`object`){let r=e.g(t,`message`);if(typeof r==`string`&&r.trim().length>0)n=r;else try{n=JSON.stringify(t)??String(t)}catch{n=String(t)}}else n=String(t);return n.trim().length>0?n:void 0}async function $(e,t){i(`fetchParsedDefinitionIO`,t.suppressBrowserWarning);let{inputs:n,outputs:r,loadWarnings:a,loadErrors:o}=await Z(e,t),{inputs:s,parseErrors:c}=Ae(n);return{inputs:s,outputs:r,...c.length>0&&{parseErrors:c},...a&&{loadWarnings:a},...o&&{loadErrors:o}}}function Ne(t){return(Array.isArray(t)?t:[t]).map(t=>({schemas:e.g(t,`schemas`),error:e.g(t,`error`)}))}var Pe=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(e.treeAccess&&z(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 z(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(e){let t=e.match(R);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(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(t,n,r,i){let a=t;return n!=null&&a<n&&(e.v().warn(`${i}: ${t} below min ${n}, clamping`),a=n),r!=null&&a>r&&(e.v().warn(`${i}: ${t} above max ${r}, clamping`),a=r),a}};exports.ComputeServerStats=t,exports.GrasshopperClient=re,exports.GrasshopperResponseProcessor=pe,exports.SolveScheduler=S,exports.TreeBuilder=Pe,exports.downloadFileData=e.t,exports.extractFilesFromComputeResponse=e.r,exports.fetchDefinitionIO=Z,exports.fetchParsedDefinitionIO=$,exports.hashDefinition=b,exports.hashSolveInput=te,exports.isDefinitionRef=e.a,exports.processInput=ke,exports.readSchemaResults=Ne,exports.solveGrasshopperDefinition=l,exports.stableStringify=h;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./core-DdSvCuFX.cjs");var t=class t{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(t,n){this.serverUrl=e.h(t),this.apiKey=n}buildHeaders(){let e={"Content-Type":`application/json`};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,n={},r=t.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(e,o)}async isServerOnline(t=5e3){this.ensureNotDisposed();let n=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(n,{method:`GET`},t)).ok}catch(t){return e.y().debug(`[ComputeServerStats] Fetch error:`,t),!1}}async getActiveChildren(n={}){this.ensureNotDisposed();let{initialize:r=!0}=n,i=r?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,a=r?t.LIFECYCLE_TIMEOUT_MS:t.DEFAULT_TIMEOUT_MS;try{let t=await this.fetchWithTimeout(i,{},a);if(!t.ok)return e.y().warn(`[ComputeServerStats] Failed to fetch active children:`,t.status),null;let n=(await t.text()).trim();return/^\d+$/.test(n)?parseInt(n,10):(e.y().warn(`[ComputeServerStats] Invalid active children response:`,n),null)}catch(t){return e.y().warn(`[ComputeServerStats] Error fetching active children:`,t),null}}async getVersion(){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!t.ok)return e.y().warn(`[ComputeServerStats] Failed to fetch version:`,t.status),null;let n=await t.text();try{let e=JSON.parse(n);return{rhino:e.rhino??``,compute:e.compute??``,git_sha:e.git_sha??null}}catch{return{rhino:n,compute:``,git_sha:null}}}catch(t){return e.y().warn(`[ComputeServerStats] Error fetching version:`,t),null}}async getInstalledPlugins(t=`gh`){this.ensureNotDisposed();try{let n=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${t}/installed`);if(!n.ok)return e.y().warn(`[ComputeServerStats] Failed to fetch ${t} plugins:`,n.status),null;let r=await n.text();try{let e=JSON.parse(r);return e&&typeof e==`object`?e:null}catch{return null}}catch(n){return e.y().warn(`[ComputeServerStats] Error fetching ${t} plugins:`,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(){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:`POST`});if(!t.ok)return e.y().warn(`[ComputeServerStats] Failed to purge cache:`,t.status),null;let n=await t.text();try{let e=JSON.parse(n);return typeof e.purged==`number`?e.purged:null}catch{return null}}catch(t){return e.y().warn(`[ComputeServerStats] Error purging cache:`,t),null}}async purgeAllChildren(){this.ensureNotDisposed();let t=await this.getActiveChildren({initialize:!1});if(t===null)return e.y().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(){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!t.ok)return e.y().warn(`[ComputeServerStats] Failed to fetch server time:`,t.status),null;let n=(await t.text()).trim().replace(/^"|"$/g,``),r=new Date(n);return isNaN(r.getTime())?null:r}catch(t){return e.y().warn(`[ComputeServerStats] Error fetching server time:`,t),null}}async getIdleSpan(){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);if(!t.ok)return e.y().warn(`[ComputeServerStats] Failed to fetch idle span:`,t.status),null;let n=parseFloat((await t.text()).trim());return isNaN(n)?null:n}catch(t){return e.y().warn(`[ComputeServerStats] Error fetching idle span:`,t),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(n){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}${n}`,{method:`POST`},t.LIFECYCLE_TIMEOUT_MS);if(!r.ok)return e.y().warn(`[ComputeServerStats] POST ${n} failed:`,r.status),null;let i=await r.text();try{return JSON.parse(i)}catch{return null}}catch(t){return e.y().warn(`[ComputeServerStats] Error on POST ${n}:`,t),null}}monitor(n,r=5e3){if(this.ensureNotDisposed(),!Number.isFinite(r)||r<t.MIN_MONITOR_INTERVAL_MS)throw RangeError(`monitor() intervalMs must be a finite number >= ${t.MIN_MONITOR_INTERVAL_MS}ms, got ${r}. Sub-${t.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`);let i=!0,a=null;e.y().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 t=await this.getServerStats();if(!i||this.disposed)return;try{n(t)}catch(t){e.y().error(`[ComputeServerStats] Monitor callback threw:`,t)}}catch(t){!i||this.disposed?e.y().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,t):e.y().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,t)}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.x(`ComputeServerStats has been disposed and cannot be used`,e.S.INVALID_STATE,{context:{disposed:this.disposed}})}};const n=new Set;function r(){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 i(t,i){i||r()&&!n.has(t)&&(n.add(t),e.y().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`))}const a={definition_not_cached:e.S.DEFINITION_NOT_CACHED};function o(e){return{...e,serverErrorCodes:{...a,...e.serverErrorCodes}}}function s(t){return t instanceof e.x?t.code===e.S.DEFINITION_NOT_CACHED||t.message.includes(`Unable to load grasshopper definition`):!1}function c(t,n){if(!n)return;let r=e._(t,`values`);if(!Array.isArray(r)||r.length===0)return;let i=[];for(let t of r){let n=e._(t,`innerTree`);(!n||Object.keys(n).length===0)&&i.push(e._(t,`paramName`)??`<unnamed>`)}if(i.length===0)return;let a=i.length===r.length?`all`:`${i.length}/${r.length}`;e.y().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 l(e,t,n){i(`solveGrasshopperDefinition`,n.suppressBrowserWarning);let{response:r}=await p(m(await f(t),e),n);return r}async function u(e,t,n){return i(`solveGrasshopperDefinitionWithCacheKey`,n.suppressBrowserWarning),p(m(await f(t),e),n)}async function d(e,t,n,r){i(`solveByCacheKey`,r.suppressBrowserWarning);let a={algo:null,pointer:t,values:e};try{return{...await p(a,r),missed:!1}}catch(t){if(!s(t))throw t;return{...await p(m(await f(n),e),r),missed:!0}}}async function f(t){if(!e.o(t))return t;try{return await t.load()}catch(n){throw new e.x(`Failed to load definition bytes for ref '${t.key}'`,e.S.INVALID_INPUT,{context:{definitionKey:t.key},originalError:n instanceof Error?n:Error(String(n))})}}async function p(t,n){ee(t,n);let r=await e.s(`grasshopper`,t,o(n)),{pointer:i,algo:a,...s}=r,l=s,u=e.c(r);if(u!==void 0){let t=typeof a==`string`?a.length:0;e.l(l,Math.max(0,u-t))}return c(l,n.debug),{response:l,cacheKey:typeof i==`string`?i:null}}function m(t,n){let r={algo:null,pointer:null,values:n};return t instanceof Uint8Array?r.algo=e.u(t):/^https?:\/\//i.test(t)?r.pointer=t:r.algo=e.f(t)??e.p(t),r}function ee(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 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":"${v(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 g(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 _(e){return g(e.length,t=>e.charCodeAt(t))}function v(e){return g(e.length,t=>e[t])}function te(e,t){return y(b(e),t)}function y(e,t){let n=h(t);return`${e}|t:${n.length}:${_(n)}`}function b(t){return e.o(t)?`r:${t.key}`:typeof t==`string`?`s:${t.length}:${_(t)}`:`u8:${t.length}:${v(t)}`}function ne(e){return typeof e!=`string`||!/^https?:\/\//i.test(e)}function re(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var x=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 t of this.subscribers)try{t()}catch(t){e.y().error(`[SolveScheduler] subscriber threw:`,t)}}solve(t,n,r){if(this.disposed)return Promise.reject(new e.x(`SolveScheduler has been disposed and cannot be used`,e.S.INVALID_STATE));let i=b(t),a=y(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};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.x(`Solve queue is full; request rejected (backpressure)`,e.S.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.x(`Solve waited longer than ${n}ms in queue; rejected (backpressure)`,e.S.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}},{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||!ne(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.x(`Superseded by newer solve`,e.S.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.x(`Request aborted by caller`,e.S.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.x?t:this.isAbortLikeError(t)?this.makeAbortError(n.ctx):new e.x(t instanceof Error?t.message:String(t),e.S.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(t,n){if(!this.cacheEnabled||!this.cacheErroredSolves&&n.errors&&n.errors.length>0)return;let r=e.c(n)??re(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(t,...n){if(t)try{t(...n)}catch(t){e.y().error(`[SolveScheduler] hook threw:`,t)}}};function S(t){return e.o(t)?`ref:${t.key}`:typeof t==`string`&&t.length<200?t:`...content...`}function C(t){return Array.isArray(t)?t.map(t=>{let n=0,r=0,i=e._(t,`innerTree`);if(i&&typeof i==`object`){for(let e of Object.values(i))if(Array.isArray(e)){n+=e.length;for(let t of e){let e=t?.data;typeof e==`string`&&(r+=e.length)}}}return{param:e._(t,`paramName`)??`<unnamed>`,items:n,bytes:r}}):[]}var ie=class n{config;serverStats;disposed=!1;constructor(e){this.config=this.normalizeComputeConfig(e),this.serverStats=new t(this.config.serverUrl,this.config.apiKey)}static async create(t){let r=new n(t),i=Math.max(1,(t.retry?.attempts??2)+1),a=t.retry?.baseDelayMs??250,o=t.retry?.maxDelayMs??1e3;for(let e=0;e<i;e++){if(await r.serverStats.isServerOnline())return r;if(e<i-1){let t=Math.min(a*2**e,o);await new Promise(e=>setTimeout(e,t))}}throw await r.dispose(),new e.x(`Rhino Compute server is not online`,e.S.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:i}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),Z(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),Y(e,this.config)}async solve(t,n,r){this.ensureNotDisposed();try{if(typeof t==`string`&&!t?.trim())throw new e.x(`Definition URL/content is required`,e.S.INVALID_INPUT,{context:{receivedUrl:t}});if(t instanceof Uint8Array&&t.length===0)throw new e.x(`Definition content is empty`,e.S.INVALID_INPUT);if(e.o(t)&&!t.key.trim())throw new e.x(`DefinitionRef key is empty`,e.S.INVALID_INPUT);let i=await l(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}});if(i?.errors&&i.errors.length>0)throw new e.x(i.errors.join(`; `)||`Computation failed`,e.S.COMPUTATION_ERROR,{context:{definition:S(t),inputSummary:C(n),errors:i.errors,warnings:i.warnings,values:i.values}});return i}catch(r){throw this.config.debug&&e.y().error(`Compute failed:`,r),r instanceof e.x?r:new e.x(r instanceof Error?r.message:String(r),e.S.COMPUTATION_ERROR,{context:{definition:S(t),inputSummary:C(n)},originalError:r instanceof Error?r:Error(String(r))})}}createScheduler(e){return this.ensureNotDisposed(),new x((e,t,n)=>l(t,e,n),this.config,e,(e,t,n,r)=>n===null?u(t,e,r).then(e=>({...e,missed:!1})):d(t,n,e,r))}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new e.x(`GrasshopperClient has been disposed and cannot be used`,e.S.INVALID_STATE)}normalizeComputeConfig(t){return{...t,serverUrl:e.h(t.serverUrl),apiKey:t.apiKey,authToken:t.authToken,debug:t.debug??!1,suppressBrowserWarning:t.suppressBrowserWarning}}};const w=new Map;function T(e,t){w.set(e,t)}T(`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}),T(`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 ae(e){if(w.has(e))return w.get(e);for(let[t,n]of w)if(e.startsWith(t))return n}function oe(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function E(e,t){return{__decodeError:!0,type:e,raw:t}}function se(t,n,r){let i=ae(n),a=!1;if(i)try{let e=i(r,t);if(e!=null)return e}catch(t){e.y().warn(`Failed to decode Rhino type ${n}:`,t),a=!0}try{if(oe(t))return r.CommonObject.decode(t)}catch(r){return e.y().warn(`Failed to decode ${n} with CommonObject:`,r),E(n,t)}return a?E(n,t):t}function ce(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 D={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},O=[`WebDisplay`];function k(e){return O.some(t=>e.includes(t))}function le(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 ue(e,t,n){switch(t){case D.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case D.INT:return Number.parseInt(e,10);case D.DOUBLE:return Number.parseFloat(e);case D.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?se(e,t,n):e}}const A=new WeakMap;function j(e){if(A.has(e))return A.get(e);let t=le(e.data);return A.set(e,t),t}function M(e,t,n,r){return typeof e.data==`string`?ue(n?j(e):e.data,t,r):e.data}function de(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 N(t){let n=e._(t,`values`);return Array.isArray(n)?n:[]}function P(e){return typeof e.type==`string`?e.type:``}function F(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 fe(t,n=!1,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r,s={},c=new Set;for(let r of N(t)){let t=e._(r,`paramName`);F(e._(r,`innerTree`),e=>{let r=P(e);if(k(r)||o&&r!==D.STRING)return;let l=n?e.id:t;if(!l)return;let u=M(e,r,i,a);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:()=>ce(s)}}function pe(t){let n=[];for(let r of N(t))F(e._(r,`innerTree`),e=>{if(!P(e).includes(`FileData`))return;let t=j(e);de(t)&&n.push(t)});return n}function me(t,n,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r;for(let r of N(t)){let t=e._(r,`innerTree`),s=!1;if(`byName`in n){if(e._(r,`paramName`)!==n.byName)continue;s=!0}let c=[];if(F(t,e=>{if(`byId`in n){if(e.id!==n.byId)return;s=!0}let t=P(e);k(t)||o&&t!==D.STRING||c.push(M(e,t,i,a))}),s)return c.length===0?void 0:c.length===1?c[0]:c}}var he=class{response;debug;constructor(e,t=!1){this.response=e,this.debug=t}getValues(e=!1,t={}){return fe(this.response,e,t)}getValue(e,t){return me(this.response,e,t)}getFileData(){return pe(this.response)}async getAndDownloadFiles(t,n){let r=this.getFileData();await e.t(r,t,n)}};const I=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function L(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>I.test(e)&&Array.isArray(t))}function R(e,t,n){let r=Number(e.toFixed(t));return Math.abs(e-r)<n?r:e}function ge(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 z(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}function B(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 V=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},H=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},_e=e=>typeof e==`string`?e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e.startsWith(`"`)?e.slice(1):e:null,ve=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function U(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.y().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return e.y().warn(`Failed to parse object value "${n}" for input ${t}`,r),null}return null}}function ye(t,n=1e-8){let r=t.paramType===`Integer`,i=z(t);if(L(t.default))return{default:t.default,stepSize:i??(r?1:.1)};if(typeof t.default==`string`&&t.default.trim()!==``&&V(t.default)===null)throw new e.x(`Invalid numeric default "${t.default}" for input "${t.name||`unknown`}"`,e.S.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let a=B(t.default,V,!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:ge(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`?R(e,l,n):e):typeof a==`number`&&(a=R(a,l,n)),{default:a,stepSize:c}}const be={types:[`Number`,`Integer`],parse(e,t){let{default:n,stepSize:r}=ye(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:z(e)??(e.paramType===`Integer`?1:.1),default:n?[r]:r}}},xe={types:[`Boolean`],parse(t,n){if(L(t.default))return{...n,paramType:`Boolean`,default:t.default};let r=B(t.default,H,!1);if(r!=null&&typeof r!=`boolean`&&!Array.isArray(r))throw new e.x(`Invalid boolean default "${String(r)}" for input "${t.name||`unknown`}"`,e.S.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}}},Se={types:[`Text`],parse(e,t){let n=B(e.default,_e,!1);return{...t,paramType:`Text`,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Text`,default:n?[``]:``}}},Ce={types:[`ValueList`],parse(t,n){if(!t.values||typeof t.values!=`object`||Object.keys(t.values).length===0)throw e.x.missingValues(t.nickname||`unnamed`,`ValueList`);let r=t.default;if(t.default!==void 0&&t.default!==null){if(typeof t.default==`object`)throw new e.x(`ValueList input "${t.nickname||`unnamed`}" default is not a string-able value`,e.S.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=String(t.default).toLowerCase(),i=Object.keys(t.values).find(e=>e.toLowerCase()===n);i===void 0?e.y().warn(`ValueList input "${t.nickname||`unnamed`}" default value "${t.default}" is not in available values`):r=i}return{...n,paramType:`ValueList`,values:t.values,default:r}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}},W={types:[`Geometry`],parse(e,t){let n=B(e.default,U(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}}},G=new Map([be,xe,Se,Ce,W,{types:[`File`],parse(e,t){let n=B(e.default,U(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=B(e.default,ve,!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]))),we=W;function K(t){return e._(t,`data`)}function Te(t){return e._(t,`type`)}const Ee=new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),De=new Set([`System.Int32`,`System.Int64`]);function Oe(t){if(typeof t.default!=`object`||t.default===null||Array.isArray(t.default))return{schema:t};if(!e.g(t.default,`innerTree`)){let n=`Input "${t.name??`unknown`}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return e.y().warn(`Unexpected structure in input.default:`,t.default),{schema:{...t,default:null},warning:{code:`MALFORMED_DEFAULT`,message:n}}}let n=e._(t.default,`innerTree`)??{};if(Object.keys(n).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let r={},i=[];for(let[a,o]of Object.entries(n)){if(!Array.isArray(o)){let n=`Input "${t.name??`unknown`}" default had a non-array innerTree branch ("${a}"); the default was dropped.`;return e.y().warn(`Unexpected structure in input.default innerTree:`,t.default),{schema:{...t,default:null},warning:{code:`MALFORMED_DEFAULT`,message:n}}}let n=[];for(let e of o){let t=K(e),r=Te(e);if(r&&Ee.has(r)){if(typeof t==`string`&&t.trim()===``)continue;let e=V(t);if(e===null){i.push(`"${String(t)}" (${r})`);continue}n.push(De.has(r)?Math.round(e):e);continue}if(r===`System.Boolean`){let e=H(t);if(e===null){i.push(`"${String(t)}" (${r})`);continue}n.push(e);continue}if(typeof t==`string`&&r?.startsWith(`Rhino.Geometry`)){try{n.push(JSON.parse(t))}catch{n.push(t)}continue}n.push(t)}r[a]=n}let a;if(i.length>0){let n=`Input "${t.name??`unknown`}" default contained ${i.length} tree value(s) that could not be parsed and were dropped: ${i.join(`, `)}.`;e.y().warn(n),a={code:`MALFORMED_DEFAULT`,message:n}}return{schema:{...t,default:r},...a&&{warning:a}}}let r=[];for(let t of Object.values(n))Array.isArray(t)&&t.forEach(t=>{t&&typeof t==`object`&&e.g(t,`data`)&&r.push(K(t))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}const ke=new Map([...G.keys()].map(e=>[e.toLowerCase(),e]));function Ae(e){return ke.get(e?.toLowerCase())??e}function je(e){return q(e).input}function q(t){let n={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??void 0,id:t.id},r=Ae(t.paramType),i={...t,paramType:r},a;try{let{schema:e,warning:n}=Oe(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=G.get(r);try{if(!o)throw e.x.unknownParamType(r,t.name);return{input:o.parse(i,n),error:a,...a&&{errors:[a]}}}catch(s){if(s instanceof e.x){e.y().error(`Validation error for input ${t.name||`unknown`}:`,s.message);let r={inputName:t.name||`unknown`,paramType:t.paramType,message:s.message,code:s.code};return{input:(o??we).fallback(i,n),error:r,errors:a?[a,r]:[r]}}throw new e.x(s instanceof Error?s.message:String(s),`VALIDATION_ERROR`,{context:{paramName:t.name,paramType:r},originalError:s instanceof Error?s:Error(String(s))})}}function Me(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 J(t){let n=e._(t,`stepSize`);return{id:e._(t,`id`)??``,name:e._(t,`name`)??``,nickname:e._(t,`nickname`)??null,description:e._(t,`description`)??``,paramType:e._(t,`paramType`)??``,treeAccess:e._(t,`treeAccess`)??!1,minimum:e._(t,`minimum`)??null,maximum:e._(t,`maximum`)??null,atLeast:e._(t,`atLeast`)??1,atMost:e._(t,`atMost`)??1,stepSize:typeof n==`number`&&Number.isFinite(n)?n:void 0,default:e._(t,`default`),values:e._(t,`values`),acceptedFormats:e._(t,`acceptedFormats`),groupName:e._(t,`groupName`)??null}}function Ne(t){return{name:e._(t,`name`)??``,nickname:e._(t,`nickname`)??null,paramType:e._(t,`paramType`)??``,id:e._(t,`id`)??``}}async function Y(t,n){let r=m(t,[]),i={};if(r.algo&&(i.algo=r.algo),r.pointer&&(i.pointer=r.pointer),!i.algo&&!i.pointer)throw new e.x(`Definition must resolve to either a URL pointer or base64 algo`,e.S.INVALID_INPUT,{context:{definition:t}});let a=await e.s(`io`,i,o(n));if(!a||typeof a!=`object`)throw new e.x(`Invalid IO response structure`,e.S.INVALID_INPUT,{context:{response:a,definition:t}});let s=X(e._(a,`warnings`)),c=X(e._(a,`errors`)),l=e._(a,`inputs`),u=e._(a,`outputs`);return{inputs:Array.isArray(l)?l.map(J):[],outputs:Array.isArray(u)?u.map(Ne):[],...s&&{loadWarnings:s},...c&&{loadErrors:c}}}function X(e){if(!Array.isArray(e))return;let t=e.map(Pe).filter(e=>e!==void 0);return t.length>0?t:void 0}function Pe(t){if(t==null)return;let n;if(typeof t==`string`)n=t;else if(typeof t==`object`){let r=e._(t,`message`);if(typeof r==`string`&&r.trim().length>0)n=r;else try{n=JSON.stringify(t)??String(t)}catch{n=String(t)}}else n=String(t);return n.trim().length>0?n:void 0}async function Z(e,t){i(`fetchParsedDefinitionIO`,t.suppressBrowserWarning);let{inputs:n,outputs:r,loadWarnings:a,loadErrors:o}=await Y(e,t),{inputs:s,parseErrors:c}=Me(n);return{inputs:s,outputs:r,...c.length>0&&{parseErrors:c},...a&&{loadWarnings:a},...o&&{loadErrors:o}}}function Fe(t){return(Array.isArray(t)?t:[t]).map(t=>({schemas:e._(t,`schemas`),error:e._(t,`error`)}))}const Ie=new Set([`options`,`defaultOptions`,`values`]),Q=e=>e>=`A`&&e<=`Z`;function Le(e){if(e.length===0||!Q(e[0]))return e;let t=0;for(;t<e.length&&Q(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function Re(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=Le(n);t[e]=Ie.has(e)?r:$(r)}return t}var ze=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(e.treeAccess&&L(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 L(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(e){let t=e.match(I);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(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(t,n,r,i){let a=t;return n!=null&&a<n&&(e.y().warn(`${i}: ${t} below min ${n}, clamping`),a=n),r!=null&&a>r&&(e.y().warn(`${i}: ${t} above max ${r}, clamping`),a=r),a}};exports.ComputeServerStats=t,exports.GrasshopperClient=ie,exports.GrasshopperResponseProcessor=he,exports.SolveScheduler=x,exports.TreeBuilder=ze,exports.downloadFileData=e.t,exports.extractFilesFromComputeResponse=e.r,exports.fetchDefinitionIO=Y,exports.fetchParsedDefinitionIO=Z,exports.hashDefinition=b,exports.hashSolveInput=te,exports.isDefinitionRef=e.o,exports.normalizeUISchemaCasing=Re,exports.processInput=je,exports.readSchemaResults=Fe,exports.solveGrasshopperDefinition=l,exports.stableStringify=h;
2
2
  //# sourceMappingURL=grasshopper.cjs.map