selva-compute 1.1.4 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  import{a as $,b as z,c as W,d as q}from"./chunk-WD3ENUAA.js";import{b as ae,c as d,d as c,e as l,f as se,g as oe,h as N,i as f,l as L,m as V,n as j}from"./chunk-MK3M76VN.js";N();se();L();var T=class e{constructor(r){d(this,"config");d(this,"serverStats");d(this,"disposed",!1);this.config=this.normalizeComputeConfig(r),this.serverStats=new j(this.config.serverUrl,this.config.apiKey)}static async create(r){let t=new e(r);if(!await t.serverStats.isServerOnline())throw new l("Rhino Compute server is not online",c.NETWORK_ERROR,{context:{serverUrl:t.config.serverUrl}});return t}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(r){return this.ensureNotDisposed(),P(r,this.config)}async getRawIO(r){return this.ensureNotDisposed(),b(r,this.config)}async solve(r,t){this.ensureNotDisposed();try{if(typeof r=="string"&&!r?.trim())throw new l("Definition URL/content is required",c.INVALID_INPUT,{context:{receivedUrl:r}});if(r instanceof Uint8Array&&r.length===0)throw new l("Definition content is empty",c.INVALID_INPUT);if(!await this.serverStats.isServerOnline())throw new l("Rhino Compute server is not online",c.NETWORK_ERROR,{context:{serverUrl:this.config.serverUrl}});let n=await C(t,r,this.config);if(n&&typeof n=="object"&&"message"in n&&!("fileData"in n))throw new l(n.message||"Computation failed",c.COMPUTATION_ERROR,{context:{definition:typeof r=="string"&&r.length<200?r:"...content...",inputs:t}});return n}catch(n){throw this.config.debug&&f().error("Compute failed:",n),n instanceof l?n:new l(n instanceof Error?n.message:String(n),c.COMPUTATION_ERROR,{context:{definition:typeof r=="string"&&r.length<200?r:"...content...",inputs:t},originalError:n instanceof Error?n:new Error(String(n))})}}async dispose(){this.disposed||(this.disposed=!0,"dispose"in this.serverStats&&typeof this.serverStats.dispose=="function"&&await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new l("GrasshopperClient has been disposed and cannot be used",c.INVALID_STATE)}normalizeComputeConfig(r){if(!r.serverUrl?.trim())throw new l("serverUrl is required",c.INVALID_CONFIG,{context:{receivedServerUrl:r.serverUrl}});try{new URL(r.serverUrl)}catch{throw new l("serverUrl must be a valid URL",c.INVALID_CONFIG,{context:{receivedServerUrl:r.serverUrl}})}if(r.serverUrl===""||r.serverUrl==="https://compute.rhino3d.com/")throw new l("serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.",c.INVALID_CONFIG,{context:{receivedServerUrl:r.serverUrl}});return{...r,serverUrl:r.serverUrl.replace(/\/+$/,""),apiKey:r.apiKey,authToken:r.authToken,debug:r.debug??!1,suppressClientSideWarning:r.suppressClientSideWarning}}};var B=async(e,r=null)=>{try{return await K(e,r)}catch(t){throw new l("Failed to extract files from compute response",c.INVALID_STATE,{context:{originalError:t instanceof Error?t.message:String(t)},originalError:t instanceof Error?t:void 0})}},S=async(e,r,t=null)=>{if(typeof document>"u"||typeof Blob>"u")throw new l("File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).",c.BROWSER_ONLY,{context:{environment:typeof window<"u"?"browser (SSR)":"Node.js",documentAvailable:typeof document<"u",blobAvailable:typeof Blob<"u"}});try{let n=await K(e,t);await ie(n,r)}catch(n){throw n instanceof l?n:new l("Failed to download files from compute response",c.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}},K=async(e,r)=>{let t=[];if(e.forEach(n=>{let a=`${n.fileName}${n.fileType}`;if(n.subFolder&&n.subFolder.trim()!==""&&(a=`${n.subFolder}/${a}`),n.isBase64Encoded===!0&&n.data){let s=W(n.data);t.push({fileName:`${n.fileName}${n.fileType}`,content:new Uint8Array(s.buffer),path:a})}else n.isBase64Encoded===!1&&n.data&&t.push({fileName:`${n.fileName}${n.fileType}`,content:n.data,path:a})}),r){let n=Array.isArray(r)?r:[r],a=await Promise.all(n.map(async s=>{try{let o=await fetch(s.filePath);if(!o.ok)return f().warn(`Failed to fetch additional file from URL: ${s.filePath}`),null;let u=await(await o.blob()).arrayBuffer();return{fileName:s.fileName,content:new Uint8Array(u),path:s.fileName}}catch(o){return f().error(`Error fetching additional file from URL: ${s.filePath}`,o),null}}));t.push(...a.filter(s=>s!==null))}return t};async function ie(e,r){let{zipSync:t,strToU8:n}=await import("fflate"),a={};e.forEach(i=>{a[i.path]=typeof i.content=="string"?n(i.content):i.content});let s=t(a,{level:6}),o=new Blob([s],{type:"application/zip"});ue(o,`${r}.zip`)}function ue(e,r){if(typeof document>"u")throw new l("saveFile requires a browser environment with DOM API access.",c.BROWSER_ONLY,{context:{function:"saveFile",requiredAPI:"document"}});let t=document.createElement("a");t.href=URL.createObjectURL(e),t.download=r,t.click(),URL.revokeObjectURL(t.href)}var F=new Map;function Y(e,r){F.set(e,r)}Y("Rhino.Geometry.Point3d",(e,r)=>{let t=r;return!t||typeof t.X!="number"?null:new e.Point([t.X,t.Y,t.Z])});Y("Rhino.Geometry.Line",(e,r)=>{let t=r;return!t||!t.From||!t.To?null:new e.Line([t.From.X,t.From.Y,t.From.Z],[t.To.X,t.To.Y,t.To.Z])});function le(e){if(F.has(e))return F.get(e);for(let[r,t]of F)if(e.startsWith(r))return t}function pe(e){return!e||typeof e!="object"?null:e.data??e.value??null}function J(e,r,t){let n=le(r);if(n)try{return n(t,e)}catch(a){f().warn(`Failed to decode Rhino type ${r}:`,a)}try{let a=pe(e);if(a)return t.CommonObject.decode(a)}catch(a){return f().warn(`Failed to decode ${r} with CommonObject:`,a),{__decodeError:!0,type:r,raw:e}}return e}var D={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},fe="Rhino.Geometry.",ce=["WebDisplay"],me="FileData";function de(e){return ce.some(r=>e.includes(r))}function X(e){if(typeof e!="string")return e;let r=e.trim();if(!(r.startsWith("{")||r.startsWith("[")||r.startsWith('"')))return e;try{let n=JSON.parse(r);if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}catch{return e}}function ye(e,r,t){switch(r){case D.STRING:return typeof e!="string"?e:e.replace(/^"(.*)"$/,"$1");case D.INT:return Number.parseInt(e,10);case D.DOUBLE:return Number.parseFloat(e);case D.BOOL:return String(e).toLowerCase()==="true";default:return t&&r.startsWith(fe)?J(e,r,t):e}}function _(e,r,t,n){if(de(r))return null;if(typeof e!="string")return e;let a=t?X(e):e;return ye(a,r,n)}function w(e,r){for(let t of Object.values(e))if(Array.isArray(t))for(let n of t)r(n)}function Z(e,r=!1,t={}){let{parseValues:n=!0,rhino:a,stringOnly:s=!1}=t,o={};for(let i of e.values)w(i.InnerTree,u=>{if(s&&u.type!==D.STRING)return;let p=r?u.id:i.ParamName;if(!p)return;let m=_(u.data,u.type,n,a);o[p]===void 0?o[p]=m:Array.isArray(o[p])?o[p].push(m):o[p]=[o[p],m]});return{values:o}}function H(e){let r=[];for(let t of e.values)w(t.InnerTree,n=>{if(!n.type.includes(me))return;let a=X(n.data);a&&a.FileName&&a.FileType&&a.Data&&r.push(a)});return r}function U(e,r,t={}){let{parseValues:n=!0,rhino:a,stringOnly:s=!1}=t,o;if("byName"in r?o=e.values.find(u=>u.ParamName===r.byName):o=e.values.find(u=>{let p=!1;return w(u.InnerTree,m=>{m.id===r.byId&&(p=!0)}),p}),!o)return;let i=[];if(w(o.InnerTree,u=>{if("byId"in r&&u.id!==r.byId||s&&u.type!==D.STRING)return;let p=_(u.data,u.type,n,a);i.push(p)}),i.length!==0)return i.length===1?i[0]:i}var I=class{constructor(r,t=!1){this.response=r;this.debug=t}getValues(r=!1,t={}){return Z(this.response,r,t)}getValueByParamName(r,t){return U(this.response,{byName:r},t)}getValueByParamId(r,t){return U(this.response,{byId:r},t)}async extractMeshesFromResponse(r){let t={debug:this.debug,...r};try{let{getThreeMeshesFromComputeResponse:n}=await import("./visualization.js");return n(this.response,t)}catch(n){let{RhinoComputeError:a,ErrorCodes:s}=(N(),ae(oe));throw new a("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",s.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)}})}}getFileData(){return H(this.response)}getAndDownloadFiles(r,t){let n=this.getFileData();S(n,r,t)}};L();function A(e,r){r||typeof window<"u"&&f().warn(`Warning: ${e} is running on the client side. For better performance and security, consider running this on the server side.`)}async function C(e,r,t){t.debug&&A("solveGrasshopperDefinition",t.suppressClientSideWarning);let n=M(r,e);he(n,t);let a=await V("grasshopper",n,t);return"pointer"in a&&delete a.pointer,a}function M(e,r){let t={algo:null,pointer:null,values:r};return e instanceof Uint8Array?t.algo=q(e):e.startsWith("http")?t.pointer=e:z(e)?t.algo=e:t.algo=$(e),t}function he(e,r){r.cachesolve!==null&&(e.cachesolve=r.cachesolve),r.modelunits!==null&&(e.modelunits=r.modelunits),r.angletolerance!==null&&(e.angletolerance=r.angletolerance),r.absolutetolerance!==null&&(e.absolutetolerance=r.absolutetolerance),r.dataversion!==null&&(e.dataversion=r.dataversion)}function ge(e,r={}){let{preserveSpaces:t=!1}=r,n=e.trim();return t?(n=n.charAt(0).toLowerCase()+n.slice(1).replace(/[-_](.)/g,(a,s)=>s?s.toUpperCase():""),n):(n=n.replace(/^[A-Z]/,a=>a.toLowerCase()).replace(/[\s-_]+(.)?/g,(a,s)=>s?s.toUpperCase():""),n)}function G(e,r={}){return!e||typeof e!="object"?e:Array.isArray(e)?r.deep?e.map(t=>G(t,r)):e:Object.keys(e).reduce((t,n)=>{let a=ge(n,{preserveSpaces:r.preserveSpaces}),s=e[n];return t[a]=r.deep?G(s,r):s,t},{})}N();function Q(e){if(typeof e.default!="object"||e.default===null)return;if(!("innerTree"in e.default)){f().warn("Unexpected structure in input.default:",e.default),e.default=null;return}let r=e.default.innerTree;if(Object.keys(r).length===0){e.default=void 0;return}if(e.treeAccess||e.atMost&&e.atMost>1){let n={};for(let[a,s]of Object.entries(r))n[a]=s.map(o=>{if(typeof o.data=="string"){if(o.type==="System.Double"||o.type==="System.Int32"){let i=Number(o.data);return Number.isNaN(i)?o.data:i}if(o.type==="System.Boolean")return o.data.toLowerCase()==="true";if(o.type.startsWith("Rhino.Geometry")||o.type==="System.String")try{return JSON.parse(o.data)}catch{return o.data}}return o.data});e.default=n;return}let t=[];for(let n of Object.values(r))Array.isArray(n)&&n.forEach(a=>{a&&typeof a=="object"&&"data"in a&&t.push(a.data)});t.length===0?e.default=void 0:t.length===1?e.default=t[0]:e.default=t}N();function R(e,r){let{transform:t,setUndefinedOnEmpty:n=!0}=r;if(!(e.default===void 0||e.default===null))if(Array.isArray(e.default)){let a=e.default.map(t).filter(s=>s!==null);e.default=a.length>0?a:void 0}else{let a=t(e.default);a!==null?e.default=a:n&&(e.default=void 0)}}function Te(){return e=>{if(typeof e=="number")return e;if(typeof e=="string"){let r=Number(e.trim());return Number.isNaN(r)?null:r}return null}}function be(){return e=>{if(typeof e=="boolean")return e;if(typeof e=="string"){let r=e.toLowerCase();if(r==="true")return!0;if(r==="false")return!1;throw new Error(`Invalid boolean string: "${e}"`)}return null}}function De(){return e=>typeof e=="string"?e.startsWith('"')&&e.endsWith('"')||e.startsWith('"')?e.slice(1,-1):e:null}function Ie(){return e=>{if(typeof e=="string"){let r=e.trim();return r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1).trim()),r}return null}}function xe(e){R(e,{transform:Ie(),setUndefinedOnEmpty:!1})}function Ce(e="unknown"){return r=>{if(typeof r=="object"&&r!==null)return r;if(typeof r=="string"&&r.trim()!=="")try{let t=JSON.parse(r);return typeof t=="object"&&t!==null?t:(f().warn(`Parsed value for input ${e} is not an object`),null)}catch(t){return f().warn(`Failed to parse object value "${r}" for input ${e}`,t),null}return null}}function ee(e,r,t){let n=Number(e.toFixed(r));return Math.abs(e-n)<t?n:e}function Pe(e,r=1e-8){if(!Number.isFinite(e)||e===0)return .1;let t=Math.abs(e);if(t>=1){let y=String(e).split(".")[1];if(y&&y.length>0){let h=Math.min(y.length,12),g=Math.pow(10,-h),k=Number(g.toFixed(h));return Math.abs(k-g)<r?k:g}return 1}let n=String(e),a=n.toLowerCase().match(/e(-?\d+)/);if(a){let E=Number(a[1]);if(E<0||n.toLowerCase().includes("e-")){let y=Math.abs(E),h=Math.pow(10,-y),g=Number(h.toFixed(y));return Math.abs(g-h)<r?g:h}return .1}let s=12,i=t.toFixed(s).replace(/0+$/,""),u=Math.min((i.split(".")[1]||"").length,s);if(u===0)return .1;let p=Math.pow(10,-u),m=Number(p.toFixed(u));return Math.abs(m-p)<r?m:p}function re(e,r=1e-8){let t=e.paramType==="Integer";if(R(e,{transform:Te()}),t){Array.isArray(e.default)?e.default=e.default.map(s=>typeof s=="number"?Math.round(s):s):typeof e.default=="number"&&(e.default=Math.round(e.default)),e.stepSize=1;return}let n=Array.isArray(e.default)?e.default[0]:e.default,a;if(typeof n=="number"&&Number.isFinite(n)&&n!==0?a=n:typeof e.minimum=="number"&&Number.isFinite(e.minimum)&&e.minimum!==0?a=e.minimum:typeof e.maximum=="number"&&Number.isFinite(e.maximum)&&e.maximum!==0&&(a=e.maximum),a!==void 0?e.stepSize=Pe(a,r):e.stepSize=.1,typeof e.stepSize=="number"){let s=0,o=String(e.stepSize),i=o.toLowerCase().match(/e(-?\d+)/);if(i?s=Math.abs(Number(i[1])):s=o.split(".")[1]?.length??0,s===0&&typeof n=="number"&&n!==0&&Math.abs(n)<1){let u=Math.ceil(-Math.log10(Math.abs(n)));Number.isFinite(u)&&u>0&&(s=u)}s=Math.min(Math.max(s,0),12),Array.isArray(e.default)?e.default=e.default.map(u=>typeof u=="number"?ee(u,s,r):u):typeof e.default=="number"&&(e.default=ee(e.default,s,r))}}function Se(e){try{R(e,{transform:be(),setUndefinedOnEmpty:!1})}catch(r){throw r instanceof Error?new l(r.message):r}}function Re(e){R(e,{transform:De(),setUndefinedOnEmpty:!1})}function te(e){R(e,{transform:Ce(e.nickname||"unnamed"),setUndefinedOnEmpty:!0})}function ve(e){if(!e.values||typeof e.values!="object"||Object.keys(e.values).length===0)throw l.missingValues(e.nickname||"unnamed","ValueList");if(e.default!==void 0&&e.default!==null){let r=String(e.default).toLowerCase();Object.keys(e.values).some(n=>n.toLowerCase()===r)||f().warn(`ValueList input "${e.nickname||"unnamed"}" default value "${e.default}" is not in available values`)}}var ne={Number:re,Integer:re,Boolean:Se,Text:Re,ValueList:ve,Geometry:te,File:te,Color:xe};L();function Oe(e,r){switch(e.paramType){case"Number":case"Integer":return{...r,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,default:e.atMost>1?[0]:0};case"Boolean":return{...r,paramType:"Boolean",default:e.atMost>1?[!1]:!1};case"Text":return{...r,paramType:"Text",default:e.atMost>1?[""]:""};case"ValueList":return{...r,paramType:"ValueList",values:e.values??{},default:e.atMost>1?[e.default]:e.default};case"File":return{...r,paramType:"File",default:e.atMost>1?[null]:null};case"Color":return{...r,paramType:"Color",default:e.atMost>1?["0, 0, 0"]:"0, 0, 0"};default:return{...r,paramType:"Geometry",default:e.atMost>1?[null]:null}}}function v(e){let r={description:e.description,name:e.name,nickname:e.nickname,treeAccess:e.treeAccess,groupName:e.groupName??"",id:e.id};try{Q(e);let t=ne[e.paramType];if(!t)throw l.unknownParamType(e.paramType,e.name);switch(t(e),e.paramType){case"Number":case"Integer":return{...r,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:e.stepSize,default:e.default};case"Boolean":return{...r,paramType:"Boolean",default:e.default};case"Text":return{...r,paramType:"Text",default:e.default};case"ValueList":return{...r,paramType:"ValueList",values:e.values,default:e.default};case"Geometry":return{...r,paramType:e.paramType,default:e.default};case"File":return{...r,paramType:e.paramType,acceptedFormats:e.acceptedFormats,default:e.default};case"Color":return{...r,paramType:"Color",default:e.default};default:throw l.unknownParamType(e.paramType,e.name)}}catch(t){if(t instanceof l)return f().error(`Validation error for input ${e.name||"unknown"}:`,t.message),Oe(e,r);throw new l(t instanceof Error?t.message:String(t),"VALIDATION_ERROR",{context:{paramName:e.name,paramType:e.paramType},originalError:t instanceof Error?t:new Error(String(t))})}}function x(e){return e.map(r=>v(r))}async function b(e,r){let t=M(e,[]),n={};t.algo&&(n.algo=t.algo),t.pointer&&(n.pointer=t.pointer);let a=await V("io",n,r);if(!a||typeof a!="object")throw new l("Invalid IO response structure",c.INVALID_INPUT,{context:{response:a,definition:e}});let s=G(a,{deep:!0});return{inputs:s.inputs,outputs:s.outputs}}async function P(e,r){A("fetchParsedDefinitionIO",r.suppressClientSideWarning);let{inputs:t,outputs:n}=await b(e,r);return{inputs:x(t),outputs:n}}var O=class e{constructor(r){d(this,"innerTree");d(this,"paramName");this.paramName=r,this.innerTree={}}append(r,t){let n=e.formatPathString(r);this.innerTree[n]||(this.innerTree[n]=[]);let a=t.map(s=>({data:e.serializeValue(s)}));return this.innerTree[n].push(...a),this}appendSingle(r,t){return this.append(r,[t])}fromDataTreeDefault(r){this.innerTree={};for(let[t,n]of Object.entries(r)){if(!Array.isArray(n))continue;let a=e.parsePathString(t);this.append(a,n)}return this}appendFlat(r){let t=Array.isArray(r)?r:[r];return this.append([0],t)}flatten(){let r=[];for(let t of Object.values(this.innerTree))if(Array.isArray(t))for(let n of t)r.push(e.deserializeValue(n.data));return r}getPaths(){return Object.keys(this.innerTree)}getPath(r){let t=e.formatPathString(r),n=this.innerTree[t];if(n)return n.map(a=>e.deserializeValue(a.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(r){return r.filter(t=>e.hasValidValue(t.default)).map(t=>{let n=new e(t.nickname||"unnamed"),a=t.default;if(t.treeAccess&&e.isDataTreeStructure(a))n.fromDataTreeDefault(a),e.isNumericInput(t)&&n.applyNumericConstraints(t.minimum,t.maximum,t.nickname||"unnamed");else{let s=Array.isArray(a)?a:[a],o=e.processValues(s,t);n.appendFlat(o)}return n.toComputeFormat()})}static fromInputParam(r){return e.hasValidValue(r.default)?e.fromInputParams([r])[0]:void 0}static replaceTreeValue(r,t,n){if(r.length>0&&r[0]instanceof e){let s=r,o=s.findIndex(u=>u.getParamName()===t),i=new e(t);return typeof n=="object"&&n!==null&&!Array.isArray(n)&&e.isDataTreeStructure(n)?i.fromDataTreeDefault(n):(Array.isArray(n),i.appendFlat(n)),o!==-1?s[o]=i:s.push(i),s}else{let s=r,o=s.findIndex(p=>p.ParamName===t),i=new e(t);typeof n=="object"&&n!==null&&!Array.isArray(n)&&e.isDataTreeStructure(n)?i.fromDataTreeDefault(n):(Array.isArray(n),i.appendFlat(n));let u=i.toComputeFormat();return o!==-1?s[o]=u:s.push(u),s}}static getTreeValue(r,t){if(r.length>0&&r[0]instanceof e){let s=r.find(i=>i.getParamName()===t);if(!s)return null;let o=s.flatten();return o.length===0?null:o.length===1?o[0]:o}else{let s=r.find(p=>p.ParamName===t);if(!s)return null;let o=s.InnerTree;if(!o)return null;let i=Object.keys(o)[0];if(!i)return null;let u=o[i];if(Array.isArray(u)){if(u.length===1){let p=u[0]?.data;return p!==void 0?e.deserializeValue(p):null}return u.map(p=>p?.data!==void 0?e.deserializeValue(p.data):null).filter(p=>p!==null)}return u?.data!==void 0?e.deserializeValue(u.data):u}}static parsePathString(r){let t=r.match(/^\{([\d;]+)\}$/);return t?t[1].split(";").map(Number):(f().warn(`Invalid TreeBuilder path format: ${r}, using [0]`),[0])}static formatPathString(r){return`{${r.join(";")}}`}applyNumericConstraints(r,t,n){for(let a of Object.values(this.innerTree))if(Array.isArray(a))for(let s of a){let o=e.deserializeValue(s.data);if(typeof o=="number"){let i=e.clampValue(o,r,t,n);s.data=e.serializeValue(i)}}}static serializeValue(r){return typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:typeof r=="object"&&r!==null?JSON.stringify(r):String(r)}static deserializeValue(r){if(typeof r=="boolean"||typeof r=="number"||typeof r!="string")return r;if(r.startsWith("{")||r.startsWith("["))try{return JSON.parse(r)}catch{return r}return isNaN(Number(r))?r==="true"?!0:r==="false"?!1:r:Number(r)}static hasValidValue(r){return r==null?!1:typeof r=="string"?!0:!(Array.isArray(r)&&r.length===0||typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0)}static isDataTreeStructure(r){return typeof r!="object"||r===null||Array.isArray(r)?!1:Object.entries(r).every(([t,n])=>typeof t=="string"&&/^\{[\d;]+\}$/.test(t)&&Array.isArray(n))}static isNumericInput(r){return r.paramType==="Number"||r.paramType==="Integer"}static processValues(r,t){return r.map(n=>e.isNumericInput(t)&&typeof n=="number"?e.clampValue(n,t.minimum,t.maximum,t.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(r,t,n,a){let s=r;return t!=null&&s<t&&(f().warn(`${a}: ${r} below min ${t}, clamping`),s=t),n!=null&&s>n&&(f().warn(`${a}: ${r} above max ${n}, clamping`),s=n),s}};export{T as a,B as b,S as c,I as d,C as e,v as f,x as g,b as h,P as i,O as j};
2
- //# sourceMappingURL=chunk-3ECK2JAS.js.map
2
+ //# sourceMappingURL=chunk-3MVIRDAI.js.map
@@ -1,2 +1,2 @@
1
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 _chunkQCHPQ22Ycjs = require('./chunk-QCHPQ22Y.cjs');var _chunkPE2FMBXDcjs = require('./chunk-PE2FMBXD.cjs');_chunkPE2FMBXDcjs.h.call(void 0, );_chunkPE2FMBXDcjs.f.call(void 0, );_chunkPE2FMBXDcjs.l.call(void 0, );var T=class e{constructor(r){_chunkPE2FMBXDcjs.c.call(void 0, this,"config");_chunkPE2FMBXDcjs.c.call(void 0, this,"serverStats");_chunkPE2FMBXDcjs.c.call(void 0, this,"disposed",!1);this.config=this.normalizeComputeConfig(r),this.serverStats=new (0, _chunkPE2FMBXDcjs.n)(this.config.serverUrl,this.config.apiKey)}static async create(r){let t=new e(r);if(!await t.serverStats.isServerOnline())throw new (0, _chunkPE2FMBXDcjs.e)("Rhino Compute server is not online",_chunkPE2FMBXDcjs.d.NETWORK_ERROR,{context:{serverUrl:t.config.serverUrl}});return t}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(r){return this.ensureNotDisposed(),P(r,this.config)}async getRawIO(r){return this.ensureNotDisposed(),b(r,this.config)}async solve(r,t){this.ensureNotDisposed();try{if(typeof r=="string"&&!_optionalChain([r, 'optionalAccess', _2 => _2.trim, 'call', _3 => _3()]))throw new (0, _chunkPE2FMBXDcjs.e)("Definition URL/content is required",_chunkPE2FMBXDcjs.d.INVALID_INPUT,{context:{receivedUrl:r}});if(r instanceof Uint8Array&&r.length===0)throw new (0, _chunkPE2FMBXDcjs.e)("Definition content is empty",_chunkPE2FMBXDcjs.d.INVALID_INPUT);if(!await this.serverStats.isServerOnline())throw new (0, _chunkPE2FMBXDcjs.e)("Rhino Compute server is not online",_chunkPE2FMBXDcjs.d.NETWORK_ERROR,{context:{serverUrl:this.config.serverUrl}});let n=await C(t,r,this.config);if(n&&typeof n=="object"&&"message"in n&&!("fileData"in n))throw new (0, _chunkPE2FMBXDcjs.e)(n.message||"Computation failed",_chunkPE2FMBXDcjs.d.COMPUTATION_ERROR,{context:{definition:typeof r=="string"&&r.length<200?r:"...content...",inputs:t}});return n}catch(n){throw this.config.debug&&_chunkPE2FMBXDcjs.i.call(void 0, ).error("Compute failed:",n),n instanceof _chunkPE2FMBXDcjs.e?n:new (0, _chunkPE2FMBXDcjs.e)(n instanceof Error?n.message:String(n),_chunkPE2FMBXDcjs.d.COMPUTATION_ERROR,{context:{definition:typeof r=="string"&&r.length<200?r:"...content...",inputs:t},originalError:n instanceof Error?n:new Error(String(n))})}}async dispose(){this.disposed||(this.disposed=!0,"dispose"in this.serverStats&&typeof this.serverStats.dispose=="function"&&await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new (0, _chunkPE2FMBXDcjs.e)("GrasshopperClient has been disposed and cannot be used",_chunkPE2FMBXDcjs.d.INVALID_STATE)}normalizeComputeConfig(r){if(!_optionalChain([r, 'access', _4 => _4.serverUrl, 'optionalAccess', _5 => _5.trim, 'call', _6 => _6()]))throw new (0, _chunkPE2FMBXDcjs.e)("serverUrl is required",_chunkPE2FMBXDcjs.d.INVALID_CONFIG,{context:{receivedServerUrl:r.serverUrl}});try{new URL(r.serverUrl)}catch (e2){throw new (0, _chunkPE2FMBXDcjs.e)("serverUrl must be a valid URL",_chunkPE2FMBXDcjs.d.INVALID_CONFIG,{context:{receivedServerUrl:r.serverUrl}})}if(r.serverUrl===""||r.serverUrl==="https://compute.rhino3d.com/")throw new (0, _chunkPE2FMBXDcjs.e)("serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.",_chunkPE2FMBXDcjs.d.INVALID_CONFIG,{context:{receivedServerUrl:r.serverUrl}});return{...r,serverUrl:r.serverUrl.replace(/\/+$/,""),apiKey:r.apiKey,authToken:r.authToken,debug:_nullishCoalesce(r.debug, () => (!1)),suppressClientSideWarning:r.suppressClientSideWarning}}};var B=async(e,r=null)=>{try{return await K(e,r)}catch(t){throw new (0, _chunkPE2FMBXDcjs.e)("Failed to extract files from compute response",_chunkPE2FMBXDcjs.d.INVALID_STATE,{context:{originalError:t instanceof Error?t.message:String(t)},originalError:t instanceof Error?t:void 0})}},S= exports.c =async(e,r,t=null)=>{if(typeof document>"u"||typeof Blob>"u")throw new (0, _chunkPE2FMBXDcjs.e)("File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).",_chunkPE2FMBXDcjs.d.BROWSER_ONLY,{context:{environment:typeof window<"u"?"browser (SSR)":"Node.js",documentAvailable:typeof document<"u",blobAvailable:typeof Blob<"u"}});try{let n=await K(e,t);await ie(n,r)}catch(n){throw n instanceof _chunkPE2FMBXDcjs.e?n:new (0, _chunkPE2FMBXDcjs.e)("Failed to download files from compute response",_chunkPE2FMBXDcjs.d.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}},K=async(e,r)=>{let t=[];if(e.forEach(n=>{let a=`${n.fileName}${n.fileType}`;if(n.subFolder&&n.subFolder.trim()!==""&&(a=`${n.subFolder}/${a}`),n.isBase64Encoded===!0&&n.data){let s=_chunkQCHPQ22Ycjs.c.call(void 0, n.data);t.push({fileName:`${n.fileName}${n.fileType}`,content:new Uint8Array(s.buffer),path:a})}else n.isBase64Encoded===!1&&n.data&&t.push({fileName:`${n.fileName}${n.fileType}`,content:n.data,path:a})}),r){let n=Array.isArray(r)?r:[r],a=await Promise.all(n.map(async s=>{try{let o=await fetch(s.filePath);if(!o.ok)return _chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Failed to fetch additional file from URL: ${s.filePath}`),null;let u=await(await o.blob()).arrayBuffer();return{fileName:s.fileName,content:new Uint8Array(u),path:s.fileName}}catch(o){return _chunkPE2FMBXDcjs.i.call(void 0, ).error(`Error fetching additional file from URL: ${s.filePath}`,o),null}}));t.push(...a.filter(s=>s!==null))}return t};async function ie(e,r){let{zipSync:t,strToU8:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("fflate"))),a={};e.forEach(i=>{a[i.path]=typeof i.content=="string"?n(i.content):i.content});let s=t(a,{level:6}),o=new Blob([s],{type:"application/zip"});ue(o,`${r}.zip`)}function ue(e,r){if(typeof document>"u")throw new (0, _chunkPE2FMBXDcjs.e)("saveFile requires a browser environment with DOM API access.",_chunkPE2FMBXDcjs.d.BROWSER_ONLY,{context:{function:"saveFile",requiredAPI:"document"}});let t=document.createElement("a");t.href=URL.createObjectURL(e),t.download=r,t.click(),URL.revokeObjectURL(t.href)}var F=new Map;function Y(e,r){F.set(e,r)}Y("Rhino.Geometry.Point3d",(e,r)=>{let t=r;return!t||typeof t.X!="number"?null:new e.Point([t.X,t.Y,t.Z])});Y("Rhino.Geometry.Line",(e,r)=>{let t=r;return!t||!t.From||!t.To?null:new e.Line([t.From.X,t.From.Y,t.From.Z],[t.To.X,t.To.Y,t.To.Z])});function le(e){if(F.has(e))return F.get(e);for(let[r,t]of F)if(e.startsWith(r))return t}function pe(e){return!e||typeof e!="object"?null:_nullishCoalesce(_nullishCoalesce(e.data, () => (e.value)), () => (null))}function J(e,r,t){let n=le(r);if(n)try{return n(t,e)}catch(a){_chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Failed to decode Rhino type ${r}:`,a)}try{let a=pe(e);if(a)return t.CommonObject.decode(a)}catch(a){return _chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Failed to decode ${r} with CommonObject:`,a),{__decodeError:!0,type:r,raw:e}}return e}var D={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},fe="Rhino.Geometry.",ce=["WebDisplay"],me="FileData";function de(e){return ce.some(r=>e.includes(r))}function X(e){if(typeof e!="string")return e;let r=e.trim();if(!(r.startsWith("{")||r.startsWith("[")||r.startsWith('"')))return e;try{let n=JSON.parse(r);if(typeof n=="string")try{return JSON.parse(n)}catch (e3){return n}return n}catch (e4){return e}}function ye(e,r,t){switch(r){case D.STRING:return typeof e!="string"?e:e.replace(/^"(.*)"$/,"$1");case D.INT:return Number.parseInt(e,10);case D.DOUBLE:return Number.parseFloat(e);case D.BOOL:return String(e).toLowerCase()==="true";default:return t&&r.startsWith(fe)?J(e,r,t):e}}function _(e,r,t,n){if(de(r))return null;if(typeof e!="string")return e;let a=t?X(e):e;return ye(a,r,n)}function w(e,r){for(let t of Object.values(e))if(Array.isArray(t))for(let n of t)r(n)}function Z(e,r=!1,t={}){let{parseValues:n=!0,rhino:a,stringOnly:s=!1}=t,o={};for(let i of e.values)w(i.InnerTree,u=>{if(s&&u.type!==D.STRING)return;let p=r?u.id:i.ParamName;if(!p)return;let m=_(u.data,u.type,n,a);o[p]===void 0?o[p]=m:Array.isArray(o[p])?o[p].push(m):o[p]=[o[p],m]});return{values:o}}function H(e){let r=[];for(let t of e.values)w(t.InnerTree,n=>{if(!n.type.includes(me))return;let a=X(n.data);a&&a.FileName&&a.FileType&&a.Data&&r.push(a)});return r}function U(e,r,t={}){let{parseValues:n=!0,rhino:a,stringOnly:s=!1}=t,o;if("byName"in r?o=e.values.find(u=>u.ParamName===r.byName):o=e.values.find(u=>{let p=!1;return w(u.InnerTree,m=>{m.id===r.byId&&(p=!0)}),p}),!o)return;let i=[];if(w(o.InnerTree,u=>{if("byId"in r&&u.id!==r.byId||s&&u.type!==D.STRING)return;let p=_(u.data,u.type,n,a);i.push(p)}),i.length!==0)return i.length===1?i[0]:i}var I=class{constructor(r,t=!1){this.response=r;this.debug=t}getValues(r=!1,t={}){return Z(this.response,r,t)}getValueByParamName(r,t){return U(this.response,{byName:r},t)}getValueByParamId(r,t){return U(this.response,{byId:r},t)}async extractMeshesFromResponse(r){let t={debug:this.debug,...r};try{let{getThreeMeshesFromComputeResponse:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("./visualization.cjs")));return n(this.response,t)}catch(n){let{RhinoComputeError:a,ErrorCodes:s}=(_chunkPE2FMBXDcjs.h.call(void 0, ),_chunkPE2FMBXDcjs.b.call(void 0, _chunkPE2FMBXDcjs.g));throw new a("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",s.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)}})}}getFileData(){return H(this.response)}getAndDownloadFiles(r,t){let n=this.getFileData();S(n,r,t)}};_chunkPE2FMBXDcjs.l.call(void 0, );function A(e,r){r||typeof window<"u"&&_chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Warning: ${e} is running on the client side. For better performance and security, consider running this on the server side.`)}async function C(e,r,t){t.debug&&A("solveGrasshopperDefinition",t.suppressClientSideWarning);let n=M(r,e);he(n,t);let a=await _chunkPE2FMBXDcjs.m.call(void 0, "grasshopper",n,t);return"pointer"in a&&delete a.pointer,a}function M(e,r){let t={algo:null,pointer:null,values:r};return e instanceof Uint8Array?t.algo=_chunkQCHPQ22Ycjs.d.call(void 0, e):e.startsWith("http")?t.pointer=e:_chunkQCHPQ22Ycjs.b.call(void 0, e)?t.algo=e:t.algo=_chunkQCHPQ22Ycjs.a.call(void 0, e),t}function he(e,r){r.cachesolve!==null&&(e.cachesolve=r.cachesolve),r.modelunits!==null&&(e.modelunits=r.modelunits),r.angletolerance!==null&&(e.angletolerance=r.angletolerance),r.absolutetolerance!==null&&(e.absolutetolerance=r.absolutetolerance),r.dataversion!==null&&(e.dataversion=r.dataversion)}function ge(e,r={}){let{preserveSpaces:t=!1}=r,n=e.trim();return t?(n=n.charAt(0).toLowerCase()+n.slice(1).replace(/[-_](.)/g,(a,s)=>s?s.toUpperCase():""),n):(n=n.replace(/^[A-Z]/,a=>a.toLowerCase()).replace(/[\s-_]+(.)?/g,(a,s)=>s?s.toUpperCase():""),n)}function G(e,r={}){return!e||typeof e!="object"?e:Array.isArray(e)?r.deep?e.map(t=>G(t,r)):e:Object.keys(e).reduce((t,n)=>{let a=ge(n,{preserveSpaces:r.preserveSpaces}),s=e[n];return t[a]=r.deep?G(s,r):s,t},{})}_chunkPE2FMBXDcjs.h.call(void 0, );function Q(e){if(typeof e.default!="object"||e.default===null)return;if(!("innerTree"in e.default)){_chunkPE2FMBXDcjs.i.call(void 0, ).warn("Unexpected structure in input.default:",e.default),e.default=null;return}let r=e.default.innerTree;if(Object.keys(r).length===0){e.default=void 0;return}if(e.treeAccess||e.atMost&&e.atMost>1){let n={};for(let[a,s]of Object.entries(r))n[a]=s.map(o=>{if(typeof o.data=="string"){if(o.type==="System.Double"||o.type==="System.Int32"){let i=Number(o.data);return Number.isNaN(i)?o.data:i}if(o.type==="System.Boolean")return o.data.toLowerCase()==="true";if(o.type.startsWith("Rhino.Geometry")||o.type==="System.String")try{return JSON.parse(o.data)}catch (e5){return o.data}}return o.data});e.default=n;return}let t=[];for(let n of Object.values(r))Array.isArray(n)&&n.forEach(a=>{a&&typeof a=="object"&&"data"in a&&t.push(a.data)});t.length===0?e.default=void 0:t.length===1?e.default=t[0]:e.default=t}_chunkPE2FMBXDcjs.h.call(void 0, );function R(e,r){let{transform:t,setUndefinedOnEmpty:n=!0}=r;if(!(e.default===void 0||e.default===null))if(Array.isArray(e.default)){let a=e.default.map(t).filter(s=>s!==null);e.default=a.length>0?a:void 0}else{let a=t(e.default);a!==null?e.default=a:n&&(e.default=void 0)}}function Te(){return e=>{if(typeof e=="number")return e;if(typeof e=="string"){let r=Number(e.trim());return Number.isNaN(r)?null:r}return null}}function be(){return e=>{if(typeof e=="boolean")return e;if(typeof e=="string"){let r=e.toLowerCase();if(r==="true")return!0;if(r==="false")return!1;throw new Error(`Invalid boolean string: "${e}"`)}return null}}function De(){return e=>typeof e=="string"?e.startsWith('"')&&e.endsWith('"')||e.startsWith('"')?e.slice(1,-1):e:null}function Ie(){return e=>{if(typeof e=="string"){let r=e.trim();return r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1).trim()),r}return null}}function xe(e){R(e,{transform:Ie(),setUndefinedOnEmpty:!1})}function Ce(e="unknown"){return r=>{if(typeof r=="object"&&r!==null)return r;if(typeof r=="string"&&r.trim()!=="")try{let t=JSON.parse(r);return typeof t=="object"&&t!==null?t:(_chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Parsed value for input ${e} is not an object`),null)}catch(t){return _chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Failed to parse object value "${r}" for input ${e}`,t),null}return null}}function ee(e,r,t){let n=Number(e.toFixed(r));return Math.abs(e-n)<t?n:e}function Pe(e,r=1e-8){if(!Number.isFinite(e)||e===0)return .1;let t=Math.abs(e);if(t>=1){let y=String(e).split(".")[1];if(y&&y.length>0){let h=Math.min(y.length,12),g=Math.pow(10,-h),k=Number(g.toFixed(h));return Math.abs(k-g)<r?k:g}return 1}let n=String(e),a=n.toLowerCase().match(/e(-?\d+)/);if(a){let E=Number(a[1]);if(E<0||n.toLowerCase().includes("e-")){let y=Math.abs(E),h=Math.pow(10,-y),g=Number(h.toFixed(y));return Math.abs(g-h)<r?g:h}return .1}let s=12,i=t.toFixed(s).replace(/0+$/,""),u=Math.min((i.split(".")[1]||"").length,s);if(u===0)return .1;let p=Math.pow(10,-u),m=Number(p.toFixed(u));return Math.abs(m-p)<r?m:p}function re(e,r=1e-8){let t=e.paramType==="Integer";if(R(e,{transform:Te()}),t){Array.isArray(e.default)?e.default=e.default.map(s=>typeof s=="number"?Math.round(s):s):typeof e.default=="number"&&(e.default=Math.round(e.default)),e.stepSize=1;return}let n=Array.isArray(e.default)?e.default[0]:e.default,a;if(typeof n=="number"&&Number.isFinite(n)&&n!==0?a=n:typeof e.minimum=="number"&&Number.isFinite(e.minimum)&&e.minimum!==0?a=e.minimum:typeof e.maximum=="number"&&Number.isFinite(e.maximum)&&e.maximum!==0&&(a=e.maximum),a!==void 0?e.stepSize=Pe(a,r):e.stepSize=.1,typeof e.stepSize=="number"){let s=0,o=String(e.stepSize),i=o.toLowerCase().match(/e(-?\d+)/);if(i?s=Math.abs(Number(i[1])):s=_nullishCoalesce(_optionalChain([o, 'access', _7 => _7.split, 'call', _8 => _8("."), 'access', _9 => _9[1], 'optionalAccess', _10 => _10.length]), () => (0)),s===0&&typeof n=="number"&&n!==0&&Math.abs(n)<1){let u=Math.ceil(-Math.log10(Math.abs(n)));Number.isFinite(u)&&u>0&&(s=u)}s=Math.min(Math.max(s,0),12),Array.isArray(e.default)?e.default=e.default.map(u=>typeof u=="number"?ee(u,s,r):u):typeof e.default=="number"&&(e.default=ee(e.default,s,r))}}function Se(e){try{R(e,{transform:be(),setUndefinedOnEmpty:!1})}catch(r){throw r instanceof Error?new (0, _chunkPE2FMBXDcjs.e)(r.message):r}}function Re(e){R(e,{transform:De(),setUndefinedOnEmpty:!1})}function te(e){R(e,{transform:Ce(e.nickname||"unnamed"),setUndefinedOnEmpty:!0})}function ve(e){if(!e.values||typeof e.values!="object"||Object.keys(e.values).length===0)throw _chunkPE2FMBXDcjs.e.missingValues(e.nickname||"unnamed","ValueList");if(e.default!==void 0&&e.default!==null){let r=String(e.default).toLowerCase();Object.keys(e.values).some(n=>n.toLowerCase()===r)||_chunkPE2FMBXDcjs.i.call(void 0, ).warn(`ValueList input "${e.nickname||"unnamed"}" default value "${e.default}" is not in available values`)}}var ne={Number:re,Integer:re,Boolean:Se,Text:Re,ValueList:ve,Geometry:te,File:te,Color:xe};_chunkPE2FMBXDcjs.l.call(void 0, );function Oe(e,r){switch(e.paramType){case"Number":case"Integer":return{...r,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,default:e.atMost>1?[0]:0};case"Boolean":return{...r,paramType:"Boolean",default:e.atMost>1?[!1]:!1};case"Text":return{...r,paramType:"Text",default:e.atMost>1?[""]:""};case"ValueList":return{...r,paramType:"ValueList",values:_nullishCoalesce(e.values, () => ({})),default:e.atMost>1?[e.default]:e.default};case"File":return{...r,paramType:"File",default:e.atMost>1?[null]:null};case"Color":return{...r,paramType:"Color",default:e.atMost>1?["0, 0, 0"]:"0, 0, 0"};default:return{...r,paramType:"Geometry",default:e.atMost>1?[null]:null}}}function v(e){let r={description:e.description,name:e.name,nickname:e.nickname,treeAccess:e.treeAccess,groupName:_nullishCoalesce(e.groupName, () => ("")),id:e.id};try{Q(e);let t=ne[e.paramType];if(!t)throw _chunkPE2FMBXDcjs.e.unknownParamType(e.paramType,e.name);switch(t(e),e.paramType){case"Number":case"Integer":return{...r,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:e.stepSize,default:e.default};case"Boolean":return{...r,paramType:"Boolean",default:e.default};case"Text":return{...r,paramType:"Text",default:e.default};case"ValueList":return{...r,paramType:"ValueList",values:e.values,default:e.default};case"Geometry":return{...r,paramType:e.paramType,default:e.default};case"File":return{...r,paramType:e.paramType,acceptedFormats:e.acceptedFormats,default:e.default};case"Color":return{...r,paramType:"Color",default:e.default};default:throw _chunkPE2FMBXDcjs.e.unknownParamType(e.paramType,e.name)}}catch(t){if(t instanceof _chunkPE2FMBXDcjs.e)return _chunkPE2FMBXDcjs.i.call(void 0, ).error(`Validation error for input ${e.name||"unknown"}:`,t.message),Oe(e,r);throw new (0, _chunkPE2FMBXDcjs.e)(t instanceof Error?t.message:String(t),"VALIDATION_ERROR",{context:{paramName:e.name,paramType:e.paramType},originalError:t instanceof Error?t:new Error(String(t))})}}function x(e){return e.map(r=>v(r))}async function b(e,r){let t=M(e,[]),n={};t.algo&&(n.algo=t.algo),t.pointer&&(n.pointer=t.pointer);let a=await _chunkPE2FMBXDcjs.m.call(void 0, "io",n,r);if(!a||typeof a!="object")throw new (0, _chunkPE2FMBXDcjs.e)("Invalid IO response structure",_chunkPE2FMBXDcjs.d.INVALID_INPUT,{context:{response:a,definition:e}});let s=G(a,{deep:!0});return{inputs:s.inputs,outputs:s.outputs}}async function P(e,r){A("fetchParsedDefinitionIO",r.suppressClientSideWarning);let{inputs:t,outputs:n}=await b(e,r);return{inputs:x(t),outputs:n}}var O=class e{constructor(r){_chunkPE2FMBXDcjs.c.call(void 0, this,"innerTree");_chunkPE2FMBXDcjs.c.call(void 0, this,"paramName");this.paramName=r,this.innerTree={}}append(r,t){let n=e.formatPathString(r);this.innerTree[n]||(this.innerTree[n]=[]);let a=t.map(s=>({data:e.serializeValue(s)}));return this.innerTree[n].push(...a),this}appendSingle(r,t){return this.append(r,[t])}fromDataTreeDefault(r){this.innerTree={};for(let[t,n]of Object.entries(r)){if(!Array.isArray(n))continue;let a=e.parsePathString(t);this.append(a,n)}return this}appendFlat(r){let t=Array.isArray(r)?r:[r];return this.append([0],t)}flatten(){let r=[];for(let t of Object.values(this.innerTree))if(Array.isArray(t))for(let n of t)r.push(e.deserializeValue(n.data));return r}getPaths(){return Object.keys(this.innerTree)}getPath(r){let t=e.formatPathString(r),n=this.innerTree[t];if(n)return n.map(a=>e.deserializeValue(a.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(r){return r.filter(t=>e.hasValidValue(t.default)).map(t=>{let n=new e(t.nickname||"unnamed"),a=t.default;if(t.treeAccess&&e.isDataTreeStructure(a))n.fromDataTreeDefault(a),e.isNumericInput(t)&&n.applyNumericConstraints(t.minimum,t.maximum,t.nickname||"unnamed");else{let s=Array.isArray(a)?a:[a],o=e.processValues(s,t);n.appendFlat(o)}return n.toComputeFormat()})}static fromInputParam(r){return e.hasValidValue(r.default)?e.fromInputParams([r])[0]:void 0}static replaceTreeValue(r,t,n){if(r.length>0&&r[0]instanceof e){let s=r,o=s.findIndex(u=>u.getParamName()===t),i=new e(t);return typeof n=="object"&&n!==null&&!Array.isArray(n)&&e.isDataTreeStructure(n)?i.fromDataTreeDefault(n):(Array.isArray(n),i.appendFlat(n)),o!==-1?s[o]=i:s.push(i),s}else{let s=r,o=s.findIndex(p=>p.ParamName===t),i=new e(t);typeof n=="object"&&n!==null&&!Array.isArray(n)&&e.isDataTreeStructure(n)?i.fromDataTreeDefault(n):(Array.isArray(n),i.appendFlat(n));let u=i.toComputeFormat();return o!==-1?s[o]=u:s.push(u),s}}static getTreeValue(r,t){if(r.length>0&&r[0]instanceof e){let s=r.find(i=>i.getParamName()===t);if(!s)return null;let o=s.flatten();return o.length===0?null:o.length===1?o[0]:o}else{let s=r.find(p=>p.ParamName===t);if(!s)return null;let o=s.InnerTree;if(!o)return null;let i=Object.keys(o)[0];if(!i)return null;let u=o[i];if(Array.isArray(u)){if(u.length===1){let p=_optionalChain([u, 'access', _11 => _11[0], 'optionalAccess', _12 => _12.data]);return p!==void 0?e.deserializeValue(p):null}return u.map(p=>_optionalChain([p, 'optionalAccess', _13 => _13.data])!==void 0?e.deserializeValue(p.data):null).filter(p=>p!==null)}return _optionalChain([u, 'optionalAccess', _14 => _14.data])!==void 0?e.deserializeValue(u.data):u}}static parsePathString(r){let t=r.match(/^\{([\d;]+)\}$/);return t?t[1].split(";").map(Number):(_chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Invalid TreeBuilder path format: ${r}, using [0]`),[0])}static formatPathString(r){return`{${r.join(";")}}`}applyNumericConstraints(r,t,n){for(let a of Object.values(this.innerTree))if(Array.isArray(a))for(let s of a){let o=e.deserializeValue(s.data);if(typeof o=="number"){let i=e.clampValue(o,r,t,n);s.data=e.serializeValue(i)}}}static serializeValue(r){return typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:typeof r=="object"&&r!==null?JSON.stringify(r):String(r)}static deserializeValue(r){if(typeof r=="boolean"||typeof r=="number"||typeof r!="string")return r;if(r.startsWith("{")||r.startsWith("["))try{return JSON.parse(r)}catch (e6){return r}return isNaN(Number(r))?r==="true"?!0:r==="false"?!1:r:Number(r)}static hasValidValue(r){return r==null?!1:typeof r=="string"?!0:!(Array.isArray(r)&&r.length===0||typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0)}static isDataTreeStructure(r){return typeof r!="object"||r===null||Array.isArray(r)?!1:Object.entries(r).every(([t,n])=>typeof t=="string"&&/^\{[\d;]+\}$/.test(t)&&Array.isArray(n))}static isNumericInput(r){return r.paramType==="Number"||r.paramType==="Integer"}static processValues(r,t){return r.map(n=>e.isNumericInput(t)&&typeof n=="number"?e.clampValue(n,t.minimum,t.maximum,t.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(r,t,n,a){let s=r;return t!=null&&s<t&&(_chunkPE2FMBXDcjs.i.call(void 0, ).warn(`${a}: ${r} below min ${t}, clamping`),s=t),n!=null&&s>n&&(_chunkPE2FMBXDcjs.i.call(void 0, ).warn(`${a}: ${r} above max ${n}, clamping`),s=n),s}};exports.a = T; exports.b = B; exports.c = S; exports.d = I; exports.e = C; exports.f = v; exports.g = x; exports.h = b; exports.i = P; exports.j = O;
2
- //# sourceMappingURL=chunk-GIV3ZLXR.cjs.map
2
+ //# sourceMappingURL=chunk-YBPIKW2A.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-GIV3ZLXR.cjs","../src/features/grasshopper/client/grasshopper-client.ts","../src/features/grasshopper/file-handling/handle-files.ts"],"names":["init_errors","init_base","init_logger","GrasshopperClient","_GrasshopperClient","config","__publicField","ComputeServerStats","client","RhinoComputeError","ErrorCodes","definition","fetchParsedDefinitionIO","fetchDefinitionIO","dataTree","result","solveGrasshopperDefinition","error","getLogger","extractFilesFromComputeResponse","downloadableFiles","additionalFiles","processFiles","err","downloadFileData","fileFoldername","processedFiles","createAndDownloadZip","dataItems","item","filePath"],"mappings":"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","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-GIV3ZLXR.cjs","sourcesContent":[null,"import { ErrorCodes } from '@/core/errors';\nimport { RhinoComputeError } from '@/core/errors/base';\nimport { getLogger } from '@/core/utils/logger';\nimport ComputeServerStats from '@/core/server/compute-server-stats';\nimport { ComputeConfig } from '@/core/types';\n\nimport { fetchDefinitionIO, fetchParsedDefinitionIO, solveGrasshopperDefinition } from '..';\nimport { GrasshopperComputeConfig, GrasshopperComputeResponse, DataTree } from '../types';\n\n/**\n * GrasshopperClient provides a simple API for interacting with a Rhino Compute server and grasshopper.\n *\n * @public This is the recommended high-level API for Rhino Compute operations.\n *\n * **Security Warning:**\n * Using this client in a browser environment exposes your server URL and API key to users.\n * For production, use this library server-side or proxy requests through your own backend.\n *\n * @example\n * ```typescript\n * const client = await GrasshopperClient.create({\n * serverUrl: 'http://localhost:6500',\n * apiKey: 'your-api-key'\n * });\n *\n * try {\n * const result = await client.solve(definitionUrl, { x: 1, y: 2 });\n * } finally {\n * await client.dispose(); // Clean up resources\n * }\n * ```\n */\nexport default class GrasshopperClient {\n\tprivate readonly config: GrasshopperComputeConfig;\n\tpublic readonly serverStats: ComputeServerStats;\n\tprivate disposed = false;\n\n\tprivate constructor(config: GrasshopperComputeConfig) {\n\t\tthis.config = this.normalizeComputeConfig(config);\n\t\tthis.serverStats = new ComputeServerStats(this.config.serverUrl, this.config.apiKey);\n\t}\n\n\t/**\n\t * Creates and initializes a GrasshopperClient with server validation.\n\t *\n\t * @throws {RhinoComputeError} with code NETWORK_ERROR if server is offline\n\t * @throws {RhinoComputeError} with code INVALID_CONFIG if configuration is invalid\n\t */\n\tstatic async create(config: GrasshopperComputeConfig): Promise<GrasshopperClient> {\n\t\tconst client = new GrasshopperClient(config);\n\n\t\t// Check server is online before returning\n\t\tif (!(await client.serverStats.isServerOnline())) {\n\t\t\tthrow new RhinoComputeError('Rhino Compute server is not online', ErrorCodes.NETWORK_ERROR, {\n\t\t\t\tcontext: { serverUrl: client.config.serverUrl }\n\t\t\t});\n\t\t}\n\n\t\treturn client;\n\t}\n\n\t/**\n\t * Gets the client's configuration.\n\t * Useful for passing to lower-level functions.\n\t */\n\tpublic getConfig(): GrasshopperComputeConfig {\n\t\tthis.ensureNotDisposed();\n\t\treturn { ...this.config };\n\t}\n\n\t/**\n\t * Get input/output parameters of a Grasshopper definition.\n\t */\n\tpublic async getIO(definition: string | Uint8Array) {\n\t\tthis.ensureNotDisposed();\n\t\treturn fetchParsedDefinitionIO(definition, this.config);\n\t}\n\n\tpublic async getRawIO(definition: string | Uint8Array) {\n\t\tthis.ensureNotDisposed();\n\t\treturn fetchDefinitionIO(definition, this.config);\n\t}\n\n\t/**\n\t * Run a compute job with a Grasshopper definition.\n\t *\n\t * @throws {RhinoComputeError} with code INVALID_INPUT if definition is empty\n\t * @throws {RhinoComputeError} with code NETWORK_ERROR if server is offline\n\t * @throws {RhinoComputeError} with code COMPUTATION_ERROR if computation fails\n\t */\n\tpublic async solve(\n\t\tdefinition: string | Uint8Array,\n\t\tdataTree: DataTree[]\n\t): Promise<GrasshopperComputeResponse> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\t// Validate inputs\n\t\t\tif (typeof definition === 'string' && !definition?.trim()) {\n\t\t\t\tthrow new RhinoComputeError(\n\t\t\t\t\t'Definition URL/content is required',\n\t\t\t\t\tErrorCodes.INVALID_INPUT,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontext: { receivedUrl: definition }\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t} else if (definition instanceof Uint8Array && definition.length === 0) {\n\t\t\t\tthrow new RhinoComputeError('Definition content is empty', ErrorCodes.INVALID_INPUT);\n\t\t\t}\n\n\t\t\t// Check server\n\t\t\tif (!(await this.serverStats.isServerOnline())) {\n\t\t\t\tthrow new RhinoComputeError(\n\t\t\t\t\t'Rhino Compute server is not online',\n\t\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t{ context: { serverUrl: this.config.serverUrl } }\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Run computation\n\t\t\tconst result = await solveGrasshopperDefinition(dataTree, definition, this.config);\n\n\t\t\t// Check for errors\n\t\t\tif (result && typeof result === 'object' && 'message' in result && !('fileData' in result)) {\n\t\t\t\tthrow new RhinoComputeError(\n\t\t\t\t\t(result as { message: string }).message || 'Computation failed',\n\t\t\t\t\tErrorCodes.COMPUTATION_ERROR,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tdefinition:\n\t\t\t\t\t\t\t\ttypeof definition === 'string' && definition.length < 200\n\t\t\t\t\t\t\t\t\t? definition\n\t\t\t\t\t\t\t\t\t: '...content...',\n\t\t\t\t\t\t\tinputs: dataTree\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tif (this.config.debug) {\n\t\t\t\tgetLogger().error('Compute failed:', error);\n\t\t\t}\n\n\t\t\tif (error instanceof RhinoComputeError) {\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tthrow new RhinoComputeError(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\tErrorCodes.COMPUTATION_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tdefinition:\n\t\t\t\t\t\t\ttypeof definition === 'string' && definition.length < 200\n\t\t\t\t\t\t\t\t? definition\n\t\t\t\t\t\t\t\t: '...content...',\n\t\t\t\t\t\tinputs: dataTree\n\t\t\t\t\t},\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}\n\n\t/**\n\t * Disposes of client resources.\n\t * Call this when you're done using the client.\n\t */\n\tpublic async dispose(): Promise<void> {\n\t\tif (this.disposed) return;\n\n\t\tthis.disposed = true;\n\n\t\t// If serverStats has a dispose method, call it\n\t\tif ('dispose' in this.serverStats && typeof this.serverStats.dispose === 'function') {\n\t\t\tawait this.serverStats.dispose();\n\t\t}\n\n\t\t// Clear any cached data or connections if needed\n\t}\n\n\t/**\n\t * Ensures the client hasn't been disposed.\n\t */\n\tprivate ensureNotDisposed(): void {\n\t\tif (this.disposed) {\n\t\t\tthrow new RhinoComputeError(\n\t\t\t\t'GrasshopperClient has been disposed and cannot be used',\n\t\t\t\tErrorCodes.INVALID_STATE\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Validates and normalizes a compute configuration.\n\t *\n\t * @throws {RhinoComputeError} with code INVALID_CONFIG if configuration is invalid\n\t */\n\tprivate normalizeComputeConfig<T extends ComputeConfig | GrasshopperComputeConfig>(config: T): T {\n\t\tif (!config.serverUrl?.trim()) {\n\t\t\tthrow new RhinoComputeError('serverUrl is required', ErrorCodes.INVALID_CONFIG, {\n\t\t\t\tcontext: { receivedServerUrl: config.serverUrl }\n\t\t\t});\n\t\t}\n\n\t\t// Validate URL format\n\t\ttry {\n\t\t\tnew URL(config.serverUrl);\n\t\t} catch {\n\t\t\tthrow new RhinoComputeError('serverUrl must be a valid URL', ErrorCodes.INVALID_CONFIG, {\n\t\t\t\tcontext: { receivedServerUrl: config.serverUrl }\n\t\t\t});\n\t\t}\n\n\t\t// Validate that it's not the default public endpoint\n\t\tif (config.serverUrl === '' || config.serverUrl === 'https://compute.rhino3d.com/') {\n\t\t\tthrow new RhinoComputeError(\n\t\t\t\t'serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.',\n\t\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t\t{ context: { receivedServerUrl: config.serverUrl } }\n\t\t\t);\n\t\t}\n\n\t\treturn {\n\t\t\t...config,\n\t\t\tserverUrl: config.serverUrl.replace(/\\/+$/, ''), // Remove trailing slashes\n\t\t\tapiKey: config.apiKey,\n\t\t\tauthToken: config.authToken,\n\t\t\tdebug: config.debug ?? false,\n\t\t\tsuppressClientSideWarning: config.suppressClientSideWarning\n\t\t} as T;\n\t}\n}\n","import { RhinoComputeError, ErrorCodes, getLogger } from '@/core';\nimport { decodeBase64ToBinary } from '@/core/utils/encoding';\n\nimport { FileBaseInfo, FileData, ProcessedFile } from './types';\n\n/**\n * Extracts and processes files from compute response data without downloading them.\n * Returns an array of ProcessedFile objects that can be used programmatically.\n *\n * @param downloadableFiles - An array of FileData items from the compute response.\n * @param additionalFiles - Optional additional files to include (fetched from URLs).\n * @returns A Promise resolving to an array of ProcessedFile objects.\n * @throws Will throw an error if file processing fails.\n *\n * @example\n * const files = await extractFilesFromComputeResponse(fileData);\n * files.forEach(file => {\n * console.log(`File: ${file.fileName}, Size: ${file.content.length}`);\n * });\n */\nexport const extractFilesFromComputeResponse = async (\n\tdownloadableFiles: FileData[],\n\tadditionalFiles: FileBaseInfo[] | FileBaseInfo | null = null\n): Promise<ProcessedFile[]> => {\n\ttry {\n\t\treturn await processFiles(downloadableFiles, additionalFiles);\n\t} catch (err) {\n\t\tthrow new RhinoComputeError(\n\t\t\t'Failed to extract files from compute response',\n\t\t\tErrorCodes.INVALID_STATE,\n\t\t\t{\n\t\t\t\tcontext: { originalError: err instanceof Error ? err.message : String(err) },\n\t\t\t\toriginalError: err instanceof Error ? err : undefined\n\t\t\t}\n\t\t);\n\t}\n};\n\n/**\n * Downloads files from a compute response as a ZIP archive.\n * Packages multiple files into a single ZIP file and triggers a browser download.\n *\n * @param downloadableFiles - An array of FileData items from the compute response.\n * @param additionalFiles - Optional additional files to include in the ZIP (fetched from URLs).\n * @param fileFoldername - The name of the ZIP file (without extension).\n * @throws Will throw an error if the file handling or download fails.\n *\n * @example\n * await downloadDataFromComputeResponse(fileData, null, 'my-export');\n * // Downloads 'my-export.zip'\n */\nexport const downloadFileData = async (\n\tdownloadableFiles: FileData[],\n\tfileFoldername: string,\n\tadditionalFiles: FileBaseInfo[] | FileBaseInfo | null = null\n): Promise<void> => {\n\t// Check if we're in a browser environment\n\tif (typeof document === 'undefined' || typeof Blob === 'undefined') {\n\t\tthrow new RhinoComputeError(\n\t\t\t'File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).',\n\t\t\tErrorCodes.BROWSER_ONLY,\n\t\t\t{\n\t\t\t\tcontext: {\n\t\t\t\t\tenvironment: typeof window !== 'undefined' ? 'browser (SSR)' : 'Node.js',\n\t\t\t\t\tdocumentAvailable: typeof document !== 'undefined',\n\t\t\t\t\tblobAvailable: typeof Blob !== 'undefined'\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\ttry {\n\t\tconst processedFiles = await processFiles(downloadableFiles, additionalFiles);\n\t\tawait createAndDownloadZip(processedFiles, fileFoldername);\n\t} catch (err) {\n\t\t// Re-throw if it's already a RhinoComputeError\n\t\tif (err instanceof RhinoComputeError) {\n\t\t\tthrow err;\n\t\t}\n\t\tthrow new RhinoComputeError(\n\t\t\t'Failed to download files from compute response',\n\t\t\tErrorCodes.INVALID_STATE,\n\t\t\t{\n\t\t\t\tcontext: { originalError: err instanceof Error ? err.message : String(err) },\n\t\t\t\toriginalError: err instanceof Error ? err : undefined\n\t\t\t}\n\t\t);\n\t}\n};\n\n/**\n * Processes files from compute response data and additional files.\n * Converts base64-encoded data to binary and fetches additional files from URLs.\n *\n * @param dataItems - An array of FileData items to process.\n * @param additionalFiles - Optional additional files to fetch and include.\n * @returns A Promise resolving to an array of ProcessedFile objects.\n */\nconst processFiles = async (\n\tdataItems: FileData[],\n\tadditionalFiles: FileBaseInfo[] | FileBaseInfo | null\n): Promise<ProcessedFile[]> => {\n\tconst processedFiles: ProcessedFile[] = [];\n\n\t// Process compute response files\n\tdataItems.forEach((item) => {\n\t\tlet filePath = `${item.fileName}${item.fileType}`;\n\n\t\tif (item.subFolder && item.subFolder.trim() !== '') {\n\t\t\tfilePath = `${item.subFolder}/${filePath}`;\n\t\t}\n\n\t\tif (item.isBase64Encoded === true && item.data) {\n\t\t\tconst bites = decodeBase64ToBinary(item.data);\n\t\t\tprocessedFiles.push({\n\t\t\t\tfileName: `${item.fileName}${item.fileType}`,\n\t\t\t\tcontent: new Uint8Array(bites.buffer),\n\t\t\t\tpath: filePath\n\t\t\t});\n\t\t} else if (item.isBase64Encoded === false && item.data) {\n\t\t\tprocessedFiles.push({\n\t\t\t\tfileName: `${item.fileName}${item.fileType}`,\n\t\t\t\tcontent: item.data,\n\t\t\t\tpath: filePath\n\t\t\t});\n\t\t}\n\t});\n\n\tif (additionalFiles) {\n\t\tconst filesArray = Array.isArray(additionalFiles) ? additionalFiles : [additionalFiles];\n\t\tconst additionalProcessed = await Promise.all(\n\t\t\tfilesArray.map(async (file) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst response = await fetch(file.filePath);\n\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\tgetLogger().warn(`Failed to fetch additional file from URL: ${file.filePath}`);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\tconst fileBlob = await response.blob();\n\t\t\t\t\tconst arrayBuffer = await fileBlob.arrayBuffer();\n\t\t\t\t\treturn {\n\t\t\t\t\t\tfileName: file.fileName,\n\t\t\t\t\t\tcontent: new Uint8Array(arrayBuffer),\n\t\t\t\t\t\tpath: file.fileName\n\t\t\t\t\t} as ProcessedFile;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tgetLogger().error(`Error fetching additional file from URL: ${file.filePath}`, error);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t})\n\t\t);\n\n\t\tprocessedFiles.push(...additionalProcessed.filter((f): f is ProcessedFile => f !== null));\n\t}\n\n\treturn processedFiles;\n};\n\n/**\n * Creates a ZIP archive from processed files and triggers a browser download.\n *\n * @param files - An array of ProcessedFile objects to include in the ZIP.\n * @param zipName - The name of the ZIP file (without extension).\n * @returns A Promise that resolves when the ZIP is generated and download is triggered.\n */\nasync function createAndDownloadZip(files: ProcessedFile[], zipName: string): Promise<void> {\n\tconst { zipSync, strToU8 } = await import('fflate');\n\n\t// Convert files to fflate format\n\tconst zipData: Record<string, Uint8Array> = {};\n\tfiles.forEach((file) => {\n\t\tzipData[file.path] = typeof file.content === 'string' ? strToU8(file.content) : file.content;\n\t});\n\n\tconst zipped = zipSync(zipData, { level: 6 });\n\n\tconst blob = new Blob([zipped as BlobPart], { type: 'application/zip' });\n\tsaveFile(blob, `${zipName}.zip`);\n}\n\n/**\n * Saves a Blob object as a file in the user's browser.\n *\n * @param blob - The Blob object representing the file content.\n * @param filename - The name to give the downloaded file (including extension).\n * @throws {RhinoComputeError} If not running in a browser environment.\n */\nfunction saveFile(blob: Blob, filename: string) {\n\tif (typeof document === 'undefined') {\n\t\tthrow new RhinoComputeError(\n\t\t\t'saveFile requires a browser environment with DOM API access.',\n\t\t\tErrorCodes.BROWSER_ONLY,\n\t\t\t{\n\t\t\t\tcontext: { function: 'saveFile', requiredAPI: 'document' }\n\t\t\t}\n\t\t);\n\t}\n\n\tconst a = document.createElement('a');\n\ta.href = URL.createObjectURL(blob);\n\ta.download = filename;\n\ta.click();\n\tURL.revokeObjectURL(a.href);\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-YBPIKW2A.cjs","../src/features/grasshopper/client/grasshopper-client.ts","../src/features/grasshopper/file-handling/handle-files.ts"],"names":["init_errors","init_base","init_logger","GrasshopperClient","_GrasshopperClient","config","__publicField","ComputeServerStats","client","RhinoComputeError","ErrorCodes","definition","fetchParsedDefinitionIO","fetchDefinitionIO","dataTree","result","solveGrasshopperDefinition","error","getLogger","extractFilesFromComputeResponse","downloadableFiles","additionalFiles","processFiles","err","downloadFileData","fileFoldername","processedFiles","createAndDownloadZip","dataItems","item","filePath"],"mappings":"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","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-YBPIKW2A.cjs","sourcesContent":[null,"import { ErrorCodes } from '@/core/errors';\nimport { RhinoComputeError } from '@/core/errors/base';\nimport { getLogger } from '@/core/utils/logger';\nimport ComputeServerStats from '@/core/server/compute-server-stats';\nimport { ComputeConfig } from '@/core/types';\n\nimport { fetchDefinitionIO, fetchParsedDefinitionIO, solveGrasshopperDefinition } from '..';\nimport { GrasshopperComputeConfig, GrasshopperComputeResponse, DataTree } from '../types';\n\n/**\n * GrasshopperClient provides a simple API for interacting with a Rhino Compute server and grasshopper.\n *\n * @public This is the recommended high-level API for Rhino Compute operations.\n *\n * **Security Warning:**\n * Using this client in a browser environment exposes your server URL and API key to users.\n * For production, use this library server-side or proxy requests through your own backend.\n *\n * @example\n * ```typescript\n * const client = await GrasshopperClient.create({\n * serverUrl: 'http://localhost:6500',\n * apiKey: 'your-api-key'\n * });\n *\n * try {\n * const result = await client.solve(definitionUrl, { x: 1, y: 2 });\n * } finally {\n * await client.dispose(); // Clean up resources\n * }\n * ```\n */\nexport default class GrasshopperClient {\n\tprivate readonly config: GrasshopperComputeConfig;\n\tpublic readonly serverStats: ComputeServerStats;\n\tprivate disposed = false;\n\n\tprivate constructor(config: GrasshopperComputeConfig) {\n\t\tthis.config = this.normalizeComputeConfig(config);\n\t\tthis.serverStats = new ComputeServerStats(this.config.serverUrl, this.config.apiKey);\n\t}\n\n\t/**\n\t * Creates and initializes a GrasshopperClient with server validation.\n\t *\n\t * @throws {RhinoComputeError} with code NETWORK_ERROR if server is offline\n\t * @throws {RhinoComputeError} with code INVALID_CONFIG if configuration is invalid\n\t */\n\tstatic async create(config: GrasshopperComputeConfig): Promise<GrasshopperClient> {\n\t\tconst client = new GrasshopperClient(config);\n\n\t\t// Check server is online before returning\n\t\tif (!(await client.serverStats.isServerOnline())) {\n\t\t\tthrow new RhinoComputeError('Rhino Compute server is not online', ErrorCodes.NETWORK_ERROR, {\n\t\t\t\tcontext: { serverUrl: client.config.serverUrl }\n\t\t\t});\n\t\t}\n\n\t\treturn client;\n\t}\n\n\t/**\n\t * Gets the client's configuration.\n\t * Useful for passing to lower-level functions.\n\t */\n\tpublic getConfig(): GrasshopperComputeConfig {\n\t\tthis.ensureNotDisposed();\n\t\treturn { ...this.config };\n\t}\n\n\t/**\n\t * Get input/output parameters of a Grasshopper definition.\n\t */\n\tpublic async getIO(definition: string | Uint8Array) {\n\t\tthis.ensureNotDisposed();\n\t\treturn fetchParsedDefinitionIO(definition, this.config);\n\t}\n\n\tpublic async getRawIO(definition: string | Uint8Array) {\n\t\tthis.ensureNotDisposed();\n\t\treturn fetchDefinitionIO(definition, this.config);\n\t}\n\n\t/**\n\t * Run a compute job with a Grasshopper definition.\n\t *\n\t * @throws {RhinoComputeError} with code INVALID_INPUT if definition is empty\n\t * @throws {RhinoComputeError} with code NETWORK_ERROR if server is offline\n\t * @throws {RhinoComputeError} with code COMPUTATION_ERROR if computation fails\n\t */\n\tpublic async solve(\n\t\tdefinition: string | Uint8Array,\n\t\tdataTree: DataTree[]\n\t): Promise<GrasshopperComputeResponse> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\t// Validate inputs\n\t\t\tif (typeof definition === 'string' && !definition?.trim()) {\n\t\t\t\tthrow new RhinoComputeError(\n\t\t\t\t\t'Definition URL/content is required',\n\t\t\t\t\tErrorCodes.INVALID_INPUT,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontext: { receivedUrl: definition }\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t} else if (definition instanceof Uint8Array && definition.length === 0) {\n\t\t\t\tthrow new RhinoComputeError('Definition content is empty', ErrorCodes.INVALID_INPUT);\n\t\t\t}\n\n\t\t\t// Check server\n\t\t\tif (!(await this.serverStats.isServerOnline())) {\n\t\t\t\tthrow new RhinoComputeError(\n\t\t\t\t\t'Rhino Compute server is not online',\n\t\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t{ context: { serverUrl: this.config.serverUrl } }\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Run computation\n\t\t\tconst result = await solveGrasshopperDefinition(dataTree, definition, this.config);\n\n\t\t\t// Check for errors\n\t\t\tif (result && typeof result === 'object' && 'message' in result && !('fileData' in result)) {\n\t\t\t\tthrow new RhinoComputeError(\n\t\t\t\t\t(result as { message: string }).message || 'Computation failed',\n\t\t\t\t\tErrorCodes.COMPUTATION_ERROR,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tdefinition:\n\t\t\t\t\t\t\t\ttypeof definition === 'string' && definition.length < 200\n\t\t\t\t\t\t\t\t\t? definition\n\t\t\t\t\t\t\t\t\t: '...content...',\n\t\t\t\t\t\t\tinputs: dataTree\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tif (this.config.debug) {\n\t\t\t\tgetLogger().error('Compute failed:', error);\n\t\t\t}\n\n\t\t\tif (error instanceof RhinoComputeError) {\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tthrow new RhinoComputeError(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\tErrorCodes.COMPUTATION_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tdefinition:\n\t\t\t\t\t\t\ttypeof definition === 'string' && definition.length < 200\n\t\t\t\t\t\t\t\t? definition\n\t\t\t\t\t\t\t\t: '...content...',\n\t\t\t\t\t\tinputs: dataTree\n\t\t\t\t\t},\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}\n\n\t/**\n\t * Disposes of client resources.\n\t * Call this when you're done using the client.\n\t */\n\tpublic async dispose(): Promise<void> {\n\t\tif (this.disposed) return;\n\n\t\tthis.disposed = true;\n\n\t\t// If serverStats has a dispose method, call it\n\t\tif ('dispose' in this.serverStats && typeof this.serverStats.dispose === 'function') {\n\t\t\tawait this.serverStats.dispose();\n\t\t}\n\n\t\t// Clear any cached data or connections if needed\n\t}\n\n\t/**\n\t * Ensures the client hasn't been disposed.\n\t */\n\tprivate ensureNotDisposed(): void {\n\t\tif (this.disposed) {\n\t\t\tthrow new RhinoComputeError(\n\t\t\t\t'GrasshopperClient has been disposed and cannot be used',\n\t\t\t\tErrorCodes.INVALID_STATE\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Validates and normalizes a compute configuration.\n\t *\n\t * @throws {RhinoComputeError} with code INVALID_CONFIG if configuration is invalid\n\t */\n\tprivate normalizeComputeConfig<T extends ComputeConfig | GrasshopperComputeConfig>(config: T): T {\n\t\tif (!config.serverUrl?.trim()) {\n\t\t\tthrow new RhinoComputeError('serverUrl is required', ErrorCodes.INVALID_CONFIG, {\n\t\t\t\tcontext: { receivedServerUrl: config.serverUrl }\n\t\t\t});\n\t\t}\n\n\t\t// Validate URL format\n\t\ttry {\n\t\t\tnew URL(config.serverUrl);\n\t\t} catch {\n\t\t\tthrow new RhinoComputeError('serverUrl must be a valid URL', ErrorCodes.INVALID_CONFIG, {\n\t\t\t\tcontext: { receivedServerUrl: config.serverUrl }\n\t\t\t});\n\t\t}\n\n\t\t// Validate that it's not the default public endpoint\n\t\tif (config.serverUrl === '' || config.serverUrl === 'https://compute.rhino3d.com/') {\n\t\t\tthrow new RhinoComputeError(\n\t\t\t\t'serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.',\n\t\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t\t{ context: { receivedServerUrl: config.serverUrl } }\n\t\t\t);\n\t\t}\n\n\t\treturn {\n\t\t\t...config,\n\t\t\tserverUrl: config.serverUrl.replace(/\\/+$/, ''), // Remove trailing slashes\n\t\t\tapiKey: config.apiKey,\n\t\t\tauthToken: config.authToken,\n\t\t\tdebug: config.debug ?? false,\n\t\t\tsuppressClientSideWarning: config.suppressClientSideWarning\n\t\t} as T;\n\t}\n}\n","import { RhinoComputeError, ErrorCodes, getLogger } from '@/core';\nimport { decodeBase64ToBinary } from '@/core/utils/encoding';\n\nimport { FileBaseInfo, FileData, ProcessedFile } from './types';\n\n/**\n * Extracts and processes files from compute response data without downloading them.\n * Returns an array of ProcessedFile objects that can be used programmatically.\n *\n * @param downloadableFiles - An array of FileData items from the compute response.\n * @param additionalFiles - Optional additional files to include (fetched from URLs).\n * @returns A Promise resolving to an array of ProcessedFile objects.\n * @throws Will throw an error if file processing fails.\n *\n * @example\n * const files = await extractFilesFromComputeResponse(fileData);\n * files.forEach(file => {\n * console.log(`File: ${file.fileName}, Size: ${file.content.length}`);\n * });\n */\nexport const extractFilesFromComputeResponse = async (\n\tdownloadableFiles: FileData[],\n\tadditionalFiles: FileBaseInfo[] | FileBaseInfo | null = null\n): Promise<ProcessedFile[]> => {\n\ttry {\n\t\treturn await processFiles(downloadableFiles, additionalFiles);\n\t} catch (err) {\n\t\tthrow new RhinoComputeError(\n\t\t\t'Failed to extract files from compute response',\n\t\t\tErrorCodes.INVALID_STATE,\n\t\t\t{\n\t\t\t\tcontext: { originalError: err instanceof Error ? err.message : String(err) },\n\t\t\t\toriginalError: err instanceof Error ? err : undefined\n\t\t\t}\n\t\t);\n\t}\n};\n\n/**\n * Downloads files from a compute response as a ZIP archive.\n * Packages multiple files into a single ZIP file and triggers a browser download.\n *\n * @param downloadableFiles - An array of FileData items from the compute response.\n * @param additionalFiles - Optional additional files to include in the ZIP (fetched from URLs).\n * @param fileFoldername - The name of the ZIP file (without extension).\n * @throws Will throw an error if the file handling or download fails.\n *\n * @example\n * await downloadDataFromComputeResponse(fileData, null, 'my-export');\n * // Downloads 'my-export.zip'\n */\nexport const downloadFileData = async (\n\tdownloadableFiles: FileData[],\n\tfileFoldername: string,\n\tadditionalFiles: FileBaseInfo[] | FileBaseInfo | null = null\n): Promise<void> => {\n\t// Check if we're in a browser environment\n\tif (typeof document === 'undefined' || typeof Blob === 'undefined') {\n\t\tthrow new RhinoComputeError(\n\t\t\t'File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).',\n\t\t\tErrorCodes.BROWSER_ONLY,\n\t\t\t{\n\t\t\t\tcontext: {\n\t\t\t\t\tenvironment: typeof window !== 'undefined' ? 'browser (SSR)' : 'Node.js',\n\t\t\t\t\tdocumentAvailable: typeof document !== 'undefined',\n\t\t\t\t\tblobAvailable: typeof Blob !== 'undefined'\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\ttry {\n\t\tconst processedFiles = await processFiles(downloadableFiles, additionalFiles);\n\t\tawait createAndDownloadZip(processedFiles, fileFoldername);\n\t} catch (err) {\n\t\t// Re-throw if it's already a RhinoComputeError\n\t\tif (err instanceof RhinoComputeError) {\n\t\t\tthrow err;\n\t\t}\n\t\tthrow new RhinoComputeError(\n\t\t\t'Failed to download files from compute response',\n\t\t\tErrorCodes.INVALID_STATE,\n\t\t\t{\n\t\t\t\tcontext: { originalError: err instanceof Error ? err.message : String(err) },\n\t\t\t\toriginalError: err instanceof Error ? err : undefined\n\t\t\t}\n\t\t);\n\t}\n};\n\n/**\n * Processes files from compute response data and additional files.\n * Converts base64-encoded data to binary and fetches additional files from URLs.\n *\n * @param dataItems - An array of FileData items to process.\n * @param additionalFiles - Optional additional files to fetch and include.\n * @returns A Promise resolving to an array of ProcessedFile objects.\n */\nconst processFiles = async (\n\tdataItems: FileData[],\n\tadditionalFiles: FileBaseInfo[] | FileBaseInfo | null\n): Promise<ProcessedFile[]> => {\n\tconst processedFiles: ProcessedFile[] = [];\n\n\t// Process compute response files\n\tdataItems.forEach((item) => {\n\t\tlet filePath = `${item.fileName}${item.fileType}`;\n\n\t\tif (item.subFolder && item.subFolder.trim() !== '') {\n\t\t\tfilePath = `${item.subFolder}/${filePath}`;\n\t\t}\n\n\t\tif (item.isBase64Encoded === true && item.data) {\n\t\t\tconst bites = decodeBase64ToBinary(item.data);\n\t\t\tprocessedFiles.push({\n\t\t\t\tfileName: `${item.fileName}${item.fileType}`,\n\t\t\t\tcontent: new Uint8Array(bites.buffer),\n\t\t\t\tpath: filePath\n\t\t\t});\n\t\t} else if (item.isBase64Encoded === false && item.data) {\n\t\t\tprocessedFiles.push({\n\t\t\t\tfileName: `${item.fileName}${item.fileType}`,\n\t\t\t\tcontent: item.data,\n\t\t\t\tpath: filePath\n\t\t\t});\n\t\t}\n\t});\n\n\tif (additionalFiles) {\n\t\tconst filesArray = Array.isArray(additionalFiles) ? additionalFiles : [additionalFiles];\n\t\tconst additionalProcessed = await Promise.all(\n\t\t\tfilesArray.map(async (file) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst response = await fetch(file.filePath);\n\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\tgetLogger().warn(`Failed to fetch additional file from URL: ${file.filePath}`);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\tconst fileBlob = await response.blob();\n\t\t\t\t\tconst arrayBuffer = await fileBlob.arrayBuffer();\n\t\t\t\t\treturn {\n\t\t\t\t\t\tfileName: file.fileName,\n\t\t\t\t\t\tcontent: new Uint8Array(arrayBuffer),\n\t\t\t\t\t\tpath: file.fileName\n\t\t\t\t\t} as ProcessedFile;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tgetLogger().error(`Error fetching additional file from URL: ${file.filePath}`, error);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t})\n\t\t);\n\n\t\tprocessedFiles.push(...additionalProcessed.filter((f): f is ProcessedFile => f !== null));\n\t}\n\n\treturn processedFiles;\n};\n\n/**\n * Creates a ZIP archive from processed files and triggers a browser download.\n *\n * @param files - An array of ProcessedFile objects to include in the ZIP.\n * @param zipName - The name of the ZIP file (without extension).\n * @returns A Promise that resolves when the ZIP is generated and download is triggered.\n */\nasync function createAndDownloadZip(files: ProcessedFile[], zipName: string): Promise<void> {\n\tconst { zipSync, strToU8 } = await import('fflate');\n\n\t// Convert files to fflate format\n\tconst zipData: Record<string, Uint8Array> = {};\n\tfiles.forEach((file) => {\n\t\tzipData[file.path] = typeof file.content === 'string' ? strToU8(file.content) : file.content;\n\t});\n\n\tconst zipped = zipSync(zipData, { level: 6 });\n\n\tconst blob = new Blob([zipped as BlobPart], { type: 'application/zip' });\n\tsaveFile(blob, `${zipName}.zip`);\n}\n\n/**\n * Saves a Blob object as a file in the user's browser.\n *\n * @param blob - The Blob object representing the file content.\n * @param filename - The name to give the downloaded file (including extension).\n * @throws {RhinoComputeError} If not running in a browser environment.\n */\nfunction saveFile(blob: Blob, filename: string) {\n\tif (typeof document === 'undefined') {\n\t\tthrow new RhinoComputeError(\n\t\t\t'saveFile requires a browser environment with DOM API access.',\n\t\t\tErrorCodes.BROWSER_ONLY,\n\t\t\t{\n\t\t\t\tcontext: { function: 'saveFile', requiredAPI: 'document' }\n\t\t\t}\n\t\t);\n\t}\n\n\tconst a = document.createElement('a');\n\ta.href = URL.createObjectURL(blob);\n\ta.download = filename;\n\ta.click();\n\tURL.revokeObjectURL(a.href);\n}\n"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkGIV3ZLXRcjs = require('./chunk-GIV3ZLXR.cjs');require('./chunk-QCHPQ22Y.cjs');var _chunkPE2FMBXDcjs = require('./chunk-PE2FMBXD.cjs');exports.GrasshopperClient = _chunkGIV3ZLXRcjs.a; exports.GrasshopperResponseProcessor = _chunkGIV3ZLXRcjs.d; exports.RhinoComputeError = _chunkPE2FMBXDcjs.e; exports.TreeBuilder = _chunkGIV3ZLXRcjs.j; exports.downloadFileData = _chunkGIV3ZLXRcjs.c; exports.extractFilesFromComputeResponse = _chunkGIV3ZLXRcjs.b; exports.fetchDefinitionIO = _chunkGIV3ZLXRcjs.h; exports.fetchParsedDefinitionIO = _chunkGIV3ZLXRcjs.i; exports.processInput = _chunkGIV3ZLXRcjs.f; exports.processInputs = _chunkGIV3ZLXRcjs.g; exports.solveGrasshopperDefinition = _chunkGIV3ZLXRcjs.e;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkYBPIKW2Acjs = require('./chunk-YBPIKW2A.cjs');require('./chunk-QCHPQ22Y.cjs');var _chunkPE2FMBXDcjs = require('./chunk-PE2FMBXD.cjs');exports.GrasshopperClient = _chunkYBPIKW2Acjs.a; exports.GrasshopperResponseProcessor = _chunkYBPIKW2Acjs.d; exports.RhinoComputeError = _chunkPE2FMBXDcjs.e; exports.TreeBuilder = _chunkYBPIKW2Acjs.j; exports.downloadFileData = _chunkYBPIKW2Acjs.c; exports.extractFilesFromComputeResponse = _chunkYBPIKW2Acjs.b; exports.fetchDefinitionIO = _chunkYBPIKW2Acjs.h; exports.fetchParsedDefinitionIO = _chunkYBPIKW2Acjs.i; exports.processInput = _chunkYBPIKW2Acjs.f; exports.processInputs = _chunkYBPIKW2Acjs.g; exports.solveGrasshopperDefinition = _chunkYBPIKW2Acjs.e;
2
2
  //# sourceMappingURL=grasshopper.cjs.map
@@ -1,2 +1,2 @@
1
- import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k}from"./chunk-3ECK2JAS.js";import"./chunk-WD3ENUAA.js";import{e as a}from"./chunk-MK3M76VN.js";export{b as GrasshopperClient,e as GrasshopperResponseProcessor,a as RhinoComputeError,k as TreeBuilder,d as downloadFileData,c as extractFilesFromComputeResponse,i as fetchDefinitionIO,j as fetchParsedDefinitionIO,g as processInput,h as processInputs,f as solveGrasshopperDefinition};
1
+ import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k}from"./chunk-3MVIRDAI.js";import"./chunk-WD3ENUAA.js";import{e as a}from"./chunk-MK3M76VN.js";export{b as GrasshopperClient,e as GrasshopperResponseProcessor,a as RhinoComputeError,k as TreeBuilder,d as downloadFileData,c as extractFilesFromComputeResponse,i as fetchDefinitionIO,j as fetchParsedDefinitionIO,g as processInput,h as processInputs,f as solveGrasshopperDefinition};
2
2
  //# sourceMappingURL=grasshopper.js.map
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkGIV3ZLXRcjs = require('./chunk-GIV3ZLXR.cjs');require('./chunk-QCHPQ22Y.cjs');var _chunkPE2FMBXDcjs = require('./chunk-PE2FMBXD.cjs');exports.ComputeServerStats = _chunkPE2FMBXDcjs.n; exports.ErrorCodes = _chunkPE2FMBXDcjs.d; exports.GrasshopperClient = _chunkGIV3ZLXRcjs.a; exports.GrasshopperResponseProcessor = _chunkGIV3ZLXRcjs.d; exports.RhinoComputeError = _chunkPE2FMBXDcjs.e; exports.TreeBuilder = _chunkGIV3ZLXRcjs.j; exports.downloadFileData = _chunkGIV3ZLXRcjs.c; exports.enableDebugLogging = _chunkPE2FMBXDcjs.k; exports.extractFilesFromComputeResponse = _chunkGIV3ZLXRcjs.b; exports.fetchDefinitionIO = _chunkGIV3ZLXRcjs.h; exports.fetchParsedDefinitionIO = _chunkGIV3ZLXRcjs.i; exports.fetchRhinoCompute = _chunkPE2FMBXDcjs.m; exports.getLogger = _chunkPE2FMBXDcjs.i; exports.processInput = _chunkGIV3ZLXRcjs.f; exports.processInputs = _chunkGIV3ZLXRcjs.g; exports.setLogger = _chunkPE2FMBXDcjs.j; exports.solveGrasshopperDefinition = _chunkGIV3ZLXRcjs.e;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkYBPIKW2Acjs = require('./chunk-YBPIKW2A.cjs');require('./chunk-QCHPQ22Y.cjs');var _chunkPE2FMBXDcjs = require('./chunk-PE2FMBXD.cjs');exports.ComputeServerStats = _chunkPE2FMBXDcjs.n; exports.ErrorCodes = _chunkPE2FMBXDcjs.d; exports.GrasshopperClient = _chunkYBPIKW2Acjs.a; exports.GrasshopperResponseProcessor = _chunkYBPIKW2Acjs.d; exports.RhinoComputeError = _chunkPE2FMBXDcjs.e; exports.TreeBuilder = _chunkYBPIKW2Acjs.j; exports.downloadFileData = _chunkYBPIKW2Acjs.c; exports.enableDebugLogging = _chunkPE2FMBXDcjs.k; exports.extractFilesFromComputeResponse = _chunkYBPIKW2Acjs.b; exports.fetchDefinitionIO = _chunkYBPIKW2Acjs.h; exports.fetchParsedDefinitionIO = _chunkYBPIKW2Acjs.i; exports.fetchRhinoCompute = _chunkPE2FMBXDcjs.m; exports.getLogger = _chunkPE2FMBXDcjs.i; exports.processInput = _chunkYBPIKW2Acjs.f; exports.processInputs = _chunkYBPIKW2Acjs.g; exports.setLogger = _chunkPE2FMBXDcjs.j; exports.solveGrasshopperDefinition = _chunkYBPIKW2Acjs.e;
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as x,b as a,c as b,d as c,e as d,f as g,g as h,h as i,i as j,j as k}from"./chunk-3ECK2JAS.js";import"./chunk-WD3ENUAA.js";import{d as o,e as r,i as e,j as f,k as m,m as p,n as t}from"./chunk-MK3M76VN.js";export{t as ComputeServerStats,o as ErrorCodes,x as GrasshopperClient,c as GrasshopperResponseProcessor,r as RhinoComputeError,k as TreeBuilder,b as downloadFileData,m as enableDebugLogging,a as extractFilesFromComputeResponse,i as fetchDefinitionIO,j as fetchParsedDefinitionIO,p as fetchRhinoCompute,e as getLogger,g as processInput,h as processInputs,f as setLogger,d as solveGrasshopperDefinition};
1
+ import{a as x,b as a,c as b,d as c,e as d,f as g,g as h,h as i,i as j,j as k}from"./chunk-3MVIRDAI.js";import"./chunk-WD3ENUAA.js";import{d as o,e as r,i as e,j as f,k as m,m as p,n as t}from"./chunk-MK3M76VN.js";export{t as ComputeServerStats,o as ErrorCodes,x as GrasshopperClient,c as GrasshopperResponseProcessor,r as RhinoComputeError,k as TreeBuilder,b as downloadFileData,m as enableDebugLogging,a as extractFilesFromComputeResponse,i as fetchDefinitionIO,j as fetchParsedDefinitionIO,p as fetchRhinoCompute,e as getLogger,g as processInput,h as processInputs,f as setLogger,d as solveGrasshopperDefinition};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkQCHPQ22Ycjs = require('./chunk-QCHPQ22Y.cjs');var _chunkPE2FMBXDcjs = require('./chunk-PE2FMBXD.cjs');var _three = require('three'); var i = _interopRequireWildcard(_three); var R = _interopRequireWildcard(_three); var E = _interopRequireWildcard(_three); var w = _interopRequireWildcard(_three);var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var V=new i.Vector3(0,0,1),k= exports.initThree =function(e,r){let t=X(r||{}),n=J(t),o=oe(t),a=ae(e,t),s=ie(o,e,t);te(n,t),ne(n,t),_optionalChain([t, 'access', _2 => _2.floor, 'optionalAccess', _3 => _3.enabled])&&re(n,t);let l=t.events.enableEventHandlers!==!1?se(e,n,o,s,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},{resize:c,dispose:T}=ee(e,a,o),{animate:m,dispose:h}=Q(a,n,o,s);m();let p=_optionalChain([t, 'access', _4 => _4.environment, 'optionalAccess', _5 => _5.sceneUp])||V;return n.up.set(p.x,p.y,p.z),{scene:n,camera:o,controls:s,renderer:a,dispose:()=>{h(),T(),l.dispose(),s.dispose(),a.dispose(),n.traverse(f=>{f instanceof i.Mesh&&(_optionalChain([f, 'access', _6 => _6.geometry, 'optionalAccess', _7 => _7.dispose, 'call', _8 => _8()]),Array.isArray(f.material)?f.material.forEach(v=>v.dispose()):_optionalChain([f, 'access', _9 => _9.material, 'optionalAccess', _10 => _10.dispose, 'call', _11 => _11()]))})},resize:c,fitToView:l.fitToView,clearSelection:l.clearSelection}};function X(e){let r=e.sceneScale||"m",n={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[r];return{sceneScale:r,camera:{position:_optionalChain([e, 'access', _12 => _12.camera, 'optionalAccess', _13 => _13.position])||new i.Vector3(-n.cameraDistance,n.cameraDistance,n.cameraDistance),fov:_optionalChain([e, 'access', _14 => _14.camera, 'optionalAccess', _15 => _15.fov])||20,near:_optionalChain([e, 'access', _16 => _16.camera, 'optionalAccess', _17 => _17.near])||n.near,far:_optionalChain([e, 'access', _18 => _18.camera, 'optionalAccess', _19 => _19.far])||n.far,target:_optionalChain([e, 'access', _20 => _20.camera, 'optionalAccess', _21 => _21.target])||new i.Vector3(0,0,0)},lighting:{enableSunlight:_nullishCoalesce(_optionalChain([e, 'access', _22 => _22.lighting, 'optionalAccess', _23 => _23.enableSunlight]), () => (!0)),sunlightIntensity:_optionalChain([e, 'access', _24 => _24.lighting, 'optionalAccess', _25 => _25.sunlightIntensity])||1,sunlightPosition:_optionalChain([e, 'access', _26 => _26.lighting, 'optionalAccess', _27 => _27.sunlightPosition])||new i.Vector3(n.lightDistance,n.lightHeight,n.lightDistance),ambientLightColor:_optionalChain([e, 'access', _28 => _28.lighting, 'optionalAccess', _29 => _29.ambientLightColor])||new i.Color(4210752),ambientLightIntensity:_optionalChain([e, 'access', _30 => _30.lighting, 'optionalAccess', _31 => _31.ambientLightIntensity])||1,sunlightColor:_optionalChain([e, 'access', _32 => _32.lighting, 'optionalAccess', _33 => _33.sunlightColor])||16777215},environment:{hdrPath:_optionalChain([e, 'access', _34 => _34.environment, 'optionalAccess', _35 => _35.hdrPath])||"/baseHDR.hdr",backgroundColor:_optionalChain([e, 'access', _36 => _36.environment, 'optionalAccess', _37 => _37.backgroundColor])||new i.Color(15790320),enableEnvironmentLighting:_nullishCoalesce(_optionalChain([e, 'access', _38 => _38.environment, 'optionalAccess', _39 => _39.enableEnvironmentLighting]), () => (!0)),sceneUp:_optionalChain([e, 'access', _40 => _40.environment, 'optionalAccess', _41 => _41.sceneUp])||V,showEnvironment:_nullishCoalesce(_optionalChain([e, 'access', _42 => _42.environment, 'optionalAccess', _43 => _43.showEnvironment]), () => (!1))},floor:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _44 => _44.floor, 'optionalAccess', _45 => _45.enabled]), () => (!1)),size:_optionalChain([e, 'access', _46 => _46.floor, 'optionalAccess', _47 => _47.size])||n.floorSize,color:_optionalChain([e, 'access', _48 => _48.floor, 'optionalAccess', _49 => _49.color])||new i.Color(8421504),roughness:_optionalChain([e, 'access', _50 => _50.floor, 'optionalAccess', _51 => _51.roughness])||.7,metalness:_optionalChain([e, 'access', _52 => _52.floor, 'optionalAccess', _53 => _53.metalness])||0,receiveShadow:_nullishCoalesce(_optionalChain([e, 'access', _54 => _54.floor, 'optionalAccess', _55 => _55.receiveShadow]), () => (!0))},render:{enableShadows:_nullishCoalesce(_optionalChain([e, 'access', _56 => _56.render, 'optionalAccess', _57 => _57.enableShadows]), () => (!0)),shadowMapSize:_optionalChain([e, 'access', _58 => _58.render, 'optionalAccess', _59 => _59.shadowMapSize])||2048,antialias:_nullishCoalesce(_optionalChain([e, 'access', _60 => _60.render, 'optionalAccess', _61 => _61.antialias]), () => (!0)),pixelRatio:_optionalChain([e, 'access', _62 => _62.render, 'optionalAccess', _63 => _63.pixelRatio])||Math.min(window.devicePixelRatio,2),toneMapping:_optionalChain([e, 'access', _64 => _64.render, 'optionalAccess', _65 => _65.toneMapping])||i.NeutralToneMapping,toneMappingExposure:_optionalChain([e, 'access', _66 => _66.render, 'optionalAccess', _67 => _67.toneMappingExposure])||1,preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _68 => _68.render, 'optionalAccess', _69 => _69.preserveDrawingBuffer]), () => (!1))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _70 => _70.controls, 'optionalAccess', _71 => _71.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _72 => _72.controls, 'optionalAccess', _73 => _73.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _74 => _74.controls, 'optionalAccess', _75 => _75.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _76 => _76.controls, 'optionalAccess', _77 => _77.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _78 => _78.controls, 'optionalAccess', _79 => _79.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _80 => _80.controls, 'optionalAccess', _81 => _81.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _82 => _82.controls, 'optionalAccess', _83 => _83.minDistance])||n.minDistance,maxDistance:_optionalChain([e, 'access', _84 => _84.controls, 'optionalAccess', _85 => _85.maxDistance])||1/0},events:{onBackgroundClicked:_optionalChain([e, 'access', _86 => _86.events, 'optionalAccess', _87 => _87.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _88 => _88.events, 'optionalAccess', _89 => _89.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _90 => _90.events, 'optionalAccess', _91 => _91.onMeshMetadataClicked]),selectionColor:_optionalChain([e, 'access', _92 => _92.events, 'optionalAccess', _93 => _93.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _94 => _94.events, 'optionalAccess', _95 => _95.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _96 => _96.events, 'optionalAccess', _97 => _97.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _98 => _98.events, 'optionalAccess', _99 => _99.enableClickToFocus]), () => (!0))}}}function J(e){let r=new i.Scene;r.children.forEach(n=>{n.userData.id!=="floor"&&r.remove(n)});let t=typeof e.environment.backgroundColor=="string"?new i.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=t||null,r}function Q(e,r,t,n){let o=null,a=function(){o=requestAnimationFrame(a),n.enableDamping&&n.update(),e.render(r,t)};return{animate:a,dispose:()=>{o!==null&&(cancelAnimationFrame(o),o=null)}}}function ee(e,r,t){let n=e.parentElement,o=null,a=null,s=()=>n?{width:n.clientWidth,height:n.clientHeight}:{width:window.innerWidth,height:window.innerHeight},l=()=>{let{width:m,height:h}=s();(r.domElement.width!==m||r.domElement.height!==h)&&(r.setSize(m,h,!1),t.aspect=m/h,t.updateProjectionMatrix())},c=()=>{o!==null&&cancelAnimationFrame(o),o=requestAnimationFrame(()=>{o=requestAnimationFrame(()=>{o=null,l()})})};return typeof ResizeObserver<"u"?(a=new ResizeObserver(c),n?a.observe(n):a.observe(e)):window.addEventListener("resize",c),{resize:c,dispose:()=>{o!==null&&(cancelAnimationFrame(o),o=null),a?a.disconnect():window.removeEventListener("resize",c)}}}function te(e,r){r.environment.enableEnvironmentLighting&&new (0, _HDRLoaderjs.HDRLoader)().load(r.environment.hdrPath||"/baseHDR.hdr",function(t){t.mapping=i.EquirectangularReflectionMapping,e.environment=t,r.environment.showEnvironment&&(e.background=t)},void 0,function(t){_chunkPE2FMBXDcjs.i.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",t);let n=new i.AmbientLight(4210752,.4);e.add(n)})}function ne(e,r){let t=new i.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(t),r.lighting.enableSunlight){let n=new i.DirectionalLight(_nullishCoalesce(r.lighting.sunlightColor, () => (16777215)),r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;if(o&&n.position.set(o.x,o.y,o.z),r.render.enableShadows){n.castShadow=!0;let a=r.sceneScale==="mm"?.1:r.sceneScale==="cm"?10:100;n.shadow.camera.left=-a,n.shadow.camera.right=a,n.shadow.camera.top=a,n.shadow.camera.bottom=-a;let s=r.sceneScale==="mm"?.001:r.sceneScale==="cm"?.1:.5,l=r.sceneScale==="mm"?1:r.sceneScale==="cm"?100:500;n.shadow.camera.near=s,n.shadow.camera.far=l,n.shadow.mapSize.width=r.render.shadowMapSize||2048,n.shadow.mapSize.height=r.render.shadowMapSize||2048,n.shadow.bias=-1e-4,n.shadow.normalBias=.02}e.add(n)}}function re(e,r){let t=r.floor.size,n=new i.PlaneGeometry(t,t),o=typeof r.floor.color=="string"?new i.Color(r.floor.color):r.floor.color,a=new i.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:i.DoubleSide}),s=new i.Mesh(n,a);s.userData.id="floor",s.name="floor",s.rotation.x=-Math.PI/2,s.position.y=0,r.floor.receiveShadow&&r.render.enableShadows&&(s.receiveShadow=!0),e.add(s)}function oe(e){let t=_optionalChain([document, 'access', _100 => _100.querySelector, 'call', _101 => _101("canvas"), 'optionalAccess', _102 => _102.parentElement]),n=t?t.clientWidth:window.innerWidth,o=t?t.clientHeight:window.innerHeight,a=new i.PerspectiveCamera(e.camera.fov,n/o,e.camera.near,e.camera.far),s=e.camera.position;return s&&a.position.set(s.x,s.y,s.z),a}function ae(e,r){let t=new i.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),n=e.parentElement,o=n?n.clientWidth:window.innerWidth,a=n?n.clientHeight:window.innerHeight;return n&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),t.setSize(o,a,!1),t.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(t.shadowMap.enabled=!0,t.shadowMap.type=i.VSMShadowMap),t.toneMapping=r.render.toneMapping||i.ACESFilmicToneMapping,t.toneMappingExposure=r.render.toneMappingExposure||1,t.outputColorSpace=i.SRGBColorSpace,t.sortObjects=!0,t}function se(e,r,t,n,o){let a=new Set,s=new Map,l=new i.Raycaster,c=new i.Vector2,T=new i.Vector2,m=()=>{let d=new i.Box3;if(r.traverse(L=>{L.visible&&L.userData.id!=="floor"&&L instanceof i.Mesh&&d.expandByObject(L)}),d.isEmpty()){_chunkPE2FMBXDcjs.i.call(void 0, ).warn("No objects to fit to view");return}let b=d.getCenter(new i.Vector3),g=d.getSize(new i.Vector3),O=Math.max(g.x,g.y,g.z),y=t.fov*(Math.PI/180),S=O/(2*Math.tan(y/2));S*=1.5;let q=t.position.clone().sub(n.target).normalize();t.position.copy(b.clone().add(q.multiplyScalar(S))),n.target.copy(b),n.update()},h=typeof o.events.selectionColor=="string"?new i.Color(o.events.selectionColor):o.events.selectionColor instanceof i.Color?o.events.selectionColor:new i.Color("#ff0000"),p=()=>{a.forEach(d=>{d instanceof i.Mesh&&s.has(d)&&(d.material=s.get(d),s.delete(d))}),a.clear()},x=d=>{T.set(d.clientX,d.clientY)},f=d=>{let b=new i.Vector2(d.clientX,d.clientY);if(T.distanceTo(b)>5)return;let g=e.getBoundingClientRect();c.x=(d.clientX-g.left)/g.width*2-1,c.y=-((d.clientY-g.top)/g.height)*2+1,l.setFromCamera(c,t);let O=l.intersectObjects(r.children,!0);if(O.length>0){let y=O[0].object;if(!a.has(y)){if(p(),a.add(y),y instanceof i.Mesh&&y.material instanceof i.Material){s.set(y,y.material);let S=y.material.clone();S.emissive=h.clone(),y.material=S}_optionalChain([o, 'access', _103 => _103.events, 'optionalAccess', _104 => _104.onObjectSelected, 'optionalCall', _105 => _105(y)]),y instanceof i.Mesh&&Object.keys(y.userData).length>0&&_optionalChain([o, 'access', _106 => _106.events, 'optionalAccess', _107 => _107.onMeshMetadataClicked, 'optionalCall', _108 => _108(y.userData)])}}else p(),_optionalChain([o, 'access', _109 => _109.events, 'optionalAccess', _110 => _110.onBackgroundClicked, 'optionalCall', _111 => _111({x:c.x,y:c.y})])},v=d=>{if(_optionalChain([o, 'access', _112 => _112.events, 'optionalAccess', _113 => _113.enableKeyboardControls]))switch(d.key.toLowerCase()){case"f":d.preventDefault(),m();break;case"escape":d.preventDefault(),p();break;case" ":d.preventDefault(),m();break}};return _optionalChain([o, 'access', _114 => _114.events, 'optionalAccess', _115 => _115.enableClickToFocus])&&(e.addEventListener("mousedown",x),e.addEventListener("click",f)),_optionalChain([o, 'access', _116 => _116.events, 'optionalAccess', _117 => _117.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",v)),{dispose:()=>{e.removeEventListener("mousedown",x),e.removeEventListener("click",f),e.removeEventListener("keydown",v),p()},fitToView:m,clearSelection:p}}function ie(e,r,t){let n=new (0, _OrbitControlsjs.OrbitControls)(e,r),o=t.camera.target;return o&&n.target.set(o.x,o.y,o.z),n.enableDamping=t.controls.enableDamping||!1,n.dampingFactor=t.controls.dampingFactor||.05,n.autoRotate=t.controls.autoRotate||!1,n.autoRotateSpeed=t.controls.autoRotateSpeed||.5,n.enableZoom=t.controls.enableZoom||!0,n.enablePan=t.controls.enablePan||!0,n.minDistance=t.controls.minDistance||.001,n.maxDistance=t.controls.maxDistance||1/0,n.screenSpacePanning=!1,n.maxPolarAngle=Math.PI,n.update(),n}var H={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},InitialDistanceMultiplier:4};function G(e,r,t,n,o){if(ce(e),r.length===0)return;r.forEach(m=>{e.add(m)});let a=D(r),s=a.getCenter(new R.Vector3),l=a.getSize(new R.Vector3),c=Math.max(l.x,l.y,l.z);if(c/Math.min(l.x||1,l.y||1,l.z||1)>H.SCALE_RATIO_THRESHOLD||c>H.HUGE_THRESHOLD?(t.near=c*H.NEAR_PLANE_FACTOR.TINY,t.far=c*H.FAR_PLANE_FACTOR.HUGE):c>H.LARGE_THRESHOLD?(t.near=c*H.NEAR_PLANE_FACTOR.SMALL,t.far=c*H.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,c*H.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,c*H.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),o)n.minDistance=t.near*2,n.maxDistance=t.far*.9;else{let m=c*H.InitialDistanceMultiplier;t.position.set(s.x+m*.8,s.y+m,s.z+m*1.2),n.target.copy(s),n.minDistance=t.near*2,n.maxDistance=t.far*.9,n.update()}}function I(e){if(!e||typeof e!="string")return _chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new R.Color(16777215);let r=e.trim();if(r.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(r))try{let t=r.startsWith("#")?r:`#${r}`;return new R.Color(t)}catch (e2){return _chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new R.Color(16777215)}if(r.includes(",")){let t=r.split(",").map(n=>parseInt(n.trim(),10));if(t.length===3&&t.every(n=>!isNaN(n)&&n>=0&&n<=255))return new R.Color(t[0]/255,t[1]/255,t[2]/255)}try{return new R.Color(r.toLowerCase())}catch (e3){return _chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new R.Color(16777215)}}function B(e,r){e.forEach(t=>{t.position.y-=r,t.updateMatrix()})}function D(e){let r=new R.Box3;return e.forEach(t=>{t.updateMatrixWorld(!0);let n=new R.Box3().setFromObject(t);r.union(n)}),r}function ce(e){let r=[];e.traverse(t=>{t instanceof R.Mesh&&t.userData.id!=="floor"&&r.push(t)}),r.forEach(t=>{t instanceof R.Mesh&&(_optionalChain([t, 'access', _118 => _118.geometry, 'optionalAccess', _119 => _119.dispose, 'call', _120 => _120()]),(Array.isArray(t.material)?t.material:[t.material]).forEach(o=>{for(let a in o){let s=o[a];s&&s instanceof R.Texture&&s.dispose()}o.dispose()})),t.removeFromParent()})}var F={};_chunkPE2FMBXDcjs.a.call(void 0, F,{CONCRETE_MATERIAL:()=>de,EMISSIVE_MATERIAL:()=>le,GLASS_MATERIAL:()=>me,METAL_MATERIAL:()=>fe,PLASTIC_MATERIAL:()=>he,RUBBER_MATERIAL:()=>Ee,WOOD_MATERIAL:()=>ue});var le=new E.MeshPhysicalMaterial({color:0,emissive:new E.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:E.FrontSide,dithering:!0}),fe=new E.MeshPhysicalMaterial({color:new E.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:E.FrontSide,dithering:!0}),de=new E.MeshPhysicalMaterial({color:new E.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:E.FrontSide,dithering:!0}),he=new E.MeshPhysicalMaterial({color:new E.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:E.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),me=new E.MeshPhysicalMaterial({color:new E.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:E.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Ee=new E.MeshPhysicalMaterial({color:new E.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:E.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),ue=new E.MeshPhysicalMaterial({color:new E.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:E.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});var _fflate = require('fflate'); var U = _interopRequireWildcard(_fflate);_chunkPE2FMBXDcjs.h.call(void 0, );async function W(e){return new Promise((r,t)=>{try{let n=()=>{try{let o=_chunkQCHPQ22Ycjs.c.call(void 0, e),a=U.gunzipSync(o),s=pe(a);r(s)}catch(o){t(new (0, _chunkPE2FMBXDcjs.e)(o instanceof _chunkPE2FMBXDcjs.e?o.message:`Failed to decompress batched data: ${o instanceof Error?o.message:String(o)}`,o instanceof _chunkPE2FMBXDcjs.e?o.code:_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{base64StringLength:e.length},originalError:o instanceof Error?o:new Error(String(o))}))}};"requestIdleCallback"in globalThis?globalThis.requestIdleCallback(n,{timeout:5e3}):setTimeout(n,0)}catch(n){t(new (0, _chunkPE2FMBXDcjs.e)(`Failed to schedule decompression: ${n instanceof Error?n.message:String(n)}`,_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{originalError:n instanceof Error?n:new Error(String(n))}))}})}function pe(e){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),t=0;if(t+4>r.byteLength)throw new (0, _chunkPE2FMBXDcjs.e)("Insufficient data to read the number of vertex floats.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{expectedBytes:4,availableBytes:r.byteLength,offset:t}});let n=r.getUint32(t,!0);if(t+=4,n%3!==0)throw new (0, _chunkPE2FMBXDcjs.e)("Invalid number of vertex floats; should be divisible by 3.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{numVertexFloats:n,remainder:n%3,totalBytes:r.byteLength}});let o=n*Float32Array.BYTES_PER_ELEMENT;if(t+o>r.byteLength)throw new (0, _chunkPE2FMBXDcjs.e)("Insufficient data to read vertices.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{expectedBytes:o,availableBytes:r.byteLength-t,offset:t}});let a=new Float32Array(e.buffer,e.byteOffset+t,n);if(t+=o,t+4>r.byteLength)throw new (0, _chunkPE2FMBXDcjs.e)("Insufficient data to read the number of face indices.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{expectedBytes:4,availableBytes:r.byteLength-t,offset:t}});let s=r.getUint32(t,!0);t+=4;let l=s*Uint32Array.BYTES_PER_ELEMENT;if(t+l>r.byteLength)throw new (0, _chunkPE2FMBXDcjs.e)("Insufficient data to read face indices.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{expectedBytes:l,availableBytes:r.byteLength-t,offset:t}});let c=new Uint32Array(e.buffer,e.byteOffset+t,s);return{vertices:a,faces:c}}async function z(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,debug:o=!1}=_nullishCoalesce(r, () => ({})),a=o?performance.now():0,s=0;try{let l=performance.now(),c=JSON.parse(e);return s=performance.now()-l,await P(c,{mergeByMaterial:t,applyTransforms:n,debug:o,parseTime:s,perfStart:a})}catch(l){return _chunkPE2FMBXDcjs.i.call(void 0, ).error("Error parsing mesh batch:",l),[]}}async function P(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,scaleFactor:o=1,debug:a=!1,parseTime:s=0,perfStart:l=a?performance.now():0}=_nullishCoalesce(r, () => ({})),c=0,T=0;try{let m=performance.now(),{vertices:h,faces:p}=await W(e.compressedData);c=performance.now()-m;let x=(e.compressedData.length*.75/1024/1024).toFixed(2),f=((h.byteLength+p.byteLength)/1024/1024).toFixed(2),v=((1-parseFloat(x)/parseFloat(f))*100).toFixed(1);a&&(_chunkPE2FMBXDcjs.i.call(void 0, ).debug("Mesh Batch Stats:"),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Materials: ${e.materials.length} | Groups: ${e.groups.length}`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Vertices: ${(h.length/3).toLocaleString()} | Faces: ${(p.length/3).toLocaleString()}`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Compressed: ${x} MB | Uncompressed: ${f} MB`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Compression Ratio: ${v}%`)),n&&we(h);let A=performance.now(),d=e.materials.map(ge),b=[];for(let g of e.groups)if(t&&g.meshes.length>1){let O=Re(g,h,p,d);b.push(O)}else{let O=Te(g,h,p,d);b.push(...O)}if(o!==1)for(let g of b)g.scale.set(o,o,o);if(T=performance.now()-A,a){let g=performance.now()-l;_chunkPE2FMBXDcjs.i.call(void 0, ).debug("Performance:"),s>0&&_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Parse JSON: ${s.toFixed(2)}ms`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Decompress: ${c.toFixed(2)}ms`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Create Meshes: ${T.toFixed(2)}ms`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Total: ${g.toFixed(2)}ms`)}return b}catch(m){return _chunkPE2FMBXDcjs.i.call(void 0, ).error("Error parsing mesh batch object:",m),[]}}function ge(e){let r=I(e.color);return new w.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:w.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function Re(e,r,t,n){let o=new w.BufferGeometry,a=0,s=0;for(let f of e.meshes)a+=f.vertexCount,s+=f.faceCount;let l=new Float32Array(a),c=new Uint32Array(s),T=0,m=0;for(let f of e.meshes){l.set(r.subarray(f.vertexOffset,f.vertexOffset+f.vertexCount),T);let v=t.subarray(f.faceOffset,f.faceOffset+f.faceCount),A=Math.floor(f.vertexOffset/3),b=Math.floor(T/3)-A;for(let g=0;g<v.length;g++)c[m+g]=v[g]+b;T+=f.vertexCount,m+=f.faceCount}o.setAttribute("position",new w.BufferAttribute(l,3)),o.setIndex(new w.BufferAttribute(c,1)),o.computeVertexNormals();let h=new w.Mesh(o,n[e.materialId]),p=e.meshes.map(f=>f.name).filter(f=>f&&f.length>0);h.name=p.length>0?p[0]:`merged_material_${e.materialId}`,h.castShadow=!0,h.receiveShadow=!0;let x=e.meshes.map(f=>f.metadata).filter(f=>f);return x.length>0&&(h.userData.mergedMetadata=x),h}function Te(e,r,t,n){let o=[];for(let a of e.meshes){let s=new w.BufferGeometry,l=r.subarray(a.vertexOffset,a.vertexOffset+a.vertexCount),c=t.subarray(a.faceOffset,a.faceOffset+a.faceCount),T=Math.floor(a.vertexOffset/3),m=new Uint32Array(c.length);for(let p=0;p<c.length;p++)m[p]=c[p]-T;s.setAttribute("position",new w.BufferAttribute(l,3)),s.setIndex(new w.BufferAttribute(m,1)),s.computeVertexNormals();let h=new w.Mesh(s,n[e.materialId]);h.name=a.name,a.metadata&&(h.userData={...h.userData,...a.metadata}),h.castShadow=!0,h.receiveShadow=!0,o.push(h)}return o}function we(e){let r=Math.cos(-Math.PI/2),t=Math.sin(-Math.PI/2);for(let n=0;n<e.length;n+=3){let o=e[n],a=e[n+1],s=e[n+2];e[n]=o,e[n+1]=a*r-s*t,e[n+2]=a*t+s*r}}var _={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},ye="Display";async function $(e,r){let t=performance.now(),n=[],{allowScaling:o=!0,allowAutoPosition:a=!0,debug:s=!1,parsing:l={}}=_nullishCoalesce(r, () => ({}));try{let c=o?be(e.modelunits):1;return await Me(e,n,c,l,s),a&&xe(n),n}catch(c){throw ve(c,n),c}finally{s&&Ce(t)}}function be(e){return _nullishCoalesce(_[e], () => (1))}async function Me(e,r,t,n,o){for(let a of e.values){let s=a.InnerTree;for(let l in s){let c=s[l];c&&await He(c,r,t,n,o)}}}async function He(e,r,t,n,o){for(let a of e)if(a.type.includes(ye)){let s={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...n},l=await z(a.data,s);if(t!==1)for(let c of l)c.scale.set(t,t,t);r.push(...l),o&&_chunkPE2FMBXDcjs.i.call(void 0, ).debug(`Extracted ${l.length} meshes from batch`)}}function xe(e){if(e.length===0)return;let t=D(e).min.y;B(e,t)}function ve(e,r){_chunkPE2FMBXDcjs.i.call(void 0, ).error("An unexpected error occurred:",e),Oe(r)}function Oe(e){for(let r of e)r.geometry&&r.geometry.dispose(),r.material&&(Array.isArray(r.material)?r.material.forEach(t=>t.dispose()):r.material.dispose())}function Ce(e){let r=performance.now()-e;_chunkPE2FMBXDcjs.i.call(void 0, ).info("Time to process meshes:",`${r.toFixed(2)}ms`)}exports.Materials = F; exports.SCALE_FACTORS = _; exports.getThreeMeshesFromComputeResponse = $; exports.initThree = k; exports.parseMeshBatchObject = P; exports.updateScene = G;
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 _chunkQCHPQ22Ycjs = require('./chunk-QCHPQ22Y.cjs');var _chunkPE2FMBXDcjs = require('./chunk-PE2FMBXD.cjs');var _three = require('three'); var i = _interopRequireWildcard(_three); var w = _interopRequireWildcard(_three); var u = _interopRequireWildcard(_three); var b = _interopRequireWildcard(_three);var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var G=new i.Vector3(0,0,1),U= exports.initThree =function(e,r){let t=ne(r||{}),n=re(t),o=fe(t,e),s=de(e,t),a=me(o,e,t);ie(n,t),ce(n,t),_optionalChain([t, 'access', _2 => _2.floor, 'optionalAccess', _3 => _3.enabled])&&le(n,t);let l=t.events.enableEventHandlers!==!1?he(e,n,o,a,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},{resize:c,dispose:R}=ae(e,s,o),{animate:m,dispose:h}=se(s,n,o,a);m();let E=_optionalChain([t, 'access', _4 => _4.environment, 'optionalAccess', _5 => _5.sceneUp])||G;return n.up.set(E.x,E.y,E.z),{scene:n,camera:o,controls:a,renderer:s,dispose:()=>{h(),R(),l.dispose(),a.dispose(),s.dispose(),n.traverse(f=>{f instanceof i.Mesh&&(_optionalChain([f, 'access', _6 => _6.geometry, 'optionalAccess', _7 => _7.dispose, 'call', _8 => _8()]),Array.isArray(f.material)?f.material.forEach(H=>H.dispose()):_optionalChain([f, 'access', _9 => _9.material, 'optionalAccess', _10 => _10.dispose, 'call', _11 => _11()]))})},resize:c,fitToView:l.fitToView,clearSelection:l.clearSelection}};function ne(e){let r=e.sceneScale||"m",n={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[r];return{sceneScale:r,camera:{position:_optionalChain([e, 'access', _12 => _12.camera, 'optionalAccess', _13 => _13.position])||new i.Vector3(-n.cameraDistance,n.cameraDistance,n.cameraDistance),fov:_optionalChain([e, 'access', _14 => _14.camera, 'optionalAccess', _15 => _15.fov])||20,near:_optionalChain([e, 'access', _16 => _16.camera, 'optionalAccess', _17 => _17.near])||n.near,far:_optionalChain([e, 'access', _18 => _18.camera, 'optionalAccess', _19 => _19.far])||n.far,target:_optionalChain([e, 'access', _20 => _20.camera, 'optionalAccess', _21 => _21.target])||new i.Vector3(0,0,0)},lighting:{enableSunlight:_nullishCoalesce(_optionalChain([e, 'access', _22 => _22.lighting, 'optionalAccess', _23 => _23.enableSunlight]), () => (!0)),sunlightIntensity:_optionalChain([e, 'access', _24 => _24.lighting, 'optionalAccess', _25 => _25.sunlightIntensity])||1,sunlightPosition:_optionalChain([e, 'access', _26 => _26.lighting, 'optionalAccess', _27 => _27.sunlightPosition])||new i.Vector3(n.lightDistance,n.lightHeight,n.lightDistance),ambientLightColor:_optionalChain([e, 'access', _28 => _28.lighting, 'optionalAccess', _29 => _29.ambientLightColor])||new i.Color(4210752),ambientLightIntensity:_optionalChain([e, 'access', _30 => _30.lighting, 'optionalAccess', _31 => _31.ambientLightIntensity])||1,sunlightColor:_optionalChain([e, 'access', _32 => _32.lighting, 'optionalAccess', _33 => _33.sunlightColor])||16777215},environment:{hdrPath:_optionalChain([e, 'access', _34 => _34.environment, 'optionalAccess', _35 => _35.hdrPath])||"/baseHDR.hdr",backgroundColor:_optionalChain([e, 'access', _36 => _36.environment, 'optionalAccess', _37 => _37.backgroundColor])||new i.Color(15790320),enableEnvironmentLighting:_nullishCoalesce(_optionalChain([e, 'access', _38 => _38.environment, 'optionalAccess', _39 => _39.enableEnvironmentLighting]), () => (!0)),sceneUp:_optionalChain([e, 'access', _40 => _40.environment, 'optionalAccess', _41 => _41.sceneUp])||G,showEnvironment:_nullishCoalesce(_optionalChain([e, 'access', _42 => _42.environment, 'optionalAccess', _43 => _43.showEnvironment]), () => (!1))},floor:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _44 => _44.floor, 'optionalAccess', _45 => _45.enabled]), () => (!1)),size:_optionalChain([e, 'access', _46 => _46.floor, 'optionalAccess', _47 => _47.size])||n.floorSize,color:_optionalChain([e, 'access', _48 => _48.floor, 'optionalAccess', _49 => _49.color])||new i.Color(8421504),roughness:_optionalChain([e, 'access', _50 => _50.floor, 'optionalAccess', _51 => _51.roughness])||.7,metalness:_optionalChain([e, 'access', _52 => _52.floor, 'optionalAccess', _53 => _53.metalness])||0,receiveShadow:_nullishCoalesce(_optionalChain([e, 'access', _54 => _54.floor, 'optionalAccess', _55 => _55.receiveShadow]), () => (!0))},render:{enableShadows:_nullishCoalesce(_optionalChain([e, 'access', _56 => _56.render, 'optionalAccess', _57 => _57.enableShadows]), () => (!0)),shadowMapSize:_optionalChain([e, 'access', _58 => _58.render, 'optionalAccess', _59 => _59.shadowMapSize])||2048,antialias:_nullishCoalesce(_optionalChain([e, 'access', _60 => _60.render, 'optionalAccess', _61 => _61.antialias]), () => (!0)),pixelRatio:_optionalChain([e, 'access', _62 => _62.render, 'optionalAccess', _63 => _63.pixelRatio])||Math.min(window.devicePixelRatio,2),toneMapping:_optionalChain([e, 'access', _64 => _64.render, 'optionalAccess', _65 => _65.toneMapping])||i.NeutralToneMapping,toneMappingExposure:_optionalChain([e, 'access', _66 => _66.render, 'optionalAccess', _67 => _67.toneMappingExposure])||1,preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _68 => _68.render, 'optionalAccess', _69 => _69.preserveDrawingBuffer]), () => (!1))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _70 => _70.controls, 'optionalAccess', _71 => _71.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _72 => _72.controls, 'optionalAccess', _73 => _73.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _74 => _74.controls, 'optionalAccess', _75 => _75.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _76 => _76.controls, 'optionalAccess', _77 => _77.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _78 => _78.controls, 'optionalAccess', _79 => _79.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _80 => _80.controls, 'optionalAccess', _81 => _81.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _82 => _82.controls, 'optionalAccess', _83 => _83.minDistance])||n.minDistance,maxDistance:_optionalChain([e, 'access', _84 => _84.controls, 'optionalAccess', _85 => _85.maxDistance])||1/0},events:{onBackgroundClicked:_optionalChain([e, 'access', _86 => _86.events, 'optionalAccess', _87 => _87.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _88 => _88.events, 'optionalAccess', _89 => _89.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _90 => _90.events, 'optionalAccess', _91 => _91.onMeshMetadataClicked]),onMeshDoubleClicked:_optionalChain([e, 'access', _92 => _92.events, 'optionalAccess', _93 => _93.onMeshDoubleClicked]),selectionColor:_optionalChain([e, 'access', _94 => _94.events, 'optionalAccess', _95 => _95.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _96 => _96.events, 'optionalAccess', _97 => _97.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _98 => _98.events, 'optionalAccess', _99 => _99.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _100 => _100.events, 'optionalAccess', _101 => _101.enableClickToFocus]), () => (!0)),enableDoubleClickZoom:_nullishCoalesce(_optionalChain([e, 'access', _102 => _102.events, 'optionalAccess', _103 => _103.enableDoubleClickZoom]), () => (!0))}}}function re(e){let r=new i.Scene,t=typeof e.environment.backgroundColor=="string"?new i.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=t||null,r}function oe(e,r,t,n,o=200){let s=e.position.clone(),a=r.target.clone(),l=performance.now(),c=m=>1-Math.pow(1-m,3),R=()=>{let m=performance.now()-l,h=c(Math.min(m/o,1));e.position.lerpVectors(s,t,h),r.target.lerpVectors(a,n,h),r.update(),h<1&&requestAnimationFrame(R)};requestAnimationFrame(R)}function se(e,r,t,n){let o=null,s=function(){o=requestAnimationFrame(s),(n.enableDamping||n.autoRotate)&&n.update(),e.render(r,t)};return{animate:s,dispose:()=>{o!==null&&(cancelAnimationFrame(o),o=null)}}}function ae(e,r,t){let n=e.parentElement,o=null,s=null,a=()=>n?{width:n.clientWidth,height:n.clientHeight}:{width:window.innerWidth,height:window.innerHeight},l=()=>{let{width:m,height:h}=a();if(m===0||h===0)return;let E=Math.min(window.devicePixelRatio,2),M=Math.round(r.domElement.clientWidth*E),f=Math.round(r.domElement.clientHeight*E),H=Math.round(m*E),C=Math.round(h*E);(M!==H||f!==C)&&(r.setPixelRatio(E),r.setSize(m,h,!0),t.aspect=m/h,t.updateProjectionMatrix())},c=()=>{o!==null&&cancelAnimationFrame(o),o=requestAnimationFrame(()=>{o=requestAnimationFrame(()=>{o=null,l()})})};return typeof ResizeObserver<"u"?(s=new ResizeObserver(c),n?s.observe(n):s.observe(e)):window.addEventListener("resize",c),{resize:c,dispose:()=>{o!==null&&(cancelAnimationFrame(o),o=null),s?s.disconnect():window.removeEventListener("resize",c)}}}function ie(e,r){r.environment.enableEnvironmentLighting&&new (0, _HDRLoaderjs.HDRLoader)().load(r.environment.hdrPath||"/baseHDR.hdr",function(t){t.mapping=i.EquirectangularReflectionMapping,e.environment=t,r.environment.showEnvironment&&(e.background=t)},void 0,function(t){_chunkPE2FMBXDcjs.i.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",t)})}function ce(e,r){let t=new i.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(t),r.lighting.enableSunlight){let n=new i.DirectionalLight(_nullishCoalesce(r.lighting.sunlightColor, () => (16777215)),r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;if(o&&n.position.set(o.x,o.y,o.z),r.render.enableShadows){n.castShadow=!0;let s=r.sceneScale==="mm"?.1:r.sceneScale==="cm"?10:100;n.shadow.camera.left=-s,n.shadow.camera.right=s,n.shadow.camera.top=s,n.shadow.camera.bottom=-s;let a=r.sceneScale==="mm"?.001:r.sceneScale==="cm"?.1:.5,l=r.sceneScale==="mm"?1:r.sceneScale==="cm"?100:500;n.shadow.camera.near=a,n.shadow.camera.far=l,n.shadow.mapSize.width=r.render.shadowMapSize||2048,n.shadow.mapSize.height=r.render.shadowMapSize||2048,n.shadow.bias=-1e-4,n.shadow.normalBias=.02}e.add(n)}}function le(e,r){let t=r.floor.size,n=new i.PlaneGeometry(t,t),o=typeof r.floor.color=="string"?new i.Color(r.floor.color):r.floor.color,s=new i.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:i.DoubleSide}),a=new i.Mesh(n,s);a.userData.id="floor",a.name="floor",a.rotation.x=-Math.PI/2,a.position.y=0,r.floor.receiveShadow&&r.render.enableShadows&&(a.receiveShadow=!0),e.add(a)}function fe(e,r){let t=r.parentElement,n=t?t.clientWidth:window.innerWidth,o=t?t.clientHeight:window.innerHeight,s=new i.PerspectiveCamera(e.camera.fov,n/o,e.camera.near,e.camera.far),a=e.camera.position;return a&&s.position.set(a.x,a.y,a.z),s}function de(e,r){let t=new i.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),n=e.parentElement,o=n?n.clientWidth:window.innerWidth,s=n?n.clientHeight:window.innerHeight;return n&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),t.setSize(o,s,!0),t.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(t.shadowMap.enabled=!0,t.shadowMap.type=i.VSMShadowMap),t.toneMapping=r.render.toneMapping||i.ACESFilmicToneMapping,t.toneMappingExposure=r.render.toneMappingExposure||1,t.outputColorSpace=i.SRGBColorSpace,t.sortObjects=!0,t}function he(e,r,t,n,o){let s=new Set,a=new Map,l=new i.Raycaster,c=new i.Vector2,R=new i.Vector2,m=()=>{let d=new i.Box3;if(r.traverse(D=>{D.visible&&D.userData.id!=="floor"&&D instanceof i.Mesh&&d.expandByObject(D)}),d.isEmpty()){_chunkPE2FMBXDcjs.i.call(void 0, ).warn("No objects to fit to view");return}let g=d.getCenter(new i.Vector3),y=d.getSize(new i.Vector3),A=Math.max(y.x,y.y,y.z),T=t.fov*(Math.PI/180),O=A/(2*Math.tan(T/2));O*=1.5;let L=t.position.clone().sub(n.target).normalize();t.position.copy(g.clone().add(L.multiplyScalar(O))),n.target.copy(g),n.update()},h=typeof o.events.selectionColor=="string"?new i.Color(o.events.selectionColor):o.events.selectionColor instanceof i.Color?o.events.selectionColor:new i.Color("#ff0000"),E=()=>{s.forEach(d=>{d instanceof i.Mesh&&a.has(d)&&(d.material=a.get(d),a.delete(d))}),s.clear()},M=d=>{R.set(d.clientX,d.clientY)},f=d=>{let g=new i.Vector2(d.clientX,d.clientY);if(R.distanceTo(g)>5)return;let y=e.getBoundingClientRect();c.x=(d.clientX-y.left)/y.width*2-1,c.y=-((d.clientY-y.top)/y.height)*2+1,l.setFromCamera(c,t);let A=l.intersectObjects(r.children,!0);if(A.length>0){let T=A[0].object;if(!s.has(T)){if(E(),s.add(T),T instanceof i.Mesh&&T.material instanceof i.Material){a.set(T,T.material);let O=T.material.clone();O.emissive=h.clone(),T.material=O}_optionalChain([o, 'access', _104 => _104.events, 'optionalAccess', _105 => _105.onObjectSelected, 'optionalCall', _106 => _106(T)]),T instanceof i.Mesh&&Object.keys(T.userData).length>0&&_optionalChain([o, 'access', _107 => _107.events, 'optionalAccess', _108 => _108.onMeshMetadataClicked, 'optionalCall', _109 => _109(T.userData)])}}else E(),_optionalChain([o, 'access', _110 => _110.events, 'optionalAccess', _111 => _111.onBackgroundClicked, 'optionalCall', _112 => _112({x:c.x,y:c.y})])},H=d=>{let g=e.getBoundingClientRect();c.x=(d.clientX-g.left)/g.width*2-1,c.y=-((d.clientY-g.top)/g.height)*2+1,l.setFromCamera(c,t);let y=l.intersectObjects(r.children,!0);if(y.length===0)return;let A=y[0].object;if(_optionalChain([o, 'access', _113 => _113.events, 'optionalAccess', _114 => _114.onMeshDoubleClicked, 'optionalCall', _115 => _115(A)]),!_optionalChain([o, 'access', _116 => _116.events, 'optionalAccess', _117 => _117.enableDoubleClickZoom]))return;let T=new i.Box3().setFromObject(A);if(T.isEmpty())return;let O=T.getCenter(new i.Vector3),L=T.getSize(new i.Vector3),D=Math.max(L.x,L.y,L.z),j=t.fov*(Math.PI/180),Z=D/(2*Math.tan(j/2))*1.5,K=t.position.clone().sub(n.target).normalize(),X=O.clone().add(K.multiplyScalar(Z));oe(t,n,X,O)},C=d=>{if(_optionalChain([o, 'access', _118 => _118.events, 'optionalAccess', _119 => _119.enableKeyboardControls]))switch(d.key.toLowerCase()){case"f":d.preventDefault(),m();break;case"escape":d.preventDefault(),E();break;case" ":d.preventDefault(),m();break}};return _optionalChain([o, 'access', _120 => _120.events, 'optionalAccess', _121 => _121.enableClickToFocus])&&(e.addEventListener("mousedown",M),e.addEventListener("click",f),e.addEventListener("dblclick",H)),_optionalChain([o, 'access', _122 => _122.events, 'optionalAccess', _123 => _123.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",C)),{dispose:()=>{e.removeEventListener("mousedown",M),e.removeEventListener("click",f),e.removeEventListener("dblclick",H),e.removeEventListener("keydown",C),E()},fitToView:m,clearSelection:E}}function me(e,r,t){let n=new (0, _OrbitControlsjs.OrbitControls)(e,r),o=t.camera.target;return o&&n.target.set(o.x,o.y,o.z),n.enableDamping=t.controls.enableDamping||!1,n.dampingFactor=t.controls.dampingFactor||.05,n.autoRotate=t.controls.autoRotate||!1,n.autoRotateSpeed=t.controls.autoRotateSpeed||.5,n.enableZoom=_nullishCoalesce(t.controls.enableZoom, () => (!0)),n.enablePan=_nullishCoalesce(t.controls.enablePan, () => (!0)),n.minDistance=t.controls.minDistance||.001,n.maxDistance=t.controls.maxDistance||1/0,n.screenSpacePanning=!1,n.maxPolarAngle=Math.PI,n.update(),n}var v={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},InitialDistanceMultiplier:4};function W(e,r,t,n,o){if(Ee(e),r.length===0)return;r.forEach(m=>{e.add(m)});let s=B(r),a=s.getCenter(new w.Vector3),l=s.getSize(new w.Vector3),c=Math.max(l.x,l.y,l.z);if(c/Math.min(l.x||1,l.y||1,l.z||1)>v.SCALE_RATIO_THRESHOLD||c>v.HUGE_THRESHOLD?(t.near=c*v.NEAR_PLANE_FACTOR.TINY,t.far=c*v.FAR_PLANE_FACTOR.HUGE):c>v.LARGE_THRESHOLD?(t.near=c*v.NEAR_PLANE_FACTOR.SMALL,t.far=c*v.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,c*v.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,c*v.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),o)n.minDistance=t.near*2,n.maxDistance=t.far*.9;else{let m=c*v.InitialDistanceMultiplier;t.position.set(a.x+m*.8,a.y+m,a.z+m*1.2),n.target.copy(a),n.minDistance=t.near*2,n.maxDistance=t.far*.9,n.update()}}function F(e){if(!e||typeof e!="string")return _chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new w.Color(16777215);let r=e.trim();if(r.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(r))try{let t=r.startsWith("#")?r:`#${r}`;return new w.Color(t)}catch (e2){return _chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new w.Color(16777215)}if(r.includes(",")){let t=r.split(",").map(n=>parseInt(n.trim(),10));if(t.length===3&&t.every(n=>!isNaN(n)&&n>=0&&n<=255))return new w.Color(t[0]/255,t[1]/255,t[2]/255)}try{return new w.Color(r.toLowerCase())}catch (e3){return _chunkPE2FMBXDcjs.i.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new w.Color(16777215)}}function P(e,r){e.forEach(t=>{t.position.y-=r,t.updateMatrix()})}function B(e){let r=new w.Box3;return e.forEach(t=>{t.updateMatrixWorld(!0);let n=new w.Box3().setFromObject(t);r.union(n)}),r}function Ee(e){let r=[];e.traverse(t=>{t instanceof w.Mesh&&t.userData.id!=="floor"&&r.push(t)}),r.forEach(t=>{t instanceof w.Mesh&&(_optionalChain([t, 'access', _124 => _124.geometry, 'optionalAccess', _125 => _125.dispose, 'call', _126 => _126()]),(Array.isArray(t.material)?t.material:[t.material]).forEach(o=>{for(let s in o){let a=o[s];a&&a instanceof w.Texture&&a.dispose()}o.dispose()})),t.removeFromParent()})}var z={};_chunkPE2FMBXDcjs.a.call(void 0, z,{CONCRETE_MATERIAL:()=>ge,EMISSIVE_MATERIAL:()=>ue,GLASS_MATERIAL:()=>Te,METAL_MATERIAL:()=>pe,PLASTIC_MATERIAL:()=>Re,RUBBER_MATERIAL:()=>we,WOOD_MATERIAL:()=>ye});var ue=new u.MeshPhysicalMaterial({color:0,emissive:new u.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:u.FrontSide,dithering:!0}),pe=new u.MeshPhysicalMaterial({color:new u.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:u.FrontSide,dithering:!0}),ge=new u.MeshPhysicalMaterial({color:new u.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:u.FrontSide,dithering:!0}),Re=new u.MeshPhysicalMaterial({color:new u.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:u.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Te=new u.MeshPhysicalMaterial({color:new u.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:u.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),we=new u.MeshPhysicalMaterial({color:new u.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:u.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),ye=new u.MeshPhysicalMaterial({color:new u.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:u.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});var _fflate = require('fflate'); var $ = _interopRequireWildcard(_fflate);_chunkPE2FMBXDcjs.h.call(void 0, );async function q(e){return new Promise((r,t)=>{try{let n=()=>{try{let o=_chunkQCHPQ22Ycjs.c.call(void 0, e),s=$.gunzipSync(o),a=be(s);r(a)}catch(o){t(new (0, _chunkPE2FMBXDcjs.e)(o instanceof _chunkPE2FMBXDcjs.e?o.message:`Failed to decompress batched data: ${o instanceof Error?o.message:String(o)}`,o instanceof _chunkPE2FMBXDcjs.e?o.code:_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{base64StringLength:e.length},originalError:o instanceof Error?o:new Error(String(o))}))}};"requestIdleCallback"in globalThis?globalThis.requestIdleCallback(n,{timeout:5e3}):setTimeout(n,0)}catch(n){t(new (0, _chunkPE2FMBXDcjs.e)(`Failed to schedule decompression: ${n instanceof Error?n.message:String(n)}`,_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{originalError:n instanceof Error?n:new Error(String(n))}))}})}function be(e){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),t=0;if(t+4>r.byteLength)throw new (0, _chunkPE2FMBXDcjs.e)("Insufficient data to read the number of vertex floats.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{expectedBytes:4,availableBytes:r.byteLength,offset:t}});let n=r.getUint32(t,!0);if(t+=4,n%3!==0)throw new (0, _chunkPE2FMBXDcjs.e)("Invalid number of vertex floats; should be divisible by 3.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{numVertexFloats:n,remainder:n%3,totalBytes:r.byteLength}});let o=n*Float32Array.BYTES_PER_ELEMENT;if(t+o>r.byteLength)throw new (0, _chunkPE2FMBXDcjs.e)("Insufficient data to read vertices.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{expectedBytes:o,availableBytes:r.byteLength-t,offset:t}});let s=new Float32Array(e.buffer,e.byteOffset+t,n);if(t+=o,t+4>r.byteLength)throw new (0, _chunkPE2FMBXDcjs.e)("Insufficient data to read the number of face indices.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{expectedBytes:4,availableBytes:r.byteLength-t,offset:t}});let a=r.getUint32(t,!0);t+=4;let l=a*Uint32Array.BYTES_PER_ELEMENT;if(t+l>r.byteLength)throw new (0, _chunkPE2FMBXDcjs.e)("Insufficient data to read face indices.",_chunkPE2FMBXDcjs.d.VALIDATION_ERROR,{context:{expectedBytes:l,availableBytes:r.byteLength-t,offset:t}});let c=new Uint32Array(e.buffer,e.byteOffset+t,a);return{vertices:s,faces:c}}async function _(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,debug:o=!1}=_nullishCoalesce(r, () => ({})),s=o?performance.now():0,a=0;try{let l=performance.now(),c=JSON.parse(e);return a=performance.now()-l,await V(c,{mergeByMaterial:t,applyTransforms:n,debug:o,parseTime:a,perfStart:s})}catch(l){return _chunkPE2FMBXDcjs.i.call(void 0, ).error("Error parsing mesh batch:",l),[]}}async function V(e,r){let{mergeByMaterial:t=!0,applyTransforms:n=!0,scaleFactor:o=1,debug:s=!1,parseTime:a=0,perfStart:l=s?performance.now():0}=_nullishCoalesce(r, () => ({})),c=0,R=0;try{let m=performance.now(),{vertices:h,faces:E}=await q(e.compressedData);c=performance.now()-m;let M=(e.compressedData.length*.75/1024/1024).toFixed(2),f=((h.byteLength+E.byteLength)/1024/1024).toFixed(2),H=((1-parseFloat(M)/parseFloat(f))*100).toFixed(1);s&&(_chunkPE2FMBXDcjs.i.call(void 0, ).debug("Mesh Batch Stats:"),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Materials: ${e.materials.length} | Groups: ${e.groups.length}`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Vertices: ${(h.length/3).toLocaleString()} | Faces: ${(E.length/3).toLocaleString()}`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Compressed: ${M} MB | Uncompressed: ${f} MB`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Compression Ratio: ${H}%`)),n&&ve(h);let C=performance.now(),I=e.materials.map(Me),d=[];for(let g of e.groups)if(t&&g.meshes.length>1){let y=He(g,h,E,I);d.push(y)}else{let y=xe(g,h,E,I);d.push(...y)}if(o!==1)for(let g of d)g.scale.set(o,o,o);if(R=performance.now()-C,s){let g=performance.now()-l;_chunkPE2FMBXDcjs.i.call(void 0, ).debug("Performance:"),a>0&&_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Parse JSON: ${a.toFixed(2)}ms`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Decompress: ${c.toFixed(2)}ms`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Create Meshes: ${R.toFixed(2)}ms`),_chunkPE2FMBXDcjs.i.call(void 0, ).debug(` Total: ${g.toFixed(2)}ms`)}return d}catch(m){return _chunkPE2FMBXDcjs.i.call(void 0, ).error("Error parsing mesh batch object:",m),[]}}function Me(e){let r=F(e.color);return new b.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:b.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function He(e,r,t,n){let o=new b.BufferGeometry,s=0,a=0;for(let f of e.meshes)s+=f.vertexCount,a+=f.faceCount;let l=new Float32Array(s),c=new Uint32Array(a),R=0,m=0;for(let f of e.meshes){l.set(r.subarray(f.vertexOffset,f.vertexOffset+f.vertexCount),R);let H=t.subarray(f.faceOffset,f.faceOffset+f.faceCount),C=Math.floor(f.vertexOffset/3),d=Math.floor(R/3)-C;for(let g=0;g<H.length;g++)c[m+g]=H[g]+d;R+=f.vertexCount,m+=f.faceCount}o.setAttribute("position",new b.BufferAttribute(l,3)),o.setIndex(new b.BufferAttribute(c,1)),o.computeVertexNormals();let h=new b.Mesh(o,n[e.materialId]),E=e.meshes.map(f=>f.name).filter(f=>f&&f.length>0);h.name=E.length>0?E[0]:`merged_material_${e.materialId}`,h.castShadow=!0,h.receiveShadow=!0;let M=e.meshes.map(f=>f.metadata).filter(f=>f);return M.length>0&&(h.userData.mergedMetadata=M),h}function xe(e,r,t,n){let o=[];for(let s of e.meshes){let a=new b.BufferGeometry,l=r.subarray(s.vertexOffset,s.vertexOffset+s.vertexCount),c=t.subarray(s.faceOffset,s.faceOffset+s.faceCount),R=Math.floor(s.vertexOffset/3),m=new Uint32Array(c.length);for(let E=0;E<c.length;E++)m[E]=c[E]-R;a.setAttribute("position",new b.BufferAttribute(l,3)),a.setIndex(new b.BufferAttribute(m,1)),a.computeVertexNormals();let h=new b.Mesh(a,n[e.materialId]);h.name=s.name,s.metadata&&(h.userData={...h.userData,...s.metadata}),h.castShadow=!0,h.receiveShadow=!0,o.push(h)}return o}function ve(e){let r=Math.cos(-Math.PI/2),t=Math.sin(-Math.PI/2);for(let n=0;n<e.length;n+=3){let o=e[n],s=e[n+1],a=e[n+2];e[n]=o,e[n+1]=s*r-a*t,e[n+2]=s*t+a*r}}var k={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},Ce="Display";async function Y(e,r){let t=performance.now(),n=[],{allowScaling:o=!0,allowAutoPosition:s=!0,debug:a=!1,parsing:l={}}=_nullishCoalesce(r, () => ({}));try{let c=o?Oe(e.modelunits):1;return await Se(e,n,c,l,a),s&&De(n),n}catch(c){throw Le(c,n),c}finally{a&&Be(t)}}function Oe(e){return _nullishCoalesce(k[e], () => (1))}async function Se(e,r,t,n,o){for(let s of e.values){let a=s.InnerTree;for(let l in a){let c=a[l];c&&await Ae(c,r,t,n,o)}}}async function Ae(e,r,t,n,o){for(let s of e)if(s.type.includes(Ce)){let a={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...n},l=await _(s.data,a);if(t!==1)for(let c of l)c.scale.set(t,t,t);r.push(...l),o&&_chunkPE2FMBXDcjs.i.call(void 0, ).debug(`Extracted ${l.length} meshes from batch`)}}function De(e){if(e.length===0)return;let t=B(e).min.y;P(e,t)}function Le(e,r){_chunkPE2FMBXDcjs.i.call(void 0, ).error("An unexpected error occurred:",e),Ie(r)}function Ie(e){for(let r of e)r.geometry&&r.geometry.dispose(),r.material&&(Array.isArray(r.material)?r.material.forEach(t=>t.dispose()):r.material.dispose())}function Be(e){let r=performance.now()-e;_chunkPE2FMBXDcjs.i.call(void 0, ).info("Time to process meshes:",`${r.toFixed(2)}ms`)}exports.Materials = z; exports.SCALE_FACTORS = k; exports.getThreeMeshesFromComputeResponse = Y; exports.initThree = U; exports.parseMeshBatchObject = V; exports.updateScene = W;
2
2
  //# sourceMappingURL=visualization.cjs.map