@selvajs/compute 3.1.0-beta.3 → 3.1.0-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-54O6BO24.js +4 -0
- package/dist/chunk-54O6BO24.js.map +1 -0
- package/dist/chunk-7KFBCOZM.cjs +2 -0
- package/dist/chunk-7KFBCOZM.cjs.map +1 -0
- package/dist/chunk-EZRBMUXT.cjs +62 -0
- package/dist/chunk-EZRBMUXT.cjs.map +1 -0
- package/dist/chunk-GF6ZIJWX.cjs +4 -0
- package/dist/chunk-GF6ZIJWX.cjs.map +1 -0
- package/dist/chunk-ORGJSKR4.js +62 -0
- package/dist/chunk-ORGJSKR4.js.map +1 -0
- package/dist/chunk-PJATLYMU.js +2 -0
- package/dist/chunk-PJATLYMU.js.map +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.d.cts +40 -3
- package/dist/core.d.ts +40 -3
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.cjs.map +1 -1
- package/dist/grasshopper.d.cts +220 -20
- package/dist/grasshopper.d.ts +220 -20
- package/dist/grasshopper.js +1 -1
- package/dist/{handle-files-9pkEgDIp.d.cts → handle-files-DMnx92gr.d.cts} +46 -10
- package/dist/{handle-files-9pkEgDIp.d.ts → handle-files-DMnx92gr.d.ts} +46 -10
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/{types-V7G83j5m.d.cts → types-C9YpTbr3.d.cts} +27 -6
- package/dist/{types-V7G83j5m.d.ts → types-C9YpTbr3.d.ts} +27 -6
- package/dist/{types-B-JygDUF.d.ts → types-Ci8Z0-hF.d.cts} +92 -20
- package/dist/{types-DGeAQnkB.d.cts → types-DuOh5XqS.d.ts} +92 -20
- package/dist/visualization-C3YOGQTW.js +2 -0
- package/dist/visualization-CERJ6XDX.cjs +2 -0
- package/dist/visualization-CERJ6XDX.cjs.map +1 -0
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.d.cts +104 -13
- package/dist/visualization.d.ts +104 -13
- package/dist/visualization.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-CTZ4ZOSM.js +0 -2
- package/dist/chunk-CTZ4ZOSM.js.map +0 -1
- package/dist/chunk-EUMIGWRX.cjs +0 -4
- package/dist/chunk-EUMIGWRX.cjs.map +0 -1
- package/dist/chunk-HNG75VAI.js +0 -55
- package/dist/chunk-HNG75VAI.js.map +0 -1
- package/dist/chunk-JIE3W4KP.cjs +0 -2
- package/dist/chunk-JIE3W4KP.cjs.map +0 -1
- package/dist/chunk-L3CNT26S.cjs +0 -55
- package/dist/chunk-L3CNT26S.cjs.map +0 -1
- package/dist/chunk-QAOHGIFT.js +0 -4
- package/dist/chunk-QAOHGIFT.js.map +0 -1
- package/dist/visualization-SI2GEY4M.cjs +0 -2
- package/dist/visualization-SI2GEY4M.cjs.map +0 -1
- package/dist/visualization-UJZN4PJD.js +0 -2
- /package/dist/{visualization-UJZN4PJD.js.map → visualization-C3YOGQTW.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 M=Object.defineProperty;var Z=(t,e,r)=>e in t?M(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Ne=(t,e)=>{for(var r in e)M(t,r,{get:e[r],enumerable:!0})};var h=(t,e,r)=>Z(t,typeof e!="symbol"?e+"":e,r);var u={NETWORK_ERROR:"NETWORK_ERROR",AUTH_ERROR:"AUTH_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",COMPUTATION_ERROR:"COMPUTATION_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",CORS_ERROR:"CORS_ERROR",NOT_FOUND:"NOT_FOUND",RATE_LIMIT:"RATE_LIMIT",INVALID_RESPONSE:"INVALID_RESPONSE",UNKNOWN_ERROR:"UNKNOWN_ERROR",INVALID_STATE:"INVALID_STATE",INVALID_INPUT:"INVALID_INPUT",INVALID_CONFIG:"INVALID_CONFIG",BROWSER_ONLY:"BROWSER_ONLY",ENVIRONMENT_ERROR:"ENVIRONMENT_ERROR",ENCODING_ERROR:"ENCODING_ERROR",MALFORMED_DEFAULT:"MALFORMED_DEFAULT",SUPERSEDED:"SUPERSEDED",ABORTED:"ABORTED",QUEUE_FULL:"QUEUE_FULL",QUEUE_TIMEOUT:"QUEUE_TIMEOUT",DEFINITION_NOT_CACHED:"DEFINITION_NOT_CACHED"},p= exports.d =class t extends Error{constructor(r,n=u.UNKNOWN_ERROR,o){super(r);h(this,"code");h(this,"statusCode");h(this,"context");h(this,"originalError");this.name="RhinoComputeError",this.code=n,this.statusCode=_optionalChain([o, 'optionalAccess', _2 => _2.statusCode]),this.context=_optionalChain([o, 'optionalAccess', _3 => _3.context]),this.originalError=_optionalChain([o, 'optionalAccess', _4 => _4.originalError]),_optionalChain([o, 'optionalAccess', _5 => _5.originalError])&&(this.cause=o.originalError)}static missingValues(r,n,o){return new t(`Input "${r}" has no values defined${n?` (expected ${n})`:""}`,u.INVALID_INPUT,{context:{inputName:r,expectedType:n,...o}})}static unknownParamType(r,n,o){return new t(`Unknown paramType: ${r}`,u.VALIDATION_ERROR,{context:{receivedParamType:r,paramName:n,...o}})}};var O=class{debug(){}info(){}warn(){}error(){}},$=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)}},_=new O;function m(){return _}function F(t){if(t===null){_=new O;return}let e=["debug","info","warn","error"].filter(r=>typeof t[r]!="function");if(e.length>0)throw new p(`Logger is missing required method(s): ${e.join(", ")}. A logger must implement debug, info, warn and error.`,u.INVALID_CONFIG,{context:{missingMethods:e}});_=t}function Q(){F(new $)}function I(){let t=globalThis.Buffer;return typeof t=="function"?t:void 0}function Me(t){let e=I();return e?e.from(t,"utf-8").toString("base64"):te(new TextEncoder().encode(t))}var X=64,ee="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Fe(t){if(!t)return null;let e=t.replace(/[\t\n\f\r ]/g,"");e.length%4===0&&(e=e.replace(/={1,2}$/,""));let r=e.length%4;if(r===1||e.length<X||!/^[A-Za-z0-9+/]*$/.test(e))return null;let n=ee.indexOf(e.charAt(e.length-1));return r===2&&(n&15)!==0||r===3&&(n&3)!==0?null:r===0?e:e+"==".slice(0,4-r)}function k(t){let e=t.replace(/[\t\n\f\r ]/g,"");if(e.length%4===0&&(e=e.replace(/={1,2}$/,"")),e.length%4===1||!/^[A-Za-z0-9+/]*$/.test(e))throw new p("Invalid base64 input.",u.ENCODING_ERROR,{context:{inputLength:t.length}});let r=I();if(r)return new Uint8Array(r.from(e,"base64"));if(typeof globalThis.atob=="function"){let n=globalThis.atob(e),o=new Uint8Array(n.length);for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s)&255;return o}throw new p("Base64 decoding not supported in this environment.",u.INVALID_STATE,{context:{environmentInfo:"atob or Buffer not available"}})}function x(t){let e=I();if(e)return e.byteLength(t,"utf-8");let r=0;for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);o<128?r+=1:o<2048?r+=2:o>=55296&&o<=56319&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(r+=4,n++):r+=3}return r}function te(t){let e=I();if(e)return e.from(t).toString("base64");if(typeof globalThis.btoa=="function"){let n=[];for(let o=0;o<t.length;o+=32766)n.push(globalThis.btoa(String.fromCharCode.apply(null,t.subarray(o,o+32766))));return n.join("")}throw new p("Base64 encoding not supported in this environment.",u.INVALID_STATE,{context:{environmentInfo:"btoa or Buffer not available"}})}function re(t){if(!t)return null;let e={raw:t},r=!1;for(let n of t.split(",")){let[o,...s]=n.trim().split(";"),l=s.find(f=>f.trim().toLowerCase().startsWith("dur"));if(!l)continue;let i=Number(l.split("=")[1]);if(!Number.isFinite(i))continue;let a=o.trim().toLowerCase();(a==="decode"||a==="solve"||a==="encode")&&(e[a]=i,r=!0)}return r?e:null}var v={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},P=new Set([502,503,504]),ne=6e4,U=4096;function oe(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 se(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 C(t,e){let r=e.baseDelayMs*Math.pow(2,t),n=Math.random()*e.baseDelayMs;return Math.min(r+n,e.maxDelayMs)}function ie(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",s)]),r()},t),s=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))};_optionalChain([e, 'optionalAccess', _9 => _9.addEventListener, 'call', _10 => _10("abort",s,{once:!0})])})}function ae(t){return t.length<=U?t:`${t.slice(0,U)}\u2026 [truncated ${t.length-U} chars]`}function ue(t,e,r,n,o,s,l,i){let{status:a,statusText:f}=t,c={};t.headers.forEach((G,Y)=>{c[Y]=G});let g=s.trim(),d=g?` \u2014 ${g.slice(0,200)}${g.length>200?"\u2026":""}`:"",E=_nullishCoalesce(i, () => (s)),T={url:e,requestId:r,method:"POST",requestSize:n,serverUrl:o,responseBody:E?ae(E):void 0,responseHeaders:c},b={401:{message:`HTTP ${a}: ${f}${d}`,code:u.AUTH_ERROR},403:{message:`HTTP ${a}: ${f}${d}`,code:u.AUTH_ERROR},404:{message:`Endpoint not found: ${e}`,code:u.NOT_FOUND},413:{message:`Request too large: ${(n/1024).toFixed(2)}KB`,code:u.VALIDATION_ERROR},429:{message:`Rate limit exceeded${d}`,code:u.RATE_LIMIT},500:{message:`Server error: ${f}${d}`,code:u.COMPUTATION_ERROR},502:{message:`Service unavailable: ${f}${d}`,code:u.NETWORK_ERROR},503:{message:`Service unavailable: ${f}${d}`,code:u.NETWORK_ERROR},504:{message:`Service unavailable: ${f}${d}`,code:u.NETWORK_ERROR}}[a]||{message:`HTTP ${a}: ${f}${d}`,code:u.UNKNOWN_ERROR},D=_nullishCoalesce(le(l), () => (b.code));throw new p(b.message,D,{statusCode:a,context:T})}function le(t){if(t==="definition_not_cached")return u.DEFINITION_NOT_CACHED}function ce(t,e){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${r}/${n}`}function de(t){try{let e=new URL(t).hostname.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch (e2){return/(localhost|127\.0\.0\.1|\[::1\])/i.test(t)}}var B=new Set;function fe(t,e){let r={...e.headers,"X-Request-ID":t,"Content-Type":"application/json",...e.authToken&&{Authorization:e.authToken},...e.apiKey&&{RhinoComputeKey:e.apiKey}};return!e.apiKey&&!e.authToken&&!B.has(e.serverUrl)&&!de(e.serverUrl)&&(B.add(e.serverUrl),m().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. (warned once per server)`)),r}function pe(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function y(t,e){e&&m().debug(t)}function me(t,e){let r=()=>{},n=typeof e=="number"&&e>0;if(!t&&!n)return{signal:void 0,cleanup:r};if(t&&!n)return{signal:t,cleanup:r};let o=typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function";if(!t){if(o)return{signal:AbortSignal.timeout(e),cleanup:r};let c=new AbortController,g=setTimeout(()=>c.abort(),e);return{signal:c.signal,cleanup:()=>clearTimeout(g)}}let s=new AbortController,l,i;if(o)l=AbortSignal.timeout(e);else{let c=new AbortController;i=setTimeout(()=>c.abort(),e),l=c.signal}let a=[t,l],f=function(){s.abort(this.reason)};for(let c of a){if(c.aborted){s.abort(c.reason);break}c.addEventListener("abort",f,{once:!0})}return{signal:s.signal,cleanup:()=>{i!==void 0&&clearTimeout(i);for(let c of a)c.removeEventListener("abort",f)}}}function q(t,e,r,n){if(!r)return;let o=re(t.headers.get("Server-Timing"));if(o)try{r(o,e)}catch(s){n&&y(` onServerTiming callback threw: ${s}`,!0)}}async function ge(t,e,r,n,o,s,l,i){let a=Math.round(performance.now()-s);if(!t.ok){let f=await t.text(),c=f;l&&(y(`\u274C Request [${r}] failed with HTTP ${t.status} in ${a}ms`,!0),y(` URL: ${e}`,!0),y(` Status: ${t.status} ${t.statusText}`,!0),c&&y(` Response body: ${c.substring(0,500)}${c.length>500?"...":""}`,!0));let g;try{let d=JSON.parse(c);typeof _optionalChain([d, 'optionalAccess', _11 => _11.code])=="string"&&(g=d.code)}catch (e3){}if(t.status===500)try{let d=JSON.parse(c);if(_optionalChain([d, 'optionalAccess', _12 => _12.values])&&(d.errors||d.warnings))return l&&(y(`\u26A0\uFE0F Request [${r}] completed with Grasshopper errors in ${a}ms`,!0),_optionalChain([d, 'access', _13 => _13.errors, 'optionalAccess', _14 => _14.length])>0&&y(` Errors: ${JSON.stringify(d.errors,null,2)}`,!0),_optionalChain([d, 'access', _15 => _15.warnings, 'optionalAccess', _16 => _16.length])>0&&y(` Warnings: ${JSON.stringify(d.warnings,null,2)}`,!0)),q(t,r,i,l),d;let E=typeof _optionalChain([d, 'optionalAccess', _17 => _17.message])=="string"&&d.message||typeof _optionalChain([d, 'optionalAccess', _18 => _18.Message])=="string"&&d.Message||"",T=typeof _optionalChain([d, 'optionalAccess', _19 => _19.ExceptionType])=="string"&&d.ExceptionType||"",S=_nullishCoalesce(_optionalChain([d, 'optionalAccess', _20 => _20.stackTrace]), () => (_optionalChain([d, 'optionalAccess', _21 => _21.StackTrace]))),b=Array.isArray(S)?S.join(`
|
|
2
|
+
`):S||"";E?c=`${T?`${T}: `:""}${E}${b?`
|
|
3
|
+
${b}`:""}`:_optionalChain([d, 'optionalAccess', _22 => _22.error])&&(c=typeof d.error=="string"?d.error:JSON.stringify(d.error,null,2))}catch(d){l&&y(` Failed to parse error body as JSON: ${d}`,!0)}ue(t,e,r,n,o,c,g,f)}y(`\u2705 Request [${r}] completed in ${a}ms`,l),q(t,r,i,l);try{return await t.json()}catch(f){let c=(_nullishCoalesce(t.headers.get("Content-Type"), () => (""))).toLowerCase();throw c!==""&&!c.includes("json")?new p(`Server returned a non-JSON response (Content-Type: ${c}) \u2014 check the server URL / proxy configuration`,u.INVALID_RESPONSE,{statusCode:t.status,context:{url:e,requestId:r,contentType:c},originalError:f instanceof Error?f:new Error(String(f))}):new p("Failed to parse JSON response",u.NETWORK_ERROR,{statusCode:t.status,context:{url:e,requestId:r},originalError:f instanceof Error?f:new Error(String(f))})}}async function he(t,e,r,n){let{signal:o,cleanup:s}=me(t.config.signal,t.config.timeoutMs),l=performance.now();try{let i=await fetch(t.fullUrl,{method:"POST",body:t.body,headers:t.headers,signal:o});if((P.has(i.status)||e.retryOn429&&i.status===429)&&r<n-1){let c=se(i.headers.get("Retry-After")),g=c!==null?Math.min(c,Math.max(e.maxDelayMs,ne)):C(r,e);return await i.text().catch(()=>{}),{ok:!1,retry:!0,delayMs:g,cause:new p(`HTTP ${i.status} ${i.statusText} (will retry)`,i.status===429?u.RATE_LIMIT:u.NETWORK_ERROR,{statusCode:i.status,context:{requestId:t.requestId}})}}return{ok:!0,value:await ge(i,t.fullUrl,t.requestId,t.requestSize,t.config.serverUrl,l,t.config.debug,t.config.onServerTiming)}}catch(i){if(i instanceof Error&&(i.name==="AbortError"||i.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 p("Request aborted by caller",u.ABORTED,{context:{endpoint:t.endpoint,requestId:t.requestId,requestSize:t.requestSize},originalError:i})};let c=typeof t.config.timeoutMs=="number"&&t.config.timeoutMs>0?new p(`Request timed out after ${t.config.timeoutMs}ms`,u.TIMEOUT_ERROR,{context:{serverUrl:t.config.serverUrl,timeoutMs:t.config.timeoutMs,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:i}):new p(`Request aborted by the runtime (${i.name}): ${i.message}`,u.NETWORK_ERROR,{context:{serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:i});return r<n-1?{ok:!1,retry:!0,delayMs:C(r,e),cause:c}:{ok:!1,retry:!1,cause:c}}if(i instanceof TypeError){let a=typeof window<"u"&&typeof window.document<"u",f={serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},c=a?new p(`Request failed: ${i.message} \u2014 in a browser this usually means a CORS misconfiguration on the server (or a network failure; the browser does not distinguish them)`,u.CORS_ERROR,{context:f,originalError:i}):new p(`Network error: ${i.message}`,u.NETWORK_ERROR,{context:f,originalError:i});return r<n-1?{ok:!1,retry:!0,delayMs:C(r,e),cause:c}:{ok:!1,retry:!1,cause:c}}if(i instanceof p){let a=i.statusCode;return(i.code===u.NETWORK_ERROR&&a!==void 0&&a>=200&&a<300||a!==void 0&&(P.has(a)||e.retryOn429&&a===429))&&r<n-1?{ok:!1,retry:!0,delayMs:C(r,e),cause:i}:{ok:!1,retry:!1,cause:i}}return{ok:!1,retry:!1,cause:new p(i instanceof Error?i.message:String(i),u.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId},originalError:i instanceof Error?i:new Error(String(i))})}}finally{s()}}async function ye(t,e,r){let n=pe(),o=JSON.stringify(e),s=x(o),l=ce(t,r.serverUrl),i=fe(n,r),a=oe(r.retry),f=a.attempts+1;if(r.debug){let g=(s/1024).toFixed(2),d=s>1e5?"\u26A0\uFE0F":"\u{1F680}";y(`${d} Starting compute request [${n}]: ${t} (${g}KB)`,!0)}let c={endpoint:t,body:o,requestSize:s,fullUrl:l,requestId:n,headers:i,config:r};for(let g=0;;g++){let d=await he(c,a,g,f);if(d.ok)return d.value;if(!d.retry)throw d.cause;r.debug&&y(`\u{1F501} Request [${n}] retrying after ${d.delayMs}ms (attempt ${g+2}/${f}): ${d.cause.message}`,!0);try{await ie(d.delayMs,r.signal)}catch (e4){throw new p("Request aborted by caller",u.ABORTED,{context:{endpoint:t,requestId:n,requestSize:s},originalError:d.cause})}}}var Re="compute.rhino3d.com";function K(t){let e=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _26 => _26.trim, 'call', _27 => _27()]), () => (""));if(!e)throw new p("serverUrl is required",u.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(!/^https?:\/\//i.test(e))throw new p(`Invalid serverUrl: "${e}". Must start with "http://" or "https://". For example: "http://localhost:5000" or "https://example.com"`,u.INVALID_CONFIG,{context:{receivedServerUrl:t}});let r;try{r=new URL(e)}catch(o){throw new p(`Invalid serverUrl: "${e}". Must be a valid URL. Received error: ${o instanceof Error?o.message:String(o)}`,u.INVALID_CONFIG,{context:{receivedServerUrl:t},originalError:o instanceof Error?o:void 0})}if(r.username!==""||r.password!=="")throw new p(`Invalid serverUrl: "${e}". Must not embed credentials (user:pass@host) \u2014 fetch rejects credentialed URLs at request time. Pass the API key separately.`,u.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(e.includes("?")||e.includes("#"))throw new p(`Invalid serverUrl: "${e}". Must not contain a query string or fragment \u2014 endpoint paths are appended to this URL (e.g. "\${serverUrl}/version"), and a "?" or "#" suffix would corrupt every request path.`,u.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(r.hostname.toLowerCase().replace(/\.+$/,"")===Re)throw new p("serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.",u.INVALID_CONFIG,{context:{receivedServerUrl:t}});return e.replace(/\/+$/,"")}var R=class R{constructor(e,r){h(this,"serverUrl");h(this,"apiKey");h(this,"disposed",!1);h(this,"activeMonitors",new Set);h(this,"activeTimeouts",new Set);this.serverUrl=K(e),this.apiKey=r}buildHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,r={},n=R.DEFAULT_TIMEOUT_MS){let o=new Headers(this.buildHeaders());r.headers&&new Headers(r.headers).forEach((i,a)=>{o.set(a,i)});let s={};o.forEach((i,a)=>{s[a]=i});let l={...r,headers:s};return n>0&&!l.signal&&(l.signal=AbortSignal.timeout(n)),fetch(e,l)}async isServerOnline(e=5e3){this.ensureNotDisposed();let r=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(r,{method:"GET"},e)).ok}catch(n){return m().debug("[ComputeServerStats] Fetch error:",n),!1}}async getActiveChildren(e={}){this.ensureNotDisposed();let{initialize:r=!0}=e,n=r?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,o=r?R.LIFECYCLE_TIMEOUT_MS:R.DEFAULT_TIMEOUT_MS;try{let s=await this.fetchWithTimeout(n,{},o);if(!s.ok)return m().warn("[ComputeServerStats] Failed to fetch active children:",s.status),null;let l=(await s.text()).trim();return/^\d+$/.test(l)?parseInt(l,10):(m().warn("[ComputeServerStats] Invalid active children response:",l),null)}catch(s){return m().warn("[ComputeServerStats] Error fetching active children:",s),null}}async getVersion(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!e.ok)return m().warn("[ComputeServerStats] Failed to fetch version:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return{rhino:_nullishCoalesce(n.rhino, () => ("")),compute:_nullishCoalesce(n.compute, () => ("")),git_sha:_nullishCoalesce(n.git_sha, () => (null))}}catch (e5){return{rhino:r,compute:"",git_sha:null}}}catch(e){return m().warn("[ComputeServerStats] Error fetching version:",e),null}}async getInstalledPlugins(e="gh"){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${e}/installed`);if(!r.ok)return m().warn(`[ComputeServerStats] Failed to fetch ${e} plugins:`,r.status),null;let n=await r.text();try{let o=JSON.parse(n);return o&&typeof o=="object"?o:null}catch (e6){return null}}catch(r){return m().warn(`[ComputeServerStats] Error fetching ${e} plugins:`,r),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[r,n]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...r&&{version:r},...n!==null&&{activeChildren:n}}}async purgeCache(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:"POST"});if(!e.ok)return m().warn("[ComputeServerStats] Failed to purge cache:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return typeof n.purged=="number"?n.purged:null}catch (e7){return null}}catch(e){return m().warn("[ComputeServerStats] Error purging cache:",e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return m().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 s=await this.purgeCache();s!==null&&(n+=s)}return{totalPurged:n,calls:r,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!e.ok)return m().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 m().warn("[ComputeServerStats] Error fetching server time:",e),null}}async getIdleSpan(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);if(!e.ok)return m().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 m().warn("[ComputeServerStats] Error fetching idle span:",e),null}}async launchChildren(){return this.postJson("/launch-children")}async launchChild(e){let r=e===void 0?"/launch-child":`/launch-child?port=${e}`;return this.postJson(r)}async shutdownChildren(e){let r=e===void 0?"/shutdown-children":`/shutdown-children?port=${e}`;return this.postJson(r)}async recycleChildren(e){let r=e===void 0?"/recycle-children":`/recycle-children?port=${e}`;return this.postJson(r)}async postJson(e){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}${e}`,{method:"POST"},R.LIFECYCLE_TIMEOUT_MS);if(!r.ok)return m().warn(`[ComputeServerStats] POST ${e} failed:`,r.status),null;let n=await r.text();try{return JSON.parse(n)}catch (e8){return null}}catch(r){return m().warn(`[ComputeServerStats] Error on POST ${e}:`,r),null}}monitor(e,r=5e3){if(this.ensureNotDisposed(),!Number.isFinite(r)||r<R.MIN_MONITOR_INTERVAL_MS)throw new RangeError(`monitor() intervalMs must be a finite number >= ${R.MIN_MONITOR_INTERVAL_MS}ms, got ${r}. Sub-${R.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`);let n=!0,o=null;m().info(`\u{1F504} Starting server stats monitoring every ${r}ms`);let s=async()=>{if(o!==null&&(this.activeTimeouts.delete(o),o=null),!(!n||this.disposed)){try{let i=await this.getServerStats();if(!n||this.disposed)return;try{e(i)}catch(a){m().error("[ComputeServerStats] Monitor callback threw:",a)}}catch(i){!n||this.disposed?m().debug("[ComputeServerStats] Monitor poll cancelled during shutdown:",i):m().error("[ComputeServerStats] Failed to fetch stats during monitor:",i)}n&&!this.disposed&&(o=setTimeout(()=>{s()},r),this.activeTimeouts.add(o))}},l=()=>{n=!1,o!==null&&(clearTimeout(o),this.activeTimeouts.delete(o),o=null),this.activeMonitors.delete(l)};return this.activeMonitors.add(l),s(),l}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new p("ComputeServerStats has been disposed and cannot be used",u.INVALID_STATE,{context:{disposed:this.disposed}})}};h(R,"DEFAULT_TIMEOUT_MS",5e3),h(R,"LIFECYCLE_TIMEOUT_MS",6e4),h(R,"MIN_MONITOR_INTERVAL_MS",100);var N=R;function V(t,e={}){let{preserveSpaces:r=!1}=e,n=r?/[-_]+(.)?/g:/[\s\-_]+(.)?/g,o=t.trim().replace(n,(s,l)=>l?l.toUpperCase():"");return o=o.replace(/^[A-Z]+(?=[A-Z][a-z]|[^A-Za-z]|$)/,s=>s.toLowerCase()),o.charAt(0).toLowerCase()+o.slice(1)}function we(t){if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function L(t,e={}){if(!t||typeof t!="object")return t;if(Array.isArray(t))return e.deep?t.map(n=>L(n,e)):t;if(!we(t))return t;let r={};for(let n of Object.keys(t)){let o=V(n,{preserveSpaces:e.preserveSpaces});Object.prototype.hasOwnProperty.call(r,o)&&m().warn(`camelcaseKeys: key '${n}' collides with an earlier key on '${o}' \u2014 the earlier value is overwritten (last key wins).`);let s=t[n];r[o]=e.deep?L(s,e):s}return r}function w(t,e){if(!t||typeof t!="object")return;let r=t;if(z(r,e))return r[e];let n=H(r).get(e.toLowerCase());return n===void 0?void 0:r[n]}var z=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);function Ze(t,e){if(!t||typeof t!="object")return!1;let r=t;return z(r,e)?!0:H(r).has(e.toLowerCase())}var W=new WeakMap;function H(t){let e=Object.keys(t),r=W.get(t);if(r&&r.keyCount===e.length)return r.map;let n=new Map;for(let o of e){let s=o.toLowerCase();n.has(s)||n.set(s,o)}return W.set(t,{keyCount:e.length,map:n}),n}var Ee=async(t,e=null)=>{try{return await J(t,e)}catch(r){throw new p("Failed to extract files from compute response",u.INVALID_STATE,{context:{originalError:r instanceof Error?r.message:String(r)},originalError:r instanceof Error?r:void 0})}},be= exports.t =async(t,e,r=null)=>{if(typeof document>"u"||typeof Blob>"u")throw new p("File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).",u.BROWSER_ONLY,{context:{environment:typeof window<"u"?"browser (SSR)":"Node.js",documentAvailable:typeof document<"u",blobAvailable:typeof Blob<"u"}});try{let n=await J(t,r);await Ie(n,e)}catch(n){throw n instanceof p?n:new p("Failed to download files from compute response",u.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}},A=t=>t.replace(/\\/g,"/").split("/").map(e=>e.trim()).filter(e=>e!==""&&e!=="."&&e!==".."&&!/^[a-zA-Z]:$/.test(e)).join("/"),ve=t=>t===!0||typeof t=="string"&&t.trim().toLowerCase()==="true",Te=t=>{let e=[];return t.forEach(r=>{let n=_nullishCoalesce(w(r,"fileName"), () => ("")),o=_nullishCoalesce(w(r,"fileType"), () => ("")),s=A(`${n}${o}`);if(s===""){m().warn(`Skipping file with unusable name "${n}${o}": no safe archive path remains after sanitization.`);return}let l=w(r,"subFolder"),i=l?A(l):"",a=i!==""?`${i}/${s}`:s,f=w(r,"data");if(typeof f!="string"||f===""){m().warn(`Skipping file "${a}": item carries no usable data.`);return}if(ve(w(r,"isBase64Encoded")))try{e.push({fileName:s,content:k(f),path:a})}catch(c){m().warn(`Skipping file "${a}": base64 decode failed.`,c)}else e.push({fileName:s,content:f,path:a})}),e},Se=3e4,Oe=async t=>(await Promise.all(t.map(async r=>{try{let n=typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function"?AbortSignal.timeout(Se):void 0,o=await fetch(r.filePath,{signal:n});if(!o.ok)return m().warn(`Failed to fetch additional file from URL: ${r.filePath}`),null;let s=await o.arrayBuffer(),l=A(r.fileName);if(l==="")return m().warn(`Skipping fetched file with unusable name: ${r.fileName}`),null;let i=r.subFolder?A(r.subFolder):"";return{fileName:l,content:new Uint8Array(s),path:i!==""?`${i}/${l}`:l}}catch(n){return m().error(`Error fetching additional file from URL: ${r.filePath}`,n),null}}))).filter(r=>r!==null),J=async(t,e)=>{let r=Te(t);if(e){let o=Array.isArray(e)?e:[e];r.push(...await Oe(o))}let n=new Set;return r.map(o=>{let s=j(o.path,n);return n.add(s),s===o.path?o:(m().warn(`Duplicate archive path "${o.path}" \u2014 storing as "${s}".`),{...o,path:s,fileName:s.slice(s.lastIndexOf("/")+1)})})};async function Ie(t,e){let{zip:r,strToU8:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("fflate"))),o={},s=new Set;t.forEach(a=>{let f=j(a.path,s);s.add(f),f!==a.path&&m().warn(`Duplicate archive path "${a.path}" \u2014 storing as "${f}".`),o[f]=typeof a.content=="string"?n(a.content):a.content});let l=await new Promise((a,f)=>{r(o,{level:6},(c,g)=>c?f(c):a(g))}),i=new Blob([l],{type:"application/zip"});Ce(i,`${e}.zip`)}function j(t,e){if(!e.has(t))return t;let r=t.lastIndexOf("/"),n=t.lastIndexOf("."),o=n>r?n:t.length,s=t.slice(0,o),l=t.slice(o);for(let i=2;;i++){let a=`${s}-${i}${l}`;if(!e.has(a))return a}}function Ce(t,e){if(typeof document>"u")throw new p("saveFile requires a browser environment with DOM API access.",u.BROWSER_ONLY,{context:{function:"saveFile",requiredAPI:"document"}});let r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=e,document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(r),1e4)}exports.a = Ne; exports.b = h; exports.c = u; exports.d = p; exports.e = m; exports.f = F; exports.g = Q; exports.h = Me; exports.i = Fe; exports.j = k; exports.k = te; exports.l = ye; exports.m = K; exports.n = N; exports.o = V; exports.p = L; exports.q = w; exports.r = Ze; exports.s = Ee; exports.t = be;
|
|
4
|
+
//# sourceMappingURL=chunk-GF6ZIJWX.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-GF6ZIJWX.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,CAEZ,SAAA,CAAW,WAAA,CAEX,UAAA,CAAY,YAAA,CAOZ,gBAAA,CAAkB,kBAAA,CAClB,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,CAOT,UAAA,CAAY,YAAA,CAMZ,aAAA,CAAe,eAAA,CAQf,qBAAA,CAAuB,uBACxB,CAAA,CASaC,CAAAA,aAAN,MAAMC,EAAAA,QAA0B,KAAM,CAM5C,WAAA,CACCC,CAAAA,CACAC,CAAAA,CAAkBJ,CAAAA,CAAW,aAAA,CAC7BK,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;ACsWzC;AA0IT","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-GF6ZIJWX.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\t/** HTTP 404 — the endpoint path does not exist on the server (usually a typo'd route or wrong server). Never retried. */\n\tNOT_FOUND: 'NOT_FOUND',\n\t/** HTTP 429 — the server is rate-limiting requests. Retried by default (honors `Retry-After`); see `RetryPolicy.retryOn429`. */\n\tRATE_LIMIT: 'RATE_LIMIT',\n\t/**\n\t * The server answered 2xx but the body is deterministically not JSON (the\n\t * response declared a non-JSON `Content-Type`, e.g. an HTML captive-portal or\n\t * proxy login page, or a misconfigured endpoint). Never retried — refetching\n\t * returns the same page.\n\t */\n\tINVALID_RESPONSE: 'INVALID_RESPONSE',\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 * Scheduler backpressure: the queue was already at `maxQueueDepth` when this\n\t * call arrived, so it was shed immediately rather than queued. Retryable — the\n\t * caller (or an HTTP layer, as 503 + Retry-After) should back off and retry.\n\t * The error `context` carries `{ queueDepth, maxQueueDepth }`.\n\t */\n\tQUEUE_FULL: 'QUEUE_FULL',\n\t/**\n\t * Scheduler backpressure: this call sat queued longer than `queueWaitMs`\n\t * without starting, so it was shed before wasting compute on a stale request.\n\t * Retryable. The error `context` carries `{ waitedMs, queueWaitMs }`.\n\t */\n\tQUEUE_TIMEOUT: 'QUEUE_TIMEOUT',\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: ErrorCode;\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: ErrorCode = ErrorCodes.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';\nimport { utf8ByteLength } from '../utils/encoding';\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\n/**\n * Absolute ceiling for a server-supplied `Retry-After` wait. The server's\n * stated window wins over `retryPolicy.maxDelayMs` (retrying earlier all but\n * guarantees another 429), but a bad/hostile header must not park the client\n * for minutes — anything above this cap is clamped.\n */\nconst RETRY_AFTER_CAP_MS = 60_000;\n\n/** Upper bound for the raw server body stored on error `context.responseBody`. */\nconst MAX_CONTEXT_BODY_CHARS = 4096;\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\n/** Truncate a server body for storage on error context — bounded, with an honest marker. */\nfunction truncateBody(body: string): string {\n\tif (body.length <= MAX_CONTEXT_BODY_CHARS) return body;\n\treturn `${body.slice(0, MAX_CONTEXT_BODY_CHARS)}… [truncated ${body.length - MAX_CONTEXT_BODY_CHARS} chars]`;\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\trawBody?: 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\t// context.responseBody holds the RAW server body (what actually came over the\n\t// wire), bounded to MAX_CONTEXT_BODY_CHARS so a huge body isn't pinned for the\n\t// error's lifetime. `errorBody` may have been rewritten into a synthesized\n\t// message (500 exception shape) — that goes in the message, not the context.\n\tconst storedBody = rawBody ?? errorBody;\n\tconst context = {\n\t\turl: fullUrl,\n\t\trequestId,\n\t\tmethod: 'POST',\n\t\trequestSize,\n\t\tserverUrl,\n\t\tresponseBody: storedBody ? truncateBody(storedBody) : undefined,\n\t\tresponseHeaders\n\t};\n\n\tconst errorMap: Record<number, { message: string; code: ErrorCode }> = {\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.NOT_FOUND },\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.RATE_LIMIT },\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\t// `hostname` (not `host`) strips the port; IPv6 hostnames keep their\n\t\t// brackets, so `http://[::1]:6500` yields `[::1]`.\n\t\tconst hostname = new URL(serverUrl).hostname.toLowerCase();\n\t\treturn hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]';\n\t} catch {\n\t\treturn /(localhost|127\\.0\\.0\\.1|\\[::1\\])/i.test(serverUrl);\n\t}\n}\n\n/** Server URLs already warned about missing auth — warn once per server, not per request. */\nconst warnedNoAuth = new Set<string>();\n\nfunction buildHeaders(requestId: string, config: ComputeConfig): HeadersInit {\n\tconst headers: HeadersInit = {\n\t\t// Caller headers first so the transport's own headers below OVERWRITE them —\n\t\t// a caller can never clobber the request id, content type, or auth.\n\t\t...config.headers,\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 (\n\t\t!config.apiKey &&\n\t\t!config.authToken &&\n\t\t!warnedNoAuth.has(config.serverUrl) &&\n\t\t!isLocalhost(config.serverUrl)\n\t) {\n\t\twarnedNoAuth.add(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. (warned once per server)`\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 noCleanup = () => {};\n\tconst wantsTimeout = typeof timeoutMs === 'number' && timeoutMs > 0;\n\n\tif (!callerSignal && !wantsTimeout) return { signal: undefined, cleanup: noCleanup };\n\tif (callerSignal && !wantsTimeout) return { signal: callerSignal, cleanup: noCleanup };\n\n\tconst supportsTimeout =\n\t\ttypeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function';\n\n\t// Timeout only: nothing is registered on a caller signal, so there is nothing to clean up on\n\t// the modern path (the pending timer is small and self-expires at timeoutMs).\n\tif (!callerSignal) {\n\t\tif (supportsTimeout) return { signal: AbortSignal.timeout(timeoutMs!), cleanup: noCleanup };\n\t\tconst ctrl = new AbortController();\n\t\tconst id = setTimeout(() => ctrl.abort(), timeoutMs);\n\t\treturn { signal: ctrl.signal, cleanup: () => clearTimeout(id) };\n\t}\n\n\t// Caller signal + timeout: composed manually rather than with AbortSignal.any — `any` offers no\n\t// way to unregister its dependent link on the caller's signal, so an app reusing one long-lived\n\t// signal across many solves accumulates a registration per attempt for the full timeoutMs after\n\t// each response (and forever on Node versions with the known AbortSignal.any leak).\n\tconst ctrl = new AbortController();\n\n\tlet timeoutSignal: AbortSignal;\n\tlet timerId: ReturnType<typeof setTimeout> | undefined;\n\tif (supportsTimeout) {\n\t\ttimeoutSignal = AbortSignal.timeout(timeoutMs!);\n\t} else {\n\t\tconst timeoutCtrl = new AbortController();\n\t\ttimerId = setTimeout(() => timeoutCtrl.abort(), timeoutMs);\n\t\ttimeoutSignal = timeoutCtrl.signal;\n\t}\n\n\tconst sources = [callerSignal, timeoutSignal];\n\t// Forward the source's reason so fetch rejects with the right error name\n\t// ('TimeoutError' vs 'AbortError'), matching AbortSignal.any semantics.\n\tconst onAbort = function (this: AbortSignal) {\n\t\tctrl.abort(this.reason);\n\t};\n\n\tfor (const s of sources) {\n\t\tif (s.aborted) {\n\t\t\tctrl.abort(s.reason);\n\t\t\tbreak;\n\t\t}\n\t\ts.addEventListener('abort', onAbort, { once: true });\n\t}\n\n\treturn {\n\t\tsignal: ctrl.signal,\n\t\tcleanup: () => {\n\t\t\tif (timerId !== undefined) clearTimeout(timerId);\n\t\t\tfor (const s of sources) s.removeEventListener('abort', onAbort);\n\t\t}\n\t};\n}\n\n// ============================================================================\n// Response Processing\n// ============================================================================\n\n/**\n * Surface the server's per-request timing breakdown (if it sent one and a\n * caller is listening). Best-effort: a throwing callback must not fail the\n * request. Called on the success path AND the 500-with-values partial-success\n * path — solves that completed with Grasshopper errors carry real timings too.\n */\nfunction fireServerTiming(\n\tresponse: Response,\n\trequestId: string,\n\tonServerTiming: ((timing: ServerTiming, requestId: string) => void) | undefined,\n\tdebug?: boolean\n): void {\n\tif (!onServerTiming) return;\n\tconst timing = parseServerTiming(response.headers.get('Server-Timing'));\n\tif (!timing) return;\n\ttry {\n\t\tonServerTiming(timing, requestId);\n\t} catch (err) {\n\t\tif (debug) log(` onServerTiming callback threw: ${err}`, true);\n\t}\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, requestId: string) => 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. `rawBody` stays what came over the wire (stored\n\t\t// on error context); `errorBody` may be rewritten into a friendlier message.\n\t\tconst rawBody = await response.text();\n\t\tlet errorBody = rawBody;\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). It can\n\t\t// ride any error status, not just 500, so read it here.\n\t\tlet serverCode: string | undefined;\n\n\t\ttry {\n\t\t\tconst parsedForCode = JSON.parse(errorBody);\n\t\t\tif (typeof parsedForCode?.code === 'string') serverCode = parsedForCode.code;\n\t\t} catch {\n\t\t\t// Non-JSON body — nothing to extract.\n\t\t}\n\n\t\t// Check if it's a valid compute response with errors/warnings\n\t\tif (response.status === 500) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(errorBody);\n\t\t\t\t// If it has values, it's a partial success with errors\n\t\t\t\tif (parsed?.values && (parsed.errors || parsed.warnings)) {\n\t\t\t\t\tif (debug) {\n\t\t\t\t\t\tlog(\n\t\t\t\t\t\t\t`⚠️ Request [${requestId}] completed with Grasshopper errors in ${responseTime}ms`,\n\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (parsed.errors?.length > 0) {\n\t\t\t\t\t\t\tlog(` Errors: ${JSON.stringify(parsed.errors, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (parsed.warnings?.length > 0) {\n\t\t\t\t\t\t\tlog(` Warnings: ${JSON.stringify(parsed.warnings, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfireServerTiming(response, requestId, onServerTiming, debug);\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(\n\t\t\tresponse,\n\t\t\tfullUrl,\n\t\t\trequestId,\n\t\t\trequestSize,\n\t\t\tserverUrl,\n\t\t\terrorBody,\n\t\t\tserverCode,\n\t\t\trawBody\n\t\t);\n\t}\n\n\tlog(`✅ Request [${requestId}] completed in ${responseTime}ms`, debug);\n\n\tfireServerTiming(response, requestId, onServerTiming, debug);\n\n\ttry {\n\t\treturn await response.json();\n\t} catch (error) {\n\t\t// Classify by the declared Content-Type (issue 87). A 2xx that DECLARES a\n\t\t// non-JSON body (HTML from a captive portal, a reverse-proxy login page, a\n\t\t// misconfigured endpoint) is deterministic — refetching returns the same\n\t\t// page — so fail immediately with INVALID_RESPONSE (never retried). A body\n\t\t// that fails to parse under a JSON (or absent) Content-Type means the\n\t\t// stream was likely cut mid-body — as transient as any network error — and\n\t\t// keeps the retryable NETWORK_ERROR classification.\n\t\tconst contentType = (response.headers.get('Content-Type') ?? '').toLowerCase();\n\t\tconst declaredNonJson = contentType !== '' && !contentType.includes('json');\n\t\tif (declaredNonJson) {\n\t\t\tthrow new RhinoComputeError(\n\t\t\t\t`Server returned a non-JSON response (Content-Type: ${contentType}) — check the server URL / proxy configuration`,\n\t\t\t\tErrorCodes.INVALID_RESPONSE,\n\t\t\t\t{\n\t\t\t\t\tstatusCode: response.status,\n\t\t\t\t\tcontext: { url: fullUrl, requestId, contentType },\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\tthrow new RhinoComputeError('Failed to parse JSON response', ErrorCodes.NETWORK_ERROR, {\n\t\t\tstatusCode: response.status,\n\t\t\tcontext: {\n\t\t\t\turl: fullUrl,\n\t\t\t\trequestId\n\t\t\t},\n\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t});\n\t}\n}\n\n// ============================================================================\n// Single attempt\n// ============================================================================\n\ninterface AttemptContext {\n\tendpoint: string;\n\tbody: string;\n\trequestSize: number;\n\tfullUrl: string;\n\trequestId: string;\n\theaders: HeadersInit;\n\tconfig: ComputeConfig;\n}\n\ninterface AttemptResult {\n\tok: true;\n\tvalue: any;\n}\n\ninterface AttemptRetry {\n\tok: false;\n\tretry: true;\n\tdelayMs: number;\n\tcause: RhinoComputeError;\n}\n\ninterface AttemptFatal {\n\tok: false;\n\tretry: false;\n\tcause: RhinoComputeError;\n}\n\nasync function attemptFetch(\n\tctx: AttemptContext,\n\tretryPolicy: Required<RetryPolicy>,\n\tattempt: number,\n\ttotalAttempts: number\n): Promise<AttemptResult | AttemptRetry | AttemptFatal> {\n\tconst { signal, cleanup } = composeSignal(ctx.config.signal, ctx.config.timeoutMs);\n\tconst startTime = performance.now();\n\n\ttry {\n\t\tconst response = await fetch(ctx.fullUrl, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: ctx.body,\n\t\t\theaders: ctx.headers,\n\t\t\tsignal\n\t\t});\n\n\t\t// 429 with Retry-After or retryable 5xx → maybe retry\n\t\tconst isRetryableStatus =\n\t\t\tRETRYABLE_STATUS.has(response.status) || (retryPolicy.retryOn429 && response.status === 429);\n\n\t\tif (isRetryableStatus && attempt < totalAttempts - 1) {\n\t\t\tconst retryAfterMs = parseRetryAfter(response.headers.get('Retry-After'));\n\t\t\t// The server's stated Retry-After window wins over maxDelayMs — retrying\n\t\t\t// before it all but guarantees another 429 and burns an attempt. It is\n\t\t\t// only clamped by the absolute RETRY_AFTER_CAP_MS safety cap (or by a\n\t\t\t// caller-configured maxDelayMs that is even larger), so a bad header\n\t\t\t// can't force a pathological sleep. backoffDelay already clamps itself.\n\t\t\tconst delayMs =\n\t\t\t\tretryAfterMs !== null\n\t\t\t\t\t? Math.min(retryAfterMs, Math.max(retryPolicy.maxDelayMs, RETRY_AFTER_CAP_MS))\n\t\t\t\t\t: backoffDelay(attempt, retryPolicy);\n\t\t\t// Drain the body so the connection can be reused on the next attempt.\n\t\t\t// On the *final* attempt we deliberately fall through — handleResponse\n\t\t\t// reads the body itself to surface the error context.\n\t\t\tawait response.text().catch(() => {});\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tretry: true,\n\t\t\t\tdelayMs,\n\t\t\t\tcause: new RhinoComputeError(\n\t\t\t\t\t`HTTP ${response.status} ${response.statusText} (will retry)`,\n\t\t\t\t\tresponse.status === 429 ? ErrorCodes.RATE_LIMIT : ErrorCodes.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.ABORTED, {\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// Only claim a timeout when we actually armed one (issue 88). Without a\n\t\t\t// configured timeoutMs, a non-caller abort came from the runtime itself\n\t\t\t// (e.g. an undici socket teardown) — as transient as any network drop, so\n\t\t\t// it stays retryable, but it is NOT a timeout: report it truthfully\n\t\t\t// instead of \"timed out after undefinedms\" / TIMEOUT_ERROR.\n\t\t\tconst timeoutArmed = typeof ctx.config.timeoutMs === 'number' && ctx.config.timeoutMs > 0;\n\t\t\tconst fatal = timeoutArmed\n\t\t\t\t? new RhinoComputeError(\n\t\t\t\t\t\t`Request timed out after ${ctx.config.timeoutMs}ms`,\n\t\t\t\t\t\tErrorCodes.TIMEOUT_ERROR,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\t\t\ttimeoutMs: ctx.config.timeoutMs,\n\t\t\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t: new RhinoComputeError(\n\t\t\t\t\t\t`Request aborted by the runtime (${error.name}): ${error.message}`,\n\t\t\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t\t}\n\t\t\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 (issue 90).\n\t\t//\n\t\t// Duplicate-POST caveat: a connection reset can strike after the body was\n\t\t// sent, in which case the server may already have executed this POST and a\n\t\t// retry runs it again. Compute solves are deterministic, so a duplicate is\n\t\t// wasted work rather than corruption; RetryPolicy documents the risk and\n\t\t// defaults to attempts: 0.\n\t\t//\n\t\t// In a real browser, a fetch TypeError with no response is most often a\n\t\t// CORS misconfiguration (the browser hides the details by design), so it is\n\t\t// classified CORS_ERROR there to stop callers chasing phantom network\n\t\t// failures. Retries are kept in both environments: the same TypeError is\n\t\t// also what a flaky/offline network produces, and there is no way to tell\n\t\t// them apart.\n\t\tif (error instanceof TypeError) {\n\t\t\tconst inBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';\n\t\t\tconst errorContext = {\n\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\turl: ctx.fullUrl,\n\t\t\t\trequestId: ctx.requestId,\n\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\trequestSize: ctx.requestSize\n\t\t\t};\n\t\t\tconst fatal = inBrowser\n\t\t\t\t? new RhinoComputeError(\n\t\t\t\t\t\t`Request failed: ${error.message} — in a browser this usually means a CORS misconfiguration on the server (or a network failure; the browser does not distinguish them)`,\n\t\t\t\t\t\tErrorCodes.CORS_ERROR,\n\t\t\t\t\t\t{ context: errorContext, originalError: error }\n\t\t\t\t\t)\n\t\t\t\t: new RhinoComputeError(`Network error: ${error.message}`, ErrorCodes.NETWORK_ERROR, {\n\t\t\t\t\t\tcontext: errorContext,\n\t\t\t\t\t\toriginalError: error\n\t\t\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\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\t// A 2xx whose body failed to parse UNDER A JSON CONTENT-TYPE\n\t\t\t// (NETWORK_ERROR from handleResponse) means the stream was cut mid-body —\n\t\t\t// as transient as any network error. A 2xx that declared a non-JSON body\n\t\t\t// arrives here as INVALID_RESPONSE (deterministic — captive portal /\n\t\t\t// login page) and deliberately does NOT match: it is never retried.\n\t\t\tconst isTruncatedSuccess =\n\t\t\t\terror.code === ErrorCodes.NETWORK_ERROR &&\n\t\t\t\tstatus !== undefined &&\n\t\t\t\tstatus >= 200 &&\n\t\t\t\tstatus < 300;\n\t\t\tconst retryable =\n\t\t\t\tisTruncatedSuccess ||\n\t\t\t\t(status !== undefined &&\n\t\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 * Timeout semantics: `config.timeoutMs` is a PER-ATTEMPT timeout, re-armed for\n * every retry. With `retry: { attempts: N }` the worst-case wall clock is\n * `(N + 1) × timeoutMs` plus backoff sleeps (and a server `Retry-After` can\n * stretch a single sleep up to 60s). For a hard overall deadline, pass\n * `config.signal` (e.g. `AbortSignal.timeout(totalMs)`) — a caller abort wins\n * immediately, including during backoff.\n *\n * Retry caveats: requests are POSTs, so a retry after a mid-flight connection\n * loss may re-execute a request the server already ran (see {@link RetryPolicy}).\n * A 2xx response that declares a non-JSON `Content-Type` (captive portal,\n * proxy login page) fails immediately with `INVALID_RESPONSE` and is never\n * retried; a body that fails to parse under a JSON content-type is treated as\n * a truncated stream and is retried.\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\t// Wire size in UTF-8 bytes — `body.length` counts UTF-16 code units and\n\t// undercounts non-ASCII payloads (matters for the 413 message and size logs).\n\tconst requestSize = utf8ByteLength(body);\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\t// Every iteration ends in `return` or `throw` (issue 105): attemptFetch never\n\t// asks to retry on the final attempt (all its retry branches are gated on\n\t// `attempt < totalAttempts - 1`), so the exhausted-retries error is the final\n\t// attempt's own `result.cause` — there is no post-loop fallback to reach.\n\tfor (let attempt = 0; ; 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\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.ABORTED, {\n\t\t\t\tcontext: { endpoint, requestId, requestSize },\n\t\t\t\toriginalError: result.cause\n\t\t\t});\n\t\t}\n\t}\n}\n"]}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import{a as Et,c as te,d as ne,e as C,j as Ae}from"./chunk-54O6BO24.js";var ht={};Et(ht,{CONCRETE_MATERIAL:()=>Le,EMISSIVE_MATERIAL:()=>Se,GLASS_MATERIAL:()=>Pe,METAL_MATERIAL:()=>De,PLASTIC_MATERIAL:()=>Oe,RUBBER_MATERIAL:()=>Ie,SHARED_MATERIALS:()=>ge,WOOD_MATERIAL:()=>Ve});import*as P from"three";var Se=new P.MeshPhysicalMaterial({color:0,emissive:new P.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1,side:P.FrontSide,dithering:!0}),De=new P.MeshPhysicalMaterial({color:new P.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,polygonOffsetFactor:1,polygonOffsetUnits:1,side:P.FrontSide,dithering:!0}),Le=new P.MeshPhysicalMaterial({color:new P.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:0,depthTest:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1,side:P.FrontSide,dithering:!0}),Oe=new P.MeshPhysicalMaterial({color:new P.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:P.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Pe=new P.MeshPhysicalMaterial({color:new P.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,depthWrite:!1,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:P.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Ie=new P.MeshPhysicalMaterial({color:new P.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:P.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Ve=new P.MeshPhysicalMaterial({color:new P.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:P.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),ge=new Set([Se,De,Le,Oe,Pe,Ie,Ve]);import*as U from"three";var Z={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 Sr(e,n,t,r,a){if(yt(e),n.length===0)return;n.forEach(d=>{e.add(d)});let o=oe(n),i=o.getCenter(new U.Vector3),s=o.getSize(new U.Vector3),l=Math.max(s.x,s.y,s.z);if(l/Math.min(s.x||1,s.y||1,s.z||1)>Z.SCALE_RATIO_THRESHOLD||l>Z.HUGE_THRESHOLD?(t.near=l*Z.NEAR_PLANE_FACTOR.TINY,t.far=l*Z.FAR_PLANE_FACTOR.HUGE):l>Z.LARGE_THRESHOLD?(t.near=l*Z.NEAR_PLANE_FACTOR.SMALL,t.far=l*Z.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,l*Z.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,l*Z.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),!a){let d=l*Z.INITIAL_DISTANCE_MULTIPLIER;t.position.set(i.x+d*.8,i.y+d,i.z+d*1.2),r.target.copy(i),r.update()}}function Be(e){if(!e||typeof e!="string")return C().warn(`Invalid color input: ${e}, using white`),new U.Color(16777215);let n=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(n))try{let r=n.startsWith("#")?n:`#${n}`;return new U.Color(r)}catch{return C().warn(`Invalid hex color: ${e}, using white`),new U.Color(16777215)}if(n.includes(",")){let r=n.split(",").map(a=>parseInt(a.trim(),10));if(r.length===3&&r.every(a=>!isNaN(a)&&a>=0&&a<=255))return new U.Color(r[0]/255,r[1]/255,r[2]/255)}let t=n.toLowerCase();return t in U.Color.NAMES?new U.Color(U.Color.NAMES[t]):(C().warn(`Invalid color string: ${e}, using white`),new U.Color(16777215))}function Fe(e,n,t="z"){e.forEach(r=>{r.position[t]-=n})}function oe(e){let n=new U.Box3;return e.length===0||e.forEach(t=>{t.updateMatrixWorld(!0);let r=new U.Box3().setFromObject(t);n.union(r)}),n}var gt=new Set(["floor","grid","label-layer"]);function yt(e){[...e.children].forEach(t=>{gt.has(t.userData.id)||t.userData.source!=="user"&&(t.traverse(r=>{let a=r;if(!a.geometry&&!a.material)return;a.geometry?.dispose();let o=a.material;if(!o)return;(Array.isArray(o)?o:[o]).forEach(s=>{if(!ge.has(s)){for(let l of Object.values(s))l instanceof U.Texture&&l.dispose();s.dispose()}})}),t.removeFromParent())})}import*as k from"three";function bt(e){let n=e.clone().normalize(),t=new k.Vector3(0,0,1),r=new k.Vector3(0,1,0),a=Math.abs(n.dot(t))>.9?r:t,o=new k.Vector3().crossVectors(n,a).normalize(),i=new k.Vector3().crossVectors(o,n).normalize();return{top:n.clone(),bottom:n.clone().negate(),front:i.clone(),back:i.clone().negate(),right:o.clone(),left:o.clone().negate(),iso:i.clone().multiplyScalar(1.2).add(o.clone()).add(n.clone()).normalize()}}function Ue(e){let{scene:n,perspective:t,controls:r,onActiveCameraChange:a}=e,o=(e.up??t.up).clone().normalize(),i=bt(o),s=new k.OrthographicCamera(-1,1,1,-1,t.near,t.far);s.up.copy(o);let l="perspective",c=t.aspect,d=()=>l==="perspective"?t:s,u=null,f=()=>{u?.cancel(),u=null},p=()=>{let b=(l==="orthographic"?s:t).position.distanceTo(r.target)*Math.tan(t.fov*Math.PI/360),v=b*c;s.left=-v,s.right=v,s.top=b,s.bottom=-b,s.near=t.near,s.far=t.far,s.updateProjectionMatrix()},g=m=>{if(m!==l){if(f(),m==="orthographic")s.position.copy(t.position),s.up.copy(t.up),s.lookAt(r.target),s.zoom=1,p();else{let b=(s.top-s.bottom)/(2*s.zoom)/Math.tan(t.fov*Math.PI/360),v=s.position.clone().sub(r.target);v.lengthSq()<1e-12&&v.copy(o),v.normalize(),t.position.copy(r.target).add(v.multiplyScalar(b))}l=m,r.object=d(),r.update(),a(d())}},y=(m,T,b,v)=>{let A=t.fov*(Math.PI/180),V=T/(2*Math.tan(A/2))*1.5,$=vt(b,o),B=m.clone().add($.clone().multiplyScalar(V)),Y=d();l==="orthographic"&&(s.zoom=1),f(),v?u=Ht(Y,r,B,m,()=>{l==="orthographic"&&p()}):(Y.position.copy(B),r.target.copy(m),l==="orthographic"&&p(),r.update())},R=(m,T=!0)=>{let b=wt(n),v=b.isEmpty()?r.target.clone():b.getCenter(new k.Vector3),A=b.isEmpty()?new k.Vector3(1,1,1):b.getSize(new k.Vector3),V=Math.max(A.x,A.y,A.z)||1;y(v,V,m,T)};return{getActiveCamera:d,getProjection:()=>l,setProjection:g,toggleProjection:()=>(g(l==="perspective"?"orthographic":"perspective"),l),setView:(m,T=!0)=>{R(i[m],T)},setViewDirection:R,frameBounds:(m,T=!0)=>{if(m.isEmpty())return;let b=m.getCenter(new k.Vector3),v=m.getSize(new k.Vector3),A=Math.max(v.x,v.y,v.z)||1,V=d().position.clone().sub(r.target);V.lengthSq()<1e-12&&V.copy(i.iso),y(b,A,V.normalize(),T)},setRotateEnabled:m=>{r.enableRotate=m},isRotateEnabled:()=>r.enableRotate,updateAspect:(m,T)=>{c=T===0?c:m/T,l==="orthographic"&&p()},dispose:f}}var Tt=new Set(["grid","floor","label-layer","measure"]);function Rt(e){let n=e;for(;n;){if(typeof n.userData.id=="string"&&Tt.has(n.userData.id))return!0;n=n.parent}return!1}function wt(e){let n=[];return e.traverse(t=>{let r=t;t.visible&&!Rt(t)&&r.geometry&&n.push(t)}),oe(n)}function vt(e,n){let t=n.clone().normalize(),r=e.clone().normalize();if(Math.abs(r.dot(t))<.9999)return e;let a=Math.abs(t.dot(new k.Vector3(0,0,1)))>.9?new k.Vector3(0,1,0):new k.Vector3(0,0,1),o=new k.Vector3().crossVectors(t,a).normalize(),i=.5*Math.PI/180;return r.multiplyScalar(Math.cos(i)).add(o.multiplyScalar(Math.sin(i))).normalize()}var xt=e=>1-Math.pow(1-e,3);function Ht(e,n,t,r,a,o=250){let i=e.position.clone(),s=n.target.clone(),l=performance.now(),c=null,d=()=>{c=null;let u=xt(Math.min((performance.now()-l)/o,1));e.position.lerpVectors(i,t,u),n.target.lerpVectors(s,r,u),a(),n.update(),u<1&&(c=requestAnimationFrame(d))};return c=requestAnimationFrame(d),{cancel:()=>{c!==null&&(cancelAnimationFrame(c),c=null)}}}import*as F from"three";var Mt=`
|
|
2
|
+
varying vec3 vWorldPos;
|
|
3
|
+
void main() {
|
|
4
|
+
vec4 world = modelMatrix * vec4(position, 1.0);
|
|
5
|
+
vWorldPos = world.xyz;
|
|
6
|
+
gl_Position = projectionMatrix * viewMatrix * world;
|
|
7
|
+
}
|
|
8
|
+
`,Ct=`
|
|
9
|
+
precision highp float;
|
|
10
|
+
varying vec3 vWorldPos;
|
|
11
|
+
|
|
12
|
+
uniform vec2 uAxes; // indices (0=x,1=y,2=z) of the two in-plane world axes
|
|
13
|
+
uniform float uCell;
|
|
14
|
+
uniform float uMajor;
|
|
15
|
+
uniform vec3 uCellColor;
|
|
16
|
+
uniform vec3 uMajorColor;
|
|
17
|
+
uniform vec3 uCenter; // fade center (camera position), projected onto plane
|
|
18
|
+
uniform float uFade;
|
|
19
|
+
|
|
20
|
+
// Antialiased grid line intensity for a given spacing, using screen-space derivatives so lines
|
|
21
|
+
// stay ~1px regardless of zoom (the standard "pristine grid" technique).
|
|
22
|
+
float gridLine(vec2 coord, float spacing) {
|
|
23
|
+
vec2 c = coord / spacing;
|
|
24
|
+
vec2 d = fwidth(c);
|
|
25
|
+
vec2 g = abs(fract(c - 0.5) - 0.5) / max(d, 1e-6);
|
|
26
|
+
float line = min(g.x, g.y);
|
|
27
|
+
return 1.0 - clamp(line, 0.0, 1.0);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Index a vec3 by a float axis id (0/1/2) without dynamic indexing (WebGL1-safe).
|
|
31
|
+
float axis(vec3 v, float i) {
|
|
32
|
+
return i < 0.5 ? v.x : (i < 1.5 ? v.y : v.z);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
void main() {
|
|
36
|
+
// Pick the two in-plane world coordinates.
|
|
37
|
+
vec2 coord = vec2(axis(vWorldPos, uAxes.x), axis(vWorldPos, uAxes.y));
|
|
38
|
+
|
|
39
|
+
float minor = gridLine(coord, uCell);
|
|
40
|
+
float major = gridLine(coord, uCell * uMajor);
|
|
41
|
+
|
|
42
|
+
vec3 color = mix(uCellColor, uMajorColor, major);
|
|
43
|
+
float alpha = max(minor, major);
|
|
44
|
+
|
|
45
|
+
// Radial fade from the camera-projected center.
|
|
46
|
+
float dist = distance(vWorldPos, uCenter);
|
|
47
|
+
float fade = 1.0 - clamp(dist / uFade, 0.0, 1.0);
|
|
48
|
+
alpha *= fade * fade;
|
|
49
|
+
|
|
50
|
+
if (alpha < 0.001) discard;
|
|
51
|
+
gl_FragColor = vec4(color, alpha);
|
|
52
|
+
}
|
|
53
|
+
`;function ze(e={}){let{cellSize:n=1,majorEvery:t=10,cellColor:r=8947848,majorColor:a=4473924,fadeDistance:o=100,plane:i="y"}=e,s=i==="y"?new F.Vector2(0,2):i==="z"?new F.Vector2(0,1):new F.Vector2(1,2),l=o*2.5,c=new F.PlaneGeometry(l,l);i==="y"?c.rotateX(-Math.PI/2):i==="x"&&c.rotateY(Math.PI/2);let d=new F.ShaderMaterial({vertexShader:Mt,fragmentShader:Ct,transparent:!0,depthWrite:!1,side:F.DoubleSide,uniforms:{uAxes:{value:s},uCell:{value:n},uMajor:{value:t},uCellColor:{value:new F.Color(r)},uMajorColor:{value:new F.Color(a)},uCenter:{value:new F.Vector3},uFade:{value:o}}}),u=new F.Mesh(c,d);u.name="grid",u.userData.id="grid",u.renderOrder=-1;let f=new F.Vector3;return{object:u,update:p=>{i==="y"?(u.position.set(p.x,0,p.z),f.set(p.x,0,p.z)):i==="z"?(u.position.set(p.x,p.y,0),f.set(p.x,p.y,0)):(u.position.set(0,p.y,p.z),f.set(0,p.y,p.z)),d.uniforms.uCenter.value.copy(f)},setVisible:p=>{u.visible=p},dispose:()=>{u.removeFromParent(),c.dispose(),d.dispose()}}}import*as N from"three";import{ViewHelper as At}from"three/addons/helpers/ViewHelper.js";function _e(e){let{camera:n,domElement:t,controller:r}=e,a=new At(n,t);a.setLabels("X","Y","Z");let o=!0,i=128,s=new N.Raycaster,l=new N.OrthographicCamera(-2,2,2,-2,0,4);l.position.set(0,0,2),l.updateMatrixWorld();let c={posX:new N.Vector3(1,0,0),negX:new N.Vector3(-1,0,0),posY:new N.Vector3(0,1,0),negY:new N.Vector3(0,-1,0),posZ:new N.Vector3(0,0,1),negZ:new N.Vector3(0,0,-1)},d=f=>{let p=t.getBoundingClientRect(),g=p.left+t.offsetWidth-i-a.location.right,y=p.top+t.offsetHeight-i-a.location.bottom,R=new N.Vector2((f.clientX-g)/i*2-1,-((f.clientY-y)/i)*2+1);if(Math.abs(R.x)>1||Math.abs(R.y)>1)return null;a.quaternion.copy(n.quaternion).invert(),a.updateMatrixWorld(),s.setFromCamera(R,l);let w=s.intersectObjects(a.children,!1);for(let E of w){let x=E.object.userData?.type;if(typeof x=="string"&&x in c)return x}return null};return{render:f=>{if(!o)return;let p=f.autoClear;f.autoClear=!1,a.render(f),f.autoClear=p},update:()=>{},handleClick:f=>{if(!o)return!1;let p=d(f);return p?(r.getProjection()==="orthographic"&&r.setProjection("perspective"),r.setViewDirection(c[p],!1),!0):!1},isAnimating:!1,setVisible:f=>{o=f},isVisible:()=>o,dispose:()=>a.dispose()}}import*as re from"three";import{LineSegmentsGeometry as St}from"three/addons/lines/LineSegmentsGeometry.js";import{LineSegments2 as ke}from"three/addons/lines/LineSegments2.js";import{LineMaterial as Dt}from"three/addons/lines/LineMaterial.js";var ce="edge-overlay",Lt=2236962,Ot=1.5,Pt=30,ye=new WeakMap;function je(e,n={}){let t=new re.Color(n.color??Lt),r=n.width??Ot,a=n.thresholdAngle??Pt,o=[];return e.traverse(i=>{if(!(i instanceof re.Mesh)||i.userData.id==="floor"||i.userData.id==="grid"||i.userData.kind===ce||i.children.some(l=>l.userData?.kind===ce)||!i.geometry)return;let s=Bt(i.geometry,t,r,a);i.add(s),o.push(s)}),o}function It(e,n){let t=ye.get(e);t||(t=new Map,ye.set(e,t));let r=t.get(n);if(!r){let a=new re.EdgesGeometry(e,n),o=new St;o.setPositions(a.attributes.position.array),a.dispose(),r={geometry:o,refCount:0},t.set(n,r)}return r.refCount+=1,r.geometry}function Vt(e){let n=e.userData,t=n.edgeSource&&ye.get(n.edgeSource),r=n.edgeThresholdAngle!=null?t?.get(n.edgeThresholdAngle):void 0;if(!r||r.geometry!==e.geometry){e.geometry.dispose();return}r.refCount-=1,r.refCount<=0&&(r.geometry.dispose(),t.delete(n.edgeThresholdAngle))}function Bt(e,n,t,r){let a=It(e,r),o=new Dt({color:n});o.linewidth=t,o.polygonOffset=!0,o.polygonOffsetFactor=-1,o.polygonOffsetUnits=-4;let i=new ke(a,o);return i.userData.kind=ce,i.userData.edgeSource=e,i.userData.edgeThresholdAngle=r,i.raycast=()=>{},i}function Ft(e){return e.userData?.kind===ce}function zr(e){let n=[];e.traverse(t=>{t instanceof ke&&Ft(t)&&n.push(t)});for(let t of n)Vt(t),t.material.dispose(),t.removeFromParent();return n.length}import{EffectComposer as Ut}from"three/addons/postprocessing/EffectComposer.js";import{RenderPass as zt}from"three/addons/postprocessing/RenderPass.js";import{GTAOPass as _t}from"three/addons/postprocessing/GTAOPass.js";import{SMAAPass as kt}from"three/addons/postprocessing/SMAAPass.js";import{OutputPass as jt}from"three/addons/postprocessing/OutputPass.js";function Ge(e,n,t,r,a,o){let i=new Ut(e),s=new zt(n,t);i.addPass(s);let l=new _t(n,t,r,a);l.blendIntensity=o.aoIntensity??1,l.updateGtaoMaterial({screenSpaceRadius:!0}),i.addPass(l);let c=new kt;i.addPass(c);let d=new jt;return i.addPass(d),e.toneMapping=o.toneMapping,e.toneMappingExposure=o.toneMappingExposure,i.setSize(r,a),{render:u=>i.render(u),setSize:(u,f,p)=>{i.setPixelRatio(p),i.setSize(u,f)},setCamera:u=>{s.camera=u,l.camera=u;let f=u.isPerspectiveCamera?1:0;l.gtaoMaterial.defines.PERSPECTIVE_CAMERA!==f&&(l.gtaoMaterial.defines.PERSPECTIVE_CAMERA=f,l.gtaoMaterial.needsUpdate=!0)},dispose:()=>{i.dispose(),l.dispose(),c.dispose(),d.dispose()}}}import*as Ne from"three";import{CSS2DRenderer as Gt,CSS2DObject as Nt}from"three/addons/renderers/CSS2DRenderer.js";function We(e,n){let t=new Gt,r=t.domElement;r.style.position="absolute",r.style.top="0",r.style.left="0",r.style.overflow="hidden",r.style.pointerEvents="none",r.style.zIndex="30",getComputedStyle(e).position==="static"&&(e.style.position="relative"),e.appendChild(r);let a={width:e.clientWidth||1,height:e.clientHeight||1};t.setSize(a.width,a.height);let o=new Ne.Group;o.name="label-layer",o.userData.id="label-layer",n.add(o);let i=new Set;return{addLabel:(l,c,d)=>{let u=document.createElement("div");u.textContent=l,d?u.className=d:Object.assign(u.style,{padding:"2px 6px",borderRadius:"4px",background:"rgba(20, 20, 20, 0.78)",color:"#fff",font:"12px/1.3 system-ui, sans-serif",whiteSpace:"pre",textAlign:"center",userSelect:"none"}),u.style.pointerEvents="none";let f=new Nt(u);return f.position.copy(c),o.add(f),i.add(f),{object:f,setPosition:p=>f.position.copy(p),setText:p=>{u.textContent=p},remove:()=>{f.removeFromParent(),u.remove(),i.delete(f)}}},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(),o.removeFromParent(),r.remove()}}}import*as L from"three";import{Line2 as Wt}from"three/addons/lines/Line2.js";import{LineGeometry as $t}from"three/addons/lines/LineGeometry.js";import{LineMaterial as Yt}from"three/addons/lines/LineMaterial.js";var Xt=12,qt=16763904,$e=.015,Ye={Millimeters:{metersPerUnit:1/1e3,suffix:"mm"},Centimeters:{metersPerUnit:1/100,suffix:"cm"},Meters:{metersPerUnit:1,suffix:"m"},Inches:{metersPerUnit:1/39.37,suffix:"in"},Feet:{metersPerUnit:1/3.28084,suffix:"ft"}};function Zt(e){let n=e&&Ye[e]||Ye.Meters;return t=>`${(t/n.metersPerUnit).toPrecision(3)} ${n.suffix}`}function Kt(e,n){if(e.isOrthographicCamera){let r=e;return Math.abs(r.top-r.bottom)/(r.zoom||1)*$e}return((n?e.position.distanceTo(n):e.position.length())||1)*$e}function Jt(e){let n=e.object;if(n instanceof L.Mesh)return e.face?[e.face.a,e.face.b,e.face.c]:null;if(n instanceof L.Points)return e.index!=null?[e.index]:null;if(n instanceof L.Line){if(e.index==null)return null;let t=n.geometry.index;return t?e.index+1>=t.count?null:[t.getX(e.index),t.getX(e.index+1)]:[e.index,e.index+1]}return null}function Qt(e,n,t,r){let a=e.point.clone(),o=e.object,i=Jt(e);if(!i||!o.geometry)return a;let s=o.geometry.attributes.position;if(!s)return a;let l=f=>{let p=f.clone().project(n);return new L.Vector2((p.x+1)/2*t.width,(1-p.y)/2*t.height)},c=l(a),d=a,u=r;for(let f of i){if(f>=s.count)continue;let g=new L.Vector3().fromBufferAttribute(s,f).applyMatrix4(o.matrixWorld),y=l(g).distanceTo(c);y<u&&(u=y,d=g)}return d}function Xe(e){let{canvas:n,scene:t,getActiveCamera:r,getViewTarget:a,labelLayer:o,options:i={}}=e,s=i.snapPixels??Xt,l=new L.Color(i.color??qt),c=Zt(i.displayUnit),d=(H,S)=>`${c(H)}
|
|
54
|
+
\u0394x ${c(S.x)} \u0394y ${c(S.y)} \u0394z ${c(S.z)}`,u=i.format??d,f=new L.Raycaster,p=new L.Vector2,g=!1,y=[],R=[],w=null,E=null,x=new L.PointsMaterial({color:l,size:8,sizeAttenuation:!1,depthTest:!1}),O=new L.PointsMaterial({color:l,size:11,sizeAttenuation:!1,depthTest:!1,transparent:!0,opacity:.5}),m=null,T=H=>{if(!H){m&&(m.visible=!1);return}if(!m){let S=new L.BufferGeometry;S.setAttribute("position",new L.Float32BufferAttribute([0,0,0],3)),m=new L.Points(S,O),m.renderOrder=1e3,m.userData.id="measure",m.raycast=()=>{},t.add(m)}m.position.copy(H),m.visible=!0},b=H=>{let S=new L.BufferGeometry;S.setAttribute("position",new L.Float32BufferAttribute([H.x,H.y,H.z],3));let z=new L.Points(S,x);return z.renderOrder=999,z.userData.id="measure",z.raycast=()=>{},t.add(z),z},v=()=>{y.length=0,R.forEach(H=>{H.geometry.dispose(),H.removeFromParent()}),R.length=0,w&&(w.geometry.dispose(),w.material.dispose(),w.removeFromParent(),w=null),E?.remove(),E=null},A=()=>{if(y.length!==2)return;let[H,S]=y,z=new $t;z.setPositions([H.x,H.y,H.z,S.x,S.y,S.z]);let J=new Yt({color:l});J.linewidth=2,J.depthTest=!1,w=new Wt(z,J),w.renderOrder=998,w.userData.id="measure",w.raycast=()=>{},t.add(w);let Q=H.clone().add(S).multiplyScalar(.5),ee=new L.Vector3(Math.abs(S.x-H.x),Math.abs(S.y-H.y),Math.abs(S.z-H.z));E=o.addLabel(u(H.distanceTo(S),ee),Q,i.labelClassName)},V=H=>{let S=n.getBoundingClientRect();p.x=(H.clientX-S.left)/S.width*2-1,p.y=-((H.clientY-S.top)/S.height)*2+1;let z=r();f.setFromCamera(p,z);let J=Kt(z,a?.());f.params.Line.threshold=J,f.params.Points.threshold=J;let Q=f.intersectObjects(t.children,!0).filter(ee=>ee.object.userData.id!=="measure"&&ee.object.userData.id!=="grid");return Q.length===0?null:Qt(Q[0],z,{width:S.width,height:S.height},s)},$=null,B=0,Y=()=>{B&&(cancelAnimationFrame(B),B=0),$=null};return{setEnabled:H=>{g=H,H||(Y(),v(),T(null))},isEnabled:()=>g,handleClick:H=>{if(!g)return!1;y.length===2&&v();let S=V(H);return S===null||(y.push(S),R.push(b(S)),y.length===2&&A()),!0},handleMove:H=>{g&&($=H,!B&&(B=requestAnimationFrame(()=>{B=0;let S=$;$=null,!(!g||!S)&&T(V(S))})))},clear:v,dispose:()=>{Y(),v(),m&&(m.geometry.dispose(),m.removeFromParent(),m=null),x.dispose(),O.dispose()}}}import*as fe from"three";var en=64,tn=256,X=new Map,ae=new Map,ue=0,me=class extends Error{constructor(n){super(`Texture load for ${n} resolved after clearTextureCache(); texture disposed.`),this.name="StaleTextureLoadError"}},de=1;function qe(e){de=Math.max(1,e);for(let n of X.values())n.anisotropy!==de&&(n.anisotropy=de,n.needsUpdate=!0)}function Ze(e,n){let t=nn(n),r=X.get(t);if(r){X.delete(t),X.set(t,r),e.map=r,e.needsUpdate=!0;return}typeof document>"u"||an(n,t).then(a=>{e.map=a,e.needsUpdate=!0}).catch(a=>{a instanceof me||C().warn(`Failed to load material texture ${n}:`,a)})}function eo(){ue++;for(let e of X.values())e.dispose();X.clear(),ae.clear()}function nn(e){return e.length<=tn?e:`data-uri:${rn(e).toString(16)}:${e.length}`}function rn(e){let n=2166136261;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return n>>>0}function on(e,n){for(X.set(e,n);X.size>en;){let t=X.keys().next().value,r=X.get(t);X.delete(t),r.dispose()}}function an(e,n){let t=ae.get(n);if(!t){let r=ue;t=new Promise((a,o)=>{new fe.TextureLoader().load(e,i=>{if(r!==ue){i.dispose(),o(new me(e));return}i.colorSpace=fe.SRGBColorSpace,i.anisotropy=de,on(n,i),ae.delete(n),a(i)},void 0,i=>{r===ue&&ae.delete(n),o(i)})}),ae.set(n,t)}return t}import*as h from"three";import{OrbitControls as sn}from"three/addons/controls/OrbitControls.js";import{HDRLoader as ln}from"three/addons/loaders/HDRLoader.js";var Ee=new h.Vector3(0,0,1),Te={technical:{toneMapping:h.NeutralToneMapping,toneMappingExposure:1,envMapIntensity:.5,cullBackfaces:!1,ambientOcclusion:!0,edges:!0,grid:!0},rendered:{toneMapping:h.ACESFilmicToneMapping,toneMappingExposure:1,envMapIntensity:1.3,cullBackfaces:!1,ambientOcclusion:!0,edges:!1,grid:!1}};function cn(e){let n=Te[e];return{envMapIntensity:n.envMapIntensity,cullBackfaces:n.cullBackfaces}}function un(e){let n=Math.abs(e.x),t=Math.abs(e.y),r=Math.abs(e.z);return r>=n&&r>=t?"z":t>=n&&t>=r?"y":"x"}var po=function(e,n){let t=dn(n||{}),r=t.environment?.sceneUp||Ee,a=t.render.pixelRatio??Math.min(window.devicePixelRatio,2),o=En(t),i=Tn(t,e);i.up.copy(r);let s=Rn(e,t,a);qe(s.capabilities.getMaxAnisotropy());let l=vn(i,e,t),c=Ue({scene:o,perspective:i,controls:l,onActiveCameraChange:()=>{},up:r}),d=()=>c.getActiveCamera(),u=!1;gn(o,t,()=>u);let f=yn(o,t),p=()=>{f&&pn(f,be(o))};t.floor?.enabled&&bn(o,t);let g=t.grid.enabled?ze({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;g&&o.add(g.object);let y=t.gizmo.enabled?_e({camera:i,domElement:e,controller:c}):null,R=e.parentElement??e,w=t.measure.enabled?We(R,o):null,E=t.measure.enabled&&w?Xe({canvas:e,scene:o,getActiveCamera:d,labelLayer:w,options:{snapPixels:t.measure.snapPixels,color:t.measure.color,labelClassName:t.measure.labelClassName,displayUnit:t.measure.displayUnit,format:t.measure.format}}):null,x=t.events.enableEventHandlers!==!1?wn(e,o,c,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},O=5,m=0,T=0,b=M=>{m=M.clientX,T=M.clientY},v=M=>Math.hypot(M.clientX-m,M.clientY-T)>O,A=M=>{if(!v(M)){if(E?.handleClick(M)){M.stopImmediatePropagation();return}y?.handleClick(M)&&M.stopImmediatePropagation()}};(y||E)&&(e.addEventListener("mousedown",b,{capture:!0}),e.addEventListener("click",A,{capture:!0}));let V=M=>E?.handleMove(M);E&&e.addEventListener("mousemove",V,{passive:!0});let $=M=>{je(M,{color:t.edges.color,width:t.edges.width,thresholdAngle:t.edges.thresholdAngle})},B=e.parentElement,Y=()=>B?{width:B.clientWidth,height:B.clientHeight}:{width:window.innerWidth,height:window.innerHeight},G=null,q=()=>{let{width:M,height:D}=Y(),_=Ge(s,o,d(),Math.max(1,M),Math.max(1,D),{toneMapping:t.render.toneMapping??h.NeutralToneMapping,toneMappingExposure:t.render.toneMappingExposure??1,aoIntensity:t.render.aoIntensity});return _.setSize(Math.max(1,M),Math.max(1,D),a),_},H=M=>{M&&!G?G=q():!M&&G&&(G.dispose(),G=null)};t.render.ambientOcclusion&&(G=q());let S=M=>{let D=Te[M];z=M,s.toneMapping=D.toneMapping,s.toneMappingExposure=D.toneMappingExposure,t.render.toneMapping=D.toneMapping,t.render.toneMappingExposure=D.toneMappingExposure,G&&H(!1),H(D.ambientOcclusion),o.traverse(_=>{if(_.userData.source!=="compute")return;let le=_,pt=Array.isArray(le.material)?le.material:le.material?[le.material]:[];for(let Ce of pt)"envMapIntensity"in Ce&&(Ce.envMapIntensity=D.envMapIntensity)}),o.traverse(_=>{_.userData.kind==="edge-overlay"&&(_.visible=D.edges)}),g&&(g.object.visible=D.grid)},z=n?.renderStyle??null,J=()=>z?cn(z):void 0,{animate:Q,dispose:ee}=hn(s,o,i,d,c,l,Y,a,t.events.onFrame,g,y,()=>G,w);Q(),o.up.set(r.x,r.y,r.z),p();let Me=M=>{M.traverse(D=>{let _=D;!_.geometry&&!_.material||(_.geometry?.dispose(),Array.isArray(_.material)?_.material.forEach(pe):_.material&&pe(_.material))})},dt=M=>{M.userData.source="user",o.add(M)},mt=M=>{M.removeFromParent(),Me(M)},ft=()=>{o.children.filter(D=>D.userData.source==="user").forEach(D=>{D.removeFromParent(),Me(D)})};return{scene:o,camera:i,controls:l,renderer:s,cameraController:c,grid:g,gizmo:y,measureTool:E,applyEdges:$,setAmbientOcclusion:H,setRenderStyle:S,getMaterialAppearance:J,updateShadowBounds:p,dispose:()=>{u=!0,ee(),x.dispose(),(y||E)&&(e.removeEventListener("mousedown",b,{capture:!0}),e.removeEventListener("click",A,{capture:!0})),E&&e.removeEventListener("mousemove",V),E?.dispose(),w?.dispose(),y?.dispose(),g?.dispose(),G?.dispose(),c.dispose(),l.dispose(),s.dispose(),s.forceContextLoss(),o.traverse(M=>{let D=M;!D.geometry&&!D.material||(D.geometry?.dispose(),Array.isArray(D.material)?D.material.forEach(pe):D.material&&pe(D.material))}),o.environment?.dispose(),o.background instanceof h.Texture&&o.background.dispose()},fitToView:x.fitToView,clearSelection:x.clearSelection,addUserGeometry:dt,removeUserGeometry:mt,clearUserGeometry:ft}};function dn(e){let n=e.sceneScale||"m",r={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}}[n],a=e.renderStyle?Te[e.renderStyle]:null;return{sceneScale:n,renderStyle:e.renderStyle??"technical",camera:{position:e.camera?.position||new h.Vector3(-r.cameraDistance,-r.cameraDistance,r.cameraDistance),fov:e.camera?.fov||20,near:e.camera?.near||r.near,far:e.camera?.far||r.far,target:e.camera?.target||new h.Vector3(0,0,0)},lighting:{enableSunlight:e.lighting?.enableSunlight??!0,sunlightIntensity:e.lighting?.sunlightIntensity??1,sunlightPosition:e.lighting?.sunlightPosition||new h.Vector3(r.lightDistance,r.lightDistance,r.lightHeight),ambientLightColor:e.lighting?.ambientLightColor||new h.Color(4210752),ambientLightIntensity:e.lighting?.ambientLightIntensity??1,sunlightColor:e.lighting?.sunlightColor||16777215},environment:{hdrPath:e.environment?.hdrPath||"/baseHDR.hdr",backgroundColor:e.environment?.backgroundColor||new h.Color(15790320),enableEnvironmentLighting:e.environment?.enableEnvironmentLighting??!0,sceneUp:e.environment?.sceneUp||Ee,showEnvironment:e.environment?.showEnvironment??!1},floor:{enabled:e.floor?.enabled??!1,size:e.floor?.size||r.floorSize,color:e.floor?.color||new h.Color(8421504),roughness:e.floor?.roughness??.7,metalness:e.floor?.metalness??0,receiveShadow:e.floor?.receiveShadow??!0},render:{enableShadows:e.render?.enableShadows??!0,shadowMapSize:e.render?.shadowMapSize||2048,antialias:e.render?.antialias??!0,pixelRatio:e.render?.pixelRatio||Math.min(window.devicePixelRatio,2),toneMapping:e.render?.toneMapping||a?.toneMapping||h.NeutralToneMapping,toneMappingExposure:e.render?.toneMappingExposure??a?.toneMappingExposure??1,preserveDrawingBuffer:e.render?.preserveDrawingBuffer??!1,ambientOcclusion:e.render?.ambientOcclusion??a?.ambientOcclusion??!1,aoIntensity:e.render?.aoIntensity??1},controls:{enableDamping:e.controls?.enableDamping??!1,dampingFactor:e.controls?.dampingFactor||.05,autoRotate:e.controls?.autoRotate??!1,autoRotateSpeed:e.controls?.autoRotateSpeed||.5,enableZoom:e.controls?.enableZoom??!0,enablePan:e.controls?.enablePan??!0,minDistance:e.controls?.minDistance||r.minDistance,maxDistance:e.controls?.maxDistance||1/0},grid:{enabled:e.grid?.enabled??a?.grid??!1,cellSize:e.grid?.cellSize??1,majorEvery:e.grid?.majorEvery??10,cellColor:e.grid?.cellColor??8947848,majorColor:e.grid?.majorColor??4473924,fadeDistance:e.grid?.fadeDistance??100,plane:e.grid?.plane??un(e.environment?.sceneUp??Ee)},gizmo:{enabled:e.gizmo?.enabled??!1},edges:{enabled:e.edges?.enabled??a?.edges??!1,color:e.edges?.color??2236962,width:e.edges?.width??1.5,thresholdAngle:e.edges?.thresholdAngle??30},measure:{enabled:e.measure?.enabled??!1,snapPixels:e.measure?.snapPixels,color:e.measure?.color,labelClassName:e.measure?.labelClassName,displayUnit:e.measure?.displayUnit,format:e.measure?.format},events:{onBackgroundClicked:e.events?.onBackgroundClicked,onObjectSelected:e.events?.onObjectSelected,onMeshMetadataClicked:e.events?.onMeshMetadataClicked,onMeshDoubleClicked:e.events?.onMeshDoubleClicked,selectionColor:e.events?.selectionColor||"#ff0000",enableEventHandlers:e.events?.enableEventHandlers??!0,enableKeyboardControls:e.events?.enableKeyboardControls??!0,enableClickToFocus:e.events?.enableClickToFocus??!0,enableDoubleClickZoom:e.events?.enableDoubleClickZoom??!0,onReady:e.events?.onReady,onFrame:e.events?.onFrame}}}function pe(e){for(let n of Object.values(e))n instanceof h.Texture&&n.dispose();e.dispose()}var mn=new Set(["grid","floor","label-layer","measure"]);function fn(e){let n=e;for(;n;){if(typeof n.userData.id=="string"&&mn.has(n.userData.id))return!0;n=n.parent}return!1}function be(e){let n=new h.Box3;return e.traverse(t=>{let r=t;t.visible&&!fn(t)&&r.geometry&&n.expandByObject(t)}),n}function pn(e,n){if(n.isEmpty())return;let t=n.getCenter(new h.Vector3),r=n.getSize(new h.Vector3).length()*.5*1.2,a=e.shadow.camera;a.left=-r,a.right=r,a.top=r,a.bottom=-r,e.target.position.copy(t),e.target.updateMatrixWorld();let o=e.position.distanceTo(t);a.near=Math.max(r*.01,o-r),a.far=o+r,a.updateProjectionMatrix()}function En(e){let n=new h.Scene,t=typeof e.environment.backgroundColor=="string"?new h.Color(e.environment.backgroundColor):e.environment.backgroundColor;return n.background=t||null,n}function hn(e,n,t,r,a,o,i,s,l,c,d,u,f){let p=null,g=performance.now(),y=()=>{let{width:E,height:x}=i();if(E===0||x===0)return;let O=Math.floor(E*s),m=Math.floor(x*s);(e.domElement.width!==O||e.domElement.height!==m)&&(e.setPixelRatio(s),e.setSize(E,x,!1),t.aspect=E/x,t.updateProjectionMatrix(),a.updateAspect(E,x),u?.()?.setSize(E,x,s),f?.setSize(E,x))},R=function(){p=requestAnimationFrame(R);let E=performance.now(),x=(E-g)/1e3;g=E,y(),(o.enableDamping||o.autoRotate)&&o.update(),c&&c.update(r().position),d&&d.update(x),l?.(x);let O=r(),m=u?.();m?(m.setCamera(O),m.render(x)):e.render(n,O),f&&f.render(n,O),d&&d.render(e)};return{animate:R,dispose:()=>{p!==null&&(cancelAnimationFrame(p),p=null)}}}function gn(e,n,t){n.environment.enableEnvironmentLighting?new ln().load(n.environment.hdrPath||"/baseHDR.hdr",function(r){if(t()){r.dispose();return}if(!r?.image){C().warn("HDR loaded without image data; skipping environment map."),r?.dispose(),n.events.onReady?.();return}r.mapping=h.EquirectangularReflectionMapping,e.environment=r,n.environment.showEnvironment&&(e.background=r),n.events.onReady?.()},void 0,function(r){t()||(C().warn("HDR texture could not be loaded, falling back to basic lighting:",r),n.events.onReady?.())}):n.events.onReady?.()}function yn(e,n){let t=new h.AmbientLight(n.lighting.ambientLightColor,n.lighting.ambientLightIntensity);if(e.add(t),!n.lighting.enableSunlight)return null;let r=new h.DirectionalLight(n.lighting.sunlightColor??16777215,n.lighting.sunlightIntensity),a=n.lighting.sunlightPosition;return a&&r.position.set(a.x,a.y,a.z),n.render.enableShadows?(r.castShadow=!0,r.shadow.mapSize.width=n.render.shadowMapSize||2048,r.shadow.mapSize.height=n.render.shadowMapSize||2048,r.shadow.bias=-1e-4,r.shadow.normalBias=.02,r.shadow.radius=4,e.add(r),e.add(r.target),r):(e.add(r),null)}function bn(e,n){let t=n.floor.size,r=new h.PlaneGeometry(t,t),a=typeof n.floor.color=="string"?new h.Color(n.floor.color):n.floor.color,o=new h.MeshStandardMaterial({color:a,roughness:n.floor.roughness,metalness:n.floor.metalness,side:h.DoubleSide}),i=new h.Mesh(r,o);i.userData.id="floor",i.name="floor";let s=(n.environment?.sceneUp||Ee).clone().normalize();i.quaternion.setFromUnitVectors(new h.Vector3(0,0,1),s),i.position.set(0,0,0),n.floor.receiveShadow&&n.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function Tn(e,n){let t=n.parentElement,r=t?t.clientWidth:window.innerWidth,a=t?t.clientHeight:window.innerHeight,o=new h.PerspectiveCamera(e.camera.fov,r/a,e.camera.near,e.camera.far),i=e.camera.position;return i&&o.position.set(i.x,i.y,i.z),o}function Rn(e,n,t){let r=new h.WebGLRenderer({antialias:n.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:n.render.preserveDrawingBuffer,logarithmicDepthBuffer:!1}),a=e.parentElement,o=a?a.clientWidth:window.innerWidth,i=a?a.clientHeight:window.innerHeight;return a&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),r.setSize(o,i,!1),r.setPixelRatio(t),n.render.enableShadows&&(r.shadowMap.enabled=!0,r.shadowMap.type=h.VSMShadowMap),r.toneMapping=n.render.toneMapping,r.toneMappingExposure=n.render.toneMappingExposure??1,r.outputColorSpace=h.SRGBColorSpace,r.sortObjects=!0,r}function wn(e,n,t,r){let a=new Set,o=new Map,i=new h.Raycaster,s=new h.Vector2,l=new h.Vector2,c=()=>t.getActiveCamera(),d=m=>{let T=m;for(;T;){if(!T.visible)return!1;T=T.parent}return!0},u=()=>{let m=be(n);if(m.isEmpty()){C().warn("No objects to fit to view");return}t.frameBounds(m,!1)},f=typeof r.events.selectionColor=="string"?new h.Color(r.events.selectionColor):r.events.selectionColor instanceof h.Color?r.events.selectionColor:new h.Color("#ff0000"),p=()=>{a.forEach(m=>{let T=m;if(o.has(m)){let b=o.get(m),v=T.material;v instanceof h.Material?v.dispose():Array.isArray(v)&&v.forEach(V=>V.dispose()),T.material=b,o.delete(m);let A=m;for(;A.parent;)A=A.parent;A!==n&&(b instanceof h.Material?b.dispose():b.forEach(V=>V.dispose()))}}),a.clear()},g=m=>{let T=m;if(!(T.material instanceof h.Material))return!1;o.set(m,T.material);let b=T.material.clone();return m instanceof h.Mesh&&"emissive"in b?b.emissive=f.clone():"color"in b&&(b.color=f.clone()),T.material=b,!0},y=()=>{let m=be(n),T=m.isEmpty()?1:m.getSize(new h.Vector3).length();i.params.Points.threshold=T*.01},R=m=>{l.set(m.clientX,m.clientY)},w=m=>{let T=new h.Vector2(m.clientX,m.clientY);if(l.distanceTo(T)>5)return;let b=e.getBoundingClientRect();s.x=(m.clientX-b.left)/b.width*2-1,s.y=-((m.clientY-b.top)/b.height)*2+1,y(),i.setFromCamera(s,c());let v=i.intersectObjects(n.children,!0).filter(A=>d(A.object));if(v.length>0){let A=v[0].object;a.has(A)||(p(),a.add(A),g(A),r.events?.onObjectSelected?.(A),A instanceof h.Mesh&&Object.keys(A.userData).length>0&&r.events?.onMeshMetadataClicked?.(A.userData))}else p(),r.events?.onBackgroundClicked?.({x:s.x,y:s.y})},E=m=>{let T=e.getBoundingClientRect();s.x=(m.clientX-T.left)/T.width*2-1,s.y=-((m.clientY-T.top)/T.height)*2+1,y(),i.setFromCamera(s,c());let b=i.intersectObjects(n.children,!0).filter(V=>d(V.object));if(b.length===0)return;let v=b[0].object;if(r.events?.onMeshDoubleClicked?.(v),!r.events?.enableDoubleClickZoom)return;let A=new h.Box3().setFromObject(v);A.isEmpty()||t.frameBounds(A,!0)},x=m=>{if(r.events?.enableKeyboardControls)switch(m.key.toLowerCase()){case"f":m.preventDefault(),u();break;case"escape":m.preventDefault(),p();break;case" ":m.preventDefault(),u();break}};return r.events?.enableClickToFocus&&(e.addEventListener("mousedown",R),e.addEventListener("click",w),e.addEventListener("dblclick",E)),r.events?.enableKeyboardControls&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",x)),{dispose:()=>{e.removeEventListener("mousedown",R),e.removeEventListener("click",w),e.removeEventListener("dblclick",E),e.removeEventListener("keydown",x),p()},fitToView:u,clearSelection:p}}function vn(e,n,t){let r=new sn(e,n),a=t.camera.target;return a&&r.target.set(a.x,a.y,a.z),r.enableDamping=t.controls.enableDamping||!1,r.dampingFactor=t.controls.dampingFactor||.05,r.autoRotate=t.controls.autoRotate||!1,r.autoRotateSpeed=t.controls.autoRotateSpeed||.5,r.enableZoom=t.controls.enableZoom??!0,r.enablePan=t.controls.enablePan??!0,r.minDistance=t.controls.minDistance||.001,r.maxDistance=t.controls.maxDistance||1/0,r.screenSpacePanning=!1,r.maxPolarAngle=Math.PI,r.update(),r}import*as W from"three";import{Line2 as xn}from"three/addons/lines/Line2.js";import{LineGeometry as Hn}from"three/addons/lines/LineGeometry.js";import{LineMaterial as Mn}from"three/addons/lines/LineMaterial.js";function he(e,n,t,r=!0){return{x:e,y:n,z:t}}var Cn="#ffffff",Ke=12,An=4e-4,Sn=12,Dn=.05;function Je(e,n={}){if(!e||e.length===0)return[];let{rhino:t,applyTransforms:r=!0}=n,a=[];for(let o of e)switch(o.kind){case"curve":{let i=On(o,t,r);i&&a.push(i);break}case"point":{let i=Pn(o,r);i&&a.push(i);break}default:{let s=o;C().warn(`Skipping unknown display item kind: ${String(s.kind)}`);break}}return a}var Ln=2;function On(e,n,t){if(!n)return C().warn("No rhino3dm instance provided; skipping curve display item."),null;let r=In(e.json,n);if(!r)return null;let a;try{a=Vn(r,t)}catch(u){return C().warn("Failed to tessellate curve display item; skipping.",u),null}finally{ie(r)}if(a.length<2)return null;let o=[];for(let u of a)o.push(u.x,u.y,u.z);let i=new Hn;i.setPositions(o);let s=Qe(e.color,e.opacity),l=new Mn({color:s.color}),c=l;c.linewidth=e.width??Ln,c.transparent=s.transparent,c.opacity=s.opacity;let d=new xn(i,l);return d.computeLineDistances(),d.name=e.name,d.userData={source:"compute",id:e.id,layer:e.layer,kind:"curve",metadata:e.metadata},d}function Pn(e,n){let{position:t}=e;if(!t||typeof t.X!="number"||!Number.isFinite(t.X)||typeof t.Y!="number"||!Number.isFinite(t.Y)||typeof t.Z!="number"||!Number.isFinite(t.Z))return C().warn(`Skipping point display item with missing or non-finite position (id: ${String(e.id)}).`),null;let{x:r,y:a,z:o}=he(t.X,t.Y,t.Z,n),i=new W.BufferGeometry;i.setAttribute("position",new W.Float32BufferAttribute([r,a,o],3));let s=new W.PointsMaterial({...Qe(e.color,e.opacity),size:6,sizeAttenuation:!1}),l=new W.Points(i,s);return l.name=e.name,l.userData={source:"compute",id:e.id,layer:e.layer,kind:"point",metadata:e.metadata},l}function ie(e){e?.delete?.()}function In(e,n){try{let t=JSON.parse(e),r=n.CommonObject.decode(t);return r&&typeof r.pointAt=="function"?r:(ie(r),C().warn("Decoded display-item JSON is not a curve; skipping."),null)}catch(t){return C().warn("Failed to decode curve display item JSON:",t),null}}function Vn(e,n){let t=Bn(e,n);return t||Fn(e,n)}function Bn(e,n){if(!e.isPolyline())return null;let t=e.tryGetPolyline(),r=Array.isArray(t)?t[1]:t;if(!r||typeof r.count!="number"||r.count<2)return ie(r),null;let a=[];for(let o=0;o<r.count;o++){let i=r.get(o),{x:s,y:l,z:c}=he(i[0],i[1],i[2],n);a.push(new W.Vector3(s,l,c))}return ie(r),a}function Fn(e,n){let t=e.domain,r=t[0],o=t[1]-r,i=u=>{let f=e.pointAt(u),{x:p,y:g,z:y}=he(f[0],f[1],f[2],n);return new W.Vector3(p,g,y)},s=Un(e),l=r,c=i(r),d=[c];for(let u=0;u<Ke;u++){let f=r+o*(u+1)/Ke,p=i(f);Re(l,c,f,p,i,s,Sn,d),d.push(p),l=f,c=p}return d}function Re(e,n,t,r,a,o,i,s){if(i<=0)return;let l=(e+t)/2,c=a(l),d=_n(c,n,r),u=zn(n,c,r);d<=o&&u<=Dn||(Re(e,n,l,c,a,o,i-1,s),s.push(c),Re(l,c,t,r,a,o,i-1,s))}function Un(e){let n=e.getBoundingBox(),t=n.min,r=n.max;ie(n);let a=Math.hypot(r[0]-t[0],r[1]-t[1],r[2]-t[2]);return Math.max(a*An,1e-6)}function zn(e,n,t){let r=n.x-e.x,a=n.y-e.y,o=n.z-e.z,i=t.x-n.x,s=t.y-n.y,l=t.z-n.z,c=Math.sqrt(r*r+a*a+o*o),d=Math.sqrt(i*i+s*s+l*l);if(c===0||d===0)return 0;let u=r*i+a*s+o*l,f=Math.max(-1,Math.min(1,u/(c*d)));return Math.acos(f)}function _n(e,n,t){let r=t.x-n.x,a=t.y-n.y,o=t.z-n.z,i=r*r+a*a+o*o;if(i===0)return e.distanceTo(n);let s=e.x-n.x,l=e.y-n.y,c=e.z-n.z,d=Math.max(0,Math.min(1,(s*r+l*a+c*o)/i)),u=s-r*d,f=l-a*d,p=c-o*d;return Math.sqrt(u*u+f*f+p*p)}function Qe(e,n){let t=n??1;return{color:new W.Color(e??Cn),transparent:t<1,opacity:t}}import{inflateSync as kn}from"fflate";var et=1096174675,jn=1515605075,tt=3,nt=1,ve=1,Gn=2,Nn=4,Wn=8,$n=16,Mo=0,Yn=1,rt=12,ot=56,Xn=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;function xe(e){if(!Xn)throw new ne("SLVA parsing requires a little-endian host: the zero-copy geometry readers view the wire bytes in host byte order.",te.ENVIRONMENT_ERROR);let n=Jn(Kn(e)),t=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n.byteLength<rt)throw j("Blob too small to contain SLVA header.",{expectedBytes:rt,availableBytes:n.byteLength});let r=0,a=t.getUint32(r,!0);if(r+=4,a!==et)throw j(`Invalid SLVA magic: 0x${a.toString(16)}`,{expectedMagic:`0x${et.toString(16)}`,actualMagic:`0x${a.toString(16)}`});let o=t.getUint32(r,!0);if(r+=4,o<nt||o>tt)throw j(`Unsupported SLVA version: ${o}`,{minSupportedVersion:nt,maxSupportedVersion:tt,actualVersion:o});let i=t.getUint32(r,!0);if(r+=4,r+i>n.byteLength)throw j("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:n.byteLength-r,offset:r});let s=n.subarray(r,r+i);r+=i;let l;try{l=JSON.parse(Qn(s))}catch(q){throw j(`Failed to parse metadata JSON: ${q instanceof Error?q.message:String(q)}`,{metadataLen:i})}if(r+ot>n.byteLength)throw j("Insufficient data to read geometry header.",{expectedBytes:ot,availableBytes:n.byteLength-r,offset:r});let c=t.getUint32(r,!0);r+=4;let d=t.getFloat64(r,!0);r+=8;let u=t.getFloat64(r,!0);r+=8;let f=t.getFloat64(r,!0);r+=8;let p=t.getFloat64(r,!0);r+=8;let g=t.getFloat64(r,!0);r+=8;let y=t.getFloat64(r,!0);r+=8;let R=t.getUint32(r,!0);r+=4;let w=(c&ve)!==0,E=(c&Nn)!==0,x=R*3,m=x*(w?4:2);if(r+m>n.byteLength)throw j("Insufficient data to read vertices.",{expectedBytes:m,availableBytes:n.byteLength-r,offset:r,useFloat32:w,vertexCount:R});let T=n.byteOffset+r,b;if(w?b=it(n.buffer,T,x):E?b=rr(we(n.buffer,T,x)):b=er(n.buffer,T,x),r+=m,r+4>n.byteLength)throw j("Insufficient data to read index count.",{expectedBytes:4,availableBytes:n.byteLength-r,offset:r});let v=t.getUint32(r,!0);r+=4;let A=(c&Gn)!==0,$=v*(A?2:4);if(r+$>n.byteLength)throw j("Insufficient data to read indices.",{expectedBytes:$,availableBytes:n.byteLength-r,offset:r,indexCount:v,useUint16Indices:A});let B=A?we(n.buffer,n.byteOffset+r,v):tr(n.buffer,n.byteOffset+r,v);E&&(B=B instanceof Uint16Array?or(B):ar(B)),nr(B,R),r+=$;let Y=null;if((c&Wn)!==0){let q=qn(n,t,r,R,E);Y=q.uvs,r=q.offset}let G=null;return(c&$n)!==0&&(G=Zn(n,r,R,E)),{metadata:l,flags:c,vertices:b,indices:B,origin:[d,u,f],scale:[p,g,y],uvs:Y,colors:G}}var at=36;function qn(e,n,t,r,a){if(t+at>e.byteLength)throw j("Insufficient data to read UV chunk header.",{expectedBytes:at,availableBytes:e.byteLength-t,offset:t});let o=n.getUint32(t,!0);t+=4;let i=n.getFloat64(t,!0);t+=8;let s=n.getFloat64(t,!0);t+=8;let l=n.getFloat64(t,!0);t+=8;let c=n.getFloat64(t,!0);t+=8;let d=r*2,u=o===Yn,f=d*(u?4:2);if(t+f>e.byteLength)throw j("Insufficient data to read UV chunk.",{expectedBytes:f,availableBytes:e.byteLength-t,offset:t,uvFormat:o,vertexCount:r});let p=e.byteOffset+t,g;if(u)g=it(e.buffer,p,d).slice();else{let y=we(e.buffer,p,d);g=new Float32Array(d);let R=0,w=0;for(let E=0;E<d;E+=2)a?(R=R+K(y[E])&65535,w=w+K(y[E+1])&65535):(R=y[E],w=y[E+1]),g[E]=i+R*l,g[E+1]=s+w*c}return{uvs:g,offset:t+f}}function Zn(e,n,t,r){let a=t*3;if(n+a>e.byteLength)throw j("Insufficient data to read vertex-color chunk.",{expectedBytes:a,availableBytes:e.byteLength-n,offset:n,vertexCount:t});let o=e.subarray(n,n+a);if(!r)return o.slice();let i=new Uint8Array(a),s=0,l=0,c=0;for(let d=0;d<a;d+=3)s=s+K(o[d])&255,l=l+K(o[d+1])&255,c=c+K(o[d+2])&255,i[d]=s,i[d+1]=l,i[d+2]=c;return i}function Kn(e){return typeof e=="string"?Ae(e):e instanceof Uint8Array?e:new Uint8Array(e)}function Jn(e){if(e.byteLength<8)return e;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint32(0,!0)!==jn)return e;let t=n.getUint32(4,!0),r=e.subarray(8),a=Math.max(r.byteLength*1032+1024,1<<20);if(t>a)throw j("SLVZ header declares an implausible uncompressed length",{uncompressedLen:t,deflatedBytes:r.byteLength,maxPlausibleLen:a});let o;try{o=kn(r,{out:new Uint8Array(t+1)})}catch(i){throw j(`Failed to inflate SLVZ blob: ${i instanceof Error?i.message:String(i)}`,{uncompressedLen:t,deflatedBytes:r.byteLength})}if(o.byteLength!==t)throw j("SLVZ payload inflated to a different size than the header declares.",{declaredLen:t,actualLen:o.byteLength,deflatedBytes:r.byteLength});return o}function Qn(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 ne("No UTF-8 decoder available in this environment.",te.INVALID_STATE)}function er(e,n,t){if(t===0)return new Int16Array(0);if(n%2===0)return new Int16Array(e,n,t);let r=new Uint8Array(t*2);return r.set(new Uint8Array(e,n,t*2)),new Int16Array(r.buffer)}function it(e,n,t){if(t===0)return new Float32Array(0);if(n%4===0)return new Float32Array(e,n,t);let r=new Uint8Array(t*4);return r.set(new Uint8Array(e,n,t*4)),new Float32Array(r.buffer)}function we(e,n,t){if(t===0)return new Uint16Array(0);if(n%2===0)return new Uint16Array(e,n,t);let r=new Uint8Array(t*2);return r.set(new Uint8Array(e,n,t*2)),new Uint16Array(r.buffer)}function tr(e,n,t){if(t===0)return new Uint32Array(0);if(n%4===0)return new Uint32Array(e,n,t);let r=new Uint8Array(t*4);return r.set(new Uint8Array(e,n,t*4)),new Uint32Array(r.buffer)}function nr(e,n){if(e.length!==0&&!(e instanceof Uint16Array&&n>65535)){for(let t=0;t<e.length;t++)if(e[t]>=n)throw j("Index out of range of vertexCount.",{indexPosition:t,indexValue:e[t],vertexCount:n})}}function K(e){return e>>>1^-(e&1)}function rr(e){let n=new Int16Array(e.length),t=0,r=0,a=0;for(let o=0;o<e.length;o+=3)t=t+K(e[o])<<16>>16,r=r+K(e[o+1])<<16>>16,a=a+K(e[o+2])<<16>>16,n[o]=t,n[o+1]=r,n[o+2]=a;return n}function or(e){let n=new Uint16Array(e.length),t=0;for(let r=0;r<e.length;r++)t=t+K(e[r])&65535,n[r]=t;return n}function ar(e){let n=new Uint32Array(e.length),t=0;for(let r=0;r<e.length;r++)t=t+K(e[r])>>>0,n[r]=t;return n}function j(e,n){return new ne(e,te.VALIDATION_ERROR,{context:n})}import*as I from"three";async function Po(e,n){let{debug:t=!1}=n??{},r=t?performance.now():0,a,o=performance.now();try{a=JSON.parse(e)}catch(s){return C().error("Error parsing mesh batch envelope JSON:",s),[]}let i=performance.now()-o;return await He(a,n,{parseTime:i,perfStart:r})}async function He(e,n,t){let{mergeByMaterial:r=!0,applyTransforms:a=!0,debug:o=!1,material:i}=n??{},{parseTime:s=0,perfStart:l=o?performance.now():0}=t??{};if(!e.compressedData)return[];let c=performance.now(),d=xe(e.compressedData),u=performance.now()-c,f=o?fr(e.compressedData):0;return st(d,{mergeByMaterial:r,applyTransforms:a,debug:o,material:i,parseTime:s,decodeTime:u,perfStart:l,blobBytes:f,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}async function Io(e,n){let{mergeByMaterial:t=!0,applyTransforms:r=!0,debug:a=!1,material:o}=n??{},i=a?performance.now():0,s=performance.now(),l=xe(e),c=performance.now()-s,d=e.byteLength;return st(l,{mergeByMaterial:t,applyTransforms:r,debug:a,material:o,parseTime:0,decodeTime:c,perfStart:i,blobBytes:d})}function st(e,n){let{mergeByMaterial:t,applyTransforms:r,debug:a,material:o,parseTime:i,decodeTime:s,perfStart:l,blobBytes:c,fallback:d}=n,u=e.metadata.materials??d?.materials??[],f=e.metadata.groups??d?.groups??[],p=d?.sourceComponentId??e.metadata.sourceComponentId,g=(e.flags&ve)!==0;ir(f,u.length,e.vertices.length/3,e.indices.length);let y=g?lr(e.vertices,r):sr(e.vertices,e.origin,e.scale,r);if(a){let O=e.vertices.byteLength+e.indices.byteLength;C().debug("Mesh Batch Stats:"),C().debug(` Materials: ${u.length} | Groups: ${f.length}`),C().debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),C().debug(` Format: ${g?"float32":"int16 quantized"}`),C().debug(` Blob: ${(c/1024/1024).toFixed(2)} MB | Geometry on wire: ${(O/1024/1024).toFixed(2)} MB`)}let R=performance.now(),w=u.map(O=>cr(O,{vertexColors:e.colors!=null,appearance:o})),E=[];for(let O of f)if(t&&O.meshes.length>1){let m=dr(O,y,e.indices,w,e.uvs,e.colors);m.userData.sourceComponentId=p??null,E.push(m)}else{let m=mr(O,y,e.indices,w,e.uvs,e.colors);for(let T of m)T.userData.sourceComponentId=p??null;E.push(...m)}let x=performance.now()-R;if(a){let O=performance.now()-l;C().debug("Performance:"),i>0&&C().debug(` Parse JSON: ${i.toFixed(2)}ms`),C().debug(` Decode binary: ${s.toFixed(2)}ms`),C().debug(` Create Meshes: ${x.toFixed(2)}ms`),C().debug(` Total: ${O.toFixed(2)}ms`)}return Promise.resolve(E)}function se(e,n){return new ne(e,te.VALIDATION_ERROR,{context:n})}function ir(e,n,t,r){for(let a of e){if(!Number.isInteger(a.materialId)||a.materialId<0||a.materialId>=n)throw se("Group materialId out of range of the materials array.",{materialId:a.materialId,materialCount:n});for(let o of a.meshes){let i={vertexStart:o.vertexStart,vertexCount:o.vertexCount,indexStart:o.indexStart,indexCount:o.indexCount};for(let[s,l]of Object.entries(i))if(!Number.isInteger(l)||l<0)throw se(`Mesh metadata field "${s}" must be a non-negative integer.`,{meshName:o.name,field:s,value:l});if(o.vertexStart+o.vertexCount>t)throw se("Mesh vertex window exceeds the batch vertex buffer.",{meshName:o.name,vertexStart:o.vertexStart,vertexCount:o.vertexCount,totalVertexCount:t});if(o.indexStart+o.indexCount>r)throw se("Mesh index window exceeds the batch index buffer.",{meshName:o.name,indexStart:o.indexStart,indexCount:o.indexCount,totalIndexCount:r})}}}function lt(e,n){if(e<n.vertexStart||e>=n.vertexStart+n.vertexCount)throw se("Index references a vertex outside its mesh's vertex window.",{meshName:n.name,indexValue:e,vertexStart:n.vertexStart,vertexCount:n.vertexCount})}function sr(e,n,t,r){let a=new Float32Array(e.length),o=n[0],i=n[1],s=n[2],l=t[0],c=t[1],d=t[2];for(let u=0;u<e.length;u+=3)a[u]=o+(e[u]+32767)*l,a[u+1]=i+(e[u+1]+32767)*c,a[u+2]=s+(e[u+2]+32767)*d;return a}function lr(e,n){return e}function cr(e,n){let t=Be(e.color),r=n?.vertexColors??!1,a=n?.appearance,o=new I.MeshPhysicalMaterial({color:t,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,vertexColors:r,side:a?.cullBackfaces?I.FrontSide:I.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0});return a?.envMapIntensity!=null&&(o.envMapIntensity=a.envMapIntensity),r&&ur(o),e.map&&Ze(o,e.map),o}function ur(e){e.onBeforeCompile=n=>{n.vertexShader=n.vertexShader.replace("#include <color_vertex>",`#include <color_vertex>
|
|
55
|
+
#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
|
|
56
|
+
vColor.rgb = mix(
|
|
57
|
+
vColor.rgb / 12.92,
|
|
58
|
+
pow( ( vColor.rgb + 0.055 ) / 1.055, vec3( 2.4 ) ),
|
|
59
|
+
step( vec3( 0.04045 ), vColor.rgb )
|
|
60
|
+
);
|
|
61
|
+
#endif`)}}function dr(e,n,t,r,a=null,o=null){let i=0,s=0;for(let E of e.meshes)i+=E.vertexCount,s+=E.indexCount;let l=new Float32Array(i*3),c=new Uint32Array(s),d=a?new Float32Array(i*2):null,u=o?new Uint8Array(i*3):null,f=0,p=0;for(let E of e.meshes){let x=E.vertexStart*3,O=E.vertexCount*3;if(l.set(n.subarray(x,x+O),f*3),d&&a){let b=E.vertexStart*2;d.set(a.subarray(b,b+E.vertexCount*2),f*2)}u&&o&&u.set(o.subarray(x,x+O),f*3);let m=t.subarray(E.indexStart,E.indexStart+E.indexCount),T=f-E.vertexStart;for(let b=0;b<m.length;b++){let v=m[b];lt(v,E),c[p+b]=v+T}f+=E.vertexCount,p+=E.indexCount}let g=new I.BufferGeometry;g.setAttribute("position",new I.BufferAttribute(l,3)),g.setIndex(new I.BufferAttribute(c,1)),d&&g.setAttribute("uv",new I.BufferAttribute(d,2)),u&&g.setAttribute("color",new I.BufferAttribute(u,3,!0)),g.computeVertexNormals();let y=new I.Mesh(g,r[e.materialId]),R=e.meshes[0],w=e.meshes.map(E=>E.name).filter(E=>E&&E.length>0);return y.name=w.length>0?w[0]:`merged_material_${e.materialId}`,y.castShadow=!0,y.receiveShadow=!0,y.userData={source:"compute",name:y.name,layer:R?.layer??"",originalIndex:R?.originalIndex??0,metadata:R?.metadata??{},mergedFrom:e.meshes.slice(1).map(E=>({name:E.name,layer:E.layer,originalIndex:E.originalIndex}))},y}function mr(e,n,t,r,a=null,o=null){let i=[];for(let s of e.meshes){let l=s.vertexStart*3,c=s.vertexCount*3,d=n.slice(l,l+c),u=t.subarray(s.indexStart,s.indexStart+s.indexCount),f=new Uint32Array(u.length),p=s.vertexStart;for(let R=0;R<u.length;R++){let w=u[R];lt(w,s),f[R]=w-p}let g=new I.BufferGeometry;if(g.setAttribute("position",new I.BufferAttribute(d,3)),g.setIndex(new I.BufferAttribute(f,1)),a){let R=s.vertexStart*2,w=a.slice(R,R+s.vertexCount*2);g.setAttribute("uv",new I.BufferAttribute(w,2))}if(o){let R=o.slice(l,l+c);g.setAttribute("color",new I.BufferAttribute(R,3,!0))}g.computeVertexNormals();let y=new I.Mesh(g,r[e.materialId]);y.name=s.name,y.userData={source:"compute",name:s.name,layer:s.layer??"",originalIndex:s.originalIndex,metadata:s.metadata??{}},y.castShadow=!0,y.receiveShadow=!0,i.push(y)}return i}function fr(e){return Math.floor(e.length*3/4)}var ct={Angstroms:1e-10,Nanometers:1e-9,Microns:1e-6,Millimeters:.001,Centimeters:.01,Decimeters:.1,Meters:1,Dekameters:10,Hectometers:100,Kilometers:1e3,Megameters:1e6,Gigameters:1e9,Microinches:254e-10,Mils:254e-7,Inches:.0254,Feet:.3048,Yards:.9144,Miles:1609.344,NauticalMiles:1852},pr="Display",Er="DisplayBatch";function hr(e){let n=e.split(".");return n.includes(pr)||n.includes(Er)}var ut=new Set;async function _o(e,n){let t=performance.now(),r=[],{allowScaling:a=!0,allowAutoPosition:o=!0,rhino:i,debug:s=!1,parsing:l={}}=n??{};try{let c=a?gr(e.modelunits):1;return await yr(e,r,c,l,i,s),o&&wr(r),r}catch(c){throw vr(c,r),c}finally{s&&Hr(t)}}function gr(e){let n=ct[e];return n!==void 0?n:(ut.has(e)||(ut.add(e),C().warn(`Unknown Rhino model unit "${e}" \u2014 geometry will not be scaled (factor 1). Known units: ${Object.keys(ct).join(", ")}.`)),1)}async function yr(e,n,t,r,a,o){for(let i of e.values){let s=i.InnerTree;for(let l in s){let c=s[l];c&&await br(c,n,t,r,a,o)}}}async function br(e,n,t,r,a,o){for(let i of e){if(!hr(i.type))continue;let s={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...r},l=Tr(i.data);if(!l){C().error("Error parsing display batch envelope: invalid JSON");continue}let c=await He(l,s),d=Je(l.items,{rhino:a,applyTransforms:s.applyTransforms}),u=[...c,...d];if(t!==1)for(let f of u)f.scale.set(t,t,t);n.push(...u),o&&C().debug(`Extracted ${c.length} meshes and ${d.length} items from batch`)}}function Tr(e){return typeof e=="string"?Rr(e):e}function Rr(e){try{return JSON.parse(e)}catch{return}}function wr(e){if(e.length===0)return;let n=oe(e);Fe(e,n.min.z,"z")}function vr(e,n){C().error("An unexpected error occurred:",e),xr(n)}function xr(e){for(let n of e){let t=n;t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(r=>r.dispose()):t.material.dispose())}}function Hr(e){let n=performance.now()-e;C().info("Time to process meshes:",`${n.toFixed(2)}ms`)}export{ht as a,Sr as b,Be as c,Fe as d,oe as e,Ue as f,ze as g,_e as h,ce as i,je as j,Ft as k,zr as l,Ge as m,We as n,Qt as o,Xe as p,en as q,qe as r,eo as s,cn as t,po as u,Je as v,et as w,jn as x,tt as y,nt as z,ve as A,Gn as B,Nn as C,Wn as D,$n as E,Mo as F,Yn as G,xe as H,Po as I,He as J,Io as K,ct as L,_o as M};
|
|
62
|
+
//# sourceMappingURL=chunk-ORGJSKR4.js.map
|