@selvajs/compute 5.0.0-beta.4 → 5.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as ServerErrorCodeMap, C as enableDebugLogging, D as ComputeAuth, E as fetchCompute, M as ComputeError, N as ErrorCode, O as ComputeConfig, P as ErrorCodes, S as Logger, T as setLogger, _ as SolveDefinition, a as extractFilesFromComputeResponse, b as hasField, c as FileData, d as ProbeVerdict, f as classifyProbeFailure, g as DefinitionRef, h as validateServerUrl, i as downloadFileDataByRoot, j as ServerTiming, k as RetryPolicy, l as ProcessedFile, m as ValidateServerUrlOptions, n as subFolderSegments, o as DownloadOptions, p as DEFAULT_BLOCKED_HOST, r as downloadFileData, s as FileBaseInfo, t as groupFilesByRoot, u as ProbeFailure, v as isDefinitionRef, w as getLogger, x as readField, y as decodeBase64ToBinary } from "./index-cMvSohkf.js";
1
+ import { A as ServerErrorCodeMap, C as enableDebugLogging, D as ComputeAuth, E as fetchCompute, M as ComputeError, N as ErrorCode, O as ComputeConfig, P as ErrorCodes, S as Logger, T as setLogger, _ as SolveDefinition, a as extractFilesFromComputeResponse, b as hasField, c as FileData, d as ProbeVerdict, f as classifyProbeFailure, g as DefinitionRef, h as validateServerUrl, i as downloadFileDataByRoot, j as ServerTiming, k as RetryPolicy, l as ProcessedFile, m as ValidateServerUrlOptions, n as subFolderSegments, o as DownloadOptions, p as DEFAULT_BLOCKED_HOST, r as downloadFileData, s as FileBaseInfo, t as groupFilesByRoot, u as ProbeFailure, v as isDefinitionRef, w as getLogger, x as readField, y as decodeBase64ToBinary } from "./index-DdWRS7rh.js";
2
2
  export { type ComputeAuth, type ComputeConfig, ComputeError, DEFAULT_BLOCKED_HOST, type DefinitionRef, type DownloadOptions, type ErrorCode, ErrorCodes, type FileBaseInfo, type FileData, type Logger, type ProbeFailure, type ProbeVerdict, type ProcessedFile, type RetryPolicy, type ServerErrorCodeMap, type ServerTiming, type SolveDefinition, type ValidateServerUrlOptions, classifyProbeFailure, decodeBase64ToBinary, downloadFileData, downloadFileDataByRoot, enableDebugLogging, extractFilesFromComputeResponse, fetchCompute, getLogger, groupFilesByRoot, hasField, isDefinitionRef, readField, setLogger, subFolderSegments, validateServerUrl };
package/dist/core.js CHANGED
@@ -1 +1 @@
1
- import{C as e,D as t,E as n,O as r,S as i,T as a,a as o,b as s,g as c,l,n as u,o as d,r as f,s as p,t as m,u as h,w as g,x as _}from"./core-CFlbOj2M.js";export{t as ComputeError,s as DEFAULT_BLOCKED_HOST,r as ErrorCodes,h as classifyProbeFailure,c as decodeBase64ToBinary,m as downloadFileData,u as downloadFileDataByRoot,g as enableDebugLogging,f as extractFilesFromComputeResponse,l as fetchCompute,a as getLogger,o as groupFilesByRoot,i as hasField,p as isDefinitionRef,e as readField,n as setLogger,d as subFolderSegments,_ as validateServerUrl};
1
+ import{C as e,D as t,E as n,O as r,S as i,T as a,a as o,b as s,g as c,l,n as u,o as d,r as f,s as p,t as m,u as h,w as g,x as _}from"./core-BC8t6doi.js";export{t as ComputeError,s as DEFAULT_BLOCKED_HOST,r as ErrorCodes,h as classifyProbeFailure,c as decodeBase64ToBinary,m as downloadFileData,u as downloadFileDataByRoot,g as enableDebugLogging,f as extractFilesFromComputeResponse,l as fetchCompute,a as getLogger,o as groupFilesByRoot,i as hasField,p as isDefinitionRef,e as readField,n as setLogger,d as subFolderSegments,_ as validateServerUrl};
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./core-UUSszGkB.cjs");var t=class t{serverUrl;headers;disposed=!1;activeMonitors=new Set;static DEFAULT_TIMEOUT_MS=5e3;static LIFECYCLE_TIMEOUT_MS=6e4;static MIN_MONITOR_INTERVAL_MS=100;static MAX_BODY_BYTES=1<<20;constructor(t,n){this.serverUrl=e.x(t),this.headers={...e.y(typeof n==`string`?{apiKey:n}:n??{}),"Content-Type":`application/json`}}fetchWithTimeout(e,n={},r=t.DEFAULT_TIMEOUT_MS){let i={...n,headers:this.headers,redirect:`manual`};return r>0&&!i.signal&&(i.signal=AbortSignal.timeout(r)),fetch(e,i)}async getText(n,r={},i=t.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let a=`${r.method??`GET`} ${n}`;try{let o=await this.fetchWithTimeout(`${this.serverUrl}${n}`,r,i);if(!o.ok)return e.T().warn(`[ComputeServerStats] ${a} failed:`,o.status),await o.body?.cancel().catch(()=>{}),null;let{text:s,truncated:c}=await e.m(o,t.MAX_BODY_BYTES);return c?(e.T().warn(`[ComputeServerStats] ${a} answered with an oversized body`),null):s}catch(t){return e.T().warn(`[ComputeServerStats] ${a} errored:`,t),null}}async isServerOnline(e=t.DEFAULT_TIMEOUT_MS){return(await this.probeServer(e)).online}async probeServer(n=t.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let r=`${this.serverUrl}/`;try{let t=await this.fetchWithTimeout(r,{method:`GET`},n);return await t.body?.cancel().catch(()=>{}),{online:t.ok||e.d(t),status:t.status}}catch(t){return e.T().debug(`[ComputeServerStats] Fetch error:`,t),{online:!1,error:t instanceof Error?`${t.name}: ${t.message}`:String(t)}}}async getActiveChildren(n={}){let{initialize:r=!0}=n,i=r?await this.getText(`/activechildren`,{},t.LIFECYCLE_TIMEOUT_MS):await this.getText(`/activechildren?initialize=false`);if(i===null)return null;let a=i.trim();return/^\d+$/.test(a)?parseInt(a,10):(e.T().warn(`[ComputeServerStats] /activechildren answered with a non-numeric body`),null)}async getVersion(){let e=await this.getText(`/version`);if(e===null)return null;let t=n(e);return t==null?{rhino:e,compute:``,git_sha:null}:{rhino:t.rhino??``,compute:t.compute??``,git_sha:t.git_sha??null}}async getInstalledPlugins(e=`gh`){let t=await this.getText(`/plugins/${e}/installed`),r=t===null?void 0:n(t);return r&&typeof r==`object`?r:null}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[e,t]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...e&&{version:e},...t!==null&&{activeChildren:t}}}async purgeCache(){let e=await this.getText(`/cache/purge`,{method:`POST`}),t=(e===null?void 0:n(e))?.purged;return typeof t==`number`?t:null}async purgeAllChildren(){this.ensureNotDisposed();let t=await this.getActiveChildren({initialize:!1});if(t===null)return e.T().warn(`[ComputeServerStats] purgeAllChildren: could not read child count`),null;if(t===0)return{totalPurged:0,calls:0,children:0,confident:!0};let n=t*2,r=0;for(let e=0;e<n;e++){let e=await this.purgeCache();e!==null&&(r+=e)}return{totalPurged:r,calls:n,children:t,confident:t===1}}async getServerTime(){let e=await this.getText(`/servertime`);if(e===null)return null;let t=new Date(e.trim().replace(/^"|"$/g,``));return isNaN(t.getTime())?null:t}async getIdleSpan(){let e=await this.getText(`/idlespan`);if(e===null)return null;let t=parseFloat(e.trim());return isNaN(t)?null:t}async launchChildren(){return this.postJson(`/launch-children`)}async launchChild(e){let t=e===void 0?`/launch-child`:`/launch-child?port=${e}`;return this.postJson(t)}async shutdownChildren(e){let t=e===void 0?`/shutdown-children`:`/shutdown-children?port=${e}`;return this.postJson(t)}async recycleChildren(e){let t=e===void 0?`/recycle-children`:`/recycle-children?port=${e}`;return this.postJson(t)}async postJson(e){let r=await this.getText(e,{method:`POST`},t.LIFECYCLE_TIMEOUT_MS);return r===null?null:n(r)??null}monitor(n,r=5e3){if(this.ensureNotDisposed(),!Number.isFinite(r)||r<t.MIN_MONITOR_INTERVAL_MS)throw new e.D(`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.`,e.O.INVALID_CONFIG,{context:{intervalMs:r}});let i=!0,a=null;e.T().info(`🔄 Starting server stats monitoring every ${r}ms`);let o=async()=>{if(a=null,i&&!this.disposed){try{let t=await this.getServerStats();if(!i||this.disposed)return;try{n(t)}catch(t){e.T().error(`[ComputeServerStats] Monitor callback threw:`,t)}}catch(t){!i||this.disposed?e.T().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,t):e.T().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,t)}i&&!this.disposed&&(a=setTimeout(()=>void o(),r))}},s=()=>{i=!1,a!==null&&(clearTimeout(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()}}ensureNotDisposed(){if(this.disposed)throw new e.D(`ComputeServerStats has been disposed and cannot be used`,e.O.INVALID_STATE)}};function n(e){try{return JSON.parse(e)}catch{return}}const r=new Set;function i(){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 a(t,n){n||i()&&!r.has(t)&&(r.add(t),e.T().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`))}const o={definition_not_cached:e.O.DEFINITION_NOT_CACHED};function s(e){return{...e,serverErrorCodes:{...o,...e.serverErrorCodes}}}function c(t){return t instanceof e.D?t.code===e.O.DEFINITION_NOT_CACHED||t.message.includes(`Unable to load grasshopper definition`):!1}function l(t,n){if(!n)return;let r=e.C(t,`values`);if(!Array.isArray(r)||r.length===0)return;let i=[];for(let t of r){let n=e.C(t,`innerTree`);(!n||Object.keys(n).length===0)&&i.push(e.C(t,`paramName`)??`<unnamed>`)}if(i.length===0)return;let a=i.length===r.length?`all`:`${i.length}/${r.length}`;e.T().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 u(e,t,n){return a(`solveGrasshopperDefinition`,n.suppressBrowserWarning),(await f(e,t,n)).response}async function d(e,t,n,r){if(a(`solveWithServerCacheKey`,r.suppressBrowserWarning),t!==null)try{return{...await m({algo:null,pointer:t,values:e},r),missed:!1}}catch(e){if(!c(e))throw e}return{...await f(e,n,r),missed:!0}}async function f(e,t,n){return m(h(await p(t),e),n)}async function p(t){if(!e.s(t))return t;try{return await t.load()}catch(n){throw new e.D(`Failed to load definition bytes for ref '${t.key}'`,e.O.INVALID_INPUT,{context:{definitionKey:t.key},originalError:n})}}async function m(t,n){e.x(n.serverUrl),ee(t,n);let{maxResponseBytes:r}=n,i=await e.l(`grasshopper`,t,s({...n,maxResponseBytes:r!==void 0&&t.algo?r+t.algo.length:r})),{pointer:a,algo:o,...c}=i,u=c,d=e.f(i);if(d!==void 0){let t=typeof o==`string`?o.length:0;e.p(u,Math.max(0,d-t))}return l(u,n.debug),{response:u,cacheKey:typeof a==`string`?a:null}}function h(t,n){let r={algo:null,pointer:null,values:n};return t instanceof Uint8Array?r.algo=e.h(t):e.c(t)?r.pointer=t:r.algo=e._(t)??e.v(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),t.selvaevents!=null&&(e.selvaevents=t.selvaevents)}function g(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}const _=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function v(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>_.test(e)&&Array.isArray(t))}function y(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 b=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=e.trim();if(t===``||/^[+-]?0[xbo]/i.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}return null},x=e=>{if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}return null},te=e=>typeof e==`string`?e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e.startsWith(`"`)?e.slice(1):e:null,ne=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function S(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.T().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return e.T().warn(`Failed to parse object value "${n}" for input ${t}`,r),null}return null}}const re=new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),ie=new Set([`System.Int32`,`System.Int64`]);function ae(t,n){return e.T().warn(n),{schema:{...t,default:null},warning:{code:e.O.MALFORMED_DEFAULT,message:n}}}function oe(t,n){if(typeof t.default!=`object`||t.default===null||Array.isArray(t.default)||v(t.default))return{schema:t};if(!e.S(t.default,`innerTree`))return ae(t,`Input "${n}" default had an unrecognized shape (no innerTree key); the default was dropped.`);let r=e.C(t.default,`innerTree`)??{};if(Object.keys(r).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let i={},a=[];for(let[o,s]of Object.entries(r)){if(!Array.isArray(s))return ae(t,`Input "${n}" default had a non-array innerTree branch ("${o}"); the default was dropped.`);let r=[];for(let t of s){let n=e.C(t,`data`),i=e.C(t,`type`);if(i&&re.has(i)){if(typeof n==`string`&&n.trim()===``)continue;let e=b(n);if(e===null){a.push(`"${String(n)}" (${i})`);continue}r.push(ie.has(i)?Math.round(e):e);continue}if(i===`System.Boolean`){let e=x(n);if(e===null){a.push(`"${String(n)}" (${i})`);continue}r.push(e);continue}if(typeof n==`string`&&i?.startsWith(`Rhino.Geometry`)){try{r.push(JSON.parse(n))}catch{r.push(n)}continue}r.push(n)}g(i,o,r)}if(a.length>0){let r=`Input "${n}" default contained ${a.length} tree value(s) that could not be parsed and were dropped: ${a.join(`, `)}.`;return e.T().warn(r),{schema:{...t,default:i},warning:{code:e.O.MALFORMED_DEFAULT,message:r}}}return{schema:{...t,default:i}}}let i=[];for(let t of Object.values(r))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&e.S(n,`data`)&&i.push(e.C(n,`data`));return{schema:{...t,default:i.length>1?i:i[0]}}}function se(e,t){let n=Number(e.toFixed(t));return Math.abs(e-n)<1e-8?n:e}function C(e){if(!Number.isFinite(e))return 0;let[t,n]=String(Math.abs(e)).split(`e`),r=n===void 0?Math.abs(e).toFixed(12).replace(/0+$/,``).split(`.`)[1]?.length??0:(t.split(`.`)[1]?.length??0)-Number(n);return Math.min(Math.max(r,0),12)}function ce(e){if(!Number.isFinite(e)||e===0)return .1;let t=C(e);return t===0?Math.abs(e)>=1?1:.1:Number((10**-t).toFixed(t))}function w(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}const T=(e,t)=>(e.atMost??1)>1?[t]:t,E=e=>w(e)??(e.paramType===`Integer`?1:.1),D=(e,t)=>Array.isArray(e)?e.map(e=>typeof e==`number`?t(e):e):typeof e==`number`?t(e):e;function le(t){if(v(t.default))return{default:t.default,stepSize:E(t)};if(typeof t.default==`string`&&t.default.trim()!==``&&b(t.default)===null)throw new e.D(`Invalid numeric default "${t.default}" for input "${t.name||`unknown`}"`,e.O.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=y(t.default,b,!0);if(t.paramType===`Integer`)return{default:D(n,Math.round),stepSize:E(t)};let r=Array.isArray(n)?n[0]:n,i=[r,t.minimum,t.maximum].find(e=>typeof e==`number`&&Number.isFinite(e)&&e!==0),a=w(t)??(i===void 0?.1:ce(i)),o=C(a);if(o===0&&typeof r==`number`&&r!==0&&Math.abs(r)<1){let e=Math.ceil(-Math.log10(Math.abs(r)));Number.isFinite(e)&&e>0&&(o=e)}return o=Math.min(Math.max(o,0),12),{default:D(n,e=>se(e,o)),stepSize:a}}const O={parse(e,t){let{default:n,stepSize:r}=le(e);return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:r,default:n}},fallback(e,t){let n=typeof e.minimum==`number`&&Number.isFinite(e.minimum)&&e.minimum>0?e.minimum:0;return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:E(e),default:T(e,n)}}},ue={parse(t,n){if(v(t.default))return{...n,paramType:`Boolean`,default:t.default};let r=y(t.default,x,!1);if(r!=null&&typeof r!=`boolean`&&!Array.isArray(r))throw new e.D(`Invalid boolean default "${String(r)}" for input "${t.name||`unknown`}"`,e.O.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});return{...n,paramType:`Boolean`,default:r}},fallback(e,t){return{...t,paramType:`Boolean`,default:T(e,!1)}}},de={parse(e,t){let n=y(e.default,te,!1);return{...t,paramType:`Text`,default:n}}},fe={parse(t,n,r){if(!t.values||typeof t.values!=`object`||Object.keys(t.values).length===0){let n=t.nickname||`unnamed`;throw new e.D(`Input "${n}" has no values defined (expected ValueList)`,e.O.INVALID_INPUT,{context:{inputName:n,expectedType:`ValueList`}})}let i=t.default;if(t.default!==void 0&&t.default!==null){if(typeof t.default==`object`)throw new e.D(`ValueList input "${t.nickname||`unnamed`}" default is not a string-able value`,e.O.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=String(t.default).toLowerCase(),a=Object.keys(t.values).find(e=>e.toLowerCase()===n);if(a!==void 0)i=a;else{let n=`ValueList input "${t.nickname||`unnamed`}" default value "${t.default}" is not in available values`;e.T().warn(n),r?.({code:e.O.VALIDATION_ERROR,message:n})}}return{...n,paramType:`ValueList`,values:t.values,default:i}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}};function k(e,t){return{...t,paramType:`Geometry`,default:T(e,null)}}const A=new Map([[`Number`,O],[`Integer`,O],[`Boolean`,ue],[`Text`,de],[`ValueList`,fe],[`Geometry`,{parse(e,t){let n=y(e.default,S(e.nickname||`unnamed`),!0);return{...t,paramType:`Geometry`,default:n}},fallback:k}],[`File`,{parse(e,t){let n=y(e.default,S(e.nickname||`unnamed`),!0);return{...t,paramType:`File`,acceptedFormats:e.acceptedFormats,default:n}}}],[`Color`,{parse(e,t){let n=y(e.default,ne,!1);return{...t,paramType:`Color`,default:n}}}]]),pe=k,me=new Map([...A.keys()].map(e=>[e.toLowerCase(),e]));function he(e){return me.get(e?.toLowerCase())??e}function ge(e){return j(e).input}function j(t){let n=t.name||`unknown`,r=[],i=({code:e,message:i})=>{r.push({inputName:n,paramType:t.paramType,message:i,code:e})},a={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??void 0,id:t.id},o=he(t.paramType),s={...t,paramType:o};try{let{schema:e,warning:t}=oe(s,n);s=e,t&&i(t)}catch(t){s={...s,default:null},i({code:e.O.MALFORMED_DEFAULT,message:`Input "${n}" default could not be normalized and was dropped: ${t instanceof Error?t.message:String(t)}`})}let c=A.get(o);try{if(!c)throw new e.D(`Unknown paramType: ${o}`,e.O.VALIDATION_ERROR,{context:{receivedParamType:o,paramName:t.name}});return{input:c.parse(s,a,i),errors:r}}catch(l){if(!(l instanceof e.D))throw new e.D(l instanceof Error?l.message:String(l),e.O.VALIDATION_ERROR,{context:{paramName:t.name,paramType:o},originalError:l});return e.T().error(`Validation error for input ${n}:`,l.message),i(l),{input:(c?.fallback??pe)(s,a),errors:r}}}function _e(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=j(r);t.push(e),n.push(...i)}return{inputs:t,parseErrors:n}}function ve(t){let n=e.C(t,`stepSize`);return{id:e.C(t,`id`)??``,name:e.C(t,`name`)??``,nickname:e.C(t,`nickname`)??null,description:e.C(t,`description`)??``,paramType:e.C(t,`paramType`)??``,treeAccess:e.C(t,`treeAccess`)??!1,minimum:e.C(t,`minimum`)??null,maximum:e.C(t,`maximum`)??null,atLeast:e.C(t,`atLeast`)??1,atMost:e.C(t,`atMost`)??1,stepSize:typeof n==`number`&&Number.isFinite(n)?n:void 0,default:e.C(t,`default`),values:e.C(t,`values`),acceptedFormats:e.C(t,`acceptedFormats`),groupName:e.C(t,`groupName`)??null}}function ye(t){return{name:e.C(t,`name`)??``,nickname:e.C(t,`nickname`)??null,paramType:e.C(t,`paramType`)??``,id:e.C(t,`id`)??``}}async function M(t,n){a(`fetchDefinitionIO`,n.suppressBrowserWarning),e.x(n.serverUrl);let{algo:r,pointer:i}=h(t,[]);if(!r&&!i)throw new e.D(`Definition must resolve to either a URL pointer or base64 algo`,e.O.INVALID_INPUT);let o=await e.l(`io`,r?{algo:r}:{pointer:i},s(n));if(!o||typeof o!=`object`)throw new e.D(`Invalid IO response structure`,e.O.INVALID_INPUT,{context:{response:o}});let c=N(e.C(o,`warnings`)),l=N(e.C(o,`errors`)),u=e.C(o,`inputs`),d=e.C(o,`outputs`);return{inputs:Array.isArray(u)?u.map(ve):[],outputs:Array.isArray(d)?d.map(ye):[],...c&&{loadWarnings:c},...l&&{loadErrors:l}}}function N(e){if(!Array.isArray(e))return;let t=e.map(be).filter(e=>e!==void 0);return t.length>0?t:void 0}function be(t){if(t==null)return;let n;if(typeof t==`string`)n=t;else if(typeof t==`object`){let r=e.C(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 P(e,t){let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await M(e,t),{inputs:o,parseErrors:s}=_e(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}const F=globalThis.process?.getBuiltinModule?.(`node:crypto`);function I(e){if(F){let t=F.createHash(`sha256`);return typeof e==`string`?t.update(e,`utf16le`):t.update(e),t.digest(`hex`)}return Se(e)}const xe=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Se(e){let t=new Ce;return typeof e==`string`?t.updateString(e):t.update(e),t.digestHex()}var Ce=class{h=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);w=new Int32Array(64);pending=new Uint8Array(64);pendingLength=0;totalBytes=0;update(e){this.totalBytes+=e.length;let t=0;if(this.pendingLength>0){let n=Math.min(64-this.pendingLength,e.length);if(this.pending.set(e.subarray(0,n),this.pendingLength),this.pendingLength+=n,t=n,this.pendingLength<64)return;this.compressBytes(this.pending,0),this.pendingLength=0}for(;t+64<=e.length;t+=64)this.compressBytes(e,t);this.pending.set(e.subarray(t),0),this.pendingLength=e.length-t}updateString(e){let t=this.w,n=e.length-e.length%32;for(let r=0;r<n;r+=32){for(let n=0;n<16;n++){let i=e.charCodeAt(r+2*n),a=e.charCodeAt(r+2*n+1);t[n]=(i&255)<<24|i>>>8<<16|(a&255)<<8|a>>>8}this.compress()}this.totalBytes+=n*2;let r=new Uint8Array((e.length-n)*2);for(let t=n,i=0;t<e.length;t++){let n=e.charCodeAt(t);r[i++]=n&255,r[i++]=n>>>8}this.update(r)}digestHex(){let e=this.totalBytes*8,t=new Uint8Array(this.pendingLength<56?64:128);t.set(this.pending.subarray(0,this.pendingLength)),t[this.pendingLength]=128;let n=new DataView(t.buffer);n.setUint32(t.length-8,Math.floor(e/4294967296)),n.setUint32(t.length-4,e>>>0);for(let e=0;e<t.length;e+=64)this.compressBytes(t,e);let r=``;for(let e of this.h)r+=(e>>>0).toString(16).padStart(8,`0`);return r}compressBytes(e,t){let n=this.w;for(let r=0;r<16;r++){let i=t+r*4;n[r]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}this.compress()}compress(){let e=this.w;for(let t=16;t<64;t++){let n=e[t-15],r=e[t-2],i=(n>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,a=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10;e[t]=e[t-16]+i+e[t-7]+a|0}let t=this.h,n=t[0],r=t[1],i=t[2],a=t[3],o=t[4],s=t[5],c=t[6],l=t[7];for(let t=0;t<64;t++){let u=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),d=o&s^~o&c,f=l+u+d+xe[t]+e[t]|0,p=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&r^n&i^r&i)|0;l=c,c=s,s=o,o=a+f|0,a=i,i=r,r=n,n=f+p|0}t[0]=t[0]+n|0,t[1]=t[1]+r|0,t[2]=t[2]+i|0,t[3]=t[3]+a|0,t[4]=t[4]+o|0,t[5]=t[5]+s|0,t[6]=t[6]+c|0,t[7]=t[7]+l|0}};function L(e){let t=new WeakSet,n=e=>{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(typeof e!=`object`)return`undefined`;if(e instanceof Uint8Array)return`{u8:${I(e)}}`;if(t.has(e))return`[Circular]`;t.add(e);let r;if(Array.isArray(e)){let t=[];for(let r=0;r<e.length;r++)t.push(n(e[r]));r=`[${t.join(`,`)}]`}else 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(`,`)}}`;return t.delete(e),r};return n(e)}function we(e,t){return R(z(e),t)}function R(e,t){return`${e}|t:${I(L(t))}`}function z(t){return e.s(t)?`r:${t.key}`:typeof t==`string`?`s:${I(t)}`:`u8:${I(t)}`}const B=new WeakMap;function Te(e){if(!(e instanceof Uint8Array))return z(e);let t=B.get(e);return t===void 0&&(t=z(e),B.set(e,t)),t}var Ee=class{hashDefinition;dataTree;definitionMemo;keyMemo;constructor(e,t){this.hashDefinition=e,this.dataTree=t}get definitionHash(){return this.definitionMemo??=this.hashDefinition()}get key(){return this.keyMemo??=R(this.definitionHash,this.dataTree)}},De=class{items=[];head=0;live=new Set;get size(){return this.live.size}push(e){this.items.push(e),this.live.add(e)}remove(e){this.live.delete(e)&&this.compact()}shift(){for(;this.head<this.items.length;){let e=this.items[this.head];if(this.items[this.head++]=void 0,e&&this.live.delete(e))return this.compact(),e}}compact(){if(this.live.size===0){this.items=[],this.head=0;return}let e=this.items.length-this.live.size;e<=64||e<=this.live.size||(this.items=this.items.filter(e=>e!==void 0&&this.live.has(e)),this.head=0)}};function Oe(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var V=class{executor;baseConfig;mode;maxConcurrent;maxQueueDepth;queueWaitMs;timeoutMs;retry;cacheEnabled;cacheMaxBytes;cacheTtl;cacheErroredSolves;cache=new Map;cacheBytes=0;cacheHits=0;cacheMisses=0;cacheEvictions=0;reuseServerDefinitionCache;serverCacheKeys=new Map;lastStringDefinition=null;onStart;onSettle;onSuperseded;subscribers=new Set;inFlight=new Set;pendingForLatestWins=null;fifo=new De;_lastResult=null;_lastError=null;_lastDurationMs=null;solveSeq=0;lastStateSeq=0;disposed=!1;constructor(t,n,r={}){if(this.executor=t,this.baseConfig=n,this.mode=r.mode??`latest-wins`,this.mode!==`latest-wins`&&this.mode!==`queue`)throw new e.D(`Unknown scheduler mode '${String(this.mode)}'. For concurrent solves use { mode: 'queue', maxConcurrent: 4 }.`,e.O.INVALID_CONFIG,{context:{mode:this.mode}});this.maxConcurrent=Math.max(1,r.maxConcurrent??1),this.maxQueueDepth=r.maxQueueDepth!==void 0&&r.maxQueueDepth>0?Math.floor(r.maxQueueDepth):void 0,this.queueWaitMs=r.queueWaitMs!==void 0&&r.queueWaitMs>0?r.queueWaitMs:void 0,this.timeoutMs=r.timeoutMs,this.retry=r.retry;let i=r.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.reuseServerDefinitionCache??!0,this.onStart=r.onStart,this.onSettle=r.onSettle,this.onSuperseded=r.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifo.size>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifo.size+ +!!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.T().error(`[SolveScheduler] subscriber threw:`,t)}}solve(e,t,n){return this.solveDetailed(e,t,n).then(e=>e.response)}solveDetailed(t,n,r){if(this.disposed)return Promise.reject(new e.D(`SolveScheduler has been disposed and cannot be used`,e.O.INVALID_STATE));let i=new Ee(()=>this.hashDefinitionMemo(t),n),a=``;if(this.cacheEnabled||this.onStart||this.onSettle||this.onSuperseded)try{a=i.key}catch(t){return Promise.reject(new e.D(`Solve input could not be hashed`,e.O.INVALID_INPUT,{originalError:t}))}let o=++this.solveSeq,s={key:a,enqueuedAt:Date.now(),startedAt:null};if(r?.signal?.aborted)return Promise.reject(this.makeAbortError(s));let c=this.readCache(a);if(c){this.mode===`latest-wins`&&this.supersedeCurrent();let e={status:`success`,response:c,durationMs:0,fromCache:!0};return this.writeLastState(o,{result:c,durationMs:0}),this.runHook(this.onStart,s),this.runHook(this.onSettle,s,e),this.notify(),Promise.resolve({response:c,fromCache:!0,durationMs:0})}return new Promise((e,a)=>{let c={definition:t,dataTree:n,hashes:i,ctx:s,seq:o,resolve:e,reject:a,externalSignal:r?.signal,selvaevents:r?.selvaevents,onServerTiming:r?.onServerTiming};c.externalSignal&&(c.queuedAbortHandler=()=>this.abortQueuedItem(c),c.externalSignal.addEventListener(`abort`,c.queuedAbortHandler,{once:!0})),this.enqueue(c)})}writeLastState(e,t){e<this.lastStateSeq||(this.lastStateSeq=e,`result`in t?(this._lastResult=t.result,this._lastError=null):this._lastError=t.error,this._lastDurationMs=t.durationMs)}supersedeCurrent(){this.pendingForLatestWins&&=(this.supersede(this.pendingForLatestWins),null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}dequeue(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null),this.fifo.remove(e)}abortQueuedItem(e){this.dequeue(e),this.fail(e,this.makeAbortError(e.ctx)),this.notify()}shedAsQueueFull(t){let n=new e.D(`Solve queue is full; request rejected (backpressure)`,e.O.QUEUE_FULL,{statusCode:503,context:{queueDepth:this.fifo.size,maxQueueDepth:this.maxQueueDepth}});this.fail(t,n),this.notify()}armQueueWaitTimer(t){if(this.queueWaitMs===void 0)return;let n=this.queueWaitMs;t.queueWaitTimer=setTimeout(()=>{if(t.settled)return;this.dequeue(t);let r=new e.D(`Solve waited longer than ${n}ms in queue; rejected (backpressure)`,e.O.QUEUE_TIMEOUT,{statusCode:503,context:{waitedMs:Date.now()-t.ctx.enqueuedAt,queueWaitMs:n}});this.fail(t,r),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`:this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifo.size>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifo.push(e))}this.notify()}async execute(e){let t=new AbortController,n=e;n.controller=t,this.inFlight.add(n),e.ctx.startedAt=Date.now(),this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e);let r=()=>t.abort();e.externalSignal?.addEventListener(`abort`,r,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let i=performance.now();try{let n={...this.baseConfig,signal:t.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry},...e.selvaevents!==void 0&&{selvaevents:e.selvaevents}},r=e.onServerTiming;if(r){let e=this.baseConfig.onServerTiming;n.onServerTiming=(t,n)=>{try{e?.(t,n)}finally{r(t,n)}}}let{response:a,definitionReuploaded:o}=await this.runExecutor(e,n),s=performance.now()-i;if(this.writeCache(e.ctx.key,a),!this.settleSuccess(e,{response:a,fromCache:!1,definitionReuploaded:o,durationMs:s}))return;this.writeLastState(e.seq,{result:a,durationMs:s}),this.runHook(this.onSettle,e.ctx,{status:`success`,response:a,durationMs:s,fromCache:!1,definitionReuploaded:o})}catch(t){let r=performance.now()-i,a=this.normalizeExecutionError(t,n);this.writeLastState(e.seq,{error:a,durationMs:r}),this.fail(e,a,r)}finally{e.externalSignal?.removeEventListener(`abort`,r),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(t,n){let{definition:r,dataTree:i}=t;if(!this.reuseServerDefinitionCache||e.c(r)){let{response:e}=await this.executor(r,i,null,n);return{response:e}}let a=t.hashes.definitionHash,o=this.serverCacheKeys.get(a)??null,s=await this.executor(r,i,o,n);return this.serverCacheKeys.delete(a),s.cacheKey&&(this.serverCacheKeys.set(a,s.cacheKey),this.serverCacheKeys.size>100&&this.serverCacheKeys.delete(this.serverCacheKeys.keys().next().value)),{response:s.response,definitionReuploaded:s.missed}}hashDefinitionMemo(e){return typeof e==`string`?(this.lastStringDefinition?.value!==e&&(this.lastStringDefinition={value:e,hash:z(e)}),this.lastStringDefinition.hash):Te(e)}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.fifo.size>0&&this.inFlight.size<this.maxConcurrent;)this.execute(this.fifo.shift())}}supersede(t){let n=new e.D(`Superseded by newer solve`,e.O.SUPERSEDED,{context:{enqueuedAt:t.ctx.enqueuedAt}});this.settleError(t,n)&&this.runHook(this.onSuperseded,t.ctx)}makeAbortError(t){return new e.D(`Request aborted by caller`,e.O.ABORTED,{context:{enqueuedAt:t.enqueuedAt}})}settleError(e,t){return!e.settled&&(e.settled={error:t},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(t),!0)}fail(e,t,n=0){this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:n})}settleSuccess(e,t){return!e.settled&&(e.settled={ok:!0},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.resolve(t),!0)}removeQueuedAbortHandler(e){e.queuedAbortHandler&&e.externalSignal&&e.externalSignal.removeEventListener(`abort`,e.queuedAbortHandler),e.queuedAbortHandler=void 0}normalizeExecutionError(t,n){return n.settled&&`error`in n.settled?n.settled.error:t instanceof e.D?t:t instanceof Error&&t.name===`AbortError`?this.makeAbortError(n.ctx):new e.D(t instanceof Error?t.message:String(t),e.O.UNKNOWN_ERROR,{originalError:t})}cancelAll(){this.pendingForLatestWins&&=(this.fail(this.pendingForLatestWins,this.makeAbortError(this.pendingForLatestWins.ctx)),null);for(let e=this.fifo.shift();e;e=this.fifo.shift())this.fail(e,this.makeAbortError(e.ctx));for(let e of this.inFlight){let t=e.ctx.startedAt?Date.now()-e.ctx.startedAt:0;this.fail(e,this.makeAbortError(e.ctx),t),e.controller.abort()}this.notify()}readCache(e){if(!this.cacheEnabled)return null;let t=this.cache.get(e);return t?this.cacheTtl>0&&Date.now()-t.insertedAt>this.cacheTtl?(this.dropCacheEntry(e),this.cacheMisses+=1,null):(this.cache.delete(e),this.cache.set(e,t),this.cacheHits+=1,t.response):(this.cacheMisses+=1,null)}writeCache(t,n){if(!this.cacheEnabled)return;let r=e.C(n,`errors`);if(!this.cacheErroredSolves&&Array.isArray(r)&&r.length>0)return;let i=e.f(n)??Oe(n);if(!(i>this.cacheMaxBytes))for(this.dropCacheEntry(t),this.cache.set(t,{response:n,insertedAt:Date.now(),sizeBytes:i}),this.cacheBytes+=i;this.cacheBytes>this.cacheMaxBytes&&this.cache.size>0;){let e=this.cache.keys().next().value;if(e===void 0)break;this.dropCacheEntry(e),this.cacheEvictions+=1}}dropCacheEntry(e){let t=this.cache.get(e);t&&(this.cache.delete(e),this.cacheBytes-=t.sizeBytes)}clearCache(){this.cache.clear(),this.cacheBytes=0}cacheStats(){return{entries:this.cache.size,bytes:this.cacheBytes,hits:this.cacheHits,misses:this.cacheMisses,evictions:this.cacheEvictions}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(t,...n){if(t)try{t(...n)}catch(t){e.T().error(`[SolveScheduler] hook threw:`,t)}}};function H(t){return e.s(t)?`ref:${t.key}`:typeof t==`string`&&t.length<200?t:`...content...`}function U(t){return Array.isArray(t)?t.map(t=>{let n=0,r=0,i=e.C(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.C(t,`paramName`)??`<unnamed>`,items:n,bytes:r}}):[]}var ke=class n{config;serverStats;disposed=!1;static CREATE_PROBE_TIMEOUT_MS=2e3;constructor(n){this.config={...n,serverUrl:e.x(n.serverUrl),debug:n.debug??!1},this.serverStats=new t(this.config.serverUrl,this.config)}static async create(t,r={}){let i=new n(t),a=Math.max(1,(r.probe?.attempts??2)+1),o=r.probe?.baseDelayMs??250,s=r.probe?.maxDelayMs??1e3,c,l=null,u=0;for(let t=0;t<a;t++){if(u=t+1,c=await i.serverStats.probeServer(n.CREATE_PROBE_TIMEOUT_MS),c.online)return i;if(l=e.u(c),l&&!l.retryable)break;if(t<a-1){let e=Math.min(o*2**t,s);await new Promise(t=>setTimeout(t,e))}}await i.dispose();let d=c?.status,f=l?`Rhino Compute server is not available. ${l.summary}`:`Rhino Compute server is not online`;throw new e.D(f,e.O.NETWORK_ERROR,{...d!==void 0&&{statusCode:d},context:{serverUrl:i.config.serverUrl,attempts:u,maxAttempts:a,...l&&{probeVerdict:l.verdict,probeRetryable:l.retryable},...d!==void 0&&{lastProbeStatus:d},...c?.error!==void 0&&{lastProbeError:c.error}}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),P(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),M(e,this.config)}async solve(t,n,r){this.ensureNotDisposed();try{if(typeof t==`string`&&!t.trim())throw new e.D(`Definition URL/content is required`,e.O.INVALID_INPUT,{context:{receivedUrl:t}});if(t instanceof Uint8Array&&t.length===0)throw new e.D(`Definition content is empty`,e.O.INVALID_INPUT);if(e.s(t)&&!t.key.trim())throw new e.D(`DefinitionRef key is empty`,e.O.INVALID_INPUT);let i=await u(n,t,{...this.config,...r?.signal!==void 0&&{signal:r.signal},...r?.timeoutMs!==void 0&&{timeoutMs:r.timeoutMs},...r?.retry!==void 0&&{retry:r.retry},...r?.selvaevents!==void 0&&{selvaevents:r.selvaevents}}),a=e.C(i,`errors`);if(Array.isArray(a)&&a.length>0)throw new e.D(a.map(String).join(`; `)||`Computation failed`,e.O.COMPUTATION_ERROR,{context:{definition:H(t),inputSummary:U(n),errors:a,warnings:e.C(i,`warnings`),values:i.values}});return i}catch(r){throw this.config.debug&&e.T().error(`Compute failed:`,r),r instanceof e.D?r:new e.D(r instanceof Error?r.message:String(r),e.O.COMPUTATION_ERROR,{context:{definition:H(t),inputSummary:U(n)},originalError:r})}}createScheduler(e){return this.ensureNotDisposed(),new V((e,t,n,r)=>d(t,n,e,r),this.config,e)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new e.D(`GrasshopperClient has been disposed and cannot be used`,e.O.INVALID_STATE)}};function Ae(e){return typeof e==`object`&&!!e&&e.__decodeError===!0}function W(e,t){return{__decodeError:!0,type:e,raw:t}}function G(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=new Map([[`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}],[`Rhino.Geometry.Line`,(e,t)=>{let n=t;return!n||!n.From||!n.To?null:new e.Line([n.From.X,n.From.Y,n.From.Z],[n.To.X,n.To.Y,n.To.Z])}]]);function je(e){if(K.has(e))return K.get(e);for(let[t,n]of K)if(e.startsWith(t))return n}function Me(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function Ne(t,n,r){let i=je(n),a=!1;if(i)try{let e=i(r,t);if(e!=null)return e}catch(t){e.T().warn(`Failed to decode Rhino type ${n}:`,t),a=!0}try{if(Me(t))return r.CommonObject.decode(t)}catch(r){return e.T().warn(`Failed to decode ${n} with CommonObject:`,r),W(n,t)}return a?W(n,t):t}const q={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},J=`FileData`;function Y(e,t){return e.includes(`WebDisplay`)||t&&e!==q.STRING}function Pe(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 Fe(e,t,n){switch(t){case q.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case q.INT:return Number.parseInt(String(e),10);case q.DOUBLE:return Number.parseFloat(String(e));case q.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?Ne(e,t,n):e}}function Ie(e,t,n,r){if(typeof e.data!=`string`)return e.data;let i=n?Pe(e.data):e.data;return n&&t.includes(J)?Le(i)??i:Fe(i,t,r)}function Le(t){if(!t||typeof t!=`object`)return null;let n=e.C(t,`fileName`),r=e.C(t,`fileType`),i=e.C(t,`subFolder`),a=e.C(t,`isBase64Encoded`);if(typeof n!=`string`||typeof r!=`string`||typeof i!=`string`||!e.S(t,`data`)||typeof a!=`boolean`&&typeof a!=`string`)return null;let o=e.C(t,`metadata`);return{fileName:n,fileType:r,data:e.C(t,`data`),isBase64Encoded:e.i(a),subFolder:i,...o?{metadata:o}:{}}}function X(t){let n=e.C(t,`values`);return Array.isArray(n)?n:[]}function Z(e){return typeof e.type==`string`?e.type:``}function Q(e,t){if(e&&typeof e==`object`){for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)e&&typeof e==`object`&&t(e)}}function Re(t,n=!1,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r,s={},c=new Set;for(let r of X(t)){let t=e.C(r,`paramName`);Q(e.C(r,`innerTree`),e=>{let r=Z(e);if(Y(r,o))return;let l=n?e.id:t;if(!l)return;let u=Ie(e,r,i,a);Object.prototype.hasOwnProperty.call(s,l)?c.has(l)?s[l].push(u):(s[l]=[s[l],u],c.add(l)):g(s,l,u)})}return{values:s,dispose:()=>G(s)}}function ze(t){let n=[];for(let r of X(t))Q(e.C(r,`innerTree`),e=>{if(!Z(e).includes(J))return;let t=Le(Pe(e.data));t&&n.push(t)});return n}function Be(t,n,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r;for(let r of X(t)){let t=e.C(r,`innerTree`),s=!1;if(`byName`in n){if(e.C(r,`paramName`)!==n.byName)continue;s=!0}let c=[];if(Q(t,e=>{if(`byId`in n){if(e.id!==n.byId)return;s=!0}let t=Z(e);Y(t,o)||c.push(Ie(e,t,i,a))}),s)return c.length===0?void 0:c.length===1?c[0]:c}}var Ve=class{response;constructor(e){this.response=e}getValues(e=!1,t={}){return Re(this.response,e,t)}getValue(e,t){return Be(this.response,e,t)}async getAndDownloadFiles(t,n){await e.t(ze(this.response),t,n)}};function He(t){return(Array.isArray(t)?t:[t]).map(t=>({schemas:e.C(t,`schemas`),error:e.C(t,`error`)}))}const Ue=new Set([`options`,`defaultOptions`,`values`]),We=new Set([`optionMedia`,`assets`]),Ge=e=>e>=`A`&&e<=`Z`;function Ke(e){if(e.length===0||!Ge(e[0]))return e;let t=0;for(;t<e.length&&Ge(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function qe(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=Ke(n);g(t,e,Ue.has(e)?r:We.has(e)?Je(r):$(r))}return t}function Je(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t={};for(let[n,r]of Object.entries(e))g(t,n,$(r));return t}var Ye=class t{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(e,n){let r=this.innerTree[t.formatPathString(e)]??=[];for(let e of n)r.push({data:t.serializeValue(e)});return this}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}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getParamName(){return this.paramName}static fromInputParams(e){return t.fromValues(e.map(e=>({paramName:e.nickname||`unnamed`,paramType:e.paramType,value:e.default,...`minimum`in e&&{minimum:e.minimum,maximum:e.maximum}})))}static fromValues(n){let r=[];for(let i of n){let n=new t(i.paramName),a=t.itemCoercer(i);for(let[r,o]of t.branchesOf(i.value)){let t=[];for(let n of o){if(n==null)continue;let r=a(n);r===null?e.T().warn(`${i.paramName}: dropped an item that is not a valid ${i.paramType}`):t.push(r)}t.length>0&&n.append(r,t)}Object.keys(n.innerTree).length>0&&r.push(n.toComputeFormat())}return r}static branchesOf(e){return t.hasValidValue(e)?v(e)?Object.entries(e).map(([e,n])=>[t.parsePathString(e),n]):[[[0],Array.isArray(e)?e:[e]]]:[]}static itemCoercer(e){let{paramName:n,minimum:r,maximum:i}=e,a=e.paramType.toLowerCase();return a===`number`||a===`integer`?e=>{let o=b(e);if(o===null)return null;let s=a===`integer`?Math.round(o):o;return t.clampValue(s,r,i,n)}:a===`boolean`?x:e=>e}static replaceTreeValue(e,n,r){let i=t.buildFromValue(n,r).toComputeFormat(),a=e.slice(),o=a.findIndex(e=>t.paramNameOf(e)===n);return o===-1?a.push(i):a[o]=i,a}static buildFromValue(e,n){let r=new t(e);return v(n)?r.fromDataTreeDefault(n):r.appendFlat(n),r}static getTree(n,r){let i=n.find(e=>t.paramNameOf(e)===r);if(!i)return null;let a=new Map,o=e.C(i,`InnerTree`);if(!o||typeof o!=`object`)return a;for(let[e,n]of Object.entries(o))Array.isArray(n)&&a.set(e,n.map(e=>e?.data===void 0?null:t.deserializeValue(e.data)));return a}static getTreeValue(n,r){let i=t.getTree(n,r);if(!i||i.size===0)return null;if(i.size>1)throw new e.D(`"${r}" has ${i.size} branches; read it with TreeBuilder.getTree`,e.O.INVALID_INPUT,{context:{paramName:r,branchCount:i.size}});let[a]=i.values();return a.length===0?null:a.length===1?a[0]:a}static paramNameOf(t){return e.C(t,`ParamName`)}static parsePathString(t){let n=t.match(_);if(!n)throw new e.D(`Invalid Grasshopper tree path: "${t}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`,e.O.INVALID_INPUT,{context:{pathStr:t}});return n[1]?n[1].split(`;`).map(Number):[]}static formatPathString(e){return`{${e.join(`;`)}}`}static serializeValue(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`?e:typeof e==`object`&&e?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e!=`string`)return e;if(e.startsWith(`{`)||e.startsWith(`[`))try{return JSON.parse(e)}catch{return e}let t=Number(e);return Number.isFinite(t)&&String(t)===e?t:e===`true`||e!==`false`&&e}static hasValidValue(e){return e==null?!1:typeof e==`string`||!(Array.isArray(e)&&e.length===0||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0)}static clampValue(t,n,r,i){let a=t;return n!=null&&a<n&&(e.T().warn(`${i}: ${t} below min ${n}, clamping`),a=n),r!=null&&a>r&&(e.T().warn(`${i}: ${t} above max ${r}, clamping`),a=r),a}};exports.ComputeServerStats=t,exports.GrasshopperClient=ke,exports.GrasshopperResponseProcessor=Ve,exports.SolveScheduler=V,exports.TreeBuilder=Ye,exports.disposeRhinoObjects=G,exports.fetchDefinitionIO=M,exports.fetchParsedDefinitionIO=P,exports.hashDefinition=z,exports.hashSolveInput=we,exports.isRhinoDecodeError=Ae,exports.normalizeUISchemaCasing=qe,exports.processInput=ge,exports.readSchemaResults=He,exports.solveGrasshopperDefinition=u,exports.stableStringify=L;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./core-yOYyTPZD.cjs");var t=class t{serverUrl;headers;disposed=!1;activeMonitors=new Set;static DEFAULT_TIMEOUT_MS=5e3;static LIFECYCLE_TIMEOUT_MS=6e4;static MIN_MONITOR_INTERVAL_MS=100;static MAX_BODY_BYTES=1<<20;constructor(t,n){this.serverUrl=e.x(t),this.headers={...e.y(typeof n==`string`?{apiKey:n}:n??{}),"Content-Type":`application/json`}}fetchWithTimeout(e,n={},r=t.DEFAULT_TIMEOUT_MS){let i={...n,headers:this.headers,redirect:`manual`};return r>0&&!i.signal&&(i.signal=AbortSignal.timeout(r)),fetch(e,i)}async getText(n,r={},i=t.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let a=`${r.method??`GET`} ${n}`;try{let o=await this.fetchWithTimeout(`${this.serverUrl}${n}`,r,i);if(!o.ok)return e.T().warn(`[ComputeServerStats] ${a} failed:`,o.status),await o.body?.cancel().catch(()=>{}),null;let{text:s,truncated:c}=await e.m(o,t.MAX_BODY_BYTES);return c?(e.T().warn(`[ComputeServerStats] ${a} answered with an oversized body`),null):s}catch(t){return e.T().warn(`[ComputeServerStats] ${a} errored:`,t),null}}async isServerOnline(e=t.DEFAULT_TIMEOUT_MS){return(await this.probeServer(e)).online}async probeServer(n=t.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let r=`${this.serverUrl}/`;try{let t=await this.fetchWithTimeout(r,{method:`GET`},n);return await t.body?.cancel().catch(()=>{}),{online:t.ok||e.d(t),status:t.status}}catch(t){return e.T().debug(`[ComputeServerStats] Fetch error:`,t),{online:!1,error:t instanceof Error?`${t.name}: ${t.message}`:String(t)}}}async getActiveChildren(n={}){let{initialize:r=!0}=n,i=r?await this.getText(`/activechildren`,{},t.LIFECYCLE_TIMEOUT_MS):await this.getText(`/activechildren?initialize=false`);if(i===null)return null;let a=i.trim();return/^\d+$/.test(a)?parseInt(a,10):(e.T().warn(`[ComputeServerStats] /activechildren answered with a non-numeric body`),null)}async getVersion(){let e=await this.getText(`/version`);if(e===null)return null;let t=n(e);return t==null?{rhino:e,compute:``,git_sha:null}:{rhino:t.rhino??``,compute:t.compute??``,git_sha:t.git_sha??null}}async getInstalledPlugins(e=`gh`){let t=await this.getText(`/plugins/${e}/installed`),r=t===null?void 0:n(t);return r&&typeof r==`object`?r:null}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[e,t]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...e&&{version:e},...t!==null&&{activeChildren:t}}}async purgeCache(){let e=await this.getText(`/cache/purge`,{method:`POST`}),t=(e===null?void 0:n(e))?.purged;return typeof t==`number`?t:null}async purgeAllChildren(){this.ensureNotDisposed();let t=await this.getActiveChildren({initialize:!1});if(t===null)return e.T().warn(`[ComputeServerStats] purgeAllChildren: could not read child count`),null;if(t===0)return{totalPurged:0,calls:0,children:0,confident:!0};let n=t*2,r=0;for(let e=0;e<n;e++){let e=await this.purgeCache();e!==null&&(r+=e)}return{totalPurged:r,calls:n,children:t,confident:t===1}}async getServerTime(){let e=await this.getText(`/servertime`);if(e===null)return null;let t=new Date(e.trim().replace(/^"|"$/g,``));return isNaN(t.getTime())?null:t}async getIdleSpan(){let e=await this.getText(`/idlespan`);if(e===null)return null;let t=parseFloat(e.trim());return isNaN(t)?null:t}async launchChildren(){return this.postJson(`/launch-children`)}async launchChild(e){let t=e===void 0?`/launch-child`:`/launch-child?port=${e}`;return this.postJson(t)}async shutdownChildren(e){let t=e===void 0?`/shutdown-children`:`/shutdown-children?port=${e}`;return this.postJson(t)}async recycleChildren(e){let t=e===void 0?`/recycle-children`:`/recycle-children?port=${e}`;return this.postJson(t)}async postJson(e){let r=await this.getText(e,{method:`POST`},t.LIFECYCLE_TIMEOUT_MS);return r===null?null:n(r)??null}monitor(n,r=5e3){if(this.ensureNotDisposed(),!Number.isFinite(r)||r<t.MIN_MONITOR_INTERVAL_MS)throw new e.D(`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.`,e.O.INVALID_CONFIG,{context:{intervalMs:r}});let i=!0,a=null;e.T().info(`🔄 Starting server stats monitoring every ${r}ms`);let o=async()=>{if(a=null,i&&!this.disposed){try{let t=await this.getServerStats();if(!i||this.disposed)return;try{n(t)}catch(t){e.T().error(`[ComputeServerStats] Monitor callback threw:`,t)}}catch(t){!i||this.disposed?e.T().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,t):e.T().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,t)}i&&!this.disposed&&(a=setTimeout(()=>void o(),r))}},s=()=>{i=!1,a!==null&&(clearTimeout(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()}}ensureNotDisposed(){if(this.disposed)throw new e.D(`ComputeServerStats has been disposed and cannot be used`,e.O.INVALID_STATE)}};function n(e){try{return JSON.parse(e)}catch{return}}const r=new Set;function i(){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 a(t,n){n||i()&&!r.has(t)&&(r.add(t),e.T().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`))}const o={definition_not_cached:e.O.DEFINITION_NOT_CACHED};function s(e){return{...e,serverErrorCodes:{...o,...e.serverErrorCodes}}}function c(t){return t instanceof e.D?t.code===e.O.DEFINITION_NOT_CACHED||t.message.includes(`Unable to load grasshopper definition`):!1}function l(t,n){if(!n)return;let r=e.C(t,`values`);if(!Array.isArray(r)||r.length===0)return;let i=[];for(let t of r){let n=e.C(t,`innerTree`);(!n||Object.keys(n).length===0)&&i.push(e.C(t,`paramName`)??`<unnamed>`)}if(i.length===0)return;let a=i.length===r.length?`all`:`${i.length}/${r.length}`;e.T().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 u(e,t,n){return a(`solveGrasshopperDefinition`,n.suppressBrowserWarning),(await f(e,t,n)).response}async function d(e,t,n,r){if(a(`solveWithServerCacheKey`,r.suppressBrowserWarning),t!==null)try{return{...await m({algo:null,pointer:t,values:e},r),missed:!1}}catch(e){if(!c(e))throw e}return{...await f(e,n,r),missed:!0}}async function f(e,t,n){return m(h(await p(t),e),n)}async function p(t){if(!e.s(t))return t;try{return await t.load()}catch(n){throw new e.D(`Failed to load definition bytes for ref '${t.key}'`,e.O.INVALID_INPUT,{context:{definitionKey:t.key},originalError:n})}}async function m(t,n){e.x(n.serverUrl),ee(t,n);let{maxResponseBytes:r}=n,i=await e.l(`grasshopper`,t,s({...n,maxResponseBytes:r!==void 0&&t.algo?r+t.algo.length:r})),{pointer:a,algo:o,...c}=i,u=c,d=e.f(i);if(d!==void 0){let t=typeof o==`string`?o.length:0;e.p(u,Math.max(0,d-t))}return l(u,n.debug),{response:u,cacheKey:typeof a==`string`?a:null}}function h(t,n){let r={algo:null,pointer:null,values:n};return t instanceof Uint8Array?r.algo=e.h(t):e.c(t)?r.pointer=t:r.algo=e._(t)??e.v(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),t.selvaevents!=null&&(e.selvaevents=t.selvaevents)}function g(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}const _=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function v(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>_.test(e)&&Array.isArray(t))}function y(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 b=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=e.trim();if(t===``||/^[+-]?0[xbo]/i.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}return null},x=e=>{if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}return null},te=e=>typeof e==`string`?e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e.startsWith(`"`)?e.slice(1):e:null,ne=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function S(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.T().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return e.T().warn(`Failed to parse object value "${n}" for input ${t}`,r),null}return null}}const re=new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),ie=new Set([`System.Int32`,`System.Int64`]);function ae(t,n){return e.T().warn(n),{schema:{...t,default:null},warning:{code:e.O.MALFORMED_DEFAULT,message:n}}}function oe(t,n){if(typeof t.default!=`object`||t.default===null||Array.isArray(t.default)||v(t.default))return{schema:t};if(!e.S(t.default,`innerTree`))return ae(t,`Input "${n}" default had an unrecognized shape (no innerTree key); the default was dropped.`);let r=e.C(t.default,`innerTree`)??{};if(Object.keys(r).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let i={},a=[];for(let[o,s]of Object.entries(r)){if(!Array.isArray(s))return ae(t,`Input "${n}" default had a non-array innerTree branch ("${o}"); the default was dropped.`);let r=[];for(let t of s){let n=e.C(t,`data`),i=e.C(t,`type`);if(i&&re.has(i)){if(typeof n==`string`&&n.trim()===``)continue;let e=b(n);if(e===null){a.push(`"${String(n)}" (${i})`);continue}r.push(ie.has(i)?Math.round(e):e);continue}if(i===`System.Boolean`){let e=x(n);if(e===null){a.push(`"${String(n)}" (${i})`);continue}r.push(e);continue}if(typeof n==`string`&&i?.startsWith(`Rhino.Geometry`)){try{r.push(JSON.parse(n))}catch{r.push(n)}continue}r.push(n)}g(i,o,r)}if(a.length>0){let r=`Input "${n}" default contained ${a.length} tree value(s) that could not be parsed and were dropped: ${a.join(`, `)}.`;return e.T().warn(r),{schema:{...t,default:i},warning:{code:e.O.MALFORMED_DEFAULT,message:r}}}return{schema:{...t,default:i}}}let i=[];for(let t of Object.values(r))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&e.S(n,`data`)&&i.push(e.C(n,`data`));return{schema:{...t,default:i.length>1?i:i[0]}}}function se(e,t){let n=Number(e.toFixed(t));return Math.abs(e-n)<1e-8?n:e}function C(e){if(!Number.isFinite(e))return 0;let[t,n]=String(Math.abs(e)).split(`e`),r=n===void 0?Math.abs(e).toFixed(12).replace(/0+$/,``).split(`.`)[1]?.length??0:(t.split(`.`)[1]?.length??0)-Number(n);return Math.min(Math.max(r,0),12)}function ce(e){if(!Number.isFinite(e)||e===0)return .1;let t=C(e);return t===0?Math.abs(e)>=1?1:.1:Number((10**-t).toFixed(t))}function w(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}const T=(e,t)=>(e.atMost??1)>1?[t]:t,E=e=>w(e)??(e.paramType===`Integer`?1:.1),D=(e,t)=>Array.isArray(e)?e.map(e=>typeof e==`number`?t(e):e):typeof e==`number`?t(e):e;function le(t){if(v(t.default))return{default:t.default,stepSize:E(t)};if(typeof t.default==`string`&&t.default.trim()!==``&&b(t.default)===null)throw new e.D(`Invalid numeric default "${t.default}" for input "${t.name||`unknown`}"`,e.O.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=y(t.default,b,!0);if(t.paramType===`Integer`)return{default:D(n,Math.round),stepSize:E(t)};let r=Array.isArray(n)?n[0]:n,i=[r,t.minimum,t.maximum].find(e=>typeof e==`number`&&Number.isFinite(e)&&e!==0),a=w(t)??(i===void 0?.1:ce(i)),o=C(a);if(o===0&&typeof r==`number`&&r!==0&&Math.abs(r)<1){let e=Math.ceil(-Math.log10(Math.abs(r)));Number.isFinite(e)&&e>0&&(o=e)}return o=Math.min(Math.max(o,0),12),{default:D(n,e=>se(e,o)),stepSize:a}}const O={parse(e,t){let{default:n,stepSize:r}=le(e);return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:r,default:n}},fallback(e,t){let n=typeof e.minimum==`number`&&Number.isFinite(e.minimum)&&e.minimum>0?e.minimum:0;return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:E(e),default:T(e,n)}}},ue={parse(t,n){if(v(t.default))return{...n,paramType:`Boolean`,default:t.default};let r=y(t.default,x,!1);if(r!=null&&typeof r!=`boolean`&&!Array.isArray(r))throw new e.D(`Invalid boolean default "${String(r)}" for input "${t.name||`unknown`}"`,e.O.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});return{...n,paramType:`Boolean`,default:r}},fallback(e,t){return{...t,paramType:`Boolean`,default:T(e,!1)}}},de={parse(e,t){let n=y(e.default,te,!1);return{...t,paramType:`Text`,default:n}}},fe={parse(t,n,r){if(!t.values||typeof t.values!=`object`||Object.keys(t.values).length===0){let n=t.nickname||`unnamed`;throw new e.D(`Input "${n}" has no values defined (expected ValueList)`,e.O.INVALID_INPUT,{context:{inputName:n,expectedType:`ValueList`}})}let i=t.default;if(t.default!==void 0&&t.default!==null){if(typeof t.default==`object`)throw new e.D(`ValueList input "${t.nickname||`unnamed`}" default is not a string-able value`,e.O.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=String(t.default).toLowerCase(),a=Object.keys(t.values).find(e=>e.toLowerCase()===n);if(a!==void 0)i=a;else{let n=`ValueList input "${t.nickname||`unnamed`}" default value "${t.default}" is not in available values`;e.T().warn(n),r?.({code:e.O.VALIDATION_ERROR,message:n})}}return{...n,paramType:`ValueList`,values:t.values,default:i}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}};function k(e,t){return{...t,paramType:`Geometry`,default:T(e,null)}}const A=new Map([[`Number`,O],[`Integer`,O],[`Boolean`,ue],[`Text`,de],[`ValueList`,fe],[`Geometry`,{parse(e,t){let n=y(e.default,S(e.nickname||`unnamed`),!0);return{...t,paramType:`Geometry`,default:n}},fallback:k}],[`File`,{parse(e,t){let n=y(e.default,S(e.nickname||`unnamed`),!0);return{...t,paramType:`File`,acceptedFormats:e.acceptedFormats,default:n}}}],[`Color`,{parse(e,t){let n=y(e.default,ne,!1);return{...t,paramType:`Color`,default:n}}}]]),pe=k,me=new Map([...A.keys()].map(e=>[e.toLowerCase(),e]));function he(e){return me.get(e?.toLowerCase())??e}function ge(e){return j(e).input}function j(t){let n=t.name||`unknown`,r=[],i=({code:e,message:i})=>{r.push({inputName:n,paramType:t.paramType,message:i,code:e})},a={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??void 0,id:t.id},o=he(t.paramType),s={...t,paramType:o};try{let{schema:e,warning:t}=oe(s,n);s=e,t&&i(t)}catch(t){s={...s,default:null},i({code:e.O.MALFORMED_DEFAULT,message:`Input "${n}" default could not be normalized and was dropped: ${t instanceof Error?t.message:String(t)}`})}let c=A.get(o);try{if(!c)throw new e.D(`Unknown paramType: ${o}`,e.O.VALIDATION_ERROR,{context:{receivedParamType:o,paramName:t.name}});return{input:c.parse(s,a,i),errors:r}}catch(l){if(!(l instanceof e.D))throw new e.D(l instanceof Error?l.message:String(l),e.O.VALIDATION_ERROR,{context:{paramName:t.name,paramType:o},originalError:l});return e.T().error(`Validation error for input ${n}:`,l.message),i(l),{input:(c?.fallback??pe)(s,a),errors:r}}}function _e(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=j(r);t.push(e),n.push(...i)}return{inputs:t,parseErrors:n}}function ve(t){let n=e.C(t,`stepSize`);return{id:e.C(t,`id`)??``,name:e.C(t,`name`)??``,nickname:e.C(t,`nickname`)??null,description:e.C(t,`description`)??``,paramType:e.C(t,`paramType`)??``,treeAccess:e.C(t,`treeAccess`)??!1,minimum:e.C(t,`minimum`)??null,maximum:e.C(t,`maximum`)??null,atLeast:e.C(t,`atLeast`)??1,atMost:e.C(t,`atMost`)??1,stepSize:typeof n==`number`&&Number.isFinite(n)?n:void 0,default:e.C(t,`default`),values:e.C(t,`values`),acceptedFormats:e.C(t,`acceptedFormats`),groupName:e.C(t,`groupName`)??null}}function ye(t){return{name:e.C(t,`name`)??``,nickname:e.C(t,`nickname`)??null,paramType:e.C(t,`paramType`)??``,id:e.C(t,`id`)??``}}async function M(t,n){a(`fetchDefinitionIO`,n.suppressBrowserWarning),e.x(n.serverUrl);let{algo:r,pointer:i}=h(t,[]);if(!r&&!i)throw new e.D(`Definition must resolve to either a URL pointer or base64 algo`,e.O.INVALID_INPUT);let o=await e.l(`io`,r?{algo:r}:{pointer:i},s(n));if(!o||typeof o!=`object`)throw new e.D(`Invalid IO response structure`,e.O.INVALID_INPUT,{context:{response:o}});let c=N(e.C(o,`warnings`)),l=N(e.C(o,`errors`)),u=e.C(o,`inputs`),d=e.C(o,`outputs`);return{inputs:Array.isArray(u)?u.map(ve):[],outputs:Array.isArray(d)?d.map(ye):[],...c&&{loadWarnings:c},...l&&{loadErrors:l}}}function N(e){if(!Array.isArray(e))return;let t=e.map(be).filter(e=>e!==void 0);return t.length>0?t:void 0}function be(t){if(t==null)return;let n;if(typeof t==`string`)n=t;else if(typeof t==`object`){let r=e.C(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 P(e,t){let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await M(e,t),{inputs:o,parseErrors:s}=_e(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}const F=globalThis.process?.getBuiltinModule?.(`node:crypto`);function I(e){if(F){let t=F.createHash(`sha256`);return typeof e==`string`?t.update(e,`utf16le`):t.update(e),t.digest(`hex`)}return Se(e)}const xe=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Se(e){let t=new Ce;return typeof e==`string`?t.updateString(e):t.update(e),t.digestHex()}var Ce=class{h=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);w=new Int32Array(64);pending=new Uint8Array(64);pendingLength=0;totalBytes=0;update(e){this.totalBytes+=e.length;let t=0;if(this.pendingLength>0){let n=Math.min(64-this.pendingLength,e.length);if(this.pending.set(e.subarray(0,n),this.pendingLength),this.pendingLength+=n,t=n,this.pendingLength<64)return;this.compressBytes(this.pending,0),this.pendingLength=0}for(;t+64<=e.length;t+=64)this.compressBytes(e,t);this.pending.set(e.subarray(t),0),this.pendingLength=e.length-t}updateString(e){let t=this.w,n=e.length-e.length%32;for(let r=0;r<n;r+=32){for(let n=0;n<16;n++){let i=e.charCodeAt(r+2*n),a=e.charCodeAt(r+2*n+1);t[n]=(i&255)<<24|i>>>8<<16|(a&255)<<8|a>>>8}this.compress()}this.totalBytes+=n*2;let r=new Uint8Array((e.length-n)*2);for(let t=n,i=0;t<e.length;t++){let n=e.charCodeAt(t);r[i++]=n&255,r[i++]=n>>>8}this.update(r)}digestHex(){let e=this.totalBytes*8,t=new Uint8Array(this.pendingLength<56?64:128);t.set(this.pending.subarray(0,this.pendingLength)),t[this.pendingLength]=128;let n=new DataView(t.buffer);n.setUint32(t.length-8,Math.floor(e/4294967296)),n.setUint32(t.length-4,e>>>0);for(let e=0;e<t.length;e+=64)this.compressBytes(t,e);let r=``;for(let e of this.h)r+=(e>>>0).toString(16).padStart(8,`0`);return r}compressBytes(e,t){let n=this.w;for(let r=0;r<16;r++){let i=t+r*4;n[r]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}this.compress()}compress(){let e=this.w;for(let t=16;t<64;t++){let n=e[t-15],r=e[t-2],i=(n>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,a=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10;e[t]=e[t-16]+i+e[t-7]+a|0}let t=this.h,n=t[0],r=t[1],i=t[2],a=t[3],o=t[4],s=t[5],c=t[6],l=t[7];for(let t=0;t<64;t++){let u=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),d=o&s^~o&c,f=l+u+d+xe[t]+e[t]|0,p=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&r^n&i^r&i)|0;l=c,c=s,s=o,o=a+f|0,a=i,i=r,r=n,n=f+p|0}t[0]=t[0]+n|0,t[1]=t[1]+r|0,t[2]=t[2]+i|0,t[3]=t[3]+a|0,t[4]=t[4]+o|0,t[5]=t[5]+s|0,t[6]=t[6]+c|0,t[7]=t[7]+l|0}};function L(e){let t=new WeakSet,n=e=>{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(typeof e!=`object`)return`undefined`;if(e instanceof Uint8Array)return`{u8:${I(e)}}`;if(t.has(e))return`[Circular]`;t.add(e);let r;if(Array.isArray(e)){let t=[];for(let r=0;r<e.length;r++)t.push(n(e[r]));r=`[${t.join(`,`)}]`}else 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(`,`)}}`;return t.delete(e),r};return n(e)}function we(e,t){return R(z(e),t)}function R(e,t){return`${e}|t:${I(L(t))}`}function z(t){return e.s(t)?`r:${t.key}`:typeof t==`string`?`s:${I(t)}`:`u8:${I(t)}`}const B=new WeakMap;function Te(e){if(!(e instanceof Uint8Array))return z(e);let t=B.get(e);return t===void 0&&(t=z(e),B.set(e,t)),t}var Ee=class{hashDefinition;dataTree;definitionMemo;keyMemo;constructor(e,t){this.hashDefinition=e,this.dataTree=t}get definitionHash(){return this.definitionMemo??=this.hashDefinition()}get key(){return this.keyMemo??=R(this.definitionHash,this.dataTree)}},De=class{items=[];head=0;live=new Set;get size(){return this.live.size}push(e){this.items.push(e),this.live.add(e)}remove(e){this.live.delete(e)&&this.compact()}shift(){for(;this.head<this.items.length;){let e=this.items[this.head];if(this.items[this.head++]=void 0,e&&this.live.delete(e))return this.compact(),e}}compact(){if(this.live.size===0){this.items=[],this.head=0;return}let e=this.items.length-this.live.size;e<=64||e<=this.live.size||(this.items=this.items.filter(e=>e!==void 0&&this.live.has(e)),this.head=0)}};function Oe(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var V=class{executor;baseConfig;mode;maxConcurrent;maxQueueDepth;queueWaitMs;timeoutMs;retry;cacheEnabled;cacheMaxBytes;cacheTtl;cacheErroredSolves;cache=new Map;cacheBytes=0;cacheHits=0;cacheMisses=0;cacheEvictions=0;reuseServerDefinitionCache;serverCacheKeys=new Map;lastStringDefinition=null;onStart;onSettle;onSuperseded;subscribers=new Set;inFlight=new Set;pendingForLatestWins=null;fifo=new De;_lastResult=null;_lastError=null;_lastDurationMs=null;solveSeq=0;lastStateSeq=0;disposed=!1;constructor(t,n,r={}){if(this.executor=t,this.baseConfig=n,this.mode=r.mode??`latest-wins`,this.mode!==`latest-wins`&&this.mode!==`queue`)throw new e.D(`Unknown scheduler mode '${String(this.mode)}'. For concurrent solves use { mode: 'queue', maxConcurrent: 4 }.`,e.O.INVALID_CONFIG,{context:{mode:this.mode}});this.maxConcurrent=Math.max(1,r.maxConcurrent??1),this.maxQueueDepth=r.maxQueueDepth!==void 0&&r.maxQueueDepth>0?Math.floor(r.maxQueueDepth):void 0,this.queueWaitMs=r.queueWaitMs!==void 0&&r.queueWaitMs>0?r.queueWaitMs:void 0,this.timeoutMs=r.timeoutMs,this.retry=r.retry;let i=r.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.reuseServerDefinitionCache??!0,this.onStart=r.onStart,this.onSettle=r.onSettle,this.onSuperseded=r.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifo.size>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifo.size+ +!!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.T().error(`[SolveScheduler] subscriber threw:`,t)}}solve(e,t,n){return this.solveDetailed(e,t,n).then(e=>e.response)}solveDetailed(t,n,r){if(this.disposed)return Promise.reject(new e.D(`SolveScheduler has been disposed and cannot be used`,e.O.INVALID_STATE));let i=new Ee(()=>this.hashDefinitionMemo(t),n),a=``;if(this.cacheEnabled||this.onStart||this.onSettle||this.onSuperseded)try{a=i.key}catch(t){return Promise.reject(new e.D(`Solve input could not be hashed`,e.O.INVALID_INPUT,{originalError:t}))}let o=++this.solveSeq,s={key:a,enqueuedAt:Date.now(),startedAt:null};if(r?.signal?.aborted)return Promise.reject(this.makeAbortError(s));let c=this.readCache(a);if(c){this.mode===`latest-wins`&&this.supersedeCurrent();let e={status:`success`,response:c,durationMs:0,fromCache:!0};return this.writeLastState(o,{result:c,durationMs:0}),this.runHook(this.onStart,s),this.runHook(this.onSettle,s,e),this.notify(),Promise.resolve({response:c,fromCache:!0,durationMs:0})}return new Promise((e,a)=>{let c={definition:t,dataTree:n,hashes:i,ctx:s,seq:o,resolve:e,reject:a,externalSignal:r?.signal,selvaevents:r?.selvaevents,onServerTiming:r?.onServerTiming};c.externalSignal&&(c.queuedAbortHandler=()=>this.abortQueuedItem(c),c.externalSignal.addEventListener(`abort`,c.queuedAbortHandler,{once:!0})),this.enqueue(c)})}writeLastState(e,t){e<this.lastStateSeq||(this.lastStateSeq=e,`result`in t?(this._lastResult=t.result,this._lastError=null):this._lastError=t.error,this._lastDurationMs=t.durationMs)}supersedeCurrent(){this.pendingForLatestWins&&=(this.supersede(this.pendingForLatestWins),null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}dequeue(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null),this.fifo.remove(e)}abortQueuedItem(e){this.dequeue(e),this.fail(e,this.makeAbortError(e.ctx)),this.notify()}shedAsQueueFull(t){let n=new e.D(`Solve queue is full; request rejected (backpressure)`,e.O.QUEUE_FULL,{statusCode:503,context:{queueDepth:this.fifo.size,maxQueueDepth:this.maxQueueDepth}});this.fail(t,n),this.notify()}armQueueWaitTimer(t){if(this.queueWaitMs===void 0)return;let n=this.queueWaitMs;t.queueWaitTimer=setTimeout(()=>{if(t.settled)return;this.dequeue(t);let r=new e.D(`Solve waited longer than ${n}ms in queue; rejected (backpressure)`,e.O.QUEUE_TIMEOUT,{statusCode:503,context:{waitedMs:Date.now()-t.ctx.enqueuedAt,queueWaitMs:n}});this.fail(t,r),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`:this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifo.size>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifo.push(e))}this.notify()}async execute(e){let t=new AbortController,n=e;n.controller=t,this.inFlight.add(n),e.ctx.startedAt=Date.now(),this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e);let r=()=>t.abort();e.externalSignal?.addEventListener(`abort`,r,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let i=performance.now();try{let n={...this.baseConfig,signal:t.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry},...e.selvaevents!==void 0&&{selvaevents:e.selvaevents}},r=e.onServerTiming;if(r){let e=this.baseConfig.onServerTiming;n.onServerTiming=(t,n)=>{try{e?.(t,n)}finally{r(t,n)}}}let{response:a,definitionReuploaded:o}=await this.runExecutor(e,n),s=performance.now()-i;if(this.writeCache(e.ctx.key,a),!this.settleSuccess(e,{response:a,fromCache:!1,definitionReuploaded:o,durationMs:s}))return;this.writeLastState(e.seq,{result:a,durationMs:s}),this.runHook(this.onSettle,e.ctx,{status:`success`,response:a,durationMs:s,fromCache:!1,definitionReuploaded:o})}catch(t){let r=performance.now()-i,a=this.normalizeExecutionError(t,n);this.writeLastState(e.seq,{error:a,durationMs:r}),this.fail(e,a,r)}finally{e.externalSignal?.removeEventListener(`abort`,r),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(t,n){let{definition:r,dataTree:i}=t;if(!this.reuseServerDefinitionCache||e.c(r)){let{response:e}=await this.executor(r,i,null,n);return{response:e}}let a=t.hashes.definitionHash,o=this.serverCacheKeys.get(a)??null,s=await this.executor(r,i,o,n);return this.serverCacheKeys.delete(a),s.cacheKey&&(this.serverCacheKeys.set(a,s.cacheKey),this.serverCacheKeys.size>100&&this.serverCacheKeys.delete(this.serverCacheKeys.keys().next().value)),{response:s.response,definitionReuploaded:s.missed}}hashDefinitionMemo(e){return typeof e==`string`?(this.lastStringDefinition?.value!==e&&(this.lastStringDefinition={value:e,hash:z(e)}),this.lastStringDefinition.hash):Te(e)}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.fifo.size>0&&this.inFlight.size<this.maxConcurrent;)this.execute(this.fifo.shift())}}supersede(t){let n=new e.D(`Superseded by newer solve`,e.O.SUPERSEDED,{context:{enqueuedAt:t.ctx.enqueuedAt}});this.settleError(t,n)&&this.runHook(this.onSuperseded,t.ctx)}makeAbortError(t){return new e.D(`Request aborted by caller`,e.O.ABORTED,{context:{enqueuedAt:t.enqueuedAt}})}settleError(e,t){return!e.settled&&(e.settled={error:t},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(t),!0)}fail(e,t,n=0){this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:n})}settleSuccess(e,t){return!e.settled&&(e.settled={ok:!0},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.resolve(t),!0)}removeQueuedAbortHandler(e){e.queuedAbortHandler&&e.externalSignal&&e.externalSignal.removeEventListener(`abort`,e.queuedAbortHandler),e.queuedAbortHandler=void 0}normalizeExecutionError(t,n){return n.settled&&`error`in n.settled?n.settled.error:t instanceof e.D?t:t instanceof Error&&t.name===`AbortError`?this.makeAbortError(n.ctx):new e.D(t instanceof Error?t.message:String(t),e.O.UNKNOWN_ERROR,{originalError:t})}cancelAll(){this.pendingForLatestWins&&=(this.fail(this.pendingForLatestWins,this.makeAbortError(this.pendingForLatestWins.ctx)),null);for(let e=this.fifo.shift();e;e=this.fifo.shift())this.fail(e,this.makeAbortError(e.ctx));for(let e of this.inFlight){let t=e.ctx.startedAt?Date.now()-e.ctx.startedAt:0;this.fail(e,this.makeAbortError(e.ctx),t),e.controller.abort()}this.notify()}readCache(e){if(!this.cacheEnabled)return null;let t=this.cache.get(e);return t?this.cacheTtl>0&&Date.now()-t.insertedAt>this.cacheTtl?(this.dropCacheEntry(e),this.cacheMisses+=1,null):(this.cache.delete(e),this.cache.set(e,t),this.cacheHits+=1,t.response):(this.cacheMisses+=1,null)}writeCache(t,n){if(!this.cacheEnabled)return;let r=e.C(n,`errors`);if(!this.cacheErroredSolves&&Array.isArray(r)&&r.length>0)return;let i=e.f(n)??Oe(n);if(!(i>this.cacheMaxBytes))for(this.dropCacheEntry(t),this.cache.set(t,{response:n,insertedAt:Date.now(),sizeBytes:i}),this.cacheBytes+=i;this.cacheBytes>this.cacheMaxBytes&&this.cache.size>0;){let e=this.cache.keys().next().value;if(e===void 0)break;this.dropCacheEntry(e),this.cacheEvictions+=1}}dropCacheEntry(e){let t=this.cache.get(e);t&&(this.cache.delete(e),this.cacheBytes-=t.sizeBytes)}clearCache(){this.cache.clear(),this.cacheBytes=0}cacheStats(){return{entries:this.cache.size,bytes:this.cacheBytes,hits:this.cacheHits,misses:this.cacheMisses,evictions:this.cacheEvictions}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(t,...n){if(t)try{t(...n)}catch(t){e.T().error(`[SolveScheduler] hook threw:`,t)}}};function H(t){return e.s(t)?`ref:${t.key}`:typeof t==`string`&&t.length<200?t:`...content...`}function U(t){return Array.isArray(t)?t.map(t=>{let n=0,r=0,i=e.C(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.C(t,`paramName`)??`<unnamed>`,items:n,bytes:r}}):[]}var ke=class n{config;serverStats;disposed=!1;static CREATE_PROBE_TIMEOUT_MS=2e3;constructor(n){this.config={...n,serverUrl:e.x(n.serverUrl),debug:n.debug??!1},this.serverStats=new t(this.config.serverUrl,this.config)}static async create(t,r={}){let i=new n(t),a=Math.max(1,(r.probe?.attempts??2)+1),o=r.probe?.baseDelayMs??250,s=r.probe?.maxDelayMs??1e3,c,l=null,u=0;for(let t=0;t<a;t++){if(u=t+1,c=await i.serverStats.probeServer(n.CREATE_PROBE_TIMEOUT_MS),c.online)return i;if(l=e.u(c),l&&!l.retryable)break;if(t<a-1){let e=Math.min(o*2**t,s);await new Promise(t=>setTimeout(t,e))}}await i.dispose();let d=c?.status,f=l?`Rhino Compute server is not available. ${l.summary}`:`Rhino Compute server is not online`;throw new e.D(f,e.O.NETWORK_ERROR,{...d!==void 0&&{statusCode:d},context:{serverUrl:i.config.serverUrl,attempts:u,maxAttempts:a,...l&&{probeVerdict:l.verdict,probeRetryable:l.retryable},...d!==void 0&&{lastProbeStatus:d},...c?.error!==void 0&&{lastProbeError:c.error}}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),P(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),M(e,this.config)}async solve(t,n,r){this.ensureNotDisposed();try{if(typeof t==`string`&&!t.trim())throw new e.D(`Definition URL/content is required`,e.O.INVALID_INPUT,{context:{receivedUrl:t}});if(t instanceof Uint8Array&&t.length===0)throw new e.D(`Definition content is empty`,e.O.INVALID_INPUT);if(e.s(t)&&!t.key.trim())throw new e.D(`DefinitionRef key is empty`,e.O.INVALID_INPUT);let i=await u(n,t,{...this.config,...r?.signal!==void 0&&{signal:r.signal},...r?.timeoutMs!==void 0&&{timeoutMs:r.timeoutMs},...r?.retry!==void 0&&{retry:r.retry},...r?.selvaevents!==void 0&&{selvaevents:r.selvaevents}}),a=e.C(i,`errors`);if(Array.isArray(a)&&a.length>0)throw new e.D(a.map(String).join(`; `)||`Computation failed`,e.O.COMPUTATION_ERROR,{context:{definition:H(t),inputSummary:U(n),errors:a,warnings:e.C(i,`warnings`),values:i.values}});return i}catch(r){throw this.config.debug&&e.T().error(`Compute failed:`,r),r instanceof e.D?r:new e.D(r instanceof Error?r.message:String(r),e.O.COMPUTATION_ERROR,{context:{definition:H(t),inputSummary:U(n)},originalError:r})}}createScheduler(e){return this.ensureNotDisposed(),new V((e,t,n,r)=>d(t,n,e,r),this.config,e)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new e.D(`GrasshopperClient has been disposed and cannot be used`,e.O.INVALID_STATE)}};function Ae(e){return typeof e==`object`&&!!e&&e.__decodeError===!0}function W(e,t){return{__decodeError:!0,type:e,raw:t}}function G(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=new Map([[`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}],[`Rhino.Geometry.Line`,(e,t)=>{let n=t;return!n||!n.From||!n.To?null:new e.Line([n.From.X,n.From.Y,n.From.Z],[n.To.X,n.To.Y,n.To.Z])}]]);function je(e){if(K.has(e))return K.get(e);for(let[t,n]of K)if(e.startsWith(t))return n}function Me(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function Ne(t,n,r){let i=je(n),a=!1;if(i)try{let e=i(r,t);if(e!=null)return e}catch(t){e.T().warn(`Failed to decode Rhino type ${n}:`,t),a=!0}try{if(Me(t))return r.CommonObject.decode(t)}catch(r){return e.T().warn(`Failed to decode ${n} with CommonObject:`,r),W(n,t)}return a?W(n,t):t}const q={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},J=`FileData`;function Y(e,t){return e.includes(`WebDisplay`)||t&&e!==q.STRING}function Pe(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 Fe(e,t,n){switch(t){case q.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case q.INT:return Number.parseInt(String(e),10);case q.DOUBLE:return Number.parseFloat(String(e));case q.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?Ne(e,t,n):e}}function Ie(e,t,n,r){if(typeof e.data!=`string`)return e.data;let i=n?Pe(e.data):e.data;return n&&t.includes(J)?Le(i)??i:Fe(i,t,r)}function Le(t){if(!t||typeof t!=`object`)return null;let n=e.C(t,`fileName`),r=e.C(t,`fileType`),i=e.C(t,`subFolder`),a=e.C(t,`isBase64Encoded`);if(typeof n!=`string`||typeof r!=`string`||typeof i!=`string`||!e.S(t,`data`)||typeof a!=`boolean`&&typeof a!=`string`)return null;let o=e.C(t,`metadata`);return{fileName:n,fileType:r,data:e.C(t,`data`),isBase64Encoded:e.i(a),subFolder:i,...o?{metadata:o}:{}}}function X(t){let n=e.C(t,`values`);return Array.isArray(n)?n:[]}function Z(e){return typeof e.type==`string`?e.type:``}function Q(e,t){if(e&&typeof e==`object`){for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)e&&typeof e==`object`&&t(e)}}function Re(t,n=!1,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r,s={},c=new Set;for(let r of X(t)){let t=e.C(r,`paramName`);Q(e.C(r,`innerTree`),e=>{let r=Z(e);if(Y(r,o))return;let l=n?e.id:t;if(!l)return;let u=Ie(e,r,i,a);Object.prototype.hasOwnProperty.call(s,l)?c.has(l)?s[l].push(u):(s[l]=[s[l],u],c.add(l)):g(s,l,u)})}return{values:s,dispose:()=>G(s)}}function ze(t){let n=[];for(let r of X(t))Q(e.C(r,`innerTree`),e=>{if(!Z(e).includes(J))return;let t=Le(Pe(e.data));t&&n.push(t)});return n}function Be(t,n,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r;for(let r of X(t)){let t=e.C(r,`innerTree`),s=!1;if(`byName`in n){if(e.C(r,`paramName`)!==n.byName)continue;s=!0}let c=[];if(Q(t,e=>{if(`byId`in n){if(e.id!==n.byId)return;s=!0}let t=Z(e);Y(t,o)||c.push(Ie(e,t,i,a))}),s)return c.length===0?void 0:c.length===1?c[0]:c}}var Ve=class{response;constructor(e){this.response=e}getValues(e=!1,t={}){return Re(this.response,e,t)}getValue(e,t){return Be(this.response,e,t)}async getAndDownloadFiles(t,n){await e.t(ze(this.response),t,n)}};function He(t){return(Array.isArray(t)?t:[t]).map(t=>({schemas:e.C(t,`schemas`),error:e.C(t,`error`)}))}const Ue=new Set([`options`,`defaultOptions`,`values`]),We=new Set([`optionMedia`,`assets`]),Ge=e=>e>=`A`&&e<=`Z`;function Ke(e){if(e.length===0||!Ge(e[0]))return e;let t=0;for(;t<e.length&&Ge(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function qe(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=Ke(n);g(t,e,Ue.has(e)?r:We.has(e)?Je(r):$(r))}return t}function Je(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t={};for(let[n,r]of Object.entries(e))g(t,n,$(r));return t}var Ye=class t{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(e,n){let r=this.innerTree[t.formatPathString(e)]??=[];for(let e of n)r.push({data:t.serializeValue(e)});return this}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}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getParamName(){return this.paramName}static fromInputParams(e){return t.fromValues(e.map(e=>({paramName:e.nickname||`unnamed`,paramType:e.paramType,value:e.default,...`minimum`in e&&{minimum:e.minimum,maximum:e.maximum}})))}static fromValues(n){let r=[];for(let i of n){let n=new t(i.paramName),a=t.itemCoercer(i);for(let[r,o]of t.branchesOf(i.value)){let t=[];for(let n of o){if(n==null)continue;let r=a(n);r===null?e.T().warn(`${i.paramName}: dropped an item that is not a valid ${i.paramType}`):t.push(r)}t.length>0&&n.append(r,t)}Object.keys(n.innerTree).length>0&&r.push(n.toComputeFormat())}return r}static branchesOf(e){return t.hasValidValue(e)?v(e)?Object.entries(e).map(([e,n])=>[t.parsePathString(e),n]):[[[0],Array.isArray(e)?e:[e]]]:[]}static itemCoercer(e){let{paramName:n,minimum:r,maximum:i}=e,a=e.paramType.toLowerCase();return a===`number`||a===`integer`?e=>{let o=b(e);if(o===null)return null;let s=a===`integer`?Math.round(o):o;return t.clampValue(s,r,i,n)}:a===`boolean`?x:e=>e}static replaceTreeValue(e,n,r){let i=t.buildFromValue(n,r).toComputeFormat(),a=e.slice(),o=a.findIndex(e=>t.paramNameOf(e)===n);return o===-1?a.push(i):a[o]=i,a}static buildFromValue(e,n){let r=new t(e);return v(n)?r.fromDataTreeDefault(n):r.appendFlat(n),r}static getTree(n,r){let i=n.find(e=>t.paramNameOf(e)===r);if(!i)return null;let a=new Map,o=e.C(i,`InnerTree`);if(!o||typeof o!=`object`)return a;for(let[e,n]of Object.entries(o))Array.isArray(n)&&a.set(e,n.map(e=>e?.data===void 0?null:t.deserializeValue(e.data)));return a}static getTreeValue(n,r){let i=t.getTree(n,r);if(!i||i.size===0)return null;if(i.size>1)throw new e.D(`"${r}" has ${i.size} branches; read it with TreeBuilder.getTree`,e.O.INVALID_INPUT,{context:{paramName:r,branchCount:i.size}});let[a]=i.values();return a.length===0?null:a.length===1?a[0]:a}static paramNameOf(t){return e.C(t,`ParamName`)}static parsePathString(t){let n=t.match(_);if(!n)throw new e.D(`Invalid Grasshopper tree path: "${t}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`,e.O.INVALID_INPUT,{context:{pathStr:t}});return n[1]?n[1].split(`;`).map(Number):[]}static formatPathString(e){return`{${e.join(`;`)}}`}static serializeValue(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`?e:typeof e==`object`&&e?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e!=`string`)return e;if(e.startsWith(`{`)||e.startsWith(`[`))try{return JSON.parse(e)}catch{return e}let t=Number(e);return Number.isFinite(t)&&String(t)===e?t:e===`true`||e!==`false`&&e}static hasValidValue(e){return e==null?!1:typeof e==`string`||!(Array.isArray(e)&&e.length===0||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0)}static clampValue(t,n,r,i){let a=t;return n!=null&&a<n&&(e.T().warn(`${i}: ${t} below min ${n}, clamping`),a=n),r!=null&&a>r&&(e.T().warn(`${i}: ${t} above max ${r}, clamping`),a=r),a}};exports.ComputeServerStats=t,exports.GrasshopperClient=ke,exports.GrasshopperResponseProcessor=Ve,exports.SolveScheduler=V,exports.TreeBuilder=Ye,exports.disposeRhinoObjects=G,exports.fetchDefinitionIO=M,exports.fetchParsedDefinitionIO=P,exports.hashDefinition=z,exports.hashSolveInput=we,exports.isRhinoDecodeError=Ae,exports.normalizeUISchemaCasing=qe,exports.processInput=ge,exports.readSchemaResults=He,exports.solveGrasshopperDefinition=u,exports.stableStringify=L;
2
2
  //# sourceMappingURL=grasshopper.cjs.map
@@ -1,4 +1,4 @@
1
- import { D as ComputeAuth, M as ComputeError, O as ComputeConfig, _ as SolveDefinition, j as ServerTiming, k as RetryPolicy, s as FileBaseInfo } from "./index-cMvSohkf.cjs";
1
+ import { D as ComputeAuth, M as ComputeError, O as ComputeConfig, _ as SolveDefinition, j as ServerTiming, k as RetryPolicy, s as FileBaseInfo } from "./index-DdWRS7rh.cjs";
2
2
  //#region src/grasshopper/server/compute-server-stats.d.ts
3
3
  interface ServerVersion {
4
4
  rhino: string;
@@ -1,4 +1,4 @@
1
- import { D as ComputeAuth, M as ComputeError, O as ComputeConfig, _ as SolveDefinition, j as ServerTiming, k as RetryPolicy, s as FileBaseInfo } from "./index-cMvSohkf.js";
1
+ import { D as ComputeAuth, M as ComputeError, O as ComputeConfig, _ as SolveDefinition, j as ServerTiming, k as RetryPolicy, s as FileBaseInfo } from "./index-DdWRS7rh.js";
2
2
  //#region src/grasshopper/server/compute-server-stats.d.ts
3
3
  interface ServerVersion {
4
4
  rhino: string;
@@ -1,2 +1,2 @@
1
- import{C as e,D as t,O as n,S as r,T as i,_ as a,c as o,d as s,f as c,h as l,i as u,l as d,m as f,p,s as m,t as ee,u as te,v as ne,x as h,y as re}from"./core-CFlbOj2M.js";var g=class e{serverUrl;headers;disposed=!1;activeMonitors=new Set;static DEFAULT_TIMEOUT_MS=5e3;static LIFECYCLE_TIMEOUT_MS=6e4;static MIN_MONITOR_INTERVAL_MS=100;static MAX_BODY_BYTES=1<<20;constructor(e,t){this.serverUrl=h(e),this.headers={...re(typeof t==`string`?{apiKey:t}:t??{}),"Content-Type":`application/json`}}fetchWithTimeout(t,n={},r=e.DEFAULT_TIMEOUT_MS){let i={...n,headers:this.headers,redirect:`manual`};return r>0&&!i.signal&&(i.signal=AbortSignal.timeout(r)),fetch(t,i)}async getText(t,n={},r=e.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let a=`${n.method??`GET`} ${t}`;try{let o=await this.fetchWithTimeout(`${this.serverUrl}${t}`,n,r);if(!o.ok)return i().warn(`[ComputeServerStats] ${a} failed:`,o.status),await o.body?.cancel().catch(()=>{}),null;let{text:s,truncated:c}=await f(o,e.MAX_BODY_BYTES);return c?(i().warn(`[ComputeServerStats] ${a} answered with an oversized body`),null):s}catch(e){return i().warn(`[ComputeServerStats] ${a} errored:`,e),null}}async isServerOnline(t=e.DEFAULT_TIMEOUT_MS){return(await this.probeServer(t)).online}async probeServer(t=e.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let n=`${this.serverUrl}/`;try{let e=await this.fetchWithTimeout(n,{method:`GET`},t);return await e.body?.cancel().catch(()=>{}),{online:e.ok||s(e),status:e.status}}catch(e){return i().debug(`[ComputeServerStats] Fetch error:`,e),{online:!1,error:e instanceof Error?`${e.name}: ${e.message}`:String(e)}}}async getActiveChildren(t={}){let{initialize:n=!0}=t,r=n?await this.getText(`/activechildren`,{},e.LIFECYCLE_TIMEOUT_MS):await this.getText(`/activechildren?initialize=false`);if(r===null)return null;let a=r.trim();return/^\d+$/.test(a)?parseInt(a,10):(i().warn(`[ComputeServerStats] /activechildren answered with a non-numeric body`),null)}async getVersion(){let e=await this.getText(`/version`);if(e===null)return null;let t=_(e);return t==null?{rhino:e,compute:``,git_sha:null}:{rhino:t.rhino??``,compute:t.compute??``,git_sha:t.git_sha??null}}async getInstalledPlugins(e=`gh`){let t=await this.getText(`/plugins/${e}/installed`),n=t===null?void 0:_(t);return n&&typeof n==`object`?n:null}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[e,t]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...e&&{version:e},...t!==null&&{activeChildren:t}}}async purgeCache(){let e=await this.getText(`/cache/purge`,{method:`POST`}),t=(e===null?void 0:_(e))?.purged;return typeof t==`number`?t:null}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return i().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(){let e=await this.getText(`/servertime`);if(e===null)return null;let t=new Date(e.trim().replace(/^"|"$/g,``));return isNaN(t.getTime())?null:t}async getIdleSpan(){let e=await this.getText(`/idlespan`);if(e===null)return null;let t=parseFloat(e.trim());return isNaN(t)?null:t}async launchChildren(){return this.postJson(`/launch-children`)}async launchChild(e){let t=e===void 0?`/launch-child`:`/launch-child?port=${e}`;return this.postJson(t)}async shutdownChildren(e){let t=e===void 0?`/shutdown-children`:`/shutdown-children?port=${e}`;return this.postJson(t)}async recycleChildren(e){let t=e===void 0?`/recycle-children`:`/recycle-children?port=${e}`;return this.postJson(t)}async postJson(t){let n=await this.getText(t,{method:`POST`},e.LIFECYCLE_TIMEOUT_MS);return n===null?null:_(n)??null}monitor(r,a=5e3){if(this.ensureNotDisposed(),!Number.isFinite(a)||a<e.MIN_MONITOR_INTERVAL_MS)throw new t(`monitor() intervalMs must be a finite number >= ${e.MIN_MONITOR_INTERVAL_MS}ms, got ${a}. Sub-${e.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`,n.INVALID_CONFIG,{context:{intervalMs:a}});let o=!0,s=null;i().info(`🔄 Starting server stats monitoring every ${a}ms`);let c=async()=>{if(s=null,o&&!this.disposed){try{let e=await this.getServerStats();if(!o||this.disposed)return;try{r(e)}catch(e){i().error(`[ComputeServerStats] Monitor callback threw:`,e)}}catch(e){!o||this.disposed?i().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,e):i().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,e)}o&&!this.disposed&&(s=setTimeout(()=>void c(),a))}},l=()=>{o=!1,s!==null&&(clearTimeout(s),s=null),this.activeMonitors.delete(l)};return this.activeMonitors.add(l),c(),l}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear()}}ensureNotDisposed(){if(this.disposed)throw new t(`ComputeServerStats has been disposed and cannot be used`,n.INVALID_STATE)}};function _(e){try{return JSON.parse(e)}catch{return}}const v=new Set;function ie(){if(typeof window>`u`||globalThis.process?.versions?.node!=null)return!1;let e=globalThis.navigator,t=typeof e?.userAgent==`string`?e.userAgent:``;return!/jsdom/i.test(t)}function y(e,t){t||ie()&&!v.has(e)&&(v.add(e),i().warn(`Warning: ${e} is running on the client side. For better performance and security, consider running this on the server side.`))}const ae={definition_not_cached:n.DEFINITION_NOT_CACHED};function oe(e){return{...e,serverErrorCodes:{...ae,...e.serverErrorCodes}}}function se(e){return e instanceof t?e.code===n.DEFINITION_NOT_CACHED||e.message.includes(`Unable to load grasshopper definition`):!1}function ce(t,n){if(!n)return;let r=e(t,`values`);if(!Array.isArray(r)||r.length===0)return;let a=[];for(let t of r){let n=e(t,`innerTree`);(!n||Object.keys(n).length===0)&&a.push(e(t,`paramName`)??`<unnamed>`)}if(a.length===0)return;let o=a.length===r.length?`all`:`${a.length}/${r.length}`;i().warn(`Solve returned empty output(s) (${o}): ${a.join(`, `)}. These parameters produced no data — check the definition's inputs and the branch feeding each.`)}async function le(e,t,n){return y(`solveGrasshopperDefinition`,n.suppressBrowserWarning),(await de(e,t,n)).response}async function ue(e,t,n,r){if(y(`solveWithServerCacheKey`,r.suppressBrowserWarning),t!==null)try{return{...await pe({algo:null,pointer:t,values:e},r),missed:!1}}catch(e){if(!se(e))throw e}return{...await de(e,n,r),missed:!0}}async function de(e,t,n){return pe(b(await fe(t),e),n)}async function fe(e){if(!m(e))return e;try{return await e.load()}catch(r){throw new t(`Failed to load definition bytes for ref '${e.key}'`,n.INVALID_INPUT,{context:{definitionKey:e.key},originalError:r})}}async function pe(e,t){h(t.serverUrl),me(e,t);let{maxResponseBytes:n}=t,r=await d(`grasshopper`,e,oe({...t,maxResponseBytes:n!==void 0&&e.algo?n+e.algo.length:n})),{pointer:i,algo:a,...o}=r,s=o,l=c(r);if(l!==void 0){let e=typeof a==`string`?a.length:0;p(s,Math.max(0,l-e))}return ce(s,t.debug),{response:s,cacheKey:typeof i==`string`?i:null}}function b(e,t){let n={algo:null,pointer:null,values:t};return e instanceof Uint8Array?n.algo=l(e):o(e)?n.pointer=e:n.algo=a(e)??ne(e),n}function me(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 x(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}const S=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function C(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>S.test(e)&&Array.isArray(t))}function w(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 T=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},E=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 D(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:(i().warn(`Parsed value for input ${e} is not an object`),null)}catch(n){return i().warn(`Failed to parse object value "${t}" for input ${e}`,n),null}return null}}const _e=new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),ve=new Set([`System.Int32`,`System.Int64`]);function O(e,t){return i().warn(t),{schema:{...e,default:null},warning:{code:n.MALFORMED_DEFAULT,message:t}}}function ye(t,a){if(typeof t.default!=`object`||t.default===null||Array.isArray(t.default)||C(t.default))return{schema:t};if(!r(t.default,`innerTree`))return O(t,`Input "${a}" default had an unrecognized shape (no innerTree key); the default was dropped.`);let o=e(t.default,`innerTree`)??{};if(Object.keys(o).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let r={},s=[];for(let[n,i]of Object.entries(o)){if(!Array.isArray(i))return O(t,`Input "${a}" default had a non-array innerTree branch ("${n}"); the default was dropped.`);let o=[];for(let t of i){let n=e(t,`data`),r=e(t,`type`);if(r&&_e.has(r)){if(typeof n==`string`&&n.trim()===``)continue;let e=T(n);if(e===null){s.push(`"${String(n)}" (${r})`);continue}o.push(ve.has(r)?Math.round(e):e);continue}if(r===`System.Boolean`){let e=E(n);if(e===null){s.push(`"${String(n)}" (${r})`);continue}o.push(e);continue}if(typeof n==`string`&&r?.startsWith(`Rhino.Geometry`)){try{o.push(JSON.parse(n))}catch{o.push(n)}continue}o.push(n)}x(r,n,o)}if(s.length>0){let e=`Input "${a}" default contained ${s.length} tree value(s) that could not be parsed and were dropped: ${s.join(`, `)}.`;return i().warn(e),{schema:{...t,default:r},warning:{code:n.MALFORMED_DEFAULT,message:e}}}return{schema:{...t,default:r}}}let s=[];for(let t of Object.values(o))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&r(n,`data`)&&s.push(e(n,`data`));return{schema:{...t,default:s.length>1?s:s[0]}}}function be(e,t){let n=Number(e.toFixed(t));return Math.abs(e-n)<1e-8?n:e}function k(e){if(!Number.isFinite(e))return 0;let[t,n]=String(Math.abs(e)).split(`e`),r=n===void 0?Math.abs(e).toFixed(12).replace(/0+$/,``).split(`.`)[1]?.length??0:(t.split(`.`)[1]?.length??0)-Number(n);return Math.min(Math.max(r,0),12)}function xe(e){if(!Number.isFinite(e)||e===0)return .1;let t=k(e);return t===0?Math.abs(e)>=1?1:.1:Number((10**-t).toFixed(t))}function A(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}const j=(e,t)=>(e.atMost??1)>1?[t]:t,M=e=>A(e)??(e.paramType===`Integer`?1:.1),N=(e,t)=>Array.isArray(e)?e.map(e=>typeof e==`number`?t(e):e):typeof e==`number`?t(e):e;function Se(e){if(C(e.default))return{default:e.default,stepSize:M(e)};if(typeof e.default==`string`&&e.default.trim()!==``&&T(e.default)===null)throw new t(`Invalid numeric default "${e.default}" for input "${e.name||`unknown`}"`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});let r=w(e.default,T,!0);if(e.paramType===`Integer`)return{default:N(r,Math.round),stepSize:M(e)};let i=Array.isArray(r)?r[0]:r,a=[i,e.minimum,e.maximum].find(e=>typeof e==`number`&&Number.isFinite(e)&&e!==0),o=A(e)??(a===void 0?.1:xe(a)),s=k(o);if(s===0&&typeof i==`number`&&i!==0&&Math.abs(i)<1){let e=Math.ceil(-Math.log10(Math.abs(i)));Number.isFinite(e)&&e>0&&(s=e)}return s=Math.min(Math.max(s,0),12),{default:N(r,e=>be(e,s)),stepSize:o}}const P={parse(e,t){let{default:n,stepSize:r}=Se(e);return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:r,default:n}},fallback(e,t){let n=typeof e.minimum==`number`&&Number.isFinite(e.minimum)&&e.minimum>0?e.minimum:0;return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:M(e),default:j(e,n)}}},Ce={parse(e,r){if(C(e.default))return{...r,paramType:`Boolean`,default:e.default};let i=w(e.default,E,!1);if(i!=null&&typeof i!=`boolean`&&!Array.isArray(i))throw new t(`Invalid boolean default "${String(i)}" for input "${e.name||`unknown`}"`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});return{...r,paramType:`Boolean`,default:i}},fallback(e,t){return{...t,paramType:`Boolean`,default:j(e,!1)}}},we={parse(e,t){let n=w(e.default,he,!1);return{...t,paramType:`Text`,default:n}}},Te={parse(e,r,a){if(!e.values||typeof e.values!=`object`||Object.keys(e.values).length===0){let r=e.nickname||`unnamed`;throw new t(`Input "${r}" has no values defined (expected ValueList)`,n.INVALID_INPUT,{context:{inputName:r,expectedType:`ValueList`}})}let o=e.default;if(e.default!==void 0&&e.default!==null){if(typeof e.default==`object`)throw new t(`ValueList input "${e.nickname||`unnamed`}" default is not a string-able value`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});let r=String(e.default).toLowerCase(),s=Object.keys(e.values).find(e=>e.toLowerCase()===r);if(s!==void 0)o=s;else{let t=`ValueList input "${e.nickname||`unnamed`}" default value "${e.default}" is not in available values`;i().warn(t),a?.({code:n.VALIDATION_ERROR,message:t})}}return{...r,paramType:`ValueList`,values:e.values,default:o}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}};function F(e,t){return{...t,paramType:`Geometry`,default:j(e,null)}}const I=new Map([[`Number`,P],[`Integer`,P],[`Boolean`,Ce],[`Text`,we],[`ValueList`,Te],[`Geometry`,{parse(e,t){let n=w(e.default,D(e.nickname||`unnamed`),!0);return{...t,paramType:`Geometry`,default:n}},fallback:F}],[`File`,{parse(e,t){let n=w(e.default,D(e.nickname||`unnamed`),!0);return{...t,paramType:`File`,acceptedFormats:e.acceptedFormats,default:n}}}],[`Color`,{parse(e,t){let n=w(e.default,ge,!1);return{...t,paramType:`Color`,default:n}}}]]),Ee=F,De=new Map([...I.keys()].map(e=>[e.toLowerCase(),e]));function Oe(e){return De.get(e?.toLowerCase())??e}function ke(e){return L(e).input}function L(e){let r=e.name||`unknown`,a=[],o=({code:t,message:n})=>{a.push({inputName:r,paramType:e.paramType,message:n,code:t})},s={description:e.description,name:e.name,nickname:e.nickname,treeAccess:e.treeAccess,groupName:e.groupName??void 0,id:e.id},c=Oe(e.paramType),l={...e,paramType:c};try{let{schema:e,warning:t}=ye(l,r);l=e,t&&o(t)}catch(e){l={...l,default:null},o({code:n.MALFORMED_DEFAULT,message:`Input "${r}" default could not be normalized and was dropped: ${e instanceof Error?e.message:String(e)}`})}let u=I.get(c);try{if(!u)throw new t(`Unknown paramType: ${c}`,n.VALIDATION_ERROR,{context:{receivedParamType:c,paramName:e.name}});return{input:u.parse(l,s,o),errors:a}}catch(d){if(!(d instanceof t))throw new t(d instanceof Error?d.message:String(d),n.VALIDATION_ERROR,{context:{paramName:e.name,paramType:c},originalError:d});return i().error(`Validation error for input ${r}:`,d.message),o(d),{input:(u?.fallback??Ee)(l,s),errors:a}}}function Ae(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=L(r);t.push(e),n.push(...i)}return{inputs:t,parseErrors:n}}function je(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 Me(t){return{name:e(t,`name`)??``,nickname:e(t,`nickname`)??null,paramType:e(t,`paramType`)??``,id:e(t,`id`)??``}}async function R(r,i){y(`fetchDefinitionIO`,i.suppressBrowserWarning),h(i.serverUrl);let{algo:a,pointer:o}=b(r,[]);if(!a&&!o)throw new t(`Definition must resolve to either a URL pointer or base64 algo`,n.INVALID_INPUT);let s=await d(`io`,a?{algo:a}:{pointer:o},oe(i));if(!s||typeof s!=`object`)throw new t(`Invalid IO response structure`,n.INVALID_INPUT,{context:{response:s}});let c=z(e(s,`warnings`)),l=z(e(s,`errors`)),u=e(s,`inputs`),f=e(s,`outputs`);return{inputs:Array.isArray(u)?u.map(je):[],outputs:Array.isArray(f)?f.map(Me):[],...c&&{loadWarnings:c},...l&&{loadErrors:l}}}function z(e){if(!Array.isArray(e))return;let t=e.map(Ne).filter(e=>e!==void 0);return t.length>0?t:void 0}function Ne(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 B(e,t){let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await R(e,t),{inputs:o,parseErrors:s}=Ae(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}const V=globalThis.process?.getBuiltinModule?.(`node:crypto`);function H(e){if(V){let t=V.createHash(`sha256`);return typeof e==`string`?t.update(e,`utf16le`):t.update(e),t.digest(`hex`)}return Fe(e)}const Pe=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Fe(e){let t=new Ie;return typeof e==`string`?t.updateString(e):t.update(e),t.digestHex()}var Ie=class{h=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);w=new Int32Array(64);pending=new Uint8Array(64);pendingLength=0;totalBytes=0;update(e){this.totalBytes+=e.length;let t=0;if(this.pendingLength>0){let n=Math.min(64-this.pendingLength,e.length);if(this.pending.set(e.subarray(0,n),this.pendingLength),this.pendingLength+=n,t=n,this.pendingLength<64)return;this.compressBytes(this.pending,0),this.pendingLength=0}for(;t+64<=e.length;t+=64)this.compressBytes(e,t);this.pending.set(e.subarray(t),0),this.pendingLength=e.length-t}updateString(e){let t=this.w,n=e.length-e.length%32;for(let r=0;r<n;r+=32){for(let n=0;n<16;n++){let i=e.charCodeAt(r+2*n),a=e.charCodeAt(r+2*n+1);t[n]=(i&255)<<24|i>>>8<<16|(a&255)<<8|a>>>8}this.compress()}this.totalBytes+=n*2;let r=new Uint8Array((e.length-n)*2);for(let t=n,i=0;t<e.length;t++){let n=e.charCodeAt(t);r[i++]=n&255,r[i++]=n>>>8}this.update(r)}digestHex(){let e=this.totalBytes*8,t=new Uint8Array(this.pendingLength<56?64:128);t.set(this.pending.subarray(0,this.pendingLength)),t[this.pendingLength]=128;let n=new DataView(t.buffer);n.setUint32(t.length-8,Math.floor(e/4294967296)),n.setUint32(t.length-4,e>>>0);for(let e=0;e<t.length;e+=64)this.compressBytes(t,e);let r=``;for(let e of this.h)r+=(e>>>0).toString(16).padStart(8,`0`);return r}compressBytes(e,t){let n=this.w;for(let r=0;r<16;r++){let i=t+r*4;n[r]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}this.compress()}compress(){let e=this.w;for(let t=16;t<64;t++){let n=e[t-15],r=e[t-2],i=(n>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,a=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10;e[t]=e[t-16]+i+e[t-7]+a|0}let t=this.h,n=t[0],r=t[1],i=t[2],a=t[3],o=t[4],s=t[5],c=t[6],l=t[7];for(let t=0;t<64;t++){let u=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),d=o&s^~o&c,f=l+u+d+Pe[t]+e[t]|0,p=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&r^n&i^r&i)|0;l=c,c=s,s=o,o=a+f|0,a=i,i=r,r=n,n=f+p|0}t[0]=t[0]+n|0,t[1]=t[1]+r|0,t[2]=t[2]+i|0,t[3]=t[3]+a|0,t[4]=t[4]+o|0,t[5]=t[5]+s|0,t[6]=t[6]+c|0,t[7]=t[7]+l|0}};function U(e){let t=new WeakSet,n=e=>{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(typeof e!=`object`)return`undefined`;if(e instanceof Uint8Array)return`{u8:${H(e)}}`;if(t.has(e))return`[Circular]`;t.add(e);let r;if(Array.isArray(e)){let t=[];for(let r=0;r<e.length;r++)t.push(n(e[r]));r=`[${t.join(`,`)}]`}else 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(`,`)}}`;return t.delete(e),r};return n(e)}function Le(e,t){return W(G(e),t)}function W(e,t){return`${e}|t:${H(U(t))}`}function G(e){return m(e)?`r:${e.key}`:typeof e==`string`?`s:${H(e)}`:`u8:${H(e)}`}const K=new WeakMap;function Re(e){if(!(e instanceof Uint8Array))return G(e);let t=K.get(e);return t===void 0&&(t=G(e),K.set(e,t)),t}var ze=class{hashDefinition;dataTree;definitionMemo;keyMemo;constructor(e,t){this.hashDefinition=e,this.dataTree=t}get definitionHash(){return this.definitionMemo??=this.hashDefinition()}get key(){return this.keyMemo??=W(this.definitionHash,this.dataTree)}},Be=class{items=[];head=0;live=new Set;get size(){return this.live.size}push(e){this.items.push(e),this.live.add(e)}remove(e){this.live.delete(e)&&this.compact()}shift(){for(;this.head<this.items.length;){let e=this.items[this.head];if(this.items[this.head++]=void 0,e&&this.live.delete(e))return this.compact(),e}}compact(){if(this.live.size===0){this.items=[],this.head=0;return}let e=this.items.length-this.live.size;e<=64||e<=this.live.size||(this.items=this.items.filter(e=>e!==void 0&&this.live.has(e)),this.head=0)}};function Ve(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var He=class{executor;baseConfig;mode;maxConcurrent;maxQueueDepth;queueWaitMs;timeoutMs;retry;cacheEnabled;cacheMaxBytes;cacheTtl;cacheErroredSolves;cache=new Map;cacheBytes=0;cacheHits=0;cacheMisses=0;cacheEvictions=0;reuseServerDefinitionCache;serverCacheKeys=new Map;lastStringDefinition=null;onStart;onSettle;onSuperseded;subscribers=new Set;inFlight=new Set;pendingForLatestWins=null;fifo=new Be;_lastResult=null;_lastError=null;_lastDurationMs=null;solveSeq=0;lastStateSeq=0;disposed=!1;constructor(e,r,i={}){if(this.executor=e,this.baseConfig=r,this.mode=i.mode??`latest-wins`,this.mode!==`latest-wins`&&this.mode!==`queue`)throw new t(`Unknown scheduler mode '${String(this.mode)}'. For concurrent solves use { mode: 'queue', maxConcurrent: 4 }.`,n.INVALID_CONFIG,{context:{mode:this.mode}});this.maxConcurrent=Math.max(1,i.maxConcurrent??1),this.maxQueueDepth=i.maxQueueDepth!==void 0&&i.maxQueueDepth>0?Math.floor(i.maxQueueDepth):void 0,this.queueWaitMs=i.queueWaitMs!==void 0&&i.queueWaitMs>0?i.queueWaitMs:void 0,this.timeoutMs=i.timeoutMs,this.retry=i.retry;let a=i.cache,o=typeof a==`object`?a:null;this.cacheMaxBytes=Math.max(0,o?.maxBytes??0),this.cacheEnabled=this.cacheMaxBytes>0,this.cacheTtl=o?.ttlMs??0,this.cacheErroredSolves=o?.cacheErroredSolves??!0,this.reuseServerDefinitionCache=i.reuseServerDefinitionCache??!0,this.onStart=i.onStart,this.onSettle=i.onSettle,this.onSuperseded=i.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifo.size>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifo.size+ +!!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){i().error(`[SolveScheduler] subscriber threw:`,e)}}solve(e,t,n){return this.solveDetailed(e,t,n).then(e=>e.response)}solveDetailed(e,r,i){if(this.disposed)return Promise.reject(new t(`SolveScheduler has been disposed and cannot be used`,n.INVALID_STATE));let a=new ze(()=>this.hashDefinitionMemo(e),r),o=``;if(this.cacheEnabled||this.onStart||this.onSettle||this.onSuperseded)try{o=a.key}catch(e){return Promise.reject(new t(`Solve input could not be hashed`,n.INVALID_INPUT,{originalError:e}))}let s=++this.solveSeq,c={key:o,enqueuedAt:Date.now(),startedAt:null};if(i?.signal?.aborted)return Promise.reject(this.makeAbortError(c));let l=this.readCache(o);if(l){this.mode===`latest-wins`&&this.supersedeCurrent();let e={status:`success`,response:l,durationMs:0,fromCache:!0};return this.writeLastState(s,{result:l,durationMs:0}),this.runHook(this.onStart,c),this.runHook(this.onSettle,c,e),this.notify(),Promise.resolve({response:l,fromCache:!0,durationMs:0})}return new Promise((t,n)=>{let o={definition:e,dataTree:r,hashes:a,ctx:c,seq:s,resolve:t,reject:n,externalSignal:i?.signal,selvaevents:i?.selvaevents,onServerTiming:i?.onServerTiming};o.externalSignal&&(o.queuedAbortHandler=()=>this.abortQueuedItem(o),o.externalSignal.addEventListener(`abort`,o.queuedAbortHandler,{once:!0})),this.enqueue(o)})}writeLastState(e,t){e<this.lastStateSeq||(this.lastStateSeq=e,`result`in t?(this._lastResult=t.result,this._lastError=null):this._lastError=t.error,this._lastDurationMs=t.durationMs)}supersedeCurrent(){this.pendingForLatestWins&&=(this.supersede(this.pendingForLatestWins),null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}dequeue(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null),this.fifo.remove(e)}abortQueuedItem(e){this.dequeue(e),this.fail(e,this.makeAbortError(e.ctx)),this.notify()}shedAsQueueFull(e){let r=new t(`Solve queue is full; request rejected (backpressure)`,n.QUEUE_FULL,{statusCode:503,context:{queueDepth:this.fifo.size,maxQueueDepth:this.maxQueueDepth}});this.fail(e,r),this.notify()}armQueueWaitTimer(e){if(this.queueWaitMs===void 0)return;let r=this.queueWaitMs;e.queueWaitTimer=setTimeout(()=>{if(e.settled)return;this.dequeue(e);let i=new t(`Solve waited longer than ${r}ms in queue; rejected (backpressure)`,n.QUEUE_TIMEOUT,{statusCode:503,context:{waitedMs:Date.now()-e.ctx.enqueuedAt,queueWaitMs:r}});this.fail(e,i),this.notify()},r)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case`latest-wins`:this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break;case`queue`:this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifo.size>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifo.push(e))}this.notify()}async execute(e){let t=new AbortController,n=e;n.controller=t,this.inFlight.add(n),e.ctx.startedAt=Date.now(),this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e);let r=()=>t.abort();e.externalSignal?.addEventListener(`abort`,r,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let i=performance.now();try{let n={...this.baseConfig,signal:t.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry},...e.selvaevents!==void 0&&{selvaevents:e.selvaevents}},r=e.onServerTiming;if(r){let e=this.baseConfig.onServerTiming;n.onServerTiming=(t,n)=>{try{e?.(t,n)}finally{r(t,n)}}}let{response:a,definitionReuploaded:o}=await this.runExecutor(e,n),s=performance.now()-i;if(this.writeCache(e.ctx.key,a),!this.settleSuccess(e,{response:a,fromCache:!1,definitionReuploaded:o,durationMs:s}))return;this.writeLastState(e.seq,{result:a,durationMs:s}),this.runHook(this.onSettle,e.ctx,{status:`success`,response:a,durationMs:s,fromCache:!1,definitionReuploaded:o})}catch(t){let r=performance.now()-i,a=this.normalizeExecutionError(t,n);this.writeLastState(e.seq,{error:a,durationMs:r}),this.fail(e,a,r)}finally{e.externalSignal?.removeEventListener(`abort`,r),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,t){let{definition:n,dataTree:r}=e;if(!this.reuseServerDefinitionCache||o(n)){let{response:e}=await this.executor(n,r,null,t);return{response:e}}let i=e.hashes.definitionHash,a=this.serverCacheKeys.get(i)??null,s=await this.executor(n,r,a,t);return this.serverCacheKeys.delete(i),s.cacheKey&&(this.serverCacheKeys.set(i,s.cacheKey),this.serverCacheKeys.size>100&&this.serverCacheKeys.delete(this.serverCacheKeys.keys().next().value)),{response:s.response,definitionReuploaded:s.missed}}hashDefinitionMemo(e){return typeof e==`string`?(this.lastStringDefinition?.value!==e&&(this.lastStringDefinition={value:e,hash:G(e)}),this.lastStringDefinition.hash):Re(e)}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.fifo.size>0&&this.inFlight.size<this.maxConcurrent;)this.execute(this.fifo.shift())}}supersede(e){let r=new t(`Superseded by newer solve`,n.SUPERSEDED,{context:{enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new t(`Request aborted by caller`,n.ABORTED,{context:{enqueuedAt:e.enqueuedAt}})}settleError(e,t){return!e.settled&&(e.settled={error:t},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(t),!0)}fail(e,t,n=0){this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:n})}settleSuccess(e,t){return!e.settled&&(e.settled={ok:!0},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.resolve(t),!0)}removeQueuedAbortHandler(e){e.queuedAbortHandler&&e.externalSignal&&e.externalSignal.removeEventListener(`abort`,e.queuedAbortHandler),e.queuedAbortHandler=void 0}normalizeExecutionError(e,r){return r.settled&&`error`in r.settled?r.settled.error:e instanceof t?e:e instanceof Error&&e.name===`AbortError`?this.makeAbortError(r.ctx):new t(e instanceof Error?e.message:String(e),n.UNKNOWN_ERROR,{originalError:e})}cancelAll(){this.pendingForLatestWins&&=(this.fail(this.pendingForLatestWins,this.makeAbortError(this.pendingForLatestWins.ctx)),null);for(let e=this.fifo.shift();e;e=this.fifo.shift())this.fail(e,this.makeAbortError(e.ctx));for(let e of this.inFlight){let t=e.ctx.startedAt?Date.now()-e.ctx.startedAt:0;this.fail(e,this.makeAbortError(e.ctx),t),e.controller.abort()}this.notify()}readCache(e){if(!this.cacheEnabled)return null;let t=this.cache.get(e);return t?this.cacheTtl>0&&Date.now()-t.insertedAt>this.cacheTtl?(this.dropCacheEntry(e),this.cacheMisses+=1,null):(this.cache.delete(e),this.cache.set(e,t),this.cacheHits+=1,t.response):(this.cacheMisses+=1,null)}writeCache(t,n){if(!this.cacheEnabled)return;let r=e(n,`errors`);if(!this.cacheErroredSolves&&Array.isArray(r)&&r.length>0)return;let i=c(n)??Ve(n);if(!(i>this.cacheMaxBytes))for(this.dropCacheEntry(t),this.cache.set(t,{response:n,insertedAt:Date.now(),sizeBytes:i}),this.cacheBytes+=i;this.cacheBytes>this.cacheMaxBytes&&this.cache.size>0;){let e=this.cache.keys().next().value;if(e===void 0)break;this.dropCacheEntry(e),this.cacheEvictions+=1}}dropCacheEntry(e){let t=this.cache.get(e);t&&(this.cache.delete(e),this.cacheBytes-=t.sizeBytes)}clearCache(){this.cache.clear(),this.cacheBytes=0}cacheStats(){return{entries:this.cache.size,bytes:this.cacheBytes,hits:this.cacheHits,misses:this.cacheMisses,evictions:this.cacheEvictions}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(e,...t){if(e)try{e(...t)}catch(e){i().error(`[SolveScheduler] hook threw:`,e)}}};function Ue(e){return m(e)?`ref:${e.key}`:typeof e==`string`&&e.length<200?e:`...content...`}function We(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 Ge=class r{config;serverStats;disposed=!1;static CREATE_PROBE_TIMEOUT_MS=2e3;constructor(e){this.config={...e,serverUrl:h(e.serverUrl),debug:e.debug??!1},this.serverStats=new g(this.config.serverUrl,this.config)}static async create(e,i={}){let a=new r(e),o=Math.max(1,(i.probe?.attempts??2)+1),s=i.probe?.baseDelayMs??250,c=i.probe?.maxDelayMs??1e3,l,u=null,d=0;for(let e=0;e<o;e++){if(d=e+1,l=await a.serverStats.probeServer(r.CREATE_PROBE_TIMEOUT_MS),l.online)return a;if(u=te(l),u&&!u.retryable)break;if(e<o-1){let t=Math.min(s*2**e,c);await new Promise(e=>setTimeout(e,t))}}await a.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,n.NETWORK_ERROR,{...f!==void 0&&{statusCode:f},context:{serverUrl:a.config.serverUrl,attempts:d,maxAttempts:o,...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(),B(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),R(e,this.config)}async solve(r,a,o){this.ensureNotDisposed();try{if(typeof r==`string`&&!r.trim())throw new t(`Definition URL/content is required`,n.INVALID_INPUT,{context:{receivedUrl:r}});if(r instanceof Uint8Array&&r.length===0)throw new t(`Definition content is empty`,n.INVALID_INPUT);if(m(r)&&!r.key.trim())throw new t(`DefinitionRef key is empty`,n.INVALID_INPUT);let i=await le(a,r,{...this.config,...o?.signal!==void 0&&{signal:o.signal},...o?.timeoutMs!==void 0&&{timeoutMs:o.timeoutMs},...o?.retry!==void 0&&{retry:o.retry},...o?.selvaevents!==void 0&&{selvaevents:o.selvaevents}}),s=e(i,`errors`);if(Array.isArray(s)&&s.length>0)throw new t(s.map(String).join(`; `)||`Computation failed`,n.COMPUTATION_ERROR,{context:{definition:Ue(r),inputSummary:We(a),errors:s,warnings:e(i,`warnings`),values:i.values}});return i}catch(e){throw this.config.debug&&i().error(`Compute failed:`,e),e instanceof t?e:new t(e instanceof Error?e.message:String(e),n.COMPUTATION_ERROR,{context:{definition:Ue(r),inputSummary:We(a)},originalError:e})}}createScheduler(e){return this.ensureNotDisposed(),new He((e,t,n,r)=>ue(t,n,e,r),this.config,e)}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`,n.INVALID_STATE)}};function Ke(e){return typeof e==`object`&&!!e&&e.__decodeError===!0}function qe(e,t){return{__decodeError:!0,type:e,raw:t}}function Je(e){let t=new WeakSet,n=e=>{if(!e||typeof e!=`object`||t.has(e))return;t.add(e);let r=e.delete;if(typeof r==`function`){let t=e.isDeleted;(typeof t!=`function`||!t.call(e))&&r.call(e);return}if(Array.isArray(e)){for(let t of e)n(t);return}let i=Object.getPrototypeOf(e);if(i===Object.prototype||i===null)for(let t of Object.values(e))n(t)};n(e)}const q=new Map([[`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}],[`Rhino.Geometry.Line`,(e,t)=>{let n=t;return!n||!n.From||!n.To?null:new e.Line([n.From.X,n.From.Y,n.From.Z],[n.To.X,n.To.Y,n.To.Z])}]]);function Ye(e){if(q.has(e))return q.get(e);for(let[t,n]of q)if(e.startsWith(t))return n}function Xe(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function Ze(e,t,n){let r=Ye(t),a=!1;if(r)try{let t=r(n,e);if(t!=null)return t}catch(e){i().warn(`Failed to decode Rhino type ${t}:`,e),a=!0}try{if(Xe(e))return n.CommonObject.decode(e)}catch(n){return i().warn(`Failed to decode ${t} with CommonObject:`,n),qe(t,e)}return a?qe(t,e):e}const J={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},Qe=`FileData`;function $e(e,t){return e.includes(`WebDisplay`)||t&&e!==J.STRING}function et(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 tt(e,t,n){switch(t){case J.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case J.INT:return Number.parseInt(String(e),10);case J.DOUBLE:return Number.parseFloat(String(e));case J.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?Ze(e,t,n):e}}function Y(e,t,n,r){if(typeof e.data!=`string`)return e.data;let i=n?et(e.data):e.data;return n&&t.includes(Qe)?nt(i)??i:tt(i,t,r)}function nt(t){if(!t||typeof t!=`object`)return null;let n=e(t,`fileName`),i=e(t,`fileType`),a=e(t,`subFolder`),o=e(t,`isBase64Encoded`);if(typeof n!=`string`||typeof i!=`string`||typeof a!=`string`||!r(t,`data`)||typeof o!=`boolean`&&typeof o!=`string`)return null;let s=e(t,`metadata`);return{fileName:n,fileType:i,data:e(t,`data`),isBase64Encoded:u(o),subFolder:a,...s?{metadata:s}:{}}}function X(t){let n=e(t,`values`);return Array.isArray(n)?n:[]}function Z(e){return typeof e.type==`string`?e.type:``}function Q(e,t){if(e&&typeof e==`object`){for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)e&&typeof e==`object`&&t(e)}}function rt(t,n=!1,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r,s={},c=new Set;for(let r of X(t)){let t=e(r,`paramName`);Q(e(r,`innerTree`),e=>{let r=Z(e);if($e(r,o))return;let l=n?e.id:t;if(!l)return;let u=Y(e,r,i,a);Object.prototype.hasOwnProperty.call(s,l)?c.has(l)?s[l].push(u):(s[l]=[s[l],u],c.add(l)):x(s,l,u)})}return{values:s,dispose:()=>Je(s)}}function it(t){let n=[];for(let r of X(t))Q(e(r,`innerTree`),e=>{if(!Z(e).includes(Qe))return;let t=nt(et(e.data));t&&n.push(t)});return n}function at(t,n,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r;for(let r of X(t)){let t=e(r,`innerTree`),s=!1;if(`byName`in n){if(e(r,`paramName`)!==n.byName)continue;s=!0}let c=[];if(Q(t,e=>{if(`byId`in n){if(e.id!==n.byId)return;s=!0}let t=Z(e);$e(t,o)||c.push(Y(e,t,i,a))}),s)return c.length===0?void 0:c.length===1?c[0]:c}}var ot=class{response;constructor(e){this.response=e}getValues(e=!1,t={}){return rt(this.response,e,t)}getValue(e,t){return at(this.response,e,t)}async getAndDownloadFiles(e,t){await ee(it(this.response),e,t)}};function st(t){return(Array.isArray(t)?t:[t]).map(t=>({schemas:e(t,`schemas`),error:e(t,`error`)}))}const ct=new Set([`options`,`defaultOptions`,`values`]),lt=new Set([`optionMedia`,`assets`]),ut=e=>e>=`A`&&e<=`Z`;function dt(e){if(e.length===0||!ut(e[0]))return e;let t=0;for(;t<e.length&&ut(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function ft(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=dt(n);x(t,e,ct.has(e)?r:lt.has(e)?pt(r):$(r))}return t}function pt(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t={};for(let[n,r]of Object.entries(e))x(t,n,$(r));return t}var mt=class r{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(e,t){let n=this.innerTree[r.formatPathString(e)]??=[];for(let e of t)n.push({data:r.serializeValue(e)});return this}fromDataTreeDefault(e){this.innerTree={};for(let[t,n]of Object.entries(e)){if(!Array.isArray(n))continue;let e=r.parsePathString(t);this.append(e,n)}return this}appendFlat(e){let t=Array.isArray(e)?e:[e];return this.append([0],t)}flatten(){let e=[];for(let t of Object.values(this.innerTree))if(Array.isArray(t))for(let n of t)e.push(r.deserializeValue(n.data));return e}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getParamName(){return this.paramName}static fromInputParams(e){return r.fromValues(e.map(e=>({paramName:e.nickname||`unnamed`,paramType:e.paramType,value:e.default,...`minimum`in e&&{minimum:e.minimum,maximum:e.maximum}})))}static fromValues(e){let t=[];for(let n of e){let e=new r(n.paramName),a=r.itemCoercer(n);for(let[t,o]of r.branchesOf(n.value)){let r=[];for(let e of o){if(e==null)continue;let t=a(e);t===null?i().warn(`${n.paramName}: dropped an item that is not a valid ${n.paramType}`):r.push(t)}r.length>0&&e.append(t,r)}Object.keys(e.innerTree).length>0&&t.push(e.toComputeFormat())}return t}static branchesOf(e){return r.hasValidValue(e)?C(e)?Object.entries(e).map(([e,t])=>[r.parsePathString(e),t]):[[[0],Array.isArray(e)?e:[e]]]:[]}static itemCoercer(e){let{paramName:t,minimum:n,maximum:i}=e,a=e.paramType.toLowerCase();return a===`number`||a===`integer`?e=>{let o=T(e);if(o===null)return null;let s=a===`integer`?Math.round(o):o;return r.clampValue(s,n,i,t)}:a===`boolean`?E:e=>e}static replaceTreeValue(e,t,n){let i=r.buildFromValue(t,n).toComputeFormat(),a=e.slice(),o=a.findIndex(e=>r.paramNameOf(e)===t);return o===-1?a.push(i):a[o]=i,a}static buildFromValue(e,t){let n=new r(e);return C(t)?n.fromDataTreeDefault(t):n.appendFlat(t),n}static getTree(t,n){let i=t.find(e=>r.paramNameOf(e)===n);if(!i)return null;let a=new Map,o=e(i,`InnerTree`);if(!o||typeof o!=`object`)return a;for(let[e,t]of Object.entries(o))Array.isArray(t)&&a.set(e,t.map(e=>e?.data===void 0?null:r.deserializeValue(e.data)));return a}static getTreeValue(e,i){let a=r.getTree(e,i);if(!a||a.size===0)return null;if(a.size>1)throw new t(`"${i}" has ${a.size} branches; read it with TreeBuilder.getTree`,n.INVALID_INPUT,{context:{paramName:i,branchCount:a.size}});let[o]=a.values();return o.length===0?null:o.length===1?o[0]:o}static paramNameOf(t){return e(t,`ParamName`)}static parsePathString(e){let r=e.match(S);if(!r)throw new t(`Invalid Grasshopper tree path: "${e}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`,n.INVALID_INPUT,{context:{pathStr:e}});return r[1]?r[1].split(`;`).map(Number):[]}static formatPathString(e){return`{${e.join(`;`)}}`}static serializeValue(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`?e:typeof e==`object`&&e?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e!=`string`)return e;if(e.startsWith(`{`)||e.startsWith(`[`))try{return JSON.parse(e)}catch{return e}let t=Number(e);return Number.isFinite(t)&&String(t)===e?t:e===`true`||e!==`false`&&e}static hasValidValue(e){return e==null?!1:typeof e==`string`||!(Array.isArray(e)&&e.length===0||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0)}static clampValue(e,t,n,r){let a=e;return t!=null&&a<t&&(i().warn(`${r}: ${e} below min ${t}, clamping`),a=t),n!=null&&a>n&&(i().warn(`${r}: ${e} above max ${n}, clamping`),a=n),a}};export{g as ComputeServerStats,Ge as GrasshopperClient,ot as GrasshopperResponseProcessor,He as SolveScheduler,mt as TreeBuilder,Je as disposeRhinoObjects,R as fetchDefinitionIO,B as fetchParsedDefinitionIO,G as hashDefinition,Le as hashSolveInput,Ke as isRhinoDecodeError,ft as normalizeUISchemaCasing,ke as processInput,st as readSchemaResults,le as solveGrasshopperDefinition,U as stableStringify};
1
+ import{C as e,D as t,O as n,S as r,T as i,_ as a,c as o,d as s,f as c,h as l,i as u,l as d,m as f,p,s as m,t as ee,u as te,v as ne,x as h,y as re}from"./core-BC8t6doi.js";var g=class e{serverUrl;headers;disposed=!1;activeMonitors=new Set;static DEFAULT_TIMEOUT_MS=5e3;static LIFECYCLE_TIMEOUT_MS=6e4;static MIN_MONITOR_INTERVAL_MS=100;static MAX_BODY_BYTES=1<<20;constructor(e,t){this.serverUrl=h(e),this.headers={...re(typeof t==`string`?{apiKey:t}:t??{}),"Content-Type":`application/json`}}fetchWithTimeout(t,n={},r=e.DEFAULT_TIMEOUT_MS){let i={...n,headers:this.headers,redirect:`manual`};return r>0&&!i.signal&&(i.signal=AbortSignal.timeout(r)),fetch(t,i)}async getText(t,n={},r=e.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let a=`${n.method??`GET`} ${t}`;try{let o=await this.fetchWithTimeout(`${this.serverUrl}${t}`,n,r);if(!o.ok)return i().warn(`[ComputeServerStats] ${a} failed:`,o.status),await o.body?.cancel().catch(()=>{}),null;let{text:s,truncated:c}=await f(o,e.MAX_BODY_BYTES);return c?(i().warn(`[ComputeServerStats] ${a} answered with an oversized body`),null):s}catch(e){return i().warn(`[ComputeServerStats] ${a} errored:`,e),null}}async isServerOnline(t=e.DEFAULT_TIMEOUT_MS){return(await this.probeServer(t)).online}async probeServer(t=e.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let n=`${this.serverUrl}/`;try{let e=await this.fetchWithTimeout(n,{method:`GET`},t);return await e.body?.cancel().catch(()=>{}),{online:e.ok||s(e),status:e.status}}catch(e){return i().debug(`[ComputeServerStats] Fetch error:`,e),{online:!1,error:e instanceof Error?`${e.name}: ${e.message}`:String(e)}}}async getActiveChildren(t={}){let{initialize:n=!0}=t,r=n?await this.getText(`/activechildren`,{},e.LIFECYCLE_TIMEOUT_MS):await this.getText(`/activechildren?initialize=false`);if(r===null)return null;let a=r.trim();return/^\d+$/.test(a)?parseInt(a,10):(i().warn(`[ComputeServerStats] /activechildren answered with a non-numeric body`),null)}async getVersion(){let e=await this.getText(`/version`);if(e===null)return null;let t=_(e);return t==null?{rhino:e,compute:``,git_sha:null}:{rhino:t.rhino??``,compute:t.compute??``,git_sha:t.git_sha??null}}async getInstalledPlugins(e=`gh`){let t=await this.getText(`/plugins/${e}/installed`),n=t===null?void 0:_(t);return n&&typeof n==`object`?n:null}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[e,t]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...e&&{version:e},...t!==null&&{activeChildren:t}}}async purgeCache(){let e=await this.getText(`/cache/purge`,{method:`POST`}),t=(e===null?void 0:_(e))?.purged;return typeof t==`number`?t:null}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return i().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(){let e=await this.getText(`/servertime`);if(e===null)return null;let t=new Date(e.trim().replace(/^"|"$/g,``));return isNaN(t.getTime())?null:t}async getIdleSpan(){let e=await this.getText(`/idlespan`);if(e===null)return null;let t=parseFloat(e.trim());return isNaN(t)?null:t}async launchChildren(){return this.postJson(`/launch-children`)}async launchChild(e){let t=e===void 0?`/launch-child`:`/launch-child?port=${e}`;return this.postJson(t)}async shutdownChildren(e){let t=e===void 0?`/shutdown-children`:`/shutdown-children?port=${e}`;return this.postJson(t)}async recycleChildren(e){let t=e===void 0?`/recycle-children`:`/recycle-children?port=${e}`;return this.postJson(t)}async postJson(t){let n=await this.getText(t,{method:`POST`},e.LIFECYCLE_TIMEOUT_MS);return n===null?null:_(n)??null}monitor(r,a=5e3){if(this.ensureNotDisposed(),!Number.isFinite(a)||a<e.MIN_MONITOR_INTERVAL_MS)throw new t(`monitor() intervalMs must be a finite number >= ${e.MIN_MONITOR_INTERVAL_MS}ms, got ${a}. Sub-${e.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`,n.INVALID_CONFIG,{context:{intervalMs:a}});let o=!0,s=null;i().info(`🔄 Starting server stats monitoring every ${a}ms`);let c=async()=>{if(s=null,o&&!this.disposed){try{let e=await this.getServerStats();if(!o||this.disposed)return;try{r(e)}catch(e){i().error(`[ComputeServerStats] Monitor callback threw:`,e)}}catch(e){!o||this.disposed?i().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,e):i().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,e)}o&&!this.disposed&&(s=setTimeout(()=>void c(),a))}},l=()=>{o=!1,s!==null&&(clearTimeout(s),s=null),this.activeMonitors.delete(l)};return this.activeMonitors.add(l),c(),l}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear()}}ensureNotDisposed(){if(this.disposed)throw new t(`ComputeServerStats has been disposed and cannot be used`,n.INVALID_STATE)}};function _(e){try{return JSON.parse(e)}catch{return}}const v=new Set;function ie(){if(typeof window>`u`||globalThis.process?.versions?.node!=null)return!1;let e=globalThis.navigator,t=typeof e?.userAgent==`string`?e.userAgent:``;return!/jsdom/i.test(t)}function y(e,t){t||ie()&&!v.has(e)&&(v.add(e),i().warn(`Warning: ${e} is running on the client side. For better performance and security, consider running this on the server side.`))}const ae={definition_not_cached:n.DEFINITION_NOT_CACHED};function oe(e){return{...e,serverErrorCodes:{...ae,...e.serverErrorCodes}}}function se(e){return e instanceof t?e.code===n.DEFINITION_NOT_CACHED||e.message.includes(`Unable to load grasshopper definition`):!1}function ce(t,n){if(!n)return;let r=e(t,`values`);if(!Array.isArray(r)||r.length===0)return;let a=[];for(let t of r){let n=e(t,`innerTree`);(!n||Object.keys(n).length===0)&&a.push(e(t,`paramName`)??`<unnamed>`)}if(a.length===0)return;let o=a.length===r.length?`all`:`${a.length}/${r.length}`;i().warn(`Solve returned empty output(s) (${o}): ${a.join(`, `)}. These parameters produced no data — check the definition's inputs and the branch feeding each.`)}async function le(e,t,n){return y(`solveGrasshopperDefinition`,n.suppressBrowserWarning),(await de(e,t,n)).response}async function ue(e,t,n,r){if(y(`solveWithServerCacheKey`,r.suppressBrowserWarning),t!==null)try{return{...await pe({algo:null,pointer:t,values:e},r),missed:!1}}catch(e){if(!se(e))throw e}return{...await de(e,n,r),missed:!0}}async function de(e,t,n){return pe(b(await fe(t),e),n)}async function fe(e){if(!m(e))return e;try{return await e.load()}catch(r){throw new t(`Failed to load definition bytes for ref '${e.key}'`,n.INVALID_INPUT,{context:{definitionKey:e.key},originalError:r})}}async function pe(e,t){h(t.serverUrl),me(e,t);let{maxResponseBytes:n}=t,r=await d(`grasshopper`,e,oe({...t,maxResponseBytes:n!==void 0&&e.algo?n+e.algo.length:n})),{pointer:i,algo:a,...o}=r,s=o,l=c(r);if(l!==void 0){let e=typeof a==`string`?a.length:0;p(s,Math.max(0,l-e))}return ce(s,t.debug),{response:s,cacheKey:typeof i==`string`?i:null}}function b(e,t){let n={algo:null,pointer:null,values:t};return e instanceof Uint8Array?n.algo=l(e):o(e)?n.pointer=e:n.algo=a(e)??ne(e),n}function me(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 x(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}const S=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function C(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>S.test(e)&&Array.isArray(t))}function w(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 T=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},E=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 D(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:(i().warn(`Parsed value for input ${e} is not an object`),null)}catch(n){return i().warn(`Failed to parse object value "${t}" for input ${e}`,n),null}return null}}const _e=new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),ve=new Set([`System.Int32`,`System.Int64`]);function O(e,t){return i().warn(t),{schema:{...e,default:null},warning:{code:n.MALFORMED_DEFAULT,message:t}}}function ye(t,a){if(typeof t.default!=`object`||t.default===null||Array.isArray(t.default)||C(t.default))return{schema:t};if(!r(t.default,`innerTree`))return O(t,`Input "${a}" default had an unrecognized shape (no innerTree key); the default was dropped.`);let o=e(t.default,`innerTree`)??{};if(Object.keys(o).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let r={},s=[];for(let[n,i]of Object.entries(o)){if(!Array.isArray(i))return O(t,`Input "${a}" default had a non-array innerTree branch ("${n}"); the default was dropped.`);let o=[];for(let t of i){let n=e(t,`data`),r=e(t,`type`);if(r&&_e.has(r)){if(typeof n==`string`&&n.trim()===``)continue;let e=T(n);if(e===null){s.push(`"${String(n)}" (${r})`);continue}o.push(ve.has(r)?Math.round(e):e);continue}if(r===`System.Boolean`){let e=E(n);if(e===null){s.push(`"${String(n)}" (${r})`);continue}o.push(e);continue}if(typeof n==`string`&&r?.startsWith(`Rhino.Geometry`)){try{o.push(JSON.parse(n))}catch{o.push(n)}continue}o.push(n)}x(r,n,o)}if(s.length>0){let e=`Input "${a}" default contained ${s.length} tree value(s) that could not be parsed and were dropped: ${s.join(`, `)}.`;return i().warn(e),{schema:{...t,default:r},warning:{code:n.MALFORMED_DEFAULT,message:e}}}return{schema:{...t,default:r}}}let s=[];for(let t of Object.values(o))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&r(n,`data`)&&s.push(e(n,`data`));return{schema:{...t,default:s.length>1?s:s[0]}}}function be(e,t){let n=Number(e.toFixed(t));return Math.abs(e-n)<1e-8?n:e}function k(e){if(!Number.isFinite(e))return 0;let[t,n]=String(Math.abs(e)).split(`e`),r=n===void 0?Math.abs(e).toFixed(12).replace(/0+$/,``).split(`.`)[1]?.length??0:(t.split(`.`)[1]?.length??0)-Number(n);return Math.min(Math.max(r,0),12)}function xe(e){if(!Number.isFinite(e)||e===0)return .1;let t=k(e);return t===0?Math.abs(e)>=1?1:.1:Number((10**-t).toFixed(t))}function A(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}const j=(e,t)=>(e.atMost??1)>1?[t]:t,M=e=>A(e)??(e.paramType===`Integer`?1:.1),N=(e,t)=>Array.isArray(e)?e.map(e=>typeof e==`number`?t(e):e):typeof e==`number`?t(e):e;function Se(e){if(C(e.default))return{default:e.default,stepSize:M(e)};if(typeof e.default==`string`&&e.default.trim()!==``&&T(e.default)===null)throw new t(`Invalid numeric default "${e.default}" for input "${e.name||`unknown`}"`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});let r=w(e.default,T,!0);if(e.paramType===`Integer`)return{default:N(r,Math.round),stepSize:M(e)};let i=Array.isArray(r)?r[0]:r,a=[i,e.minimum,e.maximum].find(e=>typeof e==`number`&&Number.isFinite(e)&&e!==0),o=A(e)??(a===void 0?.1:xe(a)),s=k(o);if(s===0&&typeof i==`number`&&i!==0&&Math.abs(i)<1){let e=Math.ceil(-Math.log10(Math.abs(i)));Number.isFinite(e)&&e>0&&(s=e)}return s=Math.min(Math.max(s,0),12),{default:N(r,e=>be(e,s)),stepSize:o}}const P={parse(e,t){let{default:n,stepSize:r}=Se(e);return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:r,default:n}},fallback(e,t){let n=typeof e.minimum==`number`&&Number.isFinite(e.minimum)&&e.minimum>0?e.minimum:0;return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:M(e),default:j(e,n)}}},Ce={parse(e,r){if(C(e.default))return{...r,paramType:`Boolean`,default:e.default};let i=w(e.default,E,!1);if(i!=null&&typeof i!=`boolean`&&!Array.isArray(i))throw new t(`Invalid boolean default "${String(i)}" for input "${e.name||`unknown`}"`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});return{...r,paramType:`Boolean`,default:i}},fallback(e,t){return{...t,paramType:`Boolean`,default:j(e,!1)}}},we={parse(e,t){let n=w(e.default,he,!1);return{...t,paramType:`Text`,default:n}}},Te={parse(e,r,a){if(!e.values||typeof e.values!=`object`||Object.keys(e.values).length===0){let r=e.nickname||`unnamed`;throw new t(`Input "${r}" has no values defined (expected ValueList)`,n.INVALID_INPUT,{context:{inputName:r,expectedType:`ValueList`}})}let o=e.default;if(e.default!==void 0&&e.default!==null){if(typeof e.default==`object`)throw new t(`ValueList input "${e.nickname||`unnamed`}" default is not a string-able value`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});let r=String(e.default).toLowerCase(),s=Object.keys(e.values).find(e=>e.toLowerCase()===r);if(s!==void 0)o=s;else{let t=`ValueList input "${e.nickname||`unnamed`}" default value "${e.default}" is not in available values`;i().warn(t),a?.({code:n.VALIDATION_ERROR,message:t})}}return{...r,paramType:`ValueList`,values:e.values,default:o}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}};function F(e,t){return{...t,paramType:`Geometry`,default:j(e,null)}}const I=new Map([[`Number`,P],[`Integer`,P],[`Boolean`,Ce],[`Text`,we],[`ValueList`,Te],[`Geometry`,{parse(e,t){let n=w(e.default,D(e.nickname||`unnamed`),!0);return{...t,paramType:`Geometry`,default:n}},fallback:F}],[`File`,{parse(e,t){let n=w(e.default,D(e.nickname||`unnamed`),!0);return{...t,paramType:`File`,acceptedFormats:e.acceptedFormats,default:n}}}],[`Color`,{parse(e,t){let n=w(e.default,ge,!1);return{...t,paramType:`Color`,default:n}}}]]),Ee=F,De=new Map([...I.keys()].map(e=>[e.toLowerCase(),e]));function Oe(e){return De.get(e?.toLowerCase())??e}function ke(e){return L(e).input}function L(e){let r=e.name||`unknown`,a=[],o=({code:t,message:n})=>{a.push({inputName:r,paramType:e.paramType,message:n,code:t})},s={description:e.description,name:e.name,nickname:e.nickname,treeAccess:e.treeAccess,groupName:e.groupName??void 0,id:e.id},c=Oe(e.paramType),l={...e,paramType:c};try{let{schema:e,warning:t}=ye(l,r);l=e,t&&o(t)}catch(e){l={...l,default:null},o({code:n.MALFORMED_DEFAULT,message:`Input "${r}" default could not be normalized and was dropped: ${e instanceof Error?e.message:String(e)}`})}let u=I.get(c);try{if(!u)throw new t(`Unknown paramType: ${c}`,n.VALIDATION_ERROR,{context:{receivedParamType:c,paramName:e.name}});return{input:u.parse(l,s,o),errors:a}}catch(d){if(!(d instanceof t))throw new t(d instanceof Error?d.message:String(d),n.VALIDATION_ERROR,{context:{paramName:e.name,paramType:c},originalError:d});return i().error(`Validation error for input ${r}:`,d.message),o(d),{input:(u?.fallback??Ee)(l,s),errors:a}}}function Ae(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=L(r);t.push(e),n.push(...i)}return{inputs:t,parseErrors:n}}function je(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 Me(t){return{name:e(t,`name`)??``,nickname:e(t,`nickname`)??null,paramType:e(t,`paramType`)??``,id:e(t,`id`)??``}}async function R(r,i){y(`fetchDefinitionIO`,i.suppressBrowserWarning),h(i.serverUrl);let{algo:a,pointer:o}=b(r,[]);if(!a&&!o)throw new t(`Definition must resolve to either a URL pointer or base64 algo`,n.INVALID_INPUT);let s=await d(`io`,a?{algo:a}:{pointer:o},oe(i));if(!s||typeof s!=`object`)throw new t(`Invalid IO response structure`,n.INVALID_INPUT,{context:{response:s}});let c=z(e(s,`warnings`)),l=z(e(s,`errors`)),u=e(s,`inputs`),f=e(s,`outputs`);return{inputs:Array.isArray(u)?u.map(je):[],outputs:Array.isArray(f)?f.map(Me):[],...c&&{loadWarnings:c},...l&&{loadErrors:l}}}function z(e){if(!Array.isArray(e))return;let t=e.map(Ne).filter(e=>e!==void 0);return t.length>0?t:void 0}function Ne(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 B(e,t){let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await R(e,t),{inputs:o,parseErrors:s}=Ae(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}const V=globalThis.process?.getBuiltinModule?.(`node:crypto`);function H(e){if(V){let t=V.createHash(`sha256`);return typeof e==`string`?t.update(e,`utf16le`):t.update(e),t.digest(`hex`)}return Fe(e)}const Pe=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Fe(e){let t=new Ie;return typeof e==`string`?t.updateString(e):t.update(e),t.digestHex()}var Ie=class{h=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);w=new Int32Array(64);pending=new Uint8Array(64);pendingLength=0;totalBytes=0;update(e){this.totalBytes+=e.length;let t=0;if(this.pendingLength>0){let n=Math.min(64-this.pendingLength,e.length);if(this.pending.set(e.subarray(0,n),this.pendingLength),this.pendingLength+=n,t=n,this.pendingLength<64)return;this.compressBytes(this.pending,0),this.pendingLength=0}for(;t+64<=e.length;t+=64)this.compressBytes(e,t);this.pending.set(e.subarray(t),0),this.pendingLength=e.length-t}updateString(e){let t=this.w,n=e.length-e.length%32;for(let r=0;r<n;r+=32){for(let n=0;n<16;n++){let i=e.charCodeAt(r+2*n),a=e.charCodeAt(r+2*n+1);t[n]=(i&255)<<24|i>>>8<<16|(a&255)<<8|a>>>8}this.compress()}this.totalBytes+=n*2;let r=new Uint8Array((e.length-n)*2);for(let t=n,i=0;t<e.length;t++){let n=e.charCodeAt(t);r[i++]=n&255,r[i++]=n>>>8}this.update(r)}digestHex(){let e=this.totalBytes*8,t=new Uint8Array(this.pendingLength<56?64:128);t.set(this.pending.subarray(0,this.pendingLength)),t[this.pendingLength]=128;let n=new DataView(t.buffer);n.setUint32(t.length-8,Math.floor(e/4294967296)),n.setUint32(t.length-4,e>>>0);for(let e=0;e<t.length;e+=64)this.compressBytes(t,e);let r=``;for(let e of this.h)r+=(e>>>0).toString(16).padStart(8,`0`);return r}compressBytes(e,t){let n=this.w;for(let r=0;r<16;r++){let i=t+r*4;n[r]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}this.compress()}compress(){let e=this.w;for(let t=16;t<64;t++){let n=e[t-15],r=e[t-2],i=(n>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,a=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10;e[t]=e[t-16]+i+e[t-7]+a|0}let t=this.h,n=t[0],r=t[1],i=t[2],a=t[3],o=t[4],s=t[5],c=t[6],l=t[7];for(let t=0;t<64;t++){let u=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),d=o&s^~o&c,f=l+u+d+Pe[t]+e[t]|0,p=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&r^n&i^r&i)|0;l=c,c=s,s=o,o=a+f|0,a=i,i=r,r=n,n=f+p|0}t[0]=t[0]+n|0,t[1]=t[1]+r|0,t[2]=t[2]+i|0,t[3]=t[3]+a|0,t[4]=t[4]+o|0,t[5]=t[5]+s|0,t[6]=t[6]+c|0,t[7]=t[7]+l|0}};function U(e){let t=new WeakSet,n=e=>{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(typeof e!=`object`)return`undefined`;if(e instanceof Uint8Array)return`{u8:${H(e)}}`;if(t.has(e))return`[Circular]`;t.add(e);let r;if(Array.isArray(e)){let t=[];for(let r=0;r<e.length;r++)t.push(n(e[r]));r=`[${t.join(`,`)}]`}else 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(`,`)}}`;return t.delete(e),r};return n(e)}function Le(e,t){return W(G(e),t)}function W(e,t){return`${e}|t:${H(U(t))}`}function G(e){return m(e)?`r:${e.key}`:typeof e==`string`?`s:${H(e)}`:`u8:${H(e)}`}const K=new WeakMap;function Re(e){if(!(e instanceof Uint8Array))return G(e);let t=K.get(e);return t===void 0&&(t=G(e),K.set(e,t)),t}var ze=class{hashDefinition;dataTree;definitionMemo;keyMemo;constructor(e,t){this.hashDefinition=e,this.dataTree=t}get definitionHash(){return this.definitionMemo??=this.hashDefinition()}get key(){return this.keyMemo??=W(this.definitionHash,this.dataTree)}},Be=class{items=[];head=0;live=new Set;get size(){return this.live.size}push(e){this.items.push(e),this.live.add(e)}remove(e){this.live.delete(e)&&this.compact()}shift(){for(;this.head<this.items.length;){let e=this.items[this.head];if(this.items[this.head++]=void 0,e&&this.live.delete(e))return this.compact(),e}}compact(){if(this.live.size===0){this.items=[],this.head=0;return}let e=this.items.length-this.live.size;e<=64||e<=this.live.size||(this.items=this.items.filter(e=>e!==void 0&&this.live.has(e)),this.head=0)}};function Ve(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var He=class{executor;baseConfig;mode;maxConcurrent;maxQueueDepth;queueWaitMs;timeoutMs;retry;cacheEnabled;cacheMaxBytes;cacheTtl;cacheErroredSolves;cache=new Map;cacheBytes=0;cacheHits=0;cacheMisses=0;cacheEvictions=0;reuseServerDefinitionCache;serverCacheKeys=new Map;lastStringDefinition=null;onStart;onSettle;onSuperseded;subscribers=new Set;inFlight=new Set;pendingForLatestWins=null;fifo=new Be;_lastResult=null;_lastError=null;_lastDurationMs=null;solveSeq=0;lastStateSeq=0;disposed=!1;constructor(e,r,i={}){if(this.executor=e,this.baseConfig=r,this.mode=i.mode??`latest-wins`,this.mode!==`latest-wins`&&this.mode!==`queue`)throw new t(`Unknown scheduler mode '${String(this.mode)}'. For concurrent solves use { mode: 'queue', maxConcurrent: 4 }.`,n.INVALID_CONFIG,{context:{mode:this.mode}});this.maxConcurrent=Math.max(1,i.maxConcurrent??1),this.maxQueueDepth=i.maxQueueDepth!==void 0&&i.maxQueueDepth>0?Math.floor(i.maxQueueDepth):void 0,this.queueWaitMs=i.queueWaitMs!==void 0&&i.queueWaitMs>0?i.queueWaitMs:void 0,this.timeoutMs=i.timeoutMs,this.retry=i.retry;let a=i.cache,o=typeof a==`object`?a:null;this.cacheMaxBytes=Math.max(0,o?.maxBytes??0),this.cacheEnabled=this.cacheMaxBytes>0,this.cacheTtl=o?.ttlMs??0,this.cacheErroredSolves=o?.cacheErroredSolves??!0,this.reuseServerDefinitionCache=i.reuseServerDefinitionCache??!0,this.onStart=i.onStart,this.onSettle=i.onSettle,this.onSuperseded=i.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifo.size>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifo.size+ +!!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){i().error(`[SolveScheduler] subscriber threw:`,e)}}solve(e,t,n){return this.solveDetailed(e,t,n).then(e=>e.response)}solveDetailed(e,r,i){if(this.disposed)return Promise.reject(new t(`SolveScheduler has been disposed and cannot be used`,n.INVALID_STATE));let a=new ze(()=>this.hashDefinitionMemo(e),r),o=``;if(this.cacheEnabled||this.onStart||this.onSettle||this.onSuperseded)try{o=a.key}catch(e){return Promise.reject(new t(`Solve input could not be hashed`,n.INVALID_INPUT,{originalError:e}))}let s=++this.solveSeq,c={key:o,enqueuedAt:Date.now(),startedAt:null};if(i?.signal?.aborted)return Promise.reject(this.makeAbortError(c));let l=this.readCache(o);if(l){this.mode===`latest-wins`&&this.supersedeCurrent();let e={status:`success`,response:l,durationMs:0,fromCache:!0};return this.writeLastState(s,{result:l,durationMs:0}),this.runHook(this.onStart,c),this.runHook(this.onSettle,c,e),this.notify(),Promise.resolve({response:l,fromCache:!0,durationMs:0})}return new Promise((t,n)=>{let o={definition:e,dataTree:r,hashes:a,ctx:c,seq:s,resolve:t,reject:n,externalSignal:i?.signal,selvaevents:i?.selvaevents,onServerTiming:i?.onServerTiming};o.externalSignal&&(o.queuedAbortHandler=()=>this.abortQueuedItem(o),o.externalSignal.addEventListener(`abort`,o.queuedAbortHandler,{once:!0})),this.enqueue(o)})}writeLastState(e,t){e<this.lastStateSeq||(this.lastStateSeq=e,`result`in t?(this._lastResult=t.result,this._lastError=null):this._lastError=t.error,this._lastDurationMs=t.durationMs)}supersedeCurrent(){this.pendingForLatestWins&&=(this.supersede(this.pendingForLatestWins),null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}dequeue(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null),this.fifo.remove(e)}abortQueuedItem(e){this.dequeue(e),this.fail(e,this.makeAbortError(e.ctx)),this.notify()}shedAsQueueFull(e){let r=new t(`Solve queue is full; request rejected (backpressure)`,n.QUEUE_FULL,{statusCode:503,context:{queueDepth:this.fifo.size,maxQueueDepth:this.maxQueueDepth}});this.fail(e,r),this.notify()}armQueueWaitTimer(e){if(this.queueWaitMs===void 0)return;let r=this.queueWaitMs;e.queueWaitTimer=setTimeout(()=>{if(e.settled)return;this.dequeue(e);let i=new t(`Solve waited longer than ${r}ms in queue; rejected (backpressure)`,n.QUEUE_TIMEOUT,{statusCode:503,context:{waitedMs:Date.now()-e.ctx.enqueuedAt,queueWaitMs:r}});this.fail(e,i),this.notify()},r)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case`latest-wins`:this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break;case`queue`:this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifo.size>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifo.push(e))}this.notify()}async execute(e){let t=new AbortController,n=e;n.controller=t,this.inFlight.add(n),e.ctx.startedAt=Date.now(),this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e);let r=()=>t.abort();e.externalSignal?.addEventListener(`abort`,r,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let i=performance.now();try{let n={...this.baseConfig,signal:t.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry},...e.selvaevents!==void 0&&{selvaevents:e.selvaevents}},r=e.onServerTiming;if(r){let e=this.baseConfig.onServerTiming;n.onServerTiming=(t,n)=>{try{e?.(t,n)}finally{r(t,n)}}}let{response:a,definitionReuploaded:o}=await this.runExecutor(e,n),s=performance.now()-i;if(this.writeCache(e.ctx.key,a),!this.settleSuccess(e,{response:a,fromCache:!1,definitionReuploaded:o,durationMs:s}))return;this.writeLastState(e.seq,{result:a,durationMs:s}),this.runHook(this.onSettle,e.ctx,{status:`success`,response:a,durationMs:s,fromCache:!1,definitionReuploaded:o})}catch(t){let r=performance.now()-i,a=this.normalizeExecutionError(t,n);this.writeLastState(e.seq,{error:a,durationMs:r}),this.fail(e,a,r)}finally{e.externalSignal?.removeEventListener(`abort`,r),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,t){let{definition:n,dataTree:r}=e;if(!this.reuseServerDefinitionCache||o(n)){let{response:e}=await this.executor(n,r,null,t);return{response:e}}let i=e.hashes.definitionHash,a=this.serverCacheKeys.get(i)??null,s=await this.executor(n,r,a,t);return this.serverCacheKeys.delete(i),s.cacheKey&&(this.serverCacheKeys.set(i,s.cacheKey),this.serverCacheKeys.size>100&&this.serverCacheKeys.delete(this.serverCacheKeys.keys().next().value)),{response:s.response,definitionReuploaded:s.missed}}hashDefinitionMemo(e){return typeof e==`string`?(this.lastStringDefinition?.value!==e&&(this.lastStringDefinition={value:e,hash:G(e)}),this.lastStringDefinition.hash):Re(e)}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.fifo.size>0&&this.inFlight.size<this.maxConcurrent;)this.execute(this.fifo.shift())}}supersede(e){let r=new t(`Superseded by newer solve`,n.SUPERSEDED,{context:{enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new t(`Request aborted by caller`,n.ABORTED,{context:{enqueuedAt:e.enqueuedAt}})}settleError(e,t){return!e.settled&&(e.settled={error:t},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(t),!0)}fail(e,t,n=0){this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:n})}settleSuccess(e,t){return!e.settled&&(e.settled={ok:!0},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.resolve(t),!0)}removeQueuedAbortHandler(e){e.queuedAbortHandler&&e.externalSignal&&e.externalSignal.removeEventListener(`abort`,e.queuedAbortHandler),e.queuedAbortHandler=void 0}normalizeExecutionError(e,r){return r.settled&&`error`in r.settled?r.settled.error:e instanceof t?e:e instanceof Error&&e.name===`AbortError`?this.makeAbortError(r.ctx):new t(e instanceof Error?e.message:String(e),n.UNKNOWN_ERROR,{originalError:e})}cancelAll(){this.pendingForLatestWins&&=(this.fail(this.pendingForLatestWins,this.makeAbortError(this.pendingForLatestWins.ctx)),null);for(let e=this.fifo.shift();e;e=this.fifo.shift())this.fail(e,this.makeAbortError(e.ctx));for(let e of this.inFlight){let t=e.ctx.startedAt?Date.now()-e.ctx.startedAt:0;this.fail(e,this.makeAbortError(e.ctx),t),e.controller.abort()}this.notify()}readCache(e){if(!this.cacheEnabled)return null;let t=this.cache.get(e);return t?this.cacheTtl>0&&Date.now()-t.insertedAt>this.cacheTtl?(this.dropCacheEntry(e),this.cacheMisses+=1,null):(this.cache.delete(e),this.cache.set(e,t),this.cacheHits+=1,t.response):(this.cacheMisses+=1,null)}writeCache(t,n){if(!this.cacheEnabled)return;let r=e(n,`errors`);if(!this.cacheErroredSolves&&Array.isArray(r)&&r.length>0)return;let i=c(n)??Ve(n);if(!(i>this.cacheMaxBytes))for(this.dropCacheEntry(t),this.cache.set(t,{response:n,insertedAt:Date.now(),sizeBytes:i}),this.cacheBytes+=i;this.cacheBytes>this.cacheMaxBytes&&this.cache.size>0;){let e=this.cache.keys().next().value;if(e===void 0)break;this.dropCacheEntry(e),this.cacheEvictions+=1}}dropCacheEntry(e){let t=this.cache.get(e);t&&(this.cache.delete(e),this.cacheBytes-=t.sizeBytes)}clearCache(){this.cache.clear(),this.cacheBytes=0}cacheStats(){return{entries:this.cache.size,bytes:this.cacheBytes,hits:this.cacheHits,misses:this.cacheMisses,evictions:this.cacheEvictions}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(e,...t){if(e)try{e(...t)}catch(e){i().error(`[SolveScheduler] hook threw:`,e)}}};function Ue(e){return m(e)?`ref:${e.key}`:typeof e==`string`&&e.length<200?e:`...content...`}function We(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 Ge=class r{config;serverStats;disposed=!1;static CREATE_PROBE_TIMEOUT_MS=2e3;constructor(e){this.config={...e,serverUrl:h(e.serverUrl),debug:e.debug??!1},this.serverStats=new g(this.config.serverUrl,this.config)}static async create(e,i={}){let a=new r(e),o=Math.max(1,(i.probe?.attempts??2)+1),s=i.probe?.baseDelayMs??250,c=i.probe?.maxDelayMs??1e3,l,u=null,d=0;for(let e=0;e<o;e++){if(d=e+1,l=await a.serverStats.probeServer(r.CREATE_PROBE_TIMEOUT_MS),l.online)return a;if(u=te(l),u&&!u.retryable)break;if(e<o-1){let t=Math.min(s*2**e,c);await new Promise(e=>setTimeout(e,t))}}await a.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,n.NETWORK_ERROR,{...f!==void 0&&{statusCode:f},context:{serverUrl:a.config.serverUrl,attempts:d,maxAttempts:o,...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(),B(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),R(e,this.config)}async solve(r,a,o){this.ensureNotDisposed();try{if(typeof r==`string`&&!r.trim())throw new t(`Definition URL/content is required`,n.INVALID_INPUT,{context:{receivedUrl:r}});if(r instanceof Uint8Array&&r.length===0)throw new t(`Definition content is empty`,n.INVALID_INPUT);if(m(r)&&!r.key.trim())throw new t(`DefinitionRef key is empty`,n.INVALID_INPUT);let i=await le(a,r,{...this.config,...o?.signal!==void 0&&{signal:o.signal},...o?.timeoutMs!==void 0&&{timeoutMs:o.timeoutMs},...o?.retry!==void 0&&{retry:o.retry},...o?.selvaevents!==void 0&&{selvaevents:o.selvaevents}}),s=e(i,`errors`);if(Array.isArray(s)&&s.length>0)throw new t(s.map(String).join(`; `)||`Computation failed`,n.COMPUTATION_ERROR,{context:{definition:Ue(r),inputSummary:We(a),errors:s,warnings:e(i,`warnings`),values:i.values}});return i}catch(e){throw this.config.debug&&i().error(`Compute failed:`,e),e instanceof t?e:new t(e instanceof Error?e.message:String(e),n.COMPUTATION_ERROR,{context:{definition:Ue(r),inputSummary:We(a)},originalError:e})}}createScheduler(e){return this.ensureNotDisposed(),new He((e,t,n,r)=>ue(t,n,e,r),this.config,e)}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`,n.INVALID_STATE)}};function Ke(e){return typeof e==`object`&&!!e&&e.__decodeError===!0}function qe(e,t){return{__decodeError:!0,type:e,raw:t}}function Je(e){let t=new WeakSet,n=e=>{if(!e||typeof e!=`object`||t.has(e))return;t.add(e);let r=e.delete;if(typeof r==`function`){let t=e.isDeleted;(typeof t!=`function`||!t.call(e))&&r.call(e);return}if(Array.isArray(e)){for(let t of e)n(t);return}let i=Object.getPrototypeOf(e);if(i===Object.prototype||i===null)for(let t of Object.values(e))n(t)};n(e)}const q=new Map([[`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}],[`Rhino.Geometry.Line`,(e,t)=>{let n=t;return!n||!n.From||!n.To?null:new e.Line([n.From.X,n.From.Y,n.From.Z],[n.To.X,n.To.Y,n.To.Z])}]]);function Ye(e){if(q.has(e))return q.get(e);for(let[t,n]of q)if(e.startsWith(t))return n}function Xe(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function Ze(e,t,n){let r=Ye(t),a=!1;if(r)try{let t=r(n,e);if(t!=null)return t}catch(e){i().warn(`Failed to decode Rhino type ${t}:`,e),a=!0}try{if(Xe(e))return n.CommonObject.decode(e)}catch(n){return i().warn(`Failed to decode ${t} with CommonObject:`,n),qe(t,e)}return a?qe(t,e):e}const J={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},Qe=`FileData`;function $e(e,t){return e.includes(`WebDisplay`)||t&&e!==J.STRING}function et(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 tt(e,t,n){switch(t){case J.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case J.INT:return Number.parseInt(String(e),10);case J.DOUBLE:return Number.parseFloat(String(e));case J.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?Ze(e,t,n):e}}function Y(e,t,n,r){if(typeof e.data!=`string`)return e.data;let i=n?et(e.data):e.data;return n&&t.includes(Qe)?nt(i)??i:tt(i,t,r)}function nt(t){if(!t||typeof t!=`object`)return null;let n=e(t,`fileName`),i=e(t,`fileType`),a=e(t,`subFolder`),o=e(t,`isBase64Encoded`);if(typeof n!=`string`||typeof i!=`string`||typeof a!=`string`||!r(t,`data`)||typeof o!=`boolean`&&typeof o!=`string`)return null;let s=e(t,`metadata`);return{fileName:n,fileType:i,data:e(t,`data`),isBase64Encoded:u(o),subFolder:a,...s?{metadata:s}:{}}}function X(t){let n=e(t,`values`);return Array.isArray(n)?n:[]}function Z(e){return typeof e.type==`string`?e.type:``}function Q(e,t){if(e&&typeof e==`object`){for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)e&&typeof e==`object`&&t(e)}}function rt(t,n=!1,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r,s={},c=new Set;for(let r of X(t)){let t=e(r,`paramName`);Q(e(r,`innerTree`),e=>{let r=Z(e);if($e(r,o))return;let l=n?e.id:t;if(!l)return;let u=Y(e,r,i,a);Object.prototype.hasOwnProperty.call(s,l)?c.has(l)?s[l].push(u):(s[l]=[s[l],u],c.add(l)):x(s,l,u)})}return{values:s,dispose:()=>Je(s)}}function it(t){let n=[];for(let r of X(t))Q(e(r,`innerTree`),e=>{if(!Z(e).includes(Qe))return;let t=nt(et(e.data));t&&n.push(t)});return n}function at(t,n,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r;for(let r of X(t)){let t=e(r,`innerTree`),s=!1;if(`byName`in n){if(e(r,`paramName`)!==n.byName)continue;s=!0}let c=[];if(Q(t,e=>{if(`byId`in n){if(e.id!==n.byId)return;s=!0}let t=Z(e);$e(t,o)||c.push(Y(e,t,i,a))}),s)return c.length===0?void 0:c.length===1?c[0]:c}}var ot=class{response;constructor(e){this.response=e}getValues(e=!1,t={}){return rt(this.response,e,t)}getValue(e,t){return at(this.response,e,t)}async getAndDownloadFiles(e,t){await ee(it(this.response),e,t)}};function st(t){return(Array.isArray(t)?t:[t]).map(t=>({schemas:e(t,`schemas`),error:e(t,`error`)}))}const ct=new Set([`options`,`defaultOptions`,`values`]),lt=new Set([`optionMedia`,`assets`]),ut=e=>e>=`A`&&e<=`Z`;function dt(e){if(e.length===0||!ut(e[0]))return e;let t=0;for(;t<e.length&&ut(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function ft(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=dt(n);x(t,e,ct.has(e)?r:lt.has(e)?pt(r):$(r))}return t}function pt(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t={};for(let[n,r]of Object.entries(e))x(t,n,$(r));return t}var mt=class r{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(e,t){let n=this.innerTree[r.formatPathString(e)]??=[];for(let e of t)n.push({data:r.serializeValue(e)});return this}fromDataTreeDefault(e){this.innerTree={};for(let[t,n]of Object.entries(e)){if(!Array.isArray(n))continue;let e=r.parsePathString(t);this.append(e,n)}return this}appendFlat(e){let t=Array.isArray(e)?e:[e];return this.append([0],t)}flatten(){let e=[];for(let t of Object.values(this.innerTree))if(Array.isArray(t))for(let n of t)e.push(r.deserializeValue(n.data));return e}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getParamName(){return this.paramName}static fromInputParams(e){return r.fromValues(e.map(e=>({paramName:e.nickname||`unnamed`,paramType:e.paramType,value:e.default,...`minimum`in e&&{minimum:e.minimum,maximum:e.maximum}})))}static fromValues(e){let t=[];for(let n of e){let e=new r(n.paramName),a=r.itemCoercer(n);for(let[t,o]of r.branchesOf(n.value)){let r=[];for(let e of o){if(e==null)continue;let t=a(e);t===null?i().warn(`${n.paramName}: dropped an item that is not a valid ${n.paramType}`):r.push(t)}r.length>0&&e.append(t,r)}Object.keys(e.innerTree).length>0&&t.push(e.toComputeFormat())}return t}static branchesOf(e){return r.hasValidValue(e)?C(e)?Object.entries(e).map(([e,t])=>[r.parsePathString(e),t]):[[[0],Array.isArray(e)?e:[e]]]:[]}static itemCoercer(e){let{paramName:t,minimum:n,maximum:i}=e,a=e.paramType.toLowerCase();return a===`number`||a===`integer`?e=>{let o=T(e);if(o===null)return null;let s=a===`integer`?Math.round(o):o;return r.clampValue(s,n,i,t)}:a===`boolean`?E:e=>e}static replaceTreeValue(e,t,n){let i=r.buildFromValue(t,n).toComputeFormat(),a=e.slice(),o=a.findIndex(e=>r.paramNameOf(e)===t);return o===-1?a.push(i):a[o]=i,a}static buildFromValue(e,t){let n=new r(e);return C(t)?n.fromDataTreeDefault(t):n.appendFlat(t),n}static getTree(t,n){let i=t.find(e=>r.paramNameOf(e)===n);if(!i)return null;let a=new Map,o=e(i,`InnerTree`);if(!o||typeof o!=`object`)return a;for(let[e,t]of Object.entries(o))Array.isArray(t)&&a.set(e,t.map(e=>e?.data===void 0?null:r.deserializeValue(e.data)));return a}static getTreeValue(e,i){let a=r.getTree(e,i);if(!a||a.size===0)return null;if(a.size>1)throw new t(`"${i}" has ${a.size} branches; read it with TreeBuilder.getTree`,n.INVALID_INPUT,{context:{paramName:i,branchCount:a.size}});let[o]=a.values();return o.length===0?null:o.length===1?o[0]:o}static paramNameOf(t){return e(t,`ParamName`)}static parsePathString(e){let r=e.match(S);if(!r)throw new t(`Invalid Grasshopper tree path: "${e}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`,n.INVALID_INPUT,{context:{pathStr:e}});return r[1]?r[1].split(`;`).map(Number):[]}static formatPathString(e){return`{${e.join(`;`)}}`}static serializeValue(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`?e:typeof e==`object`&&e?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e!=`string`)return e;if(e.startsWith(`{`)||e.startsWith(`[`))try{return JSON.parse(e)}catch{return e}let t=Number(e);return Number.isFinite(t)&&String(t)===e?t:e===`true`||e!==`false`&&e}static hasValidValue(e){return e==null?!1:typeof e==`string`||!(Array.isArray(e)&&e.length===0||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0)}static clampValue(e,t,n,r){let a=e;return t!=null&&a<t&&(i().warn(`${r}: ${e} below min ${t}, clamping`),a=t),n!=null&&a>n&&(i().warn(`${r}: ${e} above max ${n}, clamping`),a=n),a}};export{g as ComputeServerStats,Ge as GrasshopperClient,ot as GrasshopperResponseProcessor,He as SolveScheduler,mt as TreeBuilder,Je as disposeRhinoObjects,R as fetchDefinitionIO,B as fetchParsedDefinitionIO,G as hashDefinition,Le as hashSolveInput,Ke as isRhinoDecodeError,ft as normalizeUISchemaCasing,ke as processInput,st as readSchemaResults,le as solveGrasshopperDefinition,U as stableStringify};
2
2
  //# sourceMappingURL=grasshopper.js.map
@@ -150,11 +150,20 @@ interface ComputeConfig {
150
150
  }
151
151
  /** The config fields that decide how a request authenticates. */
152
152
  type ComputeAuth = Pick<ComputeConfig, 'apiKey' | 'apiKeyHeader' | 'authToken' | 'headers'>;
153
- /** `Server-Timing` durations in ms. `raw` keeps the whole header, unrecognised metrics included. */
153
+ /** The solve endpoint's `Server-Timing`, durations in ms. `raw` keeps the whole header, unrecognised metrics included. */
154
154
  interface ServerTiming {
155
155
  decode?: number;
156
156
  solve?: number;
157
157
  encode?: number;
158
+ /** The part of `solve` spent inside Grasshopper; the rest collects the outputs. */
159
+ gh?: number;
160
+ /** Objects the solve ran out of all it holds. Few ran when only a downstream input changed. */
161
+ recomputed?: {
162
+ ran: number;
163
+ total: number;
164
+ };
165
+ /** The server answered from its result cache and solved nothing. */
166
+ cacheHit?: boolean;
158
167
  raw: string;
159
168
  }
160
169
  //#endregion
@@ -433,4 +442,4 @@ declare const groupFilesByRoot: <T extends Pick<FileData, "subFolder">>(files: r
433
442
  }>;
434
443
  //#endregion
435
444
  export { ServerErrorCodeMap as A, enableDebugLogging as C, ComputeAuth as D, fetchCompute as E, ComputeError as M, ErrorCode as N, ComputeConfig as O, ErrorCodes as P, Logger as S, setLogger as T, SolveDefinition as _, extractFilesFromComputeResponse as a, hasField as b, FileData as c, ProbeVerdict as d, classifyProbeFailure as f, DefinitionRef as g, validateServerUrl as h, downloadFileDataByRoot as i, ServerTiming as j, RetryPolicy as k, ProcessedFile as l, ValidateServerUrlOptions as m, subFolderSegments as n, DownloadOptions as o, DEFAULT_BLOCKED_HOST as p, downloadFileData as r, FileBaseInfo as s, groupFilesByRoot as t, ProbeFailure as u, isDefinitionRef as v, getLogger as w, readField as x, decodeBase64ToBinary as y };
436
- //# sourceMappingURL=index-cMvSohkf.d.ts.map
445
+ //# sourceMappingURL=index-DdWRS7rh.d.cts.map
@@ -150,11 +150,20 @@ interface ComputeConfig {
150
150
  }
151
151
  /** The config fields that decide how a request authenticates. */
152
152
  type ComputeAuth = Pick<ComputeConfig, 'apiKey' | 'apiKeyHeader' | 'authToken' | 'headers'>;
153
- /** `Server-Timing` durations in ms. `raw` keeps the whole header, unrecognised metrics included. */
153
+ /** The solve endpoint's `Server-Timing`, durations in ms. `raw` keeps the whole header, unrecognised metrics included. */
154
154
  interface ServerTiming {
155
155
  decode?: number;
156
156
  solve?: number;
157
157
  encode?: number;
158
+ /** The part of `solve` spent inside Grasshopper; the rest collects the outputs. */
159
+ gh?: number;
160
+ /** Objects the solve ran out of all it holds. Few ran when only a downstream input changed. */
161
+ recomputed?: {
162
+ ran: number;
163
+ total: number;
164
+ };
165
+ /** The server answered from its result cache and solved nothing. */
166
+ cacheHit?: boolean;
158
167
  raw: string;
159
168
  }
160
169
  //#endregion
@@ -433,4 +442,4 @@ declare const groupFilesByRoot: <T extends Pick<FileData, "subFolder">>(files: r
433
442
  }>;
434
443
  //#endregion
435
444
  export { ServerErrorCodeMap as A, enableDebugLogging as C, ComputeAuth as D, fetchCompute as E, ComputeError as M, ErrorCode as N, ComputeConfig as O, ErrorCodes as P, Logger as S, setLogger as T, SolveDefinition as _, extractFilesFromComputeResponse as a, hasField as b, FileData as c, ProbeVerdict as d, classifyProbeFailure as f, DefinitionRef as g, validateServerUrl as h, downloadFileDataByRoot as i, ServerTiming as j, RetryPolicy as k, ProcessedFile as l, ValidateServerUrlOptions as m, subFolderSegments as n, DownloadOptions as o, DEFAULT_BLOCKED_HOST as p, downloadFileData as r, FileBaseInfo as s, groupFilesByRoot as t, ProbeFailure as u, isDefinitionRef as v, getLogger as w, readField as x, decodeBase64ToBinary as y };
436
- //# sourceMappingURL=index-cMvSohkf.d.cts.map
445
+ //# sourceMappingURL=index-DdWRS7rh.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selvajs/compute",
3
- "version": "5.0.0-beta.4",
3
+ "version": "5.0.0-beta.5",
4
4
  "description": "TypeScript library for Rhino Compute Server - Grasshopper and RhinoCommon",
5
5
  "author": "VektorNode",
6
6
  "license": "MIT",
@@ -1,3 +0,0 @@
1
- const e={NETWORK_ERROR:`NETWORK_ERROR`,AUTH_ERROR:`AUTH_ERROR`,VALIDATION_ERROR:`VALIDATION_ERROR`,COMPUTATION_ERROR:`COMPUTATION_ERROR`,TIMEOUT_ERROR:`TIMEOUT_ERROR`,CORS_ERROR:`CORS_ERROR`,NOT_FOUND:`NOT_FOUND`,RATE_LIMIT:`RATE_LIMIT`,INVALID_RESPONSE:`INVALID_RESPONSE`,RESPONSE_TOO_LARGE:`RESPONSE_TOO_LARGE`,UNKNOWN_ERROR:`UNKNOWN_ERROR`,INVALID_STATE:`INVALID_STATE`,INVALID_INPUT:`INVALID_INPUT`,INVALID_CONFIG:`INVALID_CONFIG`,BROWSER_ONLY:`BROWSER_ONLY`,ENVIRONMENT_ERROR:`ENVIRONMENT_ERROR`,ENCODING_ERROR:`ENCODING_ERROR`,MALFORMED_DEFAULT:`MALFORMED_DEFAULT`,SUPERSEDED:`SUPERSEDED`,ABORTED:`ABORTED`,QUEUE_FULL:`QUEUE_FULL`,QUEUE_TIMEOUT:`QUEUE_TIMEOUT`,DEFINITION_NOT_CACHED:`DEFINITION_NOT_CACHED`};var t=class extends Error{code;statusCode;context;originalError;constructor(t,n=e.UNKNOWN_ERROR,r){if(super(t),this.name=`ComputeError`,this.code=n,this.statusCode=r?.statusCode,this.context=r?.context,r?.originalError!==void 0){let e=r.originalError;this.originalError=e instanceof Error?e:Error(String(e)),this.cause=this.originalError}}};const n={debug(){},info(){},warn(){},error(){}};let r=n;function i(){return r}function a(i){if(i===null){r=n;return}let a=[`debug`,`info`,`warn`,`error`].filter(e=>typeof i[e]!=`function`);if(a.length>0)throw new t(`Logger is missing required method(s): ${a.join(`, `)}. A logger must implement debug, info, warn and error.`,e.INVALID_CONFIG,{context:{missingMethods:a}});r=i}function o(){a(console)}function s(e,t){if(!e||typeof e!=`object`)return;if(Object.prototype.hasOwnProperty.call(e,t))return t;let n=t.toLowerCase();return Object.keys(e).find(e=>e.toLowerCase()===n)}function c(e,t){let n=s(e,t);return n===void 0?void 0:e[n]}function l(e,t){return s(e,t)!==void 0}const u=`compute.rhino3d.com`;function d(n,r){let i=n?.trim()??``;if(!i)throw new t(`serverUrl is required`,e.INVALID_CONFIG,{context:{receivedServerUrl:n}});let a=(r,a)=>new t(`Invalid serverUrl: "${i}". ${r}`,e.INVALID_CONFIG,{context:{receivedServerUrl:n},originalError:a});if(!/^https?:\/\//i.test(i))throw a(`Must start with "http://" or "https://". For example: "http://localhost:6500" or "https://example.com"`);let o;try{o=new URL(i)}catch(e){throw a(`Must be a valid URL. Received error: ${e instanceof Error?e.message:String(e)}`,e)}if(o.username!==``||o.password!==``)throw a(`Must not embed credentials (user:pass@host) — fetch rejects credentialed URLs at request time. Pass the API key separately.`);if(i.includes(`?`)||i.includes(`#`))throw a('Must not contain a query string or fragment — endpoint paths are appended to this URL (e.g. "${serverUrl}/version"), and a "?" or "#" suffix would corrupt every request path.');let s=f(o.hostname.toLowerCase(),`.`);if((r?.blockedHosts??[`compute.rhino3d.com`]).map(e=>f(e.toLowerCase(),`.`)).includes(s))throw new t(`serverUrl must be set to your Compute server URL. The shared public endpoint is not allowed.`,e.INVALID_CONFIG,{context:{receivedServerUrl:n}});return f(i,`/`)}function f(e,t){let n=e.length;for(;n>0&&e[n-1]===t;)n--;return e.slice(0,n)}function p(e,t){return`${t}/${e.replace(/^\/+/,``)}`}function m(e){try{let t=new URL(e).hostname.toLowerCase();return t===`localhost`||t===`127.0.0.1`||t===`[::1]`}catch{return/(localhost|127\.0\.0\.1|\[::1\])/i.test(e)}}const h=new Set;function g(e){return y(e.headers,v(e))}function _(e,t){let n=y(t.headers,{...v(t),"X-Request-ID":e,"Content-Type":`application/json`});return!t.apiKey&&!t.authToken&&!h.has(t.serverUrl)&&!m(t.serverUrl)&&(h.add(t.serverUrl),i().warn(`⚠️ [Compute] Request [${e}] targets remote server (${t.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited. (warned once per server)`)),n}function v(e){return{...e.authToken&&{Authorization:e.authToken},...e.apiKey&&{[e.apiKeyHeader??`RhinoComputeKey`]:e.apiKey}}}function y(e,t){let n=new Set(Object.keys(t).map(e=>e.toLowerCase())),r=Object.entries(e??{}).filter(([e])=>!n.has(e.toLowerCase()));return{...Object.fromEntries(r),...t}}function b(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function x(){let e=globalThis.Buffer;return typeof e==`function`?e:void 0}function ee(e){let t=x();return t?t.from(e,`utf-8`).toString(`base64`):T(new TextEncoder().encode(e))}function te(e){let t=S(e);return t===null||/[^A-Za-z0-9+/]/.test(t)?null:t}function S(e){let t=e.replace(/[\t\n\f\r ]/g,``);return t.length%4==0&&(t=t.replace(/={1,2}$/,``)),t.length%4==1?null:t}function ne(e){let t=te(e);if(t===null||t.length<64)return null;let n=t.length%4,r=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.indexOf(t.charAt(t.length-1));return n===2&&r&15||n===3&&r&3?null:n===0?t:t+`==`.slice(0,4-n)}function C(n){let r=S(n),i=r===null?null:re(r);if(i===null)throw new t(`Invalid base64 input.`,e.ENCODING_ERROR,{context:{inputLength:n.length}});return i}function re(n){let r=x();if(r){if(r.byteLength(n,`utf8`)!==n.length||n.includes(`-`)||n.includes(`_`))return null;let e=r.from(n,`base64`);return e.length===Math.floor(n.length*3/4)?e.byteOffset===0&&e.buffer.byteLength===e.length?new Uint8Array(e.buffer,0,e.length):new Uint8Array(e):null}if(typeof globalThis.atob==`function`){let e;try{e=globalThis.atob(n)}catch{return null}let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}throw new t(`Base64 decoding not supported in this environment.`,e.ENVIRONMENT_ERROR,{context:{environmentInfo:`atob or Buffer not available`}})}function w(e){let t=x();if(t)return t.byteLength(e,`utf-8`);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n+=1:r<2048?n+=2:r>=55296&&r<=56319&&t+1<e.length&&(e.charCodeAt(t+1)&64512)==56320?(n+=4,t++):n+=3}return n}function T(n){let r=x();if(r)return r.from(n).toString(`base64`);if(typeof globalThis.btoa==`function`){let e=32766,t=[];for(let r=0;r<n.length;r+=e)t.push(globalThis.btoa(String.fromCharCode.apply(null,n.subarray(r,r+e))));return t.join(``)}throw new t(`Base64 encoding not supported in this environment.`,e.ENVIRONMENT_ERROR,{context:{environmentInfo:`btoa or Buffer not available`}})}const E=1<<20;async function D(e,t=1/0){if(t===1/0)return{text:await e.text(),truncated:!1};if(!e.body){let n=await e.text();return{text:n,truncated:w(n)>t}}let n=Number(e.headers.get(`Content-Length`));if(!e.headers.has(`Content-Encoding`)&&n>t)return await e.body.cancel().catch(()=>{}),{text:``,truncated:!0};let r=e.body.getReader(),i=new TextDecoder,a=[],o=0;for(;;){let{done:e,value:n}=await r.read();if(e)break;if(o+=n.byteLength,a.push(i.decode(n,{stream:!0})),o>t)return await r.cancel().catch(()=>{}),{text:a.join(``),truncated:!0}}return a.push(i.decode()),{text:a.join(``),truncated:!1}}function ie(e){if(!e)return null;let t={raw:e},n=!1;for(let r of e.split(`,`)){let[e,...i]=r.trim().split(`;`),a=i.find(e=>e.trim().toLowerCase().startsWith(`dur`));if(!a)continue;let o=Number(a.split(`=`)[1]);if(!Number.isFinite(o))continue;let s=e.trim().toLowerCase();(s===`decode`||s===`solve`||s===`encode`)&&(t[s]=o,n=!0)}return n?t:null}function O(e,t,n,r){if(!n)return;let a=ie(e.headers.get(`Server-Timing`));if(a)try{n(a,t)}catch(e){r&&i().debug(` onServerTiming callback threw: ${e}`)}}function k(e){return e instanceof Error&&(e.name===`AbortError`||e.name===`TimeoutError`)}function ae(e,t){let n=()=>{};if(typeof t!=`number`||t<=0)return{signal:e,cleanup:n};let r=AbortSignal.timeout(t);if(!e)return{signal:r,cleanup:n};let i=new AbortController,a=[e,r],o=function(){i.abort(this.reason)};for(let e of a){if(e.aborted){i.abort(e.reason);break}e.addEventListener(`abort`,o,{once:!0})}return{signal:i.signal,cleanup:()=>{for(let e of a)e.removeEventListener(`abort`,o)}}}const A=new WeakMap;function j(e,t){typeof e==`object`&&e&&A.set(e,t)}function oe(e){if(typeof e==`object`&&e)return A.get(e)}const M=4096;function se(e){return e.length<=M?e:`${e.slice(0,M)}… [truncated ${e.length-M} chars]`}function ce(n,r,i,a,o){let{status:s,statusText:c}=n,{fullUrl:l,requestId:u,requestSize:d,config:f}=r,p=Object.fromEntries(n.headers.entries()),m=a.trim(),h=m?` — ${m.slice(0,200)}${m.length>200?`…`:``}`:``,g={url:l,requestId:u,method:`POST`,requestSize:d,serverUrl:f.serverUrl,responseBody:i?se(i):void 0,responseHeaders:p},_={400:{message:`Bad request: ${c}${h}`,code:e.VALIDATION_ERROR},401:{message:`HTTP ${s}: ${c}${h}`,code:e.AUTH_ERROR},403:{message:`HTTP ${s}: ${c}${h}`,code:e.AUTH_ERROR},404:{message:`Endpoint not found: ${l}`,code:e.NOT_FOUND},413:{message:`Request too large: ${(d/1024).toFixed(2)}KB`,code:e.VALIDATION_ERROR},429:{message:`Rate limit exceeded${h}`,code:e.RATE_LIMIT},500:{message:`Server error: ${c}${h}`,code:e.COMPUTATION_ERROR},502:{message:`Bad gateway: ${c}${h}`,code:e.NETWORK_ERROR},503:{message:`Service unavailable: ${c}${h}`,code:e.NETWORK_ERROR},504:{message:`Gateway timeout: ${c}${h}`,code:e.NETWORK_ERROR}}[s]||{message:`HTTP ${s}: ${c}${h}`,code:e.UNKNOWN_ERROR},v=f.serverErrorCodes,y=o&&v&&Object.prototype.hasOwnProperty.call(v,o)?v[o]:void 0;throw new t(_.message,y??_.code,{statusCode:s,context:g})}function N(e){return e.type===`opaqueredirect`||e.status>=300&&e.status<400}function le(n,r){let i=n.headers.get(`Location`)??void 0;return new t(`Server redirected the request${i?` to ${i}`:``}. Redirects are not followed, so credentials never leave serverUrl: set serverUrl to the address it redirects to.`,e.INVALID_CONFIG,{...n.status>0&&{statusCode:n.status},context:{url:r.fullUrl,requestId:r.requestId,location:i}})}function P(n,r){let{maxResponseBytes:i}=r.config;return new t(`Response body exceeded maxResponseBytes (${i} bytes)`,e.RESPONSE_TOO_LARGE,{statusCode:n.status,context:{url:r.fullUrl,requestId:r.requestId,maxResponseBytes:i}})}async function ue(n,r,a){let{requestId:o,config:s}=r,{debug:l,onServerTiming:u,maxResponseBytes:d=1/0}=s,f=Math.round(performance.now()-a);if(N(n))throw await n.body?.cancel().catch(()=>{}),le(n,r);if(!n.ok){let e=n.status===500,{text:t,truncated:a}=await D(n,e?d:Math.min(E,d));if(a&&e)throw P(n,r);if(l){let e=i();e.debug(`❌ Request [${o}] failed with HTTP ${n.status} in ${f}ms`),e.debug(` URL: ${r.fullUrl}`),e.debug(` Status: ${n.status} ${n.statusText}`),t&&e.debug(` Response body: ${t.substring(0,500)}${t.length>500?`...`:``}`)}let s,p=!a;if(p)try{s=JSON.parse(t)}catch(t){p=!1,l&&e&&i().debug(` Failed to parse error body as JSON: ${t}`)}let m=typeof s?.code==`string`?s.code:void 0,h=t;if(e&&p){let e=c(s,`values`),r=c(s,`errors`),a=c(s,`warnings`);if(e&&(r||a)){if(j(s,t.length),l){let e=i();e.debug(`⚠️ Request [${o}] completed with solver errors in ${f}ms`),r&&r.length>0&&e.debug(` Errors: ${JSON.stringify(r,null,2)}`),a&&a.length>0&&e.debug(` Warnings: ${JSON.stringify(a,null,2)}`)}return O(n,o,u,l),s}let d=typeof s?.message==`string`&&s.message||typeof s?.Message==`string`&&s.Message||``,p=typeof s?.ExceptionType==`string`&&s.ExceptionType||``,m=s?.stackTrace??s?.StackTrace,g=Array.isArray(m)?m.join(`
2
- `):m||``;d?h=`${p?`${p}: `:``}${d}${g?`\n${g}`:``}`:s?.error&&(h=typeof s.error==`string`?s.error:JSON.stringify(s.error,null,2))}ce(n,r,t,h,m)}l&&i().debug(`✅ Request [${o}] completed in ${f}ms`),O(n,o,u,l);try{let{text:e,truncated:t}=await D(n,d);if(t)throw P(n,r);let i=JSON.parse(e);return j(i,e.length),i}catch(i){if(k(i)||i instanceof t)throw i;let a=(n.headers.get(`Content-Type`)??``).toLowerCase();throw a!==``&&!a.includes(`json`)?new t(`Server returned a non-JSON response (Content-Type: ${a}) — check the server URL / proxy configuration`,e.INVALID_RESPONSE,{statusCode:n.status,context:{url:r.fullUrl,requestId:o,contentType:a},originalError:i}):new t(`Failed to parse JSON response`,e.NETWORK_ERROR,{statusCode:n.status,context:{url:r.fullUrl,requestId:o},originalError:i})}}const F=/ECONNREFUSED|ERR_CONNECTION_REFUSED|connection refused/i,I=/ENOTFOUND|EAI_AGAIN|getaddrinfo|ERR_NAME_NOT_RESOLVED|dns/i,L=/TimeoutError|ETIMEDOUT|ECONNRESET|EHOSTUNREACH|ENETUNREACH|abort|timed? ?out/i;function R(e){if(e.online)return null;if(e.status!==void 0){if(e.status===401||e.status===403)return{verdict:`unauthorized`,retryable:!1,summary:`The server rejected the liveness probe with HTTP ${e.status} — check the API key.`};let t=e.status>=500;return{verdict:`http_error`,retryable:t,summary:t?`The server answered HTTP ${e.status} — it may still be starting up.`:`The server answered HTTP ${e.status}, which will not change on retry.`}}let t=e.error??``;return F.test(t)?{verdict:`refused`,retryable:!1,summary:`Connection refused — the host is reachable but nothing is listening on that port. Rhino.Compute is not running, or the URL names the wrong port.`}:I.test(t)?{verdict:`dns`,retryable:!0,summary:`The server hostname could not be resolved — check the URL and DNS.`}:L.test(t)?{verdict:`timeout`,retryable:!0,summary:`No response before the timeout — the machine may be powered off, blocked by a firewall, or still booting.`}:{verdict:`unknown`,retryable:!0,summary:t?`The connection failed: ${t}`:`The connection failed.`}}const z={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},B=new Set([502,503,504]);function V(e){return e?{attempts:e.attempts??z.attempts,baseDelayMs:e.baseDelayMs??z.baseDelayMs,maxDelayMs:e.maxDelayMs??z.maxDelayMs,retryOn429:e.retryOn429??z.retryOn429}:z}function H(e,t){return B.has(e)||t.retryOn429&&e===429}function U(e,t,n){let r=de(e);return r===null?W(t,n):Math.min(r,Math.max(n.maxDelayMs,6e4))}function de(e){if(!e)return null;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n)){let e=n-Date.now();return e>0?e:0}return null}function W(e,t){let n=t.baseDelayMs*2**e,r=Math.random()*t.baseDelayMs;return Math.min(n+r,t.maxDelayMs)}function fe(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))};t?.addEventListener(`abort`,a,{once:!0})})}function G(n,r){return new t(`Request aborted by caller`,e.ABORTED,{context:n.errorContext,originalError:r})}async function pe(n,r,i,a){let{signal:o,cleanup:s}=ae(n.config.signal,n.config.timeoutMs),c=performance.now();try{let s=await fetch(n.fullUrl,{method:`POST`,body:n.body,headers:n.headers,signal:o,redirect:`manual`});return!a&&H(s.status,r)?(await D(s,E).catch(()=>{}),{ok:!1,retryable:!0,delayMs:U(s.headers.get(`Retry-After`),i,r),cause:new t(`HTTP ${s.status} ${s.statusText} (will retry)`,s.status===429?e.RATE_LIMIT:e.NETWORK_ERROR,{statusCode:s.status,context:n.errorContext})}):{ok:!0,value:await ue(s,n,c)}}catch(e){return me(e,n)}finally{s()}}function me(n,r){if(k(n)){if(r.config.signal?.aborted)return{ok:!1,retryable:!1,cause:G(r,n)};let{timeoutMs:i}=r.config;return{ok:!1,retryable:!0,cause:typeof i==`number`&&i>0?new t(`Request timed out after ${i}ms`,e.TIMEOUT_ERROR,{context:{...r.errorContext,timeoutMs:i},originalError:n}):new t(`Request aborted by the runtime (${n.name}): ${n.message}`,e.NETWORK_ERROR,{context:r.errorContext,originalError:n})}}if(n instanceof TypeError)return{ok:!1,retryable:!0,cause:typeof window<`u`&&window.document!==void 0?new t(`Request failed: ${n.message} — in a browser this usually means a CORS misconfiguration on the server (or a network failure; the browser does not distinguish them)`,e.CORS_ERROR,{context:r.errorContext,originalError:n}):new t(`Network error: ${n.message}`,e.NETWORK_ERROR,{context:r.errorContext,originalError:n})};if(n instanceof t){let t=n.statusCode;return{ok:!1,retryable:n.code===e.NETWORK_ERROR&&t!==void 0&&t>=200&&t<300,cause:n}}return{ok:!1,retryable:!1,cause:new t(n instanceof Error?n.message:String(n),e.UNKNOWN_ERROR,{context:r.errorContext,originalError:n})}}async function he(n,r,a){let o=b(),s;try{s=JSON.stringify(r)}catch(r){throw new t(`Request body is not JSON-serializable: ${r instanceof Error?r.message:String(r)}`,e.INVALID_INPUT,{context:{endpoint:n,requestId:o},originalError:r})}let c=w(s),l=d(a.serverUrl,{blockedHosts:[]}),{maxResponseBytes:u}=a;if(u!==void 0&&!(u>=0))throw new t(`maxResponseBytes must be a number of bytes, got ${u}`,e.INVALID_CONFIG,{context:{maxResponseBytes:u}});let f=p(n,l),m=_(o,a),h=V(a.retry),g=h.attempts+1;if(a.debug){let e=(c/1024).toFixed(2),t=c>1e5?`⚠️`:`🚀`;i().debug(`${t} Starting compute request [${o}]: ${n} (${e}KB)`)}let v={endpoint:n,body:s,requestSize:c,fullUrl:f,requestId:o,headers:m,config:a,errorContext:{serverUrl:l,url:f,endpoint:n,requestId:o,requestSize:c}};for(let e=0;;e++){let t=e>=h.attempts,n=await pe(v,h,e,t);if(n.ok)return n.value;if(t||!n.retryable)throw n.cause;let r=n.delayMs??W(e,h);a.debug&&i().debug(`🔁 Request [${o}] retrying after ${r}ms (attempt ${e+2}/${g}): ${n.cause.message}`);try{await fe(r,a.signal)}catch{throw G(v,n.cause)}}}function ge(e){return typeof e==`object`&&!(e instanceof Uint8Array)&&typeof e.key==`string`&&typeof e.load==`function`}function _e(e){return typeof e==`string`&&/^https?:\/\//i.test(e)}const K=e=>(e??``).replace(/::/g,`/`).replace(/\\/g,`/`).split(`/`).map(e=>e.trim()).filter(e=>e!==``),ve=e=>K(e.subFolder)[0]??``,ye=e=>K(e.subFolder).slice(1).join(`/`),q=e=>{let t=new Map;for(let n of e){let e=ve(n),r=t.get(e);r?r.push(n):t.set(e,[n])}return Array.from(t,([e,t])=>({root:e,files:t}))},be=e=>{let t=e.replace(/[/\\:*?"<>|]/g,`_`).replace(/\s+/g,` `).trim().replace(/^\.+/,``);return t===``?`files`:t},J=async(e,t=null)=>{let n=xe(e);if(t){let e=Array.isArray(t)?t:[t];n.push(...await Se(e))}let r=new Set;return n.map(e=>{let t=$(e.path,r);return r.add(t),t===e.path?e:(i().warn(`Duplicate archive path "${e.path}" — storing as "${t}".`),{...e,path:t,fileName:t.slice(t.lastIndexOf(`/`)+1)})})},Y=async(n,r,i=null,a={})=>{if(typeof document>`u`||typeof Blob>`u`)throw new t(`File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).`,e.BROWSER_ONLY,{context:{environment:typeof window<`u`?`browser (SSR)`:`Node.js`,documentAvailable:typeof document<`u`,blobAvailable:typeof Blob<`u`}});try{await Ce(await J(n,i),r,a.saveBlob??we)}catch(n){throw n instanceof t?n:new t(`Failed to download files from compute response`,e.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)},originalError:n})}},X=async(e,t,n=null,r={})=>{let i=q(e);if(i.length===0){await Y([],t,n,r);return}let a=(i.find(e=>e.root===``)??i[0]).root;for(let{root:e,files:o}of i)await Y(e===``?o:o.map(e=>({...e,subFolder:ye(e)})),e===``?t:be(e),e===a?n:null,r)},Z=e=>K(e).filter(e=>e!==`.`&&e!==`..`&&!/^[a-zA-Z]:$/.test(e)).join(`/`),Q=e=>e===!0||typeof e==`string`&&e.trim().toLowerCase()===`true`,xe=e=>{let t=[];return e.forEach(e=>{let n=c(e,`fileName`)??``,r=c(e,`fileType`)??``,a=Z(`${n}${r}`);if(a===``){i().warn(`Skipping file with unusable name "${n}${r}": no safe archive path remains after sanitization.`);return}let o=c(e,`subFolder`),s=o?Z(o):``,l=s===``?a:`${s}/${a}`,u=c(e,`data`);if(typeof u!=`string`||u===``){i().warn(`Skipping file "${l}": item carries no usable data.`);return}let d=c(e,`metadata`);if(Q(c(e,`isBase64Encoded`)))try{t.push({fileName:a,content:C(u),path:l,subFolder:s,...d?{metadata:d}:{}})}catch(e){i().warn(`Skipping file "${l}": base64 decode failed.`,e)}else t.push({fileName:a,content:u,path:l,subFolder:s,...d?{metadata:d}:{}})}),t},Se=async e=>(await Promise.all(e.map(async e=>{try{let t=await fetch(e.filePath,{signal:AbortSignal.timeout(3e4)});if(!t.ok)return i().warn(`Failed to fetch additional file from URL: ${e.filePath}`),null;let n=await t.arrayBuffer(),r=Z(e.fileName);if(r===``)return i().warn(`Skipping fetched file with unusable name: ${e.fileName}`),null;let a=e.subFolder?Z(e.subFolder):``;return{fileName:r,content:new Uint8Array(n),path:a===``?r:`${a}/${r}`,subFolder:a}}catch(t){return i().error(`Error fetching additional file from URL: ${e.filePath}`,t),null}}))).filter(e=>e!==null);async function Ce(e,t,n){let{zip:r,strToU8:i}=await import(`fflate`),a=new Set(e.map(e=>e.path)),o={};for(let t of e){let e=t.path===`__proto__`?$(t.path,a):t.path;a.add(e),o[e]=typeof t.content==`string`?i(t.content):t.content}let s=await new Promise((e,t)=>{r(o,{level:6},(n,r)=>n?t(n):e(r))});await n(new Blob([s],{type:`application/zip`}),`${t}.zip`)}function $(e,t){if(!t.has(e))return e;let n=e.lastIndexOf(`/`),r=e.lastIndexOf(`.`),i=r>n?r:e.length,a=e.slice(0,i),o=e.slice(i);for(let e=2;;e++){let n=`${a}-${e}${o}`;if(!t.has(n))return n}}function we(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4)}export{c as C,t as D,a as E,e as O,l as S,i as T,ne as _,q as a,u as b,_e as c,N as d,oe as f,C as g,T as h,Q as i,he as l,D as m,X as n,K as o,j as p,J as r,ge as s,Y as t,R as u,ee as v,o as w,d as x,g as y};
3
- //# sourceMappingURL=core-CFlbOj2M.js.map