@selvajs/compute 2.3.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/chunk-2EO6UUZF.cjs +2 -0
  2. package/dist/chunk-2EO6UUZF.cjs.map +1 -0
  3. package/dist/chunk-GY2WLD42.js +4 -0
  4. package/dist/chunk-GY2WLD42.js.map +1 -0
  5. package/dist/chunk-UFFSB36M.js +2 -0
  6. package/dist/chunk-UFFSB36M.js.map +1 -0
  7. package/dist/{chunk-4O5AQXM4.js → chunk-UH3HH7PS.js} +2 -2
  8. package/dist/chunk-XA4OMT6Z.cjs +4 -0
  9. package/dist/chunk-XA4OMT6Z.cjs.map +1 -0
  10. package/dist/{chunk-KTWK7KQR.cjs → chunk-XXA7NEQF.cjs} +3 -3
  11. package/dist/{chunk-KTWK7KQR.cjs.map → chunk-XXA7NEQF.cjs.map} +1 -1
  12. package/dist/core.cjs +1 -1
  13. package/dist/core.d.cts +1 -1
  14. package/dist/core.d.ts +1 -1
  15. package/dist/core.js +1 -1
  16. package/dist/grasshopper.cjs +1 -1
  17. package/dist/grasshopper.d.cts +4 -4
  18. package/dist/grasshopper.d.ts +4 -4
  19. package/dist/grasshopper.js +1 -1
  20. package/dist/{handle-files-VUQET1YU.d.cts → handle-files-UcwvknQ3.d.cts} +8 -0
  21. package/dist/{handle-files-VUQET1YU.d.ts → handle-files-UcwvknQ3.d.ts} +8 -0
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.d.cts +2 -2
  24. package/dist/index.d.ts +2 -2
  25. package/dist/index.js +1 -1
  26. package/dist/{types-DqSisB8v.d.cts → types-D-HQ-gWI.d.cts} +15 -0
  27. package/dist/{types-CIsBR_xd.d.ts → types-DxT3hSkx.d.ts} +15 -0
  28. package/dist/{visualization-K26YLDGB.js → visualization-RICQHNLJ.js} +2 -2
  29. package/dist/visualization-ZFXCE5NW.cjs +2 -0
  30. package/dist/{visualization-N5MZDQND.cjs.map → visualization-ZFXCE5NW.cjs.map} +1 -1
  31. package/dist/visualization.cjs +1 -1
  32. package/dist/visualization.d.cts +2 -2
  33. package/dist/visualization.d.ts +2 -2
  34. package/dist/visualization.js +1 -1
  35. package/package.json +3 -3
  36. package/dist/chunk-4UOOVSGL.cjs +0 -4
  37. package/dist/chunk-4UOOVSGL.cjs.map +0 -1
  38. package/dist/chunk-AXAMGKTJ.js +0 -4
  39. package/dist/chunk-AXAMGKTJ.js.map +0 -1
  40. package/dist/chunk-LOMSRASE.js +0 -2
  41. package/dist/chunk-LOMSRASE.js.map +0 -1
  42. package/dist/chunk-S365UQ5O.cjs +0 -2
  43. package/dist/chunk-S365UQ5O.cjs.map +0 -1
  44. package/dist/visualization-N5MZDQND.cjs +0 -2
  45. /package/dist/{chunk-4O5AQXM4.js.map → chunk-UH3HH7PS.js.map} +0 -0
  46. /package/dist/{visualization-K26YLDGB.js.map → visualization-RICQHNLJ.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 A=Object.defineProperty;var L=(t,e,r)=>e in t?A(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var ae=(t,e)=>{for(var r in e)A(t,r,{get:e[r],enumerable:!0})};var R=(t,e,r)=>L(t,typeof e!="symbol"?e+"":e,r);var a={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"},c= exports.d =class t extends Error{constructor(r,n="UNKNOWN_ERROR",o){super(r);R(this,"code");R(this,"statusCode");R(this,"context");R(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})`:""}`,a.INVALID_INPUT,{context:{inputName:r,expectedType:n,...o}})}static unknownParamType(r,n,o){return new t(`Unknown paramType: ${r}`,a.VALIDATION_ERROR,{context:{receivedParamType:r,paramName:n,...o}})}};var w=class{debug(){}info(){}warn(){}error(){}},O=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)}},I=new w;function p(){return I}function $(t){I=t===null?new w:t}function k(){$(new O)}function M(t){if(!t)return null;let e={raw:t},r=!1;for(let n of t.split(",")){let[o,...l]=n.trim().split(";"),d=l.find(f=>f.trim().toLowerCase().startsWith("dur"));if(!d)continue;let s=Number(d.split("=")[1]);if(!Number.isFinite(s))continue;let u=o.trim().toLowerCase();(u==="decode"||u==="solve"||u==="encode")&&(e[u]=s,r=!0)}return r?e:null}var v={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},D=new Set([502,503,504]);function B(t){return t?{attempts:_nullishCoalesce(t.attempts, () => (v.attempts)),baseDelayMs:_nullishCoalesce(t.baseDelayMs, () => (v.baseDelayMs)),maxDelayMs:_nullishCoalesce(t.maxDelayMs, () => (v.maxDelayMs)),retryOn429:_nullishCoalesce(t.retryOn429, () => (v.retryOn429))}:v}function q(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 K(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",l)]),r()},t),l=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))};_optionalChain([e, 'optionalAccess', _9 => _9.addEventListener, 'call', _10 => _10("abort",l,{once:!0})])})}function H(t,e,r,n,o,l,d){let{status:s,statusText:u}=t,f={};t.headers.forEach((C,x)=>{f[x]=C});let h=l.trim(),i=h?` \u2014 ${h.slice(0,200)}${h.length>200?"\u2026":""}`:"",y={url:e,requestId:r,method:"POST",requestSize:n,serverUrl:o,responseBody:l||void 0,responseHeaders:f},b={401:{message:`HTTP ${s}: ${u}${i}`,code:a.AUTH_ERROR},403:{message:`HTTP ${s}: ${u}${i}`,code:a.AUTH_ERROR},404:{message:`Endpoint not found: ${e}`,code:a.NETWORK_ERROR},413:{message:`Request too large: ${(n/1024).toFixed(2)}KB`,code:a.VALIDATION_ERROR},429:{message:`Rate limit exceeded${i}`,code:a.NETWORK_ERROR},500:{message:`Server error: ${u}${i}`,code:a.COMPUTATION_ERROR},502:{message:`Service unavailable: ${u}${i}`,code:a.NETWORK_ERROR},503:{message:`Service unavailable: ${u}${i}`,code:a.NETWORK_ERROR},504:{message:`Service unavailable: ${u}${i}`,code:a.NETWORK_ERROR}}[s]||{message:`HTTP ${s}: ${u}${i}`,code:a.UNKNOWN_ERROR},E=_nullishCoalesce(W(d), () => (b.code));throw new c(b.message,E,{statusCode:s,context:y})}function W(t){if(t==="definition_not_cached")return a.DEFINITION_NOT_CACHED}function z(t,e){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${r}/${n}`}function V(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 J(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&&!V(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 m(t,e){e&&p().debug(t)}function G(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,u=setTimeout(()=>s.abort(),e);n=()=>clearTimeout(u),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,l=()=>o.abort();for(let s of r){if(s.aborted){o.abort();break}s.addEventListener("abort",l,{once:!0})}let d=n;return n=()=>{d();for(let s of r)s.removeEventListener("abort",l)},{signal:o.signal,cleanup:n}}async function Y(t,e,r,n,o,l,d,s){let u=Math.round(performance.now()-l);if(!t.ok){let f=await t.text();d&&(m(`\u274C Request [${r}] failed with HTTP ${t.status} in ${u}ms`,!0),m(` URL: ${e}`,!0),m(` Status: ${t.status} ${t.statusText}`,!0),f&&m(` Response body: ${f.substring(0,500)}${f.length>500?"...":""}`,!0));let h;if(t.status===500)try{let i=JSON.parse(f);if(typeof _optionalChain([i, 'optionalAccess', _11 => _11.code])=="string"&&(h=i.code),_optionalChain([i, 'optionalAccess', _12 => _12.values])&&(i.errors||i.warnings))return d&&(m(`\u26A0\uFE0F Request [${r}] completed with Grasshopper errors in ${u}ms`,!0),_optionalChain([i, 'access', _13 => _13.errors, 'optionalAccess', _14 => _14.length])>0&&m(` Errors: ${JSON.stringify(i.errors,null,2)}`,!0),_optionalChain([i, 'access', _15 => _15.warnings, 'optionalAccess', _16 => _16.length])>0&&m(` Warnings: ${JSON.stringify(i.warnings,null,2)}`,!0)),i;let y=typeof _optionalChain([i, 'optionalAccess', _17 => _17.message])=="string"&&i.message||typeof _optionalChain([i, 'optionalAccess', _18 => _18.Message])=="string"&&i.Message||"",g=typeof _optionalChain([i, 'optionalAccess', _19 => _19.ExceptionType])=="string"&&i.ExceptionType||"",b=_nullishCoalesce(_optionalChain([i, 'optionalAccess', _20 => _20.stackTrace]), () => (_optionalChain([i, 'optionalAccess', _21 => _21.StackTrace]))),E=Array.isArray(b)?b.join(`
2
+ `):b||"";y?f=`${g?`${g}: `:""}${y}${E?`
3
+ ${E}`:""}`:_optionalChain([i, 'optionalAccess', _22 => _22.error])&&(f=typeof i.error=="string"?i.error:JSON.stringify(i.error,null,2))}catch(i){d&&m(` Failed to parse error body as JSON: ${i}`,!0)}H(t,e,r,n,o,f,h)}if(m(`\u2705 Request [${r}] completed in ${u}ms`,d),s){let f=M(t.headers.get("Server-Timing"));if(f)try{s(f)}catch(h){d&&m(` onServerTiming callback threw: ${h}`,!0)}}try{return await t.json()}catch(f){throw new c("Failed to parse JSON response",a.NETWORK_ERROR,{statusCode:t.status,context:{url:e,requestId:r},originalError:f instanceof Error?f:new Error(String(f))})}}async function Z(t,e,r,n){let{signal:o,cleanup:l}=G(t.config.signal,t.config.timeoutMs),d=performance.now();try{let s=await fetch(t.fullUrl,{method:"POST",body:t.body,headers:t.headers,signal:o});if((D.has(s.status)||e.retryOn429&&s.status===429)&&r<n-1){let i=_nullishCoalesce(q(s.headers.get("Retry-After")), () => (S(r,e)));return await s.text().catch(()=>{}),{ok:!1,retry:!0,delayMs:i,cause:new c(`HTTP ${s.status} ${s.statusText} (will retry)`,a.NETWORK_ERROR,{statusCode:s.status,context:{requestId:t.requestId}})}}return{ok:!0,value:await Y(s,t.fullUrl,t.requestId,t.requestSize,t.config.serverUrl,d,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 c("Request aborted by caller",a.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId,requestSize:t.requestSize},originalError:s})};let f=new c(`Request timed out after ${t.config.timeoutMs}ms`,a.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:f}:{ok:!1,retry:!1,cause:f}}if(s instanceof TypeError){let u=new c(`Network error: ${s.message}`,a.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:u}:{ok:!1,retry:!1,cause:u}}if(s instanceof c){let u=s.statusCode;return u!==void 0&&(D.has(u)||e.retryOn429&&u===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 c(s instanceof Error?s.message:String(s),a.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId},originalError:s instanceof Error?s:new Error(String(s))})}}finally{l()}}async function X(t,e,r){let n=j(),o=JSON.stringify(e),l=o.length,d=z(t,r.serverUrl),s=J(n,r),u=B(r.retry),f=u.attempts+1;if(r.debug){let y=(l/1024).toFixed(2),g=l>1e5?"\u26A0\uFE0F":"\u{1F680}";m(`${g} Starting compute request [${n}]: ${t} (${y}KB)`,!0)}let h={endpoint:t,body:o,requestSize:l,fullUrl:d,requestId:n,headers:s,config:r},i=null;for(let y=0;y<f;y++){let g=await Z(h,u,y,f);if(g.ok)return g.value;if(!g.retry)throw g.cause;i=g.cause,r.debug&&m(`\u{1F501} Request [${n}] retrying after ${g.delayMs}ms (attempt ${y+2}/${f}): ${g.cause.message}`,!0);try{await K(g.delayMs,r.signal)}catch (e3){throw new c("Request aborted by caller",a.UNKNOWN_ERROR,{context:{endpoint:t,requestId:n,requestSize:l},originalError:i})}}throw _nullishCoalesce(i, () => (new c("Unknown error after retries",a.UNKNOWN_ERROR,{context:{endpoint:t,requestId:n,requestSize:l}})))}var Q="https://compute.rhino3d.com/";function U(t){if(!_optionalChain([t, 'optionalAccess', _26 => _26.trim, 'call', _27 => _27()]))throw new c("serverUrl is required",a.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(!t.match(/^https?:\/\//))throw new c(`Invalid serverUrl: "${t}". Must start with "http://" or "https://". For example: "http://localhost:5000" or "https://example.com"`,a.INVALID_CONFIG,{context:{receivedServerUrl:t}});try{new URL(t)}catch(e){throw new c(`Invalid serverUrl: "${t}". Must be a valid URL. Received error: ${e instanceof Error?e.message:String(e)}`,a.INVALID_CONFIG,{context:{receivedServerUrl:t},originalError:e instanceof Error?e:void 0})}if(t===Q)throw new c("serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.",a.INVALID_CONFIG,{context:{receivedServerUrl:t}});return t.replace(/\/+$/,"")}var T=class{constructor(e,r){R(this,"serverUrl");R(this,"apiKey");R(this,"disposed",!1);R(this,"activeMonitors",new Set);R(this,"activeTimeouts",new Set);this.serverUrl=U(e),this.apiKey=r}buildHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}async isServerOnline(e=5e3){this.ensureNotDisposed();let r=`${this.serverUrl}/`,n={headers:this.buildHeaders(),method:"GET"};e>0&&(n.signal=AbortSignal.timeout(e));try{return(await fetch(r,n)).ok}catch(o){return p().debug("[ComputeServerStats] Fetch error:",o),!1}}async getActiveChildren(e={}){this.ensureNotDisposed();let{initialize:r=!0}=e,n=r?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`;try{let o=await fetch(n,{headers:this.buildHeaders()});if(!o.ok)return p().warn("[ComputeServerStats] Failed to fetch active children:",o.status),null;let l=await o.text(),d=parseInt(l.trim(),10);return isNaN(d)?(p().warn("[ComputeServerStats] Invalid active children response:",l),null):d}catch(o){return p().warn("[ComputeServerStats] Error fetching active children:",o),null}}async getVersion(){this.ensureNotDisposed();try{let e=await fetch(`${this.serverUrl}/version`,{headers:this.buildHeaders()});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 (e4){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 fetch(`${this.serverUrl}/plugins/${e}/installed`,{headers:this.buildHeaders()});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 (e5){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 fetch(`${this.serverUrl}/cache/purge`,{method:"POST",headers:this.buildHeaders()});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 (e6){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 l=await this.purgeCache();l!==null&&(n+=l)}return{totalPurged:n,calls:r,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await fetch(`${this.serverUrl}/servertime`,{headers:this.buildHeaders()});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 fetch(`${this.serverUrl}/idlespan`,{headers:this.buildHeaders()});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 fetch(`${this.serverUrl}${e}`,{method:"POST",headers:this.buildHeaders()});if(!r.ok)return p().warn(`[ComputeServerStats] POST ${e} failed:`,r.status),null;let n=await r.text();try{return JSON.parse(n)}catch (e7){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 l=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(u){p().error("[ComputeServerStats] Monitor callback threw:",u)}}catch(s){p().error("[ComputeServerStats] Failed to fetch stats during monitor:",s)}n&&!this.disposed&&(o=setTimeout(()=>{l()},r),this.activeTimeouts.add(o))}},d=()=>{n=!1,o!==null&&(clearTimeout(o),this.activeTimeouts.delete(o),o=null),this.activeMonitors.delete(d)};return this.activeMonitors.add(d),l(),d}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 c("ComputeServerStats has been disposed and cannot be used",a.INVALID_STATE,{context:{disposed:this.disposed}})}};function F(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,(l,d)=>d?d.toUpperCase():"")}function N(t,e={}){return!t||typeof t!="object"?t:Array.isArray(t)?e.deep?t.map(r=>N(r,e)):t:Object.keys(t).reduce((r,n)=>{let o=F(n,{preserveSpaces:e.preserveSpaces}),l=t[n];return r[o]=e.deep?N(l,e):l,r},{})}function Te(t){return typeof globalThis.Buffer=="function"?globalThis.Buffer.from(t,"utf-8").toString("base64"):ee(new TextEncoder().encode(t))}function Oe(t){return!t||t.length<2||t.length%4!==0?!1:/^[A-Za-z0-9+/]+={0,2}$/.test(t)}function _(t){if(typeof globalThis.Buffer=="function"){let e=globalThis.Buffer.from(t,"base64");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(typeof globalThis.atob=="function"){let e=globalThis.atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n)&255;return r}throw new c("Base64 decoding not supported in this environment.",a.INVALID_STATE,{context:{environmentInfo:"atob or Buffer not available"}})}function ee(t){if(typeof globalThis.Buffer=="function")return globalThis.Buffer.from(t).toString("base64");if(typeof globalThis.btoa=="function"){let r="";for(let n=0;n<t.length;n+=32768)r+=String.fromCharCode.apply(null,Array.from(t.subarray(n,n+32768)));return globalThis.btoa(r)}throw new c("Base64 encoding not supported in this environment.",a.INVALID_STATE,{context:{environmentInfo:"btoa or Buffer not available"}})}var re=async(t,e=null)=>{try{return await P(t,e)}catch(r){throw new c("Failed to extract files from compute response",a.INVALID_STATE,{context:{originalError:r instanceof Error?r.message:String(r)},originalError:r instanceof Error?r:void 0})}},te= exports.r =async(t,e,r=null)=>{if(typeof document>"u"||typeof Blob>"u")throw new c("File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).",a.BROWSER_ONLY,{context:{environment:typeof window<"u"?"browser (SSR)":"Node.js",documentAvailable:typeof document<"u",blobAvailable:typeof Blob<"u"}});try{let n=await P(t,r);await se(n,e)}catch(n){throw n instanceof c?n:new c("Failed to download files from compute response",a.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}},ne=t=>{let e=[];return t.forEach(r=>{let n=`${r.fileName}${r.fileType}`;r.subFolder&&r.subFolder.trim()!==""&&(n=`${r.subFolder}/${n}`),r.isBase64Encoded===!0&&r.data?e.push({fileName:`${r.fileName}${r.fileType}`,content:_(r.data),path:n}):r.isBase64Encoded===!1&&r.data&&e.push({fileName:`${r.fileName}${r.fileType}`,content:r.data,path:n})}),e},oe=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 l=await(await n.blob()).arrayBuffer();return{fileName:r.fileName,content:new Uint8Array(l),path:r.fileName}}catch(n){return p().error(`Error fetching additional file from URL: ${r.filePath}`,n),null}}))).filter(r=>r!==null),P=async(t,e)=>{let r=ne(t);if(e){let n=Array.isArray(e)?e:[e];r.push(...await oe(n))}return r};async function se(t,e){let{zipSync: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 l=r(o,{level:6}),d=new Blob([l],{type:"application/zip"});ie(d,`${e}.zip`)}function ie(t,e){if(typeof document>"u")throw new c("saveFile requires a browser environment with DOM API access.",a.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 = ae; exports.b = R; exports.c = a; exports.d = c; exports.e = p; exports.f = $; exports.g = k; exports.h = X; exports.i = U; exports.j = T; exports.k = F; exports.l = N; exports.m = Te; exports.n = Oe; exports.o = _; exports.p = ee; exports.q = re; exports.r = te;
4
+ //# sourceMappingURL=chunk-XA4OMT6Z.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-XA4OMT6Z.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;ACwSzC;AAmIjC","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-XA4OMT6Z.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// 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\tif (typeof parsed?.code === 'string') serverCode = parsed.code;\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\tconst delayMs = retryAfterMs ?? 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"]}
@@ -1,4 +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 _chunk4UOOVSGLcjs = require('./chunk-4UOOVSGL.cjs');var _three = require('three'); var V = _interopRequireWildcard(_three); var z = _interopRequireWildcard(_three); var I = _interopRequireWildcard(_three); var F = _interopRequireWildcard(_three); var $ = _interopRequireWildcard(_three); var be = _interopRequireWildcard(_three); var A = _interopRequireWildcard(_three); var p = _interopRequireWildcard(_three); var L = _interopRequireWildcard(_three); var j = _interopRequireWildcard(_three); var B = _interopRequireWildcard(_three);var _={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 An(e,r,t,n,o){if(Oe(e),r.length===0)return;r.forEach(u=>{e.add(u)});let a=Y(r),i=a.getCenter(new V.Vector3),s=a.getSize(new V.Vector3),l=Math.max(s.x,s.y,s.z);if(l/Math.min(s.x||1,s.y||1,s.z||1)>_.SCALE_RATIO_THRESHOLD||l>_.HUGE_THRESHOLD?(t.near=l*_.NEAR_PLANE_FACTOR.TINY,t.far=l*_.FAR_PLANE_FACTOR.HUGE):l>_.LARGE_THRESHOLD?(t.near=l*_.NEAR_PLANE_FACTOR.SMALL,t.far=l*_.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,l*_.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,l*_.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),o)n.minDistance=t.near*2,n.maxDistance=t.far*.9;else{let u=l*_.INITIAL_DISTANCE_MULTIPLIER;t.position.set(i.x+u*.8,i.y+u,i.z+u*1.2),n.target.copy(i),n.minDistance=t.near*2,n.maxDistance=t.far*.9,n.update()}}function ue(e){if(!e||typeof e!="string")return _chunk4UOOVSGLcjs.e.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new V.Color(16777215);let r=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(r))try{let t=r.startsWith("#")?r:`#${r}`;return new V.Color(t)}catch (e2){return _chunk4UOOVSGLcjs.e.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new V.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 V.Color(t[0]/255,t[1]/255,t[2]/255)}try{return new V.Color(r.toLowerCase())}catch (e3){return _chunk4UOOVSGLcjs.e.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new V.Color(16777215)}}function de(e,r,t="z"){e.forEach(n=>{n.position[t]-=r})}function Y(e){let r=new V.Box3;return e.length===0||e.forEach(t=>{t.updateMatrixWorld(!0);let n=new V.Box3().setFromObject(t);r.union(n)}),r}var Pe=new Set(["floor","grid","label-layer"]);function Oe(e){[...e.children].forEach(t=>{Pe.has(t.userData.id)||(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(s=>{for(let l of Object.values(s))l instanceof V.Texture&&l.dispose();s.dispose()})}),t.removeFromParent())})}function Ie(e){let r=e.clone().normalize(),t=new z.Vector3(0,0,1),n=new z.Vector3(0,1,0),o=Math.abs(r.dot(t))>.9?n:t,a=new z.Vector3().crossVectors(r,o).normalize(),i=new z.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 me(e){let{scene:r,perspective:t,controls:n,onActiveCameraChange:o}=e,a=(_nullishCoalesce(e.up, () => (t.up))).clone().normalize(),i=Ie(a),s=new z.OrthographicCamera(-1,1,1,-1,t.near,t.far);s.up.copy(a);let l="perspective",c=t.aspect,u=()=>l==="perspective"?t:s,d=()=>{let h=t.position.distanceTo(n.target)*Math.tan(t.fov*Math.PI/360),T=h*c;s.left=-T,s.right=T,s.top=h,s.bottom=-h,s.near=t.near,s.far=t.far,s.updateProjectionMatrix()},m=b=>{b!==l&&(b==="orthographic"?(s.position.copy(t.position),s.up.copy(t.up),s.lookAt(n.target),d()):t.position.copy(s.position),l=b,n.object=u(),n.update(),o(u()))},E=(b,h=!0)=>{let T=ze(r),v=T.isEmpty()?n.target.clone():T.getCenter(new z.Vector3),P=T.isEmpty()?new z.Vector3(1,1,1):T.getSize(new z.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=Fe(b,a),g=v.clone().add(O.clone().multiplyScalar(C)),R=u();h?ke(R,n,g,v,()=>{l==="orthographic"&&d()}):(R.position.copy(g),n.target.copy(v),l==="orthographic"&&d(),n.update())};return{getActiveCamera:u,getProjection:()=>l,setProjection:m,toggleProjection:()=>(m(l==="perspective"?"orthographic":"perspective"),l),setView:(b,h=!0)=>{E(i[b],h)},setViewDirection:E,setRotateEnabled:b=>{n.enableRotate=b},isRotateEnabled:()=>n.enableRotate,updateAspect:(b,h)=>{c=h===0?c:b/h,l==="orthographic"&&d()}}}var Ve=new Set(["grid","floor","label-layer","measure"]);function Be(e){let r=e;for(;r;){if(typeof r.userData.id=="string"&&Ve.has(r.userData.id))return!0;r=r.parent}return!1}function ze(e){let r=[];return e.traverse(t=>{let n=t;t.visible&&!Be(t)&&n.geometry&&r.push(t)}),Y(r)}function Fe(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 z.Vector3(0,0,1)))>.9?new z.Vector3(0,1,0):new z.Vector3(0,0,1),a=new z.Vector3().crossVectors(t,o).normalize(),i=.5*Math.PI/180;return n.multiplyScalar(Math.cos(i)).add(a.multiplyScalar(Math.sin(i))).normalize()}var je=e=>1-Math.pow(1-e,3);function ke(e,r,t,n,o,a=250){let i=e.position.clone(),s=r.target.clone(),l=performance.now(),c=()=>{let u=je(Math.min((performance.now()-l)/a,1));e.position.lerpVectors(i,t,u),r.target.lerpVectors(s,n,u),o(),r.update(),u<1&&requestAnimationFrame(c)};requestAnimationFrame(c)}var _e=`
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 _chunkXA4OMT6Zcjs = require('./chunk-XA4OMT6Z.cjs');var _three = require('three'); var V = _interopRequireWildcard(_three); var z = _interopRequireWildcard(_three); var I = _interopRequireWildcard(_three); var F = _interopRequireWildcard(_three); var $ = _interopRequireWildcard(_three); var be = _interopRequireWildcard(_three); var A = _interopRequireWildcard(_three); var p = _interopRequireWildcard(_three); var L = _interopRequireWildcard(_three); var j = _interopRequireWildcard(_three); var B = _interopRequireWildcard(_three);var _={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 An(e,r,t,n,o){if(Oe(e),r.length===0)return;r.forEach(u=>{e.add(u)});let a=Y(r),i=a.getCenter(new V.Vector3),s=a.getSize(new V.Vector3),l=Math.max(s.x,s.y,s.z);if(l/Math.min(s.x||1,s.y||1,s.z||1)>_.SCALE_RATIO_THRESHOLD||l>_.HUGE_THRESHOLD?(t.near=l*_.NEAR_PLANE_FACTOR.TINY,t.far=l*_.FAR_PLANE_FACTOR.HUGE):l>_.LARGE_THRESHOLD?(t.near=l*_.NEAR_PLANE_FACTOR.SMALL,t.far=l*_.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,l*_.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,l*_.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),o)n.minDistance=t.near*2,n.maxDistance=t.far*.9;else{let u=l*_.INITIAL_DISTANCE_MULTIPLIER;t.position.set(i.x+u*.8,i.y+u,i.z+u*1.2),n.target.copy(i),n.minDistance=t.near*2,n.maxDistance=t.far*.9,n.update()}}function ue(e){if(!e||typeof e!="string")return _chunkXA4OMT6Zcjs.e.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new V.Color(16777215);let r=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(r))try{let t=r.startsWith("#")?r:`#${r}`;return new V.Color(t)}catch (e2){return _chunkXA4OMT6Zcjs.e.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new V.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 V.Color(t[0]/255,t[1]/255,t[2]/255)}try{return new V.Color(r.toLowerCase())}catch (e3){return _chunkXA4OMT6Zcjs.e.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new V.Color(16777215)}}function de(e,r,t="z"){e.forEach(n=>{n.position[t]-=r})}function Y(e){let r=new V.Box3;return e.length===0||e.forEach(t=>{t.updateMatrixWorld(!0);let n=new V.Box3().setFromObject(t);r.union(n)}),r}var Pe=new Set(["floor","grid","label-layer"]);function Oe(e){[...e.children].forEach(t=>{Pe.has(t.userData.id)||(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(s=>{for(let l of Object.values(s))l instanceof V.Texture&&l.dispose();s.dispose()})}),t.removeFromParent())})}function Ie(e){let r=e.clone().normalize(),t=new z.Vector3(0,0,1),n=new z.Vector3(0,1,0),o=Math.abs(r.dot(t))>.9?n:t,a=new z.Vector3().crossVectors(r,o).normalize(),i=new z.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 me(e){let{scene:r,perspective:t,controls:n,onActiveCameraChange:o}=e,a=(_nullishCoalesce(e.up, () => (t.up))).clone().normalize(),i=Ie(a),s=new z.OrthographicCamera(-1,1,1,-1,t.near,t.far);s.up.copy(a);let l="perspective",c=t.aspect,u=()=>l==="perspective"?t:s,d=()=>{let h=t.position.distanceTo(n.target)*Math.tan(t.fov*Math.PI/360),T=h*c;s.left=-T,s.right=T,s.top=h,s.bottom=-h,s.near=t.near,s.far=t.far,s.updateProjectionMatrix()},m=b=>{b!==l&&(b==="orthographic"?(s.position.copy(t.position),s.up.copy(t.up),s.lookAt(n.target),d()):t.position.copy(s.position),l=b,n.object=u(),n.update(),o(u()))},E=(b,h=!0)=>{let T=ze(r),v=T.isEmpty()?n.target.clone():T.getCenter(new z.Vector3),P=T.isEmpty()?new z.Vector3(1,1,1):T.getSize(new z.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=Fe(b,a),g=v.clone().add(O.clone().multiplyScalar(C)),R=u();h?ke(R,n,g,v,()=>{l==="orthographic"&&d()}):(R.position.copy(g),n.target.copy(v),l==="orthographic"&&d(),n.update())};return{getActiveCamera:u,getProjection:()=>l,setProjection:m,toggleProjection:()=>(m(l==="perspective"?"orthographic":"perspective"),l),setView:(b,h=!0)=>{E(i[b],h)},setViewDirection:E,setRotateEnabled:b=>{n.enableRotate=b},isRotateEnabled:()=>n.enableRotate,updateAspect:(b,h)=>{c=h===0?c:b/h,l==="orthographic"&&d()}}}var Ve=new Set(["grid","floor","label-layer","measure"]);function Be(e){let r=e;for(;r;){if(typeof r.userData.id=="string"&&Ve.has(r.userData.id))return!0;r=r.parent}return!1}function ze(e){let r=[];return e.traverse(t=>{let n=t;t.visible&&!Be(t)&&n.geometry&&r.push(t)}),Y(r)}function Fe(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 z.Vector3(0,0,1)))>.9?new z.Vector3(0,1,0):new z.Vector3(0,0,1),a=new z.Vector3().crossVectors(t,o).normalize(),i=.5*Math.PI/180;return n.multiplyScalar(Math.cos(i)).add(a.multiplyScalar(Math.sin(i))).normalize()}var je=e=>1-Math.pow(1-e,3);function ke(e,r,t,n,o,a=250){let i=e.position.clone(),s=r.target.clone(),l=performance.now(),c=()=>{let u=je(Math.min((performance.now()-l)/a,1));e.position.lerpVectors(i,t,u),r.target.lerpVectors(s,n,u),o(),r.update(),u<1&&requestAnimationFrame(c)};requestAnimationFrame(c)}var _e=`
2
2
  varying vec3 vWorldPos;
3
3
  void main() {
4
4
  vec4 world = modelMatrix * vec4(position, 1.0);
@@ -51,5 +51,5 @@
51
51
  gl_FragColor = vec4(color, alpha);
52
52
  }
53
53
  `;function Ee(e={}){let{cellSize:r=1,majorEvery:t=10,cellColor:n=8947848,majorColor:o=4473924,fadeDistance:a=100,plane:i="y"}=e,s=i==="y"?new I.Vector2(0,2):i==="z"?new I.Vector2(0,1):new I.Vector2(1,2),l=a*2.5,c=new I.PlaneGeometry(l,l);i==="y"?c.rotateX(-Math.PI/2):i==="x"&&c.rotateY(Math.PI/2);let u=new I.ShaderMaterial({vertexShader:_e,fragmentShader:Ue,transparent:!0,depthWrite:!1,side:I.DoubleSide,uniforms:{uAxes:{value:s},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}}}),d=new I.Mesh(c,u);d.name="grid",d.userData.id="grid",d.renderOrder=-1;let m=new I.Vector3;return{object:d,update:E=>{i==="y"?(d.position.set(E.x,0,E.z),m.set(E.x,0,E.z)):i==="z"?(d.position.set(E.x,E.y,0),m.set(E.x,E.y,0)):(d.position.set(0,E.y,E.z),m.set(0,E.y,E.z)),u.uniforms.uCenter.value.copy(m)},setVisible:E=>{d.visible=E},dispose:()=>{c.dispose(),u.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,s=new F.Raycaster,l=new F.OrthographicCamera(-2,2,2,-2,0,4);l.position.set(0,0,2);let c={posX:new F.Vector3(1,0,0),negX:new F.Vector3(-1,0,0),posY:new F.Vector3(0,1,0),negY:new F.Vector3(0,-1,0),posZ:new F.Vector3(0,0,1),negZ:new F.Vector3(0,0,-1)},u=m=>{let E=t.getBoundingClientRect(),f=E.left+t.offsetWidth-i-o.location.right,x=E.top+t.offsetHeight-i-o.location.bottom,S=new F.Vector2((m.clientX-f)/i*2-1,-((m.clientY-x)/i)*2+1);if(Math.abs(S.x)>1||Math.abs(S.y)>1)return null;o.quaternion.copy(r.quaternion).invert(),o.updateMatrixWorld(),s.setFromCamera(S,l);let b=s.intersectObjects(o.children,!1);for(let h of b){let T=_optionalChain([h, 'access', _5 => _5.object, 'access', _6 => _6.userData, 'optionalAccess', _7 => _7.type]);if(typeof T=="string"&&T in c)return T}return null};return{render:m=>{if(!a)return;let E=m.autoClear;m.autoClear=!1,o.render(m),m.autoClear=E},update:m=>{o.animating&&o.update(m)},handleClick:m=>{if(!a)return!1;let E=u(m);return E?(n.getProjection()==="orthographic"&&n.setProjection("perspective"),n.setViewDirection(c[E],!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 X="edge-overlay",$e=2236962,Ye=1.5,Xe=30;function he(e,r={}){let t=new $.Color(_nullishCoalesce(r.color, () => ($e))),n=_nullishCoalesce(r.width, () => (Ye)),o=_nullishCoalesce(r.thresholdAngle, () => (Xe)),a=[];return e.traverse(i=>{if(!(i instanceof $.Mesh)||i.userData.id==="floor"||i.userData.id==="grid"||i.userData.kind===X||i.children.some(l=>_optionalChain([l, 'access', _8 => _8.userData, 'optionalAccess', _9 => _9.kind])===X)||!i.geometry)return;let s=qe(i.geometry,t,n,o);i.add(s),a.push(s)}),a}function qe(e,r,t,n){let o=new $.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 s=new (0, _LineSegments2js.LineSegments2)(a,i);return s.userData.kind=X,s.raycast=()=>{},s}function Ze(e){return _optionalChain([e, 'access', _10 => _10.userData, 'optionalAccess', _11 => _11.kind])===X}function jn(e){let r=[];e.traverse(t=>{t instanceof _LineSegments2js.LineSegments2&&Ze(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 ge(e,r,t,n,o,a){let i=new (0, _EffectComposerjs.EffectComposer)(e),s=new (0, _RenderPassjs.RenderPass)(r,t);i.addPass(s);let l=new (0, _GTAOPassjs.GTAOPass)(r,t,n,o);l.blendIntensity=_nullishCoalesce(a.aoIntensity, () => (1)),l.updateGtaoMaterial({screenSpaceRadius:!0}),i.addPass(l);let c=new _OutputPassjs.OutputPass;return i.addPass(c),e.toneMapping=a.toneMapping,e.toneMappingExposure=a.toneMappingExposure,i.setSize(n,o),{render:u=>i.render(u),setSize:(u,d,m)=>{i.setPixelRatio(m),i.setSize(u,d),l.setSize(u,d)},setCamera:u=>{s.camera=u,l.camera=u},dispose:()=>i.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 be.Group;a.name="label-layer",a.userData.id="label-layer",r.add(a);let i=new Set;return{addLabel:(l,c,u)=>{let d=document.createElement("div");d.textContent=l,u?d.className=u:Object.assign(d.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"}),d.style.pointerEvents="none";let m=new (0, _CSS2DRendererjs.CSS2DObject)(d);return m.position.copy(c),a.add(m),i.add(m),{object:m,setPosition:E=>m.position.copy(E),setText:E=>{d.textContent=E},remove:()=>{m.removeFromParent(),d.remove(),i.delete(m)}}},render:(l,c)=>t.render(l,c),setSize:(l,c)=>t.setSize(l,c),dispose:()=>{i.forEach(l=>{l.removeFromParent(),l.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 it=12,st=16763904,Re=.015,q=e=>`${e.toPrecision(3)} m`,lt=(e,r)=>`${q(e)}
54
- \u0394x ${q(r.x)} \u0394y ${q(r.y)} \u0394z ${q(r.z)}`;function ct(e){let r=e.object;return r instanceof A.Mesh?e.face?[e.face.a,e.face.b,e.face.c]:null:r instanceof A.Points?e.index!=null?[e.index]:null:r instanceof A.Line&&e.index!=null?[e.index,e.index+1]:null}function ut(e,r,t,n){let o=e.point.clone(),a=e.object,i=ct(e);if(!i||!a.geometry)return o;let s=a.geometry.attributes.position;if(!s)return o;let l=m=>{let E=m.clone().project(r);return new A.Vector2((E.x+1)/2*t.width,(1-E.y)/2*t.height)},c=l(o),u=o,d=n;for(let m of i){if(m>=s.count)continue;let f=new A.Vector3().fromBufferAttribute(s,m).applyMatrix4(a.matrixWorld),x=l(f).distanceTo(c);x<d&&(d=x,u=f)}return u}function Te(e){let{canvas:r,scene:t,getActiveCamera:n,labelLayer:o,options:a={}}=e,i=_nullishCoalesce(a.snapPixels, () => (it)),s=new A.Color(_nullishCoalesce(a.color, () => (st))),l=_nullishCoalesce(a.format, () => (lt)),c=new A.Raycaster,u=new A.Vector2,d=!1,m=[],E=[],f=null,x=null,S=new A.PointsMaterial({color:s,size:8,sizeAttenuation:!1,depthTest:!1}),b=new A.PointsMaterial({color:s,size:11,sizeAttenuation:!1,depthTest:!1,transparent:!0,opacity:.5}),h=null,T=g=>{if(!g){h&&(h.visible=!1);return}if(!h){let R=new A.BufferGeometry;R.setAttribute("position",new A.Float32BufferAttribute([0,0,0],3)),h=new A.Points(R,b),h.renderOrder=1e3,h.userData.id="measure",h.raycast=()=>{},t.add(h)}h.position.copy(g),h.visible=!0},v=g=>{let R=new A.BufferGeometry;R.setAttribute("position",new A.Float32BufferAttribute([g.x,g.y,g.z],3));let H=new A.Points(R,S);return H.renderOrder=999,H.userData.id="measure",H.raycast=()=>{},t.add(H),H},P=()=>{m.length=0,E.forEach(g=>{g.geometry.dispose(),g.removeFromParent()}),E.length=0,f&&(f.geometry.dispose(),f.material.dispose(),f.removeFromParent(),f=null),_optionalChain([x, 'optionalAccess', _12 => _12.remove, 'call', _13 => _13()]),x=null},y=()=>{if(m.length!==2)return;let[g,R]=m,H=new _LineGeometryjs.LineGeometry;H.setPositions([g.x,g.y,g.z,R.x,R.y,R.z]);let k=new (0, _LineMaterialjs.LineMaterial)({color:s});k.linewidth=2,k.depthTest=!1,f=new (0, _Line2js.Line2)(H,k),f.renderOrder=998,f.userData.id="measure",f.raycast=()=>{},t.add(f);let N=g.clone().add(R).multiplyScalar(.5),W=new A.Vector3(Math.abs(R.x-g.x),Math.abs(R.y-g.y),Math.abs(R.z-g.z));x=o.addLabel(l(g.distanceTo(R),W),N,a.labelClassName)},w=g=>{let R=r.getBoundingClientRect();u.x=(g.clientX-R.left)/R.width*2-1,u.y=-((g.clientY-R.top)/R.height)*2+1;let H=n();c.setFromCamera(u,H);let k=H.position.length();c.params.Line={threshold:k*Re},c.params.Points={threshold:k*Re};let N=c.intersectObjects(t.children,!0).filter(W=>W.object.userData.id!=="measure"&&W.object.userData.id!=="grid");return N.length===0?null:ut(N[0],H,{width:R.width,height:R.height},i)};return{setEnabled:g=>{d=g,g||(P(),T(null))},isEnabled:()=>d,handleClick:g=>{if(!d)return!1;m.length===2&&P();let R=w(g);return R===null||(m.push(R),E.push(v(R)),m.length===2&&y()),!0},handleMove:g=>{d&&T(w(g))},clear:P,dispose:()=>{P(),h&&(h.geometry.dispose(),h.removeFromParent(),h=null),S.dispose(),b.dispose()}}}var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var Z=new p.Vector3(0,0,1);function Et(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 lr=function(e,r){let t=pt(r||{}),n=_optionalChain([t, 'access', _14 => _14.environment, 'optionalAccess', _15 => _15.sceneUp])||Z,o=bt(t),a=vt(t,e);a.up.copy(n);let i=Mt(e,t),s=xt(a,e,t),l=me({scene:o,perspective:a,controls:s,onActiveCameraChange:()=>{},up:n}),c=()=>l.getActiveCamera();Tt(o,t);let u=wt(o,t),d=()=>{u&&gt(u,ne(o))};_optionalChain([t, 'access', _16 => _16.floor, 'optionalAccess', _17 => _17.enabled])&&Ht(o,t);let m=t.grid.enabled?Ee({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 E=t.gizmo.enabled?pe({camera:a,domElement:e,controller:l}):null,f=_nullishCoalesce(e.parentElement, () => (e)),x=t.measure.enabled?ye(f,o):null,S=t.measure.enabled&&x?Te({canvas:e,scene:o,getActiveCamera:c,labelLayer:x,options:{snapPixels:t.measure.snapPixels,color:t.measure.color,labelClassName:t.measure.labelClassName,format:t.measure.format}}):null,b=t.events.enableEventHandlers!==!1?Ct(e,o,c,a,s,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},h=5,T=0,v=0,P=D=>{T=D.clientX,v=D.clientY},y=D=>Math.hypot(D.clientX-T,D.clientY-v)>h,w=D=>{if(!y(D)){if(_optionalChain([S, 'optionalAccess', _18 => _18.handleClick, 'call', _19 => _19(D)])){D.stopImmediatePropagation();return}_optionalChain([E, 'optionalAccess', _20 => _20.handleClick, 'call', _21 => _21(D)])&&D.stopImmediatePropagation()}};(E||S)&&(e.addEventListener("mousedown",P,{capture:!0}),e.addEventListener("click",w,{capture:!0}));let C=D=>_optionalChain([S, 'optionalAccess', _22 => _22.handleMove, 'call', _23 => _23(D)]);S&&e.addEventListener("mousemove",C,{passive:!0});let O=D=>{he(D,{color:t.edges.color,width:t.edges.width,thresholdAngle:t.edges.thresholdAngle})},g=e.parentElement,R=()=>g?{width:g.clientWidth,height:g.clientHeight}:{width:window.innerWidth,height:window.innerHeight},H=null,k=()=>{let{width:D,height:G}=R(),Q=Math.min(window.devicePixelRatio,2),le=ge(i,o,c(),Math.max(1,D),Math.max(1,G),{toneMapping:_nullishCoalesce(t.render.toneMapping, () => (p.NeutralToneMapping)),toneMappingExposure:_nullishCoalesce(t.render.toneMappingExposure, () => (1)),aoIntensity:t.render.aoIntensity});return le.setSize(Math.max(1,D),Math.max(1,G),Q),le},N=D=>{D&&!H?H=k():!D&&H&&(H.dispose(),H=null)};t.render.ambientOcclusion&&(H=k());let{animate:W,dispose:K}=Rt(i,o,a,c,l,s,R,t.events.onFrame,m,E,()=>H,x);return W(),o.up.set(n.x,n.y,n.z),d(),{scene:o,camera:a,controls:s,renderer:i,cameraController:l,grid:m,gizmo:E,measureTool:S,applyEdges:O,setAmbientOcclusion:N,updateShadowBounds:d,dispose:()=>{K(),b.dispose(),(E||S)&&(e.removeEventListener("mousedown",P,{capture:!0}),e.removeEventListener("click",w,{capture:!0})),S&&e.removeEventListener("mousemove",C),_optionalChain([S, 'optionalAccess', _24 => _24.dispose, 'call', _25 => _25()]),_optionalChain([x, 'optionalAccess', _26 => _26.dispose, 'call', _27 => _27()]),_optionalChain([E, 'optionalAccess', _28 => _28.dispose, 'call', _29 => _29()]),_optionalChain([m, 'optionalAccess', _30 => _30.dispose, 'call', _31 => _31()]),_optionalChain([H, 'optionalAccess', _32 => _32.dispose, 'call', _33 => _33()]),s.dispose(),i.dispose(),o.traverse(D=>{let G=D;!G.geometry&&!G.material||(_optionalChain([G, 'access', _34 => _34.geometry, 'optionalAccess', _35 => _35.dispose, 'call', _36 => _36()]),Array.isArray(G.material)?G.material.forEach(Q=>Q.dispose()):_optionalChain([G, 'access', _37 => _37.material, 'optionalAccess', _38 => _38.dispose, 'call', _39 => _39()]))})},fitToView:b.fitToView,clearSelection:b.clearSelection}};function pt(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', _40 => _40.camera, 'optionalAccess', _41 => _41.position])||new p.Vector3(-n.cameraDistance,-n.cameraDistance,n.cameraDistance),fov:_optionalChain([e, 'access', _42 => _42.camera, 'optionalAccess', _43 => _43.fov])||20,near:_optionalChain([e, 'access', _44 => _44.camera, 'optionalAccess', _45 => _45.near])||n.near,far:_optionalChain([e, 'access', _46 => _46.camera, 'optionalAccess', _47 => _47.far])||n.far,target:_optionalChain([e, 'access', _48 => _48.camera, 'optionalAccess', _49 => _49.target])||new p.Vector3(0,0,0)},lighting:{enableSunlight:_nullishCoalesce(_optionalChain([e, 'access', _50 => _50.lighting, 'optionalAccess', _51 => _51.enableSunlight]), () => (!0)),sunlightIntensity:_optionalChain([e, 'access', _52 => _52.lighting, 'optionalAccess', _53 => _53.sunlightIntensity])||1,sunlightPosition:_optionalChain([e, 'access', _54 => _54.lighting, 'optionalAccess', _55 => _55.sunlightPosition])||new p.Vector3(n.lightDistance,n.lightDistance,n.lightHeight),ambientLightColor:_optionalChain([e, 'access', _56 => _56.lighting, 'optionalAccess', _57 => _57.ambientLightColor])||new p.Color(4210752),ambientLightIntensity:_optionalChain([e, 'access', _58 => _58.lighting, 'optionalAccess', _59 => _59.ambientLightIntensity])||1,sunlightColor:_optionalChain([e, 'access', _60 => _60.lighting, 'optionalAccess', _61 => _61.sunlightColor])||16777215},environment:{hdrPath:_optionalChain([e, 'access', _62 => _62.environment, 'optionalAccess', _63 => _63.hdrPath])||"/baseHDR.hdr",backgroundColor:_optionalChain([e, 'access', _64 => _64.environment, 'optionalAccess', _65 => _65.backgroundColor])||new p.Color(15790320),enableEnvironmentLighting:_nullishCoalesce(_optionalChain([e, 'access', _66 => _66.environment, 'optionalAccess', _67 => _67.enableEnvironmentLighting]), () => (!0)),sceneUp:_optionalChain([e, 'access', _68 => _68.environment, 'optionalAccess', _69 => _69.sceneUp])||Z,showEnvironment:_nullishCoalesce(_optionalChain([e, 'access', _70 => _70.environment, 'optionalAccess', _71 => _71.showEnvironment]), () => (!1))},floor:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _72 => _72.floor, 'optionalAccess', _73 => _73.enabled]), () => (!1)),size:_optionalChain([e, 'access', _74 => _74.floor, 'optionalAccess', _75 => _75.size])||n.floorSize,color:_optionalChain([e, 'access', _76 => _76.floor, 'optionalAccess', _77 => _77.color])||new p.Color(8421504),roughness:_optionalChain([e, 'access', _78 => _78.floor, 'optionalAccess', _79 => _79.roughness])||.7,metalness:_optionalChain([e, 'access', _80 => _80.floor, 'optionalAccess', _81 => _81.metalness])||0,receiveShadow:_nullishCoalesce(_optionalChain([e, 'access', _82 => _82.floor, 'optionalAccess', _83 => _83.receiveShadow]), () => (!0))},render:{enableShadows:_nullishCoalesce(_optionalChain([e, 'access', _84 => _84.render, 'optionalAccess', _85 => _85.enableShadows]), () => (!0)),shadowMapSize:_optionalChain([e, 'access', _86 => _86.render, 'optionalAccess', _87 => _87.shadowMapSize])||2048,antialias:_nullishCoalesce(_optionalChain([e, 'access', _88 => _88.render, 'optionalAccess', _89 => _89.antialias]), () => (!0)),pixelRatio:_optionalChain([e, 'access', _90 => _90.render, 'optionalAccess', _91 => _91.pixelRatio])||Math.min(window.devicePixelRatio,2),toneMapping:_optionalChain([e, 'access', _92 => _92.render, 'optionalAccess', _93 => _93.toneMapping])||p.NeutralToneMapping,toneMappingExposure:_optionalChain([e, 'access', _94 => _94.render, 'optionalAccess', _95 => _95.toneMappingExposure])||1,preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _96 => _96.render, 'optionalAccess', _97 => _97.preserveDrawingBuffer]), () => (!1)),ambientOcclusion:_nullishCoalesce(_optionalChain([e, 'access', _98 => _98.render, 'optionalAccess', _99 => _99.ambientOcclusion]), () => (!1)),aoIntensity:_nullishCoalesce(_optionalChain([e, 'access', _100 => _100.render, 'optionalAccess', _101 => _101.aoIntensity]), () => (1))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _102 => _102.controls, 'optionalAccess', _103 => _103.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _104 => _104.controls, 'optionalAccess', _105 => _105.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _106 => _106.controls, 'optionalAccess', _107 => _107.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _108 => _108.controls, 'optionalAccess', _109 => _109.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _110 => _110.controls, 'optionalAccess', _111 => _111.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _112 => _112.controls, 'optionalAccess', _113 => _113.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _114 => _114.controls, 'optionalAccess', _115 => _115.minDistance])||n.minDistance,maxDistance:_optionalChain([e, 'access', _116 => _116.controls, 'optionalAccess', _117 => _117.maxDistance])||1/0},grid:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _118 => _118.grid, 'optionalAccess', _119 => _119.enabled]), () => (!1)),cellSize:_nullishCoalesce(_optionalChain([e, 'access', _120 => _120.grid, 'optionalAccess', _121 => _121.cellSize]), () => (1)),majorEvery:_nullishCoalesce(_optionalChain([e, 'access', _122 => _122.grid, 'optionalAccess', _123 => _123.majorEvery]), () => (10)),cellColor:_nullishCoalesce(_optionalChain([e, 'access', _124 => _124.grid, 'optionalAccess', _125 => _125.cellColor]), () => (8947848)),majorColor:_nullishCoalesce(_optionalChain([e, 'access', _126 => _126.grid, 'optionalAccess', _127 => _127.majorColor]), () => (4473924)),fadeDistance:_nullishCoalesce(_optionalChain([e, 'access', _128 => _128.grid, 'optionalAccess', _129 => _129.fadeDistance]), () => (100)),plane:_nullishCoalesce(_optionalChain([e, 'access', _130 => _130.grid, 'optionalAccess', _131 => _131.plane]), () => (Et(_nullishCoalesce(_optionalChain([e, 'access', _132 => _132.environment, 'optionalAccess', _133 => _133.sceneUp]), () => (Z)))))},gizmo:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _134 => _134.gizmo, 'optionalAccess', _135 => _135.enabled]), () => (!1))},edges:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _136 => _136.edges, 'optionalAccess', _137 => _137.enabled]), () => (!1)),color:_nullishCoalesce(_optionalChain([e, 'access', _138 => _138.edges, 'optionalAccess', _139 => _139.color]), () => (2236962)),width:_nullishCoalesce(_optionalChain([e, 'access', _140 => _140.edges, 'optionalAccess', _141 => _141.width]), () => (1.5)),thresholdAngle:_nullishCoalesce(_optionalChain([e, 'access', _142 => _142.edges, 'optionalAccess', _143 => _143.thresholdAngle]), () => (30))},measure:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _144 => _144.measure, 'optionalAccess', _145 => _145.enabled]), () => (!1)),snapPixels:_optionalChain([e, 'access', _146 => _146.measure, 'optionalAccess', _147 => _147.snapPixels]),color:_optionalChain([e, 'access', _148 => _148.measure, 'optionalAccess', _149 => _149.color]),labelClassName:_optionalChain([e, 'access', _150 => _150.measure, 'optionalAccess', _151 => _151.labelClassName]),format:_optionalChain([e, 'access', _152 => _152.measure, 'optionalAccess', _153 => _153.format])},events:{onBackgroundClicked:_optionalChain([e, 'access', _154 => _154.events, 'optionalAccess', _155 => _155.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _156 => _156.events, 'optionalAccess', _157 => _157.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _158 => _158.events, 'optionalAccess', _159 => _159.onMeshMetadataClicked]),onMeshDoubleClicked:_optionalChain([e, 'access', _160 => _160.events, 'optionalAccess', _161 => _161.onMeshDoubleClicked]),selectionColor:_optionalChain([e, 'access', _162 => _162.events, 'optionalAccess', _163 => _163.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _164 => _164.events, 'optionalAccess', _165 => _165.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _166 => _166.events, 'optionalAccess', _167 => _167.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _168 => _168.events, 'optionalAccess', _169 => _169.enableClickToFocus]), () => (!0)),enableDoubleClickZoom:_nullishCoalesce(_optionalChain([e, 'access', _170 => _170.events, 'optionalAccess', _171 => _171.enableDoubleClickZoom]), () => (!0)),onReady:_optionalChain([e, 'access', _172 => _172.events, 'optionalAccess', _173 => _173.onReady]),onFrame:_optionalChain([e, 'access', _174 => _174.events, 'optionalAccess', _175 => _175.onFrame])}}}var ft=new Set(["grid","floor","label-layer","measure"]);function ht(e){let r=e;for(;r;){if(typeof r.userData.id=="string"&&ft.has(r.userData.id))return!0;r=r.parent}return!1}function ne(e){let r=new p.Box3;return e.traverse(t=>{let n=t;t.visible&&!ht(t)&&n.geometry&&r.expandByObject(t)}),r}function gt(e,r){if(r.isEmpty())return;let t=r.getCenter(new p.Vector3),n=r.getSize(new p.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 bt(e){let r=new p.Scene,t=typeof e.environment.backgroundColor=="string"?new p.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=t||null,r}function yt(e,r,t,n,o=200){let a=e.position.clone(),i=r.target.clone(),s=performance.now(),l=u=>1-Math.pow(1-u,3),c=()=>{let u=performance.now()-s,d=l(Math.min(u/o,1));e.position.lerpVectors(a,t,d),r.target.lerpVectors(i,n,d),r.update(),d<1&&requestAnimationFrame(c)};requestAnimationFrame(c)}function Rt(e,r,t,n,o,a,i,s,l,c,u,d){let m=null,E=performance.now(),f=()=>{let{width:b,height:h}=i();if(b===0||h===0)return;let T=Math.min(window.devicePixelRatio,2),v=Math.round(b*T),P=Math.round(h*T);(e.domElement.width!==v||e.domElement.height!==P)&&(e.setPixelRatio(T),e.setSize(b,h,!1),t.aspect=b/h,t.updateProjectionMatrix(),o.updateAspect(b,h),_optionalChain([u, 'optionalCall', _176 => _176(), 'optionalAccess', _177 => _177.setSize, 'call', _178 => _178(b,h,T)]),_optionalChain([d, 'optionalAccess', _179 => _179.setSize, 'call', _180 => _180(b,h)]))},x=function(){m=requestAnimationFrame(x);let b=performance.now(),h=(b-E)/1e3;E=b,f(),(a.enableDamping||a.autoRotate)&&a.update(),l&&l.update(n().position),c&&c.update(h),_optionalChain([s, 'optionalCall', _181 => _181(h)]);let T=n(),v=_optionalChain([u, 'optionalCall', _182 => _182()]);v?(v.setCamera(T),v.render(h)):e.render(r,T),d&&d.render(r,T),c&&c.render(e)};return{animate:x,dispose:()=>{m!==null&&(cancelAnimationFrame(m),m=null)}}}function Tt(e,r){r.environment.enableEnvironmentLighting?new (0, _HDRLoaderjs.HDRLoader)().load(r.environment.hdrPath||"/baseHDR.hdr",function(t){if(!_optionalChain([t, 'optionalAccess', _183 => _183.image])){_chunk4UOOVSGLcjs.e.call(void 0, ).warn("HDR loaded without image data; skipping environment map."),_optionalChain([r, 'access', _184 => _184.events, 'access', _185 => _185.onReady, 'optionalCall', _186 => _186()]);return}t.mapping=p.EquirectangularReflectionMapping,e.environment=t,r.environment.showEnvironment&&(e.background=t),_optionalChain([r, 'access', _187 => _187.events, 'access', _188 => _188.onReady, 'optionalCall', _189 => _189()])},void 0,function(t){_chunk4UOOVSGLcjs.e.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",t),_optionalChain([r, 'access', _190 => _190.events, 'access', _191 => _191.onReady, 'optionalCall', _192 => _192()])}):_optionalChain([r, 'access', _193 => _193.events, 'access', _194 => _194.onReady, 'optionalCall', _195 => _195()])}function wt(e,r){let t=new p.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(t),!r.lighting.enableSunlight)return null;let n=new p.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 Ht(e,r){let t=r.floor.size,n=new p.PlaneGeometry(t,t),o=typeof r.floor.color=="string"?new p.Color(r.floor.color):r.floor.color,a=new p.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:p.DoubleSide}),i=new p.Mesh(n,a);i.userData.id="floor",i.name="floor";let s=(_optionalChain([r, 'access', _196 => _196.environment, 'optionalAccess', _197 => _197.sceneUp])||Z).clone().normalize();i.quaternion.setFromUnitVectors(new p.Vector3(0,0,1),s),i.position.set(0,0,0),r.floor.receiveShadow&&r.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function vt(e,r){let t=r.parentElement,n=t?t.clientWidth:window.innerWidth,o=t?t.clientHeight:window.innerHeight,a=new p.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 Mt(e,r){let t=new p.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=p.VSMShadowMap),t.toneMapping=r.render.toneMapping,t.toneMappingExposure=r.render.toneMappingExposure||1,t.outputColorSpace=p.SRGBColorSpace,t.sortObjects=!0,t}function Ct(e,r,t,n,o,a){let i=new Set,s=new Map,l=new p.Raycaster,c=new p.Vector2,u=new p.Vector2,d=y=>{let w=y;for(;w;){if(!w.visible)return!1;w=w.parent}return!0},m=()=>{let y=ne(r);if(y.isEmpty()){_chunk4UOOVSGLcjs.e.call(void 0, ).warn("No objects to fit to view");return}let w=y.getCenter(new p.Vector3),C=y.getSize(new p.Vector3),O=Math.max(C.x,C.y,C.z),g=n.fov*(Math.PI/180),R=O/(2*Math.tan(g/2));R*=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(R))),o.target.copy(w),o.update()},E=typeof a.events.selectionColor=="string"?new p.Color(a.events.selectionColor):a.events.selectionColor instanceof p.Color?a.events.selectionColor:new p.Color("#ff0000"),f=()=>{i.forEach(y=>{let w=y;if(s.has(y)){let C=s.get(y),O=w.material;O instanceof p.Material?O.dispose():Array.isArray(O)&&O.forEach(g=>g.dispose()),w.material=C,s.delete(y)}}),i.clear()},x=y=>{let w=y;if(!(w.material instanceof p.Material))return!1;s.set(y,w.material);let C=w.material.clone();return y instanceof p.Mesh&&"emissive"in C?C.emissive=E.clone():"color"in C&&(C.color=E.clone()),w.material=C,!0},S=()=>{let y=ne(r),w=y.isEmpty()?1:y.getSize(new p.Vector3).length();l.params.Points.threshold=w*.01},b=y=>{u.set(y.clientX,y.clientY)},h=y=>{let w=new p.Vector2(y.clientX,y.clientY);if(u.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,S(),l.setFromCamera(c,t());let O=l.intersectObjects(r.children,!0).filter(g=>d(g.object));if(O.length>0){let g=O[0].object;i.has(g)||(f(),i.add(g),x(g),_optionalChain([a, 'access', _198 => _198.events, 'optionalAccess', _199 => _199.onObjectSelected, 'optionalCall', _200 => _200(g)]),g instanceof p.Mesh&&Object.keys(g.userData).length>0&&_optionalChain([a, 'access', _201 => _201.events, 'optionalAccess', _202 => _202.onMeshMetadataClicked, 'optionalCall', _203 => _203(g.userData)]))}else f(),_optionalChain([a, 'access', _204 => _204.events, 'optionalAccess', _205 => _205.onBackgroundClicked, 'optionalCall', _206 => _206({x:c.x,y:c.y})])},T=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,S(),l.setFromCamera(c,t());let C=l.intersectObjects(r.children,!0).filter(D=>d(D.object));if(C.length===0)return;let O=C[0].object;if(_optionalChain([a, 'access', _207 => _207.events, 'optionalAccess', _208 => _208.onMeshDoubleClicked, 'optionalCall', _209 => _209(O)]),!_optionalChain([a, 'access', _210 => _210.events, 'optionalAccess', _211 => _211.enableDoubleClickZoom]))return;let g=new p.Box3().setFromObject(O);if(g.isEmpty())return;let R=g.getCenter(new p.Vector3),H=g.getSize(new p.Vector3),k=Math.max(H.x,H.y,H.z),N=n.fov*(Math.PI/180),W=k/(2*Math.tan(N/2))*1.5,K=n.position.clone().sub(o.target).normalize(),se=R.clone().add(K.multiplyScalar(W));yt(n,o,se,R)},v=y=>{if(_optionalChain([a, 'access', _212 => _212.events, 'optionalAccess', _213 => _213.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', _214 => _214.events, 'optionalAccess', _215 => _215.enableClickToFocus])&&(e.addEventListener("mousedown",b),e.addEventListener("click",h),e.addEventListener("dblclick",T)),_optionalChain([a, 'access', _216 => _216.events, 'optionalAccess', _217 => _217.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",v)),{dispose:()=>{e.removeEventListener("mousedown",b),e.removeEventListener("click",h),e.removeEventListener("dblclick",T),e.removeEventListener("keydown",v),f()},fitToView:m,clearSelection:f}}function xt(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 Vt={};_chunk4UOOVSGLcjs.a.call(void 0, Vt,{CONCRETE_MATERIAL:()=>Dt,EMISSIVE_MATERIAL:()=>St,GLASS_MATERIAL:()=>Pt,METAL_MATERIAL:()=>At,PLASTIC_MATERIAL:()=>Lt,RUBBER_MATERIAL:()=>Ot,WOOD_MATERIAL:()=>It});var St=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}),At=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}),Dt=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}),Lt=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}),Pt=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}),Ot=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}),It=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 J(e,r,t,n=!0){return{x:e,y:r,z:t}}var jt="#ffffff",re=12,kt=4e-4,_t=12,Ut=.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=Nt(a,t,n);i&&o.push(i);break}case"point":{o.push(Wt(a,n));break}default:{let i=a;_chunk4UOOVSGLcjs.e.call(void 0, ).warn(`Skipping unknown display item kind: ${String(i.kind)}`);break}}return o}var Gt=2;function Nt(e,r,t){if(!r)return _chunk4UOOVSGLcjs.e.call(void 0, ).warn("No rhino3dm instance provided; skipping curve display item."),null;let n=$t(e.json,r);if(!n)return null;let o=Yt(n,t);if(o.length<2)return null;let a=[];for(let d of o)a.push(d.x,d.y,d.z);let i=new _LineGeometryjs.LineGeometry;i.setPositions(a);let s=He(e.color,e.opacity),l=new (0, _LineMaterialjs.LineMaterial)({color:s.color}),c=l;c.linewidth=_nullishCoalesce(e.width, () => (Gt)),c.transparent=s.transparent,c.opacity=s.opacity;let u=new (0, _Line2js.Line2)(i,l);return u.computeLineDistances(),u.name=e.name,u.userData={id:e.id,layer:e.layer,kind:"curve",metadata:e.metadata},u}function Wt(e,r){let{x:t,y:n,z:o}=J(e.position.X,e.position.Y,e.position.Z,r),a=new j.BufferGeometry;a.setAttribute("position",new j.Float32BufferAttribute([t,n,o],3));let i=new j.PointsMaterial({...He(e.color,e.opacity),size:6,sizeAttenuation:!1}),s=new j.Points(a,i);return s.name=e.name,s.userData={id:e.id,layer:e.layer,kind:"point",metadata:e.metadata},s}function $t(e,r){try{let t=JSON.parse(e),n=r.CommonObject.decode(t);return n&&typeof n.pointAt=="function"?n:(_chunk4UOOVSGLcjs.e.call(void 0, ).warn("Decoded display-item JSON is not a curve; skipping."),null)}catch(t){return _chunk4UOOVSGLcjs.e.call(void 0, ).warn("Failed to decode curve display item JSON:",t),null}}function Yt(e,r){let t=Xt(e,r);return t||qt(e,r)}function Xt(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:s,y:l,z:c}=J(i[0],i[1],i[2],r);o.push(new j.Vector3(s,l,c))}return o}function qt(e,r){let t=e.domain,n=t[0],a=t[1]-n,i=c=>{let u=e.pointAt(c),{x:d,y:m,z:E}=J(u[0],u[1],u[2],r);return new j.Vector3(d,m,E)},s=Zt(e),l=[i(n)];for(let c=0;c<re;c++){let u=n+a*c/re,d=n+a*(c+1)/re;oe(u,i(u),d,i(d),i,s,_t,l),l.push(i(d))}return l}function oe(e,r,t,n,o,a,i,s){if(i<=0)return;let l=(e+t)/2,c=o(l),u=Kt(c,r,n),d=Jt(r,c,n);u<=a&&d<=Ut||(oe(e,r,l,c,o,a,i-1,s),s.push(c),oe(l,c,t,n,o,a,i-1,s))}function Zt(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*kt,1e-6)}function Jt(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 s=Math.max(-1,Math.min(1,n.dot(o)/(a*i)));return Math.acos(s)}function Kt(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 j.Color(_nullishCoalesce(e, () => (jt))),transparent:t<1,opacity:t}}var _fflate = require('fflate');var ve=1096174675,en=1515605075,Me= exports.t =2,Ce=1,ae= exports.u =1,tn=2,xe=12,Se=56;function ie(e){let r=rn(nn(e)),t=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.byteLength<xe)throw U("Blob too small to contain SLVA header.",{expectedBytes:xe,availableBytes:r.byteLength});let n=0,o=t.getUint32(n,!0);if(n+=4,o!==ve)throw U(`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<Ce||a>Me)throw U(`Unsupported SLVA version: ${a}`,{minSupportedVersion:Ce,maxSupportedVersion:Me,actualVersion:a});let i=t.getUint32(n,!0);if(n+=4,n+i>r.byteLength)throw U("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:r.byteLength-n,offset:n});let s=r.subarray(n,n+i);n+=i;let l;try{l=JSON.parse(on(s))}catch(H){throw U(`Failed to parse metadata JSON: ${H instanceof Error?H.message:String(H)}`,{metadataLen:i})}if(n+Se>r.byteLength)throw U("Insufficient data to read geometry header.",{expectedBytes:Se,availableBytes:r.byteLength-n,offset:n});let c=t.getUint32(n,!0);n+=4;let u=t.getFloat64(n,!0);n+=8;let d=t.getFloat64(n,!0);n+=8;let m=t.getFloat64(n,!0);n+=8;let E=t.getFloat64(n,!0);n+=8;let f=t.getFloat64(n,!0);n+=8;let x=t.getFloat64(n,!0);n+=8;let S=t.getUint32(n,!0);n+=4;let b=(c&ae)!==0,h=S*3,v=h*(b?4:2);if(n+v>r.byteLength)throw U("Insufficient data to read vertices.",{expectedBytes:v,availableBytes:r.byteLength-n,offset:n,useFloat32:b,vertexCount:S});let P=r.byteOffset+n,y=b?sn(r.buffer,P,h):an(r.buffer,P,h);if(n+=v,n+4>r.byteLength)throw U("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&tn)!==0,g=w*(C?2:4);if(n+g>r.byteLength)throw U("Insufficient data to read indices.",{expectedBytes:g,availableBytes:r.byteLength-n,offset:n,indexCount:w,useUint16Indices:C});let R=C?ln(r.buffer,r.byteOffset+n,w):cn(r.buffer,r.byteOffset+n,w);return{metadata:l,flags:c,vertices:y,indices:R,origin:[u,d,m],scale:[E,f,x]}}function nn(e){return typeof e=="string"?_chunk4UOOVSGLcjs.o.call(void 0, e):e instanceof Uint8Array?e:new Uint8Array(e)}function rn(e){if(e.byteLength<8)return e;let r=new DataView(e.buffer,e.byteOffset,e.byteLength);if(r.getUint32(0,!0)!==en)return e;let t=r.getUint32(4,!0),n=e.subarray(8);try{return _fflate.inflateSync.call(void 0, n,{out:new Uint8Array(t)})}catch(o){throw U(`Failed to inflate SLVZ blob: ${o instanceof Error?o.message:String(o)}`,{uncompressedLen:t,deflatedBytes:n.byteLength})}}function on(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, _chunk4UOOVSGLcjs.d)("No UTF-8 decoder available in this environment.",_chunk4UOOVSGLcjs.c.INVALID_STATE)}function an(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 sn(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 ln(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 cn(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 U(e,r){return new (0, _chunk4UOOVSGLcjs.d)(e,_chunk4UOOVSGLcjs.c.VALIDATION_ERROR,{context:r})}async function Ae(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 un(a,r,{parseTime:i,perfStart:n})}catch(o){return _chunk4UOOVSGLcjs.e.call(void 0, ).error("Error parsing mesh batch:",o),[]}}async function un(e,r,t){let{mergeByMaterial:n=!0,applyTransforms:o=!0,scaleFactor:a=1,debug:i=!1}=_nullishCoalesce(r, () => ({})),{parseTime:s=0,perfStart:l=i?performance.now():0}=_nullishCoalesce(t, () => ({}));try{let c=performance.now(),u=ie(e.compressedData),d=performance.now()-c,m=i?hn(e.compressedData):0;return De(u,{mergeByMaterial:n,applyTransforms:o,scaleFactor:a,debug:i,parseTime:s,decodeTime:d,perfStart:l,blobBytes:m,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}catch(c){return _chunk4UOOVSGLcjs.e.call(void 0, ).error("Error parsing mesh batch object:",c),[]}}async function vr(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,scaleFactor:o=1,debug:a=!1}=_nullishCoalesce(r, () => ({})),i=a?performance.now():0;try{let s=performance.now(),l=ie(e),c=performance.now()-s,u=e.byteLength;return De(l,{mergeByMaterial:t,applyTransforms:n,scaleFactor:o,debug:a,parseTime:0,decodeTime:c,perfStart:i,blobBytes:u})}catch(s){return _chunk4UOOVSGLcjs.e.call(void 0, ).error("Error parsing mesh batch blob:",s),[]}}function De(e,r){let{mergeByMaterial:t,applyTransforms:n,scaleFactor:o,debug:a,parseTime:i,decodeTime:s,perfStart:l,blobBytes:c,fallback:u}=r,d=_nullishCoalesce(_nullishCoalesce(e.metadata.materials, () => (_optionalChain([u, 'optionalAccess', _218 => _218.materials]))), () => ([])),m=_nullishCoalesce(_nullishCoalesce(e.metadata.groups, () => (_optionalChain([u, 'optionalAccess', _219 => _219.groups]))), () => ([])),E=_nullishCoalesce(_optionalChain([u, 'optionalAccess', _220 => _220.sourceComponentId]), () => (e.metadata.sourceComponentId)),f=(e.flags&ae)!==0,x=f?mn(e.vertices,n):dn(e.vertices,e.origin,e.scale,n);if(a){let v=e.vertices.byteLength+e.indices.byteLength;_chunk4UOOVSGLcjs.e.call(void 0, ).debug("Mesh Batch Stats:"),_chunk4UOOVSGLcjs.e.call(void 0, ).debug(` Materials: ${d.length} | Groups: ${m.length}`),_chunk4UOOVSGLcjs.e.call(void 0, ).debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),_chunk4UOOVSGLcjs.e.call(void 0, ).debug(` Format: ${f?"float32":"int16 quantized"}`),_chunk4UOOVSGLcjs.e.call(void 0, ).debug(` Blob: ${(c/1024/1024).toFixed(2)} MB | Geometry on wire: ${(v/1024/1024).toFixed(2)} MB`)}let S=performance.now(),b=d.map(En),h=[];for(let v of m)if(t&&v.meshes.length>1){let P=pn(v,x,e.indices,b);P.userData.sourceComponentId=_nullishCoalesce(E, () => (null)),h.push(P)}else{let P=fn(v,x,e.indices,b);for(let y of P)y.userData.sourceComponentId=_nullishCoalesce(E, () => (null));h.push(...P)}if(o!==1)for(let v of h)v.scale.set(o,o,o);let T=performance.now()-S;if(a){let v=performance.now()-l;_chunk4UOOVSGLcjs.e.call(void 0, ).debug("Performance:"),i>0&&_chunk4UOOVSGLcjs.e.call(void 0, ).debug(` Parse JSON: ${i.toFixed(2)}ms`),_chunk4UOOVSGLcjs.e.call(void 0, ).debug(` Decode binary: ${s.toFixed(2)}ms`),_chunk4UOOVSGLcjs.e.call(void 0, ).debug(` Create Meshes: ${T.toFixed(2)}ms`),_chunk4UOOVSGLcjs.e.call(void 0, ).debug(` Total: ${v.toFixed(2)}ms`)}return Promise.resolve(h)}function dn(e,r,t,n){let o=new Float32Array(e.length),a=r[0],i=r[1],s=r[2],l=t[0],c=t[1],u=t[2];for(let d=0;d<e.length;d+=3)o[d]=a+(e[d]+32767)*l,o[d+1]=i+(e[d+1]+32767)*c,o[d+2]=s+(e[d+2]+32767)*u;return o}function mn(e,r){return e}function En(e){let r=ue(e.color);return new B.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:B.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function pn(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),s=new Uint32Array(a),l=0,c=0;for(let f of e.meshes){let x=f.vertexStart*3,S=f.vertexCount*3;i.set(r.subarray(x,x+S),l*3);let b=t.subarray(f.indexStart,f.indexStart+f.indexCount),h=l-f.vertexStart;if(h===0)s.set(b,c);else for(let T=0;T<b.length;T++)s[c+T]=b[T]+h;l+=f.vertexCount,c+=f.indexCount}let u=new B.BufferGeometry;u.setAttribute("position",new B.BufferAttribute(i,3)),u.setIndex(new B.BufferAttribute(s,1)),u.computeVertexNormals();let d=new B.Mesh(u,n[e.materialId]),m=e.meshes[0],E=e.meshes.map(f=>f.name).filter(f=>f&&f.length>0);return d.name=E.length>0?E[0]:`merged_material_${e.materialId}`,d.castShadow=!0,d.receiveShadow=!0,d.userData={name:d.name,layer:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _221 => _221.layer]), () => ("")),originalIndex:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _222 => _222.originalIndex]), () => (0)),metadata:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _223 => _223.metadata]), () => ({})),mergedFrom:e.meshes.slice(1).map(f=>({name:f.name,layer:f.layer,originalIndex:f.originalIndex}))},d}function fn(e,r,t,n){let o=[];for(let a of e.meshes){let i=a.vertexStart*3,s=a.vertexCount*3,l=r.slice(i,i+s),c=t.subarray(a.indexStart,a.indexStart+a.indexCount),u=new Uint32Array(c.length),d=a.vertexStart;for(let f=0;f<c.length;f++)u[f]=c[f]-d;let m=new B.BufferGeometry;m.setAttribute("position",new B.BufferAttribute(l,3)),m.setIndex(new B.BufferAttribute(u,1)),m.computeVertexNormals();let E=new B.Mesh(m,n[e.materialId]);E.name=a.name,E.userData={name:a.name,layer:_nullishCoalesce(a.layer, () => ("")),originalIndex:a.originalIndex,metadata:_nullishCoalesce(a.metadata, () => ({}))},E.castShadow=!0,E.receiveShadow=!0,o.push(E)}return o}function hn(e){return Math.floor(e.length*3/4)}var gn={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},bn="Display";async function Dr(e,r){let t=performance.now(),n=[],{allowScaling:o=!0,allowAutoPosition:a=!0,rhino:i,debug:s=!1,parsing:l={}}=_nullishCoalesce(r, () => ({}));try{let c=o?yn(e.modelunits):1;return await Rn(e,n,c,l,i,s),a&&vn(n),n}catch(c){throw Mn(c,n),c}finally{s&&xn(t)}}function yn(e){return _nullishCoalesce(gn[e], () => (1))}async function Rn(e,r,t,n,o,a){for(let i of e.values){let s=i.InnerTree;for(let l in s){let c=s[l];c&&await Tn(c,r,t,n,o,a)}}}async function Tn(e,r,t,n,o,a){for(let i of e){if(!i.type.includes(bn))continue;let s={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...n},l=await Ae(i.data,s),c=we(wn(i.data),{rhino:o,applyTransforms:s.applyTransforms}),u=[...l,...c];if(t!==1)for(let d of u)d.scale.set(t,t,t);r.push(...u),a&&_chunk4UOOVSGLcjs.e.call(void 0, ).debug(`Extracted ${l.length} meshes and ${c.length} items from batch`)}}function wn(e){return_optionalChain([(typeof e=="string"?Hn(e):e), 'optionalAccess', _224 => _224.items])}function Hn(e){try{return JSON.parse(e)}catch (e4){return}}function vn(e){if(e.length===0)return;let r=Y(e);de(e,r.min.z,"z")}function Mn(e,r){_chunk4UOOVSGLcjs.e.call(void 0, ).error("An unexpected error occurred:",e),Cn(r)}function Cn(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 xn(e){let r=performance.now()-e;_chunk4UOOVSGLcjs.e.call(void 0, ).info("Time to process meshes:",`${r.toFixed(2)}ms`)}exports.a = An; exports.b = ue; exports.c = de; exports.d = Y; exports.e = me; exports.f = Ee; exports.g = pe; exports.h = X; exports.i = he; exports.j = Ze; exports.k = jn; exports.l = ge; exports.m = ye; exports.n = ut; exports.o = Te; exports.p = lr; exports.q = Vt; exports.r = we; exports.s = ve; exports.t = Me; exports.u = ae; exports.v = ie; exports.w = Ae; exports.x = un; exports.y = vr; exports.z = gn; exports.A = Dr;
55
- //# sourceMappingURL=chunk-KTWK7KQR.cjs.map
54
+ \u0394x ${q(r.x)} \u0394y ${q(r.y)} \u0394z ${q(r.z)}`;function ct(e){let r=e.object;return r instanceof A.Mesh?e.face?[e.face.a,e.face.b,e.face.c]:null:r instanceof A.Points?e.index!=null?[e.index]:null:r instanceof A.Line&&e.index!=null?[e.index,e.index+1]:null}function ut(e,r,t,n){let o=e.point.clone(),a=e.object,i=ct(e);if(!i||!a.geometry)return o;let s=a.geometry.attributes.position;if(!s)return o;let l=m=>{let E=m.clone().project(r);return new A.Vector2((E.x+1)/2*t.width,(1-E.y)/2*t.height)},c=l(o),u=o,d=n;for(let m of i){if(m>=s.count)continue;let f=new A.Vector3().fromBufferAttribute(s,m).applyMatrix4(a.matrixWorld),x=l(f).distanceTo(c);x<d&&(d=x,u=f)}return u}function Te(e){let{canvas:r,scene:t,getActiveCamera:n,labelLayer:o,options:a={}}=e,i=_nullishCoalesce(a.snapPixels, () => (it)),s=new A.Color(_nullishCoalesce(a.color, () => (st))),l=_nullishCoalesce(a.format, () => (lt)),c=new A.Raycaster,u=new A.Vector2,d=!1,m=[],E=[],f=null,x=null,S=new A.PointsMaterial({color:s,size:8,sizeAttenuation:!1,depthTest:!1}),b=new A.PointsMaterial({color:s,size:11,sizeAttenuation:!1,depthTest:!1,transparent:!0,opacity:.5}),h=null,T=g=>{if(!g){h&&(h.visible=!1);return}if(!h){let R=new A.BufferGeometry;R.setAttribute("position",new A.Float32BufferAttribute([0,0,0],3)),h=new A.Points(R,b),h.renderOrder=1e3,h.userData.id="measure",h.raycast=()=>{},t.add(h)}h.position.copy(g),h.visible=!0},v=g=>{let R=new A.BufferGeometry;R.setAttribute("position",new A.Float32BufferAttribute([g.x,g.y,g.z],3));let H=new A.Points(R,S);return H.renderOrder=999,H.userData.id="measure",H.raycast=()=>{},t.add(H),H},P=()=>{m.length=0,E.forEach(g=>{g.geometry.dispose(),g.removeFromParent()}),E.length=0,f&&(f.geometry.dispose(),f.material.dispose(),f.removeFromParent(),f=null),_optionalChain([x, 'optionalAccess', _12 => _12.remove, 'call', _13 => _13()]),x=null},y=()=>{if(m.length!==2)return;let[g,R]=m,H=new _LineGeometryjs.LineGeometry;H.setPositions([g.x,g.y,g.z,R.x,R.y,R.z]);let k=new (0, _LineMaterialjs.LineMaterial)({color:s});k.linewidth=2,k.depthTest=!1,f=new (0, _Line2js.Line2)(H,k),f.renderOrder=998,f.userData.id="measure",f.raycast=()=>{},t.add(f);let N=g.clone().add(R).multiplyScalar(.5),W=new A.Vector3(Math.abs(R.x-g.x),Math.abs(R.y-g.y),Math.abs(R.z-g.z));x=o.addLabel(l(g.distanceTo(R),W),N,a.labelClassName)},w=g=>{let R=r.getBoundingClientRect();u.x=(g.clientX-R.left)/R.width*2-1,u.y=-((g.clientY-R.top)/R.height)*2+1;let H=n();c.setFromCamera(u,H);let k=H.position.length();c.params.Line={threshold:k*Re},c.params.Points={threshold:k*Re};let N=c.intersectObjects(t.children,!0).filter(W=>W.object.userData.id!=="measure"&&W.object.userData.id!=="grid");return N.length===0?null:ut(N[0],H,{width:R.width,height:R.height},i)};return{setEnabled:g=>{d=g,g||(P(),T(null))},isEnabled:()=>d,handleClick:g=>{if(!d)return!1;m.length===2&&P();let R=w(g);return R===null||(m.push(R),E.push(v(R)),m.length===2&&y()),!0},handleMove:g=>{d&&T(w(g))},clear:P,dispose:()=>{P(),h&&(h.geometry.dispose(),h.removeFromParent(),h=null),S.dispose(),b.dispose()}}}var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var Z=new p.Vector3(0,0,1);function Et(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 lr=function(e,r){let t=pt(r||{}),n=_optionalChain([t, 'access', _14 => _14.environment, 'optionalAccess', _15 => _15.sceneUp])||Z,o=bt(t),a=vt(t,e);a.up.copy(n);let i=Mt(e,t),s=xt(a,e,t),l=me({scene:o,perspective:a,controls:s,onActiveCameraChange:()=>{},up:n}),c=()=>l.getActiveCamera();Tt(o,t);let u=wt(o,t),d=()=>{u&&gt(u,ne(o))};_optionalChain([t, 'access', _16 => _16.floor, 'optionalAccess', _17 => _17.enabled])&&Ht(o,t);let m=t.grid.enabled?Ee({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 E=t.gizmo.enabled?pe({camera:a,domElement:e,controller:l}):null,f=_nullishCoalesce(e.parentElement, () => (e)),x=t.measure.enabled?ye(f,o):null,S=t.measure.enabled&&x?Te({canvas:e,scene:o,getActiveCamera:c,labelLayer:x,options:{snapPixels:t.measure.snapPixels,color:t.measure.color,labelClassName:t.measure.labelClassName,format:t.measure.format}}):null,b=t.events.enableEventHandlers!==!1?Ct(e,o,c,a,s,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},h=5,T=0,v=0,P=D=>{T=D.clientX,v=D.clientY},y=D=>Math.hypot(D.clientX-T,D.clientY-v)>h,w=D=>{if(!y(D)){if(_optionalChain([S, 'optionalAccess', _18 => _18.handleClick, 'call', _19 => _19(D)])){D.stopImmediatePropagation();return}_optionalChain([E, 'optionalAccess', _20 => _20.handleClick, 'call', _21 => _21(D)])&&D.stopImmediatePropagation()}};(E||S)&&(e.addEventListener("mousedown",P,{capture:!0}),e.addEventListener("click",w,{capture:!0}));let C=D=>_optionalChain([S, 'optionalAccess', _22 => _22.handleMove, 'call', _23 => _23(D)]);S&&e.addEventListener("mousemove",C,{passive:!0});let O=D=>{he(D,{color:t.edges.color,width:t.edges.width,thresholdAngle:t.edges.thresholdAngle})},g=e.parentElement,R=()=>g?{width:g.clientWidth,height:g.clientHeight}:{width:window.innerWidth,height:window.innerHeight},H=null,k=()=>{let{width:D,height:G}=R(),Q=Math.min(window.devicePixelRatio,2),le=ge(i,o,c(),Math.max(1,D),Math.max(1,G),{toneMapping:_nullishCoalesce(t.render.toneMapping, () => (p.NeutralToneMapping)),toneMappingExposure:_nullishCoalesce(t.render.toneMappingExposure, () => (1)),aoIntensity:t.render.aoIntensity});return le.setSize(Math.max(1,D),Math.max(1,G),Q),le},N=D=>{D&&!H?H=k():!D&&H&&(H.dispose(),H=null)};t.render.ambientOcclusion&&(H=k());let{animate:W,dispose:K}=Rt(i,o,a,c,l,s,R,t.events.onFrame,m,E,()=>H,x);return W(),o.up.set(n.x,n.y,n.z),d(),{scene:o,camera:a,controls:s,renderer:i,cameraController:l,grid:m,gizmo:E,measureTool:S,applyEdges:O,setAmbientOcclusion:N,updateShadowBounds:d,dispose:()=>{K(),b.dispose(),(E||S)&&(e.removeEventListener("mousedown",P,{capture:!0}),e.removeEventListener("click",w,{capture:!0})),S&&e.removeEventListener("mousemove",C),_optionalChain([S, 'optionalAccess', _24 => _24.dispose, 'call', _25 => _25()]),_optionalChain([x, 'optionalAccess', _26 => _26.dispose, 'call', _27 => _27()]),_optionalChain([E, 'optionalAccess', _28 => _28.dispose, 'call', _29 => _29()]),_optionalChain([m, 'optionalAccess', _30 => _30.dispose, 'call', _31 => _31()]),_optionalChain([H, 'optionalAccess', _32 => _32.dispose, 'call', _33 => _33()]),s.dispose(),i.dispose(),o.traverse(D=>{let G=D;!G.geometry&&!G.material||(_optionalChain([G, 'access', _34 => _34.geometry, 'optionalAccess', _35 => _35.dispose, 'call', _36 => _36()]),Array.isArray(G.material)?G.material.forEach(Q=>Q.dispose()):_optionalChain([G, 'access', _37 => _37.material, 'optionalAccess', _38 => _38.dispose, 'call', _39 => _39()]))})},fitToView:b.fitToView,clearSelection:b.clearSelection}};function pt(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', _40 => _40.camera, 'optionalAccess', _41 => _41.position])||new p.Vector3(-n.cameraDistance,-n.cameraDistance,n.cameraDistance),fov:_optionalChain([e, 'access', _42 => _42.camera, 'optionalAccess', _43 => _43.fov])||20,near:_optionalChain([e, 'access', _44 => _44.camera, 'optionalAccess', _45 => _45.near])||n.near,far:_optionalChain([e, 'access', _46 => _46.camera, 'optionalAccess', _47 => _47.far])||n.far,target:_optionalChain([e, 'access', _48 => _48.camera, 'optionalAccess', _49 => _49.target])||new p.Vector3(0,0,0)},lighting:{enableSunlight:_nullishCoalesce(_optionalChain([e, 'access', _50 => _50.lighting, 'optionalAccess', _51 => _51.enableSunlight]), () => (!0)),sunlightIntensity:_optionalChain([e, 'access', _52 => _52.lighting, 'optionalAccess', _53 => _53.sunlightIntensity])||1,sunlightPosition:_optionalChain([e, 'access', _54 => _54.lighting, 'optionalAccess', _55 => _55.sunlightPosition])||new p.Vector3(n.lightDistance,n.lightDistance,n.lightHeight),ambientLightColor:_optionalChain([e, 'access', _56 => _56.lighting, 'optionalAccess', _57 => _57.ambientLightColor])||new p.Color(4210752),ambientLightIntensity:_optionalChain([e, 'access', _58 => _58.lighting, 'optionalAccess', _59 => _59.ambientLightIntensity])||1,sunlightColor:_optionalChain([e, 'access', _60 => _60.lighting, 'optionalAccess', _61 => _61.sunlightColor])||16777215},environment:{hdrPath:_optionalChain([e, 'access', _62 => _62.environment, 'optionalAccess', _63 => _63.hdrPath])||"/baseHDR.hdr",backgroundColor:_optionalChain([e, 'access', _64 => _64.environment, 'optionalAccess', _65 => _65.backgroundColor])||new p.Color(15790320),enableEnvironmentLighting:_nullishCoalesce(_optionalChain([e, 'access', _66 => _66.environment, 'optionalAccess', _67 => _67.enableEnvironmentLighting]), () => (!0)),sceneUp:_optionalChain([e, 'access', _68 => _68.environment, 'optionalAccess', _69 => _69.sceneUp])||Z,showEnvironment:_nullishCoalesce(_optionalChain([e, 'access', _70 => _70.environment, 'optionalAccess', _71 => _71.showEnvironment]), () => (!1))},floor:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _72 => _72.floor, 'optionalAccess', _73 => _73.enabled]), () => (!1)),size:_optionalChain([e, 'access', _74 => _74.floor, 'optionalAccess', _75 => _75.size])||n.floorSize,color:_optionalChain([e, 'access', _76 => _76.floor, 'optionalAccess', _77 => _77.color])||new p.Color(8421504),roughness:_optionalChain([e, 'access', _78 => _78.floor, 'optionalAccess', _79 => _79.roughness])||.7,metalness:_optionalChain([e, 'access', _80 => _80.floor, 'optionalAccess', _81 => _81.metalness])||0,receiveShadow:_nullishCoalesce(_optionalChain([e, 'access', _82 => _82.floor, 'optionalAccess', _83 => _83.receiveShadow]), () => (!0))},render:{enableShadows:_nullishCoalesce(_optionalChain([e, 'access', _84 => _84.render, 'optionalAccess', _85 => _85.enableShadows]), () => (!0)),shadowMapSize:_optionalChain([e, 'access', _86 => _86.render, 'optionalAccess', _87 => _87.shadowMapSize])||2048,antialias:_nullishCoalesce(_optionalChain([e, 'access', _88 => _88.render, 'optionalAccess', _89 => _89.antialias]), () => (!0)),pixelRatio:_optionalChain([e, 'access', _90 => _90.render, 'optionalAccess', _91 => _91.pixelRatio])||Math.min(window.devicePixelRatio,2),toneMapping:_optionalChain([e, 'access', _92 => _92.render, 'optionalAccess', _93 => _93.toneMapping])||p.NeutralToneMapping,toneMappingExposure:_optionalChain([e, 'access', _94 => _94.render, 'optionalAccess', _95 => _95.toneMappingExposure])||1,preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _96 => _96.render, 'optionalAccess', _97 => _97.preserveDrawingBuffer]), () => (!1)),ambientOcclusion:_nullishCoalesce(_optionalChain([e, 'access', _98 => _98.render, 'optionalAccess', _99 => _99.ambientOcclusion]), () => (!1)),aoIntensity:_nullishCoalesce(_optionalChain([e, 'access', _100 => _100.render, 'optionalAccess', _101 => _101.aoIntensity]), () => (1))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _102 => _102.controls, 'optionalAccess', _103 => _103.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _104 => _104.controls, 'optionalAccess', _105 => _105.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _106 => _106.controls, 'optionalAccess', _107 => _107.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _108 => _108.controls, 'optionalAccess', _109 => _109.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _110 => _110.controls, 'optionalAccess', _111 => _111.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _112 => _112.controls, 'optionalAccess', _113 => _113.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _114 => _114.controls, 'optionalAccess', _115 => _115.minDistance])||n.minDistance,maxDistance:_optionalChain([e, 'access', _116 => _116.controls, 'optionalAccess', _117 => _117.maxDistance])||1/0},grid:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _118 => _118.grid, 'optionalAccess', _119 => _119.enabled]), () => (!1)),cellSize:_nullishCoalesce(_optionalChain([e, 'access', _120 => _120.grid, 'optionalAccess', _121 => _121.cellSize]), () => (1)),majorEvery:_nullishCoalesce(_optionalChain([e, 'access', _122 => _122.grid, 'optionalAccess', _123 => _123.majorEvery]), () => (10)),cellColor:_nullishCoalesce(_optionalChain([e, 'access', _124 => _124.grid, 'optionalAccess', _125 => _125.cellColor]), () => (8947848)),majorColor:_nullishCoalesce(_optionalChain([e, 'access', _126 => _126.grid, 'optionalAccess', _127 => _127.majorColor]), () => (4473924)),fadeDistance:_nullishCoalesce(_optionalChain([e, 'access', _128 => _128.grid, 'optionalAccess', _129 => _129.fadeDistance]), () => (100)),plane:_nullishCoalesce(_optionalChain([e, 'access', _130 => _130.grid, 'optionalAccess', _131 => _131.plane]), () => (Et(_nullishCoalesce(_optionalChain([e, 'access', _132 => _132.environment, 'optionalAccess', _133 => _133.sceneUp]), () => (Z)))))},gizmo:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _134 => _134.gizmo, 'optionalAccess', _135 => _135.enabled]), () => (!1))},edges:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _136 => _136.edges, 'optionalAccess', _137 => _137.enabled]), () => (!1)),color:_nullishCoalesce(_optionalChain([e, 'access', _138 => _138.edges, 'optionalAccess', _139 => _139.color]), () => (2236962)),width:_nullishCoalesce(_optionalChain([e, 'access', _140 => _140.edges, 'optionalAccess', _141 => _141.width]), () => (1.5)),thresholdAngle:_nullishCoalesce(_optionalChain([e, 'access', _142 => _142.edges, 'optionalAccess', _143 => _143.thresholdAngle]), () => (30))},measure:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _144 => _144.measure, 'optionalAccess', _145 => _145.enabled]), () => (!1)),snapPixels:_optionalChain([e, 'access', _146 => _146.measure, 'optionalAccess', _147 => _147.snapPixels]),color:_optionalChain([e, 'access', _148 => _148.measure, 'optionalAccess', _149 => _149.color]),labelClassName:_optionalChain([e, 'access', _150 => _150.measure, 'optionalAccess', _151 => _151.labelClassName]),format:_optionalChain([e, 'access', _152 => _152.measure, 'optionalAccess', _153 => _153.format])},events:{onBackgroundClicked:_optionalChain([e, 'access', _154 => _154.events, 'optionalAccess', _155 => _155.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _156 => _156.events, 'optionalAccess', _157 => _157.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _158 => _158.events, 'optionalAccess', _159 => _159.onMeshMetadataClicked]),onMeshDoubleClicked:_optionalChain([e, 'access', _160 => _160.events, 'optionalAccess', _161 => _161.onMeshDoubleClicked]),selectionColor:_optionalChain([e, 'access', _162 => _162.events, 'optionalAccess', _163 => _163.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _164 => _164.events, 'optionalAccess', _165 => _165.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _166 => _166.events, 'optionalAccess', _167 => _167.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _168 => _168.events, 'optionalAccess', _169 => _169.enableClickToFocus]), () => (!0)),enableDoubleClickZoom:_nullishCoalesce(_optionalChain([e, 'access', _170 => _170.events, 'optionalAccess', _171 => _171.enableDoubleClickZoom]), () => (!0)),onReady:_optionalChain([e, 'access', _172 => _172.events, 'optionalAccess', _173 => _173.onReady]),onFrame:_optionalChain([e, 'access', _174 => _174.events, 'optionalAccess', _175 => _175.onFrame])}}}var ft=new Set(["grid","floor","label-layer","measure"]);function ht(e){let r=e;for(;r;){if(typeof r.userData.id=="string"&&ft.has(r.userData.id))return!0;r=r.parent}return!1}function ne(e){let r=new p.Box3;return e.traverse(t=>{let n=t;t.visible&&!ht(t)&&n.geometry&&r.expandByObject(t)}),r}function gt(e,r){if(r.isEmpty())return;let t=r.getCenter(new p.Vector3),n=r.getSize(new p.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 bt(e){let r=new p.Scene,t=typeof e.environment.backgroundColor=="string"?new p.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=t||null,r}function yt(e,r,t,n,o=200){let a=e.position.clone(),i=r.target.clone(),s=performance.now(),l=u=>1-Math.pow(1-u,3),c=()=>{let u=performance.now()-s,d=l(Math.min(u/o,1));e.position.lerpVectors(a,t,d),r.target.lerpVectors(i,n,d),r.update(),d<1&&requestAnimationFrame(c)};requestAnimationFrame(c)}function Rt(e,r,t,n,o,a,i,s,l,c,u,d){let m=null,E=performance.now(),f=()=>{let{width:b,height:h}=i();if(b===0||h===0)return;let T=Math.min(window.devicePixelRatio,2),v=Math.round(b*T),P=Math.round(h*T);(e.domElement.width!==v||e.domElement.height!==P)&&(e.setPixelRatio(T),e.setSize(b,h,!1),t.aspect=b/h,t.updateProjectionMatrix(),o.updateAspect(b,h),_optionalChain([u, 'optionalCall', _176 => _176(), 'optionalAccess', _177 => _177.setSize, 'call', _178 => _178(b,h,T)]),_optionalChain([d, 'optionalAccess', _179 => _179.setSize, 'call', _180 => _180(b,h)]))},x=function(){m=requestAnimationFrame(x);let b=performance.now(),h=(b-E)/1e3;E=b,f(),(a.enableDamping||a.autoRotate)&&a.update(),l&&l.update(n().position),c&&c.update(h),_optionalChain([s, 'optionalCall', _181 => _181(h)]);let T=n(),v=_optionalChain([u, 'optionalCall', _182 => _182()]);v?(v.setCamera(T),v.render(h)):e.render(r,T),d&&d.render(r,T),c&&c.render(e)};return{animate:x,dispose:()=>{m!==null&&(cancelAnimationFrame(m),m=null)}}}function Tt(e,r){r.environment.enableEnvironmentLighting?new (0, _HDRLoaderjs.HDRLoader)().load(r.environment.hdrPath||"/baseHDR.hdr",function(t){if(!_optionalChain([t, 'optionalAccess', _183 => _183.image])){_chunkXA4OMT6Zcjs.e.call(void 0, ).warn("HDR loaded without image data; skipping environment map."),_optionalChain([r, 'access', _184 => _184.events, 'access', _185 => _185.onReady, 'optionalCall', _186 => _186()]);return}t.mapping=p.EquirectangularReflectionMapping,e.environment=t,r.environment.showEnvironment&&(e.background=t),_optionalChain([r, 'access', _187 => _187.events, 'access', _188 => _188.onReady, 'optionalCall', _189 => _189()])},void 0,function(t){_chunkXA4OMT6Zcjs.e.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",t),_optionalChain([r, 'access', _190 => _190.events, 'access', _191 => _191.onReady, 'optionalCall', _192 => _192()])}):_optionalChain([r, 'access', _193 => _193.events, 'access', _194 => _194.onReady, 'optionalCall', _195 => _195()])}function wt(e,r){let t=new p.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(t),!r.lighting.enableSunlight)return null;let n=new p.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 Ht(e,r){let t=r.floor.size,n=new p.PlaneGeometry(t,t),o=typeof r.floor.color=="string"?new p.Color(r.floor.color):r.floor.color,a=new p.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:p.DoubleSide}),i=new p.Mesh(n,a);i.userData.id="floor",i.name="floor";let s=(_optionalChain([r, 'access', _196 => _196.environment, 'optionalAccess', _197 => _197.sceneUp])||Z).clone().normalize();i.quaternion.setFromUnitVectors(new p.Vector3(0,0,1),s),i.position.set(0,0,0),r.floor.receiveShadow&&r.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function vt(e,r){let t=r.parentElement,n=t?t.clientWidth:window.innerWidth,o=t?t.clientHeight:window.innerHeight,a=new p.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 Mt(e,r){let t=new p.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=p.VSMShadowMap),t.toneMapping=r.render.toneMapping,t.toneMappingExposure=r.render.toneMappingExposure||1,t.outputColorSpace=p.SRGBColorSpace,t.sortObjects=!0,t}function Ct(e,r,t,n,o,a){let i=new Set,s=new Map,l=new p.Raycaster,c=new p.Vector2,u=new p.Vector2,d=y=>{let w=y;for(;w;){if(!w.visible)return!1;w=w.parent}return!0},m=()=>{let y=ne(r);if(y.isEmpty()){_chunkXA4OMT6Zcjs.e.call(void 0, ).warn("No objects to fit to view");return}let w=y.getCenter(new p.Vector3),C=y.getSize(new p.Vector3),O=Math.max(C.x,C.y,C.z),g=n.fov*(Math.PI/180),R=O/(2*Math.tan(g/2));R*=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(R))),o.target.copy(w),o.update()},E=typeof a.events.selectionColor=="string"?new p.Color(a.events.selectionColor):a.events.selectionColor instanceof p.Color?a.events.selectionColor:new p.Color("#ff0000"),f=()=>{i.forEach(y=>{let w=y;if(s.has(y)){let C=s.get(y),O=w.material;O instanceof p.Material?O.dispose():Array.isArray(O)&&O.forEach(g=>g.dispose()),w.material=C,s.delete(y)}}),i.clear()},x=y=>{let w=y;if(!(w.material instanceof p.Material))return!1;s.set(y,w.material);let C=w.material.clone();return y instanceof p.Mesh&&"emissive"in C?C.emissive=E.clone():"color"in C&&(C.color=E.clone()),w.material=C,!0},S=()=>{let y=ne(r),w=y.isEmpty()?1:y.getSize(new p.Vector3).length();l.params.Points.threshold=w*.01},b=y=>{u.set(y.clientX,y.clientY)},h=y=>{let w=new p.Vector2(y.clientX,y.clientY);if(u.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,S(),l.setFromCamera(c,t());let O=l.intersectObjects(r.children,!0).filter(g=>d(g.object));if(O.length>0){let g=O[0].object;i.has(g)||(f(),i.add(g),x(g),_optionalChain([a, 'access', _198 => _198.events, 'optionalAccess', _199 => _199.onObjectSelected, 'optionalCall', _200 => _200(g)]),g instanceof p.Mesh&&Object.keys(g.userData).length>0&&_optionalChain([a, 'access', _201 => _201.events, 'optionalAccess', _202 => _202.onMeshMetadataClicked, 'optionalCall', _203 => _203(g.userData)]))}else f(),_optionalChain([a, 'access', _204 => _204.events, 'optionalAccess', _205 => _205.onBackgroundClicked, 'optionalCall', _206 => _206({x:c.x,y:c.y})])},T=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,S(),l.setFromCamera(c,t());let C=l.intersectObjects(r.children,!0).filter(D=>d(D.object));if(C.length===0)return;let O=C[0].object;if(_optionalChain([a, 'access', _207 => _207.events, 'optionalAccess', _208 => _208.onMeshDoubleClicked, 'optionalCall', _209 => _209(O)]),!_optionalChain([a, 'access', _210 => _210.events, 'optionalAccess', _211 => _211.enableDoubleClickZoom]))return;let g=new p.Box3().setFromObject(O);if(g.isEmpty())return;let R=g.getCenter(new p.Vector3),H=g.getSize(new p.Vector3),k=Math.max(H.x,H.y,H.z),N=n.fov*(Math.PI/180),W=k/(2*Math.tan(N/2))*1.5,K=n.position.clone().sub(o.target).normalize(),se=R.clone().add(K.multiplyScalar(W));yt(n,o,se,R)},v=y=>{if(_optionalChain([a, 'access', _212 => _212.events, 'optionalAccess', _213 => _213.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', _214 => _214.events, 'optionalAccess', _215 => _215.enableClickToFocus])&&(e.addEventListener("mousedown",b),e.addEventListener("click",h),e.addEventListener("dblclick",T)),_optionalChain([a, 'access', _216 => _216.events, 'optionalAccess', _217 => _217.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",v)),{dispose:()=>{e.removeEventListener("mousedown",b),e.removeEventListener("click",h),e.removeEventListener("dblclick",T),e.removeEventListener("keydown",v),f()},fitToView:m,clearSelection:f}}function xt(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 Vt={};_chunkXA4OMT6Zcjs.a.call(void 0, Vt,{CONCRETE_MATERIAL:()=>Dt,EMISSIVE_MATERIAL:()=>St,GLASS_MATERIAL:()=>Pt,METAL_MATERIAL:()=>At,PLASTIC_MATERIAL:()=>Lt,RUBBER_MATERIAL:()=>Ot,WOOD_MATERIAL:()=>It});var St=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}),At=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}),Dt=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}),Lt=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}),Pt=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}),Ot=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}),It=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 J(e,r,t,n=!0){return{x:e,y:r,z:t}}var jt="#ffffff",re=12,kt=4e-4,_t=12,Ut=.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=Nt(a,t,n);i&&o.push(i);break}case"point":{o.push(Wt(a,n));break}default:{let i=a;_chunkXA4OMT6Zcjs.e.call(void 0, ).warn(`Skipping unknown display item kind: ${String(i.kind)}`);break}}return o}var Gt=2;function Nt(e,r,t){if(!r)return _chunkXA4OMT6Zcjs.e.call(void 0, ).warn("No rhino3dm instance provided; skipping curve display item."),null;let n=$t(e.json,r);if(!n)return null;let o=Yt(n,t);if(o.length<2)return null;let a=[];for(let d of o)a.push(d.x,d.y,d.z);let i=new _LineGeometryjs.LineGeometry;i.setPositions(a);let s=He(e.color,e.opacity),l=new (0, _LineMaterialjs.LineMaterial)({color:s.color}),c=l;c.linewidth=_nullishCoalesce(e.width, () => (Gt)),c.transparent=s.transparent,c.opacity=s.opacity;let u=new (0, _Line2js.Line2)(i,l);return u.computeLineDistances(),u.name=e.name,u.userData={id:e.id,layer:e.layer,kind:"curve",metadata:e.metadata},u}function Wt(e,r){let{x:t,y:n,z:o}=J(e.position.X,e.position.Y,e.position.Z,r),a=new j.BufferGeometry;a.setAttribute("position",new j.Float32BufferAttribute([t,n,o],3));let i=new j.PointsMaterial({...He(e.color,e.opacity),size:6,sizeAttenuation:!1}),s=new j.Points(a,i);return s.name=e.name,s.userData={id:e.id,layer:e.layer,kind:"point",metadata:e.metadata},s}function $t(e,r){try{let t=JSON.parse(e),n=r.CommonObject.decode(t);return n&&typeof n.pointAt=="function"?n:(_chunkXA4OMT6Zcjs.e.call(void 0, ).warn("Decoded display-item JSON is not a curve; skipping."),null)}catch(t){return _chunkXA4OMT6Zcjs.e.call(void 0, ).warn("Failed to decode curve display item JSON:",t),null}}function Yt(e,r){let t=Xt(e,r);return t||qt(e,r)}function Xt(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:s,y:l,z:c}=J(i[0],i[1],i[2],r);o.push(new j.Vector3(s,l,c))}return o}function qt(e,r){let t=e.domain,n=t[0],a=t[1]-n,i=c=>{let u=e.pointAt(c),{x:d,y:m,z:E}=J(u[0],u[1],u[2],r);return new j.Vector3(d,m,E)},s=Zt(e),l=[i(n)];for(let c=0;c<re;c++){let u=n+a*c/re,d=n+a*(c+1)/re;oe(u,i(u),d,i(d),i,s,_t,l),l.push(i(d))}return l}function oe(e,r,t,n,o,a,i,s){if(i<=0)return;let l=(e+t)/2,c=o(l),u=Kt(c,r,n),d=Jt(r,c,n);u<=a&&d<=Ut||(oe(e,r,l,c,o,a,i-1,s),s.push(c),oe(l,c,t,n,o,a,i-1,s))}function Zt(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*kt,1e-6)}function Jt(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 s=Math.max(-1,Math.min(1,n.dot(o)/(a*i)));return Math.acos(s)}function Kt(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 j.Color(_nullishCoalesce(e, () => (jt))),transparent:t<1,opacity:t}}var _fflate = require('fflate');var ve=1096174675,en=1515605075,Me= exports.t =2,Ce=1,ae= exports.u =1,tn=2,xe=12,Se=56;function ie(e){let r=rn(nn(e)),t=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.byteLength<xe)throw U("Blob too small to contain SLVA header.",{expectedBytes:xe,availableBytes:r.byteLength});let n=0,o=t.getUint32(n,!0);if(n+=4,o!==ve)throw U(`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<Ce||a>Me)throw U(`Unsupported SLVA version: ${a}`,{minSupportedVersion:Ce,maxSupportedVersion:Me,actualVersion:a});let i=t.getUint32(n,!0);if(n+=4,n+i>r.byteLength)throw U("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:r.byteLength-n,offset:n});let s=r.subarray(n,n+i);n+=i;let l;try{l=JSON.parse(on(s))}catch(H){throw U(`Failed to parse metadata JSON: ${H instanceof Error?H.message:String(H)}`,{metadataLen:i})}if(n+Se>r.byteLength)throw U("Insufficient data to read geometry header.",{expectedBytes:Se,availableBytes:r.byteLength-n,offset:n});let c=t.getUint32(n,!0);n+=4;let u=t.getFloat64(n,!0);n+=8;let d=t.getFloat64(n,!0);n+=8;let m=t.getFloat64(n,!0);n+=8;let E=t.getFloat64(n,!0);n+=8;let f=t.getFloat64(n,!0);n+=8;let x=t.getFloat64(n,!0);n+=8;let S=t.getUint32(n,!0);n+=4;let b=(c&ae)!==0,h=S*3,v=h*(b?4:2);if(n+v>r.byteLength)throw U("Insufficient data to read vertices.",{expectedBytes:v,availableBytes:r.byteLength-n,offset:n,useFloat32:b,vertexCount:S});let P=r.byteOffset+n,y=b?sn(r.buffer,P,h):an(r.buffer,P,h);if(n+=v,n+4>r.byteLength)throw U("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&tn)!==0,g=w*(C?2:4);if(n+g>r.byteLength)throw U("Insufficient data to read indices.",{expectedBytes:g,availableBytes:r.byteLength-n,offset:n,indexCount:w,useUint16Indices:C});let R=C?ln(r.buffer,r.byteOffset+n,w):cn(r.buffer,r.byteOffset+n,w);return{metadata:l,flags:c,vertices:y,indices:R,origin:[u,d,m],scale:[E,f,x]}}function nn(e){return typeof e=="string"?_chunkXA4OMT6Zcjs.o.call(void 0, e):e instanceof Uint8Array?e:new Uint8Array(e)}function rn(e){if(e.byteLength<8)return e;let r=new DataView(e.buffer,e.byteOffset,e.byteLength);if(r.getUint32(0,!0)!==en)return e;let t=r.getUint32(4,!0),n=e.subarray(8);try{return _fflate.inflateSync.call(void 0, n,{out:new Uint8Array(t)})}catch(o){throw U(`Failed to inflate SLVZ blob: ${o instanceof Error?o.message:String(o)}`,{uncompressedLen:t,deflatedBytes:n.byteLength})}}function on(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, _chunkXA4OMT6Zcjs.d)("No UTF-8 decoder available in this environment.",_chunkXA4OMT6Zcjs.c.INVALID_STATE)}function an(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 sn(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 ln(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 cn(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 U(e,r){return new (0, _chunkXA4OMT6Zcjs.d)(e,_chunkXA4OMT6Zcjs.c.VALIDATION_ERROR,{context:r})}async function Ae(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 un(a,r,{parseTime:i,perfStart:n})}catch(o){return _chunkXA4OMT6Zcjs.e.call(void 0, ).error("Error parsing mesh batch:",o),[]}}async function un(e,r,t){let{mergeByMaterial:n=!0,applyTransforms:o=!0,scaleFactor:a=1,debug:i=!1}=_nullishCoalesce(r, () => ({})),{parseTime:s=0,perfStart:l=i?performance.now():0}=_nullishCoalesce(t, () => ({}));try{let c=performance.now(),u=ie(e.compressedData),d=performance.now()-c,m=i?hn(e.compressedData):0;return De(u,{mergeByMaterial:n,applyTransforms:o,scaleFactor:a,debug:i,parseTime:s,decodeTime:d,perfStart:l,blobBytes:m,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}catch(c){return _chunkXA4OMT6Zcjs.e.call(void 0, ).error("Error parsing mesh batch object:",c),[]}}async function vr(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,scaleFactor:o=1,debug:a=!1}=_nullishCoalesce(r, () => ({})),i=a?performance.now():0;try{let s=performance.now(),l=ie(e),c=performance.now()-s,u=e.byteLength;return De(l,{mergeByMaterial:t,applyTransforms:n,scaleFactor:o,debug:a,parseTime:0,decodeTime:c,perfStart:i,blobBytes:u})}catch(s){return _chunkXA4OMT6Zcjs.e.call(void 0, ).error("Error parsing mesh batch blob:",s),[]}}function De(e,r){let{mergeByMaterial:t,applyTransforms:n,scaleFactor:o,debug:a,parseTime:i,decodeTime:s,perfStart:l,blobBytes:c,fallback:u}=r,d=_nullishCoalesce(_nullishCoalesce(e.metadata.materials, () => (_optionalChain([u, 'optionalAccess', _218 => _218.materials]))), () => ([])),m=_nullishCoalesce(_nullishCoalesce(e.metadata.groups, () => (_optionalChain([u, 'optionalAccess', _219 => _219.groups]))), () => ([])),E=_nullishCoalesce(_optionalChain([u, 'optionalAccess', _220 => _220.sourceComponentId]), () => (e.metadata.sourceComponentId)),f=(e.flags&ae)!==0,x=f?mn(e.vertices,n):dn(e.vertices,e.origin,e.scale,n);if(a){let v=e.vertices.byteLength+e.indices.byteLength;_chunkXA4OMT6Zcjs.e.call(void 0, ).debug("Mesh Batch Stats:"),_chunkXA4OMT6Zcjs.e.call(void 0, ).debug(` Materials: ${d.length} | Groups: ${m.length}`),_chunkXA4OMT6Zcjs.e.call(void 0, ).debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),_chunkXA4OMT6Zcjs.e.call(void 0, ).debug(` Format: ${f?"float32":"int16 quantized"}`),_chunkXA4OMT6Zcjs.e.call(void 0, ).debug(` Blob: ${(c/1024/1024).toFixed(2)} MB | Geometry on wire: ${(v/1024/1024).toFixed(2)} MB`)}let S=performance.now(),b=d.map(En),h=[];for(let v of m)if(t&&v.meshes.length>1){let P=pn(v,x,e.indices,b);P.userData.sourceComponentId=_nullishCoalesce(E, () => (null)),h.push(P)}else{let P=fn(v,x,e.indices,b);for(let y of P)y.userData.sourceComponentId=_nullishCoalesce(E, () => (null));h.push(...P)}if(o!==1)for(let v of h)v.scale.set(o,o,o);let T=performance.now()-S;if(a){let v=performance.now()-l;_chunkXA4OMT6Zcjs.e.call(void 0, ).debug("Performance:"),i>0&&_chunkXA4OMT6Zcjs.e.call(void 0, ).debug(` Parse JSON: ${i.toFixed(2)}ms`),_chunkXA4OMT6Zcjs.e.call(void 0, ).debug(` Decode binary: ${s.toFixed(2)}ms`),_chunkXA4OMT6Zcjs.e.call(void 0, ).debug(` Create Meshes: ${T.toFixed(2)}ms`),_chunkXA4OMT6Zcjs.e.call(void 0, ).debug(` Total: ${v.toFixed(2)}ms`)}return Promise.resolve(h)}function dn(e,r,t,n){let o=new Float32Array(e.length),a=r[0],i=r[1],s=r[2],l=t[0],c=t[1],u=t[2];for(let d=0;d<e.length;d+=3)o[d]=a+(e[d]+32767)*l,o[d+1]=i+(e[d+1]+32767)*c,o[d+2]=s+(e[d+2]+32767)*u;return o}function mn(e,r){return e}function En(e){let r=ue(e.color);return new B.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:B.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function pn(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),s=new Uint32Array(a),l=0,c=0;for(let f of e.meshes){let x=f.vertexStart*3,S=f.vertexCount*3;i.set(r.subarray(x,x+S),l*3);let b=t.subarray(f.indexStart,f.indexStart+f.indexCount),h=l-f.vertexStart;if(h===0)s.set(b,c);else for(let T=0;T<b.length;T++)s[c+T]=b[T]+h;l+=f.vertexCount,c+=f.indexCount}let u=new B.BufferGeometry;u.setAttribute("position",new B.BufferAttribute(i,3)),u.setIndex(new B.BufferAttribute(s,1)),u.computeVertexNormals();let d=new B.Mesh(u,n[e.materialId]),m=e.meshes[0],E=e.meshes.map(f=>f.name).filter(f=>f&&f.length>0);return d.name=E.length>0?E[0]:`merged_material_${e.materialId}`,d.castShadow=!0,d.receiveShadow=!0,d.userData={name:d.name,layer:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _221 => _221.layer]), () => ("")),originalIndex:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _222 => _222.originalIndex]), () => (0)),metadata:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _223 => _223.metadata]), () => ({})),mergedFrom:e.meshes.slice(1).map(f=>({name:f.name,layer:f.layer,originalIndex:f.originalIndex}))},d}function fn(e,r,t,n){let o=[];for(let a of e.meshes){let i=a.vertexStart*3,s=a.vertexCount*3,l=r.slice(i,i+s),c=t.subarray(a.indexStart,a.indexStart+a.indexCount),u=new Uint32Array(c.length),d=a.vertexStart;for(let f=0;f<c.length;f++)u[f]=c[f]-d;let m=new B.BufferGeometry;m.setAttribute("position",new B.BufferAttribute(l,3)),m.setIndex(new B.BufferAttribute(u,1)),m.computeVertexNormals();let E=new B.Mesh(m,n[e.materialId]);E.name=a.name,E.userData={name:a.name,layer:_nullishCoalesce(a.layer, () => ("")),originalIndex:a.originalIndex,metadata:_nullishCoalesce(a.metadata, () => ({}))},E.castShadow=!0,E.receiveShadow=!0,o.push(E)}return o}function hn(e){return Math.floor(e.length*3/4)}var gn={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},bn="Display";async function Dr(e,r){let t=performance.now(),n=[],{allowScaling:o=!0,allowAutoPosition:a=!0,rhino:i,debug:s=!1,parsing:l={}}=_nullishCoalesce(r, () => ({}));try{let c=o?yn(e.modelunits):1;return await Rn(e,n,c,l,i,s),a&&vn(n),n}catch(c){throw Mn(c,n),c}finally{s&&xn(t)}}function yn(e){return _nullishCoalesce(gn[e], () => (1))}async function Rn(e,r,t,n,o,a){for(let i of e.values){let s=i.InnerTree;for(let l in s){let c=s[l];c&&await Tn(c,r,t,n,o,a)}}}async function Tn(e,r,t,n,o,a){for(let i of e){if(!i.type.includes(bn))continue;let s={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...n},l=await Ae(i.data,s),c=we(wn(i.data),{rhino:o,applyTransforms:s.applyTransforms}),u=[...l,...c];if(t!==1)for(let d of u)d.scale.set(t,t,t);r.push(...u),a&&_chunkXA4OMT6Zcjs.e.call(void 0, ).debug(`Extracted ${l.length} meshes and ${c.length} items from batch`)}}function wn(e){return_optionalChain([(typeof e=="string"?Hn(e):e), 'optionalAccess', _224 => _224.items])}function Hn(e){try{return JSON.parse(e)}catch (e4){return}}function vn(e){if(e.length===0)return;let r=Y(e);de(e,r.min.z,"z")}function Mn(e,r){_chunkXA4OMT6Zcjs.e.call(void 0, ).error("An unexpected error occurred:",e),Cn(r)}function Cn(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 xn(e){let r=performance.now()-e;_chunkXA4OMT6Zcjs.e.call(void 0, ).info("Time to process meshes:",`${r.toFixed(2)}ms`)}exports.a = An; exports.b = ue; exports.c = de; exports.d = Y; exports.e = me; exports.f = Ee; exports.g = pe; exports.h = X; exports.i = he; exports.j = Ze; exports.k = jn; exports.l = ge; exports.m = ye; exports.n = ut; exports.o = Te; exports.p = lr; exports.q = Vt; exports.r = we; exports.s = ve; exports.t = Me; exports.u = ae; exports.v = ie; exports.w = Ae; exports.x = un; exports.y = vr; exports.z = gn; exports.A = Dr;
55
+ //# sourceMappingURL=chunk-XXA7NEQF.cjs.map