@selvajs/compute 3.0.0-beta.0 → 3.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-6LCAIDQV.cjs +4 -0
- package/dist/{chunk-2QHLW6ZL.cjs.map → chunk-6LCAIDQV.cjs.map} +1 -1
- package/dist/{chunk-BF7OQEQG.cjs → chunk-FHX52FTY.cjs} +2 -2
- package/dist/{chunk-BF7OQEQG.cjs.map → chunk-FHX52FTY.cjs.map} +1 -1
- package/dist/{chunk-SA67IFJH.cjs → chunk-KS4A7AEU.cjs} +3 -3
- package/dist/{chunk-SA67IFJH.cjs.map → chunk-KS4A7AEU.cjs.map} +1 -1
- package/dist/chunk-O55PTKMV.js +4 -0
- package/dist/chunk-O55PTKMV.js.map +1 -0
- package/dist/{chunk-HKU2XHQQ.js → chunk-V5KVO4JJ.js} +2 -2
- package/dist/{chunk-WHB32TTR.js → chunk-X7RGK5IZ.js} +2 -2
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +24 -1
- package/dist/core.d.ts +24 -1
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/{visualization-N3OJSZOY.js → visualization-3VKXKTBW.js} +2 -2
- package/dist/visualization-H4P23BWC.cjs +2 -0
- package/dist/{visualization-UOIWXLDL.cjs.map → visualization-H4P23BWC.cjs.map} +1 -1
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-2KAHGLXE.js +0 -4
- package/dist/chunk-2KAHGLXE.js.map +0 -1
- package/dist/chunk-2QHLW6ZL.cjs +0 -4
- package/dist/visualization-UOIWXLDL.cjs +0 -2
- /package/dist/{chunk-HKU2XHQQ.js.map → chunk-V5KVO4JJ.js.map} +0 -0
- /package/dist/{chunk-WHB32TTR.js.map → chunk-X7RGK5IZ.js.map} +0 -0
- /package/dist/{visualization-N3OJSZOY.js.map → visualization-3VKXKTBW.js.map} +0 -0
package/dist/core.d.ts
CHANGED
|
@@ -92,4 +92,27 @@ declare function setLogger(logger: Logger | Console | null): void;
|
|
|
92
92
|
*/
|
|
93
93
|
declare function enableDebugLogging(): void;
|
|
94
94
|
|
|
95
|
-
|
|
95
|
+
/**
|
|
96
|
+
* Converts a string to camelCase.
|
|
97
|
+
* @param str - The string to convert
|
|
98
|
+
* @param options - Options object
|
|
99
|
+
* - preserveSpaces: If true, spaces are preserved (default: false)
|
|
100
|
+
*/
|
|
101
|
+
declare function toCamelCase(str: string, options?: {
|
|
102
|
+
preserveSpaces?: boolean;
|
|
103
|
+
}): string;
|
|
104
|
+
/**
|
|
105
|
+
* Recursively converts all object keys to camelCase.
|
|
106
|
+
* @param obj - The object to process
|
|
107
|
+
* @param options - Options object
|
|
108
|
+
* - deep: If true, process deeply
|
|
109
|
+
* - preserveSpaces: If true, spaces are preserved in keys
|
|
110
|
+
* @returns The new object with camelCased keys
|
|
111
|
+
* @internal
|
|
112
|
+
*/
|
|
113
|
+
declare function camelcaseKeys(obj: unknown, options?: {
|
|
114
|
+
deep?: boolean;
|
|
115
|
+
preserveSpaces?: boolean;
|
|
116
|
+
}): unknown;
|
|
117
|
+
|
|
118
|
+
export { ComputeConfig, type Logger, camelcaseKeys, enableDebugLogging, fetchRhinoCompute, getLogger, setLogger, toCamelCase };
|
package/dist/core.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as a,d as b,e as c,f as d,g as e,h as f,j as g,
|
|
1
|
+
import{c as a,d as b,e as c,f as d,g as e,h as f,j as g,k as h,l as i,q as j,r as k}from"./chunk-O55PTKMV.js";export{g as ComputeServerStats,a as ErrorCodes,b as RhinoComputeError,i as camelcaseKeys,k as downloadFileData,e as enableDebugLogging,j as extractFilesFromComputeResponse,f as fetchRhinoCompute,c as getLogger,d as setLogger,h as toCamelCase};
|
|
2
2
|
//# sourceMappingURL=core.js.map
|
package/dist/grasshopper.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkFHX52FTYcjs = require('./chunk-FHX52FTY.cjs');var _chunk6LCAIDQVcjs = require('./chunk-6LCAIDQV.cjs');exports.GrasshopperClient = _chunkFHX52FTYcjs.c; exports.GrasshopperResponseProcessor = _chunkFHX52FTYcjs.d; exports.RhinoComputeError = _chunk6LCAIDQVcjs.d; exports.SolveScheduler = _chunkFHX52FTYcjs.b; exports.TreeBuilder = _chunkFHX52FTYcjs.i; exports.downloadFileData = _chunk6LCAIDQVcjs.r; exports.extractFilesFromComputeResponse = _chunk6LCAIDQVcjs.q; exports.fetchDefinitionIO = _chunkFHX52FTYcjs.g; exports.fetchParsedDefinitionIO = _chunkFHX52FTYcjs.h; exports.processInput = _chunkFHX52FTYcjs.e; exports.processInputs = _chunkFHX52FTYcjs.f; exports.solveGrasshopperDefinition = _chunkFHX52FTYcjs.a;
|
|
2
2
|
//# sourceMappingURL=grasshopper.cjs.map
|
package/dist/grasshopper.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as d,b as e,c as f,d as g,e as h,f as i,g as j,h as k,i as l}from"./chunk-
|
|
1
|
+
import{a as d,b as e,c as f,d as g,e as h,f as i,g as j,h as k,i as l}from"./chunk-X7RGK5IZ.js";import{d as a,q as b,r as c}from"./chunk-O55PTKMV.js";export{f as GrasshopperClient,g as GrasshopperResponseProcessor,a as RhinoComputeError,e as SolveScheduler,l as TreeBuilder,c as downloadFileData,b as extractFilesFromComputeResponse,j as fetchDefinitionIO,k as fetchParsedDefinitionIO,h as processInput,i as processInputs,d 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
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkFHX52FTYcjs = require('./chunk-FHX52FTY.cjs');var _chunk6LCAIDQVcjs = require('./chunk-6LCAIDQV.cjs');exports.ComputeServerStats = _chunk6LCAIDQVcjs.j; exports.ErrorCodes = _chunk6LCAIDQVcjs.c; exports.GrasshopperClient = _chunkFHX52FTYcjs.c; exports.GrasshopperResponseProcessor = _chunkFHX52FTYcjs.d; exports.RhinoComputeError = _chunk6LCAIDQVcjs.d; exports.SolveScheduler = _chunkFHX52FTYcjs.b; exports.TreeBuilder = _chunkFHX52FTYcjs.i; exports.camelcaseKeys = _chunk6LCAIDQVcjs.l; exports.downloadFileData = _chunk6LCAIDQVcjs.r; exports.enableDebugLogging = _chunk6LCAIDQVcjs.g; exports.extractFilesFromComputeResponse = _chunk6LCAIDQVcjs.q; exports.fetchDefinitionIO = _chunkFHX52FTYcjs.g; exports.fetchParsedDefinitionIO = _chunkFHX52FTYcjs.h; exports.fetchRhinoCompute = _chunk6LCAIDQVcjs.h; exports.getLogger = _chunk6LCAIDQVcjs.e; exports.processInput = _chunkFHX52FTYcjs.e; exports.processInputs = _chunkFHX52FTYcjs.f; exports.setLogger = _chunk6LCAIDQVcjs.f; exports.solveGrasshopperDefinition = _chunkFHX52FTYcjs.a; exports.toCamelCase = _chunk6LCAIDQVcjs.k;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/index.cjs"],"names":[],"mappings":"AAAA,iIAAgG,
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/index.cjs"],"names":[],"mappings":"AAAA,iIAAgG,wDAAqG,y8BAA0c","file":"/home/runner/work/selva-compute/selva-compute/dist/index.cjs"}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { Logger, enableDebugLogging, fetchRhinoCompute, getLogger, setLogger } from './core.cjs';
|
|
1
|
+
export { Logger, camelcaseKeys, enableDebugLogging, fetchRhinoCompute, getLogger, setLogger, toCamelCase } from './core.cjs';
|
|
2
2
|
export { C as ComputeServerStats, E as ErrorCode, a as ErrorCodes, F as FileBaseInfo, b as FileData, P as ProcessedFile, R as RhinoComputeError, d as downloadFileData, e as extractFilesFromComputeResponse } from './handle-files-Bu2qmaPj.cjs';
|
|
3
3
|
export { C as ComputeConfig, R as RetryPolicy, a as RhinoModelUnit, S as ServerTiming } from './types-ChF690kY.cjs';
|
|
4
4
|
export { CacheOptions, DataTreeValue, GetValuesOptions, GetValuesResult, GrasshopperClient, GrasshopperResponseProcessor, ParsedContext, SchedulerMode, SolveContext, SolveOptions, SolveResult, SolveScheduler, SolveSchedulerOptions, TreeBuilder, fetchDefinitionIO, fetchParsedDefinitionIO, processInput, processInputs, solveGrasshopperDefinition } from './grasshopper.cjs';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { Logger, enableDebugLogging, fetchRhinoCompute, getLogger, setLogger } from './core.js';
|
|
1
|
+
export { Logger, camelcaseKeys, enableDebugLogging, fetchRhinoCompute, getLogger, setLogger, toCamelCase } from './core.js';
|
|
2
2
|
export { C as ComputeServerStats, E as ErrorCode, a as ErrorCodes, F as FileBaseInfo, b as FileData, P as ProcessedFile, R as RhinoComputeError, d as downloadFileData, e as extractFilesFromComputeResponse } from './handle-files-Bu2qmaPj.js';
|
|
3
3
|
export { C as ComputeConfig, R as RetryPolicy, a as RhinoModelUnit, S as ServerTiming } from './types-ChF690kY.js';
|
|
4
4
|
export { CacheOptions, DataTreeValue, GetValuesOptions, GetValuesResult, GrasshopperClient, GrasshopperResponseProcessor, ParsedContext, SchedulerMode, SolveContext, SolveOptions, SolveResult, SolveScheduler, SolveSchedulerOptions, TreeBuilder, fetchDefinitionIO, fetchParsedDefinitionIO, processInput, processInputs, solveGrasshopperDefinition } from './grasshopper.js';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as d,b as g,c as h,d as i,e as j,f as k,g as l,h as n,i as q}from"./chunk-X7RGK5IZ.js";import{c as o,d as r,e,f,g as m,h as p,j as t,k as x,l as a,q as b,r as c}from"./chunk-O55PTKMV.js";export{t as ComputeServerStats,o as ErrorCodes,h as GrasshopperClient,i as GrasshopperResponseProcessor,r as RhinoComputeError,g as SolveScheduler,q as TreeBuilder,a as camelcaseKeys,c as downloadFileData,m as enableDebugLogging,b as extractFilesFromComputeResponse,l as fetchDefinitionIO,n as fetchParsedDefinitionIO,p as fetchRhinoCompute,e as getLogger,j as processInput,k as processInputs,f as setLogger,d as solveGrasshopperDefinition,x as toCamelCase};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as u,a as e,b as r,c as o,d as t,e as a,f as s,g as i,h as p,i as n,j as m,k as l,l as f,m as y,n as d,o as h,p as x,q as C,r as g,s as M,t as c,u as B,v as j,w as E,x as O,y as D,z as b}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=visualization-
|
|
1
|
+
import{A as u,a as e,b as r,c as o,d as t,e as a,f as s,g as i,h as p,i as n,j as m,k as l,l as f,m as y,n as d,o as h,p as x,q as C,r as g,s as M,t as c,u as B,v as j,w as E,x as O,y as D,z as b}from"./chunk-V5KVO4JJ.js";import"./chunk-O55PTKMV.js";export{M as BINARY_MESH_MAGIC,c as BINARY_MESH_VERSION,p as EDGE_USERDATA_KIND,B as FLAG_FLOAT32,C as Materials,b as SCALE_FACTORS,n as addEdges,o as applyOffset,t as computeCombinedBoundingBox,a as createCameraController,s as createGrid,y as createLabelLayer,h as createMeasureTool,f as createRenderPipeline,i as createViewGizmo,u as getThreeMeshesFromComputeResponse,x as initThree,m as isEdgeOverlay,j as parseBinaryMeshBatch,r as parseColor,g as parseDisplayItems,E as parseMeshBatch,D as parseMeshBatchBlob,O as parseMeshBatchObject,l as removeEdges,d as snapToVertex,e as updateScene};
|
|
2
|
+
//# sourceMappingURL=visualization-3VKXKTBW.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkKS4A7AEUcjs = require('./chunk-KS4A7AEU.cjs');require('./chunk-6LCAIDQV.cjs');exports.BINARY_MESH_MAGIC = _chunkKS4A7AEUcjs.s; exports.BINARY_MESH_VERSION = _chunkKS4A7AEUcjs.t; exports.EDGE_USERDATA_KIND = _chunkKS4A7AEUcjs.h; exports.FLAG_FLOAT32 = _chunkKS4A7AEUcjs.u; exports.Materials = _chunkKS4A7AEUcjs.q; exports.SCALE_FACTORS = _chunkKS4A7AEUcjs.z; exports.addEdges = _chunkKS4A7AEUcjs.i; exports.applyOffset = _chunkKS4A7AEUcjs.c; exports.computeCombinedBoundingBox = _chunkKS4A7AEUcjs.d; exports.createCameraController = _chunkKS4A7AEUcjs.e; exports.createGrid = _chunkKS4A7AEUcjs.f; exports.createLabelLayer = _chunkKS4A7AEUcjs.m; exports.createMeasureTool = _chunkKS4A7AEUcjs.o; exports.createRenderPipeline = _chunkKS4A7AEUcjs.l; exports.createViewGizmo = _chunkKS4A7AEUcjs.g; exports.getThreeMeshesFromComputeResponse = _chunkKS4A7AEUcjs.A; exports.initThree = _chunkKS4A7AEUcjs.p; exports.isEdgeOverlay = _chunkKS4A7AEUcjs.j; exports.parseBinaryMeshBatch = _chunkKS4A7AEUcjs.v; exports.parseColor = _chunkKS4A7AEUcjs.b; exports.parseDisplayItems = _chunkKS4A7AEUcjs.r; exports.parseMeshBatch = _chunkKS4A7AEUcjs.w; exports.parseMeshBatchBlob = _chunkKS4A7AEUcjs.y; exports.parseMeshBatchObject = _chunkKS4A7AEUcjs.x; exports.removeEdges = _chunkKS4A7AEUcjs.k; exports.snapToVertex = _chunkKS4A7AEUcjs.n; exports.updateScene = _chunkKS4A7AEUcjs.a;
|
|
2
|
+
//# sourceMappingURL=visualization-H4P23BWC.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/visualization-
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/visualization-H4P23BWC.cjs"],"names":[],"mappings":"AAAA,iIAA8N,gCAA6B,owCAA+kB","file":"/home/runner/work/selva-compute/selva-compute/dist/visualization-H4P23BWC.cjs"}
|
package/dist/visualization.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkKS4A7AEUcjs = require('./chunk-KS4A7AEU.cjs');require('./chunk-6LCAIDQV.cjs');exports.EDGE_USERDATA_KIND = _chunkKS4A7AEUcjs.h; exports.Materials = _chunkKS4A7AEUcjs.q; exports.SCALE_FACTORS = _chunkKS4A7AEUcjs.z; exports.addEdges = _chunkKS4A7AEUcjs.i; exports.applyOffset = _chunkKS4A7AEUcjs.c; exports.computeCombinedBoundingBox = _chunkKS4A7AEUcjs.d; exports.createCameraController = _chunkKS4A7AEUcjs.e; exports.createGrid = _chunkKS4A7AEUcjs.f; exports.createLabelLayer = _chunkKS4A7AEUcjs.m; exports.createMeasureTool = _chunkKS4A7AEUcjs.o; exports.createRenderPipeline = _chunkKS4A7AEUcjs.l; exports.createViewGizmo = _chunkKS4A7AEUcjs.g; exports.getThreeMeshesFromComputeResponse = _chunkKS4A7AEUcjs.A; exports.initThree = _chunkKS4A7AEUcjs.p; exports.isEdgeOverlay = _chunkKS4A7AEUcjs.j; exports.parseColor = _chunkKS4A7AEUcjs.b; exports.parseDisplayItems = _chunkKS4A7AEUcjs.r; exports.parseMeshBatchBlob = _chunkKS4A7AEUcjs.y; exports.parseMeshBatchObject = _chunkKS4A7AEUcjs.x; exports.removeEdges = _chunkKS4A7AEUcjs.k; exports.snapToVertex = _chunkKS4A7AEUcjs.n; exports.updateScene = _chunkKS4A7AEUcjs.a;
|
|
2
2
|
//# sourceMappingURL=visualization.cjs.map
|
package/dist/visualization.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as j,a as e,b as r,c as t,d as o,e as i,f as a,g as s,h as p,i as n,j as l,k as f,l as m,m as y,n as u,o as d,p as x,q as C,r as g,x as h,y as c,z as v}from"./chunk-
|
|
1
|
+
import{A as j,a as e,b as r,c as t,d as o,e as i,f as a,g as s,h as p,i as n,j as l,k as f,l as m,m as y,n as u,o as d,p as x,q as C,r as g,x as h,y as c,z as v}from"./chunk-V5KVO4JJ.js";import"./chunk-O55PTKMV.js";export{p as EDGE_USERDATA_KIND,C as Materials,v as SCALE_FACTORS,n as addEdges,t as applyOffset,o as computeCombinedBoundingBox,i as createCameraController,a as createGrid,y as createLabelLayer,d as createMeasureTool,m as createRenderPipeline,s as createViewGizmo,j as getThreeMeshesFromComputeResponse,x as initThree,l as isEdgeOverlay,r as parseColor,g as parseDisplayItems,c as parseMeshBatchBlob,h as parseMeshBatchObject,f as removeEdges,u as snapToVertex,e as updateScene};
|
|
2
2
|
//# sourceMappingURL=visualization.js.map
|
package/package.json
CHANGED
package/dist/chunk-2KAHGLXE.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var A=Object.defineProperty;var M=(r,e,t)=>e in r?A(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var ae=(r,e)=>{for(var t in e)A(r,t,{get:e[t],enumerable:!0})};var g=(r,e,t)=>M(r,typeof e!="symbol"?e+"":e,t);var a={NETWORK_ERROR:"NETWORK_ERROR",AUTH_ERROR:"AUTH_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",COMPUTATION_ERROR:"COMPUTATION_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",CORS_ERROR:"CORS_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR",INVALID_STATE:"INVALID_STATE",INVALID_INPUT:"INVALID_INPUT",INVALID_CONFIG:"INVALID_CONFIG",BROWSER_ONLY:"BROWSER_ONLY",ENVIRONMENT_ERROR:"ENVIRONMENT_ERROR",ENCODING_ERROR:"ENCODING_ERROR",MALFORMED_DEFAULT:"MALFORMED_DEFAULT",SUPERSEDED:"SUPERSEDED",ABORTED:"ABORTED",DEFINITION_NOT_CACHED:"DEFINITION_NOT_CACHED"},d=class r extends Error{constructor(t,n="UNKNOWN_ERROR",o){super(t);g(this,"code");g(this,"statusCode");g(this,"context");g(this,"originalError");this.name="RhinoComputeError",this.code=n,this.statusCode=o?.statusCode,this.context=o?.context,this.originalError=o?.originalError,o?.originalError&&(this.cause=o.originalError)}static missingValues(t,n,o){return new r(`Input "${t}" has no values defined${n?` (expected ${n})`:""}`,a.INVALID_INPUT,{context:{inputName:t,expectedType:n,...o}})}static unknownParamType(t,n,o){return new r(`Unknown paramType: ${t}`,a.VALIDATION_ERROR,{context:{receivedParamType:t,paramName:n,...o}})}};var T=class{debug(){}info(){}warn(){}error(){}},N=class{debug(e,...t){console.debug(e,...t)}info(e,...t){console.info(e,...t)}warn(e,...t){console.warn(e,...t)}error(e,...t){console.error(e,...t)}},$=new T;function f(){return $}function U(r){$=r===null?new T:r}function x(){U(new N)}function k(r){if(!r)return null;let e={raw:r},t=!1;for(let n of r.split(",")){let[o,...u]=n.trim().split(";"),p=u.find(c=>c.trim().toLowerCase().startsWith("dur"));if(!p)continue;let s=Number(p.split("=")[1]);if(!Number.isFinite(s))continue;let l=o.trim().toLowerCase();(l==="decode"||l==="solve"||l==="encode")&&(e[l]=s,t=!0)}return t?e:null}var v={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},D=new Set([502,503,504]);function B(r){return r?{attempts:r.attempts??v.attempts,baseDelayMs:r.baseDelayMs??v.baseDelayMs,maxDelayMs:r.maxDelayMs??v.maxDelayMs,retryOn429:r.retryOn429??v.retryOn429}:v}function q(r){if(!r)return null;let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);if(Number.isFinite(t)){let n=t-Date.now();return n>0?n:0}return null}function S(r,e){let t=e.baseDelayMs*Math.pow(2,r),n=Math.random()*e.baseDelayMs;return Math.min(t+n,e.maxDelayMs)}function K(r,e){return new Promise((t,n)=>{if(e?.aborted){n(new DOMException("Aborted","AbortError"));return}let o=setTimeout(()=>{e?.removeEventListener("abort",u),t()},r),u=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))};e?.addEventListener("abort",u,{once:!0})})}function W(r,e,t,n,o,u,p){let{status:s,statusText:l}=r,c={};r.headers.forEach((I,L)=>{c[L]=I});let m=u.trim(),i=m?` \u2014 ${m.slice(0,200)}${m.length>200?"\u2026":""}`:"",y={url:e,requestId:t,method:"POST",requestSize:n,serverUrl:o,responseBody:u||void 0,responseHeaders:c},E={401:{message:`HTTP ${s}: ${l}${i}`,code:a.AUTH_ERROR},403:{message:`HTTP ${s}: ${l}${i}`,code:a.AUTH_ERROR},404:{message:`Endpoint not found: ${e}`,code:a.NETWORK_ERROR},413:{message:`Request too large: ${(n/1024).toFixed(2)}KB`,code:a.VALIDATION_ERROR},429:{message:`Rate limit exceeded${i}`,code:a.NETWORK_ERROR},500:{message:`Server error: ${l}${i}`,code:a.COMPUTATION_ERROR},502:{message:`Service unavailable: ${l}${i}`,code:a.NETWORK_ERROR},503:{message:`Service unavailable: ${l}${i}`,code:a.NETWORK_ERROR},504:{message:`Service unavailable: ${l}${i}`,code:a.NETWORK_ERROR}}[s]||{message:`HTTP ${s}: ${l}${i}`,code:a.UNKNOWN_ERROR},w=H(p)??E.code;throw new d(E.message,w,{statusCode:s,context:y})}function H(r){if(r==="definition_not_cached")return a.DEFINITION_NOT_CACHED}function z(r,e){let t=e.replace(/\/+$/,""),n=r.replace(/^\/+/,"");return`${t}/${n}`}function V(r){try{let e=new URL(r).host;return/^(localhost|127\.0\.0\.1|::1)(:\d+)?$/i.test(e)}catch{return/(localhost|127\.0\.0\.1)/i.test(r)}}function J(r,e){let t={"X-Request-ID":r,"Content-Type":"application/json",...e.authToken&&{Authorization:e.authToken},...e.apiKey&&{RhinoComputeKey:e.apiKey}};return!e.apiKey&&!e.authToken&&!V(e.serverUrl)&&f().warn(`\u26A0\uFE0F [Rhino Compute] Request [${r}] targets remote server (${e.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited.`),t}function j(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function R(r,e){e&&f().debug(r)}function G(r,e){let t=[],n=()=>{};if(r&&t.push(r),e&&e>0)if(typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function")t.push(AbortSignal.timeout(e));else{let s=new AbortController,l=setTimeout(()=>s.abort(),e);n=()=>clearTimeout(l),t.push(s.signal)}if(t.length===0)return{signal:void 0,cleanup:n};if(t.length===1)return{signal:t[0],cleanup:n};if(typeof AbortSignal<"u"&&typeof AbortSignal.any=="function")return{signal:AbortSignal.any(t),cleanup:n};let o=new AbortController,u=()=>o.abort();for(let s of t){if(s.aborted){o.abort();break}s.addEventListener("abort",u,{once:!0})}let p=n;return n=()=>{p();for(let s of t)s.removeEventListener("abort",u)},{signal:o.signal,cleanup:n}}async function Y(r,e,t,n,o,u,p,s){let l=Math.round(performance.now()-u);if(!r.ok){let c=await r.text();p&&(R(`\u274C Request [${t}] failed with HTTP ${r.status} in ${l}ms`,!0),R(` URL: ${e}`,!0),R(` Status: ${r.status} ${r.statusText}`,!0),c&&R(` Response body: ${c.substring(0,500)}${c.length>500?"...":""}`,!0));let m;try{let i=JSON.parse(c);typeof i?.code=="string"&&(m=i.code)}catch{}if(r.status===500)try{let i=JSON.parse(c);if(i?.values&&(i.errors||i.warnings))return p&&(R(`\u26A0\uFE0F Request [${t}] completed with Grasshopper errors in ${l}ms`,!0),i.errors?.length>0&&R(` Errors: ${JSON.stringify(i.errors,null,2)}`,!0),i.warnings?.length>0&&R(` Warnings: ${JSON.stringify(i.warnings,null,2)}`,!0)),i;let y=typeof i?.message=="string"&&i.message||typeof i?.Message=="string"&&i.Message||"",h=typeof i?.ExceptionType=="string"&&i.ExceptionType||"",E=i?.stackTrace??i?.StackTrace,w=Array.isArray(E)?E.join(`
|
|
2
|
-
`):E||"";y?c=`${h?`${h}: `:""}${y}${w?`
|
|
3
|
-
${w}`:""}`:i?.error&&(c=typeof i.error=="string"?i.error:JSON.stringify(i.error,null,2))}catch(i){p&&R(` Failed to parse error body as JSON: ${i}`,!0)}W(r,e,t,n,o,c,m)}if(R(`\u2705 Request [${t}] completed in ${l}ms`,p),s){let c=k(r.headers.get("Server-Timing"));if(c)try{s(c)}catch(m){p&&R(` onServerTiming callback threw: ${m}`,!0)}}try{return await r.json()}catch(c){throw new d("Failed to parse JSON response",a.NETWORK_ERROR,{statusCode:r.status,context:{url:e,requestId:t},originalError:c instanceof Error?c:new Error(String(c))})}}async function Z(r,e,t,n){let{signal:o,cleanup:u}=G(r.config.signal,r.config.timeoutMs),p=performance.now();try{let s=await fetch(r.fullUrl,{method:"POST",body:r.body,headers:r.headers,signal:o});if((D.has(s.status)||e.retryOn429&&s.status===429)&&t<n-1){let m=q(s.headers.get("Retry-After")),i=m!==null?Math.min(m,e.maxDelayMs):S(t,e);return await s.text().catch(()=>{}),{ok:!1,retry:!0,delayMs:i,cause:new d(`HTTP ${s.status} ${s.statusText} (will retry)`,a.NETWORK_ERROR,{statusCode:s.status,context:{requestId:r.requestId}})}}return{ok:!0,value:await Y(s,r.fullUrl,r.requestId,r.requestSize,r.config.serverUrl,p,r.config.debug,r.config.onServerTiming)}}catch(s){if(s instanceof Error&&(s.name==="AbortError"||s.name==="TimeoutError")){if(r.config.signal?.aborted===!0)return{ok:!1,retry:!1,cause:new d("Request aborted by caller",a.UNKNOWN_ERROR,{context:{endpoint:r.endpoint,requestId:r.requestId,requestSize:r.requestSize},originalError:s})};let c=new d(`Request timed out after ${r.config.timeoutMs}ms`,a.TIMEOUT_ERROR,{context:{serverUrl:r.config.serverUrl,timeoutMs:r.config.timeoutMs,url:r.fullUrl,requestId:r.requestId,endpoint:r.endpoint,requestSize:r.requestSize}});return t<n-1?{ok:!1,retry:!0,delayMs:S(t,e),cause:c}:{ok:!1,retry:!1,cause:c}}if(s instanceof TypeError){let l=new d(`Network error: ${s.message}`,a.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,url:r.fullUrl,requestId:r.requestId,endpoint:r.endpoint,requestSize:r.requestSize},originalError:s});return t<n-1?{ok:!1,retry:!0,delayMs:S(t,e),cause:l}:{ok:!1,retry:!1,cause:l}}if(s instanceof d){let l=s.statusCode;return l!==void 0&&(D.has(l)||e.retryOn429&&l===429)&&t<n-1?{ok:!1,retry:!0,delayMs:S(t,e),cause:s}:{ok:!1,retry:!1,cause:s}}return{ok:!1,retry:!1,cause:new d(s instanceof Error?s.message:String(s),a.UNKNOWN_ERROR,{context:{endpoint:r.endpoint,requestId:r.requestId},originalError:s instanceof Error?s:new Error(String(s))})}}finally{u()}}async function X(r,e,t){let n=j(),o=JSON.stringify(e),u=o.length,p=z(r,t.serverUrl),s=J(n,t),l=B(t.retry),c=l.attempts+1;if(t.debug){let y=(u/1024).toFixed(2),h=u>1e5?"\u26A0\uFE0F":"\u{1F680}";R(`${h} Starting compute request [${n}]: ${r} (${y}KB)`,!0)}let m={endpoint:r,body:o,requestSize:u,fullUrl:p,requestId:n,headers:s,config:t},i=null;for(let y=0;y<c;y++){let h=await Z(m,l,y,c);if(h.ok)return h.value;if(!h.retry)throw h.cause;i=h.cause,t.debug&&R(`\u{1F501} Request [${n}] retrying after ${h.delayMs}ms (attempt ${y+2}/${c}): ${h.cause.message}`,!0);try{await K(h.delayMs,t.signal)}catch{throw new d("Request aborted by caller",a.UNKNOWN_ERROR,{context:{endpoint:r,requestId:n,requestSize:u},originalError:i})}}throw i??new d("Unknown error after retries",a.UNKNOWN_ERROR,{context:{endpoint:r,requestId:n,requestSize:u}})}var Q="https://compute.rhino3d.com/";function F(r){if(!r?.trim())throw new d("serverUrl is required",a.INVALID_CONFIG,{context:{receivedServerUrl:r}});if(!r.match(/^https?:\/\//))throw new d(`Invalid serverUrl: "${r}". Must start with "http://" or "https://". For example: "http://localhost:5000" or "https://example.com"`,a.INVALID_CONFIG,{context:{receivedServerUrl:r}});try{new URL(r)}catch(e){throw new d(`Invalid serverUrl: "${r}". Must be a valid URL. Received error: ${e instanceof Error?e.message:String(e)}`,a.INVALID_CONFIG,{context:{receivedServerUrl:r},originalError:e instanceof Error?e:void 0})}if(r===Q)throw new d("serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.",a.INVALID_CONFIG,{context:{receivedServerUrl:r}});return r.replace(/\/+$/,"")}var b=class b{constructor(e,t){g(this,"serverUrl");g(this,"apiKey");g(this,"disposed",!1);g(this,"activeMonitors",new Set);g(this,"activeTimeouts",new Set);this.serverUrl=F(e),this.apiKey=t}buildHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,t={},n=b.DEFAULT_TIMEOUT_MS){let o={headers:this.buildHeaders(),...t};return n>0&&!o.signal&&(o.signal=AbortSignal.timeout(n)),fetch(e,o)}async isServerOnline(e=5e3){this.ensureNotDisposed();let t=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(t,{method:"GET"},e)).ok}catch(n){return f().debug("[ComputeServerStats] Fetch error:",n),!1}}async getActiveChildren(e={}){this.ensureNotDisposed();let{initialize:t=!0}=e,n=t?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,o=t?b.LIFECYCLE_TIMEOUT_MS:b.DEFAULT_TIMEOUT_MS;try{let u=await this.fetchWithTimeout(n,{},o);if(!u.ok)return f().warn("[ComputeServerStats] Failed to fetch active children:",u.status),null;let p=await u.text(),s=parseInt(p.trim(),10);return isNaN(s)?(f().warn("[ComputeServerStats] Invalid active children response:",p),null):s}catch(u){return f().warn("[ComputeServerStats] Error fetching active children:",u),null}}async getVersion(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!e.ok)return f().warn("[ComputeServerStats] Failed to fetch version:",e.status),null;let t=await e.text();try{let n=JSON.parse(t);return{rhino:n.rhino??"",compute:n.compute??"",git_sha:n.git_sha??null}}catch{return{rhino:t,compute:"",git_sha:null}}}catch(e){return f().warn("[ComputeServerStats] Error fetching version:",e),null}}async getInstalledPlugins(e="gh"){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${e}/installed`);if(!t.ok)return f().warn(`[ComputeServerStats] Failed to fetch ${e} plugins:`,t.status),null;let n=await t.text();try{let o=JSON.parse(n);return o&&typeof o=="object"?o:null}catch{return null}}catch(t){return f().warn(`[ComputeServerStats] Error fetching ${e} plugins:`,t),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[t,n]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...t&&{version:t},...n!==null&&{activeChildren:n}}}async purgeCache(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:"POST"});if(!e.ok)return f().warn("[ComputeServerStats] Failed to purge cache:",e.status),null;let t=await e.text();try{let n=JSON.parse(t);return typeof n.purged=="number"?n.purged:null}catch{return null}}catch(e){return f().warn("[ComputeServerStats] Error purging cache:",e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return f().warn("[ComputeServerStats] purgeAllChildren: could not read child count"),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let t=e*2,n=0;for(let o=0;o<t;o++){let u=await this.purgeCache();u!==null&&(n+=u)}return{totalPurged:n,calls:t,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!e.ok)return f().warn("[ComputeServerStats] Failed to fetch server time:",e.status),null;let t=(await e.text()).trim().replace(/^"|"$/g,""),n=new Date(t);return isNaN(n.getTime())?null:n}catch(e){return f().warn("[ComputeServerStats] Error fetching server time:",e),null}}async getIdleSpan(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);if(!e.ok)return f().warn("[ComputeServerStats] Failed to fetch idle span:",e.status),null;let t=parseFloat((await e.text()).trim());return isNaN(t)?null:t}catch(e){return f().warn("[ComputeServerStats] Error fetching idle span:",e),null}}async launchChildren(){return this.postJson("/launch-children")}async launchChild(e){let t=e===void 0?"/launch-child":`/launch-child?port=${e}`;return this.postJson(t)}async shutdownChildren(e){let t=e===void 0?"/shutdown-children":`/shutdown-children?port=${e}`;return this.postJson(t)}async recycleChildren(e){let t=e===void 0?"/recycle-children":`/recycle-children?port=${e}`;return this.postJson(t)}async postJson(e){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}${e}`,{method:"POST"},b.LIFECYCLE_TIMEOUT_MS);if(!t.ok)return f().warn(`[ComputeServerStats] POST ${e} failed:`,t.status),null;let n=await t.text();try{return JSON.parse(n)}catch{return null}}catch(t){return f().warn(`[ComputeServerStats] Error on POST ${e}:`,t),null}}monitor(e,t=5e3){this.ensureNotDisposed();let n=!0,o=null;f().info(`\u{1F504} Starting server stats monitoring every ${t}ms`);let u=async()=>{if(o!==null&&(this.activeTimeouts.delete(o),o=null),!(!n||this.disposed)){try{let s=await this.getServerStats();if(!n||this.disposed)return;try{e(s)}catch(l){f().error("[ComputeServerStats] Monitor callback threw:",l)}}catch(s){f().error("[ComputeServerStats] Failed to fetch stats during monitor:",s)}n&&!this.disposed&&(o=setTimeout(()=>{u()},t),this.activeTimeouts.add(o))}},p=()=>{n=!1,o!==null&&(clearTimeout(o),this.activeTimeouts.delete(o),o=null),this.activeMonitors.delete(p)};return this.activeMonitors.add(p),u(),p}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new d("ComputeServerStats has been disposed and cannot be used",a.INVALID_STATE,{context:{disposed:this.disposed}})}};g(b,"DEFAULT_TIMEOUT_MS",5e3),g(b,"LIFECYCLE_TIMEOUT_MS",6e4);var O=b;function C(){let r=globalThis.Buffer;return typeof r=="function"?r:void 0}function Te(r){let e=C();return e?e.from(r,"utf-8").toString("base64"):ee(new TextEncoder().encode(r))}function Se(r){return!r||r.length<2||r.length%4!==0?!1:/^[A-Za-z0-9+/]+={0,2}$/.test(r)}function _(r){let e=C();if(e){let t=e.from(r,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if(typeof globalThis.atob=="function"){let t=globalThis.atob(r),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o)&255;return n}throw new d("Base64 decoding not supported in this environment.",a.INVALID_STATE,{context:{environmentInfo:"atob or Buffer not available"}})}function ee(r){let e=C();if(e)return e.from(r).toString("base64");if(typeof globalThis.btoa=="function"){let n="";for(let o=0;o<r.length;o+=32768)n+=String.fromCharCode.apply(null,r.subarray(o,o+32768));return globalThis.btoa(n)}throw new d("Base64 encoding not supported in this environment.",a.INVALID_STATE,{context:{environmentInfo:"btoa or Buffer not available"}})}var te=async(r,e=null)=>{try{return await P(r,e)}catch(t){throw new d("Failed to extract files from compute response",a.INVALID_STATE,{context:{originalError:t instanceof Error?t.message:String(t)},originalError:t instanceof Error?t:void 0})}},re=async(r,e,t=null)=>{if(typeof document>"u"||typeof Blob>"u")throw new d("File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).",a.BROWSER_ONLY,{context:{environment:typeof window<"u"?"browser (SSR)":"Node.js",documentAvailable:typeof document<"u",blobAvailable:typeof Blob<"u"}});try{let n=await P(r,t);await se(n,e)}catch(n){throw n instanceof d?n:new d("Failed to download files from compute response",a.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}},ne=r=>{let e=[];return r.forEach(t=>{let n=`${t.fileName}${t.fileType}`,o=t.subFolder&&t.subFolder.trim()!==""?`${t.subFolder}/${n}`:n;t.isBase64Encoded===!0&&t.data?e.push({fileName:n,content:_(t.data),path:o}):t.isBase64Encoded===!1&&t.data&&e.push({fileName:n,content:t.data,path:o})}),e},oe=async r=>(await Promise.all(r.map(async t=>{try{let n=await fetch(t.filePath);if(!n.ok)return f().warn(`Failed to fetch additional file from URL: ${t.filePath}`),null;let u=await(await n.blob()).arrayBuffer();return{fileName:t.fileName,content:new Uint8Array(u),path:t.fileName}}catch(n){return f().error(`Error fetching additional file from URL: ${t.filePath}`,n),null}}))).filter(t=>t!==null),P=async(r,e)=>{let t=ne(r);if(e){let n=Array.isArray(e)?e:[e];t.push(...await oe(n))}return t};async function se(r,e){let{zip:t,strToU8:n}=await import("fflate"),o={};r.forEach(s=>{o[s.path]=typeof s.content=="string"?n(s.content):s.content});let u=await new Promise((s,l)=>{t(o,{level:6},(c,m)=>c?l(c):s(m))}),p=new Blob([u],{type:"application/zip"});ie(p,`${e}.zip`)}function ie(r,e){if(typeof document>"u")throw new d("saveFile requires a browser environment with DOM API access.",a.BROWSER_ONLY,{context:{function:"saveFile",requiredAPI:"document"}});let t=document.createElement("a");t.href=URL.createObjectURL(r),t.download=e,t.click(),URL.revokeObjectURL(t.href)}export{ae as a,g as b,a as c,d,f as e,U as f,x as g,X as h,F as i,O as j,Te as k,Se as l,_ as m,ee as n,te as o,re as p};
|
|
4
|
-
//# sourceMappingURL=chunk-2KAHGLXE.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/errors.ts","../src/core/utils/logger.ts","../src/core/compute-fetch/compute-fetch.ts","../src/core/server/validate-server-url.ts","../src/core/server/compute-server-stats.ts","../src/core/utils/encoding.ts","../src/core/files/handle-files.ts"],"sourcesContent":["/**\n * Error types and codes for `@selvajs/compute`.\n */\n\nexport const ErrorCodes = {\n\tNETWORK_ERROR: 'NETWORK_ERROR',\n\tAUTH_ERROR: 'AUTH_ERROR',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tCOMPUTATION_ERROR: 'COMPUTATION_ERROR',\n\tTIMEOUT_ERROR: 'TIMEOUT_ERROR',\n\tCORS_ERROR: 'CORS_ERROR',\n\tUNKNOWN_ERROR: 'UNKNOWN_ERROR',\n\tINVALID_STATE: 'INVALID_STATE',\n\tINVALID_INPUT: 'INVALID_INPUT',\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\tBROWSER_ONLY: 'BROWSER_ONLY',\n\tENVIRONMENT_ERROR: 'ENVIRONMENT_ERROR',\n\tENCODING_ERROR: 'ENCODING_ERROR',\n\t/** An input's `default` had a shape the normalizer didn't recognize (no innerTree key). */\n\tMALFORMED_DEFAULT: 'MALFORMED_DEFAULT',\n\t/** Scheduler latest-wins: this call was replaced by a newer one. */\n\tSUPERSEDED: 'SUPERSEDED',\n\t/** Scheduler / caller-supplied AbortSignal: this call was aborted. */\n\tABORTED: 'ABORTED',\n\t/**\n\t * A solve referenced a definition by `pointer` (server-side cache key), but the\n\t * server no longer holds that definition (evicted / GC'd / a different child in\n\t * the pool / server restarted). The caller should retry with the full\n\t * definition. Surfaced when the server tags its error body with\n\t * `code: \"definition_not_cached\"`, so it survives production message-scrubbing.\n\t */\n\tDEFINITION_NOT_CACHED: 'DEFINITION_NOT_CACHED'\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/**\n * Simplified error for Rhino Compute operations\n *\n * @public Use this for error handling with error codes and context.\n */\nexport class RhinoComputeError extends Error {\n\tpublic readonly code: string;\n\tpublic readonly statusCode?: number;\n\tpublic readonly context?: Record<string, unknown>;\n\tpublic readonly originalError?: Error;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: string = 'UNKNOWN_ERROR',\n\t\toptions?: { statusCode?: number; context?: Record<string, unknown>; originalError?: Error }\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'RhinoComputeError';\n\t\tthis.code = code;\n\t\tthis.statusCode = options?.statusCode;\n\t\tthis.context = options?.context;\n\t\tthis.originalError = options?.originalError;\n\t\tif (options?.originalError) {\n\t\t\t(this as { cause?: unknown }).cause = options.originalError;\n\t\t}\n\t}\n\n\t// ============================================================================\n\t// Static Validation Error Helpers\n\t// ============================================================================\n\n\t/**\n\t * Create an error for missing/empty values\n\t */\n\tstatic missingValues(\n\t\tinputName: string,\n\t\texpectedType?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(\n\t\t\t`Input \"${inputName}\" has no values defined${expectedType ? ` (expected ${expectedType})` : ''}`,\n\t\t\tErrorCodes.INVALID_INPUT,\n\t\t\t{ context: { inputName, expectedType, ...context } }\n\t\t);\n\t}\n\n\t/**\n\t * Create an error for unknown parameter type\n\t */\n\tstatic unknownParamType(\n\t\tparamType: string,\n\t\tparamName?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(`Unknown paramType: ${paramType}`, ErrorCodes.VALIDATION_ERROR, {\n\t\t\tcontext: { receivedParamType: paramType, paramName, ...context }\n\t\t});\n\t}\n}\n","/**\n * Logger interface for structured logging\n *\n * @public Implement this interface to provide custom logging behavior.\n */\nexport interface Logger {\n\tdebug(message: string, ...args: unknown[]): void;\n\tinfo(message: string, ...args: unknown[]): void;\n\twarn(message: string, ...args: unknown[]): void;\n\terror(message: string, ...args: unknown[]): void;\n}\n\n/**\n * No-op logger implementation (default)\n * @internal\n */\nclass NoOpLogger implements Logger {\n\tdebug(): void {}\n\tinfo(): void {}\n\twarn(): void {}\n\terror(): void {}\n}\n\n/**\n * Console logger implementation\n * @internal\n */\nclass ConsoleLogger implements Logger {\n\tdebug(message: string, ...args: unknown[]): void {\n\t\tconsole.debug(message, ...args);\n\t}\n\n\tinfo(message: string, ...args: unknown[]): void {\n\t\tconsole.info(message, ...args);\n\t}\n\n\twarn(message: string, ...args: unknown[]): void {\n\t\tconsole.warn(message, ...args);\n\t}\n\n\terror(message: string, ...args: unknown[]): void {\n\t\tconsole.error(message, ...args);\n\t}\n}\n\n/**\n * Internal logger instance\n * @internal\n */\nlet internalLogger: Logger = new NoOpLogger();\n\n/**\n * Get the current logger instance\n *\n * @returns The current logger instance\n */\nexport function getLogger(): Logger {\n\treturn internalLogger;\n}\n\n/**\n * Set a custom logger instance\n *\n * @public Use this to configure custom logging behavior.\n *\n * @param logger - Custom logger implementation or null to disable logging\n *\n * @example\n * ```typescript\n * import { setLogger } from '@selvajs/compute';\n *\n * // Enable console logging\n * setLogger(console);\n *\n * // Use a custom logger\n * setLogger({\n * debug: (msg, ...args) => myLogger.debug(msg, ...args),\n * info: (msg, ...args) => myLogger.info(msg, ...args),\n * warn: (msg, ...args) => myLogger.warn(msg, ...args),\n * error: (msg, ...args) => myLogger.error(msg, ...args)\n * });\n *\n * // Disable logging\n * setLogger(null);\n * ```\n */\nexport function setLogger(logger: Logger | Console | null): void {\n\tinternalLogger = logger === null ? new NoOpLogger() : (logger as Logger);\n}\n\n/**\n * Enable debug logging to console\n *\n * @public Convenience method to enable console logging.\n *\n * @example\n * ```typescript\n * import { enableDebugLogging } from '@selvajs/compute';\n *\n * enableDebugLogging();\n * ```\n */\nexport function enableDebugLogging(): void {\n\tsetLogger(new ConsoleLogger());\n}\n","import { RhinoComputeError, ErrorCodes, type ErrorCode } from '../errors';\nimport { getLogger } from '../utils/logger';\n\nimport type { ComputeConfig, RetryPolicy, ServerTiming } from '../types';\n\n// ============================================================================\n// Server-Timing\n// ============================================================================\n\n/**\n * Parse a `Server-Timing` header value into typed durations (ms).\n *\n * Header grammar (RFC 9110 §10.1.10), as emitted by the solve endpoint:\n * `decode;dur=3, solve;dur=120, encode;dur=8`\n *\n * Returns null when the header is absent or carries no recognizable metric, so\n * the caller can skip the callback entirely.\n *\n * @internal exported for tests\n */\nexport function parseServerTiming(headerValue: string | null): ServerTiming | null {\n\tif (!headerValue) return null;\n\tconst timing: ServerTiming = { raw: headerValue };\n\tlet sawMetric = false;\n\tfor (const part of headerValue.split(',')) {\n\t\tconst [name, ...params] = part.trim().split(';');\n\t\tconst durParam = params.find((p) => p.trim().toLowerCase().startsWith('dur'));\n\t\tif (!durParam) continue;\n\t\tconst dur = Number(durParam.split('=')[1]);\n\t\tif (!Number.isFinite(dur)) continue;\n\t\tconst key = name.trim().toLowerCase();\n\t\tif (key === 'decode' || key === 'solve' || key === 'encode') {\n\t\t\ttiming[key] = dur;\n\t\t\tsawMetric = true;\n\t\t}\n\t}\n\treturn sawMetric ? timing : null;\n}\n\n// ============================================================================\n// Retry Policy\n// ============================================================================\n\nconst DEFAULT_RETRY: Required<RetryPolicy> = {\n\tattempts: 0,\n\tbaseDelayMs: 500,\n\tmaxDelayMs: 30_000,\n\tretryOn429: true\n};\n\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\nfunction resolveRetryPolicy(policy: RetryPolicy | undefined): Required<RetryPolicy> {\n\tif (!policy) return DEFAULT_RETRY;\n\treturn {\n\t\tattempts: policy.attempts ?? DEFAULT_RETRY.attempts,\n\t\tbaseDelayMs: policy.baseDelayMs ?? DEFAULT_RETRY.baseDelayMs,\n\t\tmaxDelayMs: policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs,\n\t\tretryOn429: policy.retryOn429 ?? DEFAULT_RETRY.retryOn429\n\t};\n}\n\n/**\n * Parse a Retry-After header value (seconds-int or HTTP-date) into ms.\n * Returns null if the header is missing or unparseable.\n */\nfunction parseRetryAfter(headerValue: string | null): number | null {\n\tif (!headerValue) return null;\n\tconst seconds = Number(headerValue);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n\tconst dateMs = Date.parse(headerValue);\n\tif (Number.isFinite(dateMs)) {\n\t\tconst delta = dateMs - Date.now();\n\t\treturn delta > 0 ? delta : 0;\n\t}\n\treturn null;\n}\n\nfunction backoffDelay(attempt: number, policy: Required<RetryPolicy>): number {\n\tconst exponential = policy.baseDelayMs * Math.pow(2, attempt);\n\tconst jitter = Math.random() * policy.baseDelayMs;\n\treturn Math.min(exponential + jitter, policy.maxDelayMs);\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t\treturn;\n\t\t}\n\t\tconst id = setTimeout(() => {\n\t\t\tsignal?.removeEventListener('abort', onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(id);\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t};\n\t\tsignal?.addEventListener('abort', onAbort, { once: true });\n\t});\n}\n\n// ============================================================================\n// Error Handling\n// ============================================================================\n\nfunction throwHttpError(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\terrorBody: string,\n\tserverCode?: string\n): never {\n\tconst { status, statusText } = response;\n\n\tconst responseHeaders: Record<string, string> = {};\n\tresponse.headers.forEach((value, key) => {\n\t\tresponseHeaders[key] = value;\n\t});\n\n\tconst trimmed = errorBody.trim();\n\tconst bodyHint = trimmed ? ` — ${trimmed.slice(0, 200)}${trimmed.length > 200 ? '…' : ''}` : '';\n\n\tconst context = {\n\t\turl: fullUrl,\n\t\trequestId,\n\t\tmethod: 'POST',\n\t\trequestSize,\n\t\tserverUrl,\n\t\tresponseBody: errorBody || undefined,\n\t\tresponseHeaders\n\t};\n\n\tconst errorMap: Record<number, { message: string; code: string }> = {\n\t\t401: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t403: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t404: { message: `Endpoint not found: ${fullUrl}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t413: {\n\t\t\tmessage: `Request too large: ${(requestSize / 1024).toFixed(2)}KB`,\n\t\t\tcode: ErrorCodes.VALIDATION_ERROR\n\t\t},\n\t\t429: { message: `Rate limit exceeded${bodyHint}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t500: { message: `Server error: ${statusText}${bodyHint}`, code: ErrorCodes.COMPUTATION_ERROR },\n\t\t502: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t503: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t504: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t}\n\t};\n\n\tconst error = errorMap[status] || {\n\t\tmessage: `HTTP ${status}: ${statusText}${bodyHint}`,\n\t\tcode: ErrorCodes.UNKNOWN_ERROR\n\t};\n\n\t// A machine code in the server's error body (e.g. \"definition_not_cached\")\n\t// outranks the status-based mapping: it's stable across the server's\n\t// production message-scrubbing, where the human message is replaced with a\n\t// generic string. Keep the status-derived message for context.\n\tconst code = mapServerErrorCode(serverCode) ?? error.code;\n\n\tthrow new RhinoComputeError(error.message, code, { statusCode: status, context });\n}\n\n/**\n * Map a server-supplied error code (from the JSON error body's `code` field) to\n * one of our {@link ErrorCodes}. Returns `undefined` for an absent or unknown\n * code so the caller falls back to its status-based mapping.\n */\nfunction mapServerErrorCode(serverCode?: string): ErrorCode | undefined {\n\tswitch (serverCode) {\n\t\tcase 'definition_not_cached':\n\t\t\treturn ErrorCodes.DEFINITION_NOT_CACHED;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n// ============================================================================\n// Request Helpers\n// ============================================================================\n\nfunction buildUrl(endpoint: string, serverUrl: string): string {\n\tconst base = serverUrl.replace(/\\/+$/, '');\n\tconst path = endpoint.replace(/^\\/+/, '');\n\treturn `${base}/${path}`;\n}\n\nfunction isLocalhost(serverUrl: string): boolean {\n\ttry {\n\t\tconst host = new URL(serverUrl).host;\n\t\treturn /^(localhost|127\\.0\\.0\\.1|::1)(:\\d+)?$/i.test(host);\n\t} catch {\n\t\treturn /(localhost|127\\.0\\.0\\.1)/i.test(serverUrl);\n\t}\n}\n\nfunction buildHeaders(requestId: string, config: ComputeConfig): HeadersInit {\n\tconst headers: HeadersInit = {\n\t\t'X-Request-ID': requestId,\n\t\t'Content-Type': 'application/json',\n\t\t...(config.authToken && { Authorization: config.authToken }),\n\t\t...(config.apiKey && { RhinoComputeKey: config.apiKey })\n\t};\n\n\tif (!config.apiKey && !config.authToken && !isLocalhost(config.serverUrl)) {\n\t\tgetLogger().warn(\n\t\t\t`⚠️ [Rhino Compute] Request [${requestId}] targets remote server (${config.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited.`\n\t\t);\n\t}\n\n\treturn headers;\n}\n\nfunction generateRequestId(): string {\n\treturn `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n}\n\nfunction log(message: string, debug?: boolean): void {\n\tif (debug) getLogger().debug(message);\n}\n\n/**\n * Compose a caller-supplied AbortSignal with an optional timeout. Returns a\n * combined signal, or `undefined` if neither was given.\n *\n * Uses `AbortSignal.timeout` (not setTimeout) so the timer is not throttled\n * when the tab is hidden. Falls back to a manual timer for older runtimes.\n *\n * @internal exported for tests\n */\nexport function composeSignal(\n\tcallerSignal: AbortSignal | undefined,\n\ttimeoutMs: number | undefined\n): { signal: AbortSignal | undefined; cleanup: () => void } {\n\tconst signals: AbortSignal[] = [];\n\tlet cleanup = () => {};\n\n\tif (callerSignal) signals.push(callerSignal);\n\n\tif (timeoutMs && timeoutMs > 0) {\n\t\tif (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {\n\t\t\tsignals.push(AbortSignal.timeout(timeoutMs));\n\t\t} else {\n\t\t\t// Fallback for runtimes without AbortSignal.timeout\n\t\t\tconst ctrl = new AbortController();\n\t\t\tconst id = setTimeout(() => ctrl.abort(), timeoutMs);\n\t\t\tcleanup = () => clearTimeout(id);\n\t\t\tsignals.push(ctrl.signal);\n\t\t}\n\t}\n\n\tif (signals.length === 0) return { signal: undefined, cleanup };\n\tif (signals.length === 1) return { signal: signals[0], cleanup };\n\n\tif (typeof AbortSignal !== 'undefined' && typeof (AbortSignal as any).any === 'function') {\n\t\treturn { signal: (AbortSignal as any).any(signals) as AbortSignal, cleanup };\n\t}\n\n\t// Manual composition fallback\n\tconst ctrl = new AbortController();\n\tconst onAbort = () => ctrl.abort();\n\tfor (const s of signals) {\n\t\tif (s.aborted) {\n\t\t\tctrl.abort();\n\t\t\tbreak;\n\t\t}\n\t\ts.addEventListener('abort', onAbort, { once: true });\n\t}\n\tconst prevCleanup = cleanup;\n\tcleanup = () => {\n\t\tprevCleanup();\n\t\tfor (const s of signals) s.removeEventListener('abort', onAbort);\n\t};\n\treturn { signal: ctrl.signal, cleanup };\n}\n\n// ============================================================================\n// Response Processing\n// ============================================================================\n\nasync function handleResponse(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\tstartTime: number,\n\tdebug?: boolean,\n\tonServerTiming?: (timing: ServerTiming) => void\n): Promise<any> {\n\tconst responseTime = Math.round(performance.now() - startTime);\n\n\tif (!response.ok) {\n\t\t// Read body once and reuse\n\t\tlet errorBody = await response.text();\n\n\t\t// Enhanced logging for errors\n\t\tif (debug) {\n\t\t\tlog(\n\t\t\t\t`❌ Request [${requestId}] failed with HTTP ${response.status} in ${responseTime}ms`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t\tlog(` URL: ${fullUrl}`, true);\n\t\t\tlog(` Status: ${response.status} ${response.statusText}`, true);\n\t\t\tif (errorBody) {\n\t\t\t\tlog(\n\t\t\t\t\t` Response body: ${errorBody.substring(0, 500)}${errorBody.length > 500 ? '...' : ''}`,\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// A machine-readable code the server may tag onto its error body (e.g.\n\t\t// \"definition_not_cached\"). Unlike the human `message`, it isn't scrubbed in\n\t\t// the server's production (non-debug) mode, so it's the reliable signal for\n\t\t// classifying the error (see throwHttpError → mapServerErrorCode).\n\t\tlet serverCode: string | undefined;\n\n\t\t// The machine code (e.g. `definition_not_cached`) can ride any error status,\n\t\t// not just 500, and must outrank the status-based mapping — so read it here.\n\t\ttry {\n\t\t\tconst parsedForCode = JSON.parse(errorBody);\n\t\t\tif (typeof parsedForCode?.code === 'string') serverCode = parsedForCode.code;\n\t\t} catch {\n\t\t\t// Non-JSON body — nothing to extract.\n\t\t}\n\n\t\t// Check if it's a valid compute response with errors/warnings\n\t\tif (response.status === 500) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(errorBody);\n\t\t\t\t// If it has values, it's a partial success with errors\n\t\t\t\tif (parsed?.values && (parsed.errors || parsed.warnings)) {\n\t\t\t\t\tif (debug) {\n\t\t\t\t\t\tlog(\n\t\t\t\t\t\t\t`⚠️ Request [${requestId}] completed with Grasshopper errors in ${responseTime}ms`,\n\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (parsed.errors?.length > 0) {\n\t\t\t\t\t\t\tlog(` Errors: ${JSON.stringify(parsed.errors, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (parsed.warnings?.length > 0) {\n\t\t\t\t\t\t\tlog(` Warnings: ${JSON.stringify(parsed.warnings, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\n\t\t\t\t// Raw server-side exception. The Compute8 server's exception handler\n\t\t\t\t// (compute.geometry Startup.cs) emits:\n\t\t\t\t// { error: \"Internal Server Error\", message: \"<category>: <detail>\",\n\t\t\t\t// stackTrace?: string[] } // stackTrace only when Config.Debug\n\t\t\t\t// The actionable part is `message` — surface it, with the optional\n\t\t\t\t// stack appended for debugging. We prefer `message`/`error` (current\n\t\t\t\t// server) and keep `Message`/`ExceptionType`/`StackTrace` (old\n\t\t\t\t// PascalCase .NET shape) as a back-compat fallback so an older server\n\t\t\t\t// still produces a useful message.\n\t\t\t\tconst serverMessage =\n\t\t\t\t\t(typeof parsed?.message === 'string' && parsed.message) ||\n\t\t\t\t\t(typeof parsed?.Message === 'string' && parsed.Message) ||\n\t\t\t\t\t'';\n\t\t\t\tconst exceptionType =\n\t\t\t\t\t(typeof parsed?.ExceptionType === 'string' && parsed.ExceptionType) || '';\n\t\t\t\tconst stack = parsed?.stackTrace ?? parsed?.StackTrace;\n\t\t\t\tconst stackStr = Array.isArray(stack) ? stack.join('\\n') : stack || '';\n\n\t\t\t\tif (serverMessage) {\n\t\t\t\t\t// Don't repeat the generic \"Internal Server Error\" label when the\n\t\t\t\t\t// message already carries the real detail.\n\t\t\t\t\tconst prefix = exceptionType ? `${exceptionType}: ` : '';\n\t\t\t\t\terrorBody = `${prefix}${serverMessage}${stackStr ? `\\n${stackStr}` : ''}`;\n\t\t\t\t} else if (parsed?.error) {\n\t\t\t\t\terrorBody =\n\t\t\t\t\t\ttypeof parsed.error === 'string' ? parsed.error : JSON.stringify(parsed.error, null, 2);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tif (debug) {\n\t\t\t\t\tlog(` Failed to parse error body as JSON: ${e}`, true);\n\t\t\t\t}\n\t\t\t\t// Not valid JSON, proceed with HTTP error\n\t\t\t}\n\t\t}\n\n\t\tthrowHttpError(response, fullUrl, requestId, requestSize, serverUrl, errorBody, serverCode);\n\t}\n\n\tlog(`✅ Request [${requestId}] completed in ${responseTime}ms`, debug);\n\n\t// Surface the server's per-request timing breakdown (if it sent one and a\n\t// caller is listening). Best-effort: a throwing callback must not fail the\n\t// request, since the body parse below is the real result.\n\tif (onServerTiming) {\n\t\tconst timing = parseServerTiming(response.headers.get('Server-Timing'));\n\t\tif (timing) {\n\t\t\ttry {\n\t\t\t\tonServerTiming(timing);\n\t\t\t} catch (err) {\n\t\t\t\tif (debug) log(` onServerTiming callback threw: ${err}`, true);\n\t\t\t}\n\t\t}\n\t}\n\n\ttry {\n\t\treturn await response.json();\n\t} catch (error) {\n\t\tthrow new RhinoComputeError('Failed to parse JSON response', ErrorCodes.NETWORK_ERROR, {\n\t\t\tstatusCode: response.status,\n\t\t\tcontext: {\n\t\t\t\turl: fullUrl,\n\t\t\t\trequestId\n\t\t\t},\n\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t});\n\t}\n}\n\n// ============================================================================\n// Single attempt\n// ============================================================================\n\ninterface AttemptContext {\n\tendpoint: string;\n\tbody: string;\n\trequestSize: number;\n\tfullUrl: string;\n\trequestId: string;\n\theaders: HeadersInit;\n\tconfig: ComputeConfig;\n}\n\ninterface AttemptResult {\n\tok: true;\n\tvalue: any;\n}\n\ninterface AttemptRetry {\n\tok: false;\n\tretry: true;\n\tdelayMs: number;\n\tcause: RhinoComputeError;\n}\n\ninterface AttemptFatal {\n\tok: false;\n\tretry: false;\n\tcause: RhinoComputeError;\n}\n\nasync function attemptFetch(\n\tctx: AttemptContext,\n\tretryPolicy: Required<RetryPolicy>,\n\tattempt: number,\n\ttotalAttempts: number\n): Promise<AttemptResult | AttemptRetry | AttemptFatal> {\n\tconst { signal, cleanup } = composeSignal(ctx.config.signal, ctx.config.timeoutMs);\n\tconst startTime = performance.now();\n\n\ttry {\n\t\tconst response = await fetch(ctx.fullUrl, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: ctx.body,\n\t\t\theaders: ctx.headers,\n\t\t\tsignal\n\t\t});\n\n\t\t// 429 with Retry-After or retryable 5xx → maybe retry\n\t\tconst isRetryableStatus =\n\t\t\tRETRYABLE_STATUS.has(response.status) || (retryPolicy.retryOn429 && response.status === 429);\n\n\t\tif (isRetryableStatus && attempt < totalAttempts - 1) {\n\t\t\tconst retryAfterMs = parseRetryAfter(response.headers.get('Retry-After'));\n\t\t\t// Clamp Retry-After to maxDelayMs so a bad header can't force an\n\t\t\t// arbitrarily long sleep. backoffDelay already clamps.\n\t\t\tconst delayMs =\n\t\t\t\tretryAfterMs !== null\n\t\t\t\t\t? Math.min(retryAfterMs, retryPolicy.maxDelayMs)\n\t\t\t\t\t: backoffDelay(attempt, retryPolicy);\n\t\t\t// Drain the body so the connection can be reused on the next attempt.\n\t\t\t// On the *final* attempt we deliberately fall through — handleResponse\n\t\t\t// reads the body itself to surface the error context.\n\t\t\tawait response.text().catch(() => {});\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tretry: true,\n\t\t\t\tdelayMs,\n\t\t\t\tcause: new RhinoComputeError(\n\t\t\t\t\t`HTTP ${response.status} ${response.statusText} (will retry)`,\n\t\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t{ statusCode: response.status, context: { requestId: ctx.requestId } }\n\t\t\t\t)\n\t\t\t};\n\t\t}\n\n\t\tconst value = await handleResponse(\n\t\t\tresponse,\n\t\t\tctx.fullUrl,\n\t\t\tctx.requestId,\n\t\t\tctx.requestSize,\n\t\t\tctx.config.serverUrl,\n\t\t\tstartTime,\n\t\t\tctx.config.debug,\n\t\t\tctx.config.onServerTiming\n\t\t);\n\t\treturn { ok: true, value };\n\t} catch (error) {\n\t\t// Caller-aborted vs timeout-aborted distinction\n\t\tif (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {\n\t\t\tconst callerAborted = ctx.config.signal?.aborted === true;\n\n\t\t\tif (callerAborted) {\n\t\t\t\t// Caller cancellation is never retried — propagate immediately\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: false,\n\t\t\t\t\tcause: new RhinoComputeError('Request aborted by caller', ErrorCodes.UNKNOWN_ERROR, {\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t},\n\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Timeout — retryable up to attempts limit\n\t\t\tconst fatal = new RhinoComputeError(\n\t\t\t\t`Request timed out after ${ctx.config.timeoutMs}ms`,\n\t\t\t\tErrorCodes.TIMEOUT_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\ttimeoutMs: ctx.config.timeoutMs,\n\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// Network error (TypeError) — retryable\n\t\tif (error instanceof TypeError) {\n\t\t\tconst fatal = new RhinoComputeError(\n\t\t\t\t`Network error: ${error.message}`,\n\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t},\n\t\t\t\t\toriginalError: error\n\t\t\t\t}\n\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// RhinoComputeError thrown from handleResponse — already has full context.\n\t\t// Retryable only if it carries a retryable status code.\n\t\tif (error instanceof RhinoComputeError) {\n\t\t\tconst status = error.statusCode;\n\t\t\tconst retryable =\n\t\t\t\tstatus !== undefined &&\n\t\t\t\t(RETRYABLE_STATUS.has(status) || (retryPolicy.retryOn429 && status === 429));\n\t\t\tif (retryable && attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: error\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: error };\n\t\t}\n\n\t\t// Unknown — wrap and don't retry\n\t\treturn {\n\t\t\tok: false,\n\t\t\tretry: false,\n\t\t\tcause: new RhinoComputeError(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\tErrorCodes.UNKNOWN_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: { endpoint: ctx.endpoint, requestId: ctx.requestId },\n\t\t\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t}\n\t\t\t)\n\t\t};\n\t} finally {\n\t\tcleanup();\n\t}\n}\n\n// ============================================================================\n// Main Function\n// ============================================================================\n\n/**\n * Generic Rhino Compute fetch function.\n * Sends a POST request to any Compute endpoint with pre-prepared arguments.\n *\n * Use this for advanced, low-level control over compute requests. For most use cases, prefer higher-level APIs.\n *\n * The transport is response-type-agnostic: it does not know which response a\n * given endpoint returns. Callers supply the response type via `R` (defaulting\n * to `unknown`, which forces an explicit narrowing before use).\n *\n * @typeParam R - The expected response shape. The caller names it at the call site.\n * @param endpoint - The Compute API endpoint (e.g., 'grasshopper', 'io', 'mesh').\n * @param args - Pre-prepared arguments for the request body.\n * @param config - Compute configuration (server URL, API key, timeout, debug, retry, signal).\n * @returns The parsed JSON response from the server, typed as `R`.\n *\n * @example\n * // Basic usage for the Grasshopper endpoint:\n * const response = await fetchRhinoCompute(\n * 'grasshopper',\n * { ... },\n * {\n * serverUrl: 'https://my-server.com',\n * debug: true,\n * timeoutMs: 30_000,\n * retry: { attempts: 2 },\n * signal: controller.signal,\n * }\n * );\n */\nexport async function fetchRhinoCompute<R = unknown>(\n\tendpoint: string,\n\targs: Record<string, any>,\n\tconfig: ComputeConfig\n): Promise<R> {\n\tconst requestId = generateRequestId();\n\tconst body = JSON.stringify(args);\n\tconst requestSize = body.length;\n\tconst fullUrl = buildUrl(endpoint, config.serverUrl);\n\tconst headers = buildHeaders(requestId, config);\n\tconst retryPolicy = resolveRetryPolicy(config.retry);\n\tconst totalAttempts = retryPolicy.attempts + 1;\n\n\tif (config.debug) {\n\t\tconst sizeKb = (requestSize / 1024).toFixed(2);\n\t\tconst emoji = requestSize > 100000 ? '⚠️' : '🚀';\n\t\tlog(`${emoji} Starting compute request [${requestId}]: ${endpoint} (${sizeKb}KB)`, true);\n\t}\n\n\tconst ctx: AttemptContext = {\n\t\tendpoint,\n\t\tbody,\n\t\trequestSize,\n\t\tfullUrl,\n\t\trequestId,\n\t\theaders,\n\t\tconfig\n\t};\n\n\tlet lastError: RhinoComputeError | null = null;\n\n\tfor (let attempt = 0; attempt < totalAttempts; attempt++) {\n\t\tconst result = await attemptFetch(ctx, retryPolicy, attempt, totalAttempts);\n\n\t\tif (result.ok) return result.value as R;\n\n\t\tif (!result.retry) throw result.cause;\n\n\t\tlastError = result.cause;\n\t\tif (config.debug) {\n\t\t\tlog(\n\t\t\t\t`🔁 Request [${requestId}] retrying after ${result.delayMs}ms (attempt ${attempt + 2}/${totalAttempts}): ${result.cause.message}`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\tawait sleep(result.delayMs, config.signal);\n\t\t} catch {\n\t\t\t// Caller cancelled during backoff\n\t\t\tthrow new RhinoComputeError('Request aborted by caller', ErrorCodes.UNKNOWN_ERROR, {\n\t\t\t\tcontext: { endpoint, requestId, requestSize },\n\t\t\t\toriginalError: lastError\n\t\t\t});\n\t\t}\n\t}\n\n\t// Exhausted retries — throw the last seen error\n\tthrow (\n\t\tlastError ??\n\t\tnew RhinoComputeError('Unknown error after retries', ErrorCodes.UNKNOWN_ERROR, {\n\t\t\tcontext: { endpoint, requestId, requestSize }\n\t\t})\n\t);\n}\n","import { RhinoComputeError, ErrorCodes } from '@/core/errors';\n\n/** The public McNeel endpoint — disallowed as a `serverUrl`; users must point at their own server. */\nconst DEFAULT_PUBLIC_ENDPOINT = 'https://compute.rhino3d.com/';\n\n/**\n * Validate and normalize a Rhino Compute `serverUrl`.\n *\n * This is the single source of truth for \"is this a usable server URL?\" — both\n * `GrasshopperClient` (via `normalizeComputeConfig`) and the standalone-exported\n * `ComputeServerStats` constructor delegate here, so a given URL is accepted or\n * rejected identically no matter which entry point a caller uses.\n *\n * Rules (all enforced):\n * - non-empty (after trim)\n * - `http://` or `https://` scheme\n * - parseable by `new URL()`\n * - not the default public McNeel endpoint\n *\n * @param raw - The candidate server URL.\n * @returns The normalized URL with any trailing slashes removed.\n * @throws {RhinoComputeError} `INVALID_CONFIG` if any rule fails.\n */\nexport function validateServerUrl(raw: string): string {\n\tif (!raw?.trim()) {\n\t\tthrow new RhinoComputeError('serverUrl is required', ErrorCodes.INVALID_CONFIG, {\n\t\t\tcontext: { receivedServerUrl: raw }\n\t\t});\n\t}\n\n\tif (!raw.match(/^https?:\\/\\//)) {\n\t\tthrow new RhinoComputeError(\n\t\t\t`Invalid serverUrl: \"${raw}\". Must start with \"http://\" or \"https://\". ` +\n\t\t\t\t`For example: \"http://localhost:5000\" or \"https://example.com\"`,\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{ context: { receivedServerUrl: raw } }\n\t\t);\n\t}\n\n\ttry {\n\t\tnew URL(raw);\n\t} catch (err) {\n\t\tthrow new RhinoComputeError(\n\t\t\t`Invalid serverUrl: \"${raw}\". Must be a valid URL. ` +\n\t\t\t\t`Received error: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{\n\t\t\t\tcontext: { receivedServerUrl: raw },\n\t\t\t\toriginalError: err instanceof Error ? err : undefined\n\t\t\t}\n\t\t);\n\t}\n\n\tif (raw === DEFAULT_PUBLIC_ENDPOINT) {\n\t\tthrow new RhinoComputeError(\n\t\t\t'serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.',\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{ context: { receivedServerUrl: raw } }\n\t\t);\n\t}\n\n\treturn raw.replace(/\\/+$/, '');\n}\n","import { RhinoComputeError, ErrorCodes } from '../errors';\nimport { getLogger } from '../utils/logger';\nimport { validateServerUrl } from './validate-server-url';\n\n/**\n * ComputeServerStats provides methods to query Rhino Compute server statistics.\n *\n * @public Use this for server health monitoring and statistics.\n *\n * @example\n * ```typescript\n * const stats = new ComputeServerStats('http://localhost:6500', 'your-api-key');\n *\n * try {\n * const isOnline = await stats.isServerOnline();\n * const children = await stats.getActiveChildren();\n * const version = await stats.getVersion();\n *\n * // Or get everything at once\n * const allStats = await stats.getServerStats();\n * } finally {\n * await stats.dispose(); // Clean up resources\n * }\n * ```\n */\nexport default class ComputeServerStats {\n\tprivate readonly serverUrl: string;\n\tprivate readonly apiKey?: string;\n\tprivate disposed = false;\n\tprivate activeMonitors: Set<() => void> = new Set();\n\tprivate activeTimeouts: Set<ReturnType<typeof setTimeout>> = new Set();\n\n\t/**\n\t * @param serverUrl - Base URL of the Rhino Compute server with http:// or https:// scheme (e.g., 'http://localhost:6500')\n\t * @param apiKey - Optional API key for authentication\n\t */\n\t/** Timeout (ms) for the fast read/monitoring endpoints. */\n\tprivate static readonly DEFAULT_TIMEOUT_MS = 5000;\n\n\t/** Timeout (ms) for child-lifecycle POSTs — a cold Windows child can take ~30s to spawn. */\n\tprivate static readonly LIFECYCLE_TIMEOUT_MS = 60_000;\n\n\tconstructor(serverUrl: string, apiKey?: string) {\n\t\tthis.serverUrl = validateServerUrl(serverUrl);\n\t\tthis.apiKey = apiKey;\n\t}\n\n\t/**\n\t * Build request headers with optional API key.\n\t */\n\tprivate buildHeaders(): HeadersInit {\n\t\tconst headers: HeadersInit = {\n\t\t\t'Content-Type': 'application/json'\n\t\t};\n\n\t\tif (this.apiKey) {\n\t\t\theaders['RhinoComputeKey'] = this.apiKey;\n\t\t}\n\n\t\treturn headers;\n\t}\n\n\t/**\n\t * `fetch` wrapper that aborts after `timeoutMs` so a hung connection can't stall\n\t * a probe (or the `monitor()` loop) forever. Pass `0` to disable the timeout.\n\t */\n\tprivate fetchWithTimeout(\n\t\turl: string,\n\t\tinit: RequestInit = {},\n\t\ttimeoutMs: number = ComputeServerStats.DEFAULT_TIMEOUT_MS\n\t): Promise<Response> {\n\t\tconst requestInit: RequestInit = { headers: this.buildHeaders(), ...init };\n\t\tif (timeoutMs > 0 && !requestInit.signal) {\n\t\t\trequestInit.signal = AbortSignal.timeout(timeoutMs);\n\t\t}\n\t\treturn fetch(url, requestInit);\n\t}\n\n\t/**\n\t * Check if the server is online.\n\t *\n\t * This is a single-sample probe: it returns `true` only on a 2xx from the\n\t * proxy liveness root `/`, and `false` for every other outcome (non-2xx,\n\t * network error, or timeout). A cold or briefly-busy-but-up server can therefore\n\t * read as offline — callers that gate on this (e.g. client construction)\n\t * should retry rather than treat a single `false` as authoritative.\n\t *\n\t * @param timeoutMs - Abort the probe after this many ms (default: 5000).\n\t * Pass `0` to disable the timeout. Prevents a hung connection from\n\t * stalling the caller indefinitely.\n\t */\n\tpublic async isServerOnline(timeoutMs: number = 5000): Promise<boolean> {\n\t\tthis.ensureNotDisposed();\n\n\t\t// The rhino.compute proxy has no `/healthcheck` route; its real liveness\n\t\t// signal is `GET /`, which returns \"compute.rhino3d running\". Probing an\n\t\t// unknown path would instead be forwarded to a child and only tells us the\n\t\t// proxy can reach one.\n\t\tconst url = `${this.serverUrl}/`;\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(url, { method: 'GET' }, timeoutMs);\n\n\t\t\treturn response.ok;\n\t\t} catch (err) {\n\t\t\tgetLogger().debug('[ComputeServerStats] Fetch error:', err);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Get the number of active child processes on the server.\n\t *\n\t * By default the proxy's `/activechildren` endpoint will *spawn* children up\n\t * to the configured count if none are running, then report the count — which\n\t * wakes (and bills) an idle server. Pass `{ initialize: false }` for a passive\n\t * read that reports the current count without spawning; use this for\n\t * monitoring or before a purge/probe where you must not wake the server.\n\t *\n\t * @param options.initialize - When `false`, append `?initialize=false` so the\n\t * server reports without spawning. Defaults to `true` (the server's default).\n\t * @returns Number of active children, or null if unavailable\n\t */\n\tpublic async getActiveChildren(options: { initialize?: boolean } = {}): Promise<number | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\tconst { initialize = true } = options;\n\t\tconst url = initialize\n\t\t\t? `${this.serverUrl}/activechildren`\n\t\t\t: `${this.serverUrl}/activechildren?initialize=false`;\n\n\t\t// `initialize` mode may spawn children before answering — give it the\n\t\t// lifecycle budget; the passive read stays on the short default.\n\t\tconst timeoutMs = initialize\n\t\t\t? ComputeServerStats.LIFECYCLE_TIMEOUT_MS\n\t\t\t: ComputeServerStats.DEFAULT_TIMEOUT_MS;\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(url, {}, timeoutMs);\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to fetch active children:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst text = await response.text();\n\t\t\tconst count = parseInt(text.trim(), 10);\n\n\t\t\tif (isNaN(count)) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Invalid active children response:', text);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn count;\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error fetching active children:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Get the server version information.\n\t *\n\t * @returns Version object with rhino, compute, and git_sha, or null if unavailable\n\t */\n\tpublic async getVersion(): Promise<{\n\t\trhino: string;\n\t\tcompute: string;\n\t\tgit_sha: string | null;\n\t} | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/version`);\n\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to fetch version:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// Read body as text first, then try JSON.parse — avoids the\n\t\t\t// \"Body has already been read\" error if response.json() fails.\n\t\t\tconst text = await response.text();\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(text);\n\t\t\t\treturn {\n\t\t\t\t\trhino: json.rhino ?? '',\n\t\t\t\t\tcompute: json.compute ?? '',\n\t\t\t\t\tgit_sha: json.git_sha ?? null\n\t\t\t\t};\n\t\t\t} catch {\n\t\t\t\treturn { rhino: text, compute: '', git_sha: null };\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error fetching version:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Get the plugins installed on the server.\n\t *\n\t * Returns a `name → version` map of non-core plugins the server has loaded,\n\t * or `null` if the request failed. Pass `kind` to choose which inventory:\n\t * `'gh'` (default) lists Grasshopper add-on assemblies via\n\t * `/plugins/gh/installed`; `'rhino'` lists Rhino plugins via\n\t * `/plugins/rhino/installed`. Plugins that ship with Rhino / are core\n\t * libraries are excluded by the server.\n\t *\n\t * @param kind - `'gh'` for Grasshopper add-ons (default) or `'rhino'` for Rhino plugins.\n\t * @returns Map of plugin name to version, or `null` on failure.\n\t *\n\t * @example\n\t * ```ts\n\t * const gh = await stats.getInstalledPlugins(); // Grasshopper add-ons\n\t * const selvaVersion = gh?.['Selva'] ?? null;\n\t * ```\n\t */\n\tpublic async getInstalledPlugins(\n\t\tkind: 'gh' | 'rhino' = 'gh'\n\t): Promise<Record<string, string> | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/plugins/${kind}/installed`);\n\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn(`[ComputeServerStats] Failed to fetch ${kind} plugins:`, response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// Text-first so a non-JSON body can't throw \"body already read\".\n\t\t\tconst text = await response.text();\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(text);\n\t\t\t\treturn json && typeof json === 'object' ? (json as Record<string, string>) : null;\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tgetLogger().warn(`[ComputeServerStats] Error fetching ${kind} plugins:`, err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Get comprehensive server statistics.\n\t * Fetches all available server information in parallel.\n\t *\n\t * @returns Object containing server status and available stats\n\t */\n\tpublic async getServerStats(): Promise<{\n\t\tisOnline: boolean;\n\t\tversion?: { rhino: string; compute: string; git_sha: string | null };\n\t\tactiveChildren?: number;\n\t}> {\n\t\tthis.ensureNotDisposed();\n\n\t\tconst isOnline = await this.isServerOnline();\n\n\t\tif (!isOnline) {\n\t\t\treturn { isOnline: false };\n\t\t}\n\n\t\t// Passive child count — never spawn from a stats read, or merely viewing\n\t\t// server health would wake (and bill) an idle server.\n\t\tconst [version, activeChildren] = await Promise.all([\n\t\t\tthis.getVersion(),\n\t\t\tthis.getActiveChildren({ initialize: false })\n\t\t]);\n\n\t\treturn {\n\t\t\tisOnline: true,\n\t\t\t...(version && { version }),\n\t\t\t...(activeChildren !== null && { activeChildren })\n\t\t};\n\t}\n\n\t/**\n\t * Purge the server's solve-results / URL-data cache.\n\t *\n\t * POSTs to `cache/purge` and returns the number of entries removed, or `null`\n\t * if the request failed. This clears cached solve responses and fetched\n\t * definition-URL data; it does NOT evict the definition cache (active\n\t * `pointer` references stay valid).\n\t *\n\t * **Caveat:** `cache/purge` is forwarded by the rhino.compute proxy to a\n\t * single round-robin-selected child, so in a multi-child deployment one call\n\t * purges one child's cache. Call repeatedly (or size the pool to 1) if you\n\t * need a fleet-wide purge.\n\t *\n\t * @returns Number of entries removed, or `null` on failure.\n\t *\n\t * @example\n\t * ```ts\n\t * const removed = await stats.purgeCache();\n\t * if (removed !== null) console.log(`Purged ${removed} cached solves`);\n\t * ```\n\t */\n\tpublic async purgeCache(): Promise<number | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`, {\n\t\t\t\tmethod: 'POST'\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to purge cache:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// Read text-first so a non-JSON body can't throw \"body already read\".\n\t\t\tconst text = await response.text();\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(text);\n\t\t\t\treturn typeof json.purged === 'number' ? json.purged : null;\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error purging cache:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Best-effort fleet-wide cache purge across a multi-child deployment.\n\t *\n\t * A single {@link purgeCache} POST is forwarded by the rhino.compute proxy to\n\t * just ONE round-robin-selected child, so the other children keep serving\n\t * stale cached solves. There is no proxy endpoint that addresses children\n\t * individually, so this method reads the active child count (passively, never\n\t * spawning) and fires `2 × count` sequential purges, relying on the proxy's\n\t * round-robin to spread the hits across the pool.\n\t *\n\t * **This is best-effort, not a guarantee.** Round-robin can revisit one child\n\t * and skip another; under concurrent traffic the rotation drifts. The result's\n\t * `confident` flag is `true` only when the server reports a single child (where\n\t * one purge is exact) — surface it so callers don't over-promise. For a hard\n\t * fleet-wide guarantee, run the deployment at `--childcount 1` or add a\n\t * server-side fan-out endpoint.\n\t *\n\t * @returns `{ totalPurged, calls, children, confident }`, or `null` if the\n\t * child count couldn't be read (server unreachable). `totalPurged` sums the\n\t * per-call counts; `calls` is how many purges were issued; `children` is the\n\t * reported pool size; `confident` is `true` only at a single-child pool.\n\t *\n\t * @example\n\t * ```ts\n\t * const r = await stats.purgeAllChildren();\n\t * if (r && !r.confident) {\n\t * console.warn(`Purged ~${r.totalPurged} across ${r.children} children (best-effort)`);\n\t * }\n\t * ```\n\t */\n\tpublic async purgeAllChildren(): Promise<{\n\t\ttotalPurged: number;\n\t\tcalls: number;\n\t\tchildren: number;\n\t\tconfident: boolean;\n\t} | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\t// Passive read — must not spawn children just to purge them.\n\t\tconst children = await this.getActiveChildren({ initialize: false });\n\t\tif (children === null) {\n\t\t\tgetLogger().warn('[ComputeServerStats] purgeAllChildren: could not read child count');\n\t\t\treturn null;\n\t\t}\n\n\t\tif (children === 0) {\n\t\t\t// No live children means nothing is cached on the compute side.\n\t\t\treturn { totalPurged: 0, calls: 0, children: 0, confident: true };\n\t\t}\n\n\t\t// 2× the pool size gives round-robin a strong chance of reaching every\n\t\t// child at least once. Sequential (not parallel) so the proxy advances its\n\t\t// round-robin cursor one child per call rather than racing them onto one.\n\t\tconst calls = children * 2;\n\t\tlet totalPurged = 0;\n\t\tfor (let i = 0; i < calls; i++) {\n\t\t\tconst purged = await this.purgeCache();\n\t\t\tif (purged !== null) totalPurged += purged;\n\t\t}\n\n\t\treturn { totalPurged, calls, children, confident: children === 1 };\n\t}\n\n\t/**\n\t * Get the server's current UTC clock.\n\t *\n\t * GETs `/servertime`, which the server emits as a JSON-encoded ISO-8601\n\t * timestamp (e.g. `\"2026-06-18T08:30:00Z\"`). Useful for detecting clock skew\n\t * between caller and server. Returns `null` if the request failed or the body\n\t * isn't a parseable date.\n\t *\n\t * @returns A `Date` for the server's UTC time, or `null` on failure.\n\t */\n\tpublic async getServerTime(): Promise<Date | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/servertime`);\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to fetch server time:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// Body is a JSON string (\"2026-…Z\"); strip surrounding quotes if present.\n\t\t\tconst text = (await response.text()).trim().replace(/^\"|\"$/g, '');\n\t\t\tconst date = new Date(text);\n\t\t\treturn isNaN(date.getTime()) ? null : date;\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error fetching server time:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Get how long the rhino.compute proxy has been idle.\n\t *\n\t * GETs `/idlespan` on the proxy, which returns the seconds elapsed since the\n\t * last request was forwarded to a compute child. This is a proxy-level metric\n\t * (not proxied to a child) used by autoscalers to decide when a node can be\n\t * drained. Returns `null` if unavailable.\n\t *\n\t * @returns Idle time in seconds, or `null` on failure.\n\t */\n\tpublic async getIdleSpan(): Promise<number | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to fetch idle span:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst seconds = parseFloat((await response.text()).trim());\n\t\t\treturn isNaN(seconds) ? null : seconds;\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error fetching idle span:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Fill the compute child pool up to the server's configured baseline.\n\t *\n\t * POSTs `/launch-children`. No-op when the pool is already at or above the\n\t * configured `--childcount`. Returns `{ spawned, active }` — how many children\n\t * were started and the resulting child count — or `null` on failure.\n\t *\n\t * To raise capacity above the baseline use {@link launchChild}; the baseline\n\t * itself can only be changed by restarting rhino.compute.\n\t *\n\t * @returns `{ spawned, active }`, or `null` on failure.\n\t */\n\tpublic async launchChildren(): Promise<{ spawned: number[]; active: number } | null> {\n\t\treturn this.postJson('/launch-children');\n\t}\n\n\t/**\n\t * Add a single compute child to the pool, optionally on a specific port.\n\t *\n\t * POSTs `/launch-child` (with `?port=N` when `port` is given). Unlike\n\t * {@link launchChildren}, this can push the pool above the baseline, up to the\n\t * server's `MaxChildren` cap. Returns `{ spawned: [port] }` on success, or\n\t * `null` on failure (server replies 400 for a bad port, 409 if the port is in\n\t * use, 503 at the max-children cap).\n\t *\n\t * @param port - Optional specific port to launch on; otherwise the next free one.\n\t * @returns `{ spawned }` listing the launched port, or `null` on failure.\n\t */\n\tpublic async launchChild(port?: number): Promise<{ spawned: number[] } | null> {\n\t\tconst path = port === undefined ? '/launch-child' : `/launch-child?port=${port}`;\n\t\treturn this.postJson(path);\n\t}\n\n\t/**\n\t * Gracefully shut down compute children without respawning them.\n\t *\n\t * POSTs `/shutdown-children`. With no `port` it shuts down every child; with\n\t * `port` it targets just that one. Children do not respawn, but the next\n\t * `/grasshopper` request auto-spawns the pool back to the baseline. Returns\n\t * `{ shutdown, active }` — how many were stopped and the remaining count — or\n\t * `null` on failure.\n\t *\n\t * @param port - Optional port to target; omit to shut down all children.\n\t * @returns `{ shutdown, active }`, or `null` on failure.\n\t */\n\tpublic async shutdownChildren(\n\t\tport?: number\n\t): Promise<{ shutdown: number; active: number } | null> {\n\t\tconst path = port === undefined ? '/shutdown-children' : `/shutdown-children?port=${port}`;\n\t\treturn this.postJson(path);\n\t}\n\n\t/**\n\t * Shut down compute children and respawn replacements (rolling restart).\n\t *\n\t * POSTs `/recycle-children`. With no `port` it recycles every child; with\n\t * `port` it recycles just that one. The server recycles sequentially (each\n\t * replacement is serving before the next child is stopped) so the pool never\n\t * drops to zero mid-recycle. Returns `{ shutdown, spawned, active }`, or\n\t * `null` on failure.\n\t *\n\t * @param port - Optional port to target; omit to recycle all children.\n\t * @returns `{ shutdown, spawned, active }`, or `null` on failure.\n\t */\n\tpublic async recycleChildren(\n\t\tport?: number\n\t): Promise<{ shutdown: number; spawned: number[]; active: number } | null> {\n\t\tconst path = port === undefined ? '/recycle-children' : `/recycle-children?port=${port}`;\n\t\treturn this.postJson(path);\n\t}\n\n\t/**\n\t * POST a control endpoint that replies with a JSON object and return it,\n\t * degrading to `null` on any non-2xx, non-JSON, or network failure. Shared by\n\t * the child-lifecycle methods so their failure semantics stay identical. Uses\n\t * the longer lifecycle timeout since a spawn/recycle can take ~30s.\n\t */\n\tprivate async postJson<T>(path: string): Promise<T | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(\n\t\t\t\t`${this.serverUrl}${path}`,\n\t\t\t\t{ method: 'POST' },\n\t\t\t\tComputeServerStats.LIFECYCLE_TIMEOUT_MS\n\t\t\t);\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn(`[ComputeServerStats] POST ${path} failed:`, response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t// Text-first so a non-JSON body can't throw \"body already read\".\n\t\t\tconst text = await response.text();\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(text) as T;\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tgetLogger().warn(`[ComputeServerStats] Error on POST ${path}:`, err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Continuously monitor server stats at specified interval.\n\t *\n\t * @param callback - Function called with stats on each interval\n\t * @param intervalMs - Milliseconds between checks (default: 5000)\n\t * @returns Function to stop monitoring\n\t *\n\t * @example\n\t * ```typescript\n\t * const stopMonitoring = stats.monitor((data) => {\n\t * console.log('Server stats:', data);\n\t * }, 3000);\n\t *\n\t * // Later...\n\t * stopMonitoring();\n\t * ```\n\t */\n\tpublic monitor(\n\t\tcallback: (stats: Awaited<ReturnType<typeof this.getServerStats>>) => void,\n\t\tintervalMs: number = 5000\n\t): () => void {\n\t\tthis.ensureNotDisposed();\n\n\t\tlet active = true;\n\t\tlet currentTimeoutId: ReturnType<typeof setTimeout> | null = null;\n\n\t\tgetLogger().info(`🔄 Starting server stats monitoring every ${intervalMs}ms`);\n\n\t\tconst check = async () => {\n\t\t\t// Clear current timeout from tracking since it has fired\n\t\t\tif (currentTimeoutId !== null) {\n\t\t\t\tthis.activeTimeouts.delete(currentTimeoutId);\n\t\t\t\tcurrentTimeoutId = null;\n\t\t\t}\n\n\t\t\tif (!active || this.disposed) return;\n\n\t\t\ttry {\n\t\t\t\tconst _stats = await this.getServerStats();\n\n\t\t\t\t// Check again after async operation to prevent race condition\n\t\t\t\tif (!active || this.disposed) return;\n\n\t\t\t\ttry {\n\t\t\t\t\tcallback(_stats);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tgetLogger().error('[ComputeServerStats] Monitor callback threw:', err);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tgetLogger().error('[ComputeServerStats] Failed to fetch stats during monitor:', err);\n\t\t\t}\n\n\t\t\tif (active && !this.disposed) {\n\t\t\t\tcurrentTimeoutId = setTimeout(() => void check(), intervalMs);\n\t\t\t\tthis.activeTimeouts.add(currentTimeoutId);\n\t\t\t}\n\t\t};\n\n\t\tconst stopMonitoring = () => {\n\t\t\tactive = false;\n\n\t\t\t// Clear any pending timeout\n\t\t\tif (currentTimeoutId !== null) {\n\t\t\t\tclearTimeout(currentTimeoutId);\n\t\t\t\tthis.activeTimeouts.delete(currentTimeoutId);\n\t\t\t\tcurrentTimeoutId = null;\n\t\t\t}\n\n\t\t\tthis.activeMonitors.delete(stopMonitoring);\n\t\t};\n\n\t\tthis.activeMonitors.add(stopMonitoring);\n\n\t\t// Explicitly mark as fire-and-forget since we don't need to await the initial call\n\t\tvoid check();\n\n\t\treturn stopMonitoring;\n\t}\n\n\t/**\n\t * Disposes of all resources and stops all active monitors.\n\t * Call this when you're done using the stats instance.\n\t */\n\tpublic async dispose(): Promise<void> {\n\t\tif (this.disposed) return;\n\n\t\tthis.disposed = true;\n\n\t\t// Stop all active monitors (this will also clear their timeouts)\n\t\tfor (const stopMonitor of this.activeMonitors) {\n\t\t\tstopMonitor();\n\t\t}\n\t\tthis.activeMonitors.clear();\n\n\t\t// Clear any remaining timeouts (defensive cleanup)\n\t\tfor (const timeoutId of this.activeTimeouts) {\n\t\t\tclearTimeout(timeoutId);\n\t\t}\n\t\tthis.activeTimeouts.clear();\n\t}\n\n\t/**\n\t * Ensures the instance 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'ComputeServerStats has been disposed and cannot be used',\n\t\t\t\tErrorCodes.INVALID_STATE,\n\t\t\t\t{ context: { disposed: this.disposed } }\n\t\t\t);\n\t\t}\n\t}\n}\n","import { RhinoComputeError, ErrorCodes } from '../errors';\n\n/** Node's `Buffer` when present (faster path), else `undefined` in browsers/workers. */\nfunction getNodeBuffer(): typeof Buffer | undefined {\n\tconst buf = (globalThis as { Buffer?: typeof Buffer }).Buffer;\n\treturn typeof buf === 'function' ? buf : undefined;\n}\n\n/**\n * Encodes a string to base64 (Node 20+ safe)\n *\n * @internal Internal encoding helper — kept internal to `@selvajs/compute`.\n *\n * @param str - String to encode\n * @returns Base64 encoded string\n */\nexport function encodeStringToBase64(str: string): string {\n\tconst Buffer = getNodeBuffer();\n\tif (Buffer) {\n\t\treturn Buffer.from(str, 'utf-8').toString('base64');\n\t}\n\t// Browser/worker fallback: UTF-8 encode, then reuse the byte-array encoder.\n\treturn base64ByteArray(new TextEncoder().encode(str));\n}\n\n/**\n * Checks if a string is valid base64\n *\n * @internal Internal encoding helper — kept internal to `@selvajs/compute`.\n *\n * @param str - String to check\n * @returns True if the string is valid base64\n */\nexport function isBase64(str: string): boolean {\n\tif (!str || str.length < 2) return false;\n\t// Length must be a multiple of 4, only alphabet chars + at most 2 trailing '='\n\tif (str.length % 4 !== 0) return false;\n\treturn /^[A-Za-z0-9+/]+={0,2}$/.test(str);\n}\n\n/**\n * Decodes a base64 string to binary data (Uint8Array)\n *\n * @internal Internal encoding helper — kept internal to `@selvajs/compute`.\n *\n * @param base64File - Base64 encoded string\n * @returns Decoded binary data as Uint8Array\n * @throws {RhinoComputeError} If base64 decoding is not supported in this environment.\n */\nexport function decodeBase64ToBinary(base64File: string): Uint8Array {\n\t// Prefer Buffer in Node — it's faster and avoids the latin-1 string detour\n\t// that atob + charCodeAt requires.\n\tconst Buffer = getNodeBuffer();\n\tif (Buffer) {\n\t\tconst buf = Buffer.from(base64File, 'base64');\n\t\treturn new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n\t}\n\tif (typeof globalThis.atob === 'function') {\n\t\tconst binary = globalThis.atob(base64File);\n\t\tconst bytes = new Uint8Array(binary.length);\n\t\tfor (let i = 0; i < binary.length; i++) {\n\t\t\tbytes[i] = binary.charCodeAt(i) & 0xff;\n\t\t}\n\t\treturn bytes;\n\t}\n\n\tthrow new RhinoComputeError(\n\t\t'Base64 decoding not supported in this environment.',\n\t\tErrorCodes.INVALID_STATE,\n\t\t{ context: { environmentInfo: 'atob or Buffer not available' } }\n\t);\n}\n\n/**\n * Encodes binary data (Uint8Array) to base64 string.\n *\n * @internal Internal encoding helper — kept internal to `@selvajs/compute`.\n *\n * Uses Node's `Buffer` when available (faster, single allocation) and falls\n * back to `btoa` over a latin-1 string in browsers/workers.\n */\nexport function base64ByteArray(bytes: Uint8Array): string {\n\tconst Buffer = getNodeBuffer();\n\tif (Buffer) {\n\t\treturn Buffer.from(bytes).toString('base64');\n\t}\n\tif (typeof globalThis.btoa === 'function') {\n\t\t// Build a latin-1 string in chunks to avoid blowing the call stack on\n\t\t// large inputs (a single fromCharCode(...verylargearray) can exceed it).\n\t\tconst CHUNK = 0x8000;\n\t\tlet s = '';\n\t\tfor (let i = 0; i < bytes.length; i += CHUNK) {\n\t\t\t// A Uint8Array subarray is array-like, so pass it straight to\n\t\t\t// fromCharCode.apply — no need to copy it into a plain Array first.\n\t\t\ts += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK) as unknown as number[]);\n\t\t}\n\t\treturn globalThis.btoa(s);\n\t}\n\tthrow new RhinoComputeError(\n\t\t'Base64 encoding not supported in this environment.',\n\t\tErrorCodes.INVALID_STATE,\n\t\t{ context: { environmentInfo: 'btoa or Buffer not available' } }\n\t);\n}\n","import { RhinoComputeError, ErrorCodes } from '@/core/errors';\nimport { getLogger } from '@/core/utils/logger';\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 * Decode the inline files carried in a compute response into `ProcessedFile`s.\n *\n * Pure and synchronous: base64 items are decoded to binary, plain-text items are\n * passed through, and the archive path is derived from `subFolder` + name. Items\n * with no usable `data` are skipped. This is the half of file handling that both\n * public entry points share; it never touches the network and never throws.\n *\n * @param dataItems - `FileData` items from the compute response.\n * @returns The decoded files.\n */\nconst decodeResponseFiles = (dataItems: FileData[]): ProcessedFile[] => {\n\tconst processedFiles: ProcessedFile[] = [];\n\n\tdataItems.forEach((item) => {\n\t\tconst fileName = `${item.fileName}${item.fileType}`;\n\t\tconst filePath =\n\t\t\titem.subFolder && item.subFolder.trim() !== '' ? `${item.subFolder}/${fileName}` : fileName;\n\n\t\tif (item.isBase64Encoded === true && item.data) {\n\t\t\t// `decodeBase64ToBinary` already returns a correctly-bounded view;\n\t\t\t// re-wrapping `.buffer` would discard its byteOffset/byteLength and\n\t\t\t// expose the whole (possibly pooled) backing buffer as corrupt content.\n\t\t\tprocessedFiles.push({\n\t\t\t\tfileName,\n\t\t\t\tcontent: decodeBase64ToBinary(item.data),\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,\n\t\t\t\tcontent: item.data,\n\t\t\t\tpath: filePath\n\t\t\t});\n\t\t}\n\t});\n\n\treturn processedFiles;\n};\n\n/**\n * Fetch externally-referenced files over HTTP into `ProcessedFile`s.\n *\n * Async and fallible by nature. A failed fetch (network error or non-OK status)\n * is logged and that file is dropped — the rest still resolve — so one dead URL\n * degrades the result rather than aborting the whole batch. This swallow is\n * deliberate and pinned by tests; callers receive only the files that succeeded.\n *\n * @param refs - External file references to fetch.\n * @returns The successfully-fetched files (failures omitted).\n */\nconst fetchRemoteFiles = async (refs: FileBaseInfo[]): Promise<ProcessedFile[]> => {\n\tconst fetched = await Promise.all(\n\t\trefs.map(async (file) => {\n\t\t\ttry {\n\t\t\t\tconst response = await fetch(file.filePath);\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tgetLogger().warn(`Failed to fetch additional file from URL: ${file.filePath}`);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tconst fileBlob = await response.blob();\n\t\t\t\tconst arrayBuffer = await fileBlob.arrayBuffer();\n\t\t\t\treturn {\n\t\t\t\t\tfileName: file.fileName,\n\t\t\t\t\tcontent: new Uint8Array(arrayBuffer),\n\t\t\t\t\tpath: file.fileName\n\t\t\t\t} as ProcessedFile;\n\t\t\t} catch (error) {\n\t\t\t\tgetLogger().error(`Error fetching additional file from URL: ${file.filePath}`, error);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t})\n\t);\n\n\treturn fetched.filter((f): f is ProcessedFile => f !== null);\n};\n\n/**\n * Compose the decoded response files with any fetched external files.\n *\n * @param dataItems - `FileData` items from the compute response.\n * @param additionalFiles - Optional external file references to fetch and include.\n * @returns A Promise resolving to the combined `ProcessedFile` list.\n */\nconst processFiles = async (\n\tdataItems: FileData[],\n\tadditionalFiles: FileBaseInfo[] | FileBaseInfo | null\n): Promise<ProcessedFile[]> => {\n\tconst processedFiles = decodeResponseFiles(dataItems);\n\n\tif (additionalFiles) {\n\t\tconst filesArray = Array.isArray(additionalFiles) ? additionalFiles : [additionalFiles];\n\t\tprocessedFiles.push(...(await fetchRemoteFiles(filesArray)));\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 { zip, 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\t// Async `zip` deflates on a worker thread instead of blocking the main thread\n\t// like `zipSync` — keeps the UI responsive for large geometry exports.\n\tconst zipped = await new Promise<Uint8Array>((resolve, reject) => {\n\t\tzip(zipData, { level: 6 }, (err, data) => (err ? reject(err) : resolve(data)));\n\t});\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"],"mappings":"mOAIO,IAAMA,EAAa,CACzB,cAAe,gBACf,WAAY,aACZ,iBAAkB,mBAClB,kBAAmB,oBACnB,cAAe,gBACf,WAAY,aACZ,cAAe,gBACf,cAAe,gBACf,cAAe,gBACf,eAAgB,iBAChB,aAAc,eACd,kBAAmB,oBACnB,eAAgB,iBAEhB,kBAAmB,oBAEnB,WAAY,aAEZ,QAAS,UAQT,sBAAuB,uBACxB,EASaC,EAAN,MAAMC,UAA0B,KAAM,CAM5C,YACCC,EACAC,EAAe,gBACfC,EACC,CACD,MAAMF,CAAO,EAVdG,EAAA,KAAgB,QAChBA,EAAA,KAAgB,cAChBA,EAAA,KAAgB,WAChBA,EAAA,KAAgB,iBAQf,KAAK,KAAO,oBACZ,KAAK,KAAOF,EACZ,KAAK,WAAaC,GAAS,WAC3B,KAAK,QAAUA,GAAS,QACxB,KAAK,cAAgBA,GAAS,cAC1BA,GAAS,gBACX,KAA6B,MAAQA,EAAQ,cAEhD,CASA,OAAO,cACNE,EACAC,EACAC,EACC,CACD,OAAO,IAAIP,EACV,UAAUK,CAAS,0BAA0BC,EAAe,cAAcA,CAAY,IAAM,EAAE,GAC9FR,EAAW,cACX,CAAE,QAAS,CAAE,UAAAO,EAAW,aAAAC,EAAc,GAAGC,CAAQ,CAAE,CACpD,CACD,CAKA,OAAO,iBACNC,EACAC,E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AOhB,CACR,EASA,eAAeC,GAAqBgB,EAAwBC,EAAgC,CAC3F,GAAM,CAAE,IAAAC,EAAK,QAAAC,CAAQ,EAAI,KAAM,QAAO,QAAQ,EAGxCC,EAAsC,CAAC,EAC7CJ,EAAM,QAASP,GAAS,CACvBW,EAAQX,EAAK,IAAI,EAAI,OAAOA,EAAK,SAAY,SAAWU,EAAQV,EAAK,OAAO,EAAIA,EAAK,OACtF,CAAC,EAID,IAAMY,EAAS,MAAM,IAAI,QAAoB,CAACC,EAASC,IAAW,CACjEL,EAAIE,EAAS,CAAE,MAAO,CAAE,EAAG,CAAC1B,EAAK8B,IAAU9B,EAAM6B,EAAO7B,CAAG,EAAI4B,EAAQE,CAAI,CAAE,CAC9E,CAAC,EAEKC,EAAO,IAAI,KAAK,CAACJ,CAAkB,EAAG,CAAE,KAAM,iBAAkB,CAAC,EACvEK,GAASD,EAAM,GAAGR,CAAO,MAAM,CAChC,CASA,SAASS,GAASD,EAAYE,EAAkB,CAC/C,GAAI,OAAO,SAAa,IACvB,MAAM,IAAIhC,EACT,+DACAC,EAAW,aACX,CACC,QAAS,CAAE,SAAU,WAAY,YAAa,UAAW,CAC1D,CACD,EAGD,IAAMgC,EAAI,SAAS,cAAc,GAAG,EACpCA,EAAE,KAAO,IAAI,gBAAgBH,CAAI,EACjCG,EAAE,SAAWD,EACbC,EAAE,MAAM,EACR,IAAI,gBAAgBA,EAAE,IAAI,CAC3B","names":["ErrorCodes","RhinoComputeError","_RhinoComputeError","message","code","options","__publicField","inputName","expectedType","context","paramType","paramName","NoOpLogger","ConsoleLogger","message","args","internalLogger","getLogger","setLogger","logger","enableDebugLogging","parseServerTiming","headerValue","timing","sawMetric","part","name","params","durParam","p","dur","key","DEFAULT_RETRY","RETRYABLE_STATUS","resolveRetryPolicy","policy","parseRetryAfter","seconds","dateMs","delta","backoffDelay","attempt","exponential","jitter","sleep","ms","signal","resolve","reject","id","onAbort","throwHttpError","response","fullUrl","requestId","requestSize","serverUrl","errorBody","serverCode","status","statusText","responseHeaders","value","trimmed","bodyHint","context","error","ErrorCodes","code","mapServerErrorCode","RhinoComputeError","buildUrl","endpoint","base","path","isLocalhost","host","buildHeaders","config","headers","getLogger","generateRequestId","log","message","debug","composeSignal","callerSignal","timeoutMs","signals","cleanup","ctrl","prevCleanup","handleResponse","startTime","onServerTiming","responseTime","parsedForCode","parsed","serverMessage","exceptionType","stack","stackStr","e","err","attemptFetch","ctx","retryPolicy","totalAttempts","retryAfterMs","delayMs","fatal","fetchRhinoCompute","args","body","sizeKb","emoji","lastError","result","DEFAULT_PUBLIC_ENDPOINT","validateServerUrl","raw","RhinoComputeError","ErrorCodes","err","_ComputeServerStats","serverUrl","apiKey","__publicField","validateServerUrl","headers","url","init","timeoutMs","requestInit","err","getLogger","options","initialize","response","text","count","json","kind","version","activeChildren","children","calls","totalPurged","i","purged","date","seconds","port","path","callback","intervalMs","active","currentTimeoutId","check","_stats","stopMonitoring","stopMonitor","timeoutId","RhinoComputeError","ErrorCodes","ComputeServerStats","getNodeBuffer","buf","encodeStringToBase64","str","Buffer","base64ByteArray","isBase64","decodeBase64ToBinary","base64File","binary","bytes","i","RhinoComputeError","ErrorCodes","s","extractFilesFromComputeResponse","downloadableFiles","additionalFiles","processFiles","err","RhinoComputeError","ErrorCodes","downloadFileData","fileFoldername","processedFiles","createAndDownloadZip","decodeResponseFiles","dataItems","item","fileName","filePath","decodeBase64ToBinary","fetchRemoteFiles","refs","file","response","getLogger","arrayBuffer","error","f","filesArray","files","zipName","zip","strToU8","zipData","zipped","resolve","reject","data","blob","saveFile","filename","a"]}
|
package/dist/chunk-2QHLW6ZL.cjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var A=Object.defineProperty;var M=(r,e,t)=>e in r?A(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var ae=(r,e)=>{for(var t in e)A(r,t,{get:e[t],enumerable:!0})};var g=(r,e,t)=>M(r,typeof e!="symbol"?e+"":e,t);var a={NETWORK_ERROR:"NETWORK_ERROR",AUTH_ERROR:"AUTH_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",COMPUTATION_ERROR:"COMPUTATION_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",CORS_ERROR:"CORS_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR",INVALID_STATE:"INVALID_STATE",INVALID_INPUT:"INVALID_INPUT",INVALID_CONFIG:"INVALID_CONFIG",BROWSER_ONLY:"BROWSER_ONLY",ENVIRONMENT_ERROR:"ENVIRONMENT_ERROR",ENCODING_ERROR:"ENCODING_ERROR",MALFORMED_DEFAULT:"MALFORMED_DEFAULT",SUPERSEDED:"SUPERSEDED",ABORTED:"ABORTED",DEFINITION_NOT_CACHED:"DEFINITION_NOT_CACHED"},d= exports.d =class r extends Error{constructor(t,n="UNKNOWN_ERROR",o){super(t);g(this,"code");g(this,"statusCode");g(this,"context");g(this,"originalError");this.name="RhinoComputeError",this.code=n,this.statusCode=_optionalChain([o, 'optionalAccess', _2 => _2.statusCode]),this.context=_optionalChain([o, 'optionalAccess', _3 => _3.context]),this.originalError=_optionalChain([o, 'optionalAccess', _4 => _4.originalError]),_optionalChain([o, 'optionalAccess', _5 => _5.originalError])&&(this.cause=o.originalError)}static missingValues(t,n,o){return new r(`Input "${t}" has no values defined${n?` (expected ${n})`:""}`,a.INVALID_INPUT,{context:{inputName:t,expectedType:n,...o}})}static unknownParamType(t,n,o){return new r(`Unknown paramType: ${t}`,a.VALIDATION_ERROR,{context:{receivedParamType:t,paramName:n,...o}})}};var T=class{debug(){}info(){}warn(){}error(){}},N=class{debug(e,...t){console.debug(e,...t)}info(e,...t){console.info(e,...t)}warn(e,...t){console.warn(e,...t)}error(e,...t){console.error(e,...t)}},$=new T;function f(){return $}function U(r){$=r===null?new T:r}function x(){U(new N)}function k(r){if(!r)return null;let e={raw:r},t=!1;for(let n of r.split(",")){let[o,...u]=n.trim().split(";"),p=u.find(c=>c.trim().toLowerCase().startsWith("dur"));if(!p)continue;let s=Number(p.split("=")[1]);if(!Number.isFinite(s))continue;let l=o.trim().toLowerCase();(l==="decode"||l==="solve"||l==="encode")&&(e[l]=s,t=!0)}return t?e:null}var v={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},D=new Set([502,503,504]);function B(r){return r?{attempts:_nullishCoalesce(r.attempts, () => (v.attempts)),baseDelayMs:_nullishCoalesce(r.baseDelayMs, () => (v.baseDelayMs)),maxDelayMs:_nullishCoalesce(r.maxDelayMs, () => (v.maxDelayMs)),retryOn429:_nullishCoalesce(r.retryOn429, () => (v.retryOn429))}:v}function q(r){if(!r)return null;let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);if(Number.isFinite(t)){let n=t-Date.now();return n>0?n:0}return null}function S(r,e){let t=e.baseDelayMs*Math.pow(2,r),n=Math.random()*e.baseDelayMs;return Math.min(t+n,e.maxDelayMs)}function K(r,e){return new Promise((t,n)=>{if(_optionalChain([e, 'optionalAccess', _6 => _6.aborted])){n(new DOMException("Aborted","AbortError"));return}let o=setTimeout(()=>{_optionalChain([e, 'optionalAccess', _7 => _7.removeEventListener, 'call', _8 => _8("abort",u)]),t()},r),u=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))};_optionalChain([e, 'optionalAccess', _9 => _9.addEventListener, 'call', _10 => _10("abort",u,{once:!0})])})}function W(r,e,t,n,o,u,p){let{status:s,statusText:l}=r,c={};r.headers.forEach((I,L)=>{c[L]=I});let m=u.trim(),i=m?` \u2014 ${m.slice(0,200)}${m.length>200?"\u2026":""}`:"",y={url:e,requestId:t,method:"POST",requestSize:n,serverUrl:o,responseBody:u||void 0,responseHeaders:c},E={401:{message:`HTTP ${s}: ${l}${i}`,code:a.AUTH_ERROR},403:{message:`HTTP ${s}: ${l}${i}`,code:a.AUTH_ERROR},404:{message:`Endpoint not found: ${e}`,code:a.NETWORK_ERROR},413:{message:`Request too large: ${(n/1024).toFixed(2)}KB`,code:a.VALIDATION_ERROR},429:{message:`Rate limit exceeded${i}`,code:a.NETWORK_ERROR},500:{message:`Server error: ${l}${i}`,code:a.COMPUTATION_ERROR},502:{message:`Service unavailable: ${l}${i}`,code:a.NETWORK_ERROR},503:{message:`Service unavailable: ${l}${i}`,code:a.NETWORK_ERROR},504:{message:`Service unavailable: ${l}${i}`,code:a.NETWORK_ERROR}}[s]||{message:`HTTP ${s}: ${l}${i}`,code:a.UNKNOWN_ERROR},w=_nullishCoalesce(H(p), () => (E.code));throw new d(E.message,w,{statusCode:s,context:y})}function H(r){if(r==="definition_not_cached")return a.DEFINITION_NOT_CACHED}function z(r,e){let t=e.replace(/\/+$/,""),n=r.replace(/^\/+/,"");return`${t}/${n}`}function V(r){try{let e=new URL(r).host;return/^(localhost|127\.0\.0\.1|::1)(:\d+)?$/i.test(e)}catch (e2){return/(localhost|127\.0\.0\.1)/i.test(r)}}function J(r,e){let t={"X-Request-ID":r,"Content-Type":"application/json",...e.authToken&&{Authorization:e.authToken},...e.apiKey&&{RhinoComputeKey:e.apiKey}};return!e.apiKey&&!e.authToken&&!V(e.serverUrl)&&f().warn(`\u26A0\uFE0F [Rhino Compute] Request [${r}] targets remote server (${e.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited.`),t}function j(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function R(r,e){e&&f().debug(r)}function G(r,e){let t=[],n=()=>{};if(r&&t.push(r),e&&e>0)if(typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function")t.push(AbortSignal.timeout(e));else{let s=new AbortController,l=setTimeout(()=>s.abort(),e);n=()=>clearTimeout(l),t.push(s.signal)}if(t.length===0)return{signal:void 0,cleanup:n};if(t.length===1)return{signal:t[0],cleanup:n};if(typeof AbortSignal<"u"&&typeof AbortSignal.any=="function")return{signal:AbortSignal.any(t),cleanup:n};let o=new AbortController,u=()=>o.abort();for(let s of t){if(s.aborted){o.abort();break}s.addEventListener("abort",u,{once:!0})}let p=n;return n=()=>{p();for(let s of t)s.removeEventListener("abort",u)},{signal:o.signal,cleanup:n}}async function Y(r,e,t,n,o,u,p,s){let l=Math.round(performance.now()-u);if(!r.ok){let c=await r.text();p&&(R(`\u274C Request [${t}] failed with HTTP ${r.status} in ${l}ms`,!0),R(` URL: ${e}`,!0),R(` Status: ${r.status} ${r.statusText}`,!0),c&&R(` Response body: ${c.substring(0,500)}${c.length>500?"...":""}`,!0));let m;try{let i=JSON.parse(c);typeof _optionalChain([i, 'optionalAccess', _11 => _11.code])=="string"&&(m=i.code)}catch (e3){}if(r.status===500)try{let i=JSON.parse(c);if(_optionalChain([i, 'optionalAccess', _12 => _12.values])&&(i.errors||i.warnings))return p&&(R(`\u26A0\uFE0F Request [${t}] completed with Grasshopper errors in ${l}ms`,!0),_optionalChain([i, 'access', _13 => _13.errors, 'optionalAccess', _14 => _14.length])>0&&R(` Errors: ${JSON.stringify(i.errors,null,2)}`,!0),_optionalChain([i, 'access', _15 => _15.warnings, 'optionalAccess', _16 => _16.length])>0&&R(` Warnings: ${JSON.stringify(i.warnings,null,2)}`,!0)),i;let y=typeof _optionalChain([i, 'optionalAccess', _17 => _17.message])=="string"&&i.message||typeof _optionalChain([i, 'optionalAccess', _18 => _18.Message])=="string"&&i.Message||"",h=typeof _optionalChain([i, 'optionalAccess', _19 => _19.ExceptionType])=="string"&&i.ExceptionType||"",E=_nullishCoalesce(_optionalChain([i, 'optionalAccess', _20 => _20.stackTrace]), () => (_optionalChain([i, 'optionalAccess', _21 => _21.StackTrace]))),w=Array.isArray(E)?E.join(`
|
|
2
|
-
`):E||"";y?c=`${h?`${h}: `:""}${y}${w?`
|
|
3
|
-
${w}`:""}`:_optionalChain([i, 'optionalAccess', _22 => _22.error])&&(c=typeof i.error=="string"?i.error:JSON.stringify(i.error,null,2))}catch(i){p&&R(` Failed to parse error body as JSON: ${i}`,!0)}W(r,e,t,n,o,c,m)}if(R(`\u2705 Request [${t}] completed in ${l}ms`,p),s){let c=k(r.headers.get("Server-Timing"));if(c)try{s(c)}catch(m){p&&R(` onServerTiming callback threw: ${m}`,!0)}}try{return await r.json()}catch(c){throw new d("Failed to parse JSON response",a.NETWORK_ERROR,{statusCode:r.status,context:{url:e,requestId:t},originalError:c instanceof Error?c:new Error(String(c))})}}async function Z(r,e,t,n){let{signal:o,cleanup:u}=G(r.config.signal,r.config.timeoutMs),p=performance.now();try{let s=await fetch(r.fullUrl,{method:"POST",body:r.body,headers:r.headers,signal:o});if((D.has(s.status)||e.retryOn429&&s.status===429)&&t<n-1){let m=q(s.headers.get("Retry-After")),i=m!==null?Math.min(m,e.maxDelayMs):S(t,e);return await s.text().catch(()=>{}),{ok:!1,retry:!0,delayMs:i,cause:new d(`HTTP ${s.status} ${s.statusText} (will retry)`,a.NETWORK_ERROR,{statusCode:s.status,context:{requestId:r.requestId}})}}return{ok:!0,value:await Y(s,r.fullUrl,r.requestId,r.requestSize,r.config.serverUrl,p,r.config.debug,r.config.onServerTiming)}}catch(s){if(s instanceof Error&&(s.name==="AbortError"||s.name==="TimeoutError")){if(_optionalChain([r, 'access', _23 => _23.config, 'access', _24 => _24.signal, 'optionalAccess', _25 => _25.aborted])===!0)return{ok:!1,retry:!1,cause:new d("Request aborted by caller",a.UNKNOWN_ERROR,{context:{endpoint:r.endpoint,requestId:r.requestId,requestSize:r.requestSize},originalError:s})};let c=new d(`Request timed out after ${r.config.timeoutMs}ms`,a.TIMEOUT_ERROR,{context:{serverUrl:r.config.serverUrl,timeoutMs:r.config.timeoutMs,url:r.fullUrl,requestId:r.requestId,endpoint:r.endpoint,requestSize:r.requestSize}});return t<n-1?{ok:!1,retry:!0,delayMs:S(t,e),cause:c}:{ok:!1,retry:!1,cause:c}}if(s instanceof TypeError){let l=new d(`Network error: ${s.message}`,a.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,url:r.fullUrl,requestId:r.requestId,endpoint:r.endpoint,requestSize:r.requestSize},originalError:s});return t<n-1?{ok:!1,retry:!0,delayMs:S(t,e),cause:l}:{ok:!1,retry:!1,cause:l}}if(s instanceof d){let l=s.statusCode;return l!==void 0&&(D.has(l)||e.retryOn429&&l===429)&&t<n-1?{ok:!1,retry:!0,delayMs:S(t,e),cause:s}:{ok:!1,retry:!1,cause:s}}return{ok:!1,retry:!1,cause:new d(s instanceof Error?s.message:String(s),a.UNKNOWN_ERROR,{context:{endpoint:r.endpoint,requestId:r.requestId},originalError:s instanceof Error?s:new Error(String(s))})}}finally{u()}}async function X(r,e,t){let n=j(),o=JSON.stringify(e),u=o.length,p=z(r,t.serverUrl),s=J(n,t),l=B(t.retry),c=l.attempts+1;if(t.debug){let y=(u/1024).toFixed(2),h=u>1e5?"\u26A0\uFE0F":"\u{1F680}";R(`${h} Starting compute request [${n}]: ${r} (${y}KB)`,!0)}let m={endpoint:r,body:o,requestSize:u,fullUrl:p,requestId:n,headers:s,config:t},i=null;for(let y=0;y<c;y++){let h=await Z(m,l,y,c);if(h.ok)return h.value;if(!h.retry)throw h.cause;i=h.cause,t.debug&&R(`\u{1F501} Request [${n}] retrying after ${h.delayMs}ms (attempt ${y+2}/${c}): ${h.cause.message}`,!0);try{await K(h.delayMs,t.signal)}catch (e4){throw new d("Request aborted by caller",a.UNKNOWN_ERROR,{context:{endpoint:r,requestId:n,requestSize:u},originalError:i})}}throw _nullishCoalesce(i, () => (new d("Unknown error after retries",a.UNKNOWN_ERROR,{context:{endpoint:r,requestId:n,requestSize:u}})))}var Q="https://compute.rhino3d.com/";function F(r){if(!_optionalChain([r, 'optionalAccess', _26 => _26.trim, 'call', _27 => _27()]))throw new d("serverUrl is required",a.INVALID_CONFIG,{context:{receivedServerUrl:r}});if(!r.match(/^https?:\/\//))throw new d(`Invalid serverUrl: "${r}". Must start with "http://" or "https://". For example: "http://localhost:5000" or "https://example.com"`,a.INVALID_CONFIG,{context:{receivedServerUrl:r}});try{new URL(r)}catch(e){throw new d(`Invalid serverUrl: "${r}". Must be a valid URL. Received error: ${e instanceof Error?e.message:String(e)}`,a.INVALID_CONFIG,{context:{receivedServerUrl:r},originalError:e instanceof Error?e:void 0})}if(r===Q)throw new d("serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.",a.INVALID_CONFIG,{context:{receivedServerUrl:r}});return r.replace(/\/+$/,"")}var b=class b{constructor(e,t){g(this,"serverUrl");g(this,"apiKey");g(this,"disposed",!1);g(this,"activeMonitors",new Set);g(this,"activeTimeouts",new Set);this.serverUrl=F(e),this.apiKey=t}buildHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,t={},n=b.DEFAULT_TIMEOUT_MS){let o={headers:this.buildHeaders(),...t};return n>0&&!o.signal&&(o.signal=AbortSignal.timeout(n)),fetch(e,o)}async isServerOnline(e=5e3){this.ensureNotDisposed();let t=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(t,{method:"GET"},e)).ok}catch(n){return f().debug("[ComputeServerStats] Fetch error:",n),!1}}async getActiveChildren(e={}){this.ensureNotDisposed();let{initialize:t=!0}=e,n=t?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,o=t?b.LIFECYCLE_TIMEOUT_MS:b.DEFAULT_TIMEOUT_MS;try{let u=await this.fetchWithTimeout(n,{},o);if(!u.ok)return f().warn("[ComputeServerStats] Failed to fetch active children:",u.status),null;let p=await u.text(),s=parseInt(p.trim(),10);return isNaN(s)?(f().warn("[ComputeServerStats] Invalid active children response:",p),null):s}catch(u){return f().warn("[ComputeServerStats] Error fetching active children:",u),null}}async getVersion(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!e.ok)return f().warn("[ComputeServerStats] Failed to fetch version:",e.status),null;let t=await e.text();try{let n=JSON.parse(t);return{rhino:_nullishCoalesce(n.rhino, () => ("")),compute:_nullishCoalesce(n.compute, () => ("")),git_sha:_nullishCoalesce(n.git_sha, () => (null))}}catch (e5){return{rhino:t,compute:"",git_sha:null}}}catch(e){return f().warn("[ComputeServerStats] Error fetching version:",e),null}}async getInstalledPlugins(e="gh"){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${e}/installed`);if(!t.ok)return f().warn(`[ComputeServerStats] Failed to fetch ${e} plugins:`,t.status),null;let n=await t.text();try{let o=JSON.parse(n);return o&&typeof o=="object"?o:null}catch (e6){return null}}catch(t){return f().warn(`[ComputeServerStats] Error fetching ${e} plugins:`,t),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[t,n]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...t&&{version:t},...n!==null&&{activeChildren:n}}}async purgeCache(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:"POST"});if(!e.ok)return f().warn("[ComputeServerStats] Failed to purge cache:",e.status),null;let t=await e.text();try{let n=JSON.parse(t);return typeof n.purged=="number"?n.purged:null}catch (e7){return null}}catch(e){return f().warn("[ComputeServerStats] Error purging cache:",e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return f().warn("[ComputeServerStats] purgeAllChildren: could not read child count"),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let t=e*2,n=0;for(let o=0;o<t;o++){let u=await this.purgeCache();u!==null&&(n+=u)}return{totalPurged:n,calls:t,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!e.ok)return f().warn("[ComputeServerStats] Failed to fetch server time:",e.status),null;let t=(await e.text()).trim().replace(/^"|"$/g,""),n=new Date(t);return isNaN(n.getTime())?null:n}catch(e){return f().warn("[ComputeServerStats] Error fetching server time:",e),null}}async getIdleSpan(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);if(!e.ok)return f().warn("[ComputeServerStats] Failed to fetch idle span:",e.status),null;let t=parseFloat((await e.text()).trim());return isNaN(t)?null:t}catch(e){return f().warn("[ComputeServerStats] Error fetching idle span:",e),null}}async launchChildren(){return this.postJson("/launch-children")}async launchChild(e){let t=e===void 0?"/launch-child":`/launch-child?port=${e}`;return this.postJson(t)}async shutdownChildren(e){let t=e===void 0?"/shutdown-children":`/shutdown-children?port=${e}`;return this.postJson(t)}async recycleChildren(e){let t=e===void 0?"/recycle-children":`/recycle-children?port=${e}`;return this.postJson(t)}async postJson(e){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}${e}`,{method:"POST"},b.LIFECYCLE_TIMEOUT_MS);if(!t.ok)return f().warn(`[ComputeServerStats] POST ${e} failed:`,t.status),null;let n=await t.text();try{return JSON.parse(n)}catch (e8){return null}}catch(t){return f().warn(`[ComputeServerStats] Error on POST ${e}:`,t),null}}monitor(e,t=5e3){this.ensureNotDisposed();let n=!0,o=null;f().info(`\u{1F504} Starting server stats monitoring every ${t}ms`);let u=async()=>{if(o!==null&&(this.activeTimeouts.delete(o),o=null),!(!n||this.disposed)){try{let s=await this.getServerStats();if(!n||this.disposed)return;try{e(s)}catch(l){f().error("[ComputeServerStats] Monitor callback threw:",l)}}catch(s){f().error("[ComputeServerStats] Failed to fetch stats during monitor:",s)}n&&!this.disposed&&(o=setTimeout(()=>{u()},t),this.activeTimeouts.add(o))}},p=()=>{n=!1,o!==null&&(clearTimeout(o),this.activeTimeouts.delete(o),o=null),this.activeMonitors.delete(p)};return this.activeMonitors.add(p),u(),p}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new d("ComputeServerStats has been disposed and cannot be used",a.INVALID_STATE,{context:{disposed:this.disposed}})}};g(b,"DEFAULT_TIMEOUT_MS",5e3),g(b,"LIFECYCLE_TIMEOUT_MS",6e4);var O=b;function C(){let r=globalThis.Buffer;return typeof r=="function"?r:void 0}function Te(r){let e=C();return e?e.from(r,"utf-8").toString("base64"):ee(new TextEncoder().encode(r))}function Se(r){return!r||r.length<2||r.length%4!==0?!1:/^[A-Za-z0-9+/]+={0,2}$/.test(r)}function _(r){let e=C();if(e){let t=e.from(r,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if(typeof globalThis.atob=="function"){let t=globalThis.atob(r),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o)&255;return n}throw new d("Base64 decoding not supported in this environment.",a.INVALID_STATE,{context:{environmentInfo:"atob or Buffer not available"}})}function ee(r){let e=C();if(e)return e.from(r).toString("base64");if(typeof globalThis.btoa=="function"){let n="";for(let o=0;o<r.length;o+=32768)n+=String.fromCharCode.apply(null,r.subarray(o,o+32768));return globalThis.btoa(n)}throw new d("Base64 encoding not supported in this environment.",a.INVALID_STATE,{context:{environmentInfo:"btoa or Buffer not available"}})}var te=async(r,e=null)=>{try{return await P(r,e)}catch(t){throw new d("Failed to extract files from compute response",a.INVALID_STATE,{context:{originalError:t instanceof Error?t.message:String(t)},originalError:t instanceof Error?t:void 0})}},re= exports.p =async(r,e,t=null)=>{if(typeof document>"u"||typeof Blob>"u")throw new d("File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).",a.BROWSER_ONLY,{context:{environment:typeof window<"u"?"browser (SSR)":"Node.js",documentAvailable:typeof document<"u",blobAvailable:typeof Blob<"u"}});try{let n=await P(r,t);await se(n,e)}catch(n){throw n instanceof d?n:new d("Failed to download files from compute response",a.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}},ne=r=>{let e=[];return r.forEach(t=>{let n=`${t.fileName}${t.fileType}`,o=t.subFolder&&t.subFolder.trim()!==""?`${t.subFolder}/${n}`:n;t.isBase64Encoded===!0&&t.data?e.push({fileName:n,content:_(t.data),path:o}):t.isBase64Encoded===!1&&t.data&&e.push({fileName:n,content:t.data,path:o})}),e},oe=async r=>(await Promise.all(r.map(async t=>{try{let n=await fetch(t.filePath);if(!n.ok)return f().warn(`Failed to fetch additional file from URL: ${t.filePath}`),null;let u=await(await n.blob()).arrayBuffer();return{fileName:t.fileName,content:new Uint8Array(u),path:t.fileName}}catch(n){return f().error(`Error fetching additional file from URL: ${t.filePath}`,n),null}}))).filter(t=>t!==null),P=async(r,e)=>{let t=ne(r);if(e){let n=Array.isArray(e)?e:[e];t.push(...await oe(n))}return t};async function se(r,e){let{zip:t,strToU8:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("fflate"))),o={};r.forEach(s=>{o[s.path]=typeof s.content=="string"?n(s.content):s.content});let u=await new Promise((s,l)=>{t(o,{level:6},(c,m)=>c?l(c):s(m))}),p=new Blob([u],{type:"application/zip"});ie(p,`${e}.zip`)}function ie(r,e){if(typeof document>"u")throw new d("saveFile requires a browser environment with DOM API access.",a.BROWSER_ONLY,{context:{function:"saveFile",requiredAPI:"document"}});let t=document.createElement("a");t.href=URL.createObjectURL(r),t.download=e,t.click(),URL.revokeObjectURL(t.href)}exports.a = ae; exports.b = g; exports.c = a; exports.d = d; exports.e = f; exports.f = U; exports.g = x; exports.h = X; exports.i = F; exports.j = O; exports.k = Te; exports.l = Se; exports.m = _; exports.n = ee; exports.o = te; exports.p = re;
|
|
4
|
-
//# sourceMappingURL=chunk-2QHLW6ZL.cjs.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkSA67IFJHcjs = require('./chunk-SA67IFJH.cjs');require('./chunk-2QHLW6ZL.cjs');exports.BINARY_MESH_MAGIC = _chunkSA67IFJHcjs.s; exports.BINARY_MESH_VERSION = _chunkSA67IFJHcjs.t; exports.EDGE_USERDATA_KIND = _chunkSA67IFJHcjs.h; exports.FLAG_FLOAT32 = _chunkSA67IFJHcjs.u; exports.Materials = _chunkSA67IFJHcjs.q; exports.SCALE_FACTORS = _chunkSA67IFJHcjs.z; exports.addEdges = _chunkSA67IFJHcjs.i; exports.applyOffset = _chunkSA67IFJHcjs.c; exports.computeCombinedBoundingBox = _chunkSA67IFJHcjs.d; exports.createCameraController = _chunkSA67IFJHcjs.e; exports.createGrid = _chunkSA67IFJHcjs.f; exports.createLabelLayer = _chunkSA67IFJHcjs.m; exports.createMeasureTool = _chunkSA67IFJHcjs.o; exports.createRenderPipeline = _chunkSA67IFJHcjs.l; exports.createViewGizmo = _chunkSA67IFJHcjs.g; exports.getThreeMeshesFromComputeResponse = _chunkSA67IFJHcjs.A; exports.initThree = _chunkSA67IFJHcjs.p; exports.isEdgeOverlay = _chunkSA67IFJHcjs.j; exports.parseBinaryMeshBatch = _chunkSA67IFJHcjs.v; exports.parseColor = _chunkSA67IFJHcjs.b; exports.parseDisplayItems = _chunkSA67IFJHcjs.r; exports.parseMeshBatch = _chunkSA67IFJHcjs.w; exports.parseMeshBatchBlob = _chunkSA67IFJHcjs.y; exports.parseMeshBatchObject = _chunkSA67IFJHcjs.x; exports.removeEdges = _chunkSA67IFJHcjs.k; exports.snapToVertex = _chunkSA67IFJHcjs.n; exports.updateScene = _chunkSA67IFJHcjs.a;
|
|
2
|
-
//# sourceMappingURL=visualization-UOIWXLDL.cjs.map
|
|
File without changes
|
|
File without changes
|
|
File without changes
|