@selvajs/compute 3.0.1-beta.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/chunk-6LCAIDQV.cjs +4 -0
  2. package/dist/chunk-6LCAIDQV.cjs.map +1 -0
  3. package/dist/chunk-CFBKO3HX.cjs +2 -0
  4. package/dist/chunk-CFBKO3HX.cjs.map +1 -0
  5. package/dist/chunk-JF5MZTOU.cjs +55 -0
  6. package/dist/{chunk-MBCMFI2R.cjs.map → chunk-JF5MZTOU.cjs.map} +1 -1
  7. package/dist/chunk-LUP3B2DK.js +55 -0
  8. package/dist/{chunk-G3SQHFDY.js.map → chunk-LUP3B2DK.js.map} +1 -1
  9. package/dist/chunk-O55PTKMV.js +4 -0
  10. package/dist/chunk-O55PTKMV.js.map +1 -0
  11. package/dist/chunk-UAL4YXRX.js +2 -0
  12. package/dist/chunk-UAL4YXRX.js.map +1 -0
  13. package/dist/core.cjs +1 -1
  14. package/dist/core.d.cts +1 -10
  15. package/dist/core.d.ts +1 -10
  16. package/dist/core.js +1 -1
  17. package/dist/grasshopper.cjs +1 -1
  18. package/dist/grasshopper.d.cts +2 -2
  19. package/dist/grasshopper.d.ts +2 -2
  20. package/dist/grasshopper.js +1 -1
  21. package/dist/{handle-files-9pkEgDIp.d.ts → handle-files-Bu2qmaPj.d.cts} +2 -2
  22. package/dist/{handle-files-9pkEgDIp.d.cts → handle-files-Bu2qmaPj.d.ts} +2 -2
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.d.cts +1 -1
  25. package/dist/index.d.ts +1 -1
  26. package/dist/index.js +1 -1
  27. package/dist/visualization-LZ4XZPYZ.cjs +2 -0
  28. package/dist/visualization-LZ4XZPYZ.cjs.map +1 -0
  29. package/dist/visualization-SV4BTHXJ.js +2 -0
  30. package/dist/visualization.cjs +1 -1
  31. package/dist/visualization.js +1 -1
  32. package/package.json +3 -3
  33. package/dist/chunk-AUAMZCIL.cjs +0 -2
  34. package/dist/chunk-AUAMZCIL.cjs.map +0 -1
  35. package/dist/chunk-FMMK2QTR.js +0 -4
  36. package/dist/chunk-FMMK2QTR.js.map +0 -1
  37. package/dist/chunk-G3SQHFDY.js +0 -55
  38. package/dist/chunk-G5XWFITM.js +0 -2
  39. package/dist/chunk-G5XWFITM.js.map +0 -1
  40. package/dist/chunk-LBRCTJ7W.cjs +0 -4
  41. package/dist/chunk-LBRCTJ7W.cjs.map +0 -1
  42. package/dist/chunk-MBCMFI2R.cjs +0 -55
  43. package/dist/visualization-LTWBUHLN.cjs +0 -2
  44. package/dist/visualization-LTWBUHLN.cjs.map +0 -1
  45. package/dist/visualization-SU3XQ35P.js +0 -2
  46. /package/dist/{visualization-SU3XQ35P.js.map → visualization-SV4BTHXJ.js.map} +0 -0
