@selvajs/compute 4.2.1 → 4.2.2-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/grasshopper.d.cts
CHANGED
|
@@ -50,8 +50,8 @@ declare class ComputeServerStats {
|
|
|
50
50
|
/**
|
|
51
51
|
* Check if the server is online.
|
|
52
52
|
*
|
|
53
|
-
* This is a single-sample probe: it returns `true` only on a 2xx
|
|
54
|
-
* proxy liveness root `/`, and `false` for every other outcome (
|
|
53
|
+
* This is a single-sample probe: it returns `true` only on a 2xx or a redirect
|
|
54
|
+
* from the proxy liveness root `/`, and `false` for every other outcome (4xx/5xx,
|
|
55
55
|
* network error, or timeout). A cold or briefly-busy-but-up server can therefore
|
|
56
56
|
* read as offline — callers that gate on this (e.g. client construction)
|
|
57
57
|
* should retry rather than treat a single `false` as authoritative.
|
package/dist/grasshopper.d.ts
CHANGED
|
@@ -50,8 +50,8 @@ declare class ComputeServerStats {
|
|
|
50
50
|
/**
|
|
51
51
|
* Check if the server is online.
|
|
52
52
|
*
|
|
53
|
-
* This is a single-sample probe: it returns `true` only on a 2xx
|
|
54
|
-
* proxy liveness root `/`, and `false` for every other outcome (
|
|
53
|
+
* This is a single-sample probe: it returns `true` only on a 2xx or a redirect
|
|
54
|
+
* from the proxy liveness root `/`, and `false` for every other outcome (4xx/5xx,
|
|
55
55
|
* network error, or timeout). A cold or briefly-busy-but-up server can therefore
|
|
56
56
|
* read as offline — callers that gate on this (e.g. client construction)
|
|
57
57
|
* should retry rather than treat a single `false` as authoritative.
|
package/dist/grasshopper.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{C as e,S as t,_ as n,b as r,c as i,f as a,g as o,l as s,m as c,o as l,p as u,r as d,s as f,t as p,u as ee,v as m}from"./core-BSKhoCtA.js";var h=class n{serverUrl;apiKey;disposed=!1;activeMonitors=new Set;activeTimeouts=new Set;static DEFAULT_TIMEOUT_MS=5e3;static LIFECYCLE_TIMEOUT_MS=6e4;static MIN_MONITOR_INTERVAL_MS=100;constructor(e,t){this.serverUrl=o(e),this.apiKey=t}buildHeaders(){let e={"Content-Type":`application/json`};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,t={},r=n.DEFAULT_TIMEOUT_MS){let i=new Headers(this.buildHeaders());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`},e);return{online:n.ok,status:n.status}}catch(e){return r().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,i=t?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,a=t?n.LIFECYCLE_TIMEOUT_MS:n.DEFAULT_TIMEOUT_MS;try{let e=await this.fetchWithTimeout(i,{},a);if(!e.ok)return r().warn(`[ComputeServerStats] Failed to fetch active children:`,e.status),null;let t=(await e.text()).trim();return/^\d+$/.test(t)?parseInt(t,10):(r().warn(`[ComputeServerStats] Invalid active children response:`,t),null)}catch(e){return r().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 r().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 r().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 r().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 r().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 r().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 r().warn(`[ComputeServerStats] Error purging cache:`,e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return r().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 r().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 r().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 r().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 r().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 r().warn(`[ComputeServerStats] POST ${e} failed:`,t.status),null;let i=await t.text();try{return JSON.parse(i)}catch{return null}}catch(t){return r().warn(`[ComputeServerStats] Error on POST ${e}:`,t),null}}monitor(i,a=5e3){if(this.ensureNotDisposed(),!Number.isFinite(a)||a<n.MIN_MONITOR_INTERVAL_MS)throw new t(`monitor() intervalMs must be a finite number >= ${n.MIN_MONITOR_INTERVAL_MS}ms, got ${a}. Sub-${n.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`,e.INVALID_CONFIG,{context:{intervalMs:a}});let o=!0,s=null;r().info(`🔄 Starting server stats monitoring every ${a}ms`);let c=async()=>{if(s!==null&&(this.activeTimeouts.delete(s),s=null),o&&!this.disposed){try{let e=await this.getServerStats();if(!o||this.disposed)return;try{i(e)}catch(e){r().error(`[ComputeServerStats] Monitor callback threw:`,e)}}catch(e){!o||this.disposed?r().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,e):r().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,e)}o&&!this.disposed&&(s=setTimeout(()=>void c(),a),this.activeTimeouts.add(s))}},l=()=>{o=!1,s!==null&&(clearTimeout(s),this.activeTimeouts.delete(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();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new t(`ComputeServerStats has been disposed and cannot be used`,e.INVALID_STATE,{context:{disposed:this.disposed}})}};const te=new Set;function ne(){if(typeof window>`u`||globalThis.process?.versions?.node!=null)return!1;let e=globalThis.navigator,t=typeof e?.userAgent==`string`?e.userAgent:``;return!/jsdom/i.test(t)}function g(e,t){t||ne()&&!te.has(e)&&(te.add(e),r().warn(`Warning: ${e} is running on the client side. For better performance and security, consider running this on the server side.`))}const re={definition_not_cached:e.DEFINITION_NOT_CACHED};function _(e){return{...e,serverErrorCodes:{...re,...e.serverErrorCodes}}}function ie(n){return n instanceof t?n.code===e.DEFINITION_NOT_CACHED||n.message.includes(`Unable to load grasshopper definition`):!1}function ae(e,t){if(!t)return;let n=m(e,`values`);if(!Array.isArray(n)||n.length===0)return;let i=[];for(let e of n){let t=m(e,`innerTree`);(!t||Object.keys(t).length===0)&&i.push(m(e,`paramName`)??`<unnamed>`)}if(i.length===0)return;let a=i.length===n.length?`all`:`${i.length}/${n.length}`;r().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 v(e,t,n){g(`solveGrasshopperDefinition`,n.suppressBrowserWarning);let{response:r}=await b(x(await y(t),e),n);return r}async function oe(e,t,n){return g(`solveGrasshopperDefinitionWithCacheKey`,n.suppressBrowserWarning),b(x(await y(t),e),n)}async function se(e,t,n,r){g(`solveByCacheKey`,r.suppressBrowserWarning);let i={algo:null,pointer:t,values:e};try{return{...await b(i,r),missed:!1}}catch(t){if(!ie(t))throw t;return{...await b(x(await y(n),e),r),missed:!0}}}async function y(n){if(!l(n))return n;try{return await n.load()}catch(r){throw new t(`Failed to load definition bytes for ref '${n.key}'`,e.INVALID_INPUT,{context:{definitionKey:n.key},originalError:r instanceof Error?r:Error(String(r))})}}async function b(e,t){ce(e,t);let n=await f(`grasshopper`,e,_(t)),{pointer:r,algo:a,...o}=n,c=o,l=i(n);if(l!==void 0){let e=typeof a==`string`?a.length:0;s(c,Math.max(0,l-e))}return ae(c,t.debug),{response:c,cacheKey:typeof r==`string`?r:null}}function x(e,t){let n={algo:null,pointer:null,values:t};return e instanceof Uint8Array?n.algo=ee(e):/^https?:\/\//i.test(e)?n.pointer=e:n.algo=a(e)??u(e),n}function ce(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 S(e){let t=new WeakSet,n=e=>{if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`number`)return Number.isFinite(e)?String(e):`null`;if(typeof e==`string`||typeof e==`boolean`)return JSON.stringify(e);if(typeof e==`bigint`)return`${e}n`;if(e instanceof Uint8Array)return`{"__u8":${e.length},"hash":"${le(e)}"}`;if(Array.isArray(e)){if(t.has(e))return`"[Circular]"`;t.add(e);let r=[];for(let t=0;t<e.length;t++)r.push(n(e[t]));return t.delete(e),`[${r.join(`,`)}]`}if(typeof e==`object`){if(t.has(e))return`"[Circular]"`;t.add(e);let r;return r=typeof e.toJSON==`function`?n(e.toJSON()):e instanceof Map?`{"__map":[${[...e.entries()].map(([e,t])=>`[${n(e)},${n(t)}]`).sort().join(`,`)}]}`:e instanceof Set?`{"__set":[${[...e.values()].map(n).sort().join(`,`)}]}`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${n(e[t])}`).join(`,`)}}`,t.delete(e),r}return`null`};return n(e)}function C(e,t){let n=2166136261;for(let r=0;r<e;r++)n^=t(r),n=n+((n<<1)+(n<<4)+(n<<7)+(n<<8)+(n<<24))>>>0;return n.toString(16).padStart(8,`0`)}function w(e){return C(e.length,t=>e.charCodeAt(t))}function le(e){return C(e.length,t=>e[t])}function ue(e,t){return T(E(e),t)}function T(e,t){let n=S(t);return`${e}|t:${n.length}:${w(n)}`}function E(e){return l(e)?`r:${e.key}`:typeof e==`string`?`s:${e.length}:${w(e)}`:`u8:${e.length}:${le(e)}`}function de(e){return typeof e!=`string`||!/^https?:\/\//i.test(e)}function fe(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var D=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){r().error(`[SolveScheduler] subscriber threw:`,e)}}solve(n,r,i){if(this.disposed)return Promise.reject(new t(`SolveScheduler has been disposed and cannot be used`,e.INVALID_STATE));let a=E(n),o=T(a,r),s=++this.solveSeq,c={key:o,enqueuedAt:Date.now(),startedAt:null};if(i?.signal?.aborted)return Promise.reject(this.makeAbortError(c));if(this.cacheEnabled){let e=this.readCache(o);if(e){this.mode===`latest-wins`&&this.supersedeCurrent();let t={status:`success`,response:e,durationMs:0,fromCache:!0};return this.writeLastState(s,{result:e,durationMs:0}),this.runHook(this.onStart,c),this.runHook(this.onSettle,c,t),this.notify(),Promise.resolve(e)}}return new Promise((e,t)=>{let o={definition:n,dataTree:r,definitionHash:a,ctx:c,seq:s,resolve:e,reject:t,externalSignal:i?.signal,selvaevents:i?.selvaevents};o.externalSignal&&(o.queuedAbortHandler=()=>this.abortQueuedItem(o),o.externalSignal.addEventListener(`abort`,o.queuedAbortHandler,{once:!0})),this.enqueue(o)})}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(n){let r=new t(`Solve queue is full; request rejected (backpressure)`,e.QUEUE_FULL,{statusCode:503,context:{key:n.ctx.key,queueDepth:this.fifoQueue.length,maxQueueDepth:this.maxQueueDepth}});this.settleError(n,r)&&this.runHook(this.onSettle,n.ctx,{status:`error`,error:r,durationMs:0}),this.notify()}armQueueWaitTimer(n){if(this.queueWaitMs===void 0)return;let r=this.queueWaitMs;n.queueWaitTimer=setTimeout(()=>{if(n.settled)return;let i=this.fifoQueue.indexOf(n);i>=0&&this.fifoQueue.splice(i,1);let a=new t(`Solve waited longer than ${r}ms in queue; rejected (backpressure)`,e.QUEUE_TIMEOUT,{statusCode:503,context:{key:n.ctx.key,waitedMs:Date.now()-n.ctx.enqueuedAt,queueWaitMs:r}});this.settleError(n,a)&&this.runHook(this.onSettle,n.ctx,{status:`error`,error:a,durationMs:0}),this.notify()},r)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case`latest-wins`:this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break;case`queue`:case`parallel`:this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifoQueue.length>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifoQueue.push(e))}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||!de(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(n){let r=new t(`Superseded by newer solve`,e.SUPERSEDED,{context:{key:n.ctx.key,enqueuedAt:n.ctx.enqueuedAt}});this.settleError(n,r)&&this.runHook(this.onSuperseded,n.ctx)}makeAbortError(n){return new t(`Request aborted by caller`,e.ABORTED,{context:{key:n.key,enqueuedAt:n.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(n,r){return r.settled&&`error`in r.settled?r.settled.error:n instanceof t?n:this.isAbortLikeError(n)?this.makeAbortError(r.ctx):new t(n instanceof Error?n.message:String(n),e.UNKNOWN_ERROR,{originalError:n instanceof Error?n:Error(String(n))})}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 n=m(t,`errors`);if(!this.cacheErroredSolves&&Array.isArray(n)&&n.length>0)return;let r=i(t)??fe(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(e,...t){if(e)try{e(...t)}catch(e){r().error(`[SolveScheduler] hook threw:`,e)}}};function O(e){return l(e)?`ref:${e.key}`:typeof e==`string`&&e.length<200?e:`...content...`}function k(e){return Array.isArray(e)?e.map(e=>{let t=0,n=0,r=m(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:m(e,`paramName`)??`<unnamed>`,items:t,bytes:n}}):[]}var pe=class n{config;serverStats;disposed=!1;static CREATE_PROBE_TIMEOUT_MS=2e3;constructor(e){this.config=this.normalizeComputeConfig(e),this.serverStats=new h(this.config.serverUrl,this.config.apiKey)}static async create(r){let i=new n(r),a=Math.max(1,(r.retry?.attempts??2)+1),o=r.retry?.baseDelayMs??250,s=r.retry?.maxDelayMs??1e3,l,u=null,d=0;for(let e=0;e<a;e++){if(d=e+1,l=await i.serverStats.probeServer(n.CREATE_PROBE_TIMEOUT_MS),l.online)return i;if(u=c(l),u&&!u.retryable)break;if(e<a-1){let t=Math.min(o*2**e,s);await new Promise(e=>setTimeout(e,t))}}await i.dispose();let f=l?.status,p=u?`Rhino Compute server is not available. ${u.summary}`:`Rhino Compute server is not online`;throw new t(p,e.NETWORK_ERROR,{...f!==void 0&&{statusCode:f},context:{serverUrl:i.config.serverUrl,attempts:d,maxAttempts:a,...u&&{probeVerdict:u.verdict,probeRetryable:u.retryable},...f!==void 0&&{lastProbeStatus:f},...l?.error!==void 0&&{lastProbeError:l.error}}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),Xe(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),Q(e,this.config)}async solve(n,i,a){this.ensureNotDisposed();try{if(typeof n==`string`&&!n?.trim())throw new t(`Definition URL/content is required`,e.INVALID_INPUT,{context:{receivedUrl:n}});if(n instanceof Uint8Array&&n.length===0)throw new t(`Definition content is empty`,e.INVALID_INPUT);if(l(n)&&!n.key.trim())throw new t(`DefinitionRef key is empty`,e.INVALID_INPUT);let r=await v(i,n,{...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=m(r,`errors`);if(Array.isArray(o)&&o.length>0)throw new t(o.map(String).join(`; `)||`Computation failed`,e.COMPUTATION_ERROR,{context:{definition:O(n),inputSummary:k(i),errors:o,warnings:m(r,`warnings`),values:r.values}});return r}catch(a){throw this.config.debug&&r().error(`Compute failed:`,a),a instanceof t?a:new t(a instanceof Error?a.message:String(a),e.COMPUTATION_ERROR,{context:{definition:O(n),inputSummary:k(i)},originalError:a instanceof Error?a:Error(String(a))})}}createScheduler(e){return this.ensureNotDisposed(),new D((e,t,n)=>v(t,e,n),this.config,e,(e,t,n,r)=>n===null?oe(t,e,r).then(e=>({...e,missed:!1})):se(t,n,e,r))}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new t(`GrasshopperClient has been disposed and cannot be used`,e.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:o(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning}}};const A=new Map;function me(e,t){A.set(e,t)}me(`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}),me(`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(A.has(e))return A.get(e);for(let[t,n]of A)if(e.startsWith(t))return n}function ge(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function j(e,t){return{__decodeError:!0,type:e,raw:t}}function _e(e,t,n){let i=he(t),a=!1;if(i)try{let t=i(n,e);if(t!=null)return t}catch(e){r().warn(`Failed to decode Rhino type ${t}:`,e),a=!0}try{if(ge(e))return n.CommonObject.decode(e)}catch(n){return r().warn(`Failed to decode ${t} with CommonObject:`,n),j(t,e)}return a?j(t,e):e}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 M={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},ye=[`WebDisplay`],N=`FileData`;function P(e){return ye.some(t=>e.includes(t))}function be(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 xe(e,t,n){switch(t){case M.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case M.INT:return Number.parseInt(e,10);case M.DOUBLE:return Number.parseFloat(e);case M.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?_e(e,t,n):e}}const F=new WeakMap;function I(e){if(F.has(e))return F.get(e);let t=be(e.data);return F.set(e,t),t}function L(e,t,n,r){if(typeof e.data!=`string`)return e.data;let i=n?I(e):e.data;return n&&t.includes(N)?R(i)??i:xe(i,t,r)}const Se=e=>e===!0||typeof e==`string`&&e.trim().toLowerCase()===`true`;function R(e){if(!e||typeof e!=`object`)return null;let t=m(e,`fileName`),r=m(e,`fileType`),i=m(e,`subFolder`),a=m(e,`isBase64Encoded`);if(typeof t!=`string`||typeof r!=`string`||typeof i!=`string`||!n(e,`data`)||typeof a!=`boolean`&&typeof a!=`string`)return null;let o=m(e,`metadata`);return{fileName:t,fileType:r,data:m(e,`data`),isBase64Encoded:Se(a),subFolder:i,...o?{metadata:o}:{}}}function z(e){let t=m(e,`values`);return Array.isArray(t)?t:[]}function B(e){return typeof e.type==`string`?e.type:``}function V(e,t){if(e&&typeof e==`object`){for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)e&&typeof e==`object`&&t(e)}}function Ce(e,t=!1,n={}){let{parseValues:r=!0,rhino:i,stringOnly:a=!1}=n,o={},s=new Set;for(let n of z(e)){let e=m(n,`paramName`);V(m(n,`innerTree`),n=>{let c=B(n);if(P(c)||a&&c!==M.STRING)return;let l=t?n.id:e;if(!l)return;let u=L(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 we(e){let t=[];for(let n of z(e))V(m(n,`innerTree`),e=>{if(!B(e).includes(N))return;let n=R(I(e));n&&t.push(n)});return t}function Te(e,t,n={}){let{parseValues:r=!0,rhino:i,stringOnly:a=!1}=n;for(let n of z(e)){let e=m(n,`innerTree`),o=!1;if(`byName`in t){if(m(n,`paramName`)!==t.byName)continue;o=!0}let s=[];if(V(e,e=>{if(`byId`in t){if(e.id!==t.byId)return;o=!0}let n=B(e);P(n)||a&&n!==M.STRING||s.push(L(e,n,r,i))}),o)return s.length===0?void 0:s.length===1?s[0]:s}}var Ee=class{response;debug;constructor(e,t=!1){this.response=e,this.debug=t}getValues(e=!1,t={}){return Ce(this.response,e,t)}getValue(e,t){return Te(this.response,e,t)}getFileData(){return we(this.response)}async getAndDownloadFiles(e,t){let n=this.getFileData();await p(n,e,t)}};const H=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function U(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>H.test(e)&&Array.isArray(t))}function W(e,t,n){let r=Number(e.toFixed(t));return Math.abs(e-r)<n?r:e}function De(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 G(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}function K(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 q=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},J=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},Oe=e=>typeof e==`string`?e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e.startsWith(`"`)?e.slice(1):e:null,ke=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function Y(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:(r().warn(`Parsed value for input ${e} is not an object`),null)}catch(n){return r().warn(`Failed to parse object value "${t}" for input ${e}`,n),null}return null}}function Ae(n,r=1e-8){let i=n.paramType===`Integer`,a=G(n);if(U(n.default))return{default:n.default,stepSize:a??(i?1:.1)};if(typeof n.default==`string`&&n.default.trim()!==``&&q(n.default)===null)throw new t(`Invalid numeric default "${n.default}" for input "${n.name||`unknown`}"`,e.VALIDATION_ERROR,{context:{inputName:n.name,default:n.default}});let o=K(n.default,q,!0);if(i)return Array.isArray(o)?o=o.map(e=>typeof e==`number`?Math.round(e):e):typeof o==`number`&&(o=Math.round(o)),{default:o,stepSize:a??1};let s=Array.isArray(o)?o[0]:o,c;typeof s==`number`&&Number.isFinite(s)&&s!==0?c=s:typeof n.minimum==`number`&&Number.isFinite(n.minimum)&&n.minimum!==0?c=n.minimum:typeof n.maximum==`number`&&Number.isFinite(n.maximum)&&n.maximum!==0&&(c=n.maximum);let l=a??(c===void 0?.1:De(c,r)),u=0,d=String(l),f=d.toLowerCase().match(/e(-?\d+)/);if(u=f?Math.abs(Number(f[1])):d.split(`.`)[1]?.length??0,u===0&&typeof s==`number`&&s!==0&&Math.abs(s)<1){let e=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(e)&&e>0&&(u=e)}return u=Math.min(Math.max(u,0),12),Array.isArray(o)?o=o.map(e=>typeof e==`number`?W(e,u,r):e):typeof o==`number`&&(o=W(o,u,r)),{default:o,stepSize:l}}const je={types:[`Number`,`Integer`],parse(e,t){let{default:n,stepSize:r}=Ae(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:G(e)??(e.paramType===`Integer`?1:.1),default:n?[r]:r}}},Me={types:[`Boolean`],parse(n,r){if(U(n.default))return{...r,paramType:`Boolean`,default:n.default};let i=K(n.default,J,!1);if(i!=null&&typeof i!=`boolean`&&!Array.isArray(i))throw new t(`Invalid boolean default "${String(i)}" for input "${n.name||`unknown`}"`,e.VALIDATION_ERROR,{context:{inputName:n.name,default:n.default}});return{...r,paramType:`Boolean`,default:i}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Boolean`,default:n?[!1]:!1}}},Ne={types:[`Text`],parse(e,t){let n=K(e.default,Oe,!1);return{...t,paramType:`Text`,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Text`,default:n?[``]:``}}},Pe={types:[`ValueList`],parse(n,i,a){if(!n.values||typeof n.values!=`object`||Object.keys(n.values).length===0)throw t.missingValues(n.nickname||`unnamed`,`ValueList`);let o=n.default;if(n.default!==void 0&&n.default!==null){if(typeof n.default==`object`)throw new t(`ValueList input "${n.nickname||`unnamed`}" default is not a string-able value`,e.VALIDATION_ERROR,{context:{inputName:n.name,default:n.default}});let i=String(n.default).toLowerCase(),s=Object.keys(n.values).find(e=>e.toLowerCase()===i);if(s!==void 0)o=s;else{let t=`ValueList input "${n.nickname||`unnamed`}" default value "${n.default}" is not in available values`;r().warn(t),a?.({code:e.VALIDATION_ERROR,message:t})}}return{...i,paramType:`ValueList`,values:n.values,default:o}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}},X={types:[`Geometry`],parse(e,t){let n=K(e.default,Y(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}}},Z=new Map([je,Me,Ne,Pe,X,{types:[`File`],parse(e,t){let n=K(e.default,Y(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=K(e.default,ke,!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]))),Fe=X;function Ie(e){return m(e,`data`)}function Le(e){return m(e,`type`)}const Re=new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),ze=new Set([`System.Int32`,`System.Int64`]);function Be(e){if(typeof e.default!=`object`||e.default===null||Array.isArray(e.default))return{schema:e};if(!n(e.default,`innerTree`)){let t=`Input "${e.name??`unknown`}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return r().warn(`Unexpected structure in input.default:`,e.default),{schema:{...e,default:null},warning:{code:`MALFORMED_DEFAULT`,message:t}}}let t=m(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={},i=[];for(let[a,o]of Object.entries(t)){if(!Array.isArray(o)){let t=`Input "${e.name??`unknown`}" default had a non-array innerTree branch ("${a}"); the default was dropped.`;return r().warn(`Unexpected structure in input.default innerTree:`,e.default),{schema:{...e,default:null},warning:{code:`MALFORMED_DEFAULT`,message:t}}}let t=[];for(let e of o){let n=Ie(e),r=Le(e);if(r&&Re.has(r)){if(typeof n==`string`&&n.trim()===``)continue;let e=q(n);if(e===null){i.push(`"${String(n)}" (${r})`);continue}t.push(ze.has(r)?Math.round(e):e);continue}if(r===`System.Boolean`){let e=J(n);if(e===null){i.push(`"${String(n)}" (${r})`);continue}t.push(e);continue}if(typeof n==`string`&&r?.startsWith(`Rhino.Geometry`)){try{t.push(JSON.parse(n))}catch{t.push(n)}continue}t.push(n)}n[a]=t}let a;if(i.length>0){let t=`Input "${e.name??`unknown`}" default contained ${i.length} tree value(s) that could not be parsed and were dropped: ${i.join(`, `)}.`;r().warn(t),a={code:`MALFORMED_DEFAULT`,message:t}}return{schema:{...e,default:n},...a&&{warning:a}}}let i=[];for(let e of Object.values(t))Array.isArray(e)&&e.forEach(e=>{e&&typeof e==`object`&&n(e,`data`)&&i.push(Ie(e))});return i.length===0?{schema:{...e,default:void 0}}:i.length===1?{schema:{...e,default:i[0]}}:{schema:{...e,default:i}}}const Ve=new Map([...Z.keys()].map(e=>[e.toLowerCase(),e]));function He(e){return Ve.get(e?.toLowerCase())??e}function Ue(e){return We(e).input}function We(e){let n={description:e.description,name:e.name,nickname:e.nickname,treeAccess:e.treeAccess,groupName:e.groupName??void 0,id:e.id},i=He(e.paramType),a={...e,paramType:i},o;try{let{schema:t,warning:n}=Be(a);a=t,o=n&&{inputName:e.name||`unknown`,paramType:e.paramType,message:n.message,code:n.code}}catch(t){a={...a,default:null},o={inputName:e.name||`unknown`,paramType:e.paramType,message:`Input "${e.name??`unknown`}" default could not be normalized and was dropped: ${t instanceof Error?t.message:String(t)}`,code:`MALFORMED_DEFAULT`}}let s=Z.get(i),c=[],l=t=>c.push({inputName:e.name||`unknown`,paramType:e.paramType,message:t.message,code:t.code});try{if(!s)throw t.unknownParamType(i,e.name);let r=s.parse(a,n,l),u=o?[o,...c]:c;return{input:r,error:o,...u.length>0&&{errors:u}}}catch(l){if(l instanceof t){r().error(`Validation error for input ${e.name||`unknown`}:`,l.message);let t={inputName:e.name||`unknown`,paramType:e.paramType,message:l.message,code:l.code};return{input:(s??Fe).fallback(a,n),error:t,errors:[...o?[o]:[],...c,t]}}throw new t(l instanceof Error?l.message:String(l),`VALIDATION_ERROR`,{context:{paramName:e.name,paramType:i},originalError:l instanceof Error?l:Error(String(l))})}}function Ge(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=We(r);t.push(e),i&&n.push(...i)}return{inputs:t,parseErrors:n}}function Ke(e){let t=m(e,`stepSize`);return{id:m(e,`id`)??``,name:m(e,`name`)??``,nickname:m(e,`nickname`)??null,description:m(e,`description`)??``,paramType:m(e,`paramType`)??``,treeAccess:m(e,`treeAccess`)??!1,minimum:m(e,`minimum`)??null,maximum:m(e,`maximum`)??null,atLeast:m(e,`atLeast`)??1,atMost:m(e,`atMost`)??1,stepSize:typeof t==`number`&&Number.isFinite(t)?t:void 0,default:m(e,`default`),values:m(e,`values`),acceptedFormats:m(e,`acceptedFormats`),groupName:m(e,`groupName`)??null}}function qe(e){return{name:m(e,`name`)??``,nickname:m(e,`nickname`)??null,paramType:m(e,`paramType`)??``,id:m(e,`id`)??``}}async function Q(n,r){let i=x(n,[]),a={};if(i.algo&&(a.algo=i.algo),i.pointer&&(a.pointer=i.pointer),!a.algo&&!a.pointer)throw new t(`Definition must resolve to either a URL pointer or base64 algo`,e.INVALID_INPUT,{context:{definition:n}});let o=await f(`io`,a,_(r));if(!o||typeof o!=`object`)throw new t(`Invalid IO response structure`,e.INVALID_INPUT,{context:{response:o,definition:n}});let s=Je(m(o,`warnings`)),c=Je(m(o,`errors`)),l=m(o,`inputs`),u=m(o,`outputs`);return{inputs:Array.isArray(l)?l.map(Ke):[],outputs:Array.isArray(u)?u.map(qe):[],...s&&{loadWarnings:s},...c&&{loadErrors:c}}}function Je(e){if(!Array.isArray(e))return;let t=e.map(Ye).filter(e=>e!==void 0);return t.length>0?t:void 0}function Ye(e){if(e==null)return;let t;if(typeof e==`string`)t=e;else if(typeof e==`object`){let n=m(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 Xe(e,t){g(`fetchParsedDefinitionIO`,t.suppressBrowserWarning);let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await Q(e,t),{inputs:o,parseErrors:s}=Ge(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}function Ze(e){return(Array.isArray(e)?e:[e]).map(e=>({schemas:m(e,`schemas`),error:m(e,`error`)}))}const Qe=new Set([`options`,`defaultOptions`,`values`]),$e=e=>e>=`A`&&e<=`Z`;function et(e){if(e.length===0||!$e(e[0]))return e;let t=0;for(;t<e.length&&$e(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function tt(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=et(n);t[e]=Qe.has(e)?r:$(r)}return t}var nt=class n{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(e,t){let r=n.formatPathString(e);this.innerTree[r]||(this.innerTree[r]=[]);let i=t.map(e=>({data:n.serializeValue(e)}));return this.innerTree[r].push(...i),this}appendSingle(e,t){return this.append(e,[t])}fromDataTreeDefault(e){this.innerTree={};for(let[t,r]of Object.entries(e)){if(!Array.isArray(r))continue;let e=n.parsePathString(t);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 t of Object.values(this.innerTree))if(Array.isArray(t))for(let r of t)e.push(n.deserializeValue(r.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let t=n.formatPathString(e),r=this.innerTree[t];if(r)return r.map(e=>n.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=>n.hasValidValue(e.default)).map(e=>{let t=new n(e.nickname||`unnamed`),r=e.default;if(e.treeAccess&&U(r))t.fromDataTreeDefault(r),n.isNumericInput(e)&&t.applyNumericConstraints(e.minimum,e.maximum,e.nickname||`unnamed`);else{let i=Array.isArray(r)?r:[r],a=n.processValues(i,e);t.appendFlat(a)}return t.toComputeFormat()})}static fromInputParam(e){if(n.hasValidValue(e.default))return n.fromInputParams([e])[0]}static replaceTreeValue(e,t,r){let i=e.length>0&&e[0]instanceof n,a=n.buildFromValue(t,r);if(i){let n=e.slice(),r=n.findIndex(e=>e.getParamName()===t);return r===-1?n.push(a):n[r]=a,n}let o=e.slice(),s=a.toComputeFormat(),c=o.findIndex(e=>e.ParamName===t);return c===-1?o.push(s):o[c]=s,o}static buildFromValue(e,t){let r=new n(e);return U(t)?r.fromDataTreeDefault(t):r.appendFlat(t),r}static getTreeValue(e,t){let r=e.length>0&&e[0]instanceof n?n.readFromBuilders(e,t):n.readFromDataTrees(e,t);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,t){let r=e.find(e=>e.ParamName===t);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:n.deserializeValue(e.data)):a?.data===void 0?a===void 0?null:[a]:[n.deserializeValue(a.data)]}static parsePathString(n){let r=n.match(H);if(!r)throw new t(`Invalid Grasshopper tree path: "${n}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`,e.INVALID_INPUT,{context:{pathStr:n}});return r[1]?r[1].split(`;`).map(Number):[]}static formatPathString(e){return`{${e.join(`;`)}}`}applyNumericConstraints(e,t,r){for(let i of Object.values(this.innerTree))if(Array.isArray(i))for(let a of i){let i=n.deserializeValue(a.data);if(typeof i==`number`){let o=n.clampValue(i,e,t,r);a.data=n.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,t){return e.map(e=>n.isNumericInput(t)&&typeof e==`number`?n.clampValue(e,t.minimum,t.maximum,t.nickname||`unnamed`):e).filter(e=>e!=null)}static clampValue(e,t,n,i){let a=e;return t!=null&&a<t&&(r().warn(`${i}: ${e} below min ${t}, clamping`),a=t),n!=null&&a>n&&(r().warn(`${i}: ${e} above max ${n}, clamping`),a=n),a}};export{h as ComputeServerStats,pe as GrasshopperClient,Ee as GrasshopperResponseProcessor,D as SolveScheduler,nt as TreeBuilder,p as downloadFileData,d as extractFilesFromComputeResponse,Q as fetchDefinitionIO,Xe as fetchParsedDefinitionIO,E as hashDefinition,ue as hashSolveInput,l as isDefinitionRef,tt as normalizeUISchemaCasing,Ue as processInput,Ze as readSchemaResults,v as solveGrasshopperDefinition,S as stableStringify};
|
|
1
|
+
import{C as e,S as t,_ as n,b as r,c as i,f as a,g as o,l as s,m as c,o as l,p as u,r as d,s as f,t as p,u as ee,v as m}from"./core-BSKhoCtA.js";var h=class n{serverUrl;apiKey;disposed=!1;activeMonitors=new Set;activeTimeouts=new Set;static DEFAULT_TIMEOUT_MS=5e3;static LIFECYCLE_TIMEOUT_MS=6e4;static MIN_MONITOR_INTERVAL_MS=100;constructor(e,t){this.serverUrl=o(e),this.apiKey=t}buildHeaders(){let e={"Content-Type":`application/json`};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,t={},r=n.DEFAULT_TIMEOUT_MS){let i=new Headers(this.buildHeaders());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 r().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,i=t?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,a=t?n.LIFECYCLE_TIMEOUT_MS:n.DEFAULT_TIMEOUT_MS;try{let e=await this.fetchWithTimeout(i,{},a);if(!e.ok)return r().warn(`[ComputeServerStats] Failed to fetch active children:`,e.status),null;let t=(await e.text()).trim();return/^\d+$/.test(t)?parseInt(t,10):(r().warn(`[ComputeServerStats] Invalid active children response:`,t),null)}catch(e){return r().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 r().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 r().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 r().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 r().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 r().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 r().warn(`[ComputeServerStats] Error purging cache:`,e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return r().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 r().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 r().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 r().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 r().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 r().warn(`[ComputeServerStats] POST ${e} failed:`,t.status),null;let i=await t.text();try{return JSON.parse(i)}catch{return null}}catch(t){return r().warn(`[ComputeServerStats] Error on POST ${e}:`,t),null}}monitor(i,a=5e3){if(this.ensureNotDisposed(),!Number.isFinite(a)||a<n.MIN_MONITOR_INTERVAL_MS)throw new t(`monitor() intervalMs must be a finite number >= ${n.MIN_MONITOR_INTERVAL_MS}ms, got ${a}. Sub-${n.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`,e.INVALID_CONFIG,{context:{intervalMs:a}});let o=!0,s=null;r().info(`🔄 Starting server stats monitoring every ${a}ms`);let c=async()=>{if(s!==null&&(this.activeTimeouts.delete(s),s=null),o&&!this.disposed){try{let e=await this.getServerStats();if(!o||this.disposed)return;try{i(e)}catch(e){r().error(`[ComputeServerStats] Monitor callback threw:`,e)}}catch(e){!o||this.disposed?r().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,e):r().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,e)}o&&!this.disposed&&(s=setTimeout(()=>void c(),a),this.activeTimeouts.add(s))}},l=()=>{o=!1,s!==null&&(clearTimeout(s),this.activeTimeouts.delete(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();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new t(`ComputeServerStats has been disposed and cannot be used`,e.INVALID_STATE,{context:{disposed:this.disposed}})}};const te=new Set;function ne(){if(typeof window>`u`||globalThis.process?.versions?.node!=null)return!1;let e=globalThis.navigator,t=typeof e?.userAgent==`string`?e.userAgent:``;return!/jsdom/i.test(t)}function g(e,t){t||ne()&&!te.has(e)&&(te.add(e),r().warn(`Warning: ${e} is running on the client side. For better performance and security, consider running this on the server side.`))}const re={definition_not_cached:e.DEFINITION_NOT_CACHED};function _(e){return{...e,serverErrorCodes:{...re,...e.serverErrorCodes}}}function ie(n){return n instanceof t?n.code===e.DEFINITION_NOT_CACHED||n.message.includes(`Unable to load grasshopper definition`):!1}function ae(e,t){if(!t)return;let n=m(e,`values`);if(!Array.isArray(n)||n.length===0)return;let i=[];for(let e of n){let t=m(e,`innerTree`);(!t||Object.keys(t).length===0)&&i.push(m(e,`paramName`)??`<unnamed>`)}if(i.length===0)return;let a=i.length===n.length?`all`:`${i.length}/${n.length}`;r().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 v(e,t,n){g(`solveGrasshopperDefinition`,n.suppressBrowserWarning);let{response:r}=await b(x(await y(t),e),n);return r}async function oe(e,t,n){return g(`solveGrasshopperDefinitionWithCacheKey`,n.suppressBrowserWarning),b(x(await y(t),e),n)}async function se(e,t,n,r){g(`solveByCacheKey`,r.suppressBrowserWarning);let i={algo:null,pointer:t,values:e};try{return{...await b(i,r),missed:!1}}catch(t){if(!ie(t))throw t;return{...await b(x(await y(n),e),r),missed:!0}}}async function y(n){if(!l(n))return n;try{return await n.load()}catch(r){throw new t(`Failed to load definition bytes for ref '${n.key}'`,e.INVALID_INPUT,{context:{definitionKey:n.key},originalError:r instanceof Error?r:Error(String(r))})}}async function b(e,t){ce(e,t);let n=await f(`grasshopper`,e,_(t)),{pointer:r,algo:a,...o}=n,c=o,l=i(n);if(l!==void 0){let e=typeof a==`string`?a.length:0;s(c,Math.max(0,l-e))}return ae(c,t.debug),{response:c,cacheKey:typeof r==`string`?r:null}}function x(e,t){let n={algo:null,pointer:null,values:t};return e instanceof Uint8Array?n.algo=ee(e):/^https?:\/\//i.test(e)?n.pointer=e:n.algo=a(e)??u(e),n}function ce(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 S(e){let t=new WeakSet,n=e=>{if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`number`)return Number.isFinite(e)?String(e):`null`;if(typeof e==`string`||typeof e==`boolean`)return JSON.stringify(e);if(typeof e==`bigint`)return`${e}n`;if(e instanceof Uint8Array)return`{"__u8":${e.length},"hash":"${le(e)}"}`;if(Array.isArray(e)){if(t.has(e))return`"[Circular]"`;t.add(e);let r=[];for(let t=0;t<e.length;t++)r.push(n(e[t]));return t.delete(e),`[${r.join(`,`)}]`}if(typeof e==`object`){if(t.has(e))return`"[Circular]"`;t.add(e);let r;return r=typeof e.toJSON==`function`?n(e.toJSON()):e instanceof Map?`{"__map":[${[...e.entries()].map(([e,t])=>`[${n(e)},${n(t)}]`).sort().join(`,`)}]}`:e instanceof Set?`{"__set":[${[...e.values()].map(n).sort().join(`,`)}]}`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${n(e[t])}`).join(`,`)}}`,t.delete(e),r}return`null`};return n(e)}function C(e,t){let n=2166136261;for(let r=0;r<e;r++)n^=t(r),n=n+((n<<1)+(n<<4)+(n<<7)+(n<<8)+(n<<24))>>>0;return n.toString(16).padStart(8,`0`)}function w(e){return C(e.length,t=>e.charCodeAt(t))}function le(e){return C(e.length,t=>e[t])}function ue(e,t){return T(E(e),t)}function T(e,t){let n=S(t);return`${e}|t:${n.length}:${w(n)}`}function E(e){return l(e)?`r:${e.key}`:typeof e==`string`?`s:${e.length}:${w(e)}`:`u8:${e.length}:${le(e)}`}function de(e){return typeof e!=`string`||!/^https?:\/\//i.test(e)}function fe(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var D=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){r().error(`[SolveScheduler] subscriber threw:`,e)}}solve(n,r,i){if(this.disposed)return Promise.reject(new t(`SolveScheduler has been disposed and cannot be used`,e.INVALID_STATE));let a=E(n),o=T(a,r),s=++this.solveSeq,c={key:o,enqueuedAt:Date.now(),startedAt:null};if(i?.signal?.aborted)return Promise.reject(this.makeAbortError(c));if(this.cacheEnabled){let e=this.readCache(o);if(e){this.mode===`latest-wins`&&this.supersedeCurrent();let t={status:`success`,response:e,durationMs:0,fromCache:!0};return this.writeLastState(s,{result:e,durationMs:0}),this.runHook(this.onStart,c),this.runHook(this.onSettle,c,t),this.notify(),Promise.resolve(e)}}return new Promise((e,t)=>{let o={definition:n,dataTree:r,definitionHash:a,ctx:c,seq:s,resolve:e,reject:t,externalSignal:i?.signal,selvaevents:i?.selvaevents};o.externalSignal&&(o.queuedAbortHandler=()=>this.abortQueuedItem(o),o.externalSignal.addEventListener(`abort`,o.queuedAbortHandler,{once:!0})),this.enqueue(o)})}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(n){let r=new t(`Solve queue is full; request rejected (backpressure)`,e.QUEUE_FULL,{statusCode:503,context:{key:n.ctx.key,queueDepth:this.fifoQueue.length,maxQueueDepth:this.maxQueueDepth}});this.settleError(n,r)&&this.runHook(this.onSettle,n.ctx,{status:`error`,error:r,durationMs:0}),this.notify()}armQueueWaitTimer(n){if(this.queueWaitMs===void 0)return;let r=this.queueWaitMs;n.queueWaitTimer=setTimeout(()=>{if(n.settled)return;let i=this.fifoQueue.indexOf(n);i>=0&&this.fifoQueue.splice(i,1);let a=new t(`Solve waited longer than ${r}ms in queue; rejected (backpressure)`,e.QUEUE_TIMEOUT,{statusCode:503,context:{key:n.ctx.key,waitedMs:Date.now()-n.ctx.enqueuedAt,queueWaitMs:r}});this.settleError(n,a)&&this.runHook(this.onSettle,n.ctx,{status:`error`,error:a,durationMs:0}),this.notify()},r)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case`latest-wins`:this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break;case`queue`:case`parallel`:this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifoQueue.length>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifoQueue.push(e))}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||!de(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(n){let r=new t(`Superseded by newer solve`,e.SUPERSEDED,{context:{key:n.ctx.key,enqueuedAt:n.ctx.enqueuedAt}});this.settleError(n,r)&&this.runHook(this.onSuperseded,n.ctx)}makeAbortError(n){return new t(`Request aborted by caller`,e.ABORTED,{context:{key:n.key,enqueuedAt:n.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(n,r){return r.settled&&`error`in r.settled?r.settled.error:n instanceof t?n:this.isAbortLikeError(n)?this.makeAbortError(r.ctx):new t(n instanceof Error?n.message:String(n),e.UNKNOWN_ERROR,{originalError:n instanceof Error?n:Error(String(n))})}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 n=m(t,`errors`);if(!this.cacheErroredSolves&&Array.isArray(n)&&n.length>0)return;let r=i(t)??fe(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(e,...t){if(e)try{e(...t)}catch(e){r().error(`[SolveScheduler] hook threw:`,e)}}};function O(e){return l(e)?`ref:${e.key}`:typeof e==`string`&&e.length<200?e:`...content...`}function k(e){return Array.isArray(e)?e.map(e=>{let t=0,n=0,r=m(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:m(e,`paramName`)??`<unnamed>`,items:t,bytes:n}}):[]}var pe=class n{config;serverStats;disposed=!1;static CREATE_PROBE_TIMEOUT_MS=2e3;constructor(e){this.config=this.normalizeComputeConfig(e),this.serverStats=new h(this.config.serverUrl,this.config.apiKey)}static async create(r){let i=new n(r),a=Math.max(1,(r.retry?.attempts??2)+1),o=r.retry?.baseDelayMs??250,s=r.retry?.maxDelayMs??1e3,l,u=null,d=0;for(let e=0;e<a;e++){if(d=e+1,l=await i.serverStats.probeServer(n.CREATE_PROBE_TIMEOUT_MS),l.online)return i;if(u=c(l),u&&!u.retryable)break;if(e<a-1){let t=Math.min(o*2**e,s);await new Promise(e=>setTimeout(e,t))}}await i.dispose();let f=l?.status,p=u?`Rhino Compute server is not available. ${u.summary}`:`Rhino Compute server is not online`;throw new t(p,e.NETWORK_ERROR,{...f!==void 0&&{statusCode:f},context:{serverUrl:i.config.serverUrl,attempts:d,maxAttempts:a,...u&&{probeVerdict:u.verdict,probeRetryable:u.retryable},...f!==void 0&&{lastProbeStatus:f},...l?.error!==void 0&&{lastProbeError:l.error}}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),Xe(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),Q(e,this.config)}async solve(n,i,a){this.ensureNotDisposed();try{if(typeof n==`string`&&!n?.trim())throw new t(`Definition URL/content is required`,e.INVALID_INPUT,{context:{receivedUrl:n}});if(n instanceof Uint8Array&&n.length===0)throw new t(`Definition content is empty`,e.INVALID_INPUT);if(l(n)&&!n.key.trim())throw new t(`DefinitionRef key is empty`,e.INVALID_INPUT);let r=await v(i,n,{...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=m(r,`errors`);if(Array.isArray(o)&&o.length>0)throw new t(o.map(String).join(`; `)||`Computation failed`,e.COMPUTATION_ERROR,{context:{definition:O(n),inputSummary:k(i),errors:o,warnings:m(r,`warnings`),values:r.values}});return r}catch(a){throw this.config.debug&&r().error(`Compute failed:`,a),a instanceof t?a:new t(a instanceof Error?a.message:String(a),e.COMPUTATION_ERROR,{context:{definition:O(n),inputSummary:k(i)},originalError:a instanceof Error?a:Error(String(a))})}}createScheduler(e){return this.ensureNotDisposed(),new D((e,t,n)=>v(t,e,n),this.config,e,(e,t,n,r)=>n===null?oe(t,e,r).then(e=>({...e,missed:!1})):se(t,n,e,r))}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new t(`GrasshopperClient has been disposed and cannot be used`,e.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:o(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning}}};const A=new Map;function me(e,t){A.set(e,t)}me(`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}),me(`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(A.has(e))return A.get(e);for(let[t,n]of A)if(e.startsWith(t))return n}function ge(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function j(e,t){return{__decodeError:!0,type:e,raw:t}}function _e(e,t,n){let i=he(t),a=!1;if(i)try{let t=i(n,e);if(t!=null)return t}catch(e){r().warn(`Failed to decode Rhino type ${t}:`,e),a=!0}try{if(ge(e))return n.CommonObject.decode(e)}catch(n){return r().warn(`Failed to decode ${t} with CommonObject:`,n),j(t,e)}return a?j(t,e):e}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 M={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},ye=[`WebDisplay`],N=`FileData`;function P(e){return ye.some(t=>e.includes(t))}function be(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 xe(e,t,n){switch(t){case M.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case M.INT:return Number.parseInt(e,10);case M.DOUBLE:return Number.parseFloat(e);case M.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?_e(e,t,n):e}}const F=new WeakMap;function I(e){if(F.has(e))return F.get(e);let t=be(e.data);return F.set(e,t),t}function L(e,t,n,r){if(typeof e.data!=`string`)return e.data;let i=n?I(e):e.data;return n&&t.includes(N)?R(i)??i:xe(i,t,r)}const Se=e=>e===!0||typeof e==`string`&&e.trim().toLowerCase()===`true`;function R(e){if(!e||typeof e!=`object`)return null;let t=m(e,`fileName`),r=m(e,`fileType`),i=m(e,`subFolder`),a=m(e,`isBase64Encoded`);if(typeof t!=`string`||typeof r!=`string`||typeof i!=`string`||!n(e,`data`)||typeof a!=`boolean`&&typeof a!=`string`)return null;let o=m(e,`metadata`);return{fileName:t,fileType:r,data:m(e,`data`),isBase64Encoded:Se(a),subFolder:i,...o?{metadata:o}:{}}}function z(e){let t=m(e,`values`);return Array.isArray(t)?t:[]}function B(e){return typeof e.type==`string`?e.type:``}function V(e,t){if(e&&typeof e==`object`){for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)e&&typeof e==`object`&&t(e)}}function Ce(e,t=!1,n={}){let{parseValues:r=!0,rhino:i,stringOnly:a=!1}=n,o={},s=new Set;for(let n of z(e)){let e=m(n,`paramName`);V(m(n,`innerTree`),n=>{let c=B(n);if(P(c)||a&&c!==M.STRING)return;let l=t?n.id:e;if(!l)return;let u=L(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 we(e){let t=[];for(let n of z(e))V(m(n,`innerTree`),e=>{if(!B(e).includes(N))return;let n=R(I(e));n&&t.push(n)});return t}function Te(e,t,n={}){let{parseValues:r=!0,rhino:i,stringOnly:a=!1}=n;for(let n of z(e)){let e=m(n,`innerTree`),o=!1;if(`byName`in t){if(m(n,`paramName`)!==t.byName)continue;o=!0}let s=[];if(V(e,e=>{if(`byId`in t){if(e.id!==t.byId)return;o=!0}let n=B(e);P(n)||a&&n!==M.STRING||s.push(L(e,n,r,i))}),o)return s.length===0?void 0:s.length===1?s[0]:s}}var Ee=class{response;debug;constructor(e,t=!1){this.response=e,this.debug=t}getValues(e=!1,t={}){return Ce(this.response,e,t)}getValue(e,t){return Te(this.response,e,t)}getFileData(){return we(this.response)}async getAndDownloadFiles(e,t){let n=this.getFileData();await p(n,e,t)}};const H=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function U(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>H.test(e)&&Array.isArray(t))}function W(e,t,n){let r=Number(e.toFixed(t));return Math.abs(e-r)<n?r:e}function De(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 G(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}function K(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 q=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},J=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},Oe=e=>typeof e==`string`?e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e.startsWith(`"`)?e.slice(1):e:null,ke=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function Y(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:(r().warn(`Parsed value for input ${e} is not an object`),null)}catch(n){return r().warn(`Failed to parse object value "${t}" for input ${e}`,n),null}return null}}function Ae(n,r=1e-8){let i=n.paramType===`Integer`,a=G(n);if(U(n.default))return{default:n.default,stepSize:a??(i?1:.1)};if(typeof n.default==`string`&&n.default.trim()!==``&&q(n.default)===null)throw new t(`Invalid numeric default "${n.default}" for input "${n.name||`unknown`}"`,e.VALIDATION_ERROR,{context:{inputName:n.name,default:n.default}});let o=K(n.default,q,!0);if(i)return Array.isArray(o)?o=o.map(e=>typeof e==`number`?Math.round(e):e):typeof o==`number`&&(o=Math.round(o)),{default:o,stepSize:a??1};let s=Array.isArray(o)?o[0]:o,c;typeof s==`number`&&Number.isFinite(s)&&s!==0?c=s:typeof n.minimum==`number`&&Number.isFinite(n.minimum)&&n.minimum!==0?c=n.minimum:typeof n.maximum==`number`&&Number.isFinite(n.maximum)&&n.maximum!==0&&(c=n.maximum);let l=a??(c===void 0?.1:De(c,r)),u=0,d=String(l),f=d.toLowerCase().match(/e(-?\d+)/);if(u=f?Math.abs(Number(f[1])):d.split(`.`)[1]?.length??0,u===0&&typeof s==`number`&&s!==0&&Math.abs(s)<1){let e=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(e)&&e>0&&(u=e)}return u=Math.min(Math.max(u,0),12),Array.isArray(o)?o=o.map(e=>typeof e==`number`?W(e,u,r):e):typeof o==`number`&&(o=W(o,u,r)),{default:o,stepSize:l}}const je={types:[`Number`,`Integer`],parse(e,t){let{default:n,stepSize:r}=Ae(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:G(e)??(e.paramType===`Integer`?1:.1),default:n?[r]:r}}},Me={types:[`Boolean`],parse(n,r){if(U(n.default))return{...r,paramType:`Boolean`,default:n.default};let i=K(n.default,J,!1);if(i!=null&&typeof i!=`boolean`&&!Array.isArray(i))throw new t(`Invalid boolean default "${String(i)}" for input "${n.name||`unknown`}"`,e.VALIDATION_ERROR,{context:{inputName:n.name,default:n.default}});return{...r,paramType:`Boolean`,default:i}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Boolean`,default:n?[!1]:!1}}},Ne={types:[`Text`],parse(e,t){let n=K(e.default,Oe,!1);return{...t,paramType:`Text`,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Text`,default:n?[``]:``}}},Pe={types:[`ValueList`],parse(n,i,a){if(!n.values||typeof n.values!=`object`||Object.keys(n.values).length===0)throw t.missingValues(n.nickname||`unnamed`,`ValueList`);let o=n.default;if(n.default!==void 0&&n.default!==null){if(typeof n.default==`object`)throw new t(`ValueList input "${n.nickname||`unnamed`}" default is not a string-able value`,e.VALIDATION_ERROR,{context:{inputName:n.name,default:n.default}});let i=String(n.default).toLowerCase(),s=Object.keys(n.values).find(e=>e.toLowerCase()===i);if(s!==void 0)o=s;else{let t=`ValueList input "${n.nickname||`unnamed`}" default value "${n.default}" is not in available values`;r().warn(t),a?.({code:e.VALIDATION_ERROR,message:t})}}return{...i,paramType:`ValueList`,values:n.values,default:o}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}},X={types:[`Geometry`],parse(e,t){let n=K(e.default,Y(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}}},Z=new Map([je,Me,Ne,Pe,X,{types:[`File`],parse(e,t){let n=K(e.default,Y(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=K(e.default,ke,!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]))),Fe=X;function Ie(e){return m(e,`data`)}function Le(e){return m(e,`type`)}const Re=new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),ze=new Set([`System.Int32`,`System.Int64`]);function Be(e){if(typeof e.default!=`object`||e.default===null||Array.isArray(e.default))return{schema:e};if(!n(e.default,`innerTree`)){let t=`Input "${e.name??`unknown`}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return r().warn(`Unexpected structure in input.default:`,e.default),{schema:{...e,default:null},warning:{code:`MALFORMED_DEFAULT`,message:t}}}let t=m(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={},i=[];for(let[a,o]of Object.entries(t)){if(!Array.isArray(o)){let t=`Input "${e.name??`unknown`}" default had a non-array innerTree branch ("${a}"); the default was dropped.`;return r().warn(`Unexpected structure in input.default innerTree:`,e.default),{schema:{...e,default:null},warning:{code:`MALFORMED_DEFAULT`,message:t}}}let t=[];for(let e of o){let n=Ie(e),r=Le(e);if(r&&Re.has(r)){if(typeof n==`string`&&n.trim()===``)continue;let e=q(n);if(e===null){i.push(`"${String(n)}" (${r})`);continue}t.push(ze.has(r)?Math.round(e):e);continue}if(r===`System.Boolean`){let e=J(n);if(e===null){i.push(`"${String(n)}" (${r})`);continue}t.push(e);continue}if(typeof n==`string`&&r?.startsWith(`Rhino.Geometry`)){try{t.push(JSON.parse(n))}catch{t.push(n)}continue}t.push(n)}n[a]=t}let a;if(i.length>0){let t=`Input "${e.name??`unknown`}" default contained ${i.length} tree value(s) that could not be parsed and were dropped: ${i.join(`, `)}.`;r().warn(t),a={code:`MALFORMED_DEFAULT`,message:t}}return{schema:{...e,default:n},...a&&{warning:a}}}let i=[];for(let e of Object.values(t))Array.isArray(e)&&e.forEach(e=>{e&&typeof e==`object`&&n(e,`data`)&&i.push(Ie(e))});return i.length===0?{schema:{...e,default:void 0}}:i.length===1?{schema:{...e,default:i[0]}}:{schema:{...e,default:i}}}const Ve=new Map([...Z.keys()].map(e=>[e.toLowerCase(),e]));function He(e){return Ve.get(e?.toLowerCase())??e}function Ue(e){return We(e).input}function We(e){let n={description:e.description,name:e.name,nickname:e.nickname,treeAccess:e.treeAccess,groupName:e.groupName??void 0,id:e.id},i=He(e.paramType),a={...e,paramType:i},o;try{let{schema:t,warning:n}=Be(a);a=t,o=n&&{inputName:e.name||`unknown`,paramType:e.paramType,message:n.message,code:n.code}}catch(t){a={...a,default:null},o={inputName:e.name||`unknown`,paramType:e.paramType,message:`Input "${e.name??`unknown`}" default could not be normalized and was dropped: ${t instanceof Error?t.message:String(t)}`,code:`MALFORMED_DEFAULT`}}let s=Z.get(i),c=[],l=t=>c.push({inputName:e.name||`unknown`,paramType:e.paramType,message:t.message,code:t.code});try{if(!s)throw t.unknownParamType(i,e.name);let r=s.parse(a,n,l),u=o?[o,...c]:c;return{input:r,error:o,...u.length>0&&{errors:u}}}catch(l){if(l instanceof t){r().error(`Validation error for input ${e.name||`unknown`}:`,l.message);let t={inputName:e.name||`unknown`,paramType:e.paramType,message:l.message,code:l.code};return{input:(s??Fe).fallback(a,n),error:t,errors:[...o?[o]:[],...c,t]}}throw new t(l instanceof Error?l.message:String(l),`VALIDATION_ERROR`,{context:{paramName:e.name,paramType:i},originalError:l instanceof Error?l:Error(String(l))})}}function Ge(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=We(r);t.push(e),i&&n.push(...i)}return{inputs:t,parseErrors:n}}function Ke(e){let t=m(e,`stepSize`);return{id:m(e,`id`)??``,name:m(e,`name`)??``,nickname:m(e,`nickname`)??null,description:m(e,`description`)??``,paramType:m(e,`paramType`)??``,treeAccess:m(e,`treeAccess`)??!1,minimum:m(e,`minimum`)??null,maximum:m(e,`maximum`)??null,atLeast:m(e,`atLeast`)??1,atMost:m(e,`atMost`)??1,stepSize:typeof t==`number`&&Number.isFinite(t)?t:void 0,default:m(e,`default`),values:m(e,`values`),acceptedFormats:m(e,`acceptedFormats`),groupName:m(e,`groupName`)??null}}function qe(e){return{name:m(e,`name`)??``,nickname:m(e,`nickname`)??null,paramType:m(e,`paramType`)??``,id:m(e,`id`)??``}}async function Q(n,r){let i=x(n,[]),a={};if(i.algo&&(a.algo=i.algo),i.pointer&&(a.pointer=i.pointer),!a.algo&&!a.pointer)throw new t(`Definition must resolve to either a URL pointer or base64 algo`,e.INVALID_INPUT,{context:{definition:n}});let o=await f(`io`,a,_(r));if(!o||typeof o!=`object`)throw new t(`Invalid IO response structure`,e.INVALID_INPUT,{context:{response:o,definition:n}});let s=Je(m(o,`warnings`)),c=Je(m(o,`errors`)),l=m(o,`inputs`),u=m(o,`outputs`);return{inputs:Array.isArray(l)?l.map(Ke):[],outputs:Array.isArray(u)?u.map(qe):[],...s&&{loadWarnings:s},...c&&{loadErrors:c}}}function Je(e){if(!Array.isArray(e))return;let t=e.map(Ye).filter(e=>e!==void 0);return t.length>0?t:void 0}function Ye(e){if(e==null)return;let t;if(typeof e==`string`)t=e;else if(typeof e==`object`){let n=m(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 Xe(e,t){g(`fetchParsedDefinitionIO`,t.suppressBrowserWarning);let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await Q(e,t),{inputs:o,parseErrors:s}=Ge(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}function Ze(e){return(Array.isArray(e)?e:[e]).map(e=>({schemas:m(e,`schemas`),error:m(e,`error`)}))}const Qe=new Set([`options`,`defaultOptions`,`values`]),$e=e=>e>=`A`&&e<=`Z`;function et(e){if(e.length===0||!$e(e[0]))return e;let t=0;for(;t<e.length&&$e(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function tt(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=et(n);t[e]=Qe.has(e)?r:$(r)}return t}var nt=class n{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(e,t){let r=n.formatPathString(e);this.innerTree[r]||(this.innerTree[r]=[]);let i=t.map(e=>({data:n.serializeValue(e)}));return this.innerTree[r].push(...i),this}appendSingle(e,t){return this.append(e,[t])}fromDataTreeDefault(e){this.innerTree={};for(let[t,r]of Object.entries(e)){if(!Array.isArray(r))continue;let e=n.parsePathString(t);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 t of Object.values(this.innerTree))if(Array.isArray(t))for(let r of t)e.push(n.deserializeValue(r.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let t=n.formatPathString(e),r=this.innerTree[t];if(r)return r.map(e=>n.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=>n.hasValidValue(e.default)).map(e=>{let t=new n(e.nickname||`unnamed`),r=e.default;if(e.treeAccess&&U(r))t.fromDataTreeDefault(r),n.isNumericInput(e)&&t.applyNumericConstraints(e.minimum,e.maximum,e.nickname||`unnamed`);else{let i=Array.isArray(r)?r:[r],a=n.processValues(i,e);t.appendFlat(a)}return t.toComputeFormat()})}static fromInputParam(e){if(n.hasValidValue(e.default))return n.fromInputParams([e])[0]}static replaceTreeValue(e,t,r){let i=e.length>0&&e[0]instanceof n,a=n.buildFromValue(t,r);if(i){let n=e.slice(),r=n.findIndex(e=>e.getParamName()===t);return r===-1?n.push(a):n[r]=a,n}let o=e.slice(),s=a.toComputeFormat(),c=o.findIndex(e=>e.ParamName===t);return c===-1?o.push(s):o[c]=s,o}static buildFromValue(e,t){let r=new n(e);return U(t)?r.fromDataTreeDefault(t):r.appendFlat(t),r}static getTreeValue(e,t){let r=e.length>0&&e[0]instanceof n?n.readFromBuilders(e,t):n.readFromDataTrees(e,t);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,t){let r=e.find(e=>e.ParamName===t);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:n.deserializeValue(e.data)):a?.data===void 0?a===void 0?null:[a]:[n.deserializeValue(a.data)]}static parsePathString(n){let r=n.match(H);if(!r)throw new t(`Invalid Grasshopper tree path: "${n}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`,e.INVALID_INPUT,{context:{pathStr:n}});return r[1]?r[1].split(`;`).map(Number):[]}static formatPathString(e){return`{${e.join(`;`)}}`}applyNumericConstraints(e,t,r){for(let i of Object.values(this.innerTree))if(Array.isArray(i))for(let a of i){let i=n.deserializeValue(a.data);if(typeof i==`number`){let o=n.clampValue(i,e,t,r);a.data=n.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,t){return e.map(e=>n.isNumericInput(t)&&typeof e==`number`?n.clampValue(e,t.minimum,t.maximum,t.nickname||`unnamed`):e).filter(e=>e!=null)}static clampValue(e,t,n,i){let a=e;return t!=null&&a<t&&(r().warn(`${i}: ${e} below min ${t}, clamping`),a=t),n!=null&&a>n&&(r().warn(`${i}: ${e} above max ${n}, clamping`),a=n),a}};export{h as ComputeServerStats,pe as GrasshopperClient,Ee as GrasshopperResponseProcessor,D as SolveScheduler,nt as TreeBuilder,p as downloadFileData,d as extractFilesFromComputeResponse,Q as fetchDefinitionIO,Xe as fetchParsedDefinitionIO,E as hashDefinition,ue as hashSolveInput,l as isDefinitionRef,tt as normalizeUISchemaCasing,Ue as processInput,Ze as readSchemaResults,v as solveGrasshopperDefinition,S as stableStringify};
|
|
2
2
|
//# sourceMappingURL=grasshopper.js.map
|