@selvajs/compute 3.0.1 → 3.1.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/chunk-2KQHHQZW.js +2 -0
  2. package/dist/chunk-2KQHHQZW.js.map +1 -0
  3. package/dist/chunk-7XMD5YXP.cjs +62 -0
  4. package/dist/chunk-7XMD5YXP.cjs.map +1 -0
  5. package/dist/chunk-CUQQ3ZBV.cjs +4 -0
  6. package/dist/chunk-CUQQ3ZBV.cjs.map +1 -0
  7. package/dist/chunk-HOWV4A5D.cjs +2 -0
  8. package/dist/chunk-HOWV4A5D.cjs.map +1 -0
  9. package/dist/chunk-PX2YTSHJ.js +62 -0
  10. package/dist/chunk-PX2YTSHJ.js.map +1 -0
  11. package/dist/chunk-WPB2LKCD.js +4 -0
  12. package/dist/chunk-WPB2LKCD.js.map +1 -0
  13. package/dist/core.cjs +1 -1
  14. package/dist/core.cjs.map +1 -1
  15. package/dist/core.d.cts +49 -3
  16. package/dist/core.d.ts +49 -3
  17. package/dist/core.js +1 -1
  18. package/dist/grasshopper.cjs +1 -1
  19. package/dist/grasshopper.cjs.map +1 -1
  20. package/dist/grasshopper.d.cts +222 -32
  21. package/dist/grasshopper.d.ts +222 -32
  22. package/dist/grasshopper.js +1 -1
  23. package/dist/{handle-files-Bu2qmaPj.d.ts → handle-files-BISo_wob.d.cts} +53 -69
  24. package/dist/{handle-files-Bu2qmaPj.d.cts → handle-files-BISo_wob.d.ts} +53 -69
  25. package/dist/index.cjs +1 -1
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.cts +4 -4
  28. package/dist/index.d.ts +4 -4
  29. package/dist/index.js +1 -1
  30. package/dist/types-BGhtYxZ-.d.cts +45 -0
  31. package/dist/types-BGhtYxZ-.d.ts +45 -0
  32. package/dist/{types-DxT3hSkx.d.ts → types-C8XWc4Ab.d.cts} +99 -67
  33. package/dist/{types-D-HQ-gWI.d.cts → types-Dtok-mVq.d.ts} +99 -67
  34. package/dist/visualization-4RSUYQG2.cjs +2 -0
  35. package/dist/visualization-4RSUYQG2.cjs.map +1 -0
  36. package/dist/visualization-MOYO6MDN.js +2 -0
  37. package/dist/visualization.cjs +1 -1
  38. package/dist/visualization.cjs.map +1 -1
  39. package/dist/visualization.d.cts +200 -37
  40. package/dist/visualization.d.ts +200 -37
  41. package/dist/visualization.js +1 -1
  42. package/package.json +1 -1
  43. package/dist/chunk-6LCAIDQV.cjs +0 -4
  44. package/dist/chunk-6LCAIDQV.cjs.map +0 -1
  45. package/dist/chunk-CFBKO3HX.cjs +0 -2
  46. package/dist/chunk-CFBKO3HX.cjs.map +0 -1
  47. package/dist/chunk-JF5MZTOU.cjs +0 -55
  48. package/dist/chunk-JF5MZTOU.cjs.map +0 -1
  49. package/dist/chunk-LUP3B2DK.js +0 -55
  50. package/dist/chunk-LUP3B2DK.js.map +0 -1
  51. package/dist/chunk-O55PTKMV.js +0 -4
  52. package/dist/chunk-O55PTKMV.js.map +0 -1
  53. package/dist/chunk-UAL4YXRX.js +0 -2
  54. package/dist/chunk-UAL4YXRX.js.map +0 -1
  55. package/dist/types-ChF690kY.d.cts +0 -88
  56. package/dist/types-ChF690kY.d.ts +0 -88
  57. package/dist/visualization-LZ4XZPYZ.cjs +0 -2
  58. package/dist/visualization-LZ4XZPYZ.cjs.map +0 -1
  59. package/dist/visualization-SV4BTHXJ.js +0 -2
  60. /package/dist/{visualization-SV4BTHXJ.js.map → visualization-MOYO6MDN.js.map} +0 -0
@@ -1,11 +1,11 @@
1
1
  import * as THREE from 'three';
2
2
  import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
