@selvajs/compute 3.1.0-beta.1 → 3.1.0-beta.3
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-ESPPM542.js → chunk-CTZ4ZOSM.js} +2 -2
- package/dist/{chunk-DRG5SLIP.cjs → chunk-EUMIGWRX.cjs} +2 -2
- package/dist/chunk-EUMIGWRX.cjs.map +1 -0
- package/dist/chunk-HNG75VAI.js +55 -0
- package/dist/chunk-HNG75VAI.js.map +1 -0
- package/dist/{chunk-LP7LO5PR.cjs → chunk-JIE3W4KP.cjs} +2 -2
- package/dist/{chunk-LP7LO5PR.cjs.map → chunk-JIE3W4KP.cjs.map} +1 -1
- package/dist/chunk-L3CNT26S.cjs +55 -0
- package/dist/{chunk-QZ573TYU.cjs.map → chunk-L3CNT26S.cjs.map} +1 -1
- package/dist/{chunk-J3MFKB33.js → chunk-QAOHGIFT.js} +2 -2
- package/dist/chunk-QAOHGIFT.js.map +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.d.cts +2 -2
- package/dist/core.d.ts +2 -2
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.d.cts +4 -4
- package/dist/grasshopper.d.ts +4 -4
- package/dist/grasshopper.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{types-jb_K_a0s.d.ts → types-B-JygDUF.d.ts} +1 -1
- package/dist/{types-DK2-skCK.d.cts → types-DGeAQnkB.d.cts} +1 -1
- package/dist/{types-ChF690kY.d.cts → types-V7G83j5m.d.cts} +12 -0
- package/dist/{types-ChF690kY.d.ts → types-V7G83j5m.d.ts} +12 -0
- package/dist/visualization-SI2GEY4M.cjs +2 -0
- package/dist/{visualization-3E3Q76VG.cjs.map → visualization-SI2GEY4M.cjs.map} +1 -1
- package/dist/{visualization-XBMHHG6L.js → visualization-UJZN4PJD.js} +2 -2
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.d.cts +3 -3
- package/dist/visualization.d.ts +3 -3
- package/dist/visualization.js +1 -1
- package/package.json +3 -3
- package/dist/chunk-C2HJB4MH.js +0 -55
- package/dist/chunk-C2HJB4MH.js.map +0 -1
- package/dist/chunk-DRG5SLIP.cjs.map +0 -1
- package/dist/chunk-J3MFKB33.js.map +0 -1
- package/dist/chunk-QZ573TYU.cjs +0 -55
- package/dist/visualization-3E3Q76VG.cjs +0 -2
- /package/dist/{chunk-ESPPM542.js.map → chunk-CTZ4ZOSM.js.map} +0 -0
- /package/dist/{visualization-XBMHHG6L.js.map → visualization-UJZN4PJD.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as l,c as h,d as f,e as d,h as U,i as z,k as $,l as A,m as _,n as q,r as N}from"./chunk-J3MFKB33.js";function p(t,e){if(!t||typeof t!="object")return;let r=t;if(e in r)return r[e];let n=J(r).get(e.toLowerCase());return n===void 0?void 0:r[n]}function L(t,e){if(!t||typeof t!="object")return!1;let r=t;return e in r?!0:J(r).has(e.toLowerCase())}var H=new WeakMap;function J(t){let e=H.get(t);if(!e){e=new Map;for(let r of Object.keys(t)){let n=r.toLowerCase();e.has(n)||e.set(n,r)}H.set(t,e)}return e}function C(t,e){e||typeof window<"u"&&d().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`)}var Ie="Unable to load grasshopper definition";function xe(t){return t instanceof f?t.code===h.DEFINITION_NOT_CACHED||t.message.includes(Ie):!1}function Y(t,e){if(!e)return;let r=p(t,"values");if(!Array.isArray(r)||r.length===0)return;let n=[];for(let o of r){let a=p(o,"innerTree");(!a||Object.keys(a).length===0)&&n.push(p(o,"paramName")??"<unnamed>")}if(n.length===0)return;let s=n.length===r.length?"all":`${n.length}/${r.length}`;d().warn(`Solve returned empty output(s) (${s}): ${n.join(", ")}. These parameters produced no data \u2014 check the definition's inputs and the branch feeding each.`)}async function D(t,e,r){r.debug&&C("solveGrasshopperDefinition",r.suppressBrowserWarning??r.suppressClientSideWarning);let{response:n}=await O(P(e,t),r);return n}async function Q(t,e,r){return r.debug&&C("solveGrasshopperDefinitionWithCacheKey",r.suppressBrowserWarning??r.suppressClientSideWarning),O(P(e,t),r)}async function X(t,e,r,n){n.debug&&C("solveByCacheKey",n.suppressBrowserWarning??n.suppressClientSideWarning);let s={algo:null,pointer:e,values:t};try{return{...await O(s,n),missed:!1}}catch(o){if(!xe(o))throw o;return{...await O(P(r,t),n),missed:!0}}}async function O(t,e){De(t,e);let r=await A("grasshopper",t,e);if("pointer"in r){let{pointer:n,...s}=r,o=s;return Y(o,e.debug),{response:o,cacheKey:typeof n=="string"?n:null}}return Y(r,e.debug),{response:r,cacheKey:null}}function P(t,e){let r={algo:null,pointer:null,values:e};return t instanceof Uint8Array?r.algo=$(t):/^https?:\/\//i.test(t)?r.pointer=t:z(t)?r.algo=t:r.algo=U(t),r}function De(t,e){e.cachesolve!=null&&(t.cachesolve=e.cachesolve),e.cacheerroredsolves!=null&&(t.cacheerroredsolves=e.cacheerroredsolves),e.modelunits!=null&&(t.modelunits=e.modelunits),e.angletolerance!=null&&(t.angletolerance=e.angletolerance),e.absolutetolerance!=null&&(t.absolutetolerance=e.absolutetolerance),e.dataversion!=null&&(t.dataversion=e.dataversion)}function Pe(t){let e=new WeakSet,r=n=>{if(n==null)return JSON.stringify(n);if(typeof n=="number")return Number.isFinite(n)?String(n):JSON.stringify(null);if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="bigint")return JSON.stringify(n.toString());if(n instanceof Uint8Array){let s=n.length>64?Array.from(n.slice(0,32)).concat(Array.from(n.slice(-32))):Array.from(n);return JSON.stringify({__u8:!0,len:n.length,sample:s})}return Array.isArray(n)?`[${n.map(r).join(",")}]`:typeof n=="object"?e.has(n)?JSON.stringify("[Circular]"):(e.add(n),`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${r(n[a])}`).join(",")}}`):JSON.stringify(null)};return r(t)}function Z(t,e){let r=2166136261;for(let n=0;n<t;n++)r^=e(n),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r.toString(16).padStart(8,"0")}function ee(t){return Z(t.length,e=>t.charCodeAt(e))}function Re(t){return Z(t.length,e=>t[e])}function te(t,e){return ee(`${W(t)}|${Pe(e)}`)}function W(t){return typeof t=="string"?`s:${t.length}:${ee(t)}`:`u8:${t.length}:${Re(t)}`}var we=100;function Ee(t){return t instanceof Uint8Array?!0:!/^https?:\/\//i.test(t)}var S=class{constructor(e,r,n={},s){l(this,"executor");l(this,"baseConfig");l(this,"mode");l(this,"maxConcurrent");l(this,"timeoutMs");l(this,"retry");l(this,"cacheEnabled");l(this,"cacheMax");l(this,"cacheTtl");l(this,"cache",new Map);l(this,"cacheKeyExecutor");l(this,"reuseServerDefinitionCache");l(this,"serverCacheKeys",new Map);l(this,"onStart");l(this,"onSettle");l(this,"onSuperseded");l(this,"subscribers",new Set);l(this,"inFlight",new Set);l(this,"pendingForLatestWins",null);l(this,"fifoQueue",[]);l(this,"_lastResult",null);l(this,"_lastError",null);l(this,"_lastDurationMs",null);l(this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=s,this.baseConfig=r,this.mode=n.mode??"latest-wins",this.maxConcurrent=Math.max(1,n.maxConcurrent??(this.mode==="parallel"?4:1)),this.timeoutMs=n.timeoutMs,this.retry=n.retry;let o=n.cache;this.cacheEnabled=o!==void 0&&o!==!1;let a=typeof o=="object"?o:{};this.cacheMax=a.maxEntries??50,this.cacheTtl=a.ttlMs??0,this.reuseServerDefinitionCache=!!s&&(n.reuseServerDefinitionCache??!0),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+(this.pendingForLatestWins?1:0)}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(r){d().error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new f("SolveScheduler has been disposed and cannot be used",h.INVALID_STATE));let s=te(e,r),o={key:s,enqueuedAt:Date.now(),startedAt:null};if(this.cacheEnabled){let a=this.readCache(s);if(a){let i={status:"success",response:a,durationMs:0,fromCache:!0};return this._lastResult=a,this._lastError=null,this._lastDurationMs=0,this.runHook(this.onStart,o),this.runHook(this.onSettle,o,i),this.notify(),Promise.resolve(a)}}return new Promise((a,i)=>{let u={definition:e,dataTree:r,ctx:o,resolve:a,reject:i,externalSignal:n?.signal};if(u.externalSignal?.aborted){this.settleError(u,this.makeAbortError(o));return}this.enqueue(u)})}enqueue(e){switch(this.mode){case"latest-wins":{this.pendingForLatestWins&&(this.supersede(this.pendingForLatestWins),this.pendingForLatestWins=null);for(let r of this.inFlight)this.supersede(r),r.controller.abort();this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break}case"queue":case"parallel":{this.inFlight.size<this.maxConcurrent?this.execute(e):this.fifoQueue.push(e);break}}this.notify()}async execute(e){let r=new AbortController,n=e;n.controller=r,this.inFlight.add(n),e.ctx.startedAt=Date.now();let s=()=>r.abort();e.externalSignal?.addEventListener("abort",s,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let o=performance.now();try{let a={...this.baseConfig,signal:r.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},{response:i,definitionReuploaded:u}=await this.runExecutor(e.definition,e.dataTree,a),c=performance.now()-o;if(this.cacheEnabled&&this.writeCache(e.ctx.key,i),!this.settleSuccess(e,i))return;this._lastResult=i,this._lastError=null,this._lastDurationMs=c,this.runHook(this.onSettle,e.ctx,{status:"success",response:i,durationMs:c,fromCache:!1,definitionReuploaded:u})}catch(a){let i=performance.now()-o,u=this.normalizeExecutionError(a,n);this._lastError=u,this._lastDurationMs=i,this.settleError(e,u)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:u,durationMs:i})}finally{e.externalSignal?.removeEventListener("abort",s),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,r,n){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!Ee(e))return{response:await this.executor(e,r,n)};let s=W(e),o=this.serverCacheKeys.get(s)??null,a=await this.cacheKeyExecutor(e,r,o,n);if(a.cacheKey)for(this.serverCacheKeys.delete(s),this.serverCacheKeys.set(s,a.cacheKey);this.serverCacheKeys.size>we;){let i=this.serverCacheKeys.keys().next().value;if(i===void 0)break;this.serverCacheKeys.delete(i)}else this.serverCacheKeys.delete(s);return{response:a.response,definitionReuploaded:a.missed}}drainNext(){if(!this.disposed){if(this.mode==="latest-wins"){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}return}for(;this.fifoQueue.length>0&&this.inFlight.size<this.maxConcurrent;){let e=this.fifoQueue.shift();this.execute(e)}}}supersede(e){let r=new f("Superseded by newer solve",h.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new f("Request aborted by caller",h.ABORTED,{context:{key:e.key,enqueuedAt:e.enqueuedAt}})}settleError(e,r){return e.settled?!1:(e.settled={error:r},e.reject(r),!0)}settleSuccess(e,r){return e.settled?!1:(e.settled={ok:!0},e.resolve(r),!0)}isAbortLikeError(e){if(e instanceof Error){if(e.name==="AbortError")return!0;if(typeof DOMException<"u"&&e instanceof DOMException)return e.name==="AbortError"}return!1}normalizeExecutionError(e,r){return r.settled&&"error"in r.settled?r.settled.error:e instanceof f?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new f(e instanceof Error?e.message:String(e),h.UNKNOWN_ERROR,{originalError:e instanceof Error?e:new Error(String(e))})}cancelAll(){for(this.pendingForLatestWins&&(this.rejectAsAborted(this.pendingForLatestWins),this.pendingForLatestWins=null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:e.ctx.startedAt?performance.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){this.settleError(e,this.makeAbortError(e.ctx))}readCache(e){if(!this.cacheEnabled)return null;let r=this.cache.get(e);return r?this.cacheTtl>0&&Date.now()-r.insertedAt>this.cacheTtl?(this.cache.delete(e),null):(this.cache.delete(e),this.cache.set(e,r),r.response):null}writeCache(e,r){if(this.cacheEnabled)for(this.cache.set(e,{response:r,insertedAt:Date.now()});this.cache.size>this.cacheMax;){let n=this.cache.keys().next().value;if(n===void 0)break;this.cache.delete(n)}}clearCache(){this.cache.clear()}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.cache.clear())}runHook(e,...r){if(e)try{e(...r)}catch(n){d().error("[SolveScheduler] hook threw:",n)}}};var R=class t{constructor(e){l(this,"config");l(this,"serverStats");l(this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new q(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e),n=Math.max(1,(e.retry?.attempts??2)+1),s=e.retry?.baseDelayMs??250,o=e.retry?.maxDelayMs??1e3;for(let a=0;a<n;a++){if(await r.serverStats.isServerOnline())return r;if(a<n-1){let i=Math.min(s*2**a,o);await new Promise(u=>setTimeout(u,i))}}throw await r.dispose(),new f("Rhino Compute server is not online",h.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:n}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),F(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),w(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!e?.trim())throw new f("Definition URL/content is required",h.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new f("Definition content is empty",h.INVALID_INPUT);let s={...this.config,...n?.signal!==void 0&&{signal:n.signal},...n?.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs},...n?.retry!==void 0&&{retry:n.retry}},o=await D(r,e,s);if(o?.errors&&o.errors.length>0)throw new f(o.errors.join("; ")||"Computation failed",h.COMPUTATION_ERROR,{context:{definition:typeof e=="string"&&e.length<200?e:"...content...",inputs:r,errors:o.errors,warnings:o.warnings}});return o}catch(s){throw this.config.debug&&d().error("Compute failed:",s),s instanceof f?s:new f(s instanceof Error?s.message:String(s),h.COMPUTATION_ERROR,{context:{definition:typeof e=="string"&&e.length<200?e:"...content...",inputs:r},originalError:s instanceof Error?s:new Error(String(s))})}}createScheduler(e){this.ensureNotDisposed();let r=(s,o,a)=>D(o,s,a),n=(s,o,a,i)=>a===null?Q(o,s,i).then(u=>({...u,missed:!1})):X(o,a,s,i);return new S(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new f("GrasshopperClient has been disposed and cannot be used",h.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:_(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning??e.suppressClientSideWarning}}};var G=new Map;function re(t,e){G.set(t,e)}re("Rhino.Geometry.Point3d",(t,e)=>{let r=e;return!r||typeof r.X!="number"?null:new t.Point([r.X,r.Y,r.Z])});re("Rhino.Geometry.Line",(t,e)=>{let r=e;return!r||!r.From||!r.To?null:new t.Line([r.From.X,r.From.Y,r.From.Z],[r.To.X,r.To.Y,r.To.Z])});function ve(t){if(G.has(t))return G.get(t);for(let[e,r]of G)if(t.startsWith(e))return r}function Ae(t){return!t||typeof t!="object"?null:t.data??t.value??null}function ne(t,e,r){let n=ve(e);if(n)try{return n(r,t)}catch(s){d().warn(`Failed to decode Rhino type ${e}:`,s)}try{let s=Ae(t);if(s)return r.CommonObject.decode(s)}catch(s){return d().warn(`Failed to decode ${e} with CommonObject:`,s),{__decodeError:!0,type:e,raw:t}}return t}var I={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},Ne="Rhino.Geometry.",Oe=["WebDisplay"],Fe="FileData";function se(t){return Oe.some(e=>t.includes(e))}function oe(t){if(typeof t!="string")return t;let e=t.trim();if(!(e.startsWith("{")||e.startsWith("[")||e.startsWith('"')))return t;try{let n=JSON.parse(e);if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}catch{return t}}function Ge(t,e,r){switch(e){case I.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case I.INT:return Number.parseInt(t,10);case I.DOUBLE:return Number.parseFloat(t);case I.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(Ne)?ne(t,e,r):t}}function ae(t,e,r,n){if(typeof t!="string")return t;let s=r?oe(t):t;return Ge(s,e,n)}function ke(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.fileName=="string"&&typeof e.fileType=="string"&&"data"in e&&typeof e.isBase64Encoded=="boolean"&&typeof e.subFolder=="string"}function k(t,e){for(let r of Object.values(t))if(Array.isArray(r))for(let n of r)e(n)}function ie(t,e=!1,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,a={},i=new Set;for(let u of t.values)k(u.InnerTree,c=>{if(se(c.type)||o&&c.type!==I.STRING)return;let m=e?c.id:u.ParamName;if(!m)return;let y=ae(c.data,c.type,n,s);m in a?i.has(m)?a[m].push(y):(a[m]=[a[m],y],i.add(m)):a[m]=y});return{values:a}}function ue(t){let e=[];for(let r of t.values)k(r.InnerTree,n=>{if(!n.type.includes(Fe))return;let s=oe(n.data);ke(s)&&e.push(s)});return e}function pe(t,e,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,a;if("byName"in e?a=t.values.find(u=>u.ParamName===e.byName):a=t.values.find(u=>{let c=!1;return k(u.InnerTree,m=>{m.id===e.byId&&(c=!0)}),c}),!a)return;let i=[];if(k(a.InnerTree,u=>{if("byId"in e&&u.id!==e.byId||se(u.type)||o&&u.type!==I.STRING)return;let c=ae(u.data,u.type,n,s);i.push(c)}),i.length!==0)return i.length===1?i[0]:i}var E=class{constructor(e,r=!1){this.response=e;this.debug=r}getValues(e=!1,r={}){return ie(this.response,e,r)}getValue(e,r){return pe(this.response,e,r)}async extractMeshesFromResponse(e){let r={debug:this.debug,...e},n;try{({getThreeMeshesFromComputeResponse:n}=await import("./visualization-XBMHHG6L.js"))}catch(s){throw new f("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",h.INVALID_STATE,{context:{originalError:s instanceof Error?s.message:String(s)}})}return n(this.response,r)}getFileData(){return ue(this.response)}async getAndDownloadFiles(e,r){let n=this.getFileData();await N(n,e,r)}};function le(t){return p(t,"data")}function Me(t){return p(t,"type")}function ce(t){if(typeof t.default!="object"||t.default===null)return{schema:t};if(!L(t.default,"innerTree")){let n=`Input "${t.name??"unknown"}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return d().warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=p(t.default,"innerTree")??{};if(Object.keys(e).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let n={};for(let[s,o]of Object.entries(e))n[s]=o.map(a=>{let i=le(a),u=Me(a);if(typeof i=="string"){if(u==="System.Double"||u==="System.Int32"){let c=Number(i);return Number.isNaN(c)?i:c}if(u==="System.Boolean")return i.toLowerCase()==="true";if(u?.startsWith("Rhino.Geometry"))try{return JSON.parse(i)}catch{return i}}return i});return{schema:{...t,default:n}}}let r=[];for(let n of Object.values(e))Array.isArray(n)&&n.forEach(s=>{s&&typeof s=="object"&&L(s,"data")&&r.push(le(s))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}var B=/^\{(\d+(?:;\d+)*)?\}$/;function v(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.entries(t);return e.length>0&&e.every(([r,n])=>B.test(r)&&Array.isArray(n))}function x(t,e,r){if(t==null)return t;if(Array.isArray(t)){let s=t.map(e).filter(o=>o!==null);return s.length>0?s:void 0}let n=e(t);return n!==null?n:r?void 0:t}var Ve=t=>{if(typeof t=="number")return t;if(typeof t=="string"){let e=t.trim();if(e==="")return null;let r=Number(e);return Number.isNaN(r)?null:r}return null},Le=t=>{if(typeof t=="boolean")return t;if(typeof t=="string"){let e=t.toLowerCase();if(e==="true")return!0;if(e==="false")return!1;throw new Error(`Invalid boolean string: "${t}"`)}return null},We=t=>typeof t=="string"?t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t.startsWith('"')?t.slice(1):t:null,Be=t=>{if(typeof t=="string"){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}return null};function me(t){return e=>{if(typeof e=="object"&&e!==null)return e;if(typeof e=="string"&&e.trim()!=="")try{let r=JSON.parse(e);return typeof r=="object"&&r!==null?r:(d().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return d().warn(`Failed to parse object value "${e}" for input ${t}`,r),null}return null}}function fe(t,e,r){let n=Number(t.toFixed(e));return Math.abs(t-n)<r?n:t}function je(t,e){if(!Number.isFinite(t)||t===0)return .1;let r=Math.abs(t);if(r>=1){let g=String(t).split(".")[1];if(g&&g.length>0){let b=Math.min(g.length,12),T=Math.pow(10,-b),K=Number(T.toFixed(b));return Math.abs(K-T)<e?K:T}return 1}let n=String(t),s=n.toLowerCase().match(/e(-?\d+)/);if(s){let y=Number(s[1]);if(y<0||n.toLowerCase().includes("e-")){let g=Math.abs(y),b=Math.pow(10,-g),T=Number(b.toFixed(g));return Math.abs(T-b)<e?T:b}return .1}let o=12,i=r.toFixed(o).replace(/0+$/,""),u=Math.min((i.split(".")[1]||"").length,o);if(u===0)return .1;let c=Math.pow(10,-u),m=Number(c.toFixed(u));return Math.abs(m-c)<e?m:c}function Ke(t,e=1e-8){let r=t.paramType==="Integer";if(v(t.default))return{default:t.default,stepSize:r?1:.1};let n=x(t.default,Ve,!0);if(r)return Array.isArray(n)?n=n.map(m=>typeof m=="number"?Math.round(m):m):typeof n=="number"&&(n=Math.round(n)),{default:n,stepSize:1};let s=Array.isArray(n)?n[0]:n,o;typeof s=="number"&&Number.isFinite(s)&&s!==0?o=s:typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum!==0?o=t.minimum:typeof t.maximum=="number"&&Number.isFinite(t.maximum)&&t.maximum!==0&&(o=t.maximum);let a=o!==void 0?je(o,e):.1,i=0,u=String(a),c=u.toLowerCase().match(/e(-?\d+)/);if(c?i=Math.abs(Number(c[1])):i=u.split(".")[1]?.length??0,i===0&&typeof s=="number"&&s!==0&&Math.abs(s)<1){let m=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(m)&&m>0&&(i=m)}return i=Math.min(Math.max(i,0),12),Array.isArray(n)?n=n.map(m=>typeof m=="number"?fe(m,i,e):m):typeof n=="number"&&(n=fe(n,i,e)),{default:n,stepSize:a}}var Ue={types:["Number","Integer"],parse(t,e){let{default:r,stepSize:n}=Ke(t);return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:n,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,default:r?[0]:0}}},ze={types:["Boolean"],parse(t,e){let r;try{r=x(t.default,Le,!1)}catch(n){throw n instanceof Error?new f(n.message):n}return{...e,paramType:"Boolean",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Boolean",default:r?[!1]:!1}}},$e={types:["Text"],parse(t,e){let r=x(t.default,We,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Text",default:r?[""]:""}}},_e={types:["ValueList"],parse(t,e){if(!t.values||typeof t.values!="object"||Object.keys(t.values).length===0)throw f.missingValues(t.nickname||"unnamed","ValueList");if(t.default!==void 0&&t.default!==null){let r=String(t.default).toLowerCase();Object.keys(t.values).some(s=>s.toLowerCase()===r)||d().warn(`ValueList input "${t.nickname||"unnamed"}" default value "${t.default}" is not in available values`)}return{...e,paramType:"ValueList",values:t.values,default:t.default}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"ValueList",values:t.values??{},default:r?[t.default]:t.default}}},de={types:["Geometry"],parse(t,e){let r=x(t.default,me(t.nickname||"unnamed"),!0);return{...e,paramType:"Geometry",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Geometry",default:r?[null]:null}}},qe={types:["File"],parse(t,e){let r=x(t.default,me(t.nickname||"unnamed"),!0);return{...e,paramType:"File",acceptedFormats:t.acceptedFormats,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"File",default:r?[null]:null}}},He={types:["Color"],parse(t,e){let r=x(t.default,Be,!1);return{...e,paramType:"Color",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Color",default:r?["0, 0, 0"]:"0, 0, 0"}}},Je=[Ue,ze,$e,_e,de,qe,He],j=new Map(Je.flatMap(t=>t.types.map(e=>[e,t]))),he=de;var Ye=new Map([...j.keys()].map(t=>[t.toLowerCase(),t]));function Qe(t){return Ye.get(t?.toLowerCase())??t}function ye(t){return ge(t).input}function ge(t){let e={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??"",id:t.id},r=Qe(t.paramType),{schema:n,warning:s}=ce({...t,paramType:r}),o=s&&{inputName:t.name||"unknown",paramType:r,message:s.message,code:s.code},a=j.get(r);try{if(!a)throw f.unknownParamType(r,t.name);return{input:a.parse(n,e),error:o}}catch(i){if(i instanceof f)return d().error(`Validation error for input ${t.name||"unknown"}:`,i.message),{input:(a??he).fallback(n,e),error:{inputName:t.name||"unknown",paramType:r,message:i.message,code:i.code}};throw new f(i instanceof Error?i.message:String(i),"VALIDATION_ERROR",{context:{paramName:t.name,paramType:r},originalError:i instanceof Error?i:new Error(String(i))})}}function be(t){return M(t).inputs}function M(t){let e=[],r=[];for(let n of t){let{input:s,error:o}=ge(n);e.push(s),o&&r.push(o)}return{inputs:e,parseErrors:r}}function Te(t){return{id:p(t,"id"),name:p(t,"name"),nickname:p(t,"nickname")??null,description:p(t,"description"),paramType:p(t,"paramType"),treeAccess:p(t,"treeAccess"),minimum:p(t,"minimum")??null,maximum:p(t,"maximum")??null,atLeast:p(t,"atLeast"),atMost:p(t,"atMost"),stepSize:p(t,"stepSize"),default:p(t,"default"),values:p(t,"values"),acceptedFormats:p(t,"acceptedFormats"),groupName:p(t,"groupName")??""}}function Ce(t){return{name:p(t,"name"),nickname:p(t,"nickname")??null,paramType:p(t,"paramType"),id:p(t,"id")}}async function w(t,e){let r=P(t,[]),n={};if(r.algo&&(n.algo=r.algo),r.pointer&&(n.pointer=r.pointer),!n.algo&&!n.pointer)throw new f("Definition must resolve to either a URL pointer or base64 algo",h.INVALID_INPUT,{context:{definition:t}});let s=await A("io",n,e);if(!s||typeof s!="object")throw new f("Invalid IO response structure",h.INVALID_INPUT,{context:{response:s,definition:t}});let o=Se(p(s,"warnings")),a=Se(p(s,"errors")),i=p(s,"inputs"),u=p(s,"outputs");return{inputs:Array.isArray(i)?i.map(Te):[],outputs:Array.isArray(u)?u.map(Ce):[],...o&&{loadWarnings:o},...a&&{loadErrors:a}}}function Se(t){if(!Array.isArray(t))return;let e=t.filter(r=>typeof r=="string"&&r.trim().length>0);return e.length>0?e:void 0}async function F(t,e){C("fetchParsedDefinitionIO",e.suppressBrowserWarning??e.suppressClientSideWarning);let{inputs:r,outputs:n,loadWarnings:s,loadErrors:o}=await w(t,e),{inputs:a,parseErrors:i}=M(r);return{inputs:a,outputs:n,...i.length>0&&{parseErrors:i},...s&&{loadWarnings:s},...o&&{loadErrors:o}}}var V=class t{constructor(e){l(this,"innerTree");l(this,"paramName");this.paramName=e,this.innerTree={}}append(e,r){let n=t.formatPathString(e);this.innerTree[n]||(this.innerTree[n]=[]);let s=r.map(o=>({data:t.serializeValue(o)}));return this.innerTree[n].push(...s),this}appendSingle(e,r){return this.append(e,[r])}fromDataTreeDefault(e){this.innerTree={};for(let[r,n]of Object.entries(e)){if(!Array.isArray(n))continue;let s=t.parsePathString(r);this.append(s,n)}return this}appendFlat(e){let r=Array.isArray(e)?e:[e];return this.append([0],r)}flatten(){let e=[];for(let r of Object.values(this.innerTree))if(Array.isArray(r))for(let n of r)e.push(t.deserializeValue(n.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let r=t.formatPathString(e),n=this.innerTree[r];if(n)return n.map(s=>t.deserializeValue(s.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(e){return e.filter(r=>t.hasValidValue(r.default)).map(r=>{let n=new t(r.nickname||"unnamed"),s=r.default;if(r.treeAccess&&v(s))n.fromDataTreeDefault(s),t.isNumericInput(r)&&n.applyNumericConstraints(r.minimum,r.maximum,r.nickname||"unnamed");else{let o=Array.isArray(s)?s:[s],a=t.processValues(o,r);n.appendFlat(a)}return n.toComputeFormat()})}static fromInputParam(e){return t.hasValidValue(e.default)?t.fromInputParams([e])[0]:void 0}static replaceTreeValue(e,r,n){let s=e.length>0&&e[0]instanceof t,o=t.buildFromValue(r,n);if(s){let c=e,m=c.findIndex(y=>y.getParamName()===r);return m!==-1?c[m]=o:c.push(o),c}let a=e,i=o.toComputeFormat(),u=a.findIndex(c=>c.ParamName===r);return u!==-1?a[u]=i:a.push(i),a}static buildFromValue(e,r){let n=new t(e);return v(r)?n.fromDataTreeDefault(r):n.appendFlat(r),n}static getTreeValue(e,r){let s=e.length>0&&e[0]instanceof t?t.readFromBuilders(e,r):t.readFromDataTrees(e,r);return s===null||s.length===0?null:s.length===1?s[0]:s}static readFromBuilders(e,r){let n=e.find(s=>s.getParamName()===r);return n?n.flatten():null}static readFromDataTrees(e,r){let n=e.find(a=>a.ParamName===r);if(!n?.InnerTree)return null;let s=Object.keys(n.InnerTree)[0];if(!s)return null;let o=n.InnerTree[s];return Array.isArray(o)?o.map(a=>a?.data!==void 0?t.deserializeValue(a.data):null).filter(a=>a!==null):o?.data!==void 0?[t.deserializeValue(o.data)]:o!==void 0?[o]:null}static parsePathString(e){let r=e.match(B);return r?r[1]?r[1].split(";").map(Number):[]:(d().warn(`Invalid TreeBuilder path format: ${e}, using [0]`),[0])}static formatPathString(e){return`{${e.join(";")}}`}applyNumericConstraints(e,r,n){for(let s of Object.values(this.innerTree))if(Array.isArray(s))for(let o of s){let a=t.deserializeValue(o.data);if(typeof a=="number"){let i=t.clampValue(a,e,r,n);o.data=t.serializeValue(i)}}}static serializeValue(e){return typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:typeof e=="object"&&e!==null?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e=="boolean"||typeof e=="number"||typeof e!="string")return e;if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch{return e}return e.trim()!==""&&!isNaN(Number(e))?Number(e):e==="true"?!0:e==="false"?!1:e}static hasValidValue(e){return e==null?!1:typeof e=="string"?!0:!(Array.isArray(e)&&e.length===0||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType==="Number"||e.paramType==="Integer"}static processValues(e,r){return e.map(n=>t.isNumericInput(r)&&typeof n=="number"?t.clampValue(n,r.minimum,r.maximum,r.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(e,r,n,s){let o=e;return r!=null&&o<r&&(d().warn(`${s}: ${e} below min ${r}, clamping`),o=r),n!=null&&o>n&&(d().warn(`${s}: ${e} above max ${n}, clamping`),o=n),o}};export{D as a,S as b,R as c,E as d,ye as e,be as f,w as g,F as h,V as i};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{b as l,c as h,d as f,e as d,h as U,i as z,k as $,l as A,m as _,n as q,r as N}from"./chunk-QAOHGIFT.js";function p(t,e){if(!t||typeof t!="object")return;let r=t;if(e in r)return r[e];let n=J(r).get(e.toLowerCase());return n===void 0?void 0:r[n]}function L(t,e){if(!t||typeof t!="object")return!1;let r=t;return e in r?!0:J(r).has(e.toLowerCase())}var H=new WeakMap;function J(t){let e=H.get(t);if(!e){e=new Map;for(let r of Object.keys(t)){let n=r.toLowerCase();e.has(n)||e.set(n,r)}H.set(t,e)}return e}function C(t,e){e||typeof window<"u"&&d().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`)}var Ie="Unable to load grasshopper definition";function xe(t){return t instanceof f?t.code===h.DEFINITION_NOT_CACHED||t.message.includes(Ie):!1}function Y(t,e){if(!e)return;let r=p(t,"values");if(!Array.isArray(r)||r.length===0)return;let n=[];for(let o of r){let a=p(o,"innerTree");(!a||Object.keys(a).length===0)&&n.push(p(o,"paramName")??"<unnamed>")}if(n.length===0)return;let s=n.length===r.length?"all":`${n.length}/${r.length}`;d().warn(`Solve returned empty output(s) (${s}): ${n.join(", ")}. These parameters produced no data \u2014 check the definition's inputs and the branch feeding each.`)}async function D(t,e,r){r.debug&&C("solveGrasshopperDefinition",r.suppressBrowserWarning??r.suppressClientSideWarning);let{response:n}=await O(P(e,t),r);return n}async function Q(t,e,r){return r.debug&&C("solveGrasshopperDefinitionWithCacheKey",r.suppressBrowserWarning??r.suppressClientSideWarning),O(P(e,t),r)}async function X(t,e,r,n){n.debug&&C("solveByCacheKey",n.suppressBrowserWarning??n.suppressClientSideWarning);let s={algo:null,pointer:e,values:t};try{return{...await O(s,n),missed:!1}}catch(o){if(!xe(o))throw o;return{...await O(P(r,t),n),missed:!0}}}async function O(t,e){De(t,e);let r=await A("grasshopper",t,e);if("pointer"in r){let{pointer:n,...s}=r,o=s;return Y(o,e.debug),{response:o,cacheKey:typeof n=="string"?n:null}}return Y(r,e.debug),{response:r,cacheKey:null}}function P(t,e){let r={algo:null,pointer:null,values:e};return t instanceof Uint8Array?r.algo=$(t):/^https?:\/\//i.test(t)?r.pointer=t:z(t)?r.algo=t:r.algo=U(t),r}function De(t,e){e.cachesolve!=null&&(t.cachesolve=e.cachesolve),e.cacheerroredsolves!=null&&(t.cacheerroredsolves=e.cacheerroredsolves),e.modelunits!=null&&(t.modelunits=e.modelunits),e.angletolerance!=null&&(t.angletolerance=e.angletolerance),e.absolutetolerance!=null&&(t.absolutetolerance=e.absolutetolerance),e.dataversion!=null&&(t.dataversion=e.dataversion)}function Pe(t){let e=new WeakSet,r=n=>{if(n==null)return JSON.stringify(n);if(typeof n=="number")return Number.isFinite(n)?String(n):JSON.stringify(null);if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="bigint")return JSON.stringify(n.toString());if(n instanceof Uint8Array){let s=n.length>64?Array.from(n.slice(0,32)).concat(Array.from(n.slice(-32))):Array.from(n);return JSON.stringify({__u8:!0,len:n.length,sample:s})}return Array.isArray(n)?`[${n.map(r).join(",")}]`:typeof n=="object"?e.has(n)?JSON.stringify("[Circular]"):(e.add(n),`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${r(n[a])}`).join(",")}}`):JSON.stringify(null)};return r(t)}function Z(t,e){let r=2166136261;for(let n=0;n<t;n++)r^=e(n),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r.toString(16).padStart(8,"0")}function ee(t){return Z(t.length,e=>t.charCodeAt(e))}function Re(t){return Z(t.length,e=>t[e])}function te(t,e){return ee(`${W(t)}|${Pe(e)}`)}function W(t){return typeof t=="string"?`s:${t.length}:${ee(t)}`:`u8:${t.length}:${Re(t)}`}var we=100;function Ee(t){return t instanceof Uint8Array?!0:!/^https?:\/\//i.test(t)}var S=class{constructor(e,r,n={},s){l(this,"executor");l(this,"baseConfig");l(this,"mode");l(this,"maxConcurrent");l(this,"timeoutMs");l(this,"retry");l(this,"cacheEnabled");l(this,"cacheMax");l(this,"cacheTtl");l(this,"cache",new Map);l(this,"cacheKeyExecutor");l(this,"reuseServerDefinitionCache");l(this,"serverCacheKeys",new Map);l(this,"onStart");l(this,"onSettle");l(this,"onSuperseded");l(this,"subscribers",new Set);l(this,"inFlight",new Set);l(this,"pendingForLatestWins",null);l(this,"fifoQueue",[]);l(this,"_lastResult",null);l(this,"_lastError",null);l(this,"_lastDurationMs",null);l(this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=s,this.baseConfig=r,this.mode=n.mode??"latest-wins",this.maxConcurrent=Math.max(1,n.maxConcurrent??(this.mode==="parallel"?4:1)),this.timeoutMs=n.timeoutMs,this.retry=n.retry;let o=n.cache;this.cacheEnabled=o!==void 0&&o!==!1;let a=typeof o=="object"?o:{};this.cacheMax=a.maxEntries??50,this.cacheTtl=a.ttlMs??0,this.reuseServerDefinitionCache=!!s&&(n.reuseServerDefinitionCache??!0),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+(this.pendingForLatestWins?1:0)}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(r){d().error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new f("SolveScheduler has been disposed and cannot be used",h.INVALID_STATE));let s=te(e,r),o={key:s,enqueuedAt:Date.now(),startedAt:null};if(this.cacheEnabled){let a=this.readCache(s);if(a){let i={status:"success",response:a,durationMs:0,fromCache:!0};return this._lastResult=a,this._lastError=null,this._lastDurationMs=0,this.runHook(this.onStart,o),this.runHook(this.onSettle,o,i),this.notify(),Promise.resolve(a)}}return new Promise((a,i)=>{let u={definition:e,dataTree:r,ctx:o,resolve:a,reject:i,externalSignal:n?.signal};if(u.externalSignal?.aborted){this.settleError(u,this.makeAbortError(o));return}this.enqueue(u)})}enqueue(e){switch(this.mode){case"latest-wins":{this.pendingForLatestWins&&(this.supersede(this.pendingForLatestWins),this.pendingForLatestWins=null);for(let r of this.inFlight)this.supersede(r),r.controller.abort();this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break}case"queue":case"parallel":{this.inFlight.size<this.maxConcurrent?this.execute(e):this.fifoQueue.push(e);break}}this.notify()}async execute(e){let r=new AbortController,n=e;n.controller=r,this.inFlight.add(n),e.ctx.startedAt=Date.now();let s=()=>r.abort();e.externalSignal?.addEventListener("abort",s,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let o=performance.now();try{let a={...this.baseConfig,signal:r.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},{response:i,definitionReuploaded:u}=await this.runExecutor(e.definition,e.dataTree,a),c=performance.now()-o;if(this.cacheEnabled&&this.writeCache(e.ctx.key,i),!this.settleSuccess(e,i))return;this._lastResult=i,this._lastError=null,this._lastDurationMs=c,this.runHook(this.onSettle,e.ctx,{status:"success",response:i,durationMs:c,fromCache:!1,definitionReuploaded:u})}catch(a){let i=performance.now()-o,u=this.normalizeExecutionError(a,n);this._lastError=u,this._lastDurationMs=i,this.settleError(e,u)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:u,durationMs:i})}finally{e.externalSignal?.removeEventListener("abort",s),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,r,n){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!Ee(e))return{response:await this.executor(e,r,n)};let s=W(e),o=this.serverCacheKeys.get(s)??null,a=await this.cacheKeyExecutor(e,r,o,n);if(a.cacheKey)for(this.serverCacheKeys.delete(s),this.serverCacheKeys.set(s,a.cacheKey);this.serverCacheKeys.size>we;){let i=this.serverCacheKeys.keys().next().value;if(i===void 0)break;this.serverCacheKeys.delete(i)}else this.serverCacheKeys.delete(s);return{response:a.response,definitionReuploaded:a.missed}}drainNext(){if(!this.disposed){if(this.mode==="latest-wins"){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}return}for(;this.fifoQueue.length>0&&this.inFlight.size<this.maxConcurrent;){let e=this.fifoQueue.shift();this.execute(e)}}}supersede(e){let r=new f("Superseded by newer solve",h.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new f("Request aborted by caller",h.ABORTED,{context:{key:e.key,enqueuedAt:e.enqueuedAt}})}settleError(e,r){return e.settled?!1:(e.settled={error:r},e.reject(r),!0)}settleSuccess(e,r){return e.settled?!1:(e.settled={ok:!0},e.resolve(r),!0)}isAbortLikeError(e){if(e instanceof Error){if(e.name==="AbortError")return!0;if(typeof DOMException<"u"&&e instanceof DOMException)return e.name==="AbortError"}return!1}normalizeExecutionError(e,r){return r.settled&&"error"in r.settled?r.settled.error:e instanceof f?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new f(e instanceof Error?e.message:String(e),h.UNKNOWN_ERROR,{originalError:e instanceof Error?e:new Error(String(e))})}cancelAll(){for(this.pendingForLatestWins&&(this.rejectAsAborted(this.pendingForLatestWins),this.pendingForLatestWins=null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:e.ctx.startedAt?performance.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){this.settleError(e,this.makeAbortError(e.ctx))}readCache(e){if(!this.cacheEnabled)return null;let r=this.cache.get(e);return r?this.cacheTtl>0&&Date.now()-r.insertedAt>this.cacheTtl?(this.cache.delete(e),null):(this.cache.delete(e),this.cache.set(e,r),r.response):null}writeCache(e,r){if(this.cacheEnabled)for(this.cache.set(e,{response:r,insertedAt:Date.now()});this.cache.size>this.cacheMax;){let n=this.cache.keys().next().value;if(n===void 0)break;this.cache.delete(n)}}clearCache(){this.cache.clear()}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.cache.clear())}runHook(e,...r){if(e)try{e(...r)}catch(n){d().error("[SolveScheduler] hook threw:",n)}}};var R=class t{constructor(e){l(this,"config");l(this,"serverStats");l(this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new q(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e),n=Math.max(1,(e.retry?.attempts??2)+1),s=e.retry?.baseDelayMs??250,o=e.retry?.maxDelayMs??1e3;for(let a=0;a<n;a++){if(await r.serverStats.isServerOnline())return r;if(a<n-1){let i=Math.min(s*2**a,o);await new Promise(u=>setTimeout(u,i))}}throw await r.dispose(),new f("Rhino Compute server is not online",h.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:n}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),F(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),w(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!e?.trim())throw new f("Definition URL/content is required",h.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new f("Definition content is empty",h.INVALID_INPUT);let s={...this.config,...n?.signal!==void 0&&{signal:n.signal},...n?.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs},...n?.retry!==void 0&&{retry:n.retry}},o=await D(r,e,s);if(o?.errors&&o.errors.length>0)throw new f(o.errors.join("; ")||"Computation failed",h.COMPUTATION_ERROR,{context:{definition:typeof e=="string"&&e.length<200?e:"...content...",inputs:r,errors:o.errors,warnings:o.warnings}});return o}catch(s){throw this.config.debug&&d().error("Compute failed:",s),s instanceof f?s:new f(s instanceof Error?s.message:String(s),h.COMPUTATION_ERROR,{context:{definition:typeof e=="string"&&e.length<200?e:"...content...",inputs:r},originalError:s instanceof Error?s:new Error(String(s))})}}createScheduler(e){this.ensureNotDisposed();let r=(s,o,a)=>D(o,s,a),n=(s,o,a,i)=>a===null?Q(o,s,i).then(u=>({...u,missed:!1})):X(o,a,s,i);return new S(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new f("GrasshopperClient has been disposed and cannot be used",h.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:_(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning??e.suppressClientSideWarning}}};var G=new Map;function re(t,e){G.set(t,e)}re("Rhino.Geometry.Point3d",(t,e)=>{let r=e;return!r||typeof r.X!="number"?null:new t.Point([r.X,r.Y,r.Z])});re("Rhino.Geometry.Line",(t,e)=>{let r=e;return!r||!r.From||!r.To?null:new t.Line([r.From.X,r.From.Y,r.From.Z],[r.To.X,r.To.Y,r.To.Z])});function ve(t){if(G.has(t))return G.get(t);for(let[e,r]of G)if(t.startsWith(e))return r}function Ae(t){return!t||typeof t!="object"?null:t.data??t.value??null}function ne(t,e,r){let n=ve(e);if(n)try{return n(r,t)}catch(s){d().warn(`Failed to decode Rhino type ${e}:`,s)}try{let s=Ae(t);if(s)return r.CommonObject.decode(s)}catch(s){return d().warn(`Failed to decode ${e} with CommonObject:`,s),{__decodeError:!0,type:e,raw:t}}return t}var I={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},Ne="Rhino.Geometry.",Oe=["WebDisplay"],Fe="FileData";function se(t){return Oe.some(e=>t.includes(e))}function oe(t){if(typeof t!="string")return t;let e=t.trim();if(!(e.startsWith("{")||e.startsWith("[")||e.startsWith('"')))return t;try{let n=JSON.parse(e);if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}catch{return t}}function Ge(t,e,r){switch(e){case I.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case I.INT:return Number.parseInt(t,10);case I.DOUBLE:return Number.parseFloat(t);case I.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(Ne)?ne(t,e,r):t}}function ae(t,e,r,n){if(typeof t!="string")return t;let s=r?oe(t):t;return Ge(s,e,n)}function ke(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.fileName=="string"&&typeof e.fileType=="string"&&"data"in e&&typeof e.isBase64Encoded=="boolean"&&typeof e.subFolder=="string"}function k(t,e){for(let r of Object.values(t))if(Array.isArray(r))for(let n of r)e(n)}function ie(t,e=!1,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,a={},i=new Set;for(let u of t.values)k(u.InnerTree,c=>{if(se(c.type)||o&&c.type!==I.STRING)return;let m=e?c.id:u.ParamName;if(!m)return;let y=ae(c.data,c.type,n,s);m in a?i.has(m)?a[m].push(y):(a[m]=[a[m],y],i.add(m)):a[m]=y});return{values:a}}function ue(t){let e=[];for(let r of t.values)k(r.InnerTree,n=>{if(!n.type.includes(Fe))return;let s=oe(n.data);ke(s)&&e.push(s)});return e}function pe(t,e,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,a;if("byName"in e?a=t.values.find(u=>u.ParamName===e.byName):a=t.values.find(u=>{let c=!1;return k(u.InnerTree,m=>{m.id===e.byId&&(c=!0)}),c}),!a)return;let i=[];if(k(a.InnerTree,u=>{if("byId"in e&&u.id!==e.byId||se(u.type)||o&&u.type!==I.STRING)return;let c=ae(u.data,u.type,n,s);i.push(c)}),i.length!==0)return i.length===1?i[0]:i}var E=class{constructor(e,r=!1){this.response=e;this.debug=r}getValues(e=!1,r={}){return ie(this.response,e,r)}getValue(e,r){return pe(this.response,e,r)}async extractMeshesFromResponse(e){let r={debug:this.debug,...e},n;try{({getThreeMeshesFromComputeResponse:n}=await import("./visualization-UJZN4PJD.js"))}catch(s){throw new f("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",h.INVALID_STATE,{context:{originalError:s instanceof Error?s.message:String(s)}})}return n(this.response,r)}getFileData(){return ue(this.response)}async getAndDownloadFiles(e,r){let n=this.getFileData();await N(n,e,r)}};function le(t){return p(t,"data")}function Me(t){return p(t,"type")}function ce(t){if(typeof t.default!="object"||t.default===null)return{schema:t};if(!L(t.default,"innerTree")){let n=`Input "${t.name??"unknown"}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return d().warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=p(t.default,"innerTree")??{};if(Object.keys(e).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let n={};for(let[s,o]of Object.entries(e))n[s]=o.map(a=>{let i=le(a),u=Me(a);if(typeof i=="string"){if(u==="System.Double"||u==="System.Int32"){let c=Number(i);return Number.isNaN(c)?i:c}if(u==="System.Boolean")return i.toLowerCase()==="true";if(u?.startsWith("Rhino.Geometry"))try{return JSON.parse(i)}catch{return i}}return i});return{schema:{...t,default:n}}}let r=[];for(let n of Object.values(e))Array.isArray(n)&&n.forEach(s=>{s&&typeof s=="object"&&L(s,"data")&&r.push(le(s))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}var B=/^\{(\d+(?:;\d+)*)?\}$/;function v(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.entries(t);return e.length>0&&e.every(([r,n])=>B.test(r)&&Array.isArray(n))}function x(t,e,r){if(t==null)return t;if(Array.isArray(t)){let s=t.map(e).filter(o=>o!==null);return s.length>0?s:void 0}let n=e(t);return n!==null?n:r?void 0:t}var Ve=t=>{if(typeof t=="number")return t;if(typeof t=="string"){let e=t.trim();if(e==="")return null;let r=Number(e);return Number.isNaN(r)?null:r}return null},Le=t=>{if(typeof t=="boolean")return t;if(typeof t=="string"){let e=t.toLowerCase();if(e==="true")return!0;if(e==="false")return!1;throw new Error(`Invalid boolean string: "${t}"`)}return null},We=t=>typeof t=="string"?t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t.startsWith('"')?t.slice(1):t:null,Be=t=>{if(typeof t=="string"){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}return null};function me(t){return e=>{if(typeof e=="object"&&e!==null)return e;if(typeof e=="string"&&e.trim()!=="")try{let r=JSON.parse(e);return typeof r=="object"&&r!==null?r:(d().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return d().warn(`Failed to parse object value "${e}" for input ${t}`,r),null}return null}}function fe(t,e,r){let n=Number(t.toFixed(e));return Math.abs(t-n)<r?n:t}function je(t,e){if(!Number.isFinite(t)||t===0)return .1;let r=Math.abs(t);if(r>=1){let g=String(t).split(".")[1];if(g&&g.length>0){let b=Math.min(g.length,12),T=Math.pow(10,-b),K=Number(T.toFixed(b));return Math.abs(K-T)<e?K:T}return 1}let n=String(t),s=n.toLowerCase().match(/e(-?\d+)/);if(s){let y=Number(s[1]);if(y<0||n.toLowerCase().includes("e-")){let g=Math.abs(y),b=Math.pow(10,-g),T=Number(b.toFixed(g));return Math.abs(T-b)<e?T:b}return .1}let o=12,i=r.toFixed(o).replace(/0+$/,""),u=Math.min((i.split(".")[1]||"").length,o);if(u===0)return .1;let c=Math.pow(10,-u),m=Number(c.toFixed(u));return Math.abs(m-c)<e?m:c}function Ke(t,e=1e-8){let r=t.paramType==="Integer";if(v(t.default))return{default:t.default,stepSize:r?1:.1};let n=x(t.default,Ve,!0);if(r)return Array.isArray(n)?n=n.map(m=>typeof m=="number"?Math.round(m):m):typeof n=="number"&&(n=Math.round(n)),{default:n,stepSize:1};let s=Array.isArray(n)?n[0]:n,o;typeof s=="number"&&Number.isFinite(s)&&s!==0?o=s:typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum!==0?o=t.minimum:typeof t.maximum=="number"&&Number.isFinite(t.maximum)&&t.maximum!==0&&(o=t.maximum);let a=o!==void 0?je(o,e):.1,i=0,u=String(a),c=u.toLowerCase().match(/e(-?\d+)/);if(c?i=Math.abs(Number(c[1])):i=u.split(".")[1]?.length??0,i===0&&typeof s=="number"&&s!==0&&Math.abs(s)<1){let m=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(m)&&m>0&&(i=m)}return i=Math.min(Math.max(i,0),12),Array.isArray(n)?n=n.map(m=>typeof m=="number"?fe(m,i,e):m):typeof n=="number"&&(n=fe(n,i,e)),{default:n,stepSize:a}}var Ue={types:["Number","Integer"],parse(t,e){let{default:r,stepSize:n}=Ke(t);return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:n,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,default:r?[0]:0}}},ze={types:["Boolean"],parse(t,e){let r;try{r=x(t.default,Le,!1)}catch(n){throw n instanceof Error?new f(n.message):n}return{...e,paramType:"Boolean",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Boolean",default:r?[!1]:!1}}},$e={types:["Text"],parse(t,e){let r=x(t.default,We,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Text",default:r?[""]:""}}},_e={types:["ValueList"],parse(t,e){if(!t.values||typeof t.values!="object"||Object.keys(t.values).length===0)throw f.missingValues(t.nickname||"unnamed","ValueList");if(t.default!==void 0&&t.default!==null){let r=String(t.default).toLowerCase();Object.keys(t.values).some(s=>s.toLowerCase()===r)||d().warn(`ValueList input "${t.nickname||"unnamed"}" default value "${t.default}" is not in available values`)}return{...e,paramType:"ValueList",values:t.values,default:t.default}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"ValueList",values:t.values??{},default:r?[t.default]:t.default}}},de={types:["Geometry"],parse(t,e){let r=x(t.default,me(t.nickname||"unnamed"),!0);return{...e,paramType:"Geometry",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Geometry",default:r?[null]:null}}},qe={types:["File"],parse(t,e){let r=x(t.default,me(t.nickname||"unnamed"),!0);return{...e,paramType:"File",acceptedFormats:t.acceptedFormats,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"File",default:r?[null]:null}}},He={types:["Color"],parse(t,e){let r=x(t.default,Be,!1);return{...e,paramType:"Color",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Color",default:r?["0, 0, 0"]:"0, 0, 0"}}},Je=[Ue,ze,$e,_e,de,qe,He],j=new Map(Je.flatMap(t=>t.types.map(e=>[e,t]))),he=de;var Ye=new Map([...j.keys()].map(t=>[t.toLowerCase(),t]));function Qe(t){return Ye.get(t?.toLowerCase())??t}function ye(t){return ge(t).input}function ge(t){let e={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??"",id:t.id},r=Qe(t.paramType),{schema:n,warning:s}=ce({...t,paramType:r}),o=s&&{inputName:t.name||"unknown",paramType:r,message:s.message,code:s.code},a=j.get(r);try{if(!a)throw f.unknownParamType(r,t.name);return{input:a.parse(n,e),error:o}}catch(i){if(i instanceof f)return d().error(`Validation error for input ${t.name||"unknown"}:`,i.message),{input:(a??he).fallback(n,e),error:{inputName:t.name||"unknown",paramType:r,message:i.message,code:i.code}};throw new f(i instanceof Error?i.message:String(i),"VALIDATION_ERROR",{context:{paramName:t.name,paramType:r},originalError:i instanceof Error?i:new Error(String(i))})}}function be(t){return M(t).inputs}function M(t){let e=[],r=[];for(let n of t){let{input:s,error:o}=ge(n);e.push(s),o&&r.push(o)}return{inputs:e,parseErrors:r}}function Te(t){return{id:p(t,"id"),name:p(t,"name"),nickname:p(t,"nickname")??null,description:p(t,"description"),paramType:p(t,"paramType"),treeAccess:p(t,"treeAccess"),minimum:p(t,"minimum")??null,maximum:p(t,"maximum")??null,atLeast:p(t,"atLeast"),atMost:p(t,"atMost"),stepSize:p(t,"stepSize"),default:p(t,"default"),values:p(t,"values"),acceptedFormats:p(t,"acceptedFormats"),groupName:p(t,"groupName")??""}}function Ce(t){return{name:p(t,"name"),nickname:p(t,"nickname")??null,paramType:p(t,"paramType"),id:p(t,"id")}}async function w(t,e){let r=P(t,[]),n={};if(r.algo&&(n.algo=r.algo),r.pointer&&(n.pointer=r.pointer),!n.algo&&!n.pointer)throw new f("Definition must resolve to either a URL pointer or base64 algo",h.INVALID_INPUT,{context:{definition:t}});let s=await A("io",n,e);if(!s||typeof s!="object")throw new f("Invalid IO response structure",h.INVALID_INPUT,{context:{response:s,definition:t}});let o=Se(p(s,"warnings")),a=Se(p(s,"errors")),i=p(s,"inputs"),u=p(s,"outputs");return{inputs:Array.isArray(i)?i.map(Te):[],outputs:Array.isArray(u)?u.map(Ce):[],...o&&{loadWarnings:o},...a&&{loadErrors:a}}}function Se(t){if(!Array.isArray(t))return;let e=t.filter(r=>typeof r=="string"&&r.trim().length>0);return e.length>0?e:void 0}async function F(t,e){C("fetchParsedDefinitionIO",e.suppressBrowserWarning??e.suppressClientSideWarning);let{inputs:r,outputs:n,loadWarnings:s,loadErrors:o}=await w(t,e),{inputs:a,parseErrors:i}=M(r);return{inputs:a,outputs:n,...i.length>0&&{parseErrors:i},...s&&{loadWarnings:s},...o&&{loadErrors:o}}}var V=class t{constructor(e){l(this,"innerTree");l(this,"paramName");this.paramName=e,this.innerTree={}}append(e,r){let n=t.formatPathString(e);this.innerTree[n]||(this.innerTree[n]=[]);let s=r.map(o=>({data:t.serializeValue(o)}));return this.innerTree[n].push(...s),this}appendSingle(e,r){return this.append(e,[r])}fromDataTreeDefault(e){this.innerTree={};for(let[r,n]of Object.entries(e)){if(!Array.isArray(n))continue;let s=t.parsePathString(r);this.append(s,n)}return this}appendFlat(e){let r=Array.isArray(e)?e:[e];return this.append([0],r)}flatten(){let e=[];for(let r of Object.values(this.innerTree))if(Array.isArray(r))for(let n of r)e.push(t.deserializeValue(n.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let r=t.formatPathString(e),n=this.innerTree[r];if(n)return n.map(s=>t.deserializeValue(s.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(e){return e.filter(r=>t.hasValidValue(r.default)).map(r=>{let n=new t(r.nickname||"unnamed"),s=r.default;if(r.treeAccess&&v(s))n.fromDataTreeDefault(s),t.isNumericInput(r)&&n.applyNumericConstraints(r.minimum,r.maximum,r.nickname||"unnamed");else{let o=Array.isArray(s)?s:[s],a=t.processValues(o,r);n.appendFlat(a)}return n.toComputeFormat()})}static fromInputParam(e){return t.hasValidValue(e.default)?t.fromInputParams([e])[0]:void 0}static replaceTreeValue(e,r,n){let s=e.length>0&&e[0]instanceof t,o=t.buildFromValue(r,n);if(s){let c=e,m=c.findIndex(y=>y.getParamName()===r);return m!==-1?c[m]=o:c.push(o),c}let a=e,i=o.toComputeFormat(),u=a.findIndex(c=>c.ParamName===r);return u!==-1?a[u]=i:a.push(i),a}static buildFromValue(e,r){let n=new t(e);return v(r)?n.fromDataTreeDefault(r):n.appendFlat(r),n}static getTreeValue(e,r){let s=e.length>0&&e[0]instanceof t?t.readFromBuilders(e,r):t.readFromDataTrees(e,r);return s===null||s.length===0?null:s.length===1?s[0]:s}static readFromBuilders(e,r){let n=e.find(s=>s.getParamName()===r);return n?n.flatten():null}static readFromDataTrees(e,r){let n=e.find(a=>a.ParamName===r);if(!n?.InnerTree)return null;let s=Object.keys(n.InnerTree)[0];if(!s)return null;let o=n.InnerTree[s];return Array.isArray(o)?o.map(a=>a?.data!==void 0?t.deserializeValue(a.data):null).filter(a=>a!==null):o?.data!==void 0?[t.deserializeValue(o.data)]:o!==void 0?[o]:null}static parsePathString(e){let r=e.match(B);return r?r[1]?r[1].split(";").map(Number):[]:(d().warn(`Invalid TreeBuilder path format: ${e}, using [0]`),[0])}static formatPathString(e){return`{${e.join(";")}}`}applyNumericConstraints(e,r,n){for(let s of Object.values(this.innerTree))if(Array.isArray(s))for(let o of s){let a=t.deserializeValue(o.data);if(typeof a=="number"){let i=t.clampValue(a,e,r,n);o.data=t.serializeValue(i)}}}static serializeValue(e){return typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:typeof e=="object"&&e!==null?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e=="boolean"||typeof e=="number"||typeof e!="string")return e;if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch{return e}return e.trim()!==""&&!isNaN(Number(e))?Number(e):e==="true"?!0:e==="false"?!1:e}static hasValidValue(e){return e==null?!1:typeof e=="string"?!0:!(Array.isArray(e)&&e.length===0||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType==="Number"||e.paramType==="Integer"}static processValues(e,r){return e.map(n=>t.isNumericInput(r)&&typeof n=="number"?t.clampValue(n,r.minimum,r.maximum,r.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(e,r,n,s){let o=e;return r!=null&&o<r&&(d().warn(`${s}: ${e} below min ${r}, clamping`),o=r),n!=null&&o>n&&(d().warn(`${s}: ${e} above max ${n}, clamping`),o=n),o}};export{D as a,S as b,R as c,E as d,ye as e,be as f,w as g,F as h,V as i};
|
|
2
|
+
//# sourceMappingURL=chunk-CTZ4ZOSM.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var U=Object.defineProperty;var q=(t,e,r)=>e in t?U(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var pe=(t,e)=>{for(var r in e)U(t,r,{get:e[r],enumerable:!0})};var h=(t,e,r)=>q(t,typeof e!="symbol"?e+"":e,r);var u={NETWORK_ERROR:"NETWORK_ERROR",AUTH_ERROR:"AUTH_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",COMPUTATION_ERROR:"COMPUTATION_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",CORS_ERROR:"CORS_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR",INVALID_STATE:"INVALID_STATE",INVALID_INPUT:"INVALID_INPUT",INVALID_CONFIG:"INVALID_CONFIG",BROWSER_ONLY:"BROWSER_ONLY",ENVIRONMENT_ERROR:"ENVIRONMENT_ERROR",ENCODING_ERROR:"ENCODING_ERROR",MALFORMED_DEFAULT:"MALFORMED_DEFAULT",SUPERSEDED:"SUPERSEDED",ABORTED:"ABORTED",DEFINITION_NOT_CACHED:"DEFINITION_NOT_CACHED"},f= 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 T=class{debug(){}info(){}warn(){}error(){}},N=class{debug(e,...r){console.debug(e,...r)}info(e,...r){console.info(e,...r)}warn(e,...r){console.warn(e,...r)}error(e,...r){console.error(e,...r)}},A=new T;function p(){return A}function D(t){if(t===null){A=new T;return}let e=["debug","info","warn","error"].filter(r=>typeof t[r]!="function");if(e.length>0)throw new f(`Logger is missing required method(s): ${e.join(", ")}. A logger must implement debug, info, warn and error.`,u.INVALID_CONFIG,{context:{missingMethods:e}});A=t}function K(){D(new N)}function S(){let t=globalThis.Buffer;return typeof t=="function"?t:void 0}function Ee(t){let e=S();return e?e.from(t,"utf-8").toString("base64"):W(new TextEncoder().encode(t))}function ve(t){return!t||t.length<2||t.length%4!==0?!1:/^[A-Za-z0-9+/]+={0,2}$/.test(t)}function _(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 f("Invalid base64 input.",u.ENCODING_ERROR,{context:{inputLength:t.length}});let r=S();if(r){let n=r.from(e,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}if(typeof globalThis.atob=="function"){let n=globalThis.atob(e),o=new Uint8Array(n.length);for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i)&255;return o}throw new f("Base64 decoding not supported in this environment.",u.INVALID_STATE,{context:{environmentInfo:"atob or Buffer not available"}})}function F(t){let e=S();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 W(t){let e=S();if(e)return e.from(t).toString("base64");if(typeof globalThis.btoa=="function"){let n="";for(let o=0;o<t.length;o+=32768)n+=String.fromCharCode.apply(null,t.subarray(o,o+32768));return globalThis.btoa(n)}throw new f("Base64 encoding not supported in this environment.",u.INVALID_STATE,{context:{environmentInfo:"btoa or Buffer not available"}})}function H(t){if(!t)return null;let e={raw:t},r=!1;for(let n of t.split(",")){let[o,...i]=n.trim().split(";"),d=i.find(c=>c.trim().toLowerCase().startsWith("dur"));if(!d)continue;let s=Number(d.split("=")[1]);if(!Number.isFinite(s))continue;let a=o.trim().toLowerCase();(a==="decode"||a==="solve"||a==="encode")&&(e[a]=s,r=!0)}return r?e:null}var v={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},L=new Set([502,503,504]);function z(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 V(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 O(t,e){let r=e.baseDelayMs*Math.pow(2,t),n=Math.random()*e.baseDelayMs;return Math.min(r+n,e.maxDelayMs)}function J(t,e){return new Promise((r,n)=>{if(_optionalChain([e, 'optionalAccess', _6 => _6.aborted])){n(new DOMException("Aborted","AbortError"));return}let o=setTimeout(()=>{_optionalChain([e, 'optionalAccess', _7 => _7.removeEventListener, 'call', _8 => _8("abort",i)]),r()},t),i=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))};_optionalChain([e, 'optionalAccess', _9 => _9.addEventListener, 'call', _10 => _10("abort",i,{once:!0})])})}function G(t,e,r,n,o,i,d){let{status:s,statusText:a}=t,c={};t.headers.forEach(($,B)=>{c[B]=$});let m=i.trim(),l=m?` \u2014 ${m.slice(0,200)}${m.length>200?"\u2026":""}`:"",y={url:e,requestId:r,method:"POST",requestSize:n,serverUrl:o,responseBody:i||void 0,responseHeaders:c},E={401:{message:`HTTP ${s}: ${a}${l}`,code:u.AUTH_ERROR},403:{message:`HTTP ${s}: ${a}${l}`,code:u.AUTH_ERROR},404:{message:`Endpoint not found: ${e}`,code:u.NETWORK_ERROR},413:{message:`Request too large: ${(n/1024).toFixed(2)}KB`,code:u.VALIDATION_ERROR},429:{message:`Rate limit exceeded${l}`,code:u.NETWORK_ERROR},500:{message:`Server error: ${a}${l}`,code:u.COMPUTATION_ERROR},502:{message:`Service unavailable: ${a}${l}`,code:u.NETWORK_ERROR},503:{message:`Service unavailable: ${a}${l}`,code:u.NETWORK_ERROR},504:{message:`Service unavailable: ${a}${l}`,code:u.NETWORK_ERROR}}[s]||{message:`HTTP ${s}: ${a}${l}`,code:u.UNKNOWN_ERROR},w=_nullishCoalesce(j(d), () => (E.code));throw new f(E.message,w,{statusCode:s,context:y})}function j(t){if(t==="definition_not_cached")return u.DEFINITION_NOT_CACHED}function Y(t,e){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${r}/${n}`}function Z(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 x=new Set;function X(t,e){let r={"X-Request-ID":t,"Content-Type":"application/json",...e.authToken&&{Authorization:e.authToken},...e.apiKey&&{RhinoComputeKey:e.apiKey}};return!e.apiKey&&!e.authToken&&!x.has(e.serverUrl)&&!Z(e.serverUrl)&&(x.add(e.serverUrl),p().warn(`\u26A0\uFE0F [Rhino Compute] Request [${t}] targets remote server (${e.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited. (warned once per server)`)),r}function Q(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function R(t,e){e&&p().debug(t)}function ee(t,e){let r=[],n=()=>{};if(t&&r.push(t),e&&e>0)if(typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function")r.push(AbortSignal.timeout(e));else{let s=new AbortController,a=setTimeout(()=>s.abort(),e);n=()=>clearTimeout(a),r.push(s.signal)}if(r.length===0)return{signal:void 0,cleanup:n};if(r.length===1)return{signal:r[0],cleanup:n};if(typeof AbortSignal<"u"&&typeof AbortSignal.any=="function")return{signal:AbortSignal.any(r),cleanup:n};let o=new AbortController,i=()=>o.abort();for(let s of r){if(s.aborted){o.abort();break}s.addEventListener("abort",i,{once:!0})}let d=n;return n=()=>{d();for(let s of r)s.removeEventListener("abort",i)},{signal:o.signal,cleanup:n}}async function re(t,e,r,n,o,i,d,s){let a=Math.round(performance.now()-i);if(!t.ok){let c=await t.text();d&&(R(`\u274C Request [${r}] failed with HTTP ${t.status} in ${a}ms`,!0),R(` URL: ${e}`,!0),R(` Status: ${t.status} ${t.statusText}`,!0),c&&R(` Response body: ${c.substring(0,500)}${c.length>500?"...":""}`,!0));let m;try{let l=JSON.parse(c);typeof _optionalChain([l, 'optionalAccess', _11 => _11.code])=="string"&&(m=l.code)}catch (e3){}if(t.status===500)try{let l=JSON.parse(c);if(_optionalChain([l, 'optionalAccess', _12 => _12.values])&&(l.errors||l.warnings))return d&&(R(`\u26A0\uFE0F Request [${r}] completed with Grasshopper errors in ${a}ms`,!0),_optionalChain([l, 'access', _13 => _13.errors, 'optionalAccess', _14 => _14.length])>0&&R(` Errors: ${JSON.stringify(l.errors,null,2)}`,!0),_optionalChain([l, 'access', _15 => _15.warnings, 'optionalAccess', _16 => _16.length])>0&&R(` Warnings: ${JSON.stringify(l.warnings,null,2)}`,!0)),l;let y=typeof _optionalChain([l, 'optionalAccess', _17 => _17.message])=="string"&&l.message||typeof _optionalChain([l, 'optionalAccess', _18 => _18.Message])=="string"&&l.Message||"",g=typeof _optionalChain([l, 'optionalAccess', _19 => _19.ExceptionType])=="string"&&l.ExceptionType||"",E=_nullishCoalesce(_optionalChain([l, 'optionalAccess', _20 => _20.stackTrace]), () => (_optionalChain([l, 'optionalAccess', _21 => _21.StackTrace]))),w=Array.isArray(E)?E.join(`
|
|
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 U=Object.defineProperty;var q=(t,e,r)=>e in t?U(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var pe=(t,e)=>{for(var r in e)U(t,r,{get:e[r],enumerable:!0})};var h=(t,e,r)=>q(t,typeof e!="symbol"?e+"":e,r);var u={NETWORK_ERROR:"NETWORK_ERROR",AUTH_ERROR:"AUTH_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",COMPUTATION_ERROR:"COMPUTATION_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",CORS_ERROR:"CORS_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR",INVALID_STATE:"INVALID_STATE",INVALID_INPUT:"INVALID_INPUT",INVALID_CONFIG:"INVALID_CONFIG",BROWSER_ONLY:"BROWSER_ONLY",ENVIRONMENT_ERROR:"ENVIRONMENT_ERROR",ENCODING_ERROR:"ENCODING_ERROR",MALFORMED_DEFAULT:"MALFORMED_DEFAULT",SUPERSEDED:"SUPERSEDED",ABORTED:"ABORTED",DEFINITION_NOT_CACHED:"DEFINITION_NOT_CACHED"},f= 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 T=class{debug(){}info(){}warn(){}error(){}},N=class{debug(e,...r){console.debug(e,...r)}info(e,...r){console.info(e,...r)}warn(e,...r){console.warn(e,...r)}error(e,...r){console.error(e,...r)}},A=new T;function p(){return A}function D(t){if(t===null){A=new T;return}let e=["debug","info","warn","error"].filter(r=>typeof t[r]!="function");if(e.length>0)throw new f(`Logger is missing required method(s): ${e.join(", ")}. A logger must implement debug, info, warn and error.`,u.INVALID_CONFIG,{context:{missingMethods:e}});A=t}function K(){D(new N)}function S(){let t=globalThis.Buffer;return typeof t=="function"?t:void 0}function Ee(t){let e=S();return e?e.from(t,"utf-8").toString("base64"):W(new TextEncoder().encode(t))}function ve(t){return!t||t.length<2||t.length%4!==0?!1:/^[A-Za-z0-9+/]+={0,2}$/.test(t)}function _(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 f("Invalid base64 input.",u.ENCODING_ERROR,{context:{inputLength:t.length}});let r=S();if(r){let n=r.from(e,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}if(typeof globalThis.atob=="function"){let n=globalThis.atob(e),o=new Uint8Array(n.length);for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i)&255;return o}throw new f("Base64 decoding not supported in this environment.",u.INVALID_STATE,{context:{environmentInfo:"atob or Buffer not available"}})}function F(t){let e=S();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 W(t){let e=S();if(e)return e.from(t).toString("base64");if(typeof globalThis.btoa=="function"){let n="";for(let o=0;o<t.length;o+=32768)n+=String.fromCharCode.apply(null,t.subarray(o,o+32768));return globalThis.btoa(n)}throw new f("Base64 encoding not supported in this environment.",u.INVALID_STATE,{context:{environmentInfo:"btoa or Buffer not available"}})}function H(t){if(!t)return null;let e={raw:t},r=!1;for(let n of t.split(",")){let[o,...i]=n.trim().split(";"),d=i.find(c=>c.trim().toLowerCase().startsWith("dur"));if(!d)continue;let s=Number(d.split("=")[1]);if(!Number.isFinite(s))continue;let a=o.trim().toLowerCase();(a==="decode"||a==="solve"||a==="encode")&&(e[a]=s,r=!0)}return r?e:null}var v={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},L=new Set([502,503,504]);function z(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 V(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 O(t,e){let r=e.baseDelayMs*Math.pow(2,t),n=Math.random()*e.baseDelayMs;return Math.min(r+n,e.maxDelayMs)}function J(t,e){return new Promise((r,n)=>{if(_optionalChain([e, 'optionalAccess', _6 => _6.aborted])){n(new DOMException("Aborted","AbortError"));return}let o=setTimeout(()=>{_optionalChain([e, 'optionalAccess', _7 => _7.removeEventListener, 'call', _8 => _8("abort",i)]),r()},t),i=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))};_optionalChain([e, 'optionalAccess', _9 => _9.addEventListener, 'call', _10 => _10("abort",i,{once:!0})])})}function G(t,e,r,n,o,i,d){let{status:s,statusText:a}=t,c={};t.headers.forEach(($,B)=>{c[B]=$});let m=i.trim(),l=m?` \u2014 ${m.slice(0,200)}${m.length>200?"\u2026":""}`:"",y={url:e,requestId:r,method:"POST",requestSize:n,serverUrl:o,responseBody:i||void 0,responseHeaders:c},E={401:{message:`HTTP ${s}: ${a}${l}`,code:u.AUTH_ERROR},403:{message:`HTTP ${s}: ${a}${l}`,code:u.AUTH_ERROR},404:{message:`Endpoint not found: ${e}`,code:u.NETWORK_ERROR},413:{message:`Request too large: ${(n/1024).toFixed(2)}KB`,code:u.VALIDATION_ERROR},429:{message:`Rate limit exceeded${l}`,code:u.NETWORK_ERROR},500:{message:`Server error: ${a}${l}`,code:u.COMPUTATION_ERROR},502:{message:`Service unavailable: ${a}${l}`,code:u.NETWORK_ERROR},503:{message:`Service unavailable: ${a}${l}`,code:u.NETWORK_ERROR},504:{message:`Service unavailable: ${a}${l}`,code:u.NETWORK_ERROR}}[s]||{message:`HTTP ${s}: ${a}${l}`,code:u.UNKNOWN_ERROR},w=_nullishCoalesce(j(d), () => (E.code));throw new f(E.message,w,{statusCode:s,context:y})}function j(t){if(t==="definition_not_cached")return u.DEFINITION_NOT_CACHED}function Y(t,e){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${r}/${n}`}function Z(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 x=new Set;function X(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&&!x.has(e.serverUrl)&&!Z(e.serverUrl)&&(x.add(e.serverUrl),p().warn(`\u26A0\uFE0F [Rhino Compute] Request [${t}] targets remote server (${e.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited. (warned once per server)`)),r}function Q(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function R(t,e){e&&p().debug(t)}function ee(t,e){let r=[],n=()=>{};if(t&&r.push(t),e&&e>0)if(typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function")r.push(AbortSignal.timeout(e));else{let s=new AbortController,a=setTimeout(()=>s.abort(),e);n=()=>clearTimeout(a),r.push(s.signal)}if(r.length===0)return{signal:void 0,cleanup:n};if(r.length===1)return{signal:r[0],cleanup:n};if(typeof AbortSignal<"u"&&typeof AbortSignal.any=="function")return{signal:AbortSignal.any(r),cleanup:n};let o=new AbortController,i=()=>o.abort();for(let s of r){if(s.aborted){o.abort();break}s.addEventListener("abort",i,{once:!0})}let d=n;return n=()=>{d();for(let s of r)s.removeEventListener("abort",i)},{signal:o.signal,cleanup:n}}async function re(t,e,r,n,o,i,d,s){let a=Math.round(performance.now()-i);if(!t.ok){let c=await t.text();d&&(R(`\u274C Request [${r}] failed with HTTP ${t.status} in ${a}ms`,!0),R(` URL: ${e}`,!0),R(` Status: ${t.status} ${t.statusText}`,!0),c&&R(` Response body: ${c.substring(0,500)}${c.length>500?"...":""}`,!0));let m;try{let l=JSON.parse(c);typeof _optionalChain([l, 'optionalAccess', _11 => _11.code])=="string"&&(m=l.code)}catch (e3){}if(t.status===500)try{let l=JSON.parse(c);if(_optionalChain([l, 'optionalAccess', _12 => _12.values])&&(l.errors||l.warnings))return d&&(R(`\u26A0\uFE0F Request [${r}] completed with Grasshopper errors in ${a}ms`,!0),_optionalChain([l, 'access', _13 => _13.errors, 'optionalAccess', _14 => _14.length])>0&&R(` Errors: ${JSON.stringify(l.errors,null,2)}`,!0),_optionalChain([l, 'access', _15 => _15.warnings, 'optionalAccess', _16 => _16.length])>0&&R(` Warnings: ${JSON.stringify(l.warnings,null,2)}`,!0)),l;let y=typeof _optionalChain([l, 'optionalAccess', _17 => _17.message])=="string"&&l.message||typeof _optionalChain([l, 'optionalAccess', _18 => _18.Message])=="string"&&l.Message||"",g=typeof _optionalChain([l, 'optionalAccess', _19 => _19.ExceptionType])=="string"&&l.ExceptionType||"",E=_nullishCoalesce(_optionalChain([l, 'optionalAccess', _20 => _20.stackTrace]), () => (_optionalChain([l, 'optionalAccess', _21 => _21.StackTrace]))),w=Array.isArray(E)?E.join(`
|
|
2
2
|
`):E||"";y?c=`${g?`${g}: `:""}${y}${w?`
|
|
3
3
|
${w}`:""}`:_optionalChain([l, 'optionalAccess', _22 => _22.error])&&(c=typeof l.error=="string"?l.error:JSON.stringify(l.error,null,2))}catch(l){d&&R(` Failed to parse error body as JSON: ${l}`,!0)}G(t,e,r,n,o,c,m)}if(R(`\u2705 Request [${r}] completed in ${a}ms`,d),s){let c=H(t.headers.get("Server-Timing"));if(c)try{s(c)}catch(m){d&&R(` onServerTiming callback threw: ${m}`,!0)}}try{return await t.json()}catch(c){throw new f("Failed to parse JSON response",u.NETWORK_ERROR,{statusCode:t.status,context:{url:e,requestId:r},originalError:c instanceof Error?c:new Error(String(c))})}}async function te(t,e,r,n){let{signal:o,cleanup:i}=ee(t.config.signal,t.config.timeoutMs),d=performance.now();try{let s=await fetch(t.fullUrl,{method:"POST",body:t.body,headers:t.headers,signal:o});if((L.has(s.status)||e.retryOn429&&s.status===429)&&r<n-1){let m=V(s.headers.get("Retry-After")),l=m!==null?Math.min(m,e.maxDelayMs):O(r,e);return await s.text().catch(()=>{}),{ok:!1,retry:!0,delayMs:l,cause:new f(`HTTP ${s.status} ${s.statusText} (will retry)`,u.NETWORK_ERROR,{statusCode:s.status,context:{requestId:t.requestId}})}}return{ok:!0,value:await re(s,t.fullUrl,t.requestId,t.requestSize,t.config.serverUrl,d,t.config.debug,t.config.onServerTiming)}}catch(s){if(s instanceof Error&&(s.name==="AbortError"||s.name==="TimeoutError")){if(_optionalChain([t, 'access', _23 => _23.config, 'access', _24 => _24.signal, 'optionalAccess', _25 => _25.aborted])===!0)return{ok:!1,retry:!1,cause:new f("Request aborted by caller",u.ABORTED,{context:{endpoint:t.endpoint,requestId:t.requestId,requestSize:t.requestSize},originalError:s})};let c=new f(`Request timed out after ${t.config.timeoutMs}ms`,u.TIMEOUT_ERROR,{context:{serverUrl:t.config.serverUrl,timeoutMs:t.config.timeoutMs,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize}});return r<n-1?{ok:!1,retry:!0,delayMs:O(r,e),cause:c}:{ok:!1,retry:!1,cause:c}}if(s instanceof TypeError){let a=new f(`Network error: ${s.message}`,u.NETWORK_ERROR,{context:{serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:s});return r<n-1?{ok:!1,retry:!0,delayMs:O(r,e),cause:a}:{ok:!1,retry:!1,cause:a}}if(s instanceof f){let a=s.statusCode;return(s.code===u.NETWORK_ERROR&&a!==void 0&&a>=200&&a<300||a!==void 0&&(L.has(a)||e.retryOn429&&a===429))&&r<n-1?{ok:!1,retry:!0,delayMs:O(r,e),cause:s}:{ok:!1,retry:!1,cause:s}}return{ok:!1,retry:!1,cause:new f(s instanceof Error?s.message:String(s),u.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId},originalError:s instanceof Error?s:new Error(String(s))})}}finally{i()}}async function ne(t,e,r){let n=Q(),o=JSON.stringify(e),i=F(o),d=Y(t,r.serverUrl),s=X(n,r),a=z(r.retry),c=a.attempts+1;if(r.debug){let y=(i/1024).toFixed(2),g=i>1e5?"\u26A0\uFE0F":"\u{1F680}";R(`${g} Starting compute request [${n}]: ${t} (${y}KB)`,!0)}let m={endpoint:t,body:o,requestSize:i,fullUrl:d,requestId:n,headers:s,config:r},l=null;for(let y=0;y<c;y++){let g=await te(m,a,y,c);if(g.ok)return g.value;if(!g.retry)throw g.cause;l=g.cause,r.debug&&R(`\u{1F501} Request [${n}] retrying after ${g.delayMs}ms (attempt ${y+2}/${c}): ${g.cause.message}`,!0);try{await J(g.delayMs,r.signal)}catch (e4){throw new f("Request aborted by caller",u.ABORTED,{context:{endpoint:t,requestId:n,requestSize:i},originalError:l})}}throw _nullishCoalesce(l, () => (new f("Unknown error after retries",u.UNKNOWN_ERROR,{context:{endpoint:t,requestId:n,requestSize:i}})))}var oe="compute.rhino3d.com";function P(t){if(!_optionalChain([t, 'optionalAccess', _26 => _26.trim, 'call', _27 => _27()]))throw new f("serverUrl is required",u.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(!t.match(/^https?:\/\//))throw new f(`Invalid serverUrl: "${t}". Must start with "http://" or "https://". For example: "http://localhost:5000" or "https://example.com"`,u.INVALID_CONFIG,{context:{receivedServerUrl:t}});let e;try{e=new URL(t)}catch(r){throw new f(`Invalid serverUrl: "${t}". Must be a valid URL. Received error: ${r instanceof Error?r.message:String(r)}`,u.INVALID_CONFIG,{context:{receivedServerUrl:t},originalError:r instanceof Error?r:void 0})}if(e.hostname.toLowerCase()===oe)throw new f("serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.",u.INVALID_CONFIG,{context:{receivedServerUrl:t}});return t.replace(/\/+$/,"")}var b=class b{constructor(e,r){h(this,"serverUrl");h(this,"apiKey");h(this,"disposed",!1);h(this,"activeMonitors",new Set);h(this,"activeTimeouts",new Set);this.serverUrl=P(e),this.apiKey=r}buildHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,r={},n=b.DEFAULT_TIMEOUT_MS){let o=this.buildHeaders();r.headers&&new Headers(r.headers).forEach((d,s)=>{o[s]=d});let i={...r,headers:o};return n>0&&!i.signal&&(i.signal=AbortSignal.timeout(n)),fetch(e,i)}async isServerOnline(e=5e3){this.ensureNotDisposed();let r=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(r,{method:"GET"},e)).ok}catch(n){return p().debug("[ComputeServerStats] Fetch error:",n),!1}}async getActiveChildren(e={}){this.ensureNotDisposed();let{initialize:r=!0}=e,n=r?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,o=r?b.LIFECYCLE_TIMEOUT_MS:b.DEFAULT_TIMEOUT_MS;try{let i=await this.fetchWithTimeout(n,{},o);if(!i.ok)return p().warn("[ComputeServerStats] Failed to fetch active children:",i.status),null;let d=await i.text(),s=parseInt(d.trim(),10);return isNaN(s)?(p().warn("[ComputeServerStats] Invalid active children response:",d),null):s}catch(i){return p().warn("[ComputeServerStats] Error fetching active children:",i),null}}async getVersion(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch version:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return{rhino:_nullishCoalesce(n.rhino, () => ("")),compute:_nullishCoalesce(n.compute, () => ("")),git_sha:_nullishCoalesce(n.git_sha, () => (null))}}catch (e5){return{rhino:r,compute:"",git_sha:null}}}catch(e){return p().warn("[ComputeServerStats] Error fetching version:",e),null}}async getInstalledPlugins(e="gh"){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${e}/installed`);if(!r.ok)return p().warn(`[ComputeServerStats] Failed to fetch ${e} plugins:`,r.status),null;let n=await r.text();try{let o=JSON.parse(n);return o&&typeof o=="object"?o:null}catch (e6){return null}}catch(r){return p().warn(`[ComputeServerStats] Error fetching ${e} plugins:`,r),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[r,n]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...r&&{version:r},...n!==null&&{activeChildren:n}}}async purgeCache(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:"POST"});if(!e.ok)return p().warn("[ComputeServerStats] Failed to purge cache:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return typeof n.purged=="number"?n.purged:null}catch (e7){return null}}catch(e){return p().warn("[ComputeServerStats] Error purging cache:",e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return p().warn("[ComputeServerStats] purgeAllChildren: could not read child count"),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let r=e*2,n=0;for(let o=0;o<r;o++){let i=await this.purgeCache();i!==null&&(n+=i)}return{totalPurged:n,calls:r,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch server time:",e.status),null;let r=(await e.text()).trim().replace(/^"|"$/g,""),n=new Date(r);return isNaN(n.getTime())?null:n}catch(e){return p().warn("[ComputeServerStats] Error fetching server time:",e),null}}async getIdleSpan(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch idle span:",e.status),null;let r=parseFloat((await e.text()).trim());return isNaN(r)?null:r}catch(e){return p().warn("[ComputeServerStats] Error fetching idle span:",e),null}}async launchChildren(){return this.postJson("/launch-children")}async launchChild(e){let r=e===void 0?"/launch-child":`/launch-child?port=${e}`;return this.postJson(r)}async shutdownChildren(e){let r=e===void 0?"/shutdown-children":`/shutdown-children?port=${e}`;return this.postJson(r)}async recycleChildren(e){let r=e===void 0?"/recycle-children":`/recycle-children?port=${e}`;return this.postJson(r)}async postJson(e){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}${e}`,{method:"POST"},b.LIFECYCLE_TIMEOUT_MS);if(!r.ok)return p().warn(`[ComputeServerStats] POST ${e} failed:`,r.status),null;let n=await r.text();try{return JSON.parse(n)}catch (e8){return null}}catch(r){return p().warn(`[ComputeServerStats] Error on POST ${e}:`,r),null}}monitor(e,r=5e3){this.ensureNotDisposed();let n=!0,o=null;p().info(`\u{1F504} Starting server stats monitoring every ${r}ms`);let i=async()=>{if(o!==null&&(this.activeTimeouts.delete(o),o=null),!(!n||this.disposed)){try{let s=await this.getServerStats();if(!n||this.disposed)return;try{e(s)}catch(a){p().error("[ComputeServerStats] Monitor callback threw:",a)}}catch(s){p().error("[ComputeServerStats] Failed to fetch stats during monitor:",s)}n&&!this.disposed&&(o=setTimeout(()=>{i()},r),this.activeTimeouts.add(o))}},d=()=>{n=!1,o!==null&&(clearTimeout(o),this.activeTimeouts.delete(o),o=null),this.activeMonitors.delete(d)};return this.activeMonitors.add(d),i(),d}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new f("ComputeServerStats has been disposed and cannot be used",u.INVALID_STATE,{context:{disposed:this.disposed}})}};h(b,"DEFAULT_TIMEOUT_MS",5e3),h(b,"LIFECYCLE_TIMEOUT_MS",6e4);var C=b;function M(t,e={}){let{preserveSpaces:r=!1}=e,n=r?/[-_]+(.)?/g:/[\s-_]+(.)?/g,o=t.trim();return o.charAt(0).toLowerCase()+o.slice(1).replace(n,(i,d)=>d?d.toUpperCase():"")}function I(t,e={}){return!t||typeof t!="object"?t:Array.isArray(t)?e.deep?t.map(r=>I(r,e)):t:Object.keys(t).reduce((r,n)=>{let o=M(n,{preserveSpaces:e.preserveSpaces}),i=t[n];return r[o]=e.deep?I(i,e):i,r},{})}var se=async(t,e=null)=>{try{return await k(t,e)}catch(r){throw new f("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})}},ie= exports.r =async(t,e,r=null)=>{if(typeof document>"u"||typeof Blob>"u")throw new f("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 k(t,r);await ce(n,e)}catch(n){throw n instanceof f?n:new f("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})}},ae=t=>{let e=[];return t.forEach(r=>{let n=`${r.fileName}${r.fileType}`,o=r.subFolder&&r.subFolder.trim()!==""?`${r.subFolder}/${n}`:n;if(r.isBase64Encoded===!0&&r.data)try{e.push({fileName:n,content:_(r.data),path:o})}catch(i){p().warn(`Skipping file "${o}": base64 decode failed.`,i)}else r.isBase64Encoded===!1&&r.data?e.push({fileName:n,content:r.data,path:o}):p().warn(`Skipping file "${o}": item carries no usable data.`)}),e},ue=3e4,le=async t=>(await Promise.all(t.map(async r=>{try{let n=typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function"?AbortSignal.timeout(ue):void 0,o=await fetch(r.filePath,{signal:n});if(!o.ok)return p().warn(`Failed to fetch additional file from URL: ${r.filePath}`),null;let d=await(await o.blob()).arrayBuffer();return{fileName:r.fileName,content:new Uint8Array(d),path:r.fileName}}catch(n){return p().error(`Error fetching additional file from URL: ${r.filePath}`,n),null}}))).filter(r=>r!==null),k=async(t,e)=>{let r=ae(t);if(e){let n=Array.isArray(e)?e:[e];r.push(...await le(n))}return r};async function ce(t,e){let{zip:r,strToU8:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("fflate"))),o={};t.forEach(s=>{let a=de(s.path,o);a!==s.path&&p().warn(`Duplicate archive path "${s.path}" \u2014 storing as "${a}".`),o[a]=typeof s.content=="string"?n(s.content):s.content});let i=await new Promise((s,a)=>{r(o,{level:6},(c,m)=>c?a(c):s(m))}),d=new Blob([i],{type:"application/zip"});fe(d,`${e}.zip`)}function de(t,e){let r=a=>Object.prototype.hasOwnProperty.call(e,a);if(!r(t))return t;let n=t.lastIndexOf("/"),o=t.lastIndexOf("."),i=o>n?o:t.length,d=t.slice(0,i),s=t.slice(i);for(let a=2;;a++){let c=`${d}-${a}${s}`;if(!r(c))return c}}function fe(t,e){if(typeof document>"u")throw new f("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 = pe; exports.b = h; exports.c = u; exports.d = f; exports.e = p; exports.f = D; exports.g = K; exports.h = Ee; exports.i = ve; exports.j = _; exports.k = W; exports.l = ne; exports.m = P; exports.n = C; exports.o = M; exports.p = I; exports.q = se; exports.r = ie;
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-EUMIGWRX.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-EUMIGWRX.cjs","../src/core/errors.ts","../src/core/compute-fetch/compute-fetch.ts"],"names":["ErrorCodes","RhinoComputeError","_RhinoComputeError","message","code","options","__publicField","inputName","expectedType","context"],"mappings":"AAAA,u8BAAI,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CCI3N,IAAMA,CAAAA,CAAa,CACzB,aAAA,CAAe,eAAA,CACf,UAAA,CAAY,YAAA,CACZ,gBAAA,CAAkB,kBAAA,CAClB,iBAAA,CAAmB,mBAAA,CACnB,aAAA,CAAe,eAAA,CACf,UAAA,CAAY,YAAA,CACZ,aAAA,CAAe,eAAA,CACf,aAAA,CAAe,eAAA,CACf,aAAA,CAAe,eAAA,CACf,cAAA,CAAgB,gBAAA,CAChB,YAAA,CAAc,cAAA,CACd,iBAAA,CAAmB,mBAAA,CACnB,cAAA,CAAgB,gBAAA,CAEhB,iBAAA,CAAmB,mBAAA,CAEnB,UAAA,CAAY,YAAA,CAEZ,OAAA,CAAS,SAAA,CAQT,qBAAA,CAAuB,uBACxB,CAAA,CASaC,CAAAA,aAAN,MAAMC,EAAAA,QAA0B,KAAM,CAM5C,WAAA,CACCC,CAAAA,CACAC,CAAAA,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;AC+TzC;AAmI1C","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-EUMIGWRX.cjs","sourcesContent":[null,"/**\n * Error types and codes for `@selvajs/compute`.\n */\n\nexport const ErrorCodes = {\n\tNETWORK_ERROR: 'NETWORK_ERROR',\n\tAUTH_ERROR: 'AUTH_ERROR',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tCOMPUTATION_ERROR: 'COMPUTATION_ERROR',\n\tTIMEOUT_ERROR: 'TIMEOUT_ERROR',\n\tCORS_ERROR: 'CORS_ERROR',\n\tUNKNOWN_ERROR: 'UNKNOWN_ERROR',\n\tINVALID_STATE: 'INVALID_STATE',\n\tINVALID_INPUT: 'INVALID_INPUT',\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\tBROWSER_ONLY: 'BROWSER_ONLY',\n\tENVIRONMENT_ERROR: 'ENVIRONMENT_ERROR',\n\tENCODING_ERROR: 'ENCODING_ERROR',\n\t/** An input's `default` had a shape the normalizer didn't recognize (no innerTree key). */\n\tMALFORMED_DEFAULT: 'MALFORMED_DEFAULT',\n\t/** Scheduler latest-wins: this call was replaced by a newer one. */\n\tSUPERSEDED: 'SUPERSEDED',\n\t/** Scheduler / caller-supplied AbortSignal: this call was aborted. */\n\tABORTED: 'ABORTED',\n\t/**\n\t * A solve referenced a definition by `pointer` (server-side cache key), but the\n\t * server no longer holds that definition (evicted / GC'd / a different child in\n\t * the pool / server restarted). The caller should retry with the full\n\t * definition. Surfaced when the server tags its error body with\n\t * `code: \"definition_not_cached\"`, so it survives production message-scrubbing.\n\t */\n\tDEFINITION_NOT_CACHED: 'DEFINITION_NOT_CACHED'\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/**\n * Simplified error for Rhino Compute operations\n *\n * @public Use this for error handling with error codes and context.\n */\nexport class RhinoComputeError extends Error {\n\tpublic readonly code: 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\nfunction resolveRetryPolicy(policy: RetryPolicy | undefined): Required<RetryPolicy> {\n\tif (!policy) return DEFAULT_RETRY;\n\treturn {\n\t\tattempts: policy.attempts ?? DEFAULT_RETRY.attempts,\n\t\tbaseDelayMs: policy.baseDelayMs ?? DEFAULT_RETRY.baseDelayMs,\n\t\tmaxDelayMs: policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs,\n\t\tretryOn429: policy.retryOn429 ?? DEFAULT_RETRY.retryOn429\n\t};\n}\n\n/**\n * Parse a Retry-After header value (seconds-int or HTTP-date) into ms.\n * Returns null if the header is missing or unparseable.\n */\nfunction parseRetryAfter(headerValue: string | null): number | null {\n\tif (!headerValue) return null;\n\tconst seconds = Number(headerValue);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n\tconst dateMs = Date.parse(headerValue);\n\tif (Number.isFinite(dateMs)) {\n\t\tconst delta = dateMs - Date.now();\n\t\treturn delta > 0 ? delta : 0;\n\t}\n\treturn null;\n}\n\nfunction backoffDelay(attempt: number, policy: Required<RetryPolicy>): number {\n\tconst exponential = policy.baseDelayMs * Math.pow(2, attempt);\n\tconst jitter = Math.random() * policy.baseDelayMs;\n\treturn Math.min(exponential + jitter, policy.maxDelayMs);\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t\treturn;\n\t\t}\n\t\tconst id = setTimeout(() => {\n\t\t\tsignal?.removeEventListener('abort', onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(id);\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t};\n\t\tsignal?.addEventListener('abort', onAbort, { once: true });\n\t});\n}\n\n// ============================================================================\n// Error Handling\n// ============================================================================\n\nfunction throwHttpError(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\terrorBody: string,\n\tserverCode?: string\n): never {\n\tconst { status, statusText } = response;\n\n\tconst responseHeaders: Record<string, string> = {};\n\tresponse.headers.forEach((value, key) => {\n\t\tresponseHeaders[key] = value;\n\t});\n\n\tconst trimmed = errorBody.trim();\n\tconst bodyHint = trimmed ? ` — ${trimmed.slice(0, 200)}${trimmed.length > 200 ? '…' : ''}` : '';\n\n\tconst context = {\n\t\turl: fullUrl,\n\t\trequestId,\n\t\tmethod: 'POST',\n\t\trequestSize,\n\t\tserverUrl,\n\t\tresponseBody: errorBody || undefined,\n\t\tresponseHeaders\n\t};\n\n\tconst errorMap: Record<number, { message: string; code: 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.NETWORK_ERROR },\n\t\t413: {\n\t\t\tmessage: `Request too large: ${(requestSize / 1024).toFixed(2)}KB`,\n\t\t\tcode: ErrorCodes.VALIDATION_ERROR\n\t\t},\n\t\t429: { message: `Rate limit exceeded${bodyHint}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t500: { message: `Server error: ${statusText}${bodyHint}`, code: ErrorCodes.COMPUTATION_ERROR },\n\t\t502: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t503: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t504: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t}\n\t};\n\n\tconst error = errorMap[status] || {\n\t\tmessage: `HTTP ${status}: ${statusText}${bodyHint}`,\n\t\tcode: ErrorCodes.UNKNOWN_ERROR\n\t};\n\n\t// A machine code in the server's error body (e.g. \"definition_not_cached\")\n\t// outranks the status-based mapping: it's stable across the server's\n\t// production message-scrubbing, where the human message is replaced with a\n\t// generic string. Keep the status-derived message for context.\n\tconst code = mapServerErrorCode(serverCode) ?? error.code;\n\n\tthrow new RhinoComputeError(error.message, code, { statusCode: status, context });\n}\n\n/**\n * Map a server-supplied error code (from the JSON error body's `code` field) to\n * one of our {@link ErrorCodes}. Returns `undefined` for an absent or unknown\n * code so the caller falls back to its status-based mapping.\n */\nfunction mapServerErrorCode(serverCode?: string): ErrorCode | undefined {\n\tswitch (serverCode) {\n\t\tcase 'definition_not_cached':\n\t\t\treturn ErrorCodes.DEFINITION_NOT_CACHED;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n// ============================================================================\n// Request Helpers\n// ============================================================================\n\nfunction buildUrl(endpoint: string, serverUrl: string): string {\n\tconst base = serverUrl.replace(/\\/+$/, '');\n\tconst path = endpoint.replace(/^\\/+/, '');\n\treturn `${base}/${path}`;\n}\n\nfunction isLocalhost(serverUrl: string): boolean {\n\ttry {\n\t\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 signals: AbortSignal[] = [];\n\tlet cleanup = () => {};\n\n\tif (callerSignal) signals.push(callerSignal);\n\n\tif (timeoutMs && timeoutMs > 0) {\n\t\tif (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {\n\t\t\tsignals.push(AbortSignal.timeout(timeoutMs));\n\t\t} else {\n\t\t\t// Fallback for runtimes without AbortSignal.timeout\n\t\t\tconst ctrl = new AbortController();\n\t\t\tconst id = setTimeout(() => ctrl.abort(), timeoutMs);\n\t\t\tcleanup = () => clearTimeout(id);\n\t\t\tsignals.push(ctrl.signal);\n\t\t}\n\t}\n\n\tif (signals.length === 0) return { signal: undefined, cleanup };\n\tif (signals.length === 1) return { signal: signals[0], cleanup };\n\n\tif (typeof AbortSignal !== 'undefined' && typeof (AbortSignal as any).any === 'function') {\n\t\treturn { signal: (AbortSignal as any).any(signals) as AbortSignal, cleanup };\n\t}\n\n\t// Manual composition fallback\n\tconst ctrl = new AbortController();\n\tconst onAbort = () => ctrl.abort();\n\tfor (const s of signals) {\n\t\tif (s.aborted) {\n\t\t\tctrl.abort();\n\t\t\tbreak;\n\t\t}\n\t\ts.addEventListener('abort', onAbort, { once: true });\n\t}\n\tconst prevCleanup = cleanup;\n\tcleanup = () => {\n\t\tprevCleanup();\n\t\tfor (const s of signals) s.removeEventListener('abort', onAbort);\n\t};\n\treturn { signal: ctrl.signal, cleanup };\n}\n\n// ============================================================================\n// Response Processing\n// ============================================================================\n\nasync function handleResponse(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\tstartTime: number,\n\tdebug?: boolean,\n\tonServerTiming?: (timing: ServerTiming) => void\n): Promise<any> {\n\tconst responseTime = Math.round(performance.now() - startTime);\n\n\tif (!response.ok) {\n\t\t// Read body once and reuse\n\t\tlet errorBody = await response.text();\n\n\t\t// Enhanced logging for errors\n\t\tif (debug) {\n\t\t\tlog(\n\t\t\t\t`❌ Request [${requestId}] failed with HTTP ${response.status} in ${responseTime}ms`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t\tlog(` URL: ${fullUrl}`, true);\n\t\t\tlog(` Status: ${response.status} ${response.statusText}`, true);\n\t\t\tif (errorBody) {\n\t\t\t\tlog(\n\t\t\t\t\t` Response body: ${errorBody.substring(0, 500)}${errorBody.length > 500 ? '...' : ''}`,\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// A machine-readable code the server may tag onto its error body (e.g.\n\t\t// \"definition_not_cached\"). Unlike the human `message`, it isn't scrubbed in\n\t\t// the server's production (non-debug) mode, so it's the reliable signal for\n\t\t// classifying the error (see throwHttpError → mapServerErrorCode).\n\t\tlet serverCode: string | undefined;\n\n\t\t// The machine code (e.g. `definition_not_cached`) can ride any error status,\n\t\t// not just 500, and must outrank the status-based mapping — so read it here.\n\t\ttry {\n\t\t\tconst parsedForCode = JSON.parse(errorBody);\n\t\t\tif (typeof parsedForCode?.code === 'string') serverCode = parsedForCode.code;\n\t\t} catch {\n\t\t\t// Non-JSON body — nothing to extract.\n\t\t}\n\n\t\t// Check if it's a valid compute response with errors/warnings\n\t\tif (response.status === 500) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(errorBody);\n\t\t\t\t// If it has values, it's a partial success with errors\n\t\t\t\tif (parsed?.values && (parsed.errors || parsed.warnings)) {\n\t\t\t\t\tif (debug) {\n\t\t\t\t\t\tlog(\n\t\t\t\t\t\t\t`⚠️ Request [${requestId}] completed with Grasshopper errors in ${responseTime}ms`,\n\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (parsed.errors?.length > 0) {\n\t\t\t\t\t\t\tlog(` Errors: ${JSON.stringify(parsed.errors, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (parsed.warnings?.length > 0) {\n\t\t\t\t\t\t\tlog(` Warnings: ${JSON.stringify(parsed.warnings, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\n\t\t\t\t// Raw server-side exception. The Compute8 server's exception handler\n\t\t\t\t// (compute.geometry Startup.cs) emits:\n\t\t\t\t// { error: \"Internal Server Error\", message: \"<category>: <detail>\",\n\t\t\t\t// stackTrace?: string[] } // stackTrace only when Config.Debug\n\t\t\t\t// The actionable part is `message` — surface it, with the optional\n\t\t\t\t// stack appended for debugging. We prefer `message`/`error` (current\n\t\t\t\t// server) and keep `Message`/`ExceptionType`/`StackTrace` (old\n\t\t\t\t// PascalCase .NET shape) as a back-compat fallback so an older server\n\t\t\t\t// still produces a useful message.\n\t\t\t\tconst serverMessage =\n\t\t\t\t\t(typeof parsed?.message === 'string' && parsed.message) ||\n\t\t\t\t\t(typeof parsed?.Message === 'string' && parsed.Message) ||\n\t\t\t\t\t'';\n\t\t\t\tconst exceptionType =\n\t\t\t\t\t(typeof parsed?.ExceptionType === 'string' && parsed.ExceptionType) || '';\n\t\t\t\tconst stack = parsed?.stackTrace ?? parsed?.StackTrace;\n\t\t\t\tconst stackStr = Array.isArray(stack) ? stack.join('\\n') : stack || '';\n\n\t\t\t\tif (serverMessage) {\n\t\t\t\t\t// Don't repeat the generic \"Internal Server Error\" label when the\n\t\t\t\t\t// message already carries the real detail.\n\t\t\t\t\tconst prefix = exceptionType ? `${exceptionType}: ` : '';\n\t\t\t\t\terrorBody = `${prefix}${serverMessage}${stackStr ? `\\n${stackStr}` : ''}`;\n\t\t\t\t} else if (parsed?.error) {\n\t\t\t\t\terrorBody =\n\t\t\t\t\t\ttypeof parsed.error === 'string' ? parsed.error : JSON.stringify(parsed.error, null, 2);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tif (debug) {\n\t\t\t\t\tlog(` Failed to parse error body as JSON: ${e}`, true);\n\t\t\t\t}\n\t\t\t\t// Not valid JSON, proceed with HTTP error\n\t\t\t}\n\t\t}\n\n\t\tthrowHttpError(response, fullUrl, requestId, requestSize, serverUrl, errorBody, serverCode);\n\t}\n\n\tlog(`✅ Request [${requestId}] completed in ${responseTime}ms`, debug);\n\n\t// Surface the server's per-request timing breakdown (if it sent one and a\n\t// caller is listening). Best-effort: a throwing callback must not fail the\n\t// request, since the body parse below is the real result.\n\tif (onServerTiming) {\n\t\tconst timing = parseServerTiming(response.headers.get('Server-Timing'));\n\t\tif (timing) {\n\t\t\ttry {\n\t\t\t\tonServerTiming(timing);\n\t\t\t} catch (err) {\n\t\t\t\tif (debug) log(` onServerTiming callback threw: ${err}`, true);\n\t\t\t}\n\t\t}\n\t}\n\n\ttry {\n\t\treturn await response.json();\n\t} catch (error) {\n\t\tthrow new RhinoComputeError('Failed to parse JSON response', ErrorCodes.NETWORK_ERROR, {\n\t\t\tstatusCode: response.status,\n\t\t\tcontext: {\n\t\t\t\turl: fullUrl,\n\t\t\t\trequestId\n\t\t\t},\n\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t});\n\t}\n}\n\n// ============================================================================\n// Single attempt\n// ============================================================================\n\ninterface AttemptContext {\n\tendpoint: string;\n\tbody: string;\n\trequestSize: number;\n\tfullUrl: string;\n\trequestId: string;\n\theaders: HeadersInit;\n\tconfig: ComputeConfig;\n}\n\ninterface AttemptResult {\n\tok: true;\n\tvalue: any;\n}\n\ninterface AttemptRetry {\n\tok: false;\n\tretry: true;\n\tdelayMs: number;\n\tcause: RhinoComputeError;\n}\n\ninterface AttemptFatal {\n\tok: false;\n\tretry: false;\n\tcause: RhinoComputeError;\n}\n\nasync function attemptFetch(\n\tctx: AttemptContext,\n\tretryPolicy: Required<RetryPolicy>,\n\tattempt: number,\n\ttotalAttempts: number\n): Promise<AttemptResult | AttemptRetry | AttemptFatal> {\n\tconst { signal, cleanup } = composeSignal(ctx.config.signal, ctx.config.timeoutMs);\n\tconst startTime = performance.now();\n\n\ttry {\n\t\tconst response = await fetch(ctx.fullUrl, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: ctx.body,\n\t\t\theaders: ctx.headers,\n\t\t\tsignal\n\t\t});\n\n\t\t// 429 with Retry-After or retryable 5xx → maybe retry\n\t\tconst isRetryableStatus =\n\t\t\tRETRYABLE_STATUS.has(response.status) || (retryPolicy.retryOn429 && response.status === 429);\n\n\t\tif (isRetryableStatus && attempt < totalAttempts - 1) {\n\t\t\tconst retryAfterMs = parseRetryAfter(response.headers.get('Retry-After'));\n\t\t\t// Clamp Retry-After to maxDelayMs so a bad header can't force an\n\t\t\t// arbitrarily long sleep. backoffDelay already clamps.\n\t\t\tconst delayMs =\n\t\t\t\tretryAfterMs !== null\n\t\t\t\t\t? Math.min(retryAfterMs, retryPolicy.maxDelayMs)\n\t\t\t\t\t: backoffDelay(attempt, retryPolicy);\n\t\t\t// Drain the body so the connection can be reused on the next attempt.\n\t\t\t// On the *final* attempt we deliberately fall through — handleResponse\n\t\t\t// reads the body itself to surface the error context.\n\t\t\tawait response.text().catch(() => {});\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tretry: true,\n\t\t\t\tdelayMs,\n\t\t\t\tcause: new RhinoComputeError(\n\t\t\t\t\t`HTTP ${response.status} ${response.statusText} (will retry)`,\n\t\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t{ statusCode: response.status, context: { requestId: ctx.requestId } }\n\t\t\t\t)\n\t\t\t};\n\t\t}\n\n\t\tconst value = await handleResponse(\n\t\t\tresponse,\n\t\t\tctx.fullUrl,\n\t\t\tctx.requestId,\n\t\t\tctx.requestSize,\n\t\t\tctx.config.serverUrl,\n\t\t\tstartTime,\n\t\t\tctx.config.debug,\n\t\t\tctx.config.onServerTiming\n\t\t);\n\t\treturn { ok: true, value };\n\t} catch (error) {\n\t\t// Caller-aborted vs timeout-aborted distinction\n\t\tif (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {\n\t\t\tconst callerAborted = ctx.config.signal?.aborted === true;\n\n\t\t\tif (callerAborted) {\n\t\t\t\t// Caller cancellation is never retried — propagate immediately\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: false,\n\t\t\t\t\tcause: new RhinoComputeError('Request aborted by caller', ErrorCodes.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// Timeout — retryable up to attempts limit\n\t\t\tconst fatal = new RhinoComputeError(\n\t\t\t\t`Request timed out after ${ctx.config.timeoutMs}ms`,\n\t\t\t\tErrorCodes.TIMEOUT_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\ttimeoutMs: ctx.config.timeoutMs,\n\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// Network error (TypeError) — retryable\n\t\tif (error instanceof TypeError) {\n\t\t\tconst fatal = new RhinoComputeError(\n\t\t\t\t`Network error: ${error.message}`,\n\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t},\n\t\t\t\t\toriginalError: error\n\t\t\t\t}\n\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// RhinoComputeError thrown from handleResponse — already has full context.\n\t\t// Retryable only if it carries a retryable status code.\n\t\tif (error instanceof RhinoComputeError) {\n\t\t\tconst status = error.statusCode;\n\t\t\t// A 2xx whose body failed to parse (NETWORK_ERROR from handleResponse)\n\t\t\t// means the stream was cut mid-body — as transient as any network error.\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 * @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\tlet lastError: RhinoComputeError | null = null;\n\n\tfor (let attempt = 0; attempt < totalAttempts; attempt++) {\n\t\tconst result = await attemptFetch(ctx, retryPolicy, attempt, totalAttempts);\n\n\t\tif (result.ok) return result.value as R;\n\n\t\tif (!result.retry) throw result.cause;\n\n\t\tlastError = result.cause;\n\t\tif (config.debug) {\n\t\t\tlog(\n\t\t\t\t`🔁 Request [${requestId}] retrying after ${result.delayMs}ms (attempt ${attempt + 2}/${totalAttempts}): ${result.cause.message}`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\tawait sleep(result.delayMs, config.signal);\n\t\t} catch {\n\t\t\t// Caller cancelled during backoff\n\t\t\tthrow new RhinoComputeError('Request aborted by caller', ErrorCodes.ABORTED, {\n\t\t\t\tcontext: { endpoint, requestId, requestSize },\n\t\t\t\toriginalError: lastError\n\t\t\t});\n\t\t}\n\t}\n\n\t// Exhausted retries — throw the last seen error\n\tthrow (\n\t\tlastError ??\n\t\tnew RhinoComputeError('Unknown error after retries', ErrorCodes.UNKNOWN_ERROR, {\n\t\t\tcontext: { endpoint, requestId, requestSize }\n\t\t})\n\t);\n}\n"]}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import{a as Ge,c as se,d as le,e as C,j as pe}from"./chunk-QAOHGIFT.js";import*as _ from"three";var $={HUGE_THRESHOLD:1e4,LARGE_THRESHOLD:1e3,SCALE_RATIO_THRESHOLD:100,NEAR_PLANE_FACTOR:{TINY:1e-4,SMALL:.001,NORMAL:.01},FAR_PLANE_FACTOR:{HUGE:100,LARGE:50,NORMAL:20},INITIAL_DISTANCE_MULTIPLIER:4};function Zr(e,n,t,r,o){if(We(e),n.length===0)return;n.forEach(u=>{e.add(u)});let a=K(n),i=a.getCenter(new _.Vector3),s=a.getSize(new _.Vector3),l=Math.max(s.x,s.y,s.z);if(l/Math.min(s.x||1,s.y||1,s.z||1)>$.SCALE_RATIO_THRESHOLD||l>$.HUGE_THRESHOLD?(t.near=l*$.NEAR_PLANE_FACTOR.TINY,t.far=l*$.FAR_PLANE_FACTOR.HUGE):l>$.LARGE_THRESHOLD?(t.near=l*$.NEAR_PLANE_FACTOR.SMALL,t.far=l*$.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,l*$.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,l*$.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),o)r.minDistance=t.near*2,r.maxDistance=t.far*.9;else{let u=l*$.INITIAL_DISTANCE_MULTIPLIER;t.position.set(i.x+u*.8,i.y+u,i.z+u*1.2),r.target.copy(i),r.minDistance=t.near*2,r.maxDistance=t.far*.9,r.update()}}function Ee(e){if(!e||typeof e!="string")return C().warn(`Invalid color input: ${e}, using white`),new _.Color(16777215);let n=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(n))try{let t=n.startsWith("#")?n:`#${n}`;return new _.Color(t)}catch{return C().warn(`Invalid hex color: ${e}, using white`),new _.Color(16777215)}if(n.includes(",")){let t=n.split(",").map(r=>parseInt(r.trim(),10));if(t.length===3&&t.every(r=>!isNaN(r)&&r>=0&&r<=255))return new _.Color(t[0]/255,t[1]/255,t[2]/255)}try{return new _.Color(n.toLowerCase())}catch{return C().warn(`Invalid color string: ${e}, using white`),new _.Color(16777215)}}function he(e,n,t="z"){e.forEach(r=>{r.position[t]-=n})}function K(e){let n=new _.Box3;return e.length===0||e.forEach(t=>{t.updateMatrixWorld(!0);let r=new _.Box3().setFromObject(t);n.union(r)}),n}var Ne=new Set(["floor","grid","label-layer"]);function We(e){[...e.children].forEach(t=>{Ne.has(t.userData.id)||t.userData.source!=="user"&&(t.traverse(r=>{let o=r;if(!o.geometry&&!o.material)return;o.geometry?.dispose();let a=o.material;if(!a)return;(Array.isArray(a)?a:[a]).forEach(s=>{for(let l of Object.values(s))l instanceof _.Texture&&l.dispose();s.dispose()})}),t.removeFromParent())})}import*as k from"three";function $e(e){let n=e.clone().normalize(),t=new k.Vector3(0,0,1),r=new k.Vector3(0,1,0),o=Math.abs(n.dot(t))>.9?r:t,a=new k.Vector3().crossVectors(n,o).normalize(),i=new k.Vector3().crossVectors(a,n).normalize();return{top:n.clone(),bottom:n.clone().negate(),front:i.clone(),back:i.clone().negate(),right:a.clone(),left:a.clone().negate(),iso:i.clone().multiplyScalar(1.2).add(a.clone()).add(n.clone()).normalize()}}function ge(e){let{scene:n,perspective:t,controls:r,onActiveCameraChange:o}=e,a=(e.up??t.up).clone().normalize(),i=$e(a),s=new k.OrthographicCamera(-1,1,1,-1,t.near,t.far);s.up.copy(a);let l="perspective",c=t.aspect,u=()=>l==="perspective"?t:s,d=()=>{let f=t.position.distanceTo(r.target)*Math.tan(t.fov*Math.PI/360),b=f*c;s.left=-b,s.right=b,s.top=f,s.bottom=-f,s.near=t.near,s.far=t.far,s.updateProjectionMatrix()},m=h=>{h!==l&&(h==="orthographic"?(s.position.copy(t.position),s.up.copy(t.up),s.lookAt(r.target),d()):t.position.copy(s.position),l=h,r.object=u(),r.update(),o(u()))},p=(h,f=!0)=>{let b=qe(n),x=b.isEmpty()?r.target.clone():b.getCenter(new k.Vector3),O=b.isEmpty()?new k.Vector3(1,1,1):b.getSize(new k.Vector3),T=Math.max(O.x,O.y,O.z)||1,w=t.fov*(Math.PI/180),M=T/(2*Math.tan(w/2))*1.5,P=Ze(h,a),S=x.clone().add(P.clone().multiplyScalar(M)),I=u();f?Ke(I,r,S,x,()=>{l==="orthographic"&&d()}):(I.position.copy(S),r.target.copy(x),l==="orthographic"&&d(),r.update())};return{getActiveCamera:u,getProjection:()=>l,setProjection:m,toggleProjection:()=>(m(l==="perspective"?"orthographic":"perspective"),l),setView:(h,f=!0)=>{p(i[h],f)},setViewDirection:p,setRotateEnabled:h=>{r.enableRotate=h},isRotateEnabled:()=>r.enableRotate,updateAspect:(h,f)=>{c=f===0?c:h/f,l==="orthographic"&&d()}}}var Ye=new Set(["grid","floor","label-layer","measure"]);function Xe(e){let n=e;for(;n;){if(typeof n.userData.id=="string"&&Ye.has(n.userData.id))return!0;n=n.parent}return!1}function qe(e){let n=[];return e.traverse(t=>{let r=t;t.visible&&!Xe(t)&&r.geometry&&n.push(t)}),K(n)}function Ze(e,n){let t=n.clone().normalize(),r=e.clone().normalize();if(Math.abs(r.dot(t))<.9999)return e;let o=Math.abs(t.dot(new k.Vector3(0,0,1)))>.9?new k.Vector3(0,1,0):new k.Vector3(0,0,1),a=new k.Vector3().crossVectors(t,o).normalize(),i=.5*Math.PI/180;return r.multiplyScalar(Math.cos(i)).add(a.multiplyScalar(Math.sin(i))).normalize()}var Je=e=>1-Math.pow(1-e,3);function Ke(e,n,t,r,o,a=250){let i=e.position.clone(),s=n.target.clone(),l=performance.now(),c=()=>{let u=Je(Math.min((performance.now()-l)/a,1));e.position.lerpVectors(i,t,u),n.target.lerpVectors(s,r,u),o(),n.update(),u<1&&requestAnimationFrame(c)};requestAnimationFrame(c)}import*as F from"three";var Qe=`
|
|
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
|
+
`,et=`
|
|
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 ye(e={}){let{cellSize:n=1,majorEvery:t=10,cellColor:r=8947848,majorColor:o=4473924,fadeDistance:a=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=a*2.5,c=new F.PlaneGeometry(l,l);i==="y"?c.rotateX(-Math.PI/2):i==="x"&&c.rotateY(Math.PI/2);let u=new F.ShaderMaterial({vertexShader:Qe,fragmentShader:et,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(o)},uCenter:{value:new F.Vector3},uFade:{value:a}}}),d=new F.Mesh(c,u);d.name="grid",d.userData.id="grid",d.renderOrder=-1;let m=new F.Vector3;return{object:d,update:p=>{i==="y"?(d.position.set(p.x,0,p.z),m.set(p.x,0,p.z)):i==="z"?(d.position.set(p.x,p.y,0),m.set(p.x,p.y,0)):(d.position.set(0,p.y,p.z),m.set(0,p.y,p.z)),u.uniforms.uCenter.value.copy(m)},setVisible:p=>{d.visible=p},dispose:()=>{c.dispose(),u.dispose()}}}import*as G from"three";import{ViewHelper as tt}from"three/addons/helpers/ViewHelper.js";function be(e){let{camera:n,domElement:t,controller:r}=e,o=new tt(n,t);o.setLabels("X","Y","Z");let a=!0,i=128,s=new G.Raycaster,l=new G.OrthographicCamera(-2,2,2,-2,0,4);l.position.set(0,0,2);let c={posX:new G.Vector3(1,0,0),negX:new G.Vector3(-1,0,0),posY:new G.Vector3(0,1,0),negY:new G.Vector3(0,-1,0),posZ:new G.Vector3(0,0,1),negZ:new G.Vector3(0,0,-1)},u=m=>{let p=t.getBoundingClientRect(),g=p.left+t.offsetWidth-i-o.location.right,v=p.top+t.offsetHeight-i-o.location.bottom,y=new G.Vector2((m.clientX-g)/i*2-1,-((m.clientY-v)/i)*2+1);if(Math.abs(y.x)>1||Math.abs(y.y)>1)return null;o.quaternion.copy(n.quaternion).invert(),o.updateMatrixWorld(),s.setFromCamera(y,l);let h=s.intersectObjects(o.children,!1);for(let f of h){let b=f.object.userData?.type;if(typeof b=="string"&&b in c)return b}return null};return{render:m=>{if(!a)return;let p=m.autoClear;m.autoClear=!1,o.render(m),m.autoClear=p},update:m=>{o.animating&&o.update(m)},handleClick:m=>{if(!a)return!1;let p=u(m);return p?(r.getProjection()==="orthographic"&&r.setProjection("perspective"),r.setViewDirection(c[p],!1),!0):!1},get isAnimating(){return o.animating},setVisible:m=>{a=m},isVisible:()=>a,dispose:()=>o.dispose()}}import*as J from"three";import{LineSegmentsGeometry as rt}from"three/addons/lines/LineSegmentsGeometry.js";import{LineSegments2 as Te}from"three/addons/lines/LineSegments2.js";import{LineMaterial as nt}from"three/addons/lines/LineMaterial.js";var re="edge-overlay",ot=2236962,at=1.5,it=30;function Re(e,n={}){let t=new J.Color(n.color??ot),r=n.width??at,o=n.thresholdAngle??it,a=[];return e.traverse(i=>{if(!(i instanceof J.Mesh)||i.userData.id==="floor"||i.userData.id==="grid"||i.userData.kind===re||i.children.some(l=>l.userData?.kind===re)||!i.geometry)return;let s=st(i.geometry,t,r,o);i.add(s),a.push(s)}),a}function st(e,n,t,r){let o=new J.EdgesGeometry(e,r),a=new rt;a.setPositions(o.attributes.position.array),o.dispose();let i=new nt({color:n});i.linewidth=t,i.polygonOffset=!0,i.polygonOffsetFactor=-1,i.polygonOffsetUnits=-1;let s=new Te(a,i);return s.userData.kind=re,s.raycast=()=>{},s}function lt(e){return e.userData?.kind===re}function sn(e){let n=[];e.traverse(t=>{t instanceof Te&<(t)&&n.push(t)});for(let t of n)t.geometry.dispose(),t.material.dispose(),t.removeFromParent();return n.length}import{EffectComposer as ct}from"three/addons/postprocessing/EffectComposer.js";import{RenderPass as ut}from"three/addons/postprocessing/RenderPass.js";import{GTAOPass as dt}from"three/addons/postprocessing/GTAOPass.js";import{OutputPass as mt}from"three/addons/postprocessing/OutputPass.js";function we(e,n,t,r,o,a){let i=new ct(e),s=new ut(n,t);i.addPass(s);let l=new dt(n,t,r,o);l.blendIntensity=a.aoIntensity??1,l.updateGtaoMaterial({screenSpaceRadius:!0}),i.addPass(l);let c=new mt;return i.addPass(c),e.toneMapping=a.toneMapping,e.toneMappingExposure=a.toneMappingExposure,i.setSize(r,o),{render:u=>i.render(u),setSize:(u,d,m)=>{i.setPixelRatio(m),i.setSize(u,d),l.setSize(u,d)},setCamera:u=>{s.camera=u,l.camera=u},dispose:()=>{i.dispose(),l.dispose(),c.dispose()}}}import*as He from"three";import{CSS2DRenderer as ft,CSS2DObject as pt}from"three/addons/renderers/CSS2DRenderer.js";function ve(e,n){let t=new ft,r=t.domElement;r.style.position="absolute",r.style.top="0",r.style.left="0",r.style.width="100%",r.style.height="100%",r.style.overflow="hidden",r.style.pointerEvents="none",r.style.zIndex="30",getComputedStyle(e).position==="static"&&(e.style.position="relative"),e.appendChild(r);let o={width:e.clientWidth||1,height:e.clientHeight||1};t.setSize(o.width,o.height);let a=new He.Group;a.name="label-layer",a.userData.id="label-layer",n.add(a);let i=new Set;return{addLabel:(l,c,u)=>{let d=document.createElement("div");d.textContent=l,u?d.className=u:Object.assign(d.style,{padding:"2px 6px",borderRadius:"4px",background:"rgba(20, 20, 20, 0.78)",color:"#fff",font:"12px/1.3 system-ui, sans-serif",whiteSpace:"pre",textAlign:"center",userSelect:"none"}),d.style.pointerEvents="none";let m=new pt(d);return m.position.copy(c),a.add(m),i.add(m),{object:m,setPosition:p=>m.position.copy(p),setText:p=>{d.textContent=p},remove:()=>{m.removeFromParent(),d.remove(),i.delete(m)}}},render:(l,c)=>t.render(l,c),setSize:(l,c)=>t.setSize(l,c),dispose:()=>{i.forEach(l=>{l.removeFromParent(),l.element.remove()}),i.clear(),a.removeFromParent(),r.remove()}}}import*as D from"three";import{Line2 as Et}from"three/addons/lines/Line2.js";import{LineGeometry as ht}from"three/addons/lines/LineGeometry.js";import{LineMaterial as gt}from"three/addons/lines/LineMaterial.js";var yt=12,bt=16763904,Tt=.015,xe={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 Rt(e){let n=e&&xe[e]||xe.Meters;return t=>`${(t/n.metersPerUnit).toPrecision(3)} ${n.suffix}`}function wt(e){let n=e.object;return n instanceof D.Mesh?e.face?[e.face.a,e.face.b,e.face.c]:null:n instanceof D.Points?e.index!=null?[e.index]:null:n instanceof D.Line&&e.index!=null?[e.index,e.index+1]:null}function Ht(e,n,t,r){let o=e.point.clone(),a=e.object,i=wt(e);if(!i||!a.geometry)return o;let s=a.geometry.attributes.position;if(!s)return o;let l=m=>{let p=m.clone().project(n);return new D.Vector2((p.x+1)/2*t.width,(1-p.y)/2*t.height)},c=l(o),u=o,d=r;for(let m of i){if(m>=s.count)continue;let g=new D.Vector3().fromBufferAttribute(s,m).applyMatrix4(a.matrixWorld),v=l(g).distanceTo(c);v<d&&(d=v,u=g)}return u}function Me(e){let{canvas:n,scene:t,getActiveCamera:r,labelLayer:o,options:a={}}=e,i=a.snapPixels??yt,s=new D.Color(a.color??bt),l=Rt(a.displayUnit),c=(R,H)=>`${l(R)}
|
|
54
|
+
\u0394x ${l(H.x)} \u0394y ${l(H.y)} \u0394z ${l(H.z)}`,u=a.format??c,d=new D.Raycaster,m=new D.Vector2,p=!1,g=[],v=[],y=null,h=null,f=new D.PointsMaterial({color:s,size:8,sizeAttenuation:!1,depthTest:!1}),b=new D.PointsMaterial({color:s,size:11,sizeAttenuation:!1,depthTest:!1,transparent:!0,opacity:.5}),x=null,O=R=>{if(!R){x&&(x.visible=!1);return}if(!x){let H=new D.BufferGeometry;H.setAttribute("position",new D.Float32BufferAttribute([0,0,0],3)),x=new D.Points(H,b),x.renderOrder=1e3,x.userData.id="measure",x.raycast=()=>{},t.add(x)}x.position.copy(R),x.visible=!0},T=R=>{let H=new D.BufferGeometry;H.setAttribute("position",new D.Float32BufferAttribute([R.x,R.y,R.z],3));let V=new D.Points(H,f);return V.renderOrder=999,V.userData.id="measure",V.raycast=()=>{},t.add(V),V},w=()=>{g.length=0,v.forEach(R=>{R.geometry.dispose(),R.removeFromParent()}),v.length=0,y&&(y.geometry.dispose(),y.material.dispose(),y.removeFromParent(),y=null),h?.remove(),h=null},M=()=>{if(g.length!==2)return;let[R,H]=g,V=new ht;V.setPositions([R.x,R.y,R.z,H.x,H.y,H.z]);let z=new gt({color:s});z.linewidth=2,z.depthTest=!1,y=new Et(V,z),y.renderOrder=998,y.userData.id="measure",y.raycast=()=>{},t.add(y);let X=R.clone().add(H).multiplyScalar(.5),q=new D.Vector3(Math.abs(H.x-R.x),Math.abs(H.y-R.y),Math.abs(H.z-R.z));h=o.addLabel(u(R.distanceTo(H),q),X,a.labelClassName)},P=R=>{let H=n.getBoundingClientRect();m.x=(R.clientX-H.left)/H.width*2-1,m.y=-((R.clientY-H.top)/H.height)*2+1;let V=r();d.setFromCamera(m,V);let X=V.position.length()*Tt;d.params.Line.threshold=X,d.params.Points.threshold=X;let q=d.intersectObjects(t.children,!0).filter(Z=>Z.object.userData.id!=="measure"&&Z.object.userData.id!=="grid");return q.length===0?null:Ht(q[0],V,{width:H.width,height:H.height},i)};return{setEnabled:R=>{p=R,R||(w(),O(null))},isEnabled:()=>p,handleClick:R=>{if(!p)return!1;g.length===2&&w();let H=P(R);return H===null||(g.push(H),v.push(T(H)),g.length===2&&M()),!0},handleMove:R=>{p&&O(P(R))},clear:w,dispose:()=>{w(),x&&(x.geometry.dispose(),x.removeFromParent(),x=null),f.dispose(),b.dispose()}}}import*as E from"three";import{OrbitControls as vt}from"three/addons/controls/OrbitControls.js";import{HDRLoader as xt}from"three/addons/loaders/HDRLoader.js";var ne=new E.Vector3(0,0,1);function Mt(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 Dn=function(e,n){let t=Ct(n||{}),r=t.environment?.sceneUp||ne,o=Lt(t),a=Ft(t,e);a.up.copy(r);let i=Ut(e,t),s=_t(a,e,t),l=ge({scene:o,perspective:a,controls:s,onActiveCameraChange:()=>{},up:r}),c=()=>l.getActiveCamera(),u=!1;It(o,t,()=>u);let d=Vt(o,t),m=()=>{d&&Dt(d,ce(o))};t.floor?.enabled&&Bt(o,t);let p=t.grid.enabled?ye({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;p&&o.add(p.object);let g=t.gizmo.enabled?be({camera:a,domElement:e,controller:l}):null,v=e.parentElement??e,y=t.measure.enabled?ve(v,o):null,h=t.measure.enabled&&y?Me({canvas:e,scene:o,getActiveCamera:c,labelLayer:y,options:{snapPixels:t.measure.snapPixels,color:t.measure.color,labelClassName:t.measure.labelClassName,displayUnit:t.measure.displayUnit,format:t.measure.format}}):null,f=t.events.enableEventHandlers!==!1?zt(e,o,c,a,s,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},b=5,x=0,O=0,T=A=>{x=A.clientX,O=A.clientY},w=A=>Math.hypot(A.clientX-x,A.clientY-O)>b,M=A=>{if(!w(A)){if(h?.handleClick(A)){A.stopImmediatePropagation();return}g?.handleClick(A)&&A.stopImmediatePropagation()}};(g||h)&&(e.addEventListener("mousedown",T,{capture:!0}),e.addEventListener("click",M,{capture:!0}));let P=A=>h?.handleMove(A);h&&e.addEventListener("mousemove",P,{passive:!0});let S=A=>{Re(A,{color:t.edges.color,width:t.edges.width,thresholdAngle:t.edges.thresholdAngle})},I=e.parentElement,R=()=>I?{width:I.clientWidth,height:I.clientHeight}:{width:window.innerWidth,height:window.innerHeight},H=null,V=()=>{let{width:A,height:U}=R(),W=Math.min(window.devicePixelRatio,2),te=we(i,o,c(),Math.max(1,A),Math.max(1,U),{toneMapping:t.render.toneMapping??E.NeutralToneMapping,toneMappingExposure:t.render.toneMappingExposure??1,aoIntensity:t.render.aoIntensity});return te.setSize(Math.max(1,A),Math.max(1,U),W),te},z=A=>{A&&!H?H=V():!A&&H&&(H.dispose(),H=null)};t.render.ambientOcclusion&&(H=V());let{animate:X,dispose:q}=Ot(i,o,a,c,l,s,R,t.events.onFrame,p,g,()=>H,y);X(),o.up.set(r.x,r.y,r.z),m();let Z=A=>{A.traverse(U=>{let W=U;!W.geometry&&!W.material||(W.geometry?.dispose(),Array.isArray(W.material)?W.material.forEach(te=>te.dispose()):W.material?.dispose())})},_e=A=>{A.userData.source="user",o.add(A)},ke=A=>{A.removeFromParent(),Z(A)},je=()=>{o.children.filter(U=>U.userData.source==="user").forEach(U=>{U.removeFromParent(),Z(U)})};return{scene:o,camera:a,controls:s,renderer:i,cameraController:l,grid:p,gizmo:g,measureTool:h,applyEdges:S,setAmbientOcclusion:z,updateShadowBounds:m,dispose:()=>{u=!0,q(),f.dispose(),(g||h)&&(e.removeEventListener("mousedown",T,{capture:!0}),e.removeEventListener("click",M,{capture:!0})),h&&e.removeEventListener("mousemove",P),h?.dispose(),y?.dispose(),g?.dispose(),p?.dispose(),H?.dispose(),s.dispose(),i.dispose(),i.forceContextLoss(),o.traverse(A=>{let U=A;!U.geometry&&!U.material||(U.geometry?.dispose(),Array.isArray(U.material)?U.material.forEach(W=>W.dispose()):U.material?.dispose())}),o.environment?.dispose(),o.background instanceof E.Texture&&o.background.dispose()},fitToView:f.fitToView,clearSelection:f.clearSelection,addUserGeometry:_e,removeUserGeometry:ke,clearUserGeometry:je}};function Ct(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];return{sceneScale:n,camera:{position:e.camera?.position||new E.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 E.Vector3(0,0,0)},lighting:{enableSunlight:e.lighting?.enableSunlight??!0,sunlightIntensity:e.lighting?.sunlightIntensity??1,sunlightPosition:e.lighting?.sunlightPosition||new E.Vector3(r.lightDistance,r.lightDistance,r.lightHeight),ambientLightColor:e.lighting?.ambientLightColor||new E.Color(4210752),ambientLightIntensity:e.lighting?.ambientLightIntensity??1,sunlightColor:e.lighting?.sunlightColor||16777215},environment:{hdrPath:e.environment?.hdrPath||"/baseHDR.hdr",backgroundColor:e.environment?.backgroundColor||new E.Color(15790320),enableEnvironmentLighting:e.environment?.enableEnvironmentLighting??!0,sceneUp:e.environment?.sceneUp||ne,showEnvironment:e.environment?.showEnvironment??!1},floor:{enabled:e.floor?.enabled??!1,size:e.floor?.size||r.floorSize,color:e.floor?.color||new E.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||E.NeutralToneMapping,toneMappingExposure:e.render?.toneMappingExposure??1,preserveDrawingBuffer:e.render?.preserveDrawingBuffer??!1,ambientOcclusion:e.render?.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??!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??Mt(e.environment?.sceneUp??ne)},gizmo:{enabled:e.gizmo?.enabled??!1},edges:{enabled:e.edges?.enabled??!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}}}var At=new Set(["grid","floor","label-layer","measure"]);function St(e){let n=e;for(;n;){if(typeof n.userData.id=="string"&&At.has(n.userData.id))return!0;n=n.parent}return!1}function ce(e){let n=new E.Box3;return e.traverse(t=>{let r=t;t.visible&&!St(t)&&r.geometry&&n.expandByObject(t)}),n}function Dt(e,n){if(n.isEmpty())return;let t=n.getCenter(new E.Vector3),r=n.getSize(new E.Vector3).length()*.5*1.2,o=e.shadow.camera;o.left=-r,o.right=r,o.top=r,o.bottom=-r,e.target.position.copy(t),e.target.updateMatrixWorld();let a=e.position.distanceTo(t);o.near=Math.max(r*.01,a-r),o.far=a+r,o.updateProjectionMatrix()}function Lt(e){let n=new E.Scene,t=typeof e.environment.backgroundColor=="string"?new E.Color(e.environment.backgroundColor):e.environment.backgroundColor;return n.background=t||null,n}function Pt(e,n,t,r,o=200){let a=e.position.clone(),i=n.target.clone(),s=performance.now(),l=u=>1-Math.pow(1-u,3),c=()=>{let u=performance.now()-s,d=l(Math.min(u/o,1));e.position.lerpVectors(a,t,d),n.target.lerpVectors(i,r,d),n.update(),d<1&&requestAnimationFrame(c)};requestAnimationFrame(c)}function Ot(e,n,t,r,o,a,i,s,l,c,u,d){let m=null,p=performance.now(),g=()=>{let{width:h,height:f}=i();if(h===0||f===0)return;let b=Math.min(window.devicePixelRatio,2),x=Math.round(h*b),O=Math.round(f*b);(e.domElement.width!==x||e.domElement.height!==O)&&(e.setPixelRatio(b),e.setSize(h,f,!1),t.aspect=h/f,t.updateProjectionMatrix(),o.updateAspect(h,f),u?.()?.setSize(h,f,b),d?.setSize(h,f))},v=function(){m=requestAnimationFrame(v);let h=performance.now(),f=(h-p)/1e3;p=h,g(),(a.enableDamping||a.autoRotate)&&a.update(),l&&l.update(r().position),c&&c.update(f),s?.(f);let b=r(),x=u?.();x?(x.setCamera(b),x.render(f)):e.render(n,b),d&&d.render(n,b),c&&c.render(e)};return{animate:v,dispose:()=>{m!==null&&(cancelAnimationFrame(m),m=null)}}}function It(e,n,t){n.environment.enableEnvironmentLighting?new xt().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."),n.events.onReady?.();return}r.mapping=E.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 Vt(e,n){let t=new E.AmbientLight(n.lighting.ambientLightColor,n.lighting.ambientLightIntensity);if(e.add(t),!n.lighting.enableSunlight)return null;let r=new E.DirectionalLight(n.lighting.sunlightColor??16777215,n.lighting.sunlightIntensity),o=n.lighting.sunlightPosition;return o&&r.position.set(o.x,o.y,o.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 Bt(e,n){let t=n.floor.size,r=new E.PlaneGeometry(t,t),o=typeof n.floor.color=="string"?new E.Color(n.floor.color):n.floor.color,a=new E.MeshStandardMaterial({color:o,roughness:n.floor.roughness,metalness:n.floor.metalness,side:E.DoubleSide}),i=new E.Mesh(r,a);i.userData.id="floor",i.name="floor";let s=(n.environment?.sceneUp||ne).clone().normalize();i.quaternion.setFromUnitVectors(new E.Vector3(0,0,1),s),i.position.set(0,0,0),n.floor.receiveShadow&&n.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function Ft(e,n){let t=n.parentElement,r=t?t.clientWidth:window.innerWidth,o=t?t.clientHeight:window.innerHeight,a=new E.PerspectiveCamera(e.camera.fov,r/o,e.camera.near,e.camera.far),i=e.camera.position;return i&&a.position.set(i.x,i.y,i.z),a}function Ut(e,n){let t=new E.WebGLRenderer({antialias:n.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:n.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),r=e.parentElement,o=r?r.clientWidth:window.innerWidth,a=r?r.clientHeight:window.innerHeight;return r&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),t.setSize(o,a,!1),t.setPixelRatio(n.render.pixelRatio||Math.min(window.devicePixelRatio,2)),n.render.enableShadows&&(t.shadowMap.enabled=!0,t.shadowMap.type=E.VSMShadowMap),t.toneMapping=n.render.toneMapping,t.toneMappingExposure=n.render.toneMappingExposure??1,t.outputColorSpace=E.SRGBColorSpace,t.sortObjects=!0,t}function zt(e,n,t,r,o,a){let i=new Set,s=new Map,l=new E.Raycaster,c=new E.Vector2,u=new E.Vector2,d=T=>{let w=T;for(;w;){if(!w.visible)return!1;w=w.parent}return!0},m=()=>{let T=ce(n);if(T.isEmpty()){C().warn("No objects to fit to view");return}let w=T.getCenter(new E.Vector3),M=T.getSize(new E.Vector3),P=Math.max(M.x,M.y,M.z),S=r.fov*(Math.PI/180),I=P/(2*Math.tan(S/2));I*=1.5;let R=r.position.clone().sub(o.target);R.lengthSq()<1e-12&&R.set(.8,1,1.2),R.normalize(),r.position.copy(w.clone().add(R.multiplyScalar(I))),o.target.copy(w),o.update()},p=typeof a.events.selectionColor=="string"?new E.Color(a.events.selectionColor):a.events.selectionColor instanceof E.Color?a.events.selectionColor:new E.Color("#ff0000"),g=()=>{i.forEach(T=>{let w=T;if(s.has(T)){let M=s.get(T),P=w.material;P instanceof E.Material?P.dispose():Array.isArray(P)&&P.forEach(I=>I.dispose()),w.material=M,s.delete(T);let S=T;for(;S.parent;)S=S.parent;S!==n&&(M instanceof E.Material?M.dispose():M.forEach(I=>I.dispose()))}}),i.clear()},v=T=>{let w=T;if(!(w.material instanceof E.Material))return!1;s.set(T,w.material);let M=w.material.clone();return T instanceof E.Mesh&&"emissive"in M?M.emissive=p.clone():"color"in M&&(M.color=p.clone()),w.material=M,!0},y=()=>{let T=ce(n),w=T.isEmpty()?1:T.getSize(new E.Vector3).length();l.params.Points.threshold=w*.01},h=T=>{u.set(T.clientX,T.clientY)},f=T=>{let w=new E.Vector2(T.clientX,T.clientY);if(u.distanceTo(w)>5)return;let M=e.getBoundingClientRect();c.x=(T.clientX-M.left)/M.width*2-1,c.y=-((T.clientY-M.top)/M.height)*2+1,y(),l.setFromCamera(c,t());let P=l.intersectObjects(n.children,!0).filter(S=>d(S.object));if(P.length>0){let S=P[0].object;i.has(S)||(g(),i.add(S),v(S),a.events?.onObjectSelected?.(S),S instanceof E.Mesh&&Object.keys(S.userData).length>0&&a.events?.onMeshMetadataClicked?.(S.userData))}else g(),a.events?.onBackgroundClicked?.({x:c.x,y:c.y})},b=T=>{let w=e.getBoundingClientRect();c.x=(T.clientX-w.left)/w.width*2-1,c.y=-((T.clientY-w.top)/w.height)*2+1,y(),l.setFromCamera(c,t());let M=l.intersectObjects(n.children,!0).filter(Z=>d(Z.object));if(M.length===0)return;let P=M[0].object;if(a.events?.onMeshDoubleClicked?.(P),!a.events?.enableDoubleClickZoom)return;let S=new E.Box3().setFromObject(P);if(S.isEmpty())return;let I=S.getCenter(new E.Vector3),R=S.getSize(new E.Vector3),H=Math.max(R.x,R.y,R.z),V=r.fov*(Math.PI/180),z=H/(2*Math.tan(V/2))*1.5,X=r.position.clone().sub(o.target).normalize(),q=I.clone().add(X.multiplyScalar(z));Pt(r,o,q,I)},x=T=>{if(a.events?.enableKeyboardControls)switch(T.key.toLowerCase()){case"f":T.preventDefault(),m();break;case"escape":T.preventDefault(),g();break;case" ":T.preventDefault(),m();break}};return a.events?.enableClickToFocus&&(e.addEventListener("mousedown",h),e.addEventListener("click",f),e.addEventListener("dblclick",b)),a.events?.enableKeyboardControls&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",x)),{dispose:()=>{e.removeEventListener("mousedown",h),e.removeEventListener("click",f),e.removeEventListener("dblclick",b),e.removeEventListener("keydown",x),g()},fitToView:m,clearSelection:g}}function _t(e,n,t){let r=new vt(e,n),o=t.camera.target;return o&&r.target.set(o.x,o.y,o.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}var Xt={};Ge(Xt,{CONCRETE_MATERIAL:()=>Gt,EMISSIVE_MATERIAL:()=>kt,GLASS_MATERIAL:()=>Wt,METAL_MATERIAL:()=>jt,PLASTIC_MATERIAL:()=>Nt,RUBBER_MATERIAL:()=>$t,WOOD_MATERIAL:()=>Yt});import*as L from"three";var kt=new L.MeshPhysicalMaterial({color:0,emissive:new L.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:L.FrontSide,dithering:!0}),jt=new L.MeshPhysicalMaterial({color:new L.Color(0),metalness:.9,roughness:.3,envMapIntensity:1.2,clearcoat:.3,clearcoatRoughness:.2,reflectivity:1,ior:2.5,thickness:1,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,side:L.FrontSide,dithering:!0}),Gt=new L.MeshPhysicalMaterial({color:new L.Color(13421772),metalness:0,roughness:.92,envMapIntensity:.15,clearcoat:.05,clearcoatRoughness:.9,reflectivity:.15,transmission:0,ior:1.45,thickness:0,depthWrite:!0,transparent:!1,alphaTest:.5,depthTest:!0,polygonOffset:!0,side:L.FrontSide,dithering:!0}),Nt=new L.MeshPhysicalMaterial({color:new L.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:L.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Wt=new L.MeshPhysicalMaterial({color:new L.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,opacity:.3,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:L.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),$t=new L.MeshPhysicalMaterial({color:new L.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:L.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Yt=new L.MeshPhysicalMaterial({color:new L.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:L.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});import*as N from"three";import{Line2 as qt}from"three/addons/lines/Line2.js";import{LineGeometry as Zt}from"three/addons/lines/LineGeometry.js";import{LineMaterial as Jt}from"three/addons/lines/LineMaterial.js";function oe(e,n,t,r=!0){return{x:e,y:n,z:t}}var Kt="#ffffff",Ce=12,Qt=4e-4,er=12,tr=.05;function Ae(e,n={}){if(!e||e.length===0)return[];let{rhino:t,applyTransforms:r=!0}=n,o=[];for(let a of e)switch(a.kind){case"curve":{let i=nr(a,t,r);i&&o.push(i);break}case"point":{o.push(or(a,r));break}default:{let i=a;C().warn(`Skipping unknown display item kind: ${String(i.kind)}`);break}}return o}var rr=2;function nr(e,n,t){if(!n)return C().warn("No rhino3dm instance provided; skipping curve display item."),null;let r=ar(e.json,n);if(!r)return null;let o;try{o=ir(r,t)}finally{Q(r)}if(o.length<2)return null;let a=[];for(let d of o)a.push(d.x,d.y,d.z);let i=new Zt;i.setPositions(a);let s=Se(e.color,e.opacity),l=new Jt({color:s.color}),c=l;c.linewidth=e.width??rr,c.transparent=s.transparent,c.opacity=s.opacity;let u=new qt(i,l);return u.computeLineDistances(),u.name=e.name,u.userData={source:"compute",id:e.id,layer:e.layer,kind:"curve",metadata:e.metadata},u}function or(e,n){let{x:t,y:r,z:o}=oe(e.position.X,e.position.Y,e.position.Z,n),a=new N.BufferGeometry;a.setAttribute("position",new N.Float32BufferAttribute([t,r,o],3));let i=new N.PointsMaterial({...Se(e.color,e.opacity),size:6,sizeAttenuation:!1}),s=new N.Points(a,i);return s.name=e.name,s.userData={source:"compute",id:e.id,layer:e.layer,kind:"point",metadata:e.metadata},s}function Q(e){e?.delete?.()}function ar(e,n){try{let t=JSON.parse(e),r=n.CommonObject.decode(t);return r&&typeof r.pointAt=="function"?r:(Q(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 ir(e,n){let t=sr(e,n);return t||lr(e,n)}function sr(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 Q(r),null;let o=[];for(let a=0;a<r.count;a++){let i=r.get(a),{x:s,y:l,z:c}=oe(i[0],i[1],i[2],n);o.push(new N.Vector3(s,l,c))}return Q(r),o}function lr(e,n){let t=e.domain,r=t[0],a=t[1]-r,i=d=>{let m=e.pointAt(d),{x:p,y:g,z:v}=oe(m[0],m[1],m[2],n);return new N.Vector3(p,g,v)},s=cr(e),l=r,c=i(r),u=[c];for(let d=0;d<Ce;d++){let m=r+a*(d+1)/Ce,p=i(m);ue(l,c,m,p,i,s,er,u),u.push(p),l=m,c=p}return u}function ue(e,n,t,r,o,a,i,s){if(i<=0)return;let l=(e+t)/2,c=o(l),u=dr(c,n,r),d=ur(n,c,r);u<=a&&d<=tr||(ue(e,n,l,c,o,a,i-1,s),s.push(c),ue(l,c,t,r,o,a,i-1,s))}function cr(e){let n=e.getBoundingBox(),t=n.min,r=n.max;Q(n);let o=Math.hypot(r[0]-t[0],r[1]-t[1],r[2]-t[2]);return Math.max(o*Qt,1e-6)}function ur(e,n,t){let r=n.clone().sub(e),o=t.clone().sub(n),a=r.length(),i=o.length();if(a===0||i===0)return 0;let s=Math.max(-1,Math.min(1,r.dot(o)/(a*i)));return Math.acos(s)}function dr(e,n,t){let r=t.clone().sub(n),o=r.lengthSq();if(o===0)return e.distanceTo(n);let a=Math.max(0,Math.min(1,e.clone().sub(n).dot(r)/o)),i=n.clone().addScaledVector(r,a);return e.distanceTo(i)}function Se(e,n){let t=n??1;return{color:new N.Color(e??Kt),transparent:t<1,opacity:t}}import{inflateSync as mr}from"fflate";var De=1096174675,fr=1515605075,Le=3,Pe=1,me=1,pr=2,Er=4,hr=8,gr=16;var yr=1,Oe=12,Ie=56;function fe(e){let n=wr(Rr(e)),t=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n.byteLength<Oe)throw j("Blob too small to contain SLVA header.",{expectedBytes:Oe,availableBytes:n.byteLength});let r=0,o=t.getUint32(r,!0);if(r+=4,o!==De)throw j(`Invalid SLVA magic: 0x${o.toString(16)}`,{expectedMagic:`0x${De.toString(16)}`,actualMagic:`0x${o.toString(16)}`});let a=t.getUint32(r,!0);if(r+=4,a<Pe||a>Le)throw j(`Unsupported SLVA version: ${a}`,{minSupportedVersion:Pe,maxSupportedVersion:Le,actualVersion:a});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(Hr(s))}catch(z){throw j(`Failed to parse metadata JSON: ${z instanceof Error?z.message:String(z)}`,{metadataLen:i})}if(r+Ie>n.byteLength)throw j("Insufficient data to read geometry header.",{expectedBytes:Ie,availableBytes:n.byteLength-r,offset:r});let c=t.getUint32(r,!0);r+=4;let u=t.getFloat64(r,!0);r+=8;let d=t.getFloat64(r,!0);r+=8;let m=t.getFloat64(r,!0);r+=8;let p=t.getFloat64(r,!0);r+=8;let g=t.getFloat64(r,!0);r+=8;let v=t.getFloat64(r,!0);r+=8;let y=t.getUint32(r,!0);r+=4;let h=(c&me)!==0,f=(c&Er)!==0,b=y*3,O=b*(h?4:2);if(r+O>n.byteLength)throw j("Insufficient data to read vertices.",{expectedBytes:O,availableBytes:n.byteLength-r,offset:r,useFloat32:h,vertexCount:y});let T=n.byteOffset+r,w;if(h?w=Be(n.buffer,T,b):f?w=Mr(de(n.buffer,T,b)):w=vr(n.buffer,T,b),r+=O,r+4>n.byteLength)throw j("Insufficient data to read index count.",{expectedBytes:4,availableBytes:n.byteLength-r,offset:r});let M=t.getUint32(r,!0);r+=4;let P=(c&pr)!==0,I=M*(P?2:4);if(r+I>n.byteLength)throw j("Insufficient data to read indices.",{expectedBytes:I,availableBytes:n.byteLength-r,offset:r,indexCount:M,useUint16Indices:P});let R=P?de(n.buffer,n.byteOffset+r,M):xr(n.buffer,n.byteOffset+r,M);f&&(R=R instanceof Uint16Array?Cr(R):Ar(R)),r+=I;let H=null;if((c&hr)!==0){let z=br(n,t,r,y,f);H=z.uvs,r=z.offset}let V=null;return(c&gr)!==0&&(V=Tr(n,r,y,f)),{metadata:l,flags:c,vertices:w,indices:R,origin:[u,d,m],scale:[p,g,v],uvs:H,colors:V}}var Ve=36;function br(e,n,t,r,o){if(t+Ve>e.byteLength)throw j("Insufficient data to read UV chunk header.",{expectedBytes:Ve,availableBytes:e.byteLength-t,offset:t});let a=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 u=r*2,d=a===yr,m=u*(d?4:2);if(t+m>e.byteLength)throw j("Insufficient data to read UV chunk.",{expectedBytes:m,availableBytes:e.byteLength-t,offset:t,uvFormat:a,vertexCount:r});let p=e.byteOffset+t,g;if(d)g=Be(e.buffer,p,u).slice();else{let v=de(e.buffer,p,u);g=new Float32Array(u);let y=0,h=0;for(let f=0;f<u;f+=2)o?(y=y+Y(v[f])&65535,h=h+Y(v[f+1])&65535):(y=v[f],h=v[f+1]),g[f]=i+y*l,g[f+1]=s+h*c}return{uvs:g,offset:t+m}}function Tr(e,n,t,r){let o=t*3;if(n+o>e.byteLength)throw j("Insufficient data to read vertex-color chunk.",{expectedBytes:o,availableBytes:e.byteLength-n,offset:n,vertexCount:t});let a=e.subarray(n,n+o);if(!r)return a.slice();let i=new Uint8Array(o),s=0,l=0,c=0;for(let u=0;u<o;u+=3)s=s+Y(a[u])&255,l=l+Y(a[u+1])&255,c=c+Y(a[u+2])&255,i[u]=s,i[u+1]=l,i[u+2]=c;return i}function Rr(e){return typeof e=="string"?pe(e):e instanceof Uint8Array?e:new Uint8Array(e)}function wr(e){if(e.byteLength<8)return e;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint32(0,!0)!==fr)return e;let t=n.getUint32(4,!0),r=e.subarray(8),o=Math.max(r.byteLength*1032+1024,1<<20);if(t>o)throw j("SLVZ header declares an implausible uncompressed length",{uncompressedLen:t,deflatedBytes:r.byteLength,maxPlausibleLen:o});try{return mr(r,{out:new Uint8Array(t)})}catch(a){throw j(`Failed to inflate SLVZ blob: ${a instanceof Error?a.message:String(a)}`,{uncompressedLen:t,deflatedBytes:r.byteLength})}}function Hr(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 le("No UTF-8 decoder available in this environment.",se.INVALID_STATE)}function vr(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 Be(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 de(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 xr(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 Y(e){return e>>>1^-(e&1)}function Mr(e){let n=new Int16Array(e.length),t=0,r=0,o=0;for(let a=0;a<e.length;a+=3)t=t+Y(e[a])<<16>>16,r=r+Y(e[a+1])<<16>>16,o=o+Y(e[a+2])<<16>>16,n[a]=t,n[a+1]=r,n[a+2]=o;return n}function Cr(e){let n=new Uint16Array(e.length),t=0;for(let r=0;r<e.length;r++)t=t+Y(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+Y(e[r])>>>0,n[r]=t;return n}function j(e,n){return new le(e,se.VALIDATION_ERROR,{context:n})}import*as ie from"three";var ae=new Map,ee=new Map;function Fe(e,n){let t=ae.get(n);if(t){e.map=t,e.needsUpdate=!0;return}typeof document>"u"||Sr(n).then(r=>{e.map=r,e.needsUpdate=!0}).catch(r=>{C().warn(`Failed to load material texture ${n}:`,r)})}function Nn(){for(let e of ae.values())e.dispose();ae.clear(),ee.clear()}function Sr(e){let n=ee.get(e);return n||(n=new Promise((t,r)=>{new ie.TextureLoader().load(e,o=>{o.colorSpace=ie.SRGBColorSpace,ae.set(e,o),ee.delete(e),t(o)},void 0,o=>{ee.delete(e),r(o)})}),ee.set(e,n)),n}import*as B from"three";async function Ue(e,n){let{debug:t=!1}=n??{},r=t?performance.now():0;try{let o=performance.now(),a=JSON.parse(e),i=performance.now()-o;return await Dr(a,n,{parseTime:i,perfStart:r})}catch(o){return C().error("Error parsing mesh batch:",o),[]}}async function Dr(e,n,t){let{mergeByMaterial:r=!0,applyTransforms:o=!0,debug:a=!1}=n??{},{parseTime:i=0,perfStart:s=a?performance.now():0}=t??{};try{let l=performance.now(),c=fe(e.compressedData),u=performance.now()-l,d=a?Br(e.compressedData):0;return ze(c,{mergeByMaterial:r,applyTransforms:o,debug:a,parseTime:i,decodeTime:u,perfStart:s,blobBytes:d,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}catch(l){return C().error("Error parsing mesh batch object:",l),[]}}async function Zn(e,n){let{mergeByMaterial:t=!0,applyTransforms:r=!0,debug:o=!1}=n??{},a=o?performance.now():0;try{let i=performance.now(),s=fe(e),l=performance.now()-i,c=e.byteLength;return ze(s,{mergeByMaterial:t,applyTransforms:r,debug:o,parseTime:0,decodeTime:l,perfStart:a,blobBytes:c})}catch(i){return C().error("Error parsing mesh batch blob:",i),[]}}function ze(e,n){let{mergeByMaterial:t,applyTransforms:r,debug:o,parseTime:a,decodeTime:i,perfStart:s,blobBytes:l,fallback:c}=n,u=e.metadata.materials??c?.materials??[],d=e.metadata.groups??c?.groups??[],m=c?.sourceComponentId??e.metadata.sourceComponentId,p=(e.flags&me)!==0,g=p?Pr(e.vertices,r):Lr(e.vertices,e.origin,e.scale,r);if(o){let b=e.vertices.byteLength+e.indices.byteLength;C().debug("Mesh Batch Stats:"),C().debug(` Materials: ${u.length} | Groups: ${d.length}`),C().debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),C().debug(` Format: ${p?"float32":"int16 quantized"}`),C().debug(` Blob: ${(l/1024/1024).toFixed(2)} MB | Geometry on wire: ${(b/1024/1024).toFixed(2)} MB`)}let v=performance.now(),y=u.map(b=>Or(b,{vertexColors:e.colors!=null})),h=[];for(let b of d)if(t&&b.meshes.length>1){let x=Ir(b,g,e.indices,y,e.uvs,e.colors);x.userData.sourceComponentId=m??null,h.push(x)}else{let x=Vr(b,g,e.indices,y,e.uvs,e.colors);for(let O of x)O.userData.sourceComponentId=m??null;h.push(...x)}let f=performance.now()-v;if(o){let b=performance.now()-s;C().debug("Performance:"),a>0&&C().debug(` Parse JSON: ${a.toFixed(2)}ms`),C().debug(` Decode binary: ${i.toFixed(2)}ms`),C().debug(` Create Meshes: ${f.toFixed(2)}ms`),C().debug(` Total: ${b.toFixed(2)}ms`)}return Promise.resolve(h)}function Lr(e,n,t,r){let o=new Float32Array(e.length),a=n[0],i=n[1],s=n[2],l=t[0],c=t[1],u=t[2];for(let d=0;d<e.length;d+=3)o[d]=a+(e[d]+32767)*l,o[d+1]=i+(e[d+1]+32767)*c,o[d+2]=s+(e[d+2]+32767)*u;return o}function Pr(e,n){return e}function Or(e,n){let t=Ee(e.color),r=new B.MeshPhysicalMaterial({color:t,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,vertexColors:n?.vertexColors??!1,side:B.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0});return e.map&&Fe(r,e.map),r}function Ir(e,n,t,r,o=null,a=null){let i=0,s=0;for(let f of e.meshes)i+=f.vertexCount,s+=f.indexCount;let l=new Float32Array(i*3),c=new Uint32Array(s),u=o?new Float32Array(i*2):null,d=a?new Uint8Array(i*3):null,m=0,p=0;for(let f of e.meshes){let b=f.vertexStart*3,x=f.vertexCount*3;if(l.set(n.subarray(b,b+x),m*3),u&&o){let w=f.vertexStart*2;u.set(o.subarray(w,w+f.vertexCount*2),m*2)}d&&a&&d.set(a.subarray(b,b+x),m*3);let O=t.subarray(f.indexStart,f.indexStart+f.indexCount),T=m-f.vertexStart;if(T===0)c.set(O,p);else for(let w=0;w<O.length;w++)c[p+w]=O[w]+T;m+=f.vertexCount,p+=f.indexCount}let g=new B.BufferGeometry;g.setAttribute("position",new B.BufferAttribute(l,3)),g.setIndex(new B.BufferAttribute(c,1)),u&&g.setAttribute("uv",new B.BufferAttribute(u,2)),d&&g.setAttribute("color",new B.BufferAttribute(d,3,!0)),g.computeVertexNormals();let v=new B.Mesh(g,r[e.materialId]),y=e.meshes[0],h=e.meshes.map(f=>f.name).filter(f=>f&&f.length>0);return v.name=h.length>0?h[0]:`merged_material_${e.materialId}`,v.castShadow=!0,v.receiveShadow=!0,v.userData={source:"compute",name:v.name,layer:y?.layer??"",originalIndex:y?.originalIndex??0,metadata:y?.metadata??{},mergedFrom:e.meshes.slice(1).map(f=>({name:f.name,layer:f.layer,originalIndex:f.originalIndex}))},v}function Vr(e,n,t,r,o=null,a=null){let i=[];for(let s of e.meshes){let l=s.vertexStart*3,c=s.vertexCount*3,u=n.slice(l,l+c),d=t.subarray(s.indexStart,s.indexStart+s.indexCount),m=new Uint32Array(d.length),p=s.vertexStart;for(let y=0;y<d.length;y++)m[y]=d[y]-p;let g=new B.BufferGeometry;if(g.setAttribute("position",new B.BufferAttribute(u,3)),g.setIndex(new B.BufferAttribute(m,1)),o){let y=s.vertexStart*2,h=o.slice(y,y+s.vertexCount*2);g.setAttribute("uv",new B.BufferAttribute(h,2))}if(a){let y=a.slice(l,l+c);g.setAttribute("color",new B.BufferAttribute(y,3,!0))}g.computeVertexNormals();let v=new B.Mesh(g,r[e.materialId]);v.name=s.name,v.userData={source:"compute",name:s.name,layer:s.layer??"",originalIndex:s.originalIndex,metadata:s.metadata??{}},v.castShadow=!0,v.receiveShadow=!0,i.push(v)}return i}function Br(e){return Math.floor(e.length*3/4)}var Fr={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},Ur="Display";async function ro(e,n){let t=performance.now(),r=[],{allowScaling:o=!0,allowAutoPosition:a=!0,rhino:i,debug:s=!1,parsing:l={}}=n??{};try{let c=o?zr(e.modelunits):1;return await _r(e,r,c,l,i,s),a&&Nr(r),r}catch(c){throw Wr(c,r),c}finally{s&&Yr(t)}}function zr(e){return Fr[e]??1}async function _r(e,n,t,r,o,a){for(let i of e.values){let s=i.InnerTree;for(let l in s){let c=s[l];c&&await kr(c,n,t,r,o,a)}}}async function kr(e,n,t,r,o,a){for(let i of e){if(!i.type.includes(Ur))continue;let s={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...r},l=await Ue(i.data,s),c=Ae(jr(i.data),{rhino:o,applyTransforms:s.applyTransforms}),u=[...l,...c];if(t!==1)for(let d of u)d.scale.set(t,t,t);n.push(...u),a&&C().debug(`Extracted ${l.length} meshes and ${c.length} items from batch`)}}function jr(e){return(typeof e=="string"?Gr(e):e)?.items}function Gr(e){try{return JSON.parse(e)}catch{return}}function Nr(e){if(e.length===0)return;let n=K(e);he(e,n.min.z,"z")}function Wr(e,n){C().error("An unexpected error occurred:",e),$r(n)}function $r(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 Yr(e){let n=performance.now()-e;C().info("Time to process meshes:",`${n.toFixed(2)}ms`)}export{Zr as a,Ee as b,he as c,K as d,ge as e,ye as f,be as g,re as h,Re as i,lt as j,sn as k,we as l,ve as m,Ht as n,Me as o,Dn as p,Xt as q,Ae as r,De as s,Le as t,me as u,Er as v,hr as w,gr as x,fe as y,Nn as z,Ue as A,Dr as B,Zn as C,Fr as D,ro as E};
|
|
55
|
+
//# sourceMappingURL=chunk-HNG75VAI.js.map
|