@@ -0,0 +1,4 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var $=Object.defineProperty;var k=(t,e,r)=>e in t?$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var le=(t,e)=>{for(var r in e)$(t,r,{get:e[r],enumerable:!0})};var g=(t,e,r)=>k(t,typeof e!="symbol"?e+"":e,r);var u={NETWORK_ERROR:"NETWORK_ERROR",AUTH_ERROR:"AUTH_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",COMPUTATION_ERROR:"COMPUTATION_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",CORS_ERROR:"CORS_ERROR",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",DEFINITION_NOT_CACHED:"DEFINITION_NOT_CACHED"},d= exports.d =class t extends Error{constructor(r,n="UNKNOWN_ERROR",o){super(r);g(this,"code");g(this,"statusCode");g(this,"context");g(this,"originalError");this.name="RhinoComputeError",this.code=n,this.statusCode=_optionalChain([o, 'optionalAccess', _2 => _2.statusCode]),this.context=_optionalChain([o, 'optionalAccess', _3 => _3.context]),this.originalError=_optionalChain([o, 'optionalAccess', _4 => _4.originalError]),_optionalChain([o, 'optionalAccess', _5 => _5.originalError])&&(this.cause=o.originalError)}static missingValues(r,n,o){return new t(`Input "${r}" has no values defined${n?` (expected ${n})`:""}`,u.INVALID_INPUT,{context:{inputName:r,expectedType:n,...o}})}static unknownParamType(r,n,o){return new t(`Unknown paramType: ${r}`,u.VALIDATION_ERROR,{context:{receivedParamType:r,paramName:n,...o}})}};var T=class{debug(){}info(){}warn(){}error(){}},N=class{debug(e,...r){console.debug(e,...r)}info(e,...r){console.info(e,...r)}warn(e,...r){console.warn(e,...r)}error(e,...r){console.error(e,...r)}},U=new T;function p(){return U}function D(t){U=t===null?new T:t}function B(){D(new N)}function q(t){if(!t)return null;let e={raw:t},r=!1;for(let n of t.split(",")){let[o,...i]=n.trim().split(";"),f=i.find(c=>c.trim().toLowerCase().startsWith("dur"));if(!f)continue;let s=Number(f.split("=")[1]);if(!Number.isFinite(s))continue;let l=o.trim().toLowerCase();(l==="decode"||l==="solve"||l==="encode")&&(e[l]=s,r=!0)}return r?e:null}var E={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},_=new Set([502,503,504]);function K(t){return t?{attempts:_nullishCoalesce(t.attempts, () => (E.attempts)),baseDelayMs:_nullishCoalesce(t.baseDelayMs, () => (E.baseDelayMs)),maxDelayMs:_nullishCoalesce(t.maxDelayMs, () => (E.maxDelayMs)),retryOn429:_nullishCoalesce(t.retryOn429, () => (E.retryOn429))}:E}function W(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e)&&e>=0)return e*1e3;let r=Date.parse(t);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return null}function S(t,e){let r=e.baseDelayMs*Math.pow(2,t),n=Math.random()*e.baseDelayMs;return Math.min(r+n,e.maxDelayMs)}function H(t,e){return new Promise((r,n)=>{if(_optionalChain([e, 'optionalAccess', _6 => _6.aborted])){n(new DOMException("Aborted","AbortError"));return}let o=setTimeout(()=>{_optionalChain([e, 'optionalAccess', _7 => _7.removeEventListener, 'call', _8 => _8("abort",i)]),r()},t),i=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))};_optionalChain([e, 'optionalAccess', _9 => _9.addEventListener, 'call', _10 => _10("abort",i,{once:!0})])})}function z(t,e,r,n,o,i,f){let{status:s,statusText:l}=t,c={};t.headers.forEach((A,M)=>{c[M]=A});let m=i.trim(),a=m?` \u2014 ${m.slice(0,200)}${m.length>200?"\u2026":""}`:"",y={url:e,requestId:r,method:"POST",requestSize:n,serverUrl:o,responseBody:i||void 0,responseHeaders:c},v={401:{message:`HTTP ${s}: ${l}${a}`,code:u.AUTH_ERROR},403:{message:`HTTP ${s}: ${l}${a}`,code:u.AUTH_ERROR},404:{message:`Endpoint not found: ${e}`,code:u.NETWORK_ERROR},413:{message:`Request too large: ${(n/1024).toFixed(2)}KB`,code:u.VALIDATION_ERROR},429:{message:`Rate limit exceeded${a}`,code:u.NETWORK_ERROR},500:{message:`Server error: ${l}${a}`,code:u.COMPUTATION_ERROR},502:{message:`Service unavailable: ${l}${a}`,code:u.NETWORK_ERROR},503:{message:`Service unavailable: ${l}${a}`,code:u.NETWORK_ERROR},504:{message:`Service unavailable: ${l}${a}`,code:u.NETWORK_ERROR}}[s]||{message:`HTTP ${s}: ${l}${a}`,code:u.UNKNOWN_ERROR},w=_nullishCoalesce(V(f), () => (v.code));throw new d(v.message,w,{statusCode:s,context:y})}function V(t){if(t==="definition_not_cached")return u.DEFINITION_NOT_CACHED}function J(t,e){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${r}/${n}`}function G(t){try{let e=new URL(t).host;return/^(localhost|127\.0\.0\.1|::1)(:\d+)?$/i.test(e)}catch (e2){return/(localhost|127\.0\.0\.1)/i.test(t)}}function Y(t,e){let r={"X-Request-ID":t,"Content-Type":"application/json",...e.authToken&&{Authorization:e.authToken},...e.apiKey&&{RhinoComputeKey:e.apiKey}};return!e.apiKey&&!e.authToken&&!G(e.serverUrl)&&p().warn(`\u26A0\uFE0F [Rhino Compute] Request [${t}] targets remote server (${e.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited.`),r}function j(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function R(t,e){e&&p().debug(t)}function Z(t,e){let r=[],n=()=>{};if(t&&r.push(t),e&&e>0)if(typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function")r.push(AbortSignal.timeout(e));else{let s=new AbortController,l=setTimeout(()=>s.abort(),e);n=()=>clearTimeout(l),r.push(s.signal)}if(r.length===0)return{signal:void 0,cleanup:n};if(r.length===1)return{signal:r[0],cleanup:n};if(typeof AbortSignal<"u"&&typeof AbortSignal.any=="function")return{signal:AbortSignal.any(r),cleanup:n};let o=new AbortController,i=()=>o.abort();for(let s of r){if(s.aborted){o.abort();break}s.addEventListener("abort",i,{once:!0})}let f=n;return n=()=>{f();for(let s of r)s.removeEventListener("abort",i)},{signal:o.signal,cleanup:n}}async function X(t,e,r,n,o,i,f,s){let l=Math.round(performance.now()-i);if(!t.ok){let c=await t.text();f&&(R(`\u274C Request [${r}] failed with HTTP ${t.status} in ${l}ms`,!0),R(` URL: ${e}`,!0),R(` Status: ${t.status} ${t.statusText}`,!0),c&&R(` Response body: ${c.substring(0,500)}${c.length>500?"...":""}`,!0));let m;try{let a=JSON.parse(c);typeof _optionalChain([a, 'optionalAccess', _11 => _11.code])=="string"&&(m=a.code)}catch (e3){}if(t.status===500)try{let a=JSON.parse(c);if(_optionalChain([a, 'optionalAccess', _12 => _12.values])&&(a.errors||a.warnings))return f&&(R(`\u26A0\uFE0F Request [${r}] completed with Grasshopper errors in ${l}ms`,!0),_optionalChain([a, 'access', _13 => _13.errors, 'optionalAccess', _14 => _14.length])>0&&R(` Errors: ${JSON.stringify(a.errors,null,2)}`,!0),_optionalChain([a, 'access', _15 => _15.warnings, 'optionalAccess', _16 => _16.length])>0&&R(` Warnings: ${JSON.stringify(a.warnings,null,2)}`,!0)),a;let y=typeof _optionalChain([a, 'optionalAccess', _17 => _17.message])=="string"&&a.message||typeof _optionalChain([a, 'optionalAccess', _18 => _18.Message])=="string"&&a.Message||"",h=typeof _optionalChain([a, 'optionalAccess', _19 => _19.ExceptionType])=="string"&&a.ExceptionType||"",v=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _20 => _20.stackTrace]), () => (_optionalChain([a, 'optionalAccess', _21 => _21.StackTrace]))),w=Array.isArray(v)?v.join(`
2
+ `):v||"";y?c=`${h?`${h}: `:""}${y}${w?`
3
+ ${w}`:""}`:_optionalChain([a, 'optionalAccess', _22 => _22.error])&&(c=typeof a.error=="string"?a.error:JSON.stringify(a.error,null,2))}catch(a){f&&R(` Failed to parse error body as JSON: ${a}`,!0)}z(t,e,r,n,o,c,m)}if(R(`\u2705 Request [${r}] completed in ${l}ms`,f),s){let c=q(t.headers.get("Server-Timing"));if(c)try{s(c)}catch(m){f&&R(` onServerTiming callback threw: ${m}`,!0)}}try{return await t.json()}catch(c){throw new d("Failed to parse JSON response",u.NETWORK_ERROR,{statusCode:t.status,context:{url:e,requestId:r},originalError:c instanceof Error?c:new Error(String(c))})}}async function Q(t,e,r,n){let{signal:o,cleanup:i}=Z(t.config.signal,t.config.timeoutMs),f=performance.now();try{let s=await fetch(t.fullUrl,{method:"POST",body:t.body,headers:t.headers,signal:o});if((_.has(s.status)||e.retryOn429&&s.status===429)&&r<n-1){let m=W(s.headers.get("Retry-After")),a=m!==null?Math.min(m,e.maxDelayMs):S(r,e);return await s.text().catch(()=>{}),{ok:!1,retry:!0,delayMs:a,cause:new d(`HTTP ${s.status} ${s.statusText} (will retry)`,u.NETWORK_ERROR,{statusCode:s.status,context:{requestId:t.requestId}})}}return{ok:!0,value:await X(s,t.fullUrl,t.requestId,t.requestSize,t.config.serverUrl,f,t.config.debug,t.config.onServerTiming)}}catch(s){if(s instanceof Error&&(s.name==="AbortError"||s.name==="TimeoutError")){if(_optionalChain([t, 'access', _23 => _23.config, 'access', _24 => _24.signal, 'optionalAccess', _25 => _25.aborted])===!0)return{ok:!1,retry:!1,cause:new d("Request aborted by caller",u.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId,requestSize:t.requestSize},originalError:s})};let c=new d(`Request timed out after ${t.config.timeoutMs}ms`,u.TIMEOUT_ERROR,{context:{serverUrl:t.config.serverUrl,timeoutMs:t.config.timeoutMs,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize}});return r<n-1?{ok:!1,retry:!0,delayMs:S(r,e),cause:c}:{ok:!1,retry:!1,cause:c}}if(s instanceof TypeError){let l=new d(`Network error: ${s.message}`,u.NETWORK_ERROR,{context:{serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:s});return r<n-1?{ok:!1,retry:!0,delayMs:S(r,e),cause:l}:{ok:!1,retry:!1,cause:l}}if(s instanceof d){let l=s.statusCode;return l!==void 0&&(_.has(l)||e.retryOn429&&l===429)&&r<n-1?{ok:!1,retry:!0,delayMs:S(r,e),cause:s}:{ok:!1,retry:!1,cause:s}}return{ok:!1,retry:!1,cause:new d(s instanceof Error?s.message:String(s),u.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId},originalError:s instanceof Error?s:new Error(String(s))})}}finally{i()}}async function ee(t,e,r){let n=j(),o=JSON.stringify(e),i=o.length,f=J(t,r.serverUrl),s=Y(n,r),l=K(r.retry),c=l.attempts+1;if(r.debug){let y=(i/1024).toFixed(2),h=i>1e5?"\u26A0\uFE0F":"\u{1F680}";R(`${h} Starting compute request [${n}]: ${t} (${y}KB)`,!0)}let m={endpoint:t,body:o,requestSize:i,fullUrl:f,requestId:n,headers:s,config:r},a=null;for(let y=0;y<c;y++){let h=await Q(m,l,y,c);if(h.ok)return h.value;if(!h.retry)throw h.cause;a=h.cause,r.debug&&R(`\u{1F501} Request [${n}] retrying after ${h.delayMs}ms (attempt ${y+2}/${c}): ${h.cause.message}`,!0);try{await H(h.delayMs,r.signal)}catch (e4){throw new d("Request aborted by caller",u.UNKNOWN_ERROR,{context:{endpoint:t,requestId:n,requestSize:i},originalError:a})}}throw _nullishCoalesce(a, () => (new d("Unknown error after retries",u.UNKNOWN_ERROR,{context:{endpoint:t,requestId:n,requestSize:i}})))}var re="https://compute.rhino3d.com/";function F(t){if(!_optionalChain([t, 'optionalAccess', _26 => _26.trim, 'call', _27 => _27()]))throw new d("serverUrl is required",u.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(!t.match(/^https?:\/\//))throw new d(`Invalid serverUrl: "${t}". Must start with "http://" or "https://". For example: "http://localhost:5000" or "https://example.com"`,u.INVALID_CONFIG,{context:{receivedServerUrl:t}});try{new URL(t)}catch(e){throw new d(`Invalid serverUrl: "${t}". Must be a valid URL. Received error: ${e instanceof Error?e.message:String(e)}`,u.INVALID_CONFIG,{context:{receivedServerUrl:t},originalError:e instanceof Error?e:void 0})}if(t===re)throw new d("serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.",u.INVALID_CONFIG,{context:{receivedServerUrl:t}});return t.replace(/\/+$/,"")}var b=class b{constructor(e,r){g(this,"serverUrl");g(this,"apiKey");g(this,"disposed",!1);g(this,"activeMonitors",new Set);g(this,"activeTimeouts",new Set);this.serverUrl=F(e),this.apiKey=r}buildHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,r={},n=b.DEFAULT_TIMEOUT_MS){let o={headers:this.buildHeaders(),...r};return n>0&&!o.signal&&(o.signal=AbortSignal.timeout(n)),fetch(e,o)}async isServerOnline(e=5e3){this.ensureNotDisposed();let r=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(r,{method:"GET"},e)).ok}catch(n){return p().debug("[ComputeServerStats] Fetch error:",n),!1}}async getActiveChildren(e={}){this.ensureNotDisposed();let{initialize:r=!0}=e,n=r?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,o=r?b.LIFECYCLE_TIMEOUT_MS:b.DEFAULT_TIMEOUT_MS;try{let i=await this.fetchWithTimeout(n,{},o);if(!i.ok)return p().warn("[ComputeServerStats] Failed to fetch active children:",i.status),null;let f=await i.text(),s=parseInt(f.trim(),10);return isNaN(s)?(p().warn("[ComputeServerStats] Invalid active children response:",f),null):s}catch(i){return p().warn("[ComputeServerStats] Error fetching active children:",i),null}}async getVersion(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch version:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return{rhino:_nullishCoalesce(n.rhino, () => ("")),compute:_nullishCoalesce(n.compute, () => ("")),git_sha:_nullishCoalesce(n.git_sha, () => (null))}}catch (e5){return{rhino:r,compute:"",git_sha:null}}}catch(e){return p().warn("[ComputeServerStats] Error fetching version:",e),null}}async getInstalledPlugins(e="gh"){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${e}/installed`);if(!r.ok)return p().warn(`[ComputeServerStats] Failed to fetch ${e} plugins:`,r.status),null;let n=await r.text();try{let o=JSON.parse(n);return o&&typeof o=="object"?o:null}catch (e6){return null}}catch(r){return p().warn(`[ComputeServerStats] Error fetching ${e} plugins:`,r),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[r,n]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...r&&{version:r},...n!==null&&{activeChildren:n}}}async purgeCache(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:"POST"});if(!e.ok)return p().warn("[ComputeServerStats] Failed to purge cache:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return typeof n.purged=="number"?n.purged:null}catch (e7){return null}}catch(e){return p().warn("[ComputeServerStats] Error purging cache:",e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return p().warn("[ComputeServerStats] purgeAllChildren: could not read child count"),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let r=e*2,n=0;for(let o=0;o<r;o++){let i=await this.purgeCache();i!==null&&(n+=i)}return{totalPurged:n,calls:r,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch server time:",e.status),null;let r=(await e.text()).trim().replace(/^"|"$/g,""),n=new Date(r);return isNaN(n.getTime())?null:n}catch(e){return p().warn("[ComputeServerStats] Error fetching server time:",e),null}}async getIdleSpan(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch idle span:",e.status),null;let r=parseFloat((await e.text()).trim());return isNaN(r)?null:r}catch(e){return p().warn("[ComputeServerStats] Error fetching idle span:",e),null}}async launchChildren(){return this.postJson("/launch-children")}async launchChild(e){let r=e===void 0?"/launch-child":`/launch-child?port=${e}`;return this.postJson(r)}async shutdownChildren(e){let r=e===void 0?"/shutdown-children":`/shutdown-children?port=${e}`;return this.postJson(r)}async recycleChildren(e){let r=e===void 0?"/recycle-children":`/recycle-children?port=${e}`;return this.postJson(r)}async postJson(e){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}${e}`,{method:"POST"},b.LIFECYCLE_TIMEOUT_MS);if(!r.ok)return p().warn(`[ComputeServerStats] POST ${e} failed:`,r.status),null;let n=await r.text();try{return JSON.parse(n)}catch (e8){return null}}catch(r){return p().warn(`[ComputeServerStats] Error on POST ${e}:`,r),null}}monitor(e,r=5e3){this.ensureNotDisposed();let n=!0,o=null;p().info(`\u{1F504} Starting server stats monitoring every ${r}ms`);let i=async()=>{if(o!==null&&(this.activeTimeouts.delete(o),o=null),!(!n||this.disposed)){try{let s=await this.getServerStats();if(!n||this.disposed)return;try{e(s)}catch(l){p().error("[ComputeServerStats] Monitor callback threw:",l)}}catch(s){p().error("[ComputeServerStats] Failed to fetch stats during monitor:",s)}n&&!this.disposed&&(o=setTimeout(()=>{i()},r),this.activeTimeouts.add(o))}},f=()=>{n=!1,o!==null&&(clearTimeout(o),this.activeTimeouts.delete(o),o=null),this.activeMonitors.delete(f)};return this.activeMonitors.add(f),i(),f}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new d("ComputeServerStats has been disposed and cannot be used",u.INVALID_STATE,{context:{disposed:this.disposed}})}};g(b,"DEFAULT_TIMEOUT_MS",5e3),g(b,"LIFECYCLE_TIMEOUT_MS",6e4);var O=b;function P(t,e={}){let{preserveSpaces:r=!1}=e,n=r?/[-_]+(.)?/g:/[\s-_]+(.)?/g,o=t.trim();return o.charAt(0).toLowerCase()+o.slice(1).replace(n,(i,f)=>f?f.toUpperCase():"")}function C(t,e={}){return!t||typeof t!="object"?t:Array.isArray(t)?e.deep?t.map(r=>C(r,e)):t:Object.keys(t).reduce((r,n)=>{let o=P(n,{preserveSpaces:e.preserveSpaces}),i=t[n];return r[o]=e.deep?C(i,e):i,r},{})}function I(){let t=globalThis.Buffer;return typeof t=="function"?t:void 0}function Ne(t){let e=I();return e?e.from(t,"utf-8").toString("base64"):te(new TextEncoder().encode(t))}function Ce(t){return!t||t.length<2||t.length%4!==0?!1:/^[A-Za-z0-9+/]+={0,2}$/.test(t)}function L(t){let e=I();if(e){let r=e.from(t,"base64");return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(typeof globalThis.atob=="function"){let r=globalThis.atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r.charCodeAt(o)&255;return n}throw new d("Base64 decoding not supported in this environment.",u.INVALID_STATE,{context:{environmentInfo:"atob or Buffer not available"}})}function te(t){let e=I();if(e)return e.from(t).toString("base64");if(typeof globalThis.btoa=="function"){let n="";for(let o=0;o<t.length;o+=32768)n+=String.fromCharCode.apply(null,t.subarray(o,o+32768));return globalThis.btoa(n)}throw new d("Base64 encoding not supported in this environment.",u.INVALID_STATE,{context:{environmentInfo:"btoa or Buffer not available"}})}var ne=async(t,e=null)=>{try{return await x(t,e)}catch(r){throw new d("Failed to extract files from compute response",u.INVALID_STATE,{context:{originalError:r instanceof Error?r.message:String(r)},originalError:r instanceof Error?r:void 0})}},oe= exports.r =async(t,e,r=null)=>{if(typeof document>"u"||typeof Blob>"u")throw new d("File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).",u.BROWSER_ONLY,{context:{environment:typeof window<"u"?"browser (SSR)":"Node.js",documentAvailable:typeof document<"u",blobAvailable:typeof Blob<"u"}});try{let n=await x(t,r);await ae(n,e)}catch(n){throw n instanceof d?n:new d("Failed to download files from compute response",u.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}},se=t=>{let e=[];return t.forEach(r=>{let n=`${r.fileName}${r.fileType}`,o=r.subFolder&&r.subFolder.trim()!==""?`${r.subFolder}/${n}`:n;r.isBase64Encoded===!0&&r.data?e.push({fileName:n,content:L(r.data),path:o}):r.isBase64Encoded===!1&&r.data&&e.push({fileName:n,content:r.data,path:o})}),e},ie=async t=>(await Promise.all(t.map(async r=>{try{let n=await fetch(r.filePath);if(!n.ok)return p().warn(`Failed to fetch additional file from URL: ${r.filePath}`),null;let i=await(await n.blob()).arrayBuffer();return{fileName:r.fileName,content:new Uint8Array(i),path:r.fileName}}catch(n){return p().error(`Error fetching additional file from URL: ${r.filePath}`,n),null}}))).filter(r=>r!==null),x=async(t,e)=>{let r=se(t);if(e){let n=Array.isArray(e)?e:[e];r.push(...await ie(n))}return r};async function ae(t,e){let{zip:r,strToU8:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("fflate"))),o={};t.forEach(s=>{o[s.path]=typeof s.content=="string"?n(s.content):s.content});let i=await new Promise((s,l)=>{r(o,{level:6},(c,m)=>c?l(c):s(m))}),f=new Blob([i],{type:"application/zip"});ue(f,`${e}.zip`)}function ue(t,e){if(typeof document>"u")throw new d("saveFile requires a browser environment with DOM API access.",u.BROWSER_ONLY,{context:{function:"saveFile",requiredAPI:"document"}});let r=document.createElement("a");r.href=URL.createObjectURL(t),r.download=e,r.click(),URL.revokeObjectURL(r.href)}exports.a = le; exports.b = g; exports.c = u; exports.d = d; exports.e = p; exports.f = D; exports.g = B; exports.h = ee; exports.i = F; exports.j = O; exports.k = P; exports.l = C; exports.m = Ne; exports.n = Ce; exports.o = L; exports.p = te; exports.q = ne; exports.r = oe;
4
+ //# sourceMappingURL=chunk-6LCAIDQV.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-6LCAIDQV.cjs","../src/core/errors.ts","../src/core/compute-fetch/compute-fetch.ts"],"names":["ErrorCodes","RhinoComputeError","_RhinoComputeError","message","code","options","__publicField","inputName","expectedType","context"],"mappings":"AAAA,u8BAAI,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CCI3N,IAAMA,CAAAA,CAAa,CACzB,aAAA,CAAe,eAAA,CACf,UAAA,CAAY,YAAA,CACZ,gBAAA,CAAkB,kBAAA,CAClB,iBAAA,CAAmB,mBAAA,CACnB,aAAA,CAAe,eAAA,CACf,UAAA,CAAY,YAAA,CACZ,aAAA,CAAe,eAAA,CACf,aAAA,CAAe,eAAA,CACf,aAAA,CAAe,eAAA,CACf,cAAA,CAAgB,gBAAA,CAChB,YAAA,CAAc,cAAA,CACd,iBAAA,CAAmB,mBAAA,CACnB,cAAA,CAAgB,gBAAA,CAEhB,iBAAA,CAAmB,mBAAA,CAEnB,UAAA,CAAY,YAAA,CAEZ,OAAA,CAAS,SAAA,CAQT,qBAAA,CAAuB,uBACxB,CAAA,CASaC,CAAAA,aAAN,MAAMC,EAAAA,QAA0B,KAAM,CAM5C,WAAA,CACCC,CAAAA,CACAC,CAAAA,CAAe,eAAA,CACfC,CAAAA,CACC,CACD,KAAA,CAAMF,CAAO,CAAA,CAVdG,CAAAA,CAAA,IAAA,CAAgB,MAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,YAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,SAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,eAAA,CAAA,CAQf,IAAA,CAAK,IAAA,CAAO,mBAAA,CACZ,IAAA,CAAK,IAAA,CAAOF,CAAAA,CACZ,IAAA,CAAK,UAAA,iBAAaC,CAAAA,6BAAS,YAAA,CAC3B,IAAA,CAAK,OAAA,iBAAUA,CAAAA,6BAAS,SAAA,CACxB,IAAA,CAAK,aAAA,iBAAgBA,CAAAA,6BAAS,eAAA,iBAC1BA,CAAAA,6BAAS,eAAA,EAAA,CACX,IAAA,CAA6B,KAAA,CAAQA,CAAAA,CAAQ,aAAA,CAEhD,CASA,OAAO,aAAA,CACNE,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACC,CACD,OAAO,IAAIP,CAAAA,CACV,CAAA,OAAA,EAAUK,CAAS,CAAA,uBAAA,EAA0BC,CAAAA,CAAe,CAAA,WAAA,EAAcA,CAAY,CAAA,CAAA,CAAA,CAAM,EAAE,CAAA,CAAA;ACgTzC;AAmI1C","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-6LCAIDQV.cjs","sourcesContent":[null,"/**\n * Error types and codes for `@selvajs/compute`.\n */\n\nexport const ErrorCodes = {\n\tNETWORK_ERROR: 'NETWORK_ERROR',\n\tAUTH_ERROR: 'AUTH_ERROR',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tCOMPUTATION_ERROR: 'COMPUTATION_ERROR',\n\tTIMEOUT_ERROR: 'TIMEOUT_ERROR',\n\tCORS_ERROR: 'CORS_ERROR',\n\tUNKNOWN_ERROR: 'UNKNOWN_ERROR',\n\tINVALID_STATE: 'INVALID_STATE',\n\tINVALID_INPUT: 'INVALID_INPUT',\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\tBROWSER_ONLY: 'BROWSER_ONLY',\n\tENVIRONMENT_ERROR: 'ENVIRONMENT_ERROR',\n\tENCODING_ERROR: 'ENCODING_ERROR',\n\t/** An input's `default` had a shape the normalizer didn't recognize (no innerTree key). */\n\tMALFORMED_DEFAULT: 'MALFORMED_DEFAULT',\n\t/** Scheduler latest-wins: this call was replaced by a newer one. */\n\tSUPERSEDED: 'SUPERSEDED',\n\t/** Scheduler / caller-supplied AbortSignal: this call was aborted. */\n\tABORTED: 'ABORTED',\n\t/**\n\t * A solve referenced a definition by `pointer` (server-side cache key), but the\n\t * server no longer holds that definition (evicted / GC'd / a different child in\n\t * the pool / server restarted). The caller should retry with the full\n\t * definition. Surfaced when the server tags its error body with\n\t * `code: \"definition_not_cached\"`, so it survives production message-scrubbing.\n\t */\n\tDEFINITION_NOT_CACHED: 'DEFINITION_NOT_CACHED'\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/**\n * Simplified error for Rhino Compute operations\n *\n * @public Use this for error handling with error codes and context.\n */\nexport class RhinoComputeError extends Error {\n\tpublic readonly code: string;\n\tpublic readonly statusCode?: number;\n\tpublic readonly context?: Record<string, unknown>;\n\tpublic readonly originalError?: Error;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: string = 'UNKNOWN_ERROR',\n\t\toptions?: { statusCode?: number; context?: Record<string, unknown>; originalError?: Error }\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'RhinoComputeError';\n\t\tthis.code = code;\n\t\tthis.statusCode = options?.statusCode;\n\t\tthis.context = options?.context;\n\t\tthis.originalError = options?.originalError;\n\t\tif (options?.originalError) {\n\t\t\t(this as { cause?: unknown }).cause = options.originalError;\n\t\t}\n\t}\n\n\t// ============================================================================\n\t// Static Validation Error Helpers\n\t// ============================================================================\n\n\t/**\n\t * Create an error for missing/empty values\n\t */\n\tstatic missingValues(\n\t\tinputName: string,\n\t\texpectedType?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(\n\t\t\t`Input \"${inputName}\" has no values defined${expectedType ? ` (expected ${expectedType})` : ''}`,\n\t\t\tErrorCodes.INVALID_INPUT,\n\t\t\t{ context: { inputName, expectedType, ...context } }\n\t\t);\n\t}\n\n\t/**\n\t * Create an error for unknown parameter type\n\t */\n\tstatic unknownParamType(\n\t\tparamType: string,\n\t\tparamName?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(`Unknown paramType: ${paramType}`, ErrorCodes.VALIDATION_ERROR, {\n\t\t\tcontext: { receivedParamType: paramType, paramName, ...context }\n\t\t});\n\t}\n}\n","import { RhinoComputeError, ErrorCodes, type ErrorCode } from '../errors';\nimport { getLogger } from '../utils/logger';\n\nimport type { ComputeConfig, RetryPolicy, ServerTiming } from '../types';\n\n// ============================================================================\n// Server-Timing\n// ============================================================================\n\n/**\n * Parse a `Server-Timing` header value into typed durations (ms).\n *\n * Header grammar (RFC 9110 §10.1.10), as emitted by the solve endpoint:\n * `decode;dur=3, solve;dur=120, encode;dur=8`\n *\n * Returns null when the header is absent or carries no recognizable metric, so\n * the caller can skip the callback entirely.\n *\n * @internal exported for tests\n */\nexport function parseServerTiming(headerValue: string | null): ServerTiming | null {\n\tif (!headerValue) return null;\n\tconst timing: ServerTiming = { raw: headerValue };\n\tlet sawMetric = false;\n\tfor (const part of headerValue.split(',')) {\n\t\tconst [name, ...params] = part.trim().split(';');\n\t\tconst durParam = params.find((p) => p.trim().toLowerCase().startsWith('dur'));\n\t\tif (!durParam) continue;\n\t\tconst dur = Number(durParam.split('=')[1]);\n\t\tif (!Number.isFinite(dur)) continue;\n\t\tconst key = name.trim().toLowerCase();\n\t\tif (key === 'decode' || key === 'solve' || key === 'encode') {\n\t\t\ttiming[key] = dur;\n\t\t\tsawMetric = true;\n\t\t}\n\t}\n\treturn sawMetric ? timing : null;\n}\n\n// ============================================================================\n// Retry Policy\n// ============================================================================\n\nconst DEFAULT_RETRY: Required<RetryPolicy> = {\n\tattempts: 0,\n\tbaseDelayMs: 500,\n\tmaxDelayMs: 30_000,\n\tretryOn429: true\n};\n\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\nfunction resolveRetryPolicy(policy: RetryPolicy | undefined): Required<RetryPolicy> {\n\tif (!policy) return DEFAULT_RETRY;\n\treturn {\n\t\tattempts: policy.attempts ?? DEFAULT_RETRY.attempts,\n\t\tbaseDelayMs: policy.baseDelayMs ?? DEFAULT_RETRY.baseDelayMs,\n\t\tmaxDelayMs: policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs,\n\t\tretryOn429: policy.retryOn429 ?? DEFAULT_RETRY.retryOn429\n\t};\n}\n\n/**\n * Parse a Retry-After header value (seconds-int or HTTP-date) into ms.\n * Returns null if the header is missing or unparseable.\n */\nfunction parseRetryAfter(headerValue: string | null): number | null {\n\tif (!headerValue) return null;\n\tconst seconds = Number(headerValue);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n\tconst dateMs = Date.parse(headerValue);\n\tif (Number.isFinite(dateMs)) {\n\t\tconst delta = dateMs - Date.now();\n\t\treturn delta > 0 ? delta : 0;\n\t}\n\treturn null;\n}\n\nfunction backoffDelay(attempt: number, policy: Required<RetryPolicy>): number {\n\tconst exponential = policy.baseDelayMs * Math.pow(2, attempt);\n\tconst jitter = Math.random() * policy.baseDelayMs;\n\treturn Math.min(exponential + jitter, policy.maxDelayMs);\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t\treturn;\n\t\t}\n\t\tconst id = setTimeout(() => {\n\t\t\tsignal?.removeEventListener('abort', onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(id);\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t};\n\t\tsignal?.addEventListener('abort', onAbort, { once: true });\n\t});\n}\n\n// ============================================================================\n// Error Handling\n// ============================================================================\n\nfunction throwHttpError(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\terrorBody: string,\n\tserverCode?: string\n): never {\n\tconst { status, statusText } = response;\n\n\tconst responseHeaders: Record<string, string> = {};\n\tresponse.headers.forEach((value, key) => {\n\t\tresponseHeaders[key] = value;\n\t});\n\n\tconst trimmed = errorBody.trim();\n\tconst bodyHint = trimmed ? ` — ${trimmed.slice(0, 200)}${trimmed.length > 200 ? '…' : ''}` : '';\n\n\tconst context = {\n\t\turl: fullUrl,\n\t\trequestId,\n\t\tmethod: 'POST',\n\t\trequestSize,\n\t\tserverUrl,\n\t\tresponseBody: errorBody || undefined,\n\t\tresponseHeaders\n\t};\n\n\tconst errorMap: Record<number, { message: string; code: string }> = {\n\t\t401: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t403: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t404: { message: `Endpoint not found: ${fullUrl}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t413: {\n\t\t\tmessage: `Request too large: ${(requestSize / 1024).toFixed(2)}KB`,\n\t\t\tcode: ErrorCodes.VALIDATION_ERROR\n\t\t},\n\t\t429: { message: `Rate limit exceeded${bodyHint}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t500: { message: `Server error: ${statusText}${bodyHint}`, code: ErrorCodes.COMPUTATION_ERROR },\n\t\t502: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t503: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t504: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t}\n\t};\n\n\tconst error = errorMap[status] || {\n\t\tmessage: `HTTP ${status}: ${statusText}${bodyHint}`,\n\t\tcode: ErrorCodes.UNKNOWN_ERROR\n\t};\n\n\t// A machine code in the server's error body (e.g. \"definition_not_cached\")\n\t// outranks the status-based mapping: it's stable across the server's\n\t// production message-scrubbing, where the human message is replaced with a\n\t// generic string. Keep the status-derived message for context.\n\tconst code = mapServerErrorCode(serverCode) ?? error.code;\n\n\tthrow new RhinoComputeError(error.message, code, { statusCode: status, context });\n}\n\n/**\n * Map a server-supplied error code (from the JSON error body's `code` field) to\n * one of our {@link ErrorCodes}. Returns `undefined` for an absent or unknown\n * code so the caller falls back to its status-based mapping.\n */\nfunction mapServerErrorCode(serverCode?: string): ErrorCode | undefined {\n\tswitch (serverCode) {\n\t\tcase 'definition_not_cached':\n\t\t\treturn ErrorCodes.DEFINITION_NOT_CACHED;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n// ============================================================================\n// Request Helpers\n// ============================================================================\n\nfunction buildUrl(endpoint: string, serverUrl: string): string {\n\tconst base = serverUrl.replace(/\\/+$/, '');\n\tconst path = endpoint.replace(/^\\/+/, '');\n\treturn `${base}/${path}`;\n}\n\nfunction isLocalhost(serverUrl: string): boolean {\n\ttry {\n\t\tconst host = new URL(serverUrl).host;\n\t\treturn /^(localhost|127\\.0\\.0\\.1|::1)(:\\d+)?$/i.test(host);\n\t} catch {\n\t\treturn /(localhost|127\\.0\\.0\\.1)/i.test(serverUrl);\n\t}\n}\n\nfunction buildHeaders(requestId: string, config: ComputeConfig): HeadersInit {\n\tconst headers: HeadersInit = {\n\t\t'X-Request-ID': requestId,\n\t\t'Content-Type': 'application/json',\n\t\t...(config.authToken && { Authorization: config.authToken }),\n\t\t...(config.apiKey && { RhinoComputeKey: config.apiKey })\n\t};\n\n\tif (!config.apiKey && !config.authToken && !isLocalhost(config.serverUrl)) {\n\t\tgetLogger().warn(\n\t\t\t`⚠️ [Rhino Compute] Request [${requestId}] targets remote server (${config.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited.`\n\t\t);\n\t}\n\n\treturn headers;\n}\n\nfunction generateRequestId(): string {\n\treturn `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n}\n\nfunction log(message: string, debug?: boolean): void {\n\tif (debug) getLogger().debug(message);\n}\n\n/**\n * Compose a caller-supplied AbortSignal with an optional timeout. Returns a\n * combined signal, or `undefined` if neither was given.\n *\n * Uses `AbortSignal.timeout` (not setTimeout) so the timer is not throttled\n * when the tab is hidden. Falls back to a manual timer for older runtimes.\n *\n * @internal exported for tests\n */\nexport function composeSignal(\n\tcallerSignal: AbortSignal | undefined,\n\ttimeoutMs: number | undefined\n): { signal: AbortSignal | undefined; cleanup: () => void } {\n\tconst signals: AbortSignal[] = [];\n\tlet cleanup = () => {};\n\n\tif (callerSignal) signals.push(callerSignal);\n\n\tif (timeoutMs && timeoutMs > 0) {\n\t\tif (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {\n\t\t\tsignals.push(AbortSignal.timeout(timeoutMs));\n\t\t} else {\n\t\t\t// Fallback for runtimes without AbortSignal.timeout\n\t\t\tconst ctrl = new AbortController();\n\t\t\tconst id = setTimeout(() => ctrl.abort(), timeoutMs);\n\t\t\tcleanup = () => clearTimeout(id);\n\t\t\tsignals.push(ctrl.signal);\n\t\t}\n\t}\n\n\tif (signals.length === 0) return { signal: undefined, cleanup };\n\tif (signals.length === 1) return { signal: signals[0], cleanup };\n\n\tif (typeof AbortSignal !== 'undefined' && typeof (AbortSignal as any).any === 'function') {\n\t\treturn { signal: (AbortSignal as any).any(signals) as AbortSignal, cleanup };\n\t}\n\n\t// Manual composition fallback\n\tconst ctrl = new AbortController();\n\tconst onAbort = () => ctrl.abort();\n\tfor (const s of signals) {\n\t\tif (s.aborted) {\n\t\t\tctrl.abort();\n\t\t\tbreak;\n\t\t}\n\t\ts.addEventListener('abort', onAbort, { once: true });\n\t}\n\tconst prevCleanup = cleanup;\n\tcleanup = () => {\n\t\tprevCleanup();\n\t\tfor (const s of signals) s.removeEventListener('abort', onAbort);\n\t};\n\treturn { signal: ctrl.signal, cleanup };\n}\n\n// ============================================================================\n// Response Processing\n// ============================================================================\n\nasync function handleResponse(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\tstartTime: number,\n\tdebug?: boolean,\n\tonServerTiming?: (timing: ServerTiming) => void\n): Promise<any> {\n\tconst responseTime = Math.round(performance.now() - startTime);\n\n\tif (!response.ok) {\n\t\t// Read body once and reuse\n\t\tlet errorBody = await response.text();\n\n\t\t// Enhanced logging for errors\n\t\tif (debug) {\n\t\t\tlog(\n\t\t\t\t`❌ Request [${requestId}] failed with HTTP ${response.status} in ${responseTime}ms`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t\tlog(` URL: ${fullUrl}`, true);\n\t\t\tlog(` Status: ${response.status} ${response.statusText}`, true);\n\t\t\tif (errorBody) {\n\t\t\t\tlog(\n\t\t\t\t\t` Response body: ${errorBody.substring(0, 500)}${errorBody.length > 500 ? '...' : ''}`,\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// A machine-readable code the server may tag onto its error body (e.g.\n\t\t// \"definition_not_cached\"). Unlike the human `message`, it isn't scrubbed in\n\t\t// the server's production (non-debug) mode, so it's the reliable signal for\n\t\t// classifying the error (see throwHttpError → mapServerErrorCode).\n\t\tlet serverCode: string | undefined;\n\n\t\t// The machine code (e.g. `definition_not_cached`) can ride any error status,\n\t\t// not just 500, and must outrank the status-based mapping — so read it here.\n\t\ttry {\n\t\t\tconst parsedForCode = JSON.parse(errorBody);\n\t\t\tif (typeof parsedForCode?.code === 'string') serverCode = parsedForCode.code;\n\t\t} catch {\n\t\t\t// Non-JSON body — nothing to extract.\n\t\t}\n\n\t\t// Check if it's a valid compute response with errors/warnings\n\t\tif (response.status === 500) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(errorBody);\n\t\t\t\t// If it has values, it's a partial success with errors\n\t\t\t\tif (parsed?.values && (parsed.errors || parsed.warnings)) {\n\t\t\t\t\tif (debug) {\n\t\t\t\t\t\tlog(\n\t\t\t\t\t\t\t`⚠️ Request [${requestId}] completed with Grasshopper errors in ${responseTime}ms`,\n\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (parsed.errors?.length > 0) {\n\t\t\t\t\t\t\tlog(` Errors: ${JSON.stringify(parsed.errors, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (parsed.warnings?.length > 0) {\n\t\t\t\t\t\t\tlog(` Warnings: ${JSON.stringify(parsed.warnings, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\n\t\t\t\t// Raw server-side exception. The Compute8 server's exception handler\n\t\t\t\t// (compute.geometry Startup.cs) emits:\n\t\t\t\t// { error: \"Internal Server Error\", message: \"<category>: <detail>\",\n\t\t\t\t// stackTrace?: string[] } // stackTrace only when Config.Debug\n\t\t\t\t// The actionable part is `message` — surface it, with the optional\n\t\t\t\t// stack appended for debugging. We prefer `message`/`error` (current\n\t\t\t\t// server) and keep `Message`/`ExceptionType`/`StackTrace` (old\n\t\t\t\t// PascalCase .NET shape) as a back-compat fallback so an older server\n\t\t\t\t// still produces a useful message.\n\t\t\t\tconst serverMessage =\n\t\t\t\t\t(typeof parsed?.message === 'string' && parsed.message) ||\n\t\t\t\t\t(typeof parsed?.Message === 'string' && parsed.Message) ||\n\t\t\t\t\t'';\n\t\t\t\tconst exceptionType =\n\t\t\t\t\t(typeof parsed?.ExceptionType === 'string' && parsed.ExceptionType) || '';\n\t\t\t\tconst stack = parsed?.stackTrace ?? parsed?.StackTrace;\n\t\t\t\tconst stackStr = Array.isArray(stack) ? stack.join('\\n') : stack || '';\n\n\t\t\t\tif (serverMessage) {\n\t\t\t\t\t// Don't repeat the generic \"Internal Server Error\" label when the\n\t\t\t\t\t// message already carries the real detail.\n\t\t\t\t\tconst prefix = exceptionType ? `${exceptionType}: ` : '';\n\t\t\t\t\terrorBody = `${prefix}${serverMessage}${stackStr ? `\\n${stackStr}` : ''}`;\n\t\t\t\t} else if (parsed?.error) {\n\t\t\t\t\terrorBody =\n\t\t\t\t\t\ttypeof parsed.error === 'string' ? parsed.error : JSON.stringify(parsed.error, null, 2);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tif (debug) {\n\t\t\t\t\tlog(` Failed to parse error body as JSON: ${e}`, true);\n\t\t\t\t}\n\t\t\t\t// Not valid JSON, proceed with HTTP error\n\t\t\t}\n\t\t}\n\n\t\tthrowHttpError(response, fullUrl, requestId, requestSize, serverUrl, errorBody, serverCode);\n\t}\n\n\tlog(`✅ Request [${requestId}] completed in ${responseTime}ms`, debug);\n\n\t// Surface the server's per-request timing breakdown (if it sent one and a\n\t// caller is listening). Best-effort: a throwing callback must not fail the\n\t// request, since the body parse below is the real result.\n\tif (onServerTiming) {\n\t\tconst timing = parseServerTiming(response.headers.get('Server-Timing'));\n\t\tif (timing) {\n\t\t\ttry {\n\t\t\t\tonServerTiming(timing);\n\t\t\t} catch (err) {\n\t\t\t\tif (debug) log(` onServerTiming callback threw: ${err}`, true);\n\t\t\t}\n\t\t}\n\t}\n\n\ttry {\n\t\treturn await response.json();\n\t} catch (error) {\n\t\tthrow new RhinoComputeError('Failed to parse JSON response', ErrorCodes.NETWORK_ERROR, {\n\t\t\tstatusCode: response.status,\n\t\t\tcontext: {\n\t\t\t\turl: fullUrl,\n\t\t\t\trequestId\n\t\t\t},\n\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t});\n\t}\n}\n\n// ============================================================================\n// Single attempt\n// ============================================================================\n\ninterface AttemptContext {\n\tendpoint: string;\n\tbody: string;\n\trequestSize: number;\n\tfullUrl: string;\n\trequestId: string;\n\theaders: HeadersInit;\n\tconfig: ComputeConfig;\n}\n\ninterface AttemptResult {\n\tok: true;\n\tvalue: any;\n}\n\ninterface AttemptRetry {\n\tok: false;\n\tretry: true;\n\tdelayMs: number;\n\tcause: RhinoComputeError;\n}\n\ninterface AttemptFatal {\n\tok: false;\n\tretry: false;\n\tcause: RhinoComputeError;\n}\n\nasync function attemptFetch(\n\tctx: AttemptContext,\n\tretryPolicy: Required<RetryPolicy>,\n\tattempt: number,\n\ttotalAttempts: number\n): Promise<AttemptResult | AttemptRetry | AttemptFatal> {\n\tconst { signal, cleanup } = composeSignal(ctx.config.signal, ctx.config.timeoutMs);\n\tconst startTime = performance.now();\n\n\ttry {\n\t\tconst response = await fetch(ctx.fullUrl, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: ctx.body,\n\t\t\theaders: ctx.headers,\n\t\t\tsignal\n\t\t});\n\n\t\t// 429 with Retry-After or retryable 5xx → maybe retry\n\t\tconst isRetryableStatus =\n\t\t\tRETRYABLE_STATUS.has(response.status) || (retryPolicy.retryOn429 && response.status === 429);\n\n\t\tif (isRetryableStatus && attempt < totalAttempts - 1) {\n\t\t\tconst retryAfterMs = parseRetryAfter(response.headers.get('Retry-After'));\n\t\t\t// Clamp Retry-After to maxDelayMs so a bad header can't force an\n\t\t\t// arbitrarily long sleep. backoffDelay already clamps.\n\t\t\tconst delayMs =\n\t\t\t\tretryAfterMs !== null\n\t\t\t\t\t? Math.min(retryAfterMs, retryPolicy.maxDelayMs)\n\t\t\t\t\t: backoffDelay(attempt, retryPolicy);\n\t\t\t// Drain the body so the connection can be reused on the next attempt.\n\t\t\t// On the *final* attempt we deliberately fall through — handleResponse\n\t\t\t// reads the body itself to surface the error context.\n\t\t\tawait response.text().catch(() => {});\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tretry: true,\n\t\t\t\tdelayMs,\n\t\t\t\tcause: new RhinoComputeError(\n\t\t\t\t\t`HTTP ${response.status} ${response.statusText} (will retry)`,\n\t\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t{ statusCode: response.status, context: { requestId: ctx.requestId } }\n\t\t\t\t)\n\t\t\t};\n\t\t}\n\n\t\tconst value = await handleResponse(\n\t\t\tresponse,\n\t\t\tctx.fullUrl,\n\t\t\tctx.requestId,\n\t\t\tctx.requestSize,\n\t\t\tctx.config.serverUrl,\n\t\t\tstartTime,\n\t\t\tctx.config.debug,\n\t\t\tctx.config.onServerTiming\n\t\t);\n\t\treturn { ok: true, value };\n\t} catch (error) {\n\t\t// Caller-aborted vs timeout-aborted distinction\n\t\tif (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {\n\t\t\tconst callerAborted = ctx.config.signal?.aborted === true;\n\n\t\t\tif (callerAborted) {\n\t\t\t\t// Caller cancellation is never retried — propagate immediately\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: false,\n\t\t\t\t\tcause: new RhinoComputeError('Request aborted by caller', ErrorCodes.UNKNOWN_ERROR, {\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t},\n\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Timeout — retryable up to attempts limit\n\t\t\tconst fatal = new RhinoComputeError(\n\t\t\t\t`Request timed out after ${ctx.config.timeoutMs}ms`,\n\t\t\t\tErrorCodes.TIMEOUT_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\ttimeoutMs: ctx.config.timeoutMs,\n\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// Network error (TypeError) — retryable\n\t\tif (error instanceof TypeError) {\n\t\t\tconst fatal = new RhinoComputeError(\n\t\t\t\t`Network error: ${error.message}`,\n\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t},\n\t\t\t\t\toriginalError: error\n\t\t\t\t}\n\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// RhinoComputeError thrown from handleResponse — already has full context.\n\t\t// Retryable only if it carries a retryable status code.\n\t\tif (error instanceof RhinoComputeError) {\n\t\t\tconst status = error.statusCode;\n\t\t\tconst retryable =\n\t\t\t\tstatus !== undefined &&\n\t\t\t\t(RETRYABLE_STATUS.has(status) || (retryPolicy.retryOn429 && status === 429));\n\t\t\tif (retryable && attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: error\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: error };\n\t\t}\n\n\t\t// Unknown — wrap and don't retry\n\t\treturn {\n\t\t\tok: false,\n\t\t\tretry: false,\n\t\t\tcause: new RhinoComputeError(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\tErrorCodes.UNKNOWN_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: { endpoint: ctx.endpoint, requestId: ctx.requestId },\n\t\t\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t}\n\t\t\t)\n\t\t};\n\t} finally {\n\t\tcleanup();\n\t}\n}\n\n// ============================================================================\n// Main Function\n// ============================================================================\n\n/**\n * Generic Rhino Compute fetch function.\n * Sends a POST request to any Compute endpoint with pre-prepared arguments.\n *\n * Use this for advanced, low-level control over compute requests. For most use cases, prefer higher-level APIs.\n *\n * The transport is response-type-agnostic: it does not know which response a\n * given endpoint returns. Callers supply the response type via `R` (defaulting\n * to `unknown`, which forces an explicit narrowing before use).\n *\n * @typeParam R - The expected response shape. The caller names it at the call site.\n * @param endpoint - The Compute API endpoint (e.g., 'grasshopper', 'io', 'mesh').\n * @param args - Pre-prepared arguments for the request body.\n * @param config - Compute configuration (server URL, API key, timeout, debug, retry, signal).\n * @returns The parsed JSON response from the server, typed as `R`.\n *\n * @example\n * // Basic usage for the Grasshopper endpoint:\n * const response = await fetchRhinoCompute(\n * 'grasshopper',\n * { ... },\n * {\n * serverUrl: 'https://my-server.com',\n * debug: true,\n * timeoutMs: 30_000,\n * retry: { attempts: 2 },\n * signal: controller.signal,\n * }\n * );\n */\nexport async function fetchRhinoCompute<R = unknown>(\n\tendpoint: string,\n\targs: Record<string, any>,\n\tconfig: ComputeConfig\n): Promise<R> {\n\tconst requestId = generateRequestId();\n\tconst body = JSON.stringify(args);\n\tconst requestSize = body.length;\n\tconst fullUrl = buildUrl(endpoint, config.serverUrl);\n\tconst headers = buildHeaders(requestId, config);\n\tconst retryPolicy = resolveRetryPolicy(config.retry);\n\tconst totalAttempts = retryPolicy.attempts + 1;\n\n\tif (config.debug) {\n\t\tconst sizeKb = (requestSize / 1024).toFixed(2);\n\t\tconst emoji = requestSize > 100000 ? '⚠️' : '🚀';\n\t\tlog(`${emoji} Starting compute request [${requestId}]: ${endpoint} (${sizeKb}KB)`, true);\n\t}\n\n\tconst ctx: AttemptContext = {\n\t\tendpoint,\n\t\tbody,\n\t\trequestSize,\n\t\tfullUrl,\n\t\trequestId,\n\t\theaders,\n\t\tconfig\n\t};\n\n\tlet lastError: RhinoComputeError | null = null;\n\n\tfor (let attempt = 0; attempt < totalAttempts; attempt++) {\n\t\tconst result = await attemptFetch(ctx, retryPolicy, attempt, totalAttempts);\n\n\t\tif (result.ok) return result.value as R;\n\n\t\tif (!result.retry) throw result.cause;\n\n\t\tlastError = result.cause;\n\t\tif (config.debug) {\n\t\t\tlog(\n\t\t\t\t`🔁 Request [${requestId}] retrying after ${result.delayMs}ms (attempt ${attempt + 2}/${totalAttempts}): ${result.cause.message}`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\tawait sleep(result.delayMs, config.signal);\n\t\t} catch {\n\t\t\t// Caller cancelled during backoff\n\t\t\tthrow new RhinoComputeError('Request aborted by caller', ErrorCodes.UNKNOWN_ERROR, {\n\t\t\t\tcontext: { endpoint, requestId, requestSize },\n\t\t\t\toriginalError: lastError\n\t\t\t});\n\t\t}\n\t}\n\n\t// Exhausted retries — throw the last seen error\n\tthrow (\n\t\tlastError ??\n\t\tnew RhinoComputeError('Unknown error after retries', ErrorCodes.UNKNOWN_ERROR, {\n\t\t\tcontext: { endpoint, requestId, requestSize }\n\t\t})\n\t);\n}\n"]}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk6LCAIDQVcjs = require('./chunk-6LCAIDQV.cjs');function p(t,e){if(!t||typeof t!="object")return;let r=t;if(e in r)return r[e];let n=e.toLowerCase();for(let s of Object.keys(r))if(s.toLowerCase()===n)return r[s]}function L(t,e){if(!t||typeof t!="object")return!1;let r=t;if(e in r)return!0;let n=e.toLowerCase();return Object.keys(r).some(s=>s.toLowerCase()===n)}function C(t,e){e||typeof window<"u"&&_chunk6LCAIDQVcjs.e.call(void 0, ).warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`)}var Ce="Unable to load grasshopper definition";function Se(t){return t instanceof _chunk6LCAIDQVcjs.d?t.code===_chunk6LCAIDQVcjs.c.DEFINITION_NOT_CACHED||t.message.includes(Ce):!1}function H(t,e){if(!e)return;let r=p(t,"values");if(!Array.isArray(r)||r.length===0)return;let n=[];for(let o of r){let a=p(o,"innerTree");(!a||Object.keys(a).length===0)&&n.push(_nullishCoalesce(p(o,"paramName"), () => ("<unnamed>")))}if(n.length===0)return;let s=n.length===r.length?"all":`${n.length}/${r.length}`;_chunk6LCAIDQVcjs.e.call(void 0, ).warn(`Solve returned empty output(s) (${s}): ${n.join(", ")}. These parameters produced no data \u2014 check the definition's inputs and the branch feeding each.`)}async function D(t,e,r){r.debug&&C("solveGrasshopperDefinition",_nullishCoalesce(r.suppressBrowserWarning, () => (r.suppressClientSideWarning)));let{response:n}=await O(P(e,t),r);return n}async function J(t,e,r){return r.debug&&C("solveGrasshopperDefinitionWithCacheKey",_nullishCoalesce(r.suppressBrowserWarning, () => (r.suppressClientSideWarning))),O(P(e,t),r)}async function Y(t,e,r,n){n.debug&&C("solveByCacheKey",_nullishCoalesce(n.suppressBrowserWarning, () => (n.suppressClientSideWarning)));let s={algo:null,pointer:e,values:t};try{return{...await O(s,n),missed:!1}}catch(o){if(!Se(o))throw o;return{...await O(P(r,t),n),missed:!0}}}async function O(t,e){Ie(t,e);let r=await _chunk6LCAIDQVcjs.h.call(void 0, "grasshopper",t,e);if("pointer"in r){let{pointer:n,...s}=r,o=s;return H(o,e.debug),{response:o,cacheKey:typeof n=="string"?n:null}}return H(r,e.debug),{response:r,cacheKey:null}}function P(t,e){let r={algo:null,pointer:null,values:e};return t instanceof Uint8Array?r.algo=_chunk6LCAIDQVcjs.p.call(void 0, t):/^https?:\/\//i.test(t)?r.pointer=t:_chunk6LCAIDQVcjs.n.call(void 0, t)?r.algo=t:r.algo=_chunk6LCAIDQVcjs.m.call(void 0, t),r}function Ie(t,e){e.cachesolve!=null&&(t.cachesolve=e.cachesolve),e.cacheerroredsolves!=null&&(t.cacheerroredsolves=e.cacheerroredsolves),e.modelunits!=null&&(t.modelunits=e.modelunits),e.angletolerance!=null&&(t.angletolerance=e.angletolerance),e.absolutetolerance!=null&&(t.absolutetolerance=e.absolutetolerance),e.dataversion!=null&&(t.dataversion=e.dataversion)}function xe(t){let e=new WeakSet,r=n=>{if(n==null)return JSON.stringify(n);if(typeof n=="number")return Number.isFinite(n)?String(n):JSON.stringify(null);if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="bigint")return JSON.stringify(n.toString());if(n instanceof Uint8Array){let s=n.length>64?Array.from(n.slice(0,32)).concat(Array.from(n.slice(-32))):Array.from(n);return JSON.stringify({__u8:!0,len:n.length,sample:s})}return Array.isArray(n)?`[${n.map(r).join(",")}]`:typeof n=="object"?e.has(n)?JSON.stringify("[Circular]"):(e.add(n),`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${r(n[a])}`).join(",")}}`):JSON.stringify(null)};return r(t)}function Q(t,e){let r=2166136261;for(let n=0;n<t;n++)r^=e(n),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r.toString(16).padStart(8,"0")}function X(t){return Q(t.length,e=>t.charCodeAt(e))}function De(t){return Q(t.length,e=>t[e])}function Z(t,e){return X(`${W(t)}|${xe(e)}`)}function W(t){return typeof t=="string"?`s:${t.length}:${X(t)}`:`u8:${t.length}:${De(t)}`}var Pe=100;function Re(t){return t instanceof Uint8Array?!0:!/^https?:\/\//i.test(t)}var S=class{constructor(e,r,n={},s){_chunk6LCAIDQVcjs.b.call(void 0, this,"executor");_chunk6LCAIDQVcjs.b.call(void 0, this,"baseConfig");_chunk6LCAIDQVcjs.b.call(void 0, this,"mode");_chunk6LCAIDQVcjs.b.call(void 0, this,"maxConcurrent");_chunk6LCAIDQVcjs.b.call(void 0, this,"timeoutMs");_chunk6LCAIDQVcjs.b.call(void 0, this,"retry");_chunk6LCAIDQVcjs.b.call(void 0, this,"cacheEnabled");_chunk6LCAIDQVcjs.b.call(void 0, this,"cacheMax");_chunk6LCAIDQVcjs.b.call(void 0, this,"cacheTtl");_chunk6LCAIDQVcjs.b.call(void 0, this,"cache",new Map);_chunk6LCAIDQVcjs.b.call(void 0, this,"cacheKeyExecutor");_chunk6LCAIDQVcjs.b.call(void 0, this,"reuseServerDefinitionCache");_chunk6LCAIDQVcjs.b.call(void 0, this,"serverCacheKeys",new Map);_chunk6LCAIDQVcjs.b.call(void 0, this,"onStart");_chunk6LCAIDQVcjs.b.call(void 0, this,"onSettle");_chunk6LCAIDQVcjs.b.call(void 0, this,"onSuperseded");_chunk6LCAIDQVcjs.b.call(void 0, this,"subscribers",new Set);_chunk6LCAIDQVcjs.b.call(void 0, this,"inFlight",new Set);_chunk6LCAIDQVcjs.b.call(void 0, this,"pendingForLatestWins",null);_chunk6LCAIDQVcjs.b.call(void 0, this,"fifoQueue",[]);_chunk6LCAIDQVcjs.b.call(void 0, this,"_lastResult",null);_chunk6LCAIDQVcjs.b.call(void 0, this,"_lastError",null);_chunk6LCAIDQVcjs.b.call(void 0, this,"_lastDurationMs",null);_chunk6LCAIDQVcjs.b.call(void 0, this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=s,this.baseConfig=r,this.mode=_nullishCoalesce(n.mode, () => ("latest-wins")),this.maxConcurrent=Math.max(1,_nullishCoalesce(n.maxConcurrent, () => ((this.mode==="parallel"?4:1)))),this.timeoutMs=n.timeoutMs,this.retry=n.retry;let o=n.cache;this.cacheEnabled=o!==void 0&&o!==!1;let a=typeof o=="object"?o:{};this.cacheMax=_nullishCoalesce(a.maxEntries, () => (50)),this.cacheTtl=_nullishCoalesce(a.ttlMs, () => (0)),this.reuseServerDefinitionCache=!!s&&(_nullishCoalesce(n.reuseServerDefinitionCache, () => (!0))),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+(this.pendingForLatestWins?1:0)}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(r){_chunk6LCAIDQVcjs.e.call(void 0, ).error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new (0, _chunk6LCAIDQVcjs.d)("SolveScheduler has been disposed and cannot be used",_chunk6LCAIDQVcjs.c.INVALID_STATE));let s=Z(e,r),o={key:s,enqueuedAt:Date.now(),startedAt:null};if(this.cacheEnabled){let a=this.readCache(s);if(a){let i={status:"success",response:a,durationMs:0,fromCache:!0};return this._lastResult=a,this._lastError=null,this._lastDurationMs=0,this.runHook(this.onStart,o),this.runHook(this.onSettle,o,i),this.notify(),Promise.resolve(a)}}return new Promise((a,i)=>{let u={definition:e,dataTree:r,ctx:o,resolve:a,reject:i,externalSignal:_optionalChain([n, 'optionalAccess', _2 => _2.signal])};if(_optionalChain([u, 'access', _3 => _3.externalSignal, 'optionalAccess', _4 => _4.aborted])){this.settleError(u,this.makeAbortError(o));return}this.enqueue(u)})}enqueue(e){switch(this.mode){case"latest-wins":{this.pendingForLatestWins&&(this.supersede(this.pendingForLatestWins),this.pendingForLatestWins=null);for(let r of this.inFlight)this.supersede(r),r.controller.abort();this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break}case"queue":case"parallel":{this.inFlight.size<this.maxConcurrent?this.execute(e):this.fifoQueue.push(e);break}}this.notify()}async execute(e){let r=new AbortController,n=e;n.controller=r,this.inFlight.add(n),e.ctx.startedAt=Date.now();let s=()=>r.abort();_optionalChain([e, 'access', _5 => _5.externalSignal, 'optionalAccess', _6 => _6.addEventListener, 'call', _7 => _7("abort",s,{once:!0})]),this.runHook(this.onStart,e.ctx),this.notify();let o=performance.now();try{let a={...this.baseConfig,signal:r.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},{response:i,definitionReuploaded:u}=await this.runExecutor(e.definition,e.dataTree,a),c=performance.now()-o;if(this.cacheEnabled&&this.writeCache(e.ctx.key,i),!this.settleSuccess(e,i))return;this._lastResult=i,this._lastError=null,this._lastDurationMs=c,this.runHook(this.onSettle,e.ctx,{status:"success",response:i,durationMs:c,fromCache:!1,definitionReuploaded:u})}catch(a){let i=performance.now()-o,u=this.normalizeExecutionError(a,n);this._lastError=u,this._lastDurationMs=i,this.settleError(e,u)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:u,durationMs:i})}finally{_optionalChain([e, 'access', _8 => _8.externalSignal, 'optionalAccess', _9 => _9.removeEventListener, 'call', _10 => _10("abort",s)]),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,r,n){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!Re(e))return{response:await this.executor(e,r,n)};let s=W(e),o=_nullishCoalesce(this.serverCacheKeys.get(s), () => (null)),a=await this.cacheKeyExecutor(e,r,o,n);if(a.cacheKey)for(this.serverCacheKeys.delete(s),this.serverCacheKeys.set(s,a.cacheKey);this.serverCacheKeys.size>Pe;){let i=this.serverCacheKeys.keys().next().value;if(i===void 0)break;this.serverCacheKeys.delete(i)}else this.serverCacheKeys.delete(s);return{response:a.response,definitionReuploaded:a.missed}}drainNext(){if(!this.disposed){if(this.mode==="latest-wins"){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}return}for(;this.fifoQueue.length>0&&this.inFlight.size<this.maxConcurrent;){let e=this.fifoQueue.shift();this.execute(e)}}}supersede(e){let r=new (0, _chunk6LCAIDQVcjs.d)("Superseded by newer solve",_chunk6LCAIDQVcjs.c.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new (0, _chunk6LCAIDQVcjs.d)("Request aborted by caller",_chunk6LCAIDQVcjs.c.ABORTED,{context:{key:e.key,enqueuedAt:e.enqueuedAt}})}settleError(e,r){return e.settled?!1:(e.settled={error:r},e.reject(r),!0)}settleSuccess(e,r){return e.settled?!1:(e.settled={ok:!0},e.resolve(r),!0)}isAbortLikeError(e){if(e instanceof Error){if(e.name==="AbortError")return!0;if(typeof DOMException<"u"&&e instanceof DOMException)return e.name==="AbortError"}return!1}normalizeExecutionError(e,r){return r.settled&&"error"in r.settled?r.settled.error:e instanceof _chunk6LCAIDQVcjs.d?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new (0, _chunk6LCAIDQVcjs.d)(e instanceof Error?e.message:String(e),_chunk6LCAIDQVcjs.c.UNKNOWN_ERROR,{originalError:e instanceof Error?e:new Error(String(e))})}cancelAll(){for(this.pendingForLatestWins&&(this.rejectAsAborted(this.pendingForLatestWins),this.pendingForLatestWins=null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:e.ctx.startedAt?performance.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){this.settleError(e,this.makeAbortError(e.ctx))}readCache(e){if(!this.cacheEnabled)return null;let r=this.cache.get(e);return r?this.cacheTtl>0&&Date.now()-r.insertedAt>this.cacheTtl?(this.cache.delete(e),null):(this.cache.delete(e),this.cache.set(e,r),r.response):null}writeCache(e,r){if(this.cacheEnabled)for(this.cache.set(e,{response:r,insertedAt:Date.now()});this.cache.size>this.cacheMax;){let n=this.cache.keys().next().value;if(n===void 0)break;this.cache.delete(n)}}clearCache(){this.cache.clear()}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.cache.clear())}runHook(e,...r){if(e)try{e(...r)}catch(n){_chunk6LCAIDQVcjs.e.call(void 0, ).error("[SolveScheduler] hook threw:",n)}}};var R=class t{constructor(e){_chunk6LCAIDQVcjs.b.call(void 0, this,"config");_chunk6LCAIDQVcjs.b.call(void 0, this,"serverStats");_chunk6LCAIDQVcjs.b.call(void 0, this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new (0, _chunk6LCAIDQVcjs.j)(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e),n=Math.max(1,(_nullishCoalesce(_optionalChain([e, 'access', _11 => _11.retry, 'optionalAccess', _12 => _12.attempts]), () => (2)))+1),s=_nullishCoalesce(_optionalChain([e, 'access', _13 => _13.retry, 'optionalAccess', _14 => _14.baseDelayMs]), () => (250)),o=_nullishCoalesce(_optionalChain([e, 'access', _15 => _15.retry, 'optionalAccess', _16 => _16.maxDelayMs]), () => (1e3));for(let a=0;a<n;a++){if(await r.serverStats.isServerOnline())return r;if(a<n-1){let i=Math.min(s*2**a,o);await new Promise(u=>setTimeout(u,i))}}throw await r.dispose(),new (0, _chunk6LCAIDQVcjs.d)("Rhino Compute server is not online",_chunk6LCAIDQVcjs.c.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:n}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),F(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),E(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!_optionalChain([e, 'optionalAccess', _17 => _17.trim, 'call', _18 => _18()]))throw new (0, _chunk6LCAIDQVcjs.d)("Definition URL/content is required",_chunk6LCAIDQVcjs.c.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new (0, _chunk6LCAIDQVcjs.d)("Definition content is empty",_chunk6LCAIDQVcjs.c.INVALID_INPUT);let s={...this.config,..._optionalChain([n, 'optionalAccess', _19 => _19.signal])!==void 0&&{signal:n.signal},..._optionalChain([n, 'optionalAccess', _20 => _20.timeoutMs])!==void 0&&{timeoutMs:n.timeoutMs},..._optionalChain([n, 'optionalAccess', _21 => _21.retry])!==void 0&&{retry:n.retry}},o=await D(r,e,s);if(_optionalChain([o, 'optionalAccess', _22 => _22.errors])&&o.errors.length>0)throw new (0, _chunk6LCAIDQVcjs.d)(o.errors.join("; ")||"Computation failed",_chunk6LCAIDQVcjs.c.COMPUTATION_ERROR,{context:{definition:typeof e=="string"&&e.length<200?e:"...content...",inputs:r,errors:o.errors,warnings:o.warnings}});return o}catch(s){throw this.config.debug&&_chunk6LCAIDQVcjs.e.call(void 0, ).error("Compute failed:",s),s instanceof _chunk6LCAIDQVcjs.d?s:new (0, _chunk6LCAIDQVcjs.d)(s instanceof Error?s.message:String(s),_chunk6LCAIDQVcjs.c.COMPUTATION_ERROR,{context:{definition:typeof e=="string"&&e.length<200?e:"...content...",inputs:r},originalError:s instanceof Error?s:new Error(String(s))})}}createScheduler(e){this.ensureNotDisposed();let r=(s,o,a)=>D(o,s,a),n=(s,o,a,i)=>a===null?J(o,s,i).then(u=>({...u,missed:!1})):Y(o,a,s,i);return new S(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new (0, _chunk6LCAIDQVcjs.d)("GrasshopperClient has been disposed and cannot be used",_chunk6LCAIDQVcjs.c.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:_chunk6LCAIDQVcjs.i.call(void 0, e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:_nullishCoalesce(e.debug, () => (!1)),suppressBrowserWarning:_nullishCoalesce(e.suppressBrowserWarning, () => (e.suppressClientSideWarning))}}};var G=new Map;function ee(t,e){G.set(t,e)}ee("Rhino.Geometry.Point3d",(t,e)=>{let r=e;return!r||typeof r.X!="number"?null:new t.Point([r.X,r.Y,r.Z])});ee("Rhino.Geometry.Line",(t,e)=>{let r=e;return!r||!r.From||!r.To?null:new t.Line([r.From.X,r.From.Y,r.From.Z],[r.To.X,r.To.Y,r.To.Z])});function Ee(t){if(G.has(t))return G.get(t);for(let[e,r]of G)if(t.startsWith(e))return r}function we(t){return!t||typeof t!="object"?null:_nullishCoalesce(_nullishCoalesce(t.data, () => (t.value)), () => (null))}function te(t,e,r){let n=Ee(e);if(n)try{return n(r,t)}catch(s){_chunk6LCAIDQVcjs.e.call(void 0, ).warn(`Failed to decode Rhino type ${e}:`,s)}try{let s=we(t);if(s)return r.CommonObject.decode(s)}catch(s){return _chunk6LCAIDQVcjs.e.call(void 0, ).warn(`Failed to decode ${e} with CommonObject:`,s),{__decodeError:!0,type:e,raw:t}}return t}var I={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},ve="Rhino.Geometry.",Ae=["WebDisplay"],Ne="FileData";function re(t){return Ae.some(e=>t.includes(e))}function ne(t){if(typeof t!="string")return t;let e=t.trim();if(!(e.startsWith("{")||e.startsWith("[")||e.startsWith('"')))return t;try{let n=JSON.parse(e);if(typeof n=="string")try{return JSON.parse(n)}catch (e2){return n}return n}catch (e3){return t}}function Oe(t,e,r){switch(e){case I.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case I.INT:return Number.parseInt(t,10);case I.DOUBLE:return Number.parseFloat(t);case I.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(ve)?te(t,e,r):t}}function se(t,e,r,n){if(typeof t!="string")return t;let s=r?ne(t):t;return Oe(s,e,n)}function Fe(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.fileName=="string"&&typeof e.fileType=="string"&&"data"in e&&typeof e.isBase64Encoded=="boolean"&&typeof e.subFolder=="string"}function k(t,e){for(let r of Object.values(t))if(Array.isArray(r))for(let n of r)e(n)}function oe(t,e=!1,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,a={},i=new Set;for(let u of t.values)k(u.InnerTree,c=>{if(re(c.type)||o&&c.type!==I.STRING)return;let m=e?c.id:u.ParamName;if(!m)return;let y=se(c.data,c.type,n,s);m in a?i.has(m)?a[m].push(y):(a[m]=[a[m],y],i.add(m)):a[m]=y});return{values:a}}function ae(t){let e=[];for(let r of t.values)k(r.InnerTree,n=>{if(!n.type.includes(Ne))return;let s=ne(n.data);Fe(s)&&e.push(s)});return e}function ie(t,e,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,a;if("byName"in e?a=t.values.find(u=>u.ParamName===e.byName):a=t.values.find(u=>{let c=!1;return k(u.InnerTree,m=>{m.id===e.byId&&(c=!0)}),c}),!a)return;let i=[];if(k(a.InnerTree,u=>{if("byId"in e&&u.id!==e.byId||re(u.type)||o&&u.type!==I.STRING)return;let c=se(u.data,u.type,n,s);i.push(c)}),i.length!==0)return i.length===1?i[0]:i}var w=class{constructor(e,r=!1){this.response=e;this.debug=r}getValues(e=!1,r={}){return oe(this.response,e,r)}getValue(e,r){return ie(this.response,e,r)}async extractMeshesFromResponse(e){let r={debug:this.debug,...e},n;try{({getThreeMeshesFromComputeResponse:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("./visualization-LZ4XZPYZ.cjs"))))}catch(s){throw new (0, _chunk6LCAIDQVcjs.d)("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",_chunk6LCAIDQVcjs.c.INVALID_STATE,{context:{originalError:s instanceof Error?s.message:String(s)}})}return n(this.response,r)}getFileData(){return ae(this.response)}async getAndDownloadFiles(e,r){let n=this.getFileData();await _chunk6LCAIDQVcjs.r.call(void 0, n,e,r)}};function ue(t){return p(t,"data")}function Ge(t){return p(t,"type")}function pe(t){if(typeof t.default!="object"||t.default===null)return{schema:t};if(!L(t.default,"innerTree")){let n=`Input "${_nullishCoalesce(t.name, () => ("unknown"))}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return _chunk6LCAIDQVcjs.e.call(void 0, ).warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=_nullishCoalesce(p(t.default,"innerTree"), () => ({}));if(Object.keys(e).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let n={};for(let[s,o]of Object.entries(e))n[s]=o.map(a=>{let i=ue(a),u=Ge(a);if(typeof i=="string"){if(u==="System.Double"||u==="System.Int32"){let c=Number(i);return Number.isNaN(c)?i:c}if(u==="System.Boolean")return i.toLowerCase()==="true";if(_optionalChain([u, 'optionalAccess', _23 => _23.startsWith, 'call', _24 => _24("Rhino.Geometry")]))try{return JSON.parse(i)}catch (e4){return i}}return i});return{schema:{...t,default:n}}}let r=[];for(let n of Object.values(e))Array.isArray(n)&&n.forEach(s=>{s&&typeof s=="object"&&L(s,"data")&&r.push(ue(s))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}var B=/^\{(\d+(?:;\d+)*)?\}$/;function v(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.entries(t);return e.length>0&&e.every(([r,n])=>B.test(r)&&Array.isArray(n))}function x(t,e,r){if(t==null)return t;if(Array.isArray(t)){let s=t.map(e).filter(o=>o!==null);return s.length>0?s:void 0}let n=e(t);return n!==null?n:r?void 0:t}var ke=t=>{if(typeof t=="number")return t;if(typeof t=="string"){let e=t.trim();if(e==="")return null;let r=Number(e);return Number.isNaN(r)?null:r}return null},Ve=t=>{if(typeof t=="boolean")return t;if(typeof t=="string"){let e=t.toLowerCase();if(e==="true")return!0;if(e==="false")return!1;throw new Error(`Invalid boolean string: "${t}"`)}return null},Me=t=>typeof t=="string"?t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t.startsWith('"')?t.slice(1):t:null,Le=t=>{if(typeof t=="string"){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}return null};function ce(t){return e=>{if(typeof e=="object"&&e!==null)return e;if(typeof e=="string"&&e.trim()!=="")try{let r=JSON.parse(e);return typeof r=="object"&&r!==null?r:(_chunk6LCAIDQVcjs.e.call(void 0, ).warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return _chunk6LCAIDQVcjs.e.call(void 0, ).warn(`Failed to parse object value "${e}" for input ${t}`,r),null}return null}}function le(t,e,r){let n=Number(t.toFixed(e));return Math.abs(t-n)<r?n:t}function We(t,e){if(!Number.isFinite(t)||t===0)return .1;let r=Math.abs(t);if(r>=1){let g=String(t).split(".")[1];if(g&&g.length>0){let b=Math.min(g.length,12),T=Math.pow(10,-b),U=Number(T.toFixed(b));return Math.abs(U-T)<e?U:T}return 1}let n=String(t),s=n.toLowerCase().match(/e(-?\d+)/);if(s){let y=Number(s[1]);if(y<0||n.toLowerCase().includes("e-")){let g=Math.abs(y),b=Math.pow(10,-g),T=Number(b.toFixed(g));return Math.abs(T-b)<e?T:b}return .1}let o=12,i=r.toFixed(o).replace(/0+$/,""),u=Math.min((i.split(".")[1]||"").length,o);if(u===0)return .1;let c=Math.pow(10,-u),m=Number(c.toFixed(u));return Math.abs(m-c)<e?m:c}function Be(t,e=1e-8){let r=t.paramType==="Integer";if(v(t.default))return{default:t.default,stepSize:r?1:.1};let n=x(t.default,ke,!0);if(r)return Array.isArray(n)?n=n.map(m=>typeof m=="number"?Math.round(m):m):typeof n=="number"&&(n=Math.round(n)),{default:n,stepSize:1};let s=Array.isArray(n)?n[0]:n,o;typeof s=="number"&&Number.isFinite(s)&&s!==0?o=s:typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum!==0?o=t.minimum:typeof t.maximum=="number"&&Number.isFinite(t.maximum)&&t.maximum!==0&&(o=t.maximum);let a=o!==void 0?We(o,e):.1,i=0,u=String(a),c=u.toLowerCase().match(/e(-?\d+)/);if(c?i=Math.abs(Number(c[1])):i=_nullishCoalesce(_optionalChain([u, 'access', _25 => _25.split, 'call', _26 => _26("."), 'access', _27 => _27[1], 'optionalAccess', _28 => _28.length]), () => (0)),i===0&&typeof s=="number"&&s!==0&&Math.abs(s)<1){let m=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(m)&&m>0&&(i=m)}return i=Math.min(Math.max(i,0),12),Array.isArray(n)?n=n.map(m=>typeof m=="number"?le(m,i,e):m):typeof n=="number"&&(n=le(n,i,e)),{default:n,stepSize:a}}var je={types:["Number","Integer"],parse(t,e){let{default:r,stepSize:n}=Be(t);return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:n,default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,default:r?[0]:0}}},Ue={types:["Boolean"],parse(t,e){let r;try{r=x(t.default,Ve,!1)}catch(n){throw n instanceof Error?new (0, _chunk6LCAIDQVcjs.d)(n.message):n}return{...e,paramType:"Boolean",default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"Boolean",default:r?[!1]:!1}}},Ke={types:["Text"],parse(t,e){let r=x(t.default,Me,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"Text",default:r?[""]:""}}},ze={types:["ValueList"],parse(t,e){if(!t.values||typeof t.values!="object"||Object.keys(t.values).length===0)throw _chunk6LCAIDQVcjs.d.missingValues(t.nickname||"unnamed","ValueList");if(t.default!==void 0&&t.default!==null){let r=String(t.default).toLowerCase();Object.keys(t.values).some(s=>s.toLowerCase()===r)||_chunk6LCAIDQVcjs.e.call(void 0, ).warn(`ValueList input "${t.nickname||"unnamed"}" default value "${t.default}" is not in available values`)}return{...e,paramType:"ValueList",values:t.values,default:t.default}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"ValueList",values:_nullishCoalesce(t.values, () => ({})),default:r?[t.default]:t.default}}},fe={types:["Geometry"],parse(t,e){let r=x(t.default,ce(t.nickname||"unnamed"),!0);return{...e,paramType:"Geometry",default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"Geometry",default:r?[null]:null}}},$e={types:["File"],parse(t,e){let r=x(t.default,ce(t.nickname||"unnamed"),!0);return{...e,paramType:"File",acceptedFormats:t.acceptedFormats,default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"File",default:r?[null]:null}}},_e={types:["Color"],parse(t,e){let r=x(t.default,Le,!1);return{...e,paramType:"Color",default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"Color",default:r?["0, 0, 0"]:"0, 0, 0"}}},qe=[je,Ue,Ke,ze,fe,$e,_e],j=new Map(qe.flatMap(t=>t.types.map(e=>[e,t]))),me=fe;var He=new Map([...j.keys()].map(t=>[t.toLowerCase(),t]));function Je(t){return _nullishCoalesce(He.get(_optionalChain([t, 'optionalAccess', _29 => _29.toLowerCase, 'call', _30 => _30()])), () => (t))}function de(t){return he(t).input}function he(t){let e={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:_nullishCoalesce(t.groupName, () => ("")),id:t.id},r=Je(t.paramType),{schema:n,warning:s}=pe({...t,paramType:r}),o=s&&{inputName:t.name||"unknown",paramType:r,message:s.message,code:s.code},a=j.get(r);try{if(!a)throw _chunk6LCAIDQVcjs.d.unknownParamType(r,t.name);return{input:a.parse(n,e),error:o}}catch(i){if(i instanceof _chunk6LCAIDQVcjs.d)return _chunk6LCAIDQVcjs.e.call(void 0, ).error(`Validation error for input ${t.name||"unknown"}:`,i.message),{input:(_nullishCoalesce(a, () => (me))).fallback(n,e),error:{inputName:t.name||"unknown",paramType:r,message:i.message,code:i.code}};throw new (0, _chunk6LCAIDQVcjs.d)(i instanceof Error?i.message:String(i),"VALIDATION_ERROR",{context:{paramName:t.name,paramType:r},originalError:i instanceof Error?i:new Error(String(i))})}}function ye(t){return V(t).inputs}function V(t){let e=[],r=[];for(let n of t){let{input:s,error:o}=he(n);e.push(s),o&&r.push(o)}return{inputs:e,parseErrors:r}}function ge(t){return{id:p(t,"id"),name:p(t,"name"),nickname:_nullishCoalesce(p(t,"nickname"), () => (null)),description:p(t,"description"),paramType:p(t,"paramType"),treeAccess:p(t,"treeAccess"),minimum:_nullishCoalesce(p(t,"minimum"), () => (null)),maximum:_nullishCoalesce(p(t,"maximum"), () => (null)),atLeast:p(t,"atLeast"),atMost:p(t,"atMost"),stepSize:p(t,"stepSize"),default:p(t,"default"),values:p(t,"values"),acceptedFormats:p(t,"acceptedFormats"),groupName:_nullishCoalesce(p(t,"groupName"), () => (""))}}function be(t){return{name:p(t,"name"),nickname:_nullishCoalesce(p(t,"nickname"), () => (null)),paramType:p(t,"paramType"),id:p(t,"id")}}async function E(t,e){let r=P(t,[]),n={};if(r.algo&&(n.algo=r.algo),r.pointer&&(n.pointer=r.pointer),!n.algo&&!n.pointer)throw new (0, _chunk6LCAIDQVcjs.d)("Definition must resolve to either a URL pointer or base64 algo",_chunk6LCAIDQVcjs.c.INVALID_INPUT,{context:{definition:t}});let s=await _chunk6LCAIDQVcjs.h.call(void 0, "io",n,e);if(!s||typeof s!="object")throw new (0, _chunk6LCAIDQVcjs.d)("Invalid IO response structure",_chunk6LCAIDQVcjs.c.INVALID_INPUT,{context:{response:s,definition:t}});let o=Te(p(s,"warnings")),a=Te(p(s,"errors")),i=p(s,"inputs"),u=p(s,"outputs");return{inputs:Array.isArray(i)?i.map(ge):[],outputs:Array.isArray(u)?u.map(be):[],...o&&{loadWarnings:o},...a&&{loadErrors:a}}}function Te(t){if(!Array.isArray(t))return;let e=t.filter(r=>typeof r=="string"&&r.trim().length>0);return e.length>0?e:void 0}async function F(t,e){C("fetchParsedDefinitionIO",_nullishCoalesce(e.suppressBrowserWarning, () => (e.suppressClientSideWarning)));let{inputs:r,outputs:n,loadWarnings:s,loadErrors:o}=await E(t,e),{inputs:a,parseErrors:i}=V(r);return{inputs:a,outputs:n,...i.length>0&&{parseErrors:i},...s&&{loadWarnings:s},...o&&{loadErrors:o}}}var M=class t{constructor(e){_chunk6LCAIDQVcjs.b.call(void 0, this,"innerTree");_chunk6LCAIDQVcjs.b.call(void 0, this,"paramName");this.paramName=e,this.innerTree={}}append(e,r){let n=t.formatPathString(e);this.innerTree[n]||(this.innerTree[n]=[]);let s=r.map(o=>({data:t.serializeValue(o)}));return this.innerTree[n].push(...s),this}appendSingle(e,r){return this.append(e,[r])}fromDataTreeDefault(e){this.innerTree={};for(let[r,n]of Object.entries(e)){if(!Array.isArray(n))continue;let s=t.parsePathString(r);this.append(s,n)}return this}appendFlat(e){let r=Array.isArray(e)?e:[e];return this.append([0],r)}flatten(){let e=[];for(let r of Object.values(this.innerTree))if(Array.isArray(r))for(let n of r)e.push(t.deserializeValue(n.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let r=t.formatPathString(e),n=this.innerTree[r];if(n)return n.map(s=>t.deserializeValue(s.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(e){return e.filter(r=>t.hasValidValue(r.default)).map(r=>{let n=new t(r.nickname||"unnamed"),s=r.default;if(r.treeAccess&&v(s))n.fromDataTreeDefault(s),t.isNumericInput(r)&&n.applyNumericConstraints(r.minimum,r.maximum,r.nickname||"unnamed");else{let o=Array.isArray(s)?s:[s],a=t.processValues(o,r);n.appendFlat(a)}return n.toComputeFormat()})}static fromInputParam(e){return t.hasValidValue(e.default)?t.fromInputParams([e])[0]:void 0}static replaceTreeValue(e,r,n){let s=e.length>0&&e[0]instanceof t,o=t.buildFromValue(r,n);if(s){let c=e,m=c.findIndex(y=>y.getParamName()===r);return m!==-1?c[m]=o:c.push(o),c}let a=e,i=o.toComputeFormat(),u=a.findIndex(c=>c.ParamName===r);return u!==-1?a[u]=i:a.push(i),a}static buildFromValue(e,r){let n=new t(e);return v(r)?n.fromDataTreeDefault(r):n.appendFlat(r),n}static getTreeValue(e,r){let s=e.length>0&&e[0]instanceof t?t.readFromBuilders(e,r):t.readFromDataTrees(e,r);return s===null||s.length===0?null:s.length===1?s[0]:s}static readFromBuilders(e,r){let n=e.find(s=>s.getParamName()===r);return n?n.flatten():null}static readFromDataTrees(e,r){let n=e.find(a=>a.ParamName===r);if(!_optionalChain([n, 'optionalAccess', _31 => _31.InnerTree]))return null;let s=Object.keys(n.InnerTree)[0];if(!s)return null;let o=n.InnerTree[s];return Array.isArray(o)?o.map(a=>_optionalChain([a, 'optionalAccess', _32 => _32.data])!==void 0?t.deserializeValue(a.data):null).filter(a=>a!==null):_optionalChain([o, 'optionalAccess', _33 => _33.data])!==void 0?[t.deserializeValue(o.data)]:o!==void 0?[o]:null}static parsePathString(e){let r=e.match(B);return r?r[1]?r[1].split(";").map(Number):[]:(_chunk6LCAIDQVcjs.e.call(void 0, ).warn(`Invalid TreeBuilder path format: ${e}, using [0]`),[0])}static formatPathString(e){return`{${e.join(";")}}`}applyNumericConstraints(e,r,n){for(let s of Object.values(this.innerTree))if(Array.isArray(s))for(let o of s){let a=t.deserializeValue(o.data);if(typeof a=="number"){let i=t.clampValue(a,e,r,n);o.data=t.serializeValue(i)}}}static serializeValue(e){return typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:typeof e=="object"&&e!==null?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e=="boolean"||typeof e=="number"||typeof e!="string")return e;if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch (e5){return e}return e.trim()!==""&&!isNaN(Number(e))?Number(e):e==="true"?!0:e==="false"?!1:e}static hasValidValue(e){return e==null?!1:typeof e=="string"?!0:!(Array.isArray(e)&&e.length===0||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType==="Number"||e.paramType==="Integer"}static processValues(e,r){return e.map(n=>t.isNumericInput(r)&&typeof n=="number"?t.clampValue(n,r.minimum,r.maximum,r.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(e,r,n,s){let o=e;return r!=null&&o<r&&(_chunk6LCAIDQVcjs.e.call(void 0, ).warn(`${s}: ${e} below min ${r}, clamping`),o=r),n!=null&&o>n&&(_chunk6LCAIDQVcjs.e.call(void 0, ).warn(`${s}: ${e} above max ${n}, clamping`),o=n),o}};exports.a = D; exports.b = S; exports.c = R; exports.d = w; exports.e = de; exports.f = ye; exports.g = E; exports.h = F; exports.i = M;
2
+ //# sourceMappingURL=chunk-CFBKO3HX.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-CFBKO3HX.cjs","../src/core/utils/read-field.ts","../src/core/utils/warnings.ts","../src/features/grasshopper/solve.ts"],"names":["readField","obj","name","record","lower","key","hasField","warnIfClientSide","functionName","suppress","getLogger","DEFINITION_LOAD_FAILED","isDefinitionLoadMiss","error","RhinoComputeError","ErrorCodes","warnOnEmptyInnerTrees","response","debug","values","empty","param","innerTree","scope"],"mappings":"AAAA,2/BAA8G,SCyB9FA,CAAAA,CAAuBC,CAAAA,CAAcC,CAAAA,CAA6B,CACjF,EAAA,CAAI,CAACD,CAAAA,EAAO,OAAOA,CAAAA,EAAQ,QAAA,CAAU,MAAA,CAErC,IAAME,CAAAA,CAASF,CAAAA,CACf,EAAA,CAAIC,EAAAA,GAAQC,CAAAA,CAAQ,OAAOA,CAAAA,CAAOD,CAAI,CAAA,CAEtC,IAAME,CAAAA,CAAQF,CAAAA,CAAK,WAAA,CAAY,CAAA,CAC/B,GAAA,CAAA,IAAWG,EAAAA,GAAO,MAAA,CAAO,IAAA,CAAKF,CAAM,CAAA,CACnC,EAAA,CAAIE,CAAAA,CAAI,WAAA,CAAY,CAAA,GAAMD,CAAAA,CAAO,OAAOD,CAAAA,CAAOE,CAAG,CAGpD,CAOO,SAASC,CAAAA,CAASL,CAAAA,CAAcC,CAAAA,CAAuB,CAC7D,EAAA,CAAI,CAACD,CAAAA,EAAO,OAAOA,CAAAA,EAAQ,QAAA,CAAU,MAAO,CAAA,CAAA,CAC5C,IAAME,CAAAA,CAASF,CAAAA,CACf,EAAA,CAAIC,EAAAA,GAAQC,CAAAA,CAAQ,MAAO,CAAA,CAAA,CAC3B,IAAMC,CAAAA,CAAQF,CAAAA,CAAK,WAAA,CAAY,CAAA,CAC/B,OAAO,MAAA,CAAO,IAAA,CAAKC,CAAM,CAAA,CAAE,IAAA,CAAME,CAAAA,EAAQA,CAAAA,CAAI,WAAA,CAAY,CAAA,GAAMD,CAAK,CACrE,CC/CO,SAASG,CAAAA,CAAiBC,CAAAA,CAAsBC,CAAAA,CAA0B,CAC5EA,CAAAA,EAIA,OAAO,MAAA,CAAW,GAAA,EACrBC,iCAAAA,CAAU,CAAE,IAAA,CACX,CAAA,SAAA,EAAYF,CAAY,CAAA,8GAAA,CACzB,CAEF,CCeA,IAAMG,EAAAA,CAAyB,uCAAA,CAG/B,SAASC,EAAAA,CAAqBC,CAAAA,CAAyB,CACtD,OAAMA,EAAAA,WAAiBC,mBAAAA,CAEtBD,CAAAA,CAAM,IAAA,GAASE,mBAAAA,CAAW,qBAAA,EAC1BF,CAAAA,CAAM,OAAA,CAAQ,QAAA,CAASF,EAAsB,CAAA,CAHI,CAAA,CAKnD,CAeO,SAASK,CAAAA,CAAsBC,CAAAA,CAAsCC,CAAAA,CAAuB,CAClG,EAAA,CAAI,CAACA,CAAAA,CAAO,MAAA,CAEZ,IAAMC,CAAAA,CAASnB,CAAAA,CAAqBiB,CAAAA,CAAU,QAAQ,CAAA,CACtD,EAAA,CAAI,CAAC,KAAA,CAAM,OAAA,CAAQE,CAAM,CAAA,EAAKA,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAEnD,IAAMC,CAAAA,CAAkB,CAAC,CAAA,CACzB,GAAA,CAAA,IAAWC,EAAAA,GAASF,CAAAA,CAAQ,CAC3B,IAAMG,CAAAA,CAAYtB,CAAAA,CAAmCqB,CAAAA,CAAO,WAAW,CAAA,CAAA,CAEnE,CAACC,CAAAA,EAAa,MAAA,CAAO,IAAA,CAAKA,CAAS,CAAA,CAAE,MAAA,GAAW,CAAA,CAAA,EACnDF,CAAAA,CAAM,IAAA,kBAAKpB,CAAAA,CAAkBqB,CAAAA,CAAO,WAAW,CAAA,SAAK,aAAW,CAEjE,CAEA,EAAA,CAAID,CAAAA,CAAM,MAAA,GAAW,CAAA,CAAG,MAAA,CAExB,IAAMG,CAAAA,CAAQH,CAAAA,CAAM,MAAA,GAAWD,CAAAA,CAAO,MAAA,CAAS,KAAA,CAAQ,CAAA,EAAA","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-CFBKO3HX.cjs","sourcesContent":[null,"/**\n * Case-insensitive single-key reader for wire payloads.\n *\n * The Rhino Compute family serializes the same logical field with different\n * casing depending on the server branch:\n *\n * - mcneel 8.x / 9.x: the IO schema is PascalCase (`ParamType`, `Default`,\n * `InnerTree`, …) because those C# classes carry no `[JsonProperty]`.\n * - VektorNode Compute8: the IO schema is camelCase (`paramType`, `default`,\n * …) because the fork added `[JsonProperty(\"camelCase\")]`, BUT the nested\n * `default` DataTree wrapper stays PascalCase (`ParamName` / `InnerTree`)\n * since `Resthopper.IO.DataTree` is an external type the fork can't attribute.\n *\n * So a single response can mix casings, and which casing a given field uses\n * depends on the server branch. Rather than deep-camelCasing the whole payload\n * (the old `camelcaseKeys` approach — which corrupted user-authored value-list\n * label keys and item `data` JSON), read the specific fields we care about\n * case-insensitively and leave everything else verbatim.\n *\n * Prefers an exact-case match when present, then falls back to the first\n * case-insensitive match. Returns `undefined` when no key matches.\n *\n * @param obj - The source object (any non-object input yields `undefined`).\n * @param name - The logical field name, in any casing.\n */\nexport function readField<T = unknown>(obj: unknown, name: string): T | undefined {\n\tif (!obj || typeof obj !== 'object') return undefined;\n\n\tconst record = obj as Record<string, unknown>;\n\tif (name in record) return record[name] as T;\n\n\tconst lower = name.toLowerCase();\n\tfor (const key of Object.keys(record)) {\n\t\tif (key.toLowerCase() === lower) return record[key] as T;\n\t}\n\treturn undefined;\n}\n\n/**\n * True when `obj` has a key matching `name` (case-insensitively). Distinguishes\n * \"field present but value is null/undefined\" from \"field absent\" — needed where\n * presence itself carries meaning (e.g. an `innerTree` that exists but is empty).\n */\nexport function hasField(obj: unknown, name: string): boolean {\n\tif (!obj || typeof obj !== 'object') return false;\n\tconst record = obj as Record<string, unknown>;\n\tif (name in record) return true;\n\tconst lower = name.toLowerCase();\n\treturn Object.keys(record).some((key) => key.toLowerCase() === lower);\n}\n","import { getLogger } from './logger';\n\nexport function warnIfClientSide(functionName: string, suppress?: boolean): void {\n\tif (suppress) {\n\t\treturn;\n\t}\n\n\tif (typeof window !== 'undefined') {\n\t\tgetLogger().warn(\n\t\t\t`Warning: ${functionName} is running on the client side. For better performance and security, consider running this on the server side.`\n\t\t);\n\t}\n}\n","import { fetchRhinoCompute, RhinoComputeError, ErrorCodes } from '@/core';\nimport { base64ByteArray, encodeStringToBase64, isBase64 } from '@/core/utils/encoding';\nimport { getLogger } from '@/core/utils/logger';\nimport { readField } from '@/core/utils/read-field';\nimport { warnIfClientSide } from '@/core/utils/warnings';\n\nimport {\n\tGrasshopperRequestSchema,\n\tGrasshopperComputeConfig,\n\tGrasshopperComputeResponse,\n\tDataTree\n} from './types';\n\n/**\n * The exact message the server throws when it can neither resolve a `pointer`\n * nor a base64 `algo` to a definition (ResthopperEndpoints.cs). This is the\n * signal that a cache-key pointer missed the server's definition cache (GC'd, or\n * a different child in the pool), so the caller should retry with the full\n * definition. Matched as a substring because the server wraps it with a category\n * prefix in its exception handler.\n *\n * NOTE: the server only includes this message when running in debug mode; its\n * production exception handler scrubs the message to a generic string. The\n * reliable signal is therefore {@link ErrorCodes.DEFINITION_NOT_CACHED}, derived\n * from the server's machine `code` (which isn't scrubbed). The string match is\n * kept as a fallback for debug-mode servers and forks that don't yet emit a code.\n */\nconst DEFINITION_LOAD_FAILED = 'Unable to load grasshopper definition';\n\n/** Does this error look like a server-side definition-load miss? */\nfunction isDefinitionLoadMiss(error: unknown): boolean {\n\tif (!(error instanceof RhinoComputeError)) return false;\n\treturn (\n\t\terror.code === ErrorCodes.DEFINITION_NOT_CACHED ||\n\t\terror.message.includes(DEFINITION_LOAD_FAILED)\n\t);\n}\n\n/**\n * Debug aid: a solve can return successfully yet hand back outputs whose\n * `InnerTree` is empty (`{}`), meaning that parameter produced nothing — often a\n * sign the definition didn't actually compute (wrong/missing inputs, a guarded\n * branch). The names tell you exactly which output was empty so you can trace it\n * back to the responsible branch.\n *\n * Only logs when `debug` is set: an empty output can be legitimate, so this is a\n * diagnostic, never a hard failure. Reads `ParamName` / `InnerTree`\n * case-insensitively to stay robust across server-branch casing.\n *\n * @internal Exported for testing.\n */\nexport function warnOnEmptyInnerTrees(response: GrasshopperComputeResponse, debug?: boolean): void {\n\tif (!debug) return;\n\n\tconst values = readField<unknown[]>(response, 'values');\n\tif (!Array.isArray(values) || values.length === 0) return;\n\n\tconst empty: string[] = [];\n\tfor (const param of values) {\n\t\tconst innerTree = readField<Record<string, unknown>>(param, 'innerTree');\n\t\t// Treat a missing or empty innerTree as \"produced nothing\".\n\t\tif (!innerTree || Object.keys(innerTree).length === 0) {\n\t\t\tempty.push(readField<string>(param, 'paramName') ?? '<unnamed>');\n\t\t}\n\t}\n\n\tif (empty.length === 0) return;\n\n\tconst scope = empty.length === values.length ? 'all' : `${empty.length}/${values.length}`;\n\tgetLogger().warn(\n\t\t`Solve returned empty output(s) (${scope}): ${empty.join(', ')}. ` +\n\t\t\t`These parameters produced no data — check the definition's inputs and the branch feeding each.`\n\t);\n}\n\n/**\n * Result of a solve that also reports the definition's server-side cache key.\n *\n * `cacheKey` is the `md5_…` identifier the server assigned to the (base64)\n * definition — stable for identical content. A caller that holds it can solve\n * the same definition again by reference (`pointer: cacheKey`) instead of\n * re-uploading the full base64, which matters a lot for large (multi-MB)\n * definitions on a live UI. `null` when the server didn't return one (e.g. a\n * URL-pointer solve).\n */\nexport interface SolveWithCacheKey {\n\tresponse: GrasshopperComputeResponse;\n\tcacheKey: string | null;\n}\n\n/**\n * Runs a Rhino Compute job using the provided tree prototypes and Grasshopper definition.\n *\n * @public Use this for direct compute control. For high-level API, use `GrasshopperClient.solve()`.\n *\n * @param dataTree - An array of `DataTree` objects representing the input data for the compute job.\n * @param definition - The Grasshopper definition, which can be:\n * - A URL string (e.g., 'https://example.com/definition.gh')\n * - A base64-encoded string of the .gh file\n * - A plain string (will be base64-encoded)\n * - A Uint8Array of the .gh file (will be base64-encoded)\n * @param config - Compute configuration (server URL, API key, etc. along with optional timeout, units, etc.)\n * @returns An object containing the compute result and extracted file data.\n *\n * @example\n * // Using a URL\n * await solveGrasshopperDefinition(trees, 'https://example.com/definition.gh', config);\n *\n * // Using a base64 string\n * await solveGrasshopperDefinition(trees, 'UEsDBBQAAAAIAL...', config);\n *\n * // Using binary data\n * const fileData = new Uint8Array([...]);\n * await solveGrasshopperDefinition(trees, fileData, config);\n */\nexport async function solveGrasshopperDefinition(\n\tdataTree: DataTree[],\n\tdefinition: string | Uint8Array,\n\tconfig: GrasshopperComputeConfig\n): Promise<GrasshopperComputeResponse> {\n\tif (config.debug) {\n\t\twarnIfClientSide(\n\t\t\t'solveGrasshopperDefinition',\n\t\t\tconfig.suppressBrowserWarning ?? config.suppressClientSideWarning\n\t\t);\n\t}\n\n\tconst { response } = await runSolve(prepareGrasshopperArgs(definition, dataTree), config);\n\treturn response;\n}\n\n/**\n * Solve while reporting the server's definition cache key.\n *\n * Behaves like {@link solveGrasshopperDefinition} but returns the `cacheKey` the\n * server assigned, so a caller (e.g. the scheduler) can later solve the same\n * definition by reference instead of re-uploading it. The cache key is only\n * meaningful for base64/binary definitions; a URL-pointer solve returns the URL.\n *\n * @internal\n */\nexport async function solveGrasshopperDefinitionWithCacheKey(\n\tdataTree: DataTree[],\n\tdefinition: string | Uint8Array,\n\tconfig: GrasshopperComputeConfig\n): Promise<SolveWithCacheKey> {\n\tif (config.debug) {\n\t\twarnIfClientSide(\n\t\t\t'solveGrasshopperDefinitionWithCacheKey',\n\t\t\tconfig.suppressBrowserWarning ?? config.suppressClientSideWarning\n\t\t);\n\t}\n\n\treturn runSolve(prepareGrasshopperArgs(definition, dataTree), config);\n}\n\n/**\n * Solve a definition by its server-side cache key (`pointer: cacheKey`),\n * skipping the (potentially multi-MB) base64 upload. If the key has been evicted\n * from the server's definition cache — `DEFINITION_LOAD_FAILED` — transparently\n * retry once with the full `definition` and report the fresh cache key so the\n * caller can update its mapping.\n *\n * @returns The solve result plus the (possibly refreshed) cache key, and whether\n * the fast path missed (so callers can record the new key / track hit rate).\n * @internal\n */\nexport async function solveByCacheKey(\n\tdataTree: DataTree[],\n\tcacheKey: string,\n\tdefinition: string | Uint8Array,\n\tconfig: GrasshopperComputeConfig\n): Promise<SolveWithCacheKey & { missed: boolean }> {\n\tif (config.debug) {\n\t\twarnIfClientSide(\n\t\t\t'solveByCacheKey',\n\t\t\tconfig.suppressBrowserWarning ?? config.suppressClientSideWarning\n\t\t);\n\t}\n\n\tconst pointerArgs: GrasshopperRequestSchema = { algo: null, pointer: cacheKey, values: dataTree };\n\n\ttry {\n\t\tconst fast = await runSolve(pointerArgs, config);\n\t\treturn { ...fast, missed: false };\n\t} catch (error) {\n\t\tif (!isDefinitionLoadMiss(error)) throw error;\n\t\t// Cache miss — fall back to the full upload and capture the fresh key.\n\t\tconst full = await runSolve(prepareGrasshopperArgs(definition, dataTree), config);\n\t\treturn { ...full, missed: true };\n\t}\n}\n\n/**\n * Shared solve body: apply optional settings, POST, and split the server's\n * `pointer` (its cache key) off the response. Stripping via shallow copy rather\n * than `delete` keeps any already-observed response object unmutated.\n */\nasync function runSolve(\n\targs: GrasshopperRequestSchema,\n\tconfig: GrasshopperComputeConfig\n): Promise<SolveWithCacheKey> {\n\tapplyOptionalComputeSettings(args, config);\n\n\tconst result = await fetchRhinoCompute<GrasshopperComputeResponse>('grasshopper', args, config);\n\n\tif ('pointer' in result) {\n\t\tconst { pointer, ...rest } = result as GrasshopperComputeResponse & { pointer?: unknown };\n\t\tconst response = rest as GrasshopperComputeResponse;\n\t\twarnOnEmptyInnerTrees(response, config.debug);\n\t\treturn {\n\t\t\tresponse,\n\t\t\tcacheKey: typeof pointer === 'string' ? pointer : null\n\t\t};\n\t}\n\n\twarnOnEmptyInnerTrees(result, config.debug);\n\treturn { response: result, cacheKey: null };\n}\n\n// ============================================================================\n// Grasshopper Arguments\n// ============================================================================\n\n/**\n * Prepares Grasshopper arguments from a definition and data tree.\n * Automatically detects the definition format and converts it appropriately.\n *\n * @param definition - Can be a URL, base64 string, plain string, or Uint8Array\n * @param dataTree - Array of DataTree objects for compute inputs\n * @internal\n */\nexport function prepareGrasshopperArgs(\n\tdefinition: string | Uint8Array,\n\tdataTree: DataTree[]\n): GrasshopperRequestSchema {\n\tconst args: GrasshopperRequestSchema = {\n\t\talgo: null,\n\t\tpointer: null,\n\t\tvalues: dataTree\n\t};\n\n\tif (definition instanceof Uint8Array) {\n\t\t// Binary data → convert to base64\n\t\targs.algo = base64ByteArray(definition);\n\t} else if (/^https?:\\/\\//i.test(definition)) {\n\t\t// URL → use as pointer reference\n\t\targs.pointer = definition;\n\t} else if (isBase64(definition)) {\n\t\t// Already base64 → use as-is\n\t\targs.algo = definition;\n\t} else {\n\t\t// Plain string → encode to base64\n\t\targs.algo = encodeStringToBase64(definition);\n\t}\n\n\treturn args;\n}\n\n/**\n * @internal\n */\nexport function applyOptionalComputeSettings(\n\targlist: GrasshopperRequestSchema,\n\toptions: GrasshopperComputeConfig\n): void {\n\tif (options.cachesolve != null) arglist.cachesolve = options.cachesolve;\n\tif (options.cacheerroredsolves != null) arglist.cacheerroredsolves = options.cacheerroredsolves;\n\tif (options.modelunits != null) arglist.modelunits = options.modelunits;\n\tif (options.angletolerance != null) arglist.angletolerance = options.angletolerance;\n\tif (options.absolutetolerance != null) arglist.absolutetolerance = options.absolutetolerance;\n\tif (options.dataversion != null) arglist.dataversion = options.dataversion;\n}\n"]}
@@ -0,0 +1,55 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk6LCAIDQVcjs = require('./chunk-6LCAIDQV.cjs');var _three = require('three'); var z = _interopRequireWildcard(_three); var k = _interopRequireWildcard(_three); var I = _interopRequireWildcard(_three); var U = _interopRequireWildcard(_three); var Z = _interopRequireWildcard(_three); var ge = _interopRequireWildcard(_three); var D = _interopRequireWildcard(_three); var E = _interopRequireWildcard(_three); var L = _interopRequireWildcard(_three); var _ = _interopRequireWildcard(_three); var F = _interopRequireWildcard(_three);var W={HUGE_THRESHOLD:1e4,LARGE_THRESHOLD:1e3,SCALE_RATIO_THRESHOLD:100,NEAR_PLANE_FACTOR:{TINY:1e-4,SMALL:.001,NORMAL:.01},FAR_PLANE_FACTOR:{HUGE:100,LARGE:50,NORMAL:20},INITIAL_DISTANCE_MULTIPLIER:4};function In(e,r,t,n,o){if(Be(e),r.length===0)return;r.forEach(d=>{e.add(d)});let a=J(r),i=a.getCenter(new z.Vector3),l=a.getSize(new z.Vector3),s=Math.max(l.x,l.y,l.z);if(s/Math.min(l.x||1,l.y||1,l.z||1)>W.SCALE_RATIO_THRESHOLD||s>W.HUGE_THRESHOLD?(t.near=s*W.NEAR_PLANE_FACTOR.TINY,t.far=s*W.FAR_PLANE_FACTOR.HUGE):s>W.LARGE_THRESHOLD?(t.near=s*W.NEAR_PLANE_FACTOR.SMALL,t.far=s*W.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,s*W.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,s*W.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),o)n.minDistance=t.near*2,n.maxDistance=t.far*.9;else{let d=s*W.INITIAL_DISTANCE_MULTIPLIER;t.position.set(i.x+d*.8,i.y+d,i.z+d*1.2),n.target.copy(i),n.minDistance=t.near*2,n.maxDistance=t.far*.9,n.update()}}function ce(e){if(!e||typeof e!="string")return _chunk6LCAIDQVcjs.e.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new z.Color(16777215);let r=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(r))try{let t=r.startsWith("#")?r:`#${r}`;return new z.Color(t)}catch (e2){return _chunk6LCAIDQVcjs.e.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new z.Color(16777215)}if(r.includes(",")){let t=r.split(",").map(n=>parseInt(n.trim(),10));if(t.length===3&&t.every(n=>!isNaN(n)&&n>=0&&n<=255))return new z.Color(t[0]/255,t[1]/255,t[2]/255)}try{return new z.Color(r.toLowerCase())}catch (e3){return _chunk6LCAIDQVcjs.e.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new z.Color(16777215)}}function ue(e,r,t="z"){e.forEach(n=>{n.position[t]-=r})}function J(e){let r=new z.Box3;return e.length===0||e.forEach(t=>{t.updateMatrixWorld(!0);let n=new z.Box3().setFromObject(t);r.union(n)}),r}var Ve=new Set(["floor","grid","label-layer"]);function Be(e){[...e.children].forEach(t=>{Ve.has(t.userData.id)||t.userData.source!=="user"&&(t.traverse(n=>{let o=n;if(!o.geometry&&!o.material)return;_optionalChain([o, 'access', _2 => _2.geometry, 'optionalAccess', _3 => _3.dispose, 'call', _4 => _4()]);let a=o.material;if(!a)return;(Array.isArray(a)?a:[a]).forEach(l=>{for(let s of Object.values(l))s instanceof z.Texture&&s.dispose();l.dispose()})}),t.removeFromParent())})}function ze(e){let r=e.clone().normalize(),t=new k.Vector3(0,0,1),n=new k.Vector3(0,1,0),o=Math.abs(r.dot(t))>.9?n:t,a=new k.Vector3().crossVectors(r,o).normalize(),i=new k.Vector3().crossVectors(a,r).normalize();return{top:r.clone(),bottom:r.clone().negate(),front:i.clone(),back:i.clone().negate(),right:a.clone(),left:a.clone().negate(),iso:i.clone().multiplyScalar(1.2).add(a.clone()).add(r.clone()).normalize()}}function de(e){let{scene:r,perspective:t,controls:n,onActiveCameraChange:o}=e,a=(_nullishCoalesce(e.up, () => (t.up))).clone().normalize(),i=ze(a),l=new k.OrthographicCamera(-1,1,1,-1,t.near,t.far);l.up.copy(a);let s="perspective",c=t.aspect,d=()=>s==="perspective"?t:l,u=()=>{let R=t.position.distanceTo(n.target)*Math.tan(t.fov*Math.PI/360),b=R*c;l.left=-b,l.right=b,l.top=R,l.bottom=-R,l.near=t.near,l.far=t.far,l.updateProjectionMatrix()},m=g=>{g!==s&&(g==="orthographic"?(l.position.copy(t.position),l.up.copy(t.up),l.lookAt(n.target),u()):t.position.copy(l.position),s=g,n.object=d(),n.update(),o(d()))},p=(g,R=!0)=>{let b=ke(r),T=b.isEmpty()?n.target.clone():b.getCenter(new k.Vector3),P=b.isEmpty()?new k.Vector3(1,1,1):b.getSize(new k.Vector3),y=Math.max(P.x,P.y,P.z)||1,w=t.fov*(Math.PI/180),C=y/(2*Math.tan(w/2))*1.5,O=Ue(g,a),A=T.clone().add(O.clone().multiplyScalar(C)),j=d();R?Ge(j,n,A,T,()=>{s==="orthographic"&&u()}):(j.position.copy(A),n.target.copy(T),s==="orthographic"&&u(),n.update())};return{getActiveCamera:d,getProjection:()=>s,setProjection:m,toggleProjection:()=>(m(s==="perspective"?"orthographic":"perspective"),s),setView:(g,R=!0)=>{p(i[g],R)},setViewDirection:p,setRotateEnabled:g=>{n.enableRotate=g},isRotateEnabled:()=>n.enableRotate,updateAspect:(g,R)=>{c=R===0?c:g/R,s==="orthographic"&&u()}}}var Fe=new Set(["grid","floor","label-layer","measure"]);function je(e){let r=e;for(;r;){if(typeof r.userData.id=="string"&&Fe.has(r.userData.id))return!0;r=r.parent}return!1}function ke(e){let r=[];return e.traverse(t=>{let n=t;t.visible&&!je(t)&&n.geometry&&r.push(t)}),J(r)}function Ue(e,r){let t=r.clone().normalize(),n=e.clone().normalize();if(Math.abs(n.dot(t))<.9999)return e;let o=Math.abs(t.dot(new k.Vector3(0,0,1)))>.9?new k.Vector3(0,1,0):new k.Vector3(0,0,1),a=new k.Vector3().crossVectors(t,o).normalize(),i=.5*Math.PI/180;return n.multiplyScalar(Math.cos(i)).add(a.multiplyScalar(Math.sin(i))).normalize()}var _e=e=>1-Math.pow(1-e,3);function Ge(e,r,t,n,o,a=250){let i=e.position.clone(),l=r.target.clone(),s=performance.now(),c=()=>{let d=_e(Math.min((performance.now()-s)/a,1));e.position.lerpVectors(i,t,d),r.target.lerpVectors(l,n,d),o(),r.update(),d<1&&requestAnimationFrame(c)};requestAnimationFrame(c)}var Ne=`
2
+ varying vec3 vWorldPos;
3
+ void main() {
4
+ vec4 world = modelMatrix * vec4(position, 1.0);
5
+ vWorldPos = world.xyz;
6
+ gl_Position = projectionMatrix * viewMatrix * world;
7
+ }
8
+ `,We=`
9
+ precision highp float;
10
+ varying vec3 vWorldPos;
11
+
12
+ uniform vec2 uAxes; // indices (0=x,1=y,2=z) of the two in-plane world axes
13
+ uniform float uCell;
14
+ uniform float uMajor;
15
+ uniform vec3 uCellColor;
16
+ uniform vec3 uMajorColor;
17
+ uniform vec3 uCenter; // fade center (camera position), projected onto plane
18
+ uniform float uFade;
19
+
20
+ // Antialiased grid line intensity for a given spacing, using screen-space derivatives so lines
21
+ // stay ~1px regardless of zoom (the standard "pristine grid" technique).
22
+ float gridLine(vec2 coord, float spacing) {
23
+ vec2 c = coord / spacing;
24
+ vec2 d = fwidth(c);
25
+ vec2 g = abs(fract(c - 0.5) - 0.5) / max(d, 1e-6);
26
+ float line = min(g.x, g.y);
27
+ return 1.0 - clamp(line, 0.0, 1.0);
28
+ }
29
+
30
+ // Index a vec3 by a float axis id (0/1/2) without dynamic indexing (WebGL1-safe).
31
+ float axis(vec3 v, float i) {
32
+ return i < 0.5 ? v.x : (i < 1.5 ? v.y : v.z);
33
+ }
34
+
35
+ void main() {
36
+ // Pick the two in-plane world coordinates.
37
+ vec2 coord = vec2(axis(vWorldPos, uAxes.x), axis(vWorldPos, uAxes.y));
38
+
39
+ float minor = gridLine(coord, uCell);
40
+ float major = gridLine(coord, uCell * uMajor);
41
+
42
+ vec3 color = mix(uCellColor, uMajorColor, major);
43
+ float alpha = max(minor, major);
44
+
45
+ // Radial fade from the camera-projected center.
46
+ float dist = distance(vWorldPos, uCenter);
47
+ float fade = 1.0 - clamp(dist / uFade, 0.0, 1.0);
48
+ alpha *= fade * fade;
49
+
50
+ if (alpha < 0.001) discard;
51
+ gl_FragColor = vec4(color, alpha);
52
+ }
53
+ `;function me(e={}){let{cellSize:r=1,majorEvery:t=10,cellColor:n=8947848,majorColor:o=4473924,fadeDistance:a=100,plane:i="y"}=e,l=i==="y"?new I.Vector2(0,2):i==="z"?new I.Vector2(0,1):new I.Vector2(1,2),s=a*2.5,c=new I.PlaneGeometry(s,s);i==="y"?c.rotateX(-Math.PI/2):i==="x"&&c.rotateY(Math.PI/2);let d=new I.ShaderMaterial({vertexShader:Ne,fragmentShader:We,transparent:!0,depthWrite:!1,side:I.DoubleSide,uniforms:{uAxes:{value:l},uCell:{value:r},uMajor:{value:t},uCellColor:{value:new I.Color(n)},uMajorColor:{value:new I.Color(o)},uCenter:{value:new I.Vector3},uFade:{value:a}}}),u=new I.Mesh(c,d);u.name="grid",u.userData.id="grid",u.renderOrder=-1;let m=new I.Vector3;return{object:u,update:p=>{i==="y"?(u.position.set(p.x,0,p.z),m.set(p.x,0,p.z)):i==="z"?(u.position.set(p.x,p.y,0),m.set(p.x,p.y,0)):(u.position.set(0,p.y,p.z),m.set(0,p.y,p.z)),d.uniforms.uCenter.value.copy(m)},setVisible:p=>{u.visible=p},dispose:()=>{c.dispose(),d.dispose()}}}var _ViewHelperjs = require('three/addons/helpers/ViewHelper.js');function pe(e){let{camera:r,domElement:t,controller:n}=e,o=new (0, _ViewHelperjs.ViewHelper)(r,t);o.setLabels("X","Y","Z");let a=!0,i=128,l=new U.Raycaster,s=new U.OrthographicCamera(-2,2,2,-2,0,4);s.position.set(0,0,2);let c={posX:new U.Vector3(1,0,0),negX:new U.Vector3(-1,0,0),posY:new U.Vector3(0,1,0),negY:new U.Vector3(0,-1,0),posZ:new U.Vector3(0,0,1),negZ:new U.Vector3(0,0,-1)},d=m=>{let p=t.getBoundingClientRect(),f=p.left+t.offsetWidth-i-o.location.right,S=p.top+t.offsetHeight-i-o.location.bottom,H=new U.Vector2((m.clientX-f)/i*2-1,-((m.clientY-S)/i)*2+1);if(Math.abs(H.x)>1||Math.abs(H.y)>1)return null;o.quaternion.copy(r.quaternion).invert(),o.updateMatrixWorld(),l.setFromCamera(H,s);let g=l.intersectObjects(o.children,!1);for(let R of g){let b=_optionalChain([R, 'access', _5 => _5.object, 'access', _6 => _6.userData, 'optionalAccess', _7 => _7.type]);if(typeof b=="string"&&b in c)return b}return null};return{render:m=>{if(!a)return;let p=m.autoClear;m.autoClear=!1,o.render(m),m.autoClear=p},update:m=>{o.animating&&o.update(m)},handleClick:m=>{if(!a)return!1;let p=d(m);return p?(n.getProjection()==="orthographic"&&n.setProjection("perspective"),n.setViewDirection(c[p],!1),!0):!1},get isAnimating(){return o.animating},setVisible:m=>{a=m},isVisible:()=>a,dispose:()=>o.dispose()}}var _LineSegmentsGeometryjs = require('three/addons/lines/LineSegmentsGeometry.js');var _LineSegments2js = require('three/addons/lines/LineSegments2.js');var _LineMaterialjs = require('three/addons/lines/LineMaterial.js');var Q="edge-overlay",qe=2236962,Ze=1.5,Je=30;function fe(e,r={}){let t=new Z.Color(_nullishCoalesce(r.color, () => (qe))),n=_nullishCoalesce(r.width, () => (Ze)),o=_nullishCoalesce(r.thresholdAngle, () => (Je)),a=[];return e.traverse(i=>{if(!(i instanceof Z.Mesh)||i.userData.id==="floor"||i.userData.id==="grid"||i.userData.kind===Q||i.children.some(s=>_optionalChain([s, 'access', _8 => _8.userData, 'optionalAccess', _9 => _9.kind])===Q)||!i.geometry)return;let l=Ke(i.geometry,t,n,o);i.add(l),a.push(l)}),a}function Ke(e,r,t,n){let o=new Z.EdgesGeometry(e,n),a=new _LineSegmentsGeometryjs.LineSegmentsGeometry;a.setPositions(Array.from(o.attributes.position.array)),o.dispose();let i=new (0, _LineMaterialjs.LineMaterial)({color:r});i.linewidth=t,i.polygonOffset=!0,i.polygonOffsetFactor=-1,i.polygonOffsetUnits=-1;let l=new (0, _LineSegments2js.LineSegments2)(a,i);return l.userData.kind=Q,l.raycast=()=>{},l}function Qe(e){return _optionalChain([e, 'access', _10 => _10.userData, 'optionalAccess', _11 => _11.kind])===Q}function Nn(e){let r=[];e.traverse(t=>{t instanceof _LineSegments2js.LineSegments2&&Qe(t)&&r.push(t)});for(let t of r)t.geometry.dispose(),t.material.dispose(),t.removeFromParent();return r.length}var _EffectComposerjs = require('three/addons/postprocessing/EffectComposer.js');var _RenderPassjs = require('three/addons/postprocessing/RenderPass.js');var _GTAOPassjs = require('three/addons/postprocessing/GTAOPass.js');var _OutputPassjs = require('three/addons/postprocessing/OutputPass.js');function he(e,r,t,n,o,a){let i=new (0, _EffectComposerjs.EffectComposer)(e),l=new (0, _RenderPassjs.RenderPass)(r,t);i.addPass(l);let s=new (0, _GTAOPassjs.GTAOPass)(r,t,n,o);s.blendIntensity=_nullishCoalesce(a.aoIntensity, () => (1)),s.updateGtaoMaterial({screenSpaceRadius:!0}),i.addPass(s);let c=new _OutputPassjs.OutputPass;return i.addPass(c),e.toneMapping=a.toneMapping,e.toneMappingExposure=a.toneMappingExposure,i.setSize(n,o),{render:d=>i.render(d),setSize:(d,u,m)=>{i.setPixelRatio(m),i.setSize(d,u),s.setSize(d,u)},setCamera:d=>{l.camera=d,s.camera=d},dispose:()=>{i.dispose(),s.dispose(),c.dispose()}}}var _CSS2DRendererjs = require('three/addons/renderers/CSS2DRenderer.js');function ye(e,r){let t=new _CSS2DRendererjs.CSS2DRenderer,n=t.domElement;n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",n.style.overflow="hidden",n.style.pointerEvents="none",n.style.zIndex="30",getComputedStyle(e).position==="static"&&(e.style.position="relative"),e.appendChild(n);let o={width:e.clientWidth||1,height:e.clientHeight||1};t.setSize(o.width,o.height);let a=new ge.Group;a.name="label-layer",a.userData.id="label-layer",r.add(a);let i=new Set;return{addLabel:(s,c,d)=>{let u=document.createElement("div");u.textContent=s,d?u.className=d:Object.assign(u.style,{padding:"2px 6px",borderRadius:"4px",background:"rgba(20, 20, 20, 0.78)",color:"#fff",font:"12px/1.3 system-ui, sans-serif",whiteSpace:"pre",textAlign:"center",userSelect:"none"}),u.style.pointerEvents="none";let m=new (0, _CSS2DRendererjs.CSS2DObject)(u);return m.position.copy(c),a.add(m),i.add(m),{object:m,setPosition:p=>m.position.copy(p),setText:p=>{u.textContent=p},remove:()=>{m.removeFromParent(),u.remove(),i.delete(m)}}},render:(s,c)=>t.render(s,c),setSize:(s,c)=>t.setSize(s,c),dispose:()=>{i.forEach(s=>{s.removeFromParent(),s.element.remove()}),i.clear(),a.removeFromParent(),n.remove()}}}var _Line2js = require('three/addons/lines/Line2.js');var _LineGeometryjs = require('three/addons/lines/LineGeometry.js');var ct=12,ut=16763904,dt=.015,be={Millimeters:{metersPerUnit:1/1e3,suffix:"mm"},Centimeters:{metersPerUnit:1/100,suffix:"cm"},Meters:{metersPerUnit:1,suffix:"m"},Inches:{metersPerUnit:1/39.37,suffix:"in"},Feet:{metersPerUnit:1/3.28084,suffix:"ft"}};function mt(e){let r=e&&be[e]||be.Meters;return t=>`${(t/r.metersPerUnit).toPrecision(3)} ${r.suffix}`}function pt(e){let r=e.object;return r instanceof D.Mesh?e.face?[e.face.a,e.face.b,e.face.c]:null:r instanceof D.Points?e.index!=null?[e.index]:null:r instanceof D.Line&&e.index!=null?[e.index,e.index+1]:null}function Et(e,r,t,n){let o=e.point.clone(),a=e.object,i=pt(e);if(!i||!a.geometry)return o;let l=a.geometry.attributes.position;if(!l)return o;let s=m=>{let p=m.clone().project(r);return new D.Vector2((p.x+1)/2*t.width,(1-p.y)/2*t.height)},c=s(o),d=o,u=n;for(let m of i){if(m>=l.count)continue;let f=new D.Vector3().fromBufferAttribute(l,m).applyMatrix4(a.matrixWorld),S=s(f).distanceTo(c);S<u&&(u=S,d=f)}return d}function Re(e){let{canvas:r,scene:t,getActiveCamera:n,labelLayer:o,options:a={}}=e,i=_nullishCoalesce(a.snapPixels, () => (ct)),l=new D.Color(_nullishCoalesce(a.color, () => (ut))),s=mt(a.displayUnit),c=(h,v)=>`${s(h)}
54
+ \u0394x ${s(v.x)} \u0394y ${s(v.y)} \u0394z ${s(v.z)}`,d=_nullishCoalesce(a.format, () => (c)),u=new D.Raycaster,m=new D.Vector2,p=!1,f=[],S=[],H=null,g=null,R=new D.PointsMaterial({color:l,size:8,sizeAttenuation:!1,depthTest:!1}),b=new D.PointsMaterial({color:l,size:11,sizeAttenuation:!1,depthTest:!1,transparent:!0,opacity:.5}),T=null,P=h=>{if(!h){T&&(T.visible=!1);return}if(!T){let v=new D.BufferGeometry;v.setAttribute("position",new D.Float32BufferAttribute([0,0,0],3)),T=new D.Points(v,b),T.renderOrder=1e3,T.userData.id="measure",T.raycast=()=>{},t.add(T)}T.position.copy(h),T.visible=!0},y=h=>{let v=new D.BufferGeometry;v.setAttribute("position",new D.Float32BufferAttribute([h.x,h.y,h.z],3));let V=new D.Points(v,R);return V.renderOrder=999,V.userData.id="measure",V.raycast=()=>{},t.add(V),V},w=()=>{f.length=0,S.forEach(h=>{h.geometry.dispose(),h.removeFromParent()}),S.length=0,H&&(H.geometry.dispose(),H.material.dispose(),H.removeFromParent(),H=null),_optionalChain([g, 'optionalAccess', _12 => _12.remove, 'call', _13 => _13()]),g=null},C=()=>{if(f.length!==2)return;let[h,v]=f,V=new _LineGeometryjs.LineGeometry;V.setPositions([h.x,h.y,h.z,v.x,v.y,v.z]);let Y=new (0, _LineMaterialjs.LineMaterial)({color:l});Y.linewidth=2,Y.depthTest=!1,H=new (0, _Line2js.Line2)(V,Y),H.renderOrder=998,H.userData.id="measure",H.raycast=()=>{},t.add(H);let X=h.clone().add(v).multiplyScalar(.5),$=new D.Vector3(Math.abs(v.x-h.x),Math.abs(v.y-h.y),Math.abs(v.z-h.z));g=o.addLabel(d(h.distanceTo(v),$),X,a.labelClassName)},O=h=>{let v=r.getBoundingClientRect();m.x=(h.clientX-v.left)/v.width*2-1,m.y=-((h.clientY-v.top)/v.height)*2+1;let V=n();u.setFromCamera(m,V);let X=V.position.length()*dt;u.params.Line.threshold=X,u.params.Points.threshold=X;let $=u.intersectObjects(t.children,!0).filter(q=>q.object.userData.id!=="measure"&&q.object.userData.id!=="grid");return $.length===0?null:Et($[0],V,{width:v.width,height:v.height},i)};return{setEnabled:h=>{p=h,h||(w(),P(null))},isEnabled:()=>p,handleClick:h=>{if(!p)return!1;f.length===2&&w();let v=O(h);return v===null||(f.push(v),S.push(y(v)),f.length===2&&C()),!0},handleMove:h=>{p&&P(O(h))},clear:w,dispose:()=>{w(),T&&(T.geometry.dispose(),T.removeFromParent(),T=null),R.dispose(),b.dispose()}}}var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var ee=new E.Vector3(0,0,1);function gt(e){let r=Math.abs(e.x),t=Math.abs(e.y),n=Math.abs(e.z);return n>=r&&n>=t?"z":t>=r&&t>=n?"y":"x"}var pr=function(e,r){let t=yt(r||{}),n=_optionalChain([t, 'access', _14 => _14.environment, 'optionalAccess', _15 => _15.sceneUp])||ee,o=wt(t),a=St(t,e);a.up.copy(n);let i=At(e,t),l=Lt(a,e,t),s=de({scene:o,perspective:a,controls:l,onActiveCameraChange:()=>{},up:n}),c=()=>s.getActiveCamera();Mt(o,t);let d=xt(o,t),u=()=>{d&&Tt(d,oe(o))};_optionalChain([t, 'access', _16 => _16.floor, 'optionalAccess', _17 => _17.enabled])&&Ct(o,t);let m=t.grid.enabled?me({cellSize:t.grid.cellSize,majorEvery:t.grid.majorEvery,cellColor:t.grid.cellColor,majorColor:t.grid.majorColor,fadeDistance:t.grid.fadeDistance,plane:t.grid.plane}):null;m&&o.add(m.object);let p=t.gizmo.enabled?pe({camera:a,domElement:e,controller:s}):null,f=_nullishCoalesce(e.parentElement, () => (e)),S=t.measure.enabled?ye(f,o):null,H=t.measure.enabled&&S?Re({canvas:e,scene:o,getActiveCamera:c,labelLayer:S,options:{snapPixels:t.measure.snapPixels,color:t.measure.color,labelClassName:t.measure.labelClassName,displayUnit:t.measure.displayUnit,format:t.measure.format}}):null,g=t.events.enableEventHandlers!==!1?Dt(e,o,c,a,l,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},R=5,b=0,T=0,P=M=>{b=M.clientX,T=M.clientY},y=M=>Math.hypot(M.clientX-b,M.clientY-T)>R,w=M=>{if(!y(M)){if(_optionalChain([H, 'optionalAccess', _18 => _18.handleClick, 'call', _19 => _19(M)])){M.stopImmediatePropagation();return}_optionalChain([p, 'optionalAccess', _20 => _20.handleClick, 'call', _21 => _21(M)])&&M.stopImmediatePropagation()}};(p||H)&&(e.addEventListener("mousedown",P,{capture:!0}),e.addEventListener("click",w,{capture:!0}));let C=M=>_optionalChain([H, 'optionalAccess', _22 => _22.handleMove, 'call', _23 => _23(M)]);H&&e.addEventListener("mousemove",C,{passive:!0});let O=M=>{fe(M,{color:t.edges.color,width:t.edges.width,thresholdAngle:t.edges.thresholdAngle})},A=e.parentElement,j=()=>A?{width:A.clientWidth,height:A.clientHeight}:{width:window.innerWidth,height:window.innerHeight},h=null,v=()=>{let{width:M,height:B}=j(),N=Math.min(window.devicePixelRatio,2),K=he(i,o,c(),Math.max(1,M),Math.max(1,B),{toneMapping:_nullishCoalesce(t.render.toneMapping, () => (E.NeutralToneMapping)),toneMappingExposure:_nullishCoalesce(t.render.toneMappingExposure, () => (1)),aoIntensity:t.render.aoIntensity});return K.setSize(Math.max(1,M),Math.max(1,B),N),K},V=M=>{M&&!h?h=v():!M&&h&&(h.dispose(),h=null)};t.render.ambientOcclusion&&(h=v());let{animate:Y,dispose:X}=vt(i,o,a,c,s,l,j,t.events.onFrame,m,p,()=>h,S);Y(),o.up.set(n.x,n.y,n.z),u();let $=M=>{M.traverse(B=>{let N=B;!N.geometry&&!N.material||(_optionalChain([N, 'access', _24 => _24.geometry, 'optionalAccess', _25 => _25.dispose, 'call', _26 => _26()]),Array.isArray(N.material)?N.material.forEach(K=>K.dispose()):_optionalChain([N, 'access', _27 => _27.material, 'optionalAccess', _28 => _28.dispose, 'call', _29 => _29()]))})},q=M=>{M.userData.source="user",o.add(M)},Pe=M=>{M.removeFromParent(),$(M)},Oe=()=>{o.children.filter(B=>B.userData.source==="user").forEach(B=>{B.removeFromParent(),$(B)})};return{scene:o,camera:a,controls:l,renderer:i,cameraController:s,grid:m,gizmo:p,measureTool:H,applyEdges:O,setAmbientOcclusion:V,updateShadowBounds:u,dispose:()=>{X(),g.dispose(),(p||H)&&(e.removeEventListener("mousedown",P,{capture:!0}),e.removeEventListener("click",w,{capture:!0})),H&&e.removeEventListener("mousemove",C),_optionalChain([H, 'optionalAccess', _30 => _30.dispose, 'call', _31 => _31()]),_optionalChain([S, 'optionalAccess', _32 => _32.dispose, 'call', _33 => _33()]),_optionalChain([p, 'optionalAccess', _34 => _34.dispose, 'call', _35 => _35()]),_optionalChain([m, 'optionalAccess', _36 => _36.dispose, 'call', _37 => _37()]),_optionalChain([h, 'optionalAccess', _38 => _38.dispose, 'call', _39 => _39()]),l.dispose(),i.dispose(),o.traverse(M=>{let B=M;!B.geometry&&!B.material||(_optionalChain([B, 'access', _40 => _40.geometry, 'optionalAccess', _41 => _41.dispose, 'call', _42 => _42()]),Array.isArray(B.material)?B.material.forEach(N=>N.dispose()):_optionalChain([B, 'access', _43 => _43.material, 'optionalAccess', _44 => _44.dispose, 'call', _45 => _45()]))}),_optionalChain([o, 'access', _46 => _46.environment, 'optionalAccess', _47 => _47.dispose, 'call', _48 => _48()]),o.background instanceof E.Texture&&o.background.dispose()},fitToView:g.fitToView,clearSelection:g.clearSelection,addUserGeometry:q,removeUserGeometry:Pe,clearUserGeometry:Oe}};function yt(e){let r=e.sceneScale||"m",n={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[r];return{sceneScale:r,camera:{position:_optionalChain([e, 'access', _49 => _49.camera, 'optionalAccess', _50 => _50.position])||new E.Vector3(-n.cameraDistance,-n.cameraDistance,n.cameraDistance),fov:_optionalChain([e, 'access', _51 => _51.camera, 'optionalAccess', _52 => _52.fov])||20,near:_optionalChain([e, 'access', _53 => _53.camera, 'optionalAccess', _54 => _54.near])||n.near,far:_optionalChain([e, 'access', _55 => _55.camera, 'optionalAccess', _56 => _56.far])||n.far,target:_optionalChain([e, 'access', _57 => _57.camera, 'optionalAccess', _58 => _58.target])||new E.Vector3(0,0,0)},lighting:{enableSunlight:_nullishCoalesce(_optionalChain([e, 'access', _59 => _59.lighting, 'optionalAccess', _60 => _60.enableSunlight]), () => (!0)),sunlightIntensity:_nullishCoalesce(_optionalChain([e, 'access', _61 => _61.lighting, 'optionalAccess', _62 => _62.sunlightIntensity]), () => (1)),sunlightPosition:_optionalChain([e, 'access', _63 => _63.lighting, 'optionalAccess', _64 => _64.sunlightPosition])||new E.Vector3(n.lightDistance,n.lightDistance,n.lightHeight),ambientLightColor:_optionalChain([e, 'access', _65 => _65.lighting, 'optionalAccess', _66 => _66.ambientLightColor])||new E.Color(4210752),ambientLightIntensity:_nullishCoalesce(_optionalChain([e, 'access', _67 => _67.lighting, 'optionalAccess', _68 => _68.ambientLightIntensity]), () => (1)),sunlightColor:_optionalChain([e, 'access', _69 => _69.lighting, 'optionalAccess', _70 => _70.sunlightColor])||16777215},environment:{hdrPath:_optionalChain([e, 'access', _71 => _71.environment, 'optionalAccess', _72 => _72.hdrPath])||"/baseHDR.hdr",backgroundColor:_optionalChain([e, 'access', _73 => _73.environment, 'optionalAccess', _74 => _74.backgroundColor])||new E.Color(15790320),enableEnvironmentLighting:_nullishCoalesce(_optionalChain([e, 'access', _75 => _75.environment, 'optionalAccess', _76 => _76.enableEnvironmentLighting]), () => (!0)),sceneUp:_optionalChain([e, 'access', _77 => _77.environment, 'optionalAccess', _78 => _78.sceneUp])||ee,showEnvironment:_nullishCoalesce(_optionalChain([e, 'access', _79 => _79.environment, 'optionalAccess', _80 => _80.showEnvironment]), () => (!1))},floor:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _81 => _81.floor, 'optionalAccess', _82 => _82.enabled]), () => (!1)),size:_optionalChain([e, 'access', _83 => _83.floor, 'optionalAccess', _84 => _84.size])||n.floorSize,color:_optionalChain([e, 'access', _85 => _85.floor, 'optionalAccess', _86 => _86.color])||new E.Color(8421504),roughness:_nullishCoalesce(_optionalChain([e, 'access', _87 => _87.floor, 'optionalAccess', _88 => _88.roughness]), () => (.7)),metalness:_nullishCoalesce(_optionalChain([e, 'access', _89 => _89.floor, 'optionalAccess', _90 => _90.metalness]), () => (0)),receiveShadow:_nullishCoalesce(_optionalChain([e, 'access', _91 => _91.floor, 'optionalAccess', _92 => _92.receiveShadow]), () => (!0))},render:{enableShadows:_nullishCoalesce(_optionalChain([e, 'access', _93 => _93.render, 'optionalAccess', _94 => _94.enableShadows]), () => (!0)),shadowMapSize:_optionalChain([e, 'access', _95 => _95.render, 'optionalAccess', _96 => _96.shadowMapSize])||2048,antialias:_nullishCoalesce(_optionalChain([e, 'access', _97 => _97.render, 'optionalAccess', _98 => _98.antialias]), () => (!0)),pixelRatio:_optionalChain([e, 'access', _99 => _99.render, 'optionalAccess', _100 => _100.pixelRatio])||Math.min(window.devicePixelRatio,2),toneMapping:_optionalChain([e, 'access', _101 => _101.render, 'optionalAccess', _102 => _102.toneMapping])||E.NeutralToneMapping,toneMappingExposure:_nullishCoalesce(_optionalChain([e, 'access', _103 => _103.render, 'optionalAccess', _104 => _104.toneMappingExposure]), () => (1)),preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _105 => _105.render, 'optionalAccess', _106 => _106.preserveDrawingBuffer]), () => (!1)),ambientOcclusion:_nullishCoalesce(_optionalChain([e, 'access', _107 => _107.render, 'optionalAccess', _108 => _108.ambientOcclusion]), () => (!1)),aoIntensity:_nullishCoalesce(_optionalChain([e, 'access', _109 => _109.render, 'optionalAccess', _110 => _110.aoIntensity]), () => (1))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _111 => _111.controls, 'optionalAccess', _112 => _112.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _113 => _113.controls, 'optionalAccess', _114 => _114.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _115 => _115.controls, 'optionalAccess', _116 => _116.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _117 => _117.controls, 'optionalAccess', _118 => _118.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _119 => _119.controls, 'optionalAccess', _120 => _120.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _121 => _121.controls, 'optionalAccess', _122 => _122.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _123 => _123.controls, 'optionalAccess', _124 => _124.minDistance])||n.minDistance,maxDistance:_optionalChain([e, 'access', _125 => _125.controls, 'optionalAccess', _126 => _126.maxDistance])||1/0},grid:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _127 => _127.grid, 'optionalAccess', _128 => _128.enabled]), () => (!1)),cellSize:_nullishCoalesce(_optionalChain([e, 'access', _129 => _129.grid, 'optionalAccess', _130 => _130.cellSize]), () => (1)),majorEvery:_nullishCoalesce(_optionalChain([e, 'access', _131 => _131.grid, 'optionalAccess', _132 => _132.majorEvery]), () => (10)),cellColor:_nullishCoalesce(_optionalChain([e, 'access', _133 => _133.grid, 'optionalAccess', _134 => _134.cellColor]), () => (8947848)),majorColor:_nullishCoalesce(_optionalChain([e, 'access', _135 => _135.grid, 'optionalAccess', _136 => _136.majorColor]), () => (4473924)),fadeDistance:_nullishCoalesce(_optionalChain([e, 'access', _137 => _137.grid, 'optionalAccess', _138 => _138.fadeDistance]), () => (100)),plane:_nullishCoalesce(_optionalChain([e, 'access', _139 => _139.grid, 'optionalAccess', _140 => _140.plane]), () => (gt(_nullishCoalesce(_optionalChain([e, 'access', _141 => _141.environment, 'optionalAccess', _142 => _142.sceneUp]), () => (ee)))))},gizmo:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _143 => _143.gizmo, 'optionalAccess', _144 => _144.enabled]), () => (!1))},edges:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _145 => _145.edges, 'optionalAccess', _146 => _146.enabled]), () => (!1)),color:_nullishCoalesce(_optionalChain([e, 'access', _147 => _147.edges, 'optionalAccess', _148 => _148.color]), () => (2236962)),width:_nullishCoalesce(_optionalChain([e, 'access', _149 => _149.edges, 'optionalAccess', _150 => _150.width]), () => (1.5)),thresholdAngle:_nullishCoalesce(_optionalChain([e, 'access', _151 => _151.edges, 'optionalAccess', _152 => _152.thresholdAngle]), () => (30))},measure:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _153 => _153.measure, 'optionalAccess', _154 => _154.enabled]), () => (!1)),snapPixels:_optionalChain([e, 'access', _155 => _155.measure, 'optionalAccess', _156 => _156.snapPixels]),color:_optionalChain([e, 'access', _157 => _157.measure, 'optionalAccess', _158 => _158.color]),labelClassName:_optionalChain([e, 'access', _159 => _159.measure, 'optionalAccess', _160 => _160.labelClassName]),displayUnit:_optionalChain([e, 'access', _161 => _161.measure, 'optionalAccess', _162 => _162.displayUnit]),format:_optionalChain([e, 'access', _163 => _163.measure, 'optionalAccess', _164 => _164.format])},events:{onBackgroundClicked:_optionalChain([e, 'access', _165 => _165.events, 'optionalAccess', _166 => _166.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _167 => _167.events, 'optionalAccess', _168 => _168.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _169 => _169.events, 'optionalAccess', _170 => _170.onMeshMetadataClicked]),onMeshDoubleClicked:_optionalChain([e, 'access', _171 => _171.events, 'optionalAccess', _172 => _172.onMeshDoubleClicked]),selectionColor:_optionalChain([e, 'access', _173 => _173.events, 'optionalAccess', _174 => _174.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _175 => _175.events, 'optionalAccess', _176 => _176.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _177 => _177.events, 'optionalAccess', _178 => _178.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _179 => _179.events, 'optionalAccess', _180 => _180.enableClickToFocus]), () => (!0)),enableDoubleClickZoom:_nullishCoalesce(_optionalChain([e, 'access', _181 => _181.events, 'optionalAccess', _182 => _182.enableDoubleClickZoom]), () => (!0)),onReady:_optionalChain([e, 'access', _183 => _183.events, 'optionalAccess', _184 => _184.onReady]),onFrame:_optionalChain([e, 'access', _185 => _185.events, 'optionalAccess', _186 => _186.onFrame])}}}var bt=new Set(["grid","floor","label-layer","measure"]);function Rt(e){let r=e;for(;r;){if(typeof r.userData.id=="string"&&bt.has(r.userData.id))return!0;r=r.parent}return!1}function oe(e){let r=new E.Box3;return e.traverse(t=>{let n=t;t.visible&&!Rt(t)&&n.geometry&&r.expandByObject(t)}),r}function Tt(e,r){if(r.isEmpty())return;let t=r.getCenter(new E.Vector3),n=r.getSize(new E.Vector3).length()*.5*1.2,o=e.shadow.camera;o.left=-n,o.right=n,o.top=n,o.bottom=-n,e.target.position.copy(t),e.target.updateMatrixWorld();let a=e.position.distanceTo(t);o.near=Math.max(n*.01,a-n),o.far=a+n,o.updateProjectionMatrix()}function wt(e){let r=new E.Scene,t=typeof e.environment.backgroundColor=="string"?new E.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=t||null,r}function Ht(e,r,t,n,o=200){let a=e.position.clone(),i=r.target.clone(),l=performance.now(),s=d=>1-Math.pow(1-d,3),c=()=>{let d=performance.now()-l,u=s(Math.min(d/o,1));e.position.lerpVectors(a,t,u),r.target.lerpVectors(i,n,u),r.update(),u<1&&requestAnimationFrame(c)};requestAnimationFrame(c)}function vt(e,r,t,n,o,a,i,l,s,c,d,u){let m=null,p=performance.now(),f=()=>{let{width:g,height:R}=i();if(g===0||R===0)return;let b=Math.min(window.devicePixelRatio,2),T=Math.round(g*b),P=Math.round(R*b);(e.domElement.width!==T||e.domElement.height!==P)&&(e.setPixelRatio(b),e.setSize(g,R,!1),t.aspect=g/R,t.updateProjectionMatrix(),o.updateAspect(g,R),_optionalChain([d, 'optionalCall', _187 => _187(), 'optionalAccess', _188 => _188.setSize, 'call', _189 => _189(g,R,b)]),_optionalChain([u, 'optionalAccess', _190 => _190.setSize, 'call', _191 => _191(g,R)]))},S=function(){m=requestAnimationFrame(S);let g=performance.now(),R=(g-p)/1e3;p=g,f(),(a.enableDamping||a.autoRotate)&&a.update(),s&&s.update(n().position),c&&c.update(R),_optionalChain([l, 'optionalCall', _192 => _192(R)]);let b=n(),T=_optionalChain([d, 'optionalCall', _193 => _193()]);T?(T.setCamera(b),T.render(R)):e.render(r,b),u&&u.render(r,b),c&&c.render(e)};return{animate:S,dispose:()=>{m!==null&&(cancelAnimationFrame(m),m=null)}}}function Mt(e,r){r.environment.enableEnvironmentLighting?new (0, _HDRLoaderjs.HDRLoader)().load(r.environment.hdrPath||"/baseHDR.hdr",function(t){if(!_optionalChain([t, 'optionalAccess', _194 => _194.image])){_chunk6LCAIDQVcjs.e.call(void 0, ).warn("HDR loaded without image data; skipping environment map."),_optionalChain([r, 'access', _195 => _195.events, 'access', _196 => _196.onReady, 'optionalCall', _197 => _197()]);return}t.mapping=E.EquirectangularReflectionMapping,e.environment=t,r.environment.showEnvironment&&(e.background=t),_optionalChain([r, 'access', _198 => _198.events, 'access', _199 => _199.onReady, 'optionalCall', _200 => _200()])},void 0,function(t){_chunk6LCAIDQVcjs.e.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",t),_optionalChain([r, 'access', _201 => _201.events, 'access', _202 => _202.onReady, 'optionalCall', _203 => _203()])}):_optionalChain([r, 'access', _204 => _204.events, 'access', _205 => _205.onReady, 'optionalCall', _206 => _206()])}function xt(e,r){let t=new E.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(t),!r.lighting.enableSunlight)return null;let n=new E.DirectionalLight(_nullishCoalesce(r.lighting.sunlightColor, () => (16777215)),r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;return o&&n.position.set(o.x,o.y,o.z),r.render.enableShadows?(n.castShadow=!0,n.shadow.mapSize.width=r.render.shadowMapSize||2048,n.shadow.mapSize.height=r.render.shadowMapSize||2048,n.shadow.bias=-1e-4,n.shadow.normalBias=.02,n.shadow.radius=4,e.add(n),e.add(n.target),n):(e.add(n),null)}function Ct(e,r){let t=r.floor.size,n=new E.PlaneGeometry(t,t),o=typeof r.floor.color=="string"?new E.Color(r.floor.color):r.floor.color,a=new E.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:E.DoubleSide}),i=new E.Mesh(n,a);i.userData.id="floor",i.name="floor";let l=(_optionalChain([r, 'access', _207 => _207.environment, 'optionalAccess', _208 => _208.sceneUp])||ee).clone().normalize();i.quaternion.setFromUnitVectors(new E.Vector3(0,0,1),l),i.position.set(0,0,0),r.floor.receiveShadow&&r.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function St(e,r){let t=r.parentElement,n=t?t.clientWidth:window.innerWidth,o=t?t.clientHeight:window.innerHeight,a=new E.PerspectiveCamera(e.camera.fov,n/o,e.camera.near,e.camera.far),i=e.camera.position;return i&&a.position.set(i.x,i.y,i.z),a}function At(e,r){let t=new E.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),n=e.parentElement,o=n?n.clientWidth:window.innerWidth,a=n?n.clientHeight:window.innerHeight;return n&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),t.setSize(o,a,!1),t.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(t.shadowMap.enabled=!0,t.shadowMap.type=E.VSMShadowMap),t.toneMapping=r.render.toneMapping,t.toneMappingExposure=_nullishCoalesce(r.render.toneMappingExposure, () => (1)),t.outputColorSpace=E.SRGBColorSpace,t.sortObjects=!0,t}function Dt(e,r,t,n,o,a){let i=new Set,l=new Map,s=new E.Raycaster,c=new E.Vector2,d=new E.Vector2,u=y=>{let w=y;for(;w;){if(!w.visible)return!1;w=w.parent}return!0},m=()=>{let y=oe(r);if(y.isEmpty()){_chunk6LCAIDQVcjs.e.call(void 0, ).warn("No objects to fit to view");return}let w=y.getCenter(new E.Vector3),C=y.getSize(new E.Vector3),O=Math.max(C.x,C.y,C.z),A=n.fov*(Math.PI/180),j=O/(2*Math.tan(A/2));j*=1.5;let h=n.position.clone().sub(o.target);h.lengthSq()<1e-12&&h.set(.8,1,1.2),h.normalize(),n.position.copy(w.clone().add(h.multiplyScalar(j))),o.target.copy(w),o.update()},p=typeof a.events.selectionColor=="string"?new E.Color(a.events.selectionColor):a.events.selectionColor instanceof E.Color?a.events.selectionColor:new E.Color("#ff0000"),f=()=>{i.forEach(y=>{let w=y;if(l.has(y)){let C=l.get(y),O=w.material;O instanceof E.Material?O.dispose():Array.isArray(O)&&O.forEach(A=>A.dispose()),w.material=C,l.delete(y)}}),i.clear()},S=y=>{let w=y;if(!(w.material instanceof E.Material))return!1;l.set(y,w.material);let C=w.material.clone();return y instanceof E.Mesh&&"emissive"in C?C.emissive=p.clone():"color"in C&&(C.color=p.clone()),w.material=C,!0},H=()=>{let y=oe(r),w=y.isEmpty()?1:y.getSize(new E.Vector3).length();s.params.Points.threshold=w*.01},g=y=>{d.set(y.clientX,y.clientY)},R=y=>{let w=new E.Vector2(y.clientX,y.clientY);if(d.distanceTo(w)>5)return;let C=e.getBoundingClientRect();c.x=(y.clientX-C.left)/C.width*2-1,c.y=-((y.clientY-C.top)/C.height)*2+1,H(),s.setFromCamera(c,t());let O=s.intersectObjects(r.children,!0).filter(A=>u(A.object));if(O.length>0){let A=O[0].object;i.has(A)||(f(),i.add(A),S(A),_optionalChain([a, 'access', _209 => _209.events, 'optionalAccess', _210 => _210.onObjectSelected, 'optionalCall', _211 => _211(A)]),A instanceof E.Mesh&&Object.keys(A.userData).length>0&&_optionalChain([a, 'access', _212 => _212.events, 'optionalAccess', _213 => _213.onMeshMetadataClicked, 'optionalCall', _214 => _214(A.userData)]))}else f(),_optionalChain([a, 'access', _215 => _215.events, 'optionalAccess', _216 => _216.onBackgroundClicked, 'optionalCall', _217 => _217({x:c.x,y:c.y})])},b=y=>{let w=e.getBoundingClientRect();c.x=(y.clientX-w.left)/w.width*2-1,c.y=-((y.clientY-w.top)/w.height)*2+1,H(),s.setFromCamera(c,t());let C=s.intersectObjects(r.children,!0).filter(q=>u(q.object));if(C.length===0)return;let O=C[0].object;if(_optionalChain([a, 'access', _218 => _218.events, 'optionalAccess', _219 => _219.onMeshDoubleClicked, 'optionalCall', _220 => _220(O)]),!_optionalChain([a, 'access', _221 => _221.events, 'optionalAccess', _222 => _222.enableDoubleClickZoom]))return;let A=new E.Box3().setFromObject(O);if(A.isEmpty())return;let j=A.getCenter(new E.Vector3),h=A.getSize(new E.Vector3),v=Math.max(h.x,h.y,h.z),V=n.fov*(Math.PI/180),Y=v/(2*Math.tan(V/2))*1.5,X=n.position.clone().sub(o.target).normalize(),$=j.clone().add(X.multiplyScalar(Y));Ht(n,o,$,j)},T=y=>{if(_optionalChain([a, 'access', _223 => _223.events, 'optionalAccess', _224 => _224.enableKeyboardControls]))switch(y.key.toLowerCase()){case"f":y.preventDefault(),m();break;case"escape":y.preventDefault(),f();break;case" ":y.preventDefault(),m();break}};return _optionalChain([a, 'access', _225 => _225.events, 'optionalAccess', _226 => _226.enableClickToFocus])&&(e.addEventListener("mousedown",g),e.addEventListener("click",R),e.addEventListener("dblclick",b)),_optionalChain([a, 'access', _227 => _227.events, 'optionalAccess', _228 => _228.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",T)),{dispose:()=>{e.removeEventListener("mousedown",g),e.removeEventListener("click",R),e.removeEventListener("dblclick",b),e.removeEventListener("keydown",T),f()},fitToView:m,clearSelection:f}}function Lt(e,r,t){let n=new (0, _OrbitControlsjs.OrbitControls)(e,r),o=t.camera.target;return o&&n.target.set(o.x,o.y,o.z),n.enableDamping=t.controls.enableDamping||!1,n.dampingFactor=t.controls.dampingFactor||.05,n.autoRotate=t.controls.autoRotate||!1,n.autoRotateSpeed=t.controls.autoRotateSpeed||.5,n.enableZoom=_nullishCoalesce(t.controls.enableZoom, () => (!0)),n.enablePan=_nullishCoalesce(t.controls.enablePan, () => (!0)),n.minDistance=t.controls.minDistance||.001,n.maxDistance=t.controls.maxDistance||1/0,n.screenSpacePanning=!1,n.maxPolarAngle=Math.PI,n.update(),n}var jt={};_chunk6LCAIDQVcjs.a.call(void 0, jt,{CONCRETE_MATERIAL:()=>It,EMISSIVE_MATERIAL:()=>Pt,GLASS_MATERIAL:()=>Bt,METAL_MATERIAL:()=>Ot,PLASTIC_MATERIAL:()=>Vt,RUBBER_MATERIAL:()=>zt,WOOD_MATERIAL:()=>Ft});var Pt=new L.MeshPhysicalMaterial({color:0,emissive:new L.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:L.FrontSide,dithering:!0}),Ot=new L.MeshPhysicalMaterial({color:new L.Color(0),metalness:.9,roughness:.3,envMapIntensity:1.2,clearcoat:.3,clearcoatRoughness:.2,reflectivity:1,ior:2.5,thickness:1,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,side:L.FrontSide,dithering:!0}),It=new L.MeshPhysicalMaterial({color:new L.Color(13421772),metalness:0,roughness:.92,envMapIntensity:.15,clearcoat:.05,clearcoatRoughness:.9,reflectivity:.15,transmission:0,ior:1.45,thickness:0,depthWrite:!0,transparent:!1,alphaTest:.5,depthTest:!0,polygonOffset:!0,side:L.FrontSide,dithering:!0}),Vt=new L.MeshPhysicalMaterial({color:new L.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:L.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Bt=new L.MeshPhysicalMaterial({color:new L.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,opacity:.3,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:L.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),zt=new L.MeshPhysicalMaterial({color:new L.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:L.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Ft=new L.MeshPhysicalMaterial({color:new L.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:L.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});function te(e,r,t,n=!0){return{x:e,y:r,z:t}}var Gt="#ffffff",Te=12,Nt=4e-4,Wt=12,$t=.05;function we(e,r={}){if(!e||e.length===0)return[];let{rhino:t,applyTransforms:n=!0}=r,o=[];for(let a of e)switch(a.kind){case"curve":{let i=Xt(a,t,n);i&&o.push(i);break}case"point":{o.push(qt(a,n));break}default:{let i=a;_chunk6LCAIDQVcjs.e.call(void 0, ).warn(`Skipping unknown display item kind: ${String(i.kind)}`);break}}return o}var Yt=2;function Xt(e,r,t){if(!r)return _chunk6LCAIDQVcjs.e.call(void 0, ).warn("No rhino3dm instance provided; skipping curve display item."),null;let n=Zt(e.json,r);if(!n)return null;let o=Jt(n,t);if(o.length<2)return null;let a=[];for(let u of o)a.push(u.x,u.y,u.z);let i=new _LineGeometryjs.LineGeometry;i.setPositions(a);let l=He(e.color,e.opacity),s=new (0, _LineMaterialjs.LineMaterial)({color:l.color}),c=s;c.linewidth=_nullishCoalesce(e.width, () => (Yt)),c.transparent=l.transparent,c.opacity=l.opacity;let d=new (0, _Line2js.Line2)(i,s);return d.computeLineDistances(),d.name=e.name,d.userData={source:"compute",id:e.id,layer:e.layer,kind:"curve",metadata:e.metadata},d}function qt(e,r){let{x:t,y:n,z:o}=te(e.position.X,e.position.Y,e.position.Z,r),a=new _.BufferGeometry;a.setAttribute("position",new _.Float32BufferAttribute([t,n,o],3));let i=new _.PointsMaterial({...He(e.color,e.opacity),size:6,sizeAttenuation:!1}),l=new _.Points(a,i);return l.name=e.name,l.userData={source:"compute",id:e.id,layer:e.layer,kind:"point",metadata:e.metadata},l}function Zt(e,r){try{let t=JSON.parse(e),n=r.CommonObject.decode(t);return n&&typeof n.pointAt=="function"?n:(_chunk6LCAIDQVcjs.e.call(void 0, ).warn("Decoded display-item JSON is not a curve; skipping."),null)}catch(t){return _chunk6LCAIDQVcjs.e.call(void 0, ).warn("Failed to decode curve display item JSON:",t),null}}function Jt(e,r){let t=Kt(e,r);return t||Qt(e,r)}function Kt(e,r){if(!e.isPolyline())return null;let t=e.tryGetPolyline(),n=Array.isArray(t)?t[1]:t;if(!n||typeof n.count!="number"||n.count<2)return null;let o=[];for(let a=0;a<n.count;a++){let i=n.get(a),{x:l,y:s,z:c}=te(i[0],i[1],i[2],r);o.push(new _.Vector3(l,s,c))}return o}function Qt(e,r){let t=e.domain,n=t[0],a=t[1]-n,i=u=>{let m=e.pointAt(u),{x:p,y:f,z:S}=te(m[0],m[1],m[2],r);return new _.Vector3(p,f,S)},l=en(e),s=n,c=i(n),d=[c];for(let u=0;u<Te;u++){let m=n+a*(u+1)/Te,p=i(m);ae(s,c,m,p,i,l,Wt,d),d.push(p),s=m,c=p}return d}function ae(e,r,t,n,o,a,i,l){if(i<=0)return;let s=(e+t)/2,c=o(s),d=nn(c,r,n),u=tn(r,c,n);d<=a&&u<=$t||(ae(e,r,s,c,o,a,i-1,l),l.push(c),ae(s,c,t,n,o,a,i-1,l))}function en(e){let r=e.getBoundingBox(),t=r.min,n=r.max,o=Math.hypot(n[0]-t[0],n[1]-t[1],n[2]-t[2]);return Math.max(o*Nt,1e-6)}function tn(e,r,t){let n=r.clone().sub(e),o=t.clone().sub(r),a=n.length(),i=o.length();if(a===0||i===0)return 0;let l=Math.max(-1,Math.min(1,n.dot(o)/(a*i)));return Math.acos(l)}function nn(e,r,t){let n=t.clone().sub(r),o=n.lengthSq();if(o===0)return e.distanceTo(r);let a=Math.max(0,Math.min(1,e.clone().sub(r).dot(n)/o)),i=r.clone().addScaledVector(n,a);return e.distanceTo(i)}function He(e,r){let t=_nullishCoalesce(r, () => (1));return{color:new _.Color(_nullishCoalesce(e, () => (Gt))),transparent:t<1,opacity:t}}var _fflate = require('fflate');var ve=1096174675,on=1515605075,Me= exports.t =2,xe=1,ie= exports.u =1,an=2,Ce=12,Se=56;function se(e){let r=ln(sn(e)),t=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.byteLength<Ce)throw G("Blob too small to contain SLVA header.",{expectedBytes:Ce,availableBytes:r.byteLength});let n=0,o=t.getUint32(n,!0);if(n+=4,o!==ve)throw G(`Invalid SLVA magic: 0x${o.toString(16)}`,{expectedMagic:`0x${ve.toString(16)}`,actualMagic:`0x${o.toString(16)}`});let a=t.getUint32(n,!0);if(n+=4,a<xe||a>Me)throw G(`Unsupported SLVA version: ${a}`,{minSupportedVersion:xe,maxSupportedVersion:Me,actualVersion:a});let i=t.getUint32(n,!0);if(n+=4,n+i>r.byteLength)throw G("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:r.byteLength-n,offset:n});let l=r.subarray(n,n+i);n+=i;let s;try{s=JSON.parse(cn(l))}catch(h){throw G(`Failed to parse metadata JSON: ${h instanceof Error?h.message:String(h)}`,{metadataLen:i})}if(n+Se>r.byteLength)throw G("Insufficient data to read geometry header.",{expectedBytes:Se,availableBytes:r.byteLength-n,offset:n});let c=t.getUint32(n,!0);n+=4;let d=t.getFloat64(n,!0);n+=8;let u=t.getFloat64(n,!0);n+=8;let m=t.getFloat64(n,!0);n+=8;let p=t.getFloat64(n,!0);n+=8;let f=t.getFloat64(n,!0);n+=8;let S=t.getFloat64(n,!0);n+=8;let H=t.getUint32(n,!0);n+=4;let g=(c&ie)!==0,R=H*3,T=R*(g?4:2);if(n+T>r.byteLength)throw G("Insufficient data to read vertices.",{expectedBytes:T,availableBytes:r.byteLength-n,offset:n,useFloat32:g,vertexCount:H});let P=r.byteOffset+n,y=g?dn(r.buffer,P,R):un(r.buffer,P,R);if(n+=T,n+4>r.byteLength)throw G("Insufficient data to read index count.",{expectedBytes:4,availableBytes:r.byteLength-n,offset:n});let w=t.getUint32(n,!0);n+=4;let C=(c&an)!==0,A=w*(C?2:4);if(n+A>r.byteLength)throw G("Insufficient data to read indices.",{expectedBytes:A,availableBytes:r.byteLength-n,offset:n,indexCount:w,useUint16Indices:C});let j=C?mn(r.buffer,r.byteOffset+n,w):pn(r.buffer,r.byteOffset+n,w);return{metadata:s,flags:c,vertices:y,indices:j,origin:[d,u,m],scale:[p,f,S]}}function sn(e){return typeof e=="string"?_chunk6LCAIDQVcjs.o.call(void 0, e):e instanceof Uint8Array?e:new Uint8Array(e)}function ln(e){if(e.byteLength<8)return e;let r=new DataView(e.buffer,e.byteOffset,e.byteLength);if(r.getUint32(0,!0)!==on)return e;let t=r.getUint32(4,!0),n=e.subarray(8),o=Math.max(n.byteLength*1032+1024,1<<20);if(t>o)throw G("SLVZ header declares an implausible uncompressed length",{uncompressedLen:t,deflatedBytes:n.byteLength,maxPlausibleLen:o});try{return _fflate.inflateSync.call(void 0, n,{out:new Uint8Array(t)})}catch(a){throw G(`Failed to inflate SLVZ blob: ${a instanceof Error?a.message:String(a)}`,{uncompressedLen:t,deflatedBytes:n.byteLength})}}function cn(e){if(typeof TextDecoder<"u")return new TextDecoder("utf-8").decode(e);if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(e).toString("utf-8");throw new (0, _chunk6LCAIDQVcjs.d)("No UTF-8 decoder available in this environment.",_chunk6LCAIDQVcjs.c.INVALID_STATE)}function un(e,r,t){if(t===0)return new Int16Array(0);if(r%2===0)return new Int16Array(e,r,t);let n=new Uint8Array(t*2);return n.set(new Uint8Array(e,r,t*2)),new Int16Array(n.buffer)}function dn(e,r,t){if(t===0)return new Float32Array(0);if(r%4===0)return new Float32Array(e,r,t);let n=new Uint8Array(t*4);return n.set(new Uint8Array(e,r,t*4)),new Float32Array(n.buffer)}function mn(e,r,t){if(t===0)return new Uint16Array(0);if(r%2===0)return new Uint16Array(e,r,t);let n=new Uint8Array(t*2);return n.set(new Uint8Array(e,r,t*2)),new Uint16Array(n.buffer)}function pn(e,r,t){if(t===0)return new Uint32Array(0);if(r%4===0)return new Uint32Array(e,r,t);let n=new Uint8Array(t*4);return n.set(new Uint8Array(e,r,t*4)),new Uint32Array(n.buffer)}function G(e,r){return new (0, _chunk6LCAIDQVcjs.d)(e,_chunk6LCAIDQVcjs.c.VALIDATION_ERROR,{context:r})}async function De(e,r){let{debug:t=!1}=_nullishCoalesce(r, () => ({})),n=t?performance.now():0;try{let o=performance.now(),a=JSON.parse(e),i=performance.now()-o;return await En(a,r,{parseTime:i,perfStart:n})}catch(o){return _chunk6LCAIDQVcjs.e.call(void 0, ).error("Error parsing mesh batch:",o),[]}}async function En(e,r,t){let{mergeByMaterial:n=!0,applyTransforms:o=!0,debug:a=!1}=_nullishCoalesce(r, () => ({})),{parseTime:i=0,perfStart:l=a?performance.now():0}=_nullishCoalesce(t, () => ({}));try{let s=performance.now(),c=se(e.compressedData),d=performance.now()-s,u=a?Rn(e.compressedData):0;return Le(c,{mergeByMaterial:n,applyTransforms:o,debug:a,parseTime:i,decodeTime:d,perfStart:l,blobBytes:u,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}catch(s){return _chunk6LCAIDQVcjs.e.call(void 0, ).error("Error parsing mesh batch object:",s),[]}}async function Ar(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,debug:o=!1}=_nullishCoalesce(r, () => ({})),a=o?performance.now():0;try{let i=performance.now(),l=se(e),s=performance.now()-i,c=e.byteLength;return Le(l,{mergeByMaterial:t,applyTransforms:n,debug:o,parseTime:0,decodeTime:s,perfStart:a,blobBytes:c})}catch(i){return _chunk6LCAIDQVcjs.e.call(void 0, ).error("Error parsing mesh batch blob:",i),[]}}function Le(e,r){let{mergeByMaterial:t,applyTransforms:n,debug:o,parseTime:a,decodeTime:i,perfStart:l,blobBytes:s,fallback:c}=r,d=_nullishCoalesce(_nullishCoalesce(e.metadata.materials, () => (_optionalChain([c, 'optionalAccess', _229 => _229.materials]))), () => ([])),u=_nullishCoalesce(_nullishCoalesce(e.metadata.groups, () => (_optionalChain([c, 'optionalAccess', _230 => _230.groups]))), () => ([])),m=_nullishCoalesce(_optionalChain([c, 'optionalAccess', _231 => _231.sourceComponentId]), () => (e.metadata.sourceComponentId)),p=(e.flags&ie)!==0,f=p?hn(e.vertices,n):fn(e.vertices,e.origin,e.scale,n);if(o){let b=e.vertices.byteLength+e.indices.byteLength;_chunk6LCAIDQVcjs.e.call(void 0, ).debug("Mesh Batch Stats:"),_chunk6LCAIDQVcjs.e.call(void 0, ).debug(` Materials: ${d.length} | Groups: ${u.length}`),_chunk6LCAIDQVcjs.e.call(void 0, ).debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),_chunk6LCAIDQVcjs.e.call(void 0, ).debug(` Format: ${p?"float32":"int16 quantized"}`),_chunk6LCAIDQVcjs.e.call(void 0, ).debug(` Blob: ${(s/1024/1024).toFixed(2)} MB | Geometry on wire: ${(b/1024/1024).toFixed(2)} MB`)}let S=performance.now(),H=d.map(gn),g=[];for(let b of u)if(t)for(let T of yn(b))if(T.meshes.length>1){let P=bn(T,f,e.indices,H);P.userData.sourceComponentId=_nullishCoalesce(m, () => (null)),g.push(P)}else{let P=Ae(T,f,e.indices,H);for(let y of P)y.userData.sourceComponentId=_nullishCoalesce(m, () => (null));g.push(...P)}else{let T=Ae(b,f,e.indices,H);for(let P of T)P.userData.sourceComponentId=_nullishCoalesce(m, () => (null));g.push(...T)}let R=performance.now()-S;if(o){let b=performance.now()-l;_chunk6LCAIDQVcjs.e.call(void 0, ).debug("Performance:"),a>0&&_chunk6LCAIDQVcjs.e.call(void 0, ).debug(` Parse JSON: ${a.toFixed(2)}ms`),_chunk6LCAIDQVcjs.e.call(void 0, ).debug(` Decode binary: ${i.toFixed(2)}ms`),_chunk6LCAIDQVcjs.e.call(void 0, ).debug(` Create Meshes: ${R.toFixed(2)}ms`),_chunk6LCAIDQVcjs.e.call(void 0, ).debug(` Total: ${b.toFixed(2)}ms`)}return Promise.resolve(g)}function fn(e,r,t,n){let o=new Float32Array(e.length),a=r[0],i=r[1],l=r[2],s=t[0],c=t[1],d=t[2];for(let u=0;u<e.length;u+=3)o[u]=a+(e[u]+32767)*s,o[u+1]=i+(e[u+1]+32767)*c,o[u+2]=l+(e[u+2]+32767)*d;return o}function hn(e,r){return e}function gn(e){let r=ce(e.color);return new F.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:F.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function yn(e){let r=new Map;for(let t of e.meshes){let n=_nullishCoalesce(t.layer, () => ("")),o=r.get(n);o?o.push(t):r.set(n,[t])}return r.size<=1?[e]:Array.from(r.values(),t=>({materialId:e.materialId,meshes:t}))}function bn(e,r,t,n){let o=0,a=0;for(let f of e.meshes)o+=f.vertexCount,a+=f.indexCount;let i=new Float32Array(o*3),l=new Uint32Array(a),s=0,c=0;for(let f of e.meshes){let S=f.vertexStart*3,H=f.vertexCount*3;i.set(r.subarray(S,S+H),s*3);let g=t.subarray(f.indexStart,f.indexStart+f.indexCount),R=s-f.vertexStart;if(R===0)l.set(g,c);else for(let b=0;b<g.length;b++)l[c+b]=g[b]+R;s+=f.vertexCount,c+=f.indexCount}let d=new F.BufferGeometry;d.setAttribute("position",new F.BufferAttribute(i,3)),d.setIndex(new F.BufferAttribute(l,1)),d.computeVertexNormals();let u=new F.Mesh(d,n[e.materialId]),m=e.meshes[0],p=e.meshes.map(f=>f.name).filter(f=>f&&f.length>0);return u.name=p.length>0?p[0]:`merged_material_${e.materialId}`,u.castShadow=!0,u.receiveShadow=!0,u.userData={source:"compute",name:u.name,layer:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _232 => _232.layer]), () => ("")),originalIndex:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _233 => _233.originalIndex]), () => (0)),metadata:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _234 => _234.metadata]), () => ({})),mergedFrom:e.meshes.slice(1).map(f=>({name:f.name,layer:f.layer,originalIndex:f.originalIndex}))},u}function Ae(e,r,t,n){let o=[];for(let a of e.meshes){let i=a.vertexStart*3,l=a.vertexCount*3,s=r.slice(i,i+l),c=t.subarray(a.indexStart,a.indexStart+a.indexCount),d=new Uint32Array(c.length),u=a.vertexStart;for(let f=0;f<c.length;f++)d[f]=c[f]-u;let m=new F.BufferGeometry;m.setAttribute("position",new F.BufferAttribute(s,3)),m.setIndex(new F.BufferAttribute(d,1)),m.computeVertexNormals();let p=new F.Mesh(m,n[e.materialId]);p.name=a.name,p.userData={source:"compute",name:a.name,layer:_nullishCoalesce(a.layer, () => ("")),originalIndex:a.originalIndex,metadata:_nullishCoalesce(a.metadata, () => ({}))},p.castShadow=!0,p.receiveShadow=!0,o.push(p)}return o}function Rn(e){return Math.floor(e.length*3/4)}var Tn={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},wn="Display";async function Vr(e,r){let t=performance.now(),n=[],{allowScaling:o=!0,allowAutoPosition:a=!0,rhino:i,debug:l=!1,parsing:s={}}=_nullishCoalesce(r, () => ({}));try{let c=o?Hn(e.modelunits):1;return await vn(e,n,c,s,i,l),a&&Sn(n),n}catch(c){throw An(c,n),c}finally{l&&Ln(t)}}function Hn(e){return _nullishCoalesce(Tn[e], () => (1))}async function vn(e,r,t,n,o,a){for(let i of e.values){let l=i.InnerTree;for(let s in l){let c=l[s];c&&await Mn(c,r,t,n,o,a)}}}async function Mn(e,r,t,n,o,a){for(let i of e){if(!i.type.includes(wn))continue;let l={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...n},s=await De(i.data,l),c=we(xn(i.data),{rhino:o,applyTransforms:l.applyTransforms}),d=[...s,...c];if(t!==1)for(let u of d)u.scale.set(t,t,t);r.push(...d),a&&_chunk6LCAIDQVcjs.e.call(void 0, ).debug(`Extracted ${s.length} meshes and ${c.length} items from batch`)}}function xn(e){return_optionalChain([(typeof e=="string"?Cn(e):e), 'optionalAccess', _235 => _235.items])}function Cn(e){try{return JSON.parse(e)}catch (e4){return}}function Sn(e){if(e.length===0)return;let r=J(e);ue(e,r.min.z,"z")}function An(e,r){_chunk6LCAIDQVcjs.e.call(void 0, ).error("An unexpected error occurred:",e),Dn(r)}function Dn(e){for(let r of e){let t=r;t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(n=>n.dispose()):t.material.dispose())}}function Ln(e){let r=performance.now()-e;_chunk6LCAIDQVcjs.e.call(void 0, ).info("Time to process meshes:",`${r.toFixed(2)}ms`)}exports.a = In; exports.b = ce; exports.c = ue; exports.d = J; exports.e = de; exports.f = me; exports.g = pe; exports.h = Q; exports.i = fe; exports.j = Qe; exports.k = Nn; exports.l = he; exports.m = ye; exports.n = Et; exports.o = Re; exports.p = pr; exports.q = jt; exports.r = we; exports.s = ve; exports.t = Me; exports.u = ie; exports.v = se; exports.w = De; exports.x = En; exports.y = Ar; exports.z = Tn; exports.A = Vr;
55
+ //# sourceMappingURL=chunk-JF5MZTOU.cjs.map