3
+ import { M as MaterialAppearanceOptions, f as GrasshopperComputeResponse, m as MeshExtractionOptions, n as MeshBatchParsingOptions, o as DisplayBatch, p as DisplayItem } from './types-Dtok-mVq.js';
4
+ export { q as DisplayCurve, r as DisplayIdentity, s as DisplayItemBase, t as DisplayPoint, u as DisplayPosition, v as MeshBatch } from './types-Dtok-mVq.js';
3
5
  import { CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
4
6
  import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';
5
- import { f as GrasshopperComputeResponse, M as MeshExtractionOptions, m as MeshBatchParsingOptions, n as DisplayBatch, o as DisplayItem } from './types-DxT3hSkx.js';
6
- export { p as DisplayCurve, q as DisplayIdentity, r as DisplayItemBase, s as DisplayPoint, t as DisplayPosition, u as MeshBatch } from './types-DxT3hSkx.js';
7
7
  import { RhinoModule } from 'rhino3dm';
8
- import './types-ChF690kY.js';
8
+ import './types-BGhtYxZ-.js';
9
9
 
10
10
  type CameraConfig = {
11
11
  position?: THREE.Vector3;
@@ -13,6 +13,13 @@ type CameraConfig = {
13
13
  near?: number;
14
14
  far?: number;
15
15
  target?: THREE.Vector3;
16
+ /**
17
+ * Refit the perspective camera's near plane to the camera↔content gap every frame (default true).
18
+ * Recovers depth-buffer precision when zoomed out (precision ∝ near/z²), which is what stops
19
+ * distant surfaces z-fighting. `near` stays the lower bound — the plane is only raised, never
20
+ * lowered below it.
21
+ */
22
+ dynamicNear?: boolean;
16
23
  };
17
24
  type LightingConfig = {
18
25
  enableSunlight?: boolean;
@@ -21,6 +28,20 @@ type LightingConfig = {
21
28
  ambientLightColor?: THREE.Color;
22
29
  ambientLightIntensity?: number;
23
30
  sunlightColor?: THREE.Color | number;
31
+ /**
32
+ * Add a hemisphere fill light (sky color from above, ground color from below). Unlike the flat
33
+ * ambient, this gives soft *direction-aware* fill, so downward- and side-facing surfaces never
34
+ * collapse to black when the HDR's lower hemisphere is dark. The single biggest lever for keeping
35
+ * results well-lit regardless of which HDR is loaded. Default false (opt-in) — enabling it shifts
36
+ * the look. See {@link LightingConfig.hemisphereIntensity}.
37
+ */
38
+ enableHemisphereLight?: boolean;
39
+ /** Hemisphere fill sky color (lights upward-facing surfaces). Default white. */
40
+ hemisphereSkyColor?: THREE.Color | number;
41
+ /** Hemisphere fill ground color (lights downward-facing surfaces). Default a mid grey. */
42
+ hemisphereGroundColor?: THREE.Color | number;
43
+ /** Hemisphere fill strength. Default 0.6. Only applies when {@link LightingConfig.enableHemisphereLight}. */
44
+ hemisphereIntensity?: number;
24
45
  };
25
46
  type EnvironmentConfig = {
26
47
  hdrPath?: string;
@@ -28,6 +49,13 @@ type EnvironmentConfig = {
28
49
  enableEnvironmentLighting?: boolean;
29
50
  sceneUp?: THREE.Vector3;
30
51
  showEnvironment?: boolean;
52
+ /**
53
+ * Uniform multiplier on the HDR's image-based lighting contribution (`scene.environmentIntensity`).
54
+ * Normalizes brightness across HDRs of differing exposure — raise it to lift a dim HDR, lower it to
55
+ * tame a blown-out one — so the scene doesn't render dim-or-blown purely because of the HDR chosen.
56
+ * Default 1 (three.js default, unchanged look).
57
+ */
58
+ environmentIntensity?: number;
31
59
  };
32
60
  type FloorConfig = {
33
61
  enabled?: boolean;
@@ -52,7 +80,36 @@ type RenderConfig = {
52
80
  ambientOcclusion?: boolean;
53
81
  /** AO strength 0–1 when {@link RenderConfig.ambientOcclusion} is on. Default 1. */
54
82
  aoIntensity?: number;
83
+ /**
84
+ * Device-pixel-ratio cap for the ambient-occlusion postprocessing buffers. AO is low-frequency, so
85
+ * rendering its buffers below the display DPR is nearly invisible but hugely cheaper — on a Retina
86
+ * display (DPR 2) full-resolution AO means 4× the pixels through GTAO's per-pixel sample loops,
87
+ * which can dominate frame time. Default 1 (AO buffers at 1× regardless of display DPR). Raise
88
+ * toward the display DPR for sharper AO at higher cost; only relevant when AO is enabled.
89
+ */
90
+ aoPixelRatio?: number;
55
91
  };
92
+ /**
93
+ * A ready-to-go visual look. A `look` is a named bundle of LIGHTING/MATERIAL defaults only — it is
94
+ * deliberately decoupled from the CAD overlays (edges, grid), which are driven independently by
95
+ * {@link EdgesConfig}/{@link GridConfig}. Pick one and the viewer looks professional with zero other
96
+ * config; every individual `lighting`/`environment`/`render` option still overrides the preset. Seeds
97
+ * construction defaults and can be re-applied live via `setLook`.
98
+ *
99
+ * - 'technical' (default): matte, drawing-like — neutral tone mapping, low IBL, no fill. Reads like a
100
+ * CAD shaded view (Rhino/Onshape).
101
+ * - 'studio': balanced presentation — ACES tone mapping, hemisphere fill + lifted HDR so results are
102
+ * well-lit regardless of the HDR, without washing colour out. The polished "product shot" look.
103
+ * - 'showcase': punchier presentation — ACES, stronger IBL/fill and a touch more exposure.
104
+ */
105
+ /**
106
+ * The look values as a runtime array — the single source of truth. {@link Look} is derived from it, so
107
+ * the type and the enumerable list can never drift. Consumers (e.g. a viewer's style picker) iterate
108
+ * this instead of hardcoding the names, so adding or renaming a look here updates them automatically.
109
+ * 'technical' is first because it's the default.
110
+ */
111
+ declare const LOOKS: readonly ["technical", "studio", "showcase"];
112
+ type Look = (typeof LOOKS)[number];
56
113
  /** Crisp boundary/crease edge overlays on meshes. See `addEdges`. */
57
114
  type EdgesConfig = {
58
115
  /** Auto-attach edge overlays to meshes as they load. Default false (opt-in). */
@@ -63,6 +120,8 @@ type EdgesConfig = {
63
120
  width?: number;
64
121
  /** Crease angle (degrees): keep edges where faces differ by more than this. Default 30. */
65
122
  thresholdAngle?: number;
123
+ /** Fade an overlay out as its mesh shrinks on screen, so far zoom-outs stay clean. Default true. */
124
+ distanceFade?: boolean;
66
125
  };
67
126
  type ControlsConfig = {
68
127
  enableDamping?: boolean;
@@ -122,6 +181,14 @@ type MeasureConfig = {
122
181
  };
123
182
  type ThreeInitializerOptions = {
124
183
  sceneScale?: 'mm' | 'cm' | 'm' | 'inches' | 'feet';
184
+ /**
185
+ * Pick a ready-to-go visual look up front — seeds professional lighting/material defaults (tone
186
+ * mapping, AO, IBL strength, hemisphere fill; see {@link Look}). Individual `lighting`/
187
+ * `environment`/`render` options still win when set explicitly, so this only fills in what you
188
+ * leave unspecified. A look does NOT touch edges/grid (those are independent overlays). Defaults
189
+ * to 'technical'. Re-apply later via the init result's `setLook`.
190
+ */
191
+ look?: Look;
125
192
  camera?: CameraConfig;
126
193
  lighting?: LightingConfig;
127
194
  environment?: EnvironmentConfig;
@@ -193,12 +260,20 @@ interface CameraController {
193
260
  * singularity.
194
261
  */
195
262
  setViewDirection(direction: THREE.Vector3, animate?: boolean): void;
263
+ /**
264
+ * Frame an arbitrary world-space box (e.g. a double-clicked object) from the current view
265
+ * direction, moving the *active* camera — in 2D mode that means resizing the ortho frustum, not
266
+ * just translating. No-op on an empty box.
267
+ */
268
+ frameBounds(box: THREE.Box3, animate?: boolean): void;
196
269
  /** Enable/disable orbit rotation at runtime (pan/zoom unaffected). */
197
270
  setRotateEnabled(enabled: boolean): void;
198
271
  /** Whether rotation is currently enabled. */
199
272
  isRotateEnabled(): boolean;
200
273
  /** Keep the orthographic frustum aspect in sync on canvas resize. Called by the resize loop. */
201
274
  updateAspect(width: number, height: number): void;
275
+ /** Cancel any in-flight camera tween. Call on viewer teardown so ticks can't touch disposed controls. */
276
+ dispose(): void;
202
277
  }
203
278
  interface CameraControllerDeps {
204
279
  scene: THREE.Scene;
@@ -265,14 +340,24 @@ declare function createGrid(options?: GridOptions): Grid;
265
340
  *
266
341
  * Caller responsibilities (mirror ViewHelper's own contract):
267
342
  * - call {@link ViewGizmo.render} *after* the main scene render each frame (overlay viewport),
268
- * - call {@link ViewGizmo.update} each frame (no-op now; kept for API symmetry),
269
343
  * - forward pointer clicks to {@link ViewGizmo.handleClick}.
270
344
  */
271
345
  interface ViewGizmo {
272
346
  render(renderer: THREE.WebGLRenderer): void;
347
+ /**
348
+ * @deprecated No-op, kept only for API stability. This wrapper never uses ViewHelper's
349
+ * click→animate path (see module comment) — view changes snap instantly through the camera
350
+ * controller — so there is never a gizmo animation to advance. Safe to stop calling.
351
+ */
273
352
  update(delta: number): void;
274
353
  /** Hit-test a click. Returns true if it hit the gizmo (and a view change started). */
275
354
  handleClick(event: MouseEvent): boolean;
355
+ /**
356
+ * @deprecated Always `false`, kept only for API stability. Gizmo clicks snap the view
357
+ * instantly rather than animating (deliberately — ViewHelper's built-in animation assumes a
358
+ * Y-up world and rolls the view in this Z-up scene), so there is no animation window to gate
359
+ * input on.
360
+ */
276
361
  readonly isAnimating: boolean;
277
362
  /** Show/hide the gizmo at runtime. Hidden = not rendered and not click-hittable. */
278
363
  setVisible(visible: boolean): void;
@@ -375,6 +460,14 @@ interface MeasureDeps {
375
460
  canvas: HTMLCanvasElement;
376
461
  scene: THREE.Scene;
377
462
  getActiveCamera: () => THREE.Camera;
463
+ /**
464
+ * The current orbit target (e.g. `controls.target`). Used to scale the line/point pick
465
+ * threshold with the view: the tolerance is a fraction of the camera→target distance, so it
466
+ * stays roughly constant on screen wherever the user has framed the model. Optional for
467
+ * backward compatibility — without it the perspective fallback is the camera's distance to the
468
+ * world origin, which misjudges the threshold for off-origin content. Thread it in when you can.
469
+ */
470
+ getViewTarget?: () => THREE.Vector3;
378
471
  labelLayer: LabelLayer;
379
472
  options?: MeasureOptions;
380
473
  }
@@ -412,6 +505,46 @@ declare const initThree: (canvas: HTMLCanvasElement, options?: ThreeInitializerO
412
505
  applyEdges: (root: THREE.Object3D) => void;
413
506
  /** Toggle ambient occlusion at runtime — builds or tears down the postprocessing pipeline. */
414
507
  setAmbientOcclusion: (enabled: boolean) => void;
508
+ /**
509
+ * Apply a coherent look to the already-loaded scene: 'technical' (matte/CAD — edges, grid, low
510
+ * IBL, neutral tone mapping) or 'rendered' (presentation — stronger IBL, ACES tone mapping, no
511
+ * edges). Retunes viewer-owned dials only; per-material parse choices are set via the batch
512
+ * parser's `material` option. Handy for comparing the two looks in a live viewer.
513
+ */
514
+ /**
515
+ * Switch the viewer to a ready-to-go look at runtime ('studio' | 'technical' | 'showcase'). Retunes
516
+ * lighting/material only (tone mapping, fill, IBL, AO) — never edges/grid. A straight preset apply:
517
+ * overwrites any granular lighting dials you set earlier.
518
+ */
519
+ setLook: (look: "studio" | "technical" | "showcase") => void;
520
+ /**
521
+ * Retune the fill lights at runtime: the direction-aware hemisphere fill (sky/ground) and the flat
522
+ * ambient. Raising `hemisphereIntensity` is the most effective way to lift shadowed / under-facing
523
+ * surfaces a dark HDR leaves black. A positive `hemisphereIntensity` lazily creates the hemisphere
524
+ * light if the viewer was built without one; `0` switches it off.
525
+ */
526
+ setFillLights: (opts: {
527
+ hemisphereIntensity?: number;
528
+ hemisphereSkyColor?: THREE.Color | number;
529
+ hemisphereGroundColor?: THREE.Color | number;
530
+ ambientIntensity?: number;
531
+ }) => void;
532
+ /**
533
+ * Set the uniform multiplier on the HDR's image-based lighting (`scene.environmentIntensity`) at
534
+ * runtime — normalizes brightness across HDRs of differing exposure so the scene isn't at the
535
+ * mercy of whichever HDR is loaded. Applies immediately, even before the HDR finishes decoding.
536
+ */
537
+ setEnvironmentIntensity: (intensity: number) => void;
538
+ /** Set renderer tone-mapping exposure at runtime. Higher lifts shadows and overall brightness. */
539
+ setToneMappingExposure: (exposure: number) => void;
540
+ /** Set GTAO strength at runtime (0–1). No-op when ambient occlusion isn't active. */
541
+ setAoIntensity: (intensity: number) => void;
542
+ /**
543
+ * The parse-time material options (backface culling, IBL strength) matching the active look — feed
544
+ * into the batch parser's `material` option so freshly-loaded meshes are built to match it. See
545
+ * `setLook`.
546
+ */
547
+ getMaterialAppearance: () => MaterialAppearanceOptions;
415
548
  /**
416
549
  * Refit the sun's shadow frustum to the current scene content for crisp shadows. Call after
417
550
  * loading or replacing geometry (e.g. after `updateScene`). No-op when sunlight/shadows are off.
@@ -432,25 +565,9 @@ declare const initThree: (canvas: HTMLCanvasElement, options?: ThreeInitializerO
432
565
  clearUserGeometry: () => void;
433
566
  };
434
567
 
435
- /**
436
- * Updates the scene with the given meshes and camera settings.
437
- * If initialPositionSet is false, it positions the camera and sets the controls target based on the bounding boxes of the meshes.
438
- * @param scene - The THREE.Scene object to update.
439
- * @param meshes - An array of THREE.Mesh objects to add to the scene.
440
- * @param camera - The THREE.PerspectiveCamera object to position.
441
- * @param controls - The OrbitControls object to update.
442
- * @param initialPositionSet - A boolean indicating whether the initial position of the camera and controls have been set.
443
- */
568
+ /** Updates scene with meshes and positions camera on first call. */
444
569
  declare function updateScene(scene: THREE.Scene, meshes: THREE.Object3D[], camera: THREE.PerspectiveCamera, controls: OrbitControls, initialPositionSet: boolean): void;
445
- /**
446
- * Parses a color string in multiple formats to a THREE.Color object.
447
- * Supported formats:
448
- * - Hex: "#C7A5A5", "C7A5A5"
449
- * - RGB: "199, 165, 165"
450
- * - CSS named colors: "red", "blue", etc.
451
- * @param colorString - The color string to parse.
452
- * @returns A THREE.Color object.
453
- */
570
+ /** Parses color strings (hex, RGB, CSS names). */
454
571
  declare function parseColor(colorString: string): THREE.Color;
455
572
  /**
456
573
  * Shift objects along one world axis. Defaults to `z` — the up axis of the unified Z-up scene
@@ -470,6 +587,8 @@ declare const PLASTIC_MATERIAL: THREE.MeshPhysicalMaterial;
470
587
  declare const GLASS_MATERIAL: THREE.MeshPhysicalMaterial;
471
588
  declare const RUBBER_MATERIAL: THREE.MeshPhysicalMaterial;
472
589
  declare const WOOD_MATERIAL: THREE.MeshPhysicalMaterial;
590
+ /** Shared singleton materials; must not be disposed (rebuilds shaders, frees textures). */
591
+ declare const SHARED_MATERIALS: ReadonlySet<THREE.Material>;
473
592
 
474
593
  declare const threeMaterials_CONCRETE_MATERIAL: typeof CONCRETE_MATERIAL;
475
594
  declare const threeMaterials_EMISSIVE_MATERIAL: typeof EMISSIVE_MATERIAL;
@@ -477,9 +596,10 @@ declare const threeMaterials_GLASS_MATERIAL: typeof GLASS_MATERIAL;
477
596
  declare const threeMaterials_METAL_MATERIAL: typeof METAL_MATERIAL;
478
597
  declare const threeMaterials_PLASTIC_MATERIAL: typeof PLASTIC_MATERIAL;
479
598
  declare const threeMaterials_RUBBER_MATERIAL: typeof RUBBER_MATERIAL;
599
+ declare const threeMaterials_SHARED_MATERIALS: typeof SHARED_MATERIALS;
480
600
  declare const threeMaterials_WOOD_MATERIAL: typeof WOOD_MATERIAL;
481
601
  declare namespace threeMaterials {
482
- export { threeMaterials_CONCRETE_MATERIAL as CONCRETE_MATERIAL, threeMaterials_EMISSIVE_MATERIAL as EMISSIVE_MATERIAL, threeMaterials_GLASS_MATERIAL as GLASS_MATERIAL, threeMaterials_METAL_MATERIAL as METAL_MATERIAL, threeMaterials_PLASTIC_MATERIAL as PLASTIC_MATERIAL, threeMaterials_RUBBER_MATERIAL as RUBBER_MATERIAL, threeMaterials_WOOD_MATERIAL as WOOD_MATERIAL };
602
+ export { threeMaterials_CONCRETE_MATERIAL as CONCRETE_MATERIAL, threeMaterials_EMISSIVE_MATERIAL as EMISSIVE_MATERIAL, threeMaterials_GLASS_MATERIAL as GLASS_MATERIAL, threeMaterials_METAL_MATERIAL as METAL_MATERIAL, threeMaterials_PLASTIC_MATERIAL as PLASTIC_MATERIAL, threeMaterials_RUBBER_MATERIAL as RUBBER_MATERIAL, threeMaterials_SHARED_MATERIALS as SHARED_MATERIALS, threeMaterials_WOOD_MATERIAL as WOOD_MATERIAL };
483
603
  }
484
604
 
485
605
  /**
@@ -491,6 +611,15 @@ declare namespace threeMaterials {
491
611
  * `LineMaterial` family as curves (Phase 1) — so edges get controllable thickness, not the 1px cap
492
612
  * of `THREE.LineSegments`. The overlay is added as a *child* of each mesh, so it inherits the mesh's
493
613
  * transform and is disposed when the mesh subtree is cleared.
614
+ *
615
+ * Depth strategy: edges render at TRUE depth; the mesh's own surface is pushed back a hair with
616
+ * polygonOffset instead (see {@link setSurfaceDepthOffset}). Biasing the lines toward the camera —
617
+ * the obvious alternative — needs a multi-ULP constant offset to survive glancing angles (fat-line
618
+ * quads face the screen, so the slope-scaled factor term is nil), and a depth ULP grows ~quadratically
619
+ * with distance: zoomed out, that constant becomes a meter-scale pull that makes hidden edges bleed
620
+ * through whatever mesh is in front. Offsetting the surfaces instead lets the slope-proportional
621
+ * factor term do the glancing-angle work, keeps the constant term at quantization scale, and leaves
622
+ * occlusion of hidden edges exact.
494
623
  */
495
624
  interface EdgeOptions {
496
625
  /** Edge color. Default near-black. */
@@ -502,6 +631,11 @@ interface EdgeOptions {
502
631
  * Default 30. Higher = fewer edges (only sharp creases); lower = more (catches gentle bends).
503
632
  */
504
633
  thresholdAngle?: number;
634
+ /**
635
+ * Fade an overlay out as its mesh shrinks on screen (default true). Constant-px edges on a mesh
636
+ * covering only tens of pixels alias into dark noise; fading them keeps far zoom-outs clean.
637
+ */
638
+ distanceFade?: boolean;
505
639
  }
506
640
  /** Tag on edge overlays so pick/fit/clear logic can recognize and skip or dispose them. */
507
641
  declare const EDGE_USERDATA_KIND = "edge-overlay";
@@ -526,11 +660,18 @@ declare function removeEdges(root: THREE.Object3D): number;
526
660
  * this when `render.ambientOcclusion` is enabled, and otherwise renders with a plain
527
661
  * `renderer.render` so the cheap path stays cheap (the chosen tradeoff — see cad-viewer-plan.md).
528
662
  *
529
- * Pipeline: RenderPass → GTAOPass → OutputPass. GTAO (ground-truth AO) is the modern replacement for
530
- * SSAO/SAO — better contact shadows in crevices, the "engineered" depth cue. `screenSpaceRadius` is
531
- * on so the AO radius is in screen space, which keeps it scale-robust across the viewer's mm→m
532
- * scenes without per-scene tuning. OutputPass applies tone mapping + color space (taking over the
533
- * roles the renderer did directly in the non-composer path).
663
+ * Pipeline: RenderPass → GTAOPass → SMAAPass → OutputPass. GTAO (ground-truth AO) is the modern
664
+ * replacement for SSAO/SAO — better contact shadows in crevices, the "engineered" depth cue.
665
+ * `screenSpaceRadius` is on so the AO radius is in screen space, which keeps it scale-robust across
666
+ * the viewer's mm→m scenes without per-scene tuning.
667
+ *
668
+ * SMAA restores antialiasing on this path. The EffectComposer renders into an offscreen target, so
669
+ * the WebGLRenderer's own MSAA (`antialias: true`) does nothing here — without a dedicated AA pass,
670
+ * enabling AO would visibly *worsen* edge quality. SMAA is chosen over TAA because TAA's temporal
671
+ * jitter smears during OrbitControls drags; SMAA is single-frame, cheap, and stable while orbiting.
672
+ *
673
+ * OutputPass applies tone mapping + color space last (taking over the roles the renderer did
674
+ * directly in the non-composer path), so SMAA operates on the pre-tonemapped image as intended.
534
675
  *
535
676
  * Camera swaps: the active camera can flip perspective↔ortho. Rather than rebuild the composer, we
536
677
  * retarget the passes' `camera` each render via {@link setCamera}.
@@ -548,9 +689,21 @@ interface RenderPipelineOptions {
548
689
  toneMappingExposure: number;
549
690
  /** AO strength 0–1. Default 1. */
550
691
  aoIntensity?: number;
692
+ /**
693
+ * Cap on the device-pixel-ratio used for the composer's (AO) buffers. AO is low-frequency, so
694
+ * rendering below the display DPR is nearly invisible but far cheaper. `setSize`'s incoming
695
+ * pixelRatio is clamped to this. Default 1.
696
+ */
697
+ aoPixelRatio?: number;
551
698
  }
552
699
  declare function createRenderPipeline(renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.Camera, width: number, height: number, options: RenderPipelineOptions): RenderPipeline;
553
700
 
701
+ /**
702
+ * Metres per model unit, keyed by Rhino `UnitSystem` name (the `modelunits` string on the compute
703
+ * response). Imperial factors are the exact international definitions (1 in = 0.0254 m,
704
+ * 1 ft = 0.3048 m, 1 mi = 1609.344 m). Units not in this table scale 1 and log a one-time warning
705
+ * — see {@link getScaleFactor}.
706
+ */
554
707
  declare const SCALE_FACTORS: Record<string, number>;
555
708
  /**
556
709
  * Extracts and processes display meshes from a ComputePointerResponse using the Grasshopper WebDisplay component.
@@ -558,7 +711,9 @@ declare const SCALE_FACTORS: Record<string, number>;
558
711
  * This is the primary entry point for extracting mesh geometry from Grasshopper compute responses.
559
712
  * It handles all aspects of mesh processing: decompression, coordinate transformation, scaling, and positioning.
560
713
  *
561
- * **Note:** Mesh decompression happens asynchronously in a Web Worker to prevent UI blocking.
714
+ * **Note:** The entire pipeline (base64 decode, inflate, dequantization, mesh construction) runs
715
+ * synchronously on the calling thread — large batches will block the UI for their duration. The
716
+ * function is `async` only so its shape can stay stable if parsing moves off-thread later.
562
717
  *
563
718
  * @param data - The ComputePointerResponse containing Grasshopper output trees.
564
719
  * @param options - Configuration for mesh extraction and parsing behavior. All options are optional with sensible defaults.
@@ -569,7 +724,7 @@ declare const SCALE_FACTORS: Record<string, number>;
569
724
  * - Only works with the WebDisplay component of GHHeadless.
570
725
  * - Requires changes to Rhino.Compute (see https://github.com/TheVessen/compute.rhino3d).
571
726
  * - Provides a performant way to display mesh data in Three.js.
572
- * - Decompression is performed in a Web Worker for non-blocking UI updates.
727
+ * - All decoding is synchronous on the main thread; there is no Web Worker offload today.
573
728
  * - Supports mesh metadata (names, user data) if provided in the compute response.
574
729
  *
575
730
  * @internal Internal helper: high-level extraction remains public via visualization module, but this
@@ -598,11 +753,7 @@ declare const SCALE_FACTORS: Record<string, number>;
598
753
  */
599
754
  declare function getThreeMeshesFromComputeResponse(data: GrasshopperComputeResponse, options?: MeshExtractionOptions): Promise<THREE.Object3D[]>;
600
755
 
601
- /**
602
- * Internal-only telemetry threaded from an outer entry point (e.g. the JSON
603
- * `parseMeshBatch` measuring its own `JSON.parse` cost) into the shared build
604
- * step. Never part of any public options surface — callers don't supply timings.
605
- */
756
+ /** Internal telemetry only (not exposed in public options). */
606
757
  interface ParseTelemetry {
607
758
  parseTime?: number;
608
759
  perfStart?: number;
@@ -614,9 +765,14 @@ interface ParseTelemetry {
614
765
  * over the blob. The function stays `async` so callers don't have to change shape if we move
615
766
  * parsing into a worker later.
616
767
  *
768
+ * A batch with no `compressedData` (genuinely empty/absent geometry) resolves to `[]`. A corrupt,
769
+ * truncated, or unsupported blob throws so callers get a signal instead of a silent empty scene —
770
+ * `getThreeMeshesFromComputeResponse` documents (and now delivers) exactly that rethrow.
771
+ *
617
772
  * @param batch - DisplayBatch object
618
773
  * @param options - Rendering options
619
774
  * @returns Promise resolving to array of Three.js mesh objects
775
+ * @throws {RhinoComputeError} On a corrupt/truncated/unsupported mesh blob or malformed group metadata.
620
776
  */
621
777
  declare function parseMeshBatchObject(batch: DisplayBatch, options?: MeshBatchParsingOptions,
622
778
  /** @internal Timings threaded from an outer entry point; not a caller option. */
@@ -632,13 +788,20 @@ telemetry?: ParseTelemetry): Promise<THREE.Mesh[]>;
632
788
  * @param blob - Raw blob bytes from a binary WebSocket frame.
633
789
  * @param options - Rendering options.
634
790
  * @returns Promise resolving to array of Three.js mesh objects.
791
+ * @throws {RhinoComputeError} On a corrupt/truncated/unsupported mesh blob or malformed group metadata.
635
792
  */
636
793
  declare function parseMeshBatchBlob(blob: ArrayBuffer | Uint8Array, options?: MeshBatchParsingOptions): Promise<THREE.Mesh[]>;
637
794
 
638
795
  interface DisplayItemParseOptions {
639
796
  /** rhino3dm instance for decoding curve JSON. Omit to skip curves (points still render). */
640
797
  rhino?: RhinoModule;
641
- /** Apply the Rhino Z-up → Three Y-up transform. Defaults to true (matches the mesh path). */
798
+ /**
799
+ * No-op. Historically toggled the Rhino Z-up → Three Y-up rotation, but the pipeline now keeps
800
+ * one coordinate frame end to end ({@link rhinoToThree} is the identity), so this flag no longer
801
+ * changes the result. Do NOT pre-rotate your own geometry to compensate — none is applied.
802
+ *
803
+ * @deprecated Retained only so existing call sites compile unchanged; has no effect.
804
+ */
642
805
  applyTransforms?: boolean;
643
806
  }
644
807
  /**
@@ -648,4 +811,4 @@ interface DisplayItemParseOptions {
648
811
  */
649
812
  declare function parseDisplayItems(items: DisplayItem[] | undefined, options?: DisplayItemParseOptions): THREE.Object3D[];
650
813
 
651
- export { type CameraConfig, type CameraController, type CameraProjection, type ControlsConfig, DisplayBatch, DisplayItem, type DisplayItemParseOptions, EDGE_USERDATA_KIND, type EdgeOptions, type EdgesConfig, type EnvironmentConfig, type EventConfig, type FloorConfig, type GizmoConfig, type Grid, type GridConfig, type GridOptions, type LabelHandle, type LabelLayer, type LightingConfig, threeMaterials as Materials, type MeasureConfig, type MeasureOptions, type MeasureTool, MeshExtractionOptions, type RenderConfig, type RenderPipeline, type RenderPipelineOptions, SCALE_FACTORS, type ThreeInitializerOptions, type ViewGizmo, type ViewPreset, addEdges, applyOffset, computeCombinedBoundingBox, createCameraController, createGrid, createLabelLayer, createMeasureTool, createRenderPipeline, createViewGizmo, getThreeMeshesFromComputeResponse, initThree, isEdgeOverlay, parseColor, parseDisplayItems, parseMeshBatchBlob, parseMeshBatchObject, removeEdges, snapToVertex, updateScene };
814
+ export { type CameraConfig, type CameraController, type CameraProjection, type ControlsConfig, DisplayBatch, DisplayItem, type DisplayItemParseOptions, EDGE_USERDATA_KIND, type EdgeOptions, type EdgesConfig, type EnvironmentConfig, type EventConfig, type FloorConfig, type GizmoConfig, type Grid, type GridConfig, type GridOptions, LOOKS, type LabelHandle, type LabelLayer, type LightingConfig, type Look, threeMaterials as Materials, type MeasureConfig, type MeasureOptions, type MeasureTool, MeshExtractionOptions, type RenderConfig, type RenderPipeline, type RenderPipelineOptions, SCALE_FACTORS, type ThreeInitializerOptions, type ViewGizmo, type ViewPreset, addEdges, applyOffset, computeCombinedBoundingBox, createCameraController, createGrid, createLabelLayer, createMeasureTool, createRenderPipeline, createViewGizmo, getThreeMeshesFromComputeResponse, initThree, isEdgeOverlay, parseColor, parseDisplayItems, parseMeshBatchBlob, parseMeshBatchObject, removeEdges, snapToVertex, updateScene };
@@ -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-LUP3B2DK.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};
1
+ import{K as v,L as c,M as j,N as z,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 x,p as d,u as C,v as g,w as h}from"./chunk-PX2YTSHJ.js";import"./chunk-WPB2LKCD.js";export{n as EDGE_USERDATA_KIND,g as LOOKS,e as Materials,j as SCALE_FACTORS,l as addEdges,o as applyOffset,i as computeCombinedBoundingBox,a as createCameraController,s as createGrid,u as createLabelLayer,d as createMeasureTool,y as createRenderPipeline,p as createViewGizmo,z as getThreeMeshesFromComputeResponse,C as initThree,f as isEdgeOverlay,t as parseColor,h as parseDisplayItems,c as parseMeshBatchBlob,v as parseMeshBatchObject,m as removeEdges,x as snapToVertex,r as updateScene};
2
2
  //# sourceMappingURL=visualization.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selvajs/compute",
3
- "version": "3.0.1",
3
+ "version": "3.1.0-beta.10",
4
4
  "description": "TypeScript library for Rhino Compute Server - Grasshopper and RhinoCommon",
5
5
  "author": "VektorNode",
6
6
  "license": "MIT",
@@ -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 $=Object.defineProperty;var k=(t,e,r)=>e in t?$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var le=(t,e)=>{for(var r in e)$(t,r,{get:e[r],enumerable:!0})};var g=(t,e,r)=>k(t,typeof e!="symbol"?e+"":e,r);var u={NETWORK_ERROR:"NETWORK_ERROR",AUTH_ERROR:"AUTH_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",COMPUTATION_ERROR:"COMPUTATION_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",CORS_ERROR:"CORS_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR",INVALID_STATE:"INVALID_STATE",INVALID_INPUT:"INVALID_INPUT",INVALID_CONFIG:"INVALID_CONFIG",BROWSER_ONLY:"BROWSER_ONLY",ENVIRONMENT_ERROR:"ENVIRONMENT_ERROR",ENCODING_ERROR:"ENCODING_ERROR",MALFORMED_DEFAULT:"MALFORMED_DEFAULT",SUPERSEDED:"SUPERSEDED",ABORTED:"ABORTED",DEFINITION_NOT_CACHED:"DEFINITION_NOT_CACHED"},d= exports.d =class t extends Error{constructor(r,n="UNKNOWN_ERROR",o){super(r);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(r,n,o){return new t(`Input "${r}" has no values defined${n?` (expected ${n})`:""}`,u.INVALID_INPUT,{context:{inputName:r,expectedType:n,...o}})}static unknownParamType(r,n,o){return new t(`Unknown paramType: ${r}`,u.VALIDATION_ERROR,{context:{receivedParamType:r,paramName:n,...o}})}};var T=class{debug(){}info(){}warn(){}error(){}},N=class{debug(e,...r){console.debug(e,...r)}info(e,...r){console.info(e,...r)}warn(e,...r){console.warn(e,...r)}error(e,...r){console.error(e,...r)}},U=new T;function p(){return U}function D(t){U=t===null?new T:t}function B(){D(new N)}function q(t){if(!t)return null;let e={raw:t},r=!1;for(let n of t.split(",")){let[o,...i]=n.trim().split(";"),f=i.find(c=>c.trim().toLowerCase().startsWith("dur"));if(!f)continue;let s=Number(f.split("=")[1]);if(!Number.isFinite(s))continue;let l=o.trim().toLowerCase();(l==="decode"||l==="solve"||l==="encode")&&(e[l]=s,r=!0)}return r?e:null}var E={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},_=new Set([502,503,504]);function K(t){return t?{attempts:_nullishCoalesce(t.attempts, () => (E.attempts)),baseDelayMs:_nullishCoalesce(t.baseDelayMs, () => (E.baseDelayMs)),maxDelayMs:_nullishCoalesce(t.maxDelayMs, () => (E.maxDelayMs)),retryOn429:_nullishCoalesce(t.retryOn429, () => (E.retryOn429))}:E}function W(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e)&&e>=0)return e*1e3;let r=Date.parse(t);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return null}function S(t,e){let r=e.baseDelayMs*Math.pow(2,t),n=Math.random()*e.baseDelayMs;return Math.min(r+n,e.maxDelayMs)}function H(t,e){return new Promise((r,n)=>{if(_optionalChain([e, 'optionalAccess', _6 => _6.aborted])){n(new DOMException("Aborted","AbortError"));return}let o=setTimeout(()=>{_optionalChain([e, 'optionalAccess', _7 => _7.removeEventListener, 'call', _8 => _8("abort",i)]),r()},t),i=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))};_optionalChain([e, 'optionalAccess', _9 => _9.addEventListener, 'call', _10 => _10("abort",i,{once:!0})])})}function z(t,e,r,n,o,i,f){let{status:s,statusText:l}=t,c={};t.headers.forEach((A,M)=>{c[M]=A});let m=i.trim(),a=m?` \u2014 ${m.slice(0,200)}${m.length>200?"\u2026":""}`:"",y={url:e,requestId:r,method:"POST",requestSize:n,serverUrl:o,responseBody:i||void 0,responseHeaders:c},v={401:{message:`HTTP ${s}: ${l}${a}`,code:u.AUTH_ERROR},403:{message:`HTTP ${s}: ${l}${a}`,code:u.AUTH_ERROR},404:{message:`Endpoint not found: ${e}`,code:u.NETWORK_ERROR},413:{message:`Request too large: ${(n/1024).toFixed(2)}KB`,code:u.VALIDATION_ERROR},429:{message:`Rate limit exceeded${a}`,code:u.NETWORK_ERROR},500:{message:`Server error: ${l}${a}`,code:u.COMPUTATION_ERROR},502:{message:`Service unavailable: ${l}${a}`,code:u.NETWORK_ERROR},503:{message:`Service unavailable: ${l}${a}`,code:u.NETWORK_ERROR},504:{message:`Service unavailable: ${l}${a}`,code:u.NETWORK_ERROR}}[s]||{message:`HTTP ${s}: ${l}${a}`,code:u.UNKNOWN_ERROR},w=_nullishCoalesce(V(f), () => (v.code));throw new d(v.message,w,{statusCode:s,context:y})}function V(t){if(t==="definition_not_cached")return u.DEFINITION_NOT_CACHED}function J(t,e){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${r}/${n}`}function G(t){try{let e=new URL(t).host;return/^(localhost|127\.0\.0\.1|::1)(:\d+)?$/i.test(e)}catch (e2){return/(localhost|127\.0\.0\.1)/i.test(t)}}function Y(t,e){let r={"X-Request-ID":t,"Content-Type":"application/json",...e.authToken&&{Authorization:e.authToken},...e.apiKey&&{RhinoComputeKey:e.apiKey}};return!e.apiKey&&!e.authToken&&!G(e.serverUrl)&&p().warn(`\u26A0\uFE0F [Rhino Compute] Request [${t}] targets remote server (${e.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited.`),r}function j(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function R(t,e){e&&p().debug(t)}function Z(t,e){let r=[],n=()=>{};if(t&&r.push(t),e&&e>0)if(typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function")r.push(AbortSignal.timeout(e));else{let s=new AbortController,l=setTimeout(()=>s.abort(),e);n=()=>clearTimeout(l),r.push(s.signal)}if(r.length===0)return{signal:void 0,cleanup:n};if(r.length===1)return{signal:r[0],cleanup:n};if(typeof AbortSignal<"u"&&typeof AbortSignal.any=="function")return{signal:AbortSignal.any(r),cleanup:n};let o=new AbortController,i=()=>o.abort();for(let s of r){if(s.aborted){o.abort();break}s.addEventListener("abort",i,{once:!0})}let f=n;return n=()=>{f();for(let s of r)s.removeEventListener("abort",i)},{signal:o.signal,cleanup:n}}async function X(t,e,r,n,o,i,f,s){let l=Math.round(performance.now()-i);if(!t.ok){let c=await t.text();f&&(R(`\u274C Request [${r}] failed with HTTP ${t.status} in ${l}ms`,!0),R(` URL: ${e}`,!0),R(` Status: ${t.status} ${t.statusText}`,!0),c&&R(` Response body: ${c.substring(0,500)}${c.length>500?"...":""}`,!0));let m;try{let a=JSON.parse(c);typeof _optionalChain([a, 'optionalAccess', _11 => _11.code])=="string"&&(m=a.code)}catch (e3){}if(t.status===500)try{let a=JSON.parse(c);if(_optionalChain([a, 'optionalAccess', _12 => _12.values])&&(a.errors||a.warnings))return f&&(R(`\u26A0\uFE0F Request [${r}] completed with Grasshopper errors in ${l}ms`,!0),_optionalChain([a, 'access', _13 => _13.errors, 'optionalAccess', _14 => _14.length])>0&&R(` Errors: ${JSON.stringify(a.errors,null,2)}`,!0),_optionalChain([a, 'access', _15 => _15.warnings, 'optionalAccess', _16 => _16.length])>0&&R(` Warnings: ${JSON.stringify(a.warnings,null,2)}`,!0)),a;let y=typeof _optionalChain([a, 'optionalAccess', _17 => _17.message])=="string"&&a.message||typeof _optionalChain([a, 'optionalAccess', _18 => _18.Message])=="string"&&a.Message||"",h=typeof _optionalChain([a, 'optionalAccess', _19 => _19.ExceptionType])=="string"&&a.ExceptionType||"",v=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _20 => _20.stackTrace]), () => (_optionalChain([a, 'optionalAccess', _21 => _21.StackTrace]))),w=Array.isArray(v)?v.join(`
2
- `):v||"";y?c=`${h?`${h}: `:""}${y}${w?`
3
- ${w}`:""}`:_optionalChain([a, 'optionalAccess', _22 => _22.error])&&(c=typeof a.error=="string"?a.error:JSON.stringify(a.error,null,2))}catch(a){f&&R(` Failed to parse error body as JSON: ${a}`,!0)}z(t,e,r,n,o,c,m)}if(R(`\u2705 Request [${r}] completed in ${l}ms`,f),s){let c=q(t.headers.get("Server-Timing"));if(c)try{s(c)}catch(m){f&&R(` onServerTiming callback threw: ${m}`,!0)}}try{return await t.json()}catch(c){throw new d("Failed to parse JSON response",u.NETWORK_ERROR,{statusCode:t.status,context:{url:e,requestId:r},originalError:c instanceof Error?c:new Error(String(c))})}}async function Q(t,e,r,n){let{signal:o,cleanup:i}=Z(t.config.signal,t.config.timeoutMs),f=performance.now();try{let s=await fetch(t.fullUrl,{method:"POST",body:t.body,headers:t.headers,signal:o});if((_.has(s.status)||e.retryOn429&&s.status===429)&&r<n-1){let m=W(s.headers.get("Retry-After")),a=m!==null?Math.min(m,e.maxDelayMs):S(r,e);return await s.text().catch(()=>{}),{ok:!1,retry:!0,delayMs:a,cause:new d(`HTTP ${s.status} ${s.statusText} (will retry)`,u.NETWORK_ERROR,{statusCode:s.status,context:{requestId:t.requestId}})}}return{ok:!0,value:await X(s,t.fullUrl,t.requestId,t.requestSize,t.config.serverUrl,f,t.config.debug,t.config.onServerTiming)}}catch(s){if(s instanceof Error&&(s.name==="AbortError"||s.name==="TimeoutError")){if(_optionalChain([t, 'access', _23 => _23.config, 'access', _24 => _24.signal, 'optionalAccess', _25 => _25.aborted])===!0)return{ok:!1,retry:!1,cause:new d("Request aborted by caller",u.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId,requestSize:t.requestSize},originalError:s})};let c=new d(`Request timed out after ${t.config.timeoutMs}ms`,u.TIMEOUT_ERROR,{context:{serverUrl:t.config.serverUrl,timeoutMs:t.config.timeoutMs,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize}});return r<n-1?{ok:!1,retry:!0,delayMs:S(r,e),cause:c}:{ok:!1,retry:!1,cause:c}}if(s instanceof TypeError){let l=new d(`Network error: ${s.message}`,u.NETWORK_ERROR,{context:{serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:s});return r<n-1?{ok:!1,retry:!0,delayMs:S(r,e),cause:l}:{ok:!1,retry:!1,cause:l}}if(s instanceof d){let l=s.statusCode;return l!==void 0&&(_.has(l)||e.retryOn429&&l===429)&&r<n-1?{ok:!1,retry:!0,delayMs:S(r,e),cause:s}:{ok:!1,retry:!1,cause:s}}return{ok:!1,retry:!1,cause:new d(s instanceof Error?s.message:String(s),u.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId},originalError:s instanceof Error?s:new Error(String(s))})}}finally{i()}}async function ee(t,e,r){let n=j(),o=JSON.stringify(e),i=o.length,f=J(t,r.serverUrl),s=Y(n,r),l=K(r.retry),c=l.attempts+1;if(r.debug){let y=(i/1024).toFixed(2),h=i>1e5?"\u26A0\uFE0F":"\u{1F680}";R(`${h} Starting compute request [${n}]: ${t} (${y}KB)`,!0)}let m={endpoint:t,body:o,requestSize:i,fullUrl:f,requestId:n,headers:s,config:r},a=null;for(let y=0;y<c;y++){let h=await Q(m,l,y,c);if(h.ok)return h.value;if(!h.retry)throw h.cause;a=h.cause,r.debug&&R(`\u{1F501} Request [${n}] retrying after ${h.delayMs}ms (attempt ${y+2}/${c}): ${h.cause.message}`,!0);try{await H(h.delayMs,r.signal)}catch (e4){throw new d("Request aborted by caller",u.UNKNOWN_ERROR,{context:{endpoint:t,requestId:n,requestSize:i},originalError:a})}}throw _nullishCoalesce(a, () => (new d("Unknown error after retries",u.UNKNOWN_ERROR,{context:{endpoint:t,requestId:n,requestSize:i}})))}var re="https://compute.rhino3d.com/";function F(t){if(!_optionalChain([t, 'optionalAccess', _26 => _26.trim, 'call', _27 => _27()]))throw new d("serverUrl is required",u.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(!t.match(/^https?:\/\//))throw new d(`Invalid serverUrl: "${t}". Must start with "http://" or "https://". For example: "http://localhost:5000" or "https://example.com"`,u.INVALID_CONFIG,{context:{receivedServerUrl:t}});try{new URL(t)}catch(e){throw new d(`Invalid serverUrl: "${t}". Must be a valid URL. Received error: ${e instanceof Error?e.message:String(e)}`,u.INVALID_CONFIG,{context:{receivedServerUrl:t},originalError:e instanceof Error?e:void 0})}if(t===re)throw new d("serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.",u.INVALID_CONFIG,{context:{receivedServerUrl:t}});return t.replace(/\/+$/,"")}var b=class b{constructor(e,r){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=r}buildHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,r={},n=b.DEFAULT_TIMEOUT_MS){let o={headers:this.buildHeaders(),...r};return n>0&&!o.signal&&(o.signal=AbortSignal.timeout(n)),fetch(e,o)}async isServerOnline(e=5e3){this.ensureNotDisposed();let r=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(r,{method:"GET"},e)).ok}catch(n){return p().debug("[ComputeServerStats] Fetch error:",n),!1}}async getActiveChildren(e={}){this.ensureNotDisposed();let{initialize:r=!0}=e,n=r?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,o=r?b.LIFECYCLE_TIMEOUT_MS:b.DEFAULT_TIMEOUT_MS;try{let i=await this.fetchWithTimeout(n,{},o);if(!i.ok)return p().warn("[ComputeServerStats] Failed to fetch active children:",i.status),null;let f=await i.text(),s=parseInt(f.trim(),10);return isNaN(s)?(p().warn("[ComputeServerStats] Invalid active children response:",f),null):s}catch(i){return p().warn("[ComputeServerStats] Error fetching active children:",i),null}}async getVersion(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch version:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return{rhino:_nullishCoalesce(n.rhino, () => ("")),compute:_nullishCoalesce(n.compute, () => ("")),git_sha:_nullishCoalesce(n.git_sha, () => (null))}}catch (e5){return{rhino:r,compute:"",git_sha:null}}}catch(e){return p().warn("[ComputeServerStats] Error fetching version:",e),null}}async getInstalledPlugins(e="gh"){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${e}/installed`);if(!r.ok)return p().warn(`[ComputeServerStats] Failed to fetch ${e} plugins:`,r.status),null;let n=await r.text();try{let o=JSON.parse(n);return o&&typeof o=="object"?o:null}catch (e6){return null}}catch(r){return p().warn(`[ComputeServerStats] Error fetching ${e} plugins:`,r),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[r,n]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...r&&{version:r},...n!==null&&{activeChildren:n}}}async purgeCache(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:"POST"});if(!e.ok)return p().warn("[ComputeServerStats] Failed to purge cache:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return typeof n.purged=="number"?n.purged:null}catch (e7){return null}}catch(e){return p().warn("[ComputeServerStats] Error purging cache:",e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return p().warn("[ComputeServerStats] purgeAllChildren: could not read child count"),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let r=e*2,n=0;for(let o=0;o<r;o++){let i=await this.purgeCache();i!==null&&(n+=i)}return{totalPurged:n,calls:r,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch server time:",e.status),null;let r=(await e.text()).trim().replace(/^"|"$/g,""),n=new Date(r);return isNaN(n.getTime())?null:n}catch(e){return p().warn("[ComputeServerStats] Error fetching server time:",e),null}}async getIdleSpan(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch idle span:",e.status),null;let r=parseFloat((await e.text()).trim());return isNaN(r)?null:r}catch(e){return p().warn("[ComputeServerStats] Error fetching idle span:",e),null}}async launchChildren(){return this.postJson("/launch-children")}async launchChild(e){let r=e===void 0?"/launch-child":`/launch-child?port=${e}`;return this.postJson(r)}async shutdownChildren(e){let r=e===void 0?"/shutdown-children":`/shutdown-children?port=${e}`;return this.postJson(r)}async recycleChildren(e){let r=e===void 0?"/recycle-children":`/recycle-children?port=${e}`;return this.postJson(r)}async postJson(e){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}${e}`,{method:"POST"},b.LIFECYCLE_TIMEOUT_MS);if(!r.ok)return p().warn(`[ComputeServerStats] POST ${e} failed:`,r.status),null;let n=await r.text();try{return JSON.parse(n)}catch (e8){return null}}catch(r){return p().warn(`[ComputeServerStats] Error on POST ${e}:`,r),null}}monitor(e,r=5e3){this.ensureNotDisposed();let n=!0,o=null;p().info(`\u{1F504} Starting server stats monitoring every ${r}ms`);let i=async()=>{if(o!==null&&(this.activeTimeouts.delete(o),o=null),!(!n||this.disposed)){try{let s=await this.getServerStats();if(!n||this.disposed)return;try{e(s)}catch(l){p().error("[ComputeServerStats] Monitor callback threw:",l)}}catch(s){p().error("[ComputeServerStats] Failed to fetch stats during monitor:",s)}n&&!this.disposed&&(o=setTimeout(()=>{i()},r),this.activeTimeouts.add(o))}},f=()=>{n=!1,o!==null&&(clearTimeout(o),this.activeTimeouts.delete(o),o=null),this.activeMonitors.delete(f)};return this.activeMonitors.add(f),i(),f}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",u.INVALID_STATE,{context:{disposed:this.disposed}})}};g(b,"DEFAULT_TIMEOUT_MS",5e3),g(b,"LIFECYCLE_TIMEOUT_MS",6e4);var O=b;function P(t,e={}){let{preserveSpaces:r=!1}=e,n=r?/[-_]+(.)?/g:/[\s-_]+(.)?/g,o=t.trim();return o.charAt(0).toLowerCase()+o.slice(1).replace(n,(i,f)=>f?f.toUpperCase():"")}function C(t,e={}){return!t||typeof t!="object"?t:Array.isArray(t)?e.deep?t.map(r=>C(r,e)):t:Object.keys(t).reduce((r,n)=>{let o=P(n,{preserveSpaces:e.preserveSpaces}),i=t[n];return r[o]=e.deep?C(i,e):i,r},{})}function I(){let t=globalThis.Buffer;return typeof t=="function"?t:void 0}function Ne(t){let e=I();return e?e.from(t,"utf-8").toString("base64"):te(new TextEncoder().encode(t))}function Ce(t){return!t||t.length<2||t.length%4!==0?!1:/^[A-Za-z0-9+/]+={0,2}$/.test(t)}function L(t){let e=I();if(e){let r=e.from(t,"base64");return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(typeof globalThis.atob=="function"){let r=globalThis.atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r.charCodeAt(o)&255;return n}throw new d("Base64 decoding not supported in this environment.",u.INVALID_STATE,{context:{environmentInfo:"atob or Buffer not available"}})}function te(t){let e=I();if(e)return e.from(t).toString("base64");if(typeof globalThis.btoa=="function"){let n="";for(let o=0;o<t.length;o+=32768)n+=String.fromCharCode.apply(null,t.subarray(o,o+32768));return globalThis.btoa(n)}throw new d("Base64 encoding not supported in this environment.",u.INVALID_STATE,{context:{environmentInfo:"btoa or Buffer not available"}})}var ne=async(t,e=null)=>{try{return await x(t,e)}catch(r){throw new d("Failed to extract files from compute response",u.INVALID_STATE,{context:{originalError:r instanceof Error?r.message:String(r)},originalError:r instanceof Error?r:void 0})}},oe= exports.r =async(t,e,r=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).",u.BROWSER_ONLY,{context:{environment:typeof window<"u"?"browser (SSR)":"Node.js",documentAvailable:typeof document<"u",blobAvailable:typeof Blob<"u"}});try{let n=await x(t,r);await ae(n,e)}catch(n){throw n instanceof d?n:new d("Failed to download files from compute response",u.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}},se=t=>{let e=[];return t.forEach(r=>{let n=`${r.fileName}${r.fileType}`,o=r.subFolder&&r.subFolder.trim()!==""?`${r.subFolder}/${n}`:n;r.isBase64Encoded===!0&&r.data?e.push({fileName:n,content:L(r.data),path:o}):r.isBase64Encoded===!1&&r.data&&e.push({fileName:n,content:r.data,path:o})}),e},ie=async t=>(await Promise.all(t.map(async r=>{try{let n=await fetch(r.filePath);if(!n.ok)return p().warn(`Failed to fetch additional file from URL: ${r.filePath}`),null;let i=await(await n.blob()).arrayBuffer();return{fileName:r.fileName,content:new Uint8Array(i),path:r.fileName}}catch(n){return p().error(`Error fetching additional file from URL: ${r.filePath}`,n),null}}))).filter(r=>r!==null),x=async(t,e)=>{let r=se(t);if(e){let n=Array.isArray(e)?e:[e];r.push(...await ie(n))}return r};async function ae(t,e){let{zip:r,strToU8:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("fflate"))),o={};t.forEach(s=>{o[s.path]=typeof s.content=="string"?n(s.content):s.content});let i=await new Promise((s,l)=>{r(o,{level:6},(c,m)=>c?l(c):s(m))}),f=new Blob([i],{type:"application/zip"});ue(f,`${e}.zip`)}function ue(t,e){if(typeof document>"u")throw new d("saveFile requires a browser environment with DOM API access.",u.BROWSER_ONLY,{context:{function:"saveFile",requiredAPI:"document"}});let r=document.createElement("a");r.href=URL.createObjectURL(t),r.download=e,r.click(),URL.revokeObjectURL(r.href)}exports.a = le; exports.b = g; exports.c = u; exports.d = d; exports.e = p; exports.f = D; exports.g = B; exports.h = ee; exports.i = F; exports.j = O; exports.k = P; exports.l = C; exports.m = Ne; exports.n = Ce; exports.o = L; exports.p = te; exports.q = ne; exports.r = oe;
4
- //# sourceMappingURL=chunk-6LCAIDQV.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-6LCAIDQV.cjs","../src/core/errors.ts","../src/core/compute-fetch/compute-fetch.ts"],"names":["ErrorCodes","RhinoComputeError","_RhinoComputeError","message","code","options","__publicField","inputName","expectedType","context"],"mappings":"AAAA,u8BAAI,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CCI3N,IAAMA,CAAAA,CAAa,CACzB,aAAA,CAAe,eAAA,CACf,UAAA,CAAY,YAAA,CACZ,gBAAA,CAAkB,kBAAA,CAClB,iBAAA,CAAmB,mBAAA,CACnB,aAAA,CAAe,eAAA,CACf,UAAA,CAAY,YAAA,CACZ,aAAA,CAAe,eAAA,CACf,aAAA,CAAe,eAAA,CACf,aAAA,CAAe,eAAA,CACf,cAAA,CAAgB,gBAAA,CAChB,YAAA,CAAc,cAAA,CACd,iBAAA,CAAmB,mBAAA,CACnB,cAAA,CAAgB,gBAAA,CAEhB,iBAAA,CAAmB,mBAAA,CAEnB,UAAA,CAAY,YAAA,CAEZ,OAAA,CAAS,SAAA,CAQT,qBAAA,CAAuB,uBACxB,CAAA,CASaC,CAAAA,aAAN,MAAMC,EAAAA,QAA0B,KAAM,CAM5C,WAAA,CACCC,CAAAA,CACAC,CAAAA,CAAe,eAAA,CACfC,CAAAA,CACC,CACD,KAAA,CAAMF,CAAO,CAAA,CAVdG,CAAAA,CAAA,IAAA,CAAgB,MAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,YAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,SAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,eAAA,CAAA,CAQf,IAAA,CAAK,IAAA,CAAO,mBAAA,CACZ,IAAA,CAAK,IAAA,CAAOF,CAAAA,CACZ,IAAA,CAAK,UAAA,iBAAaC,CAAAA,6BAAS,YAAA,CAC3B,IAAA,CAAK,OAAA,iBAAUA,CAAAA,6BAAS,SAAA,CACxB,IAAA,CAAK,aAAA,iBAAgBA,CAAAA,6BAAS,eAAA,iBAC1BA,CAAAA,6BAAS,eAAA,EAAA,CACX,IAAA,CAA6B,KAAA,CAAQA,CAAAA,CAAQ,aAAA,CAEhD,CASA,OAAO,aAAA,CACNE,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACC,CACD,OAAO,IAAIP,CAAAA,CACV,CAAA,OAAA,EAAUK,CAAS,CAAA,uBAAA,EAA0BC,CAAAA,CAAe,CAAA,WAAA,EAAcA,CAAY,CAAA,CAAA,CAAA,CAAM,EAAE,CAAA,CAAA;ACgTzC;AAmI1C","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-6LCAIDQV.cjs","sourcesContent":[null,"/**\n * Error types and codes for `@selvajs/compute`.\n */\n\nexport const ErrorCodes = {\n\tNETWORK_ERROR: 'NETWORK_ERROR',\n\tAUTH_ERROR: 'AUTH_ERROR',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tCOMPUTATION_ERROR: 'COMPUTATION_ERROR',\n\tTIMEOUT_ERROR: 'TIMEOUT_ERROR',\n\tCORS_ERROR: 'CORS_ERROR',\n\tUNKNOWN_ERROR: 'UNKNOWN_ERROR',\n\tINVALID_STATE: 'INVALID_STATE',\n\tINVALID_INPUT: 'INVALID_INPUT',\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\tBROWSER_ONLY: 'BROWSER_ONLY',\n\tENVIRONMENT_ERROR: 'ENVIRONMENT_ERROR',\n\tENCODING_ERROR: 'ENCODING_ERROR',\n\t/** An input's `default` had a shape the normalizer didn't recognize (no innerTree key). */\n\tMALFORMED_DEFAULT: 'MALFORMED_DEFAULT',\n\t/** Scheduler latest-wins: this call was replaced by a newer one. */\n\tSUPERSEDED: 'SUPERSEDED',\n\t/** Scheduler / caller-supplied AbortSignal: this call was aborted. */\n\tABORTED: 'ABORTED',\n\t/**\n\t * A solve referenced a definition by `pointer` (server-side cache key), but the\n\t * server no longer holds that definition (evicted / GC'd / a different child in\n\t * the pool / server restarted). The caller should retry with the full\n\t * definition. Surfaced when the server tags its error body with\n\t * `code: \"definition_not_cached\"`, so it survives production message-scrubbing.\n\t */\n\tDEFINITION_NOT_CACHED: 'DEFINITION_NOT_CACHED'\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/**\n * Simplified error for Rhino Compute operations\n *\n * @public Use this for error handling with error codes and context.\n */\nexport class RhinoComputeError extends Error {\n\tpublic readonly code: string;\n\tpublic readonly statusCode?: number;\n\tpublic readonly context?: Record<string, unknown>;\n\tpublic readonly originalError?: Error;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: string = 'UNKNOWN_ERROR',\n\t\toptions?: { statusCode?: number; context?: Record<string, unknown>; originalError?: Error }\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'RhinoComputeError';\n\t\tthis.code = code;\n\t\tthis.statusCode = options?.statusCode;\n\t\tthis.context = options?.context;\n\t\tthis.originalError = options?.originalError;\n\t\tif (options?.originalError) {\n\t\t\t(this as { cause?: unknown }).cause = options.originalError;\n\t\t}\n\t}\n\n\t// ============================================================================\n\t// Static Validation Error Helpers\n\t// ============================================================================\n\n\t/**\n\t * Create an error for missing/empty values\n\t */\n\tstatic missingValues(\n\t\tinputName: string,\n\t\texpectedType?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(\n\t\t\t`Input \"${inputName}\" has no values defined${expectedType ? ` (expected ${expectedType})` : ''}`,\n\t\t\tErrorCodes.INVALID_INPUT,\n\t\t\t{ context: { inputName, expectedType, ...context } }\n\t\t);\n\t}\n\n\t/**\n\t * Create an error for unknown parameter type\n\t */\n\tstatic unknownParamType(\n\t\tparamType: string,\n\t\tparamName?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(`Unknown paramType: ${paramType}`, ErrorCodes.VALIDATION_ERROR, {\n\t\t\tcontext: { receivedParamType: paramType, paramName, ...context }\n\t\t});\n\t}\n}\n","import { RhinoComputeError, ErrorCodes, type ErrorCode } from '../errors';\nimport { getLogger } from '../utils/logger';\n\nimport type { ComputeConfig, RetryPolicy, ServerTiming } from '../types';\n\n// ============================================================================\n// Server-Timing\n// ============================================================================\n\n/**\n * Parse a `Server-Timing` header value into typed durations (ms).\n *\n * Header grammar (RFC 9110 §10.1.10), as emitted by the solve endpoint:\n * `decode;dur=3, solve;dur=120, encode;dur=8`\n *\n * Returns null when the header is absent or carries no recognizable metric, so\n * the caller can skip the callback entirely.\n *\n * @internal exported for tests\n */\nexport function parseServerTiming(headerValue: string | null): ServerTiming | null {\n\tif (!headerValue) return null;\n\tconst timing: ServerTiming = { raw: headerValue };\n\tlet sawMetric = false;\n\tfor (const part of headerValue.split(',')) {\n\t\tconst [name, ...params] = part.trim().split(';');\n\t\tconst durParam = params.find((p) => p.trim().toLowerCase().startsWith('dur'));\n\t\tif (!durParam) continue;\n\t\tconst dur = Number(durParam.split('=')[1]);\n\t\tif (!Number.isFinite(dur)) continue;\n\t\tconst key = name.trim().toLowerCase();\n\t\tif (key === 'decode' || key === 'solve' || key === 'encode') {\n\t\t\ttiming[key] = dur;\n\t\t\tsawMetric = true;\n\t\t}\n\t}\n\treturn sawMetric ? timing : null;\n}\n\n// ============================================================================\n// Retry Policy\n// ============================================================================\n\nconst DEFAULT_RETRY: Required<RetryPolicy> = {\n\tattempts: 0,\n\tbaseDelayMs: 500,\n\tmaxDelayMs: 30_000,\n\tretryOn429: true\n};\n\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\nfunction resolveRetryPolicy(policy: RetryPolicy | undefined): Required<RetryPolicy> {\n\tif (!policy) return DEFAULT_RETRY;\n\treturn {\n\t\tattempts: policy.attempts ?? DEFAULT_RETRY.attempts,\n\t\tbaseDelayMs: policy.baseDelayMs ?? DEFAULT_RETRY.baseDelayMs,\n\t\tmaxDelayMs: policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs,\n\t\tretryOn429: policy.retryOn429 ?? DEFAULT_RETRY.retryOn429\n\t};\n}\n\n/**\n * Parse a Retry-After header value (seconds-int or HTTP-date) into ms.\n * Returns null if the header is missing or unparseable.\n */\nfunction parseRetryAfter(headerValue: string | null): number | null {\n\tif (!headerValue) return null;\n\tconst seconds = Number(headerValue);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n\tconst dateMs = Date.parse(headerValue);\n\tif (Number.isFinite(dateMs)) {\n\t\tconst delta = dateMs - Date.now();\n\t\treturn delta > 0 ? delta : 0;\n\t}\n\treturn null;\n}\n\nfunction backoffDelay(attempt: number, policy: Required<RetryPolicy>): number {\n\tconst exponential = policy.baseDelayMs * Math.pow(2, attempt);\n\tconst jitter = Math.random() * policy.baseDelayMs;\n\treturn Math.min(exponential + jitter, policy.maxDelayMs);\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t\treturn;\n\t\t}\n\t\tconst id = setTimeout(() => {\n\t\t\tsignal?.removeEventListener('abort', onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(id);\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t};\n\t\tsignal?.addEventListener('abort', onAbort, { once: true });\n\t});\n}\n\n// ============================================================================\n// Error Handling\n// ============================================================================\n\nfunction throwHttpError(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\terrorBody: string,\n\tserverCode?: string\n): never {\n\tconst { status, statusText } = response;\n\n\tconst responseHeaders: Record<string, string> = {};\n\tresponse.headers.forEach((value, key) => {\n\t\tresponseHeaders[key] = value;\n\t});\n\n\tconst trimmed = errorBody.trim();\n\tconst bodyHint = trimmed ? ` — ${trimmed.slice(0, 200)}${trimmed.length > 200 ? '…' : ''}` : '';\n\n\tconst context = {\n\t\turl: fullUrl,\n\t\trequestId,\n\t\tmethod: 'POST',\n\t\trequestSize,\n\t\tserverUrl,\n\t\tresponseBody: errorBody || undefined,\n\t\tresponseHeaders\n\t};\n\n\tconst errorMap: Record<number, { message: string; code: string }> = {\n\t\t401: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t403: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t404: { message: `Endpoint not found: ${fullUrl}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t413: {\n\t\t\tmessage: `Request too large: ${(requestSize / 1024).toFixed(2)}KB`,\n\t\t\tcode: ErrorCodes.VALIDATION_ERROR\n\t\t},\n\t\t429: { message: `Rate limit exceeded${bodyHint}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t500: { message: `Server error: ${statusText}${bodyHint}`, code: ErrorCodes.COMPUTATION_ERROR },\n\t\t502: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t503: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t504: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t}\n\t};\n\n\tconst error = errorMap[status] || {\n\t\tmessage: `HTTP ${status}: ${statusText}${bodyHint}`,\n\t\tcode: ErrorCodes.UNKNOWN_ERROR\n\t};\n\n\t// A machine code in the server's error body (e.g. \"definition_not_cached\")\n\t// outranks the status-based mapping: it's stable across the server's\n\t// production message-scrubbing, where the human message is replaced with a\n\t// generic string. Keep the status-derived message for context.\n\tconst code = mapServerErrorCode(serverCode) ?? error.code;\n\n\tthrow new RhinoComputeError(error.message, code, { statusCode: status, context });\n}\n\n/**\n * Map a server-supplied error code (from the JSON error body's `code` field) to\n * one of our {@link ErrorCodes}. Returns `undefined` for an absent or unknown\n * code so the caller falls back to its status-based mapping.\n */\nfunction mapServerErrorCode(serverCode?: string): ErrorCode | undefined {\n\tswitch (serverCode) {\n\t\tcase 'definition_not_cached':\n\t\t\treturn ErrorCodes.DEFINITION_NOT_CACHED;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n// ============================================================================\n// Request Helpers\n// ============================================================================\n\nfunction buildUrl(endpoint: string, serverUrl: string): string {\n\tconst base = serverUrl.replace(/\\/+$/, '');\n\tconst path = endpoint.replace(/^\\/+/, '');\n\treturn `${base}/${path}`;\n}\n\nfunction isLocalhost(serverUrl: string): boolean {\n\ttry {\n\t\tconst host = new URL(serverUrl).host;\n\t\treturn /^(localhost|127\\.0\\.0\\.1|::1)(:\\d+)?$/i.test(host);\n\t} catch {\n\t\treturn /(localhost|127\\.0\\.0\\.1)/i.test(serverUrl);\n\t}\n}\n\nfunction buildHeaders(requestId: string, config: ComputeConfig): HeadersInit {\n\tconst headers: HeadersInit = {\n\t\t'X-Request-ID': requestId,\n\t\t'Content-Type': 'application/json',\n\t\t...(config.authToken && { Authorization: config.authToken }),\n\t\t...(config.apiKey && { RhinoComputeKey: config.apiKey })\n\t};\n\n\tif (!config.apiKey && !config.authToken && !isLocalhost(config.serverUrl)) {\n\t\tgetLogger().warn(\n\t\t\t`⚠️ [Rhino Compute] Request [${requestId}] targets remote server (${config.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited.`\n\t\t);\n\t}\n\n\treturn headers;\n}\n\nfunction generateRequestId(): string {\n\treturn `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n}\n\nfunction log(message: string, debug?: boolean): void {\n\tif (debug) getLogger().debug(message);\n}\n\n/**\n * Compose a caller-supplied AbortSignal with an optional timeout. Returns a\n * combined signal, or `undefined` if neither was given.\n *\n * Uses `AbortSignal.timeout` (not setTimeout) so the timer is not throttled\n * when the tab is hidden. Falls back to a manual timer for older runtimes.\n *\n * @internal exported for tests\n */\nexport function composeSignal(\n\tcallerSignal: AbortSignal | undefined,\n\ttimeoutMs: number | undefined\n): { signal: AbortSignal | undefined; cleanup: () => void } {\n\tconst signals: AbortSignal[] = [];\n\tlet cleanup = () => {};\n\n\tif (callerSignal) signals.push(callerSignal);\n\n\tif (timeoutMs && timeoutMs > 0) {\n\t\tif (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {\n\t\t\tsignals.push(AbortSignal.timeout(timeoutMs));\n\t\t} else {\n\t\t\t// Fallback for runtimes without AbortSignal.timeout\n\t\t\tconst ctrl = new AbortController();\n\t\t\tconst id = setTimeout(() => ctrl.abort(), timeoutMs);\n\t\t\tcleanup = () => clearTimeout(id);\n\t\t\tsignals.push(ctrl.signal);\n\t\t}\n\t}\n\n\tif (signals.length === 0) return { signal: undefined, cleanup };\n\tif (signals.length === 1) return { signal: signals[0], cleanup };\n\n\tif (typeof AbortSignal !== 'undefined' && typeof (AbortSignal as any).any === 'function') {\n\t\treturn { signal: (AbortSignal as any).any(signals) as AbortSignal, cleanup };\n\t}\n\n\t// Manual composition fallback\n\tconst ctrl = new AbortController();\n\tconst onAbort = () => ctrl.abort();\n\tfor (const s of signals) {\n\t\tif (s.aborted) {\n\t\t\tctrl.abort();\n\t\t\tbreak;\n\t\t}\n\t\ts.addEventListener('abort', onAbort, { once: true });\n\t}\n\tconst prevCleanup = cleanup;\n\tcleanup = () => {\n\t\tprevCleanup();\n\t\tfor (const s of signals) s.removeEventListener('abort', onAbort);\n\t};\n\treturn { signal: ctrl.signal, cleanup };\n}\n\n// ============================================================================\n// Response Processing\n// ============================================================================\n\nasync function handleResponse(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\tstartTime: number,\n\tdebug?: boolean,\n\tonServerTiming?: (timing: ServerTiming) => void\n): Promise<any> {\n\tconst responseTime = Math.round(performance.now() - startTime);\n\n\tif (!response.ok) {\n\t\t// Read body once and reuse\n\t\tlet errorBody = await response.text();\n\n\t\t// Enhanced logging for errors\n\t\tif (debug) {\n\t\t\tlog(\n\t\t\t\t`❌ Request [${requestId}] failed with HTTP ${response.status} in ${responseTime}ms`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t\tlog(` URL: ${fullUrl}`, true);\n\t\t\tlog(` Status: ${response.status} ${response.statusText}`, true);\n\t\t\tif (errorBody) {\n\t\t\t\tlog(\n\t\t\t\t\t` Response body: ${errorBody.substring(0, 500)}${errorBody.length > 500 ? '...' : ''}`,\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// A machine-readable code the server may tag onto its error body (e.g.\n\t\t// \"definition_not_cached\"). Unlike the human `message`, it isn't scrubbed in\n\t\t// the server's production (non-debug) mode, so it's the reliable signal for\n\t\t// classifying the error (see throwHttpError → mapServerErrorCode).\n\t\tlet serverCode: string | undefined;\n\n\t\t// 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"]}