//#region src/core/errors.d.ts declare const ErrorCodes: { readonly NETWORK_ERROR: "NETWORK_ERROR"; readonly AUTH_ERROR: "AUTH_ERROR"; readonly VALIDATION_ERROR: "VALIDATION_ERROR"; readonly COMPUTATION_ERROR: "COMPUTATION_ERROR"; readonly TIMEOUT_ERROR: "TIMEOUT_ERROR"; readonly CORS_ERROR: "CORS_ERROR"; /** HTTP 404 — the endpoint path does not exist on the server (usually a typo'd route or wrong server). Never retried. */ readonly NOT_FOUND: "NOT_FOUND"; /** HTTP 429 — the server is rate-limiting requests. Retried (honoring `Retry-After`) once a retry policy sets `attempts > 0`; opt out via `RetryPolicy.retryOn429`. */ readonly RATE_LIMIT: "RATE_LIMIT"; /** * The server answered 2xx but the body is deterministically not JSON (the * response declared a non-JSON `Content-Type`, e.g. an HTML captive-portal or * proxy login page, or a misconfigured endpoint). Never retried — refetching * returns the same page. */ readonly INVALID_RESPONSE: "INVALID_RESPONSE"; readonly UNKNOWN_ERROR: "UNKNOWN_ERROR"; readonly INVALID_STATE: "INVALID_STATE"; readonly INVALID_INPUT: "INVALID_INPUT"; readonly INVALID_CONFIG: "INVALID_CONFIG"; readonly BROWSER_ONLY: "BROWSER_ONLY"; /** The runtime lacks a required capability (e.g. no base64 codec — neither `Buffer` nor `atob`/`btoa`). */ readonly ENVIRONMENT_ERROR: "ENVIRONMENT_ERROR"; readonly ENCODING_ERROR: "ENCODING_ERROR"; /** An input's `default` had a shape the normalizer didn't recognize (no innerTree key). */ readonly MALFORMED_DEFAULT: "MALFORMED_DEFAULT"; /** Scheduler latest-wins: this call was replaced by a newer one. */ readonly SUPERSEDED: "SUPERSEDED"; /** Scheduler / caller-supplied AbortSignal: this call was aborted. */ readonly ABORTED: "ABORTED"; /** * Scheduler backpressure: the queue was already at `maxQueueDepth` when this * call arrived, so it was rejected immediately rather than queued. Retryable — the * caller (or an HTTP layer, as 503 + Retry-After) should back off and retry. * The error `context` carries `{ queueDepth, maxQueueDepth }`. */ readonly QUEUE_FULL: "QUEUE_FULL"; /** * Scheduler backpressure: this call sat queued longer than `queueWaitMs` * without starting, so it was rejected before wasting compute on a stale request. * Retryable. The error `context` carries `{ waitedMs, queueWaitMs }`. */ readonly QUEUE_TIMEOUT: "QUEUE_TIMEOUT"; /** * A solve referenced a definition by `pointer` (server-side cache key), but the * server no longer holds that definition (evicted / GC'd / a different child in * the pool / server restarted). The caller should retry with the full * definition. Surfaced when the server tags its error body with * `code: "definition_not_cached"`, so it survives production message-scrubbing. */ readonly DEFINITION_NOT_CACHED: "DEFINITION_NOT_CACHED"; }; type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes]; /** * Simplified error for Rhino Compute operations * * @public Use this for error handling with error codes and context. */ declare class ComputeError extends Error { readonly code: ErrorCode; readonly statusCode?: number; readonly context?: Record; readonly originalError?: Error; constructor(message: string, code?: ErrorCode, options?: { statusCode?: number; context?: Record; originalError?: Error; }); /** * Create an error for missing/empty values */ static missingValues(inputName: string, expectedType?: string, context?: Record): ComputeError; /** * Create an error for unknown parameter type */ static unknownParamType(paramType: string, paramName?: string, context?: Record): ComputeError; } //#endregion //#region src/core/types.d.ts /** * Backend wire code (the JSON error body's `code` field) → one of our * {@link ErrorCodes}. An unlisted code falls back to the status-based mapping. */ type ServerErrorCodeMap = Record; interface RetryPolicy { /** Maximum number of retry attempts after the initial request (default: 0). */ attempts?: number; /** Base delay in milliseconds for exponential backoff (default: 500). */ baseDelayMs?: number; /** Upper bound for backoff delay (default: 30_000). */ maxDelayMs?: number; /** Whether to retry on 429 responses (default: true — honors Retry-After). */ retryOn429?: boolean; } interface ComputeConfig { serverUrl: string; /** Optional API key for authenticating with the server. Sent as {@link apiKeyHeader}. */ apiKey?: string; /** * Header name carrying `apiKey`. Defaults to `'RhinoComputeKey'` — the name * rhino.compute expects. A different backend sets its own. */ apiKeyHeader?: string; /** Optional Bearer token for authentication (e.g., when behind a proxy or API gateway) */ authToken?: string; headers?: Record; /** Enable debug logging to the console */ debug?: boolean; /** Suppress browser security warnings in the console */ suppressBrowserWarning?: boolean; timeoutMs?: number; /** * Retry policy for transient errors. Default: no retries. */ retry?: RetryPolicy; /** * Optional caller-supplied AbortSignal. Composes with the internal timeout — * whichever fires first wins. Lets callers cancel in-flight requests * (e.g. on component unmount or when superseding a stale solve). */ signal?: AbortSignal; /** * Machine-readable error codes this backend tags onto its error bodies, mapped * to our {@link ErrorCodes}. A code here outranks the status-based mapping. * Core knows no backend's codes — the client supplies its own table. */ serverErrorCodes?: ServerErrorCodeMap; onServerTiming?: (timing: ServerTiming, requestId: string) => void; } interface ServerTiming { decode?: number; solve?: number; encode?: number; raw: string; } //#endregion //#region src/core/compute-fetch/compute-fetch.d.ts /** * Generic Rhino Compute fetch function. * Sends a POST request to any Compute endpoint with pre-prepared arguments. * * Use this for advanced, low-level control over compute requests. For most use cases, prefer higher-level APIs. * * The transport is response-type-agnostic: it does not know which response a * given endpoint returns. Callers supply the response type via `R` (defaulting * to `unknown`, which forces an explicit narrowing before use). * * Timeout semantics: `config.timeoutMs` is a PER-ATTEMPT timeout, re-armed for * every retry. With `retry: { attempts: N }` the worst-case wall clock is * `(N + 1) × timeoutMs` plus backoff sleeps (and a server `Retry-After` can * stretch a single sleep up to 60s). For a hard overall deadline, pass * `config.signal` (e.g. `AbortSignal.timeout(totalMs)`) — a caller abort wins * immediately, including during backoff. * * Retry caveats: requests are POSTs, so a retry after a mid-flight connection * loss may re-execute a request the server already ran (see {@link RetryPolicy}). * A 2xx response that declares a non-JSON `Content-Type` (captive portal, * proxy login page) fails immediately with `INVALID_RESPONSE` and is never * retried; a body that fails to parse under a JSON content-type is treated as * a truncated stream and is retried. * * @typeParam R - The expected response shape. The caller names it at the call site. * @param endpoint - The Compute API endpoint (e.g., 'grasshopper', 'io', 'mesh'). * @param args - Pre-prepared arguments for the request body. * @param config - Compute configuration (server URL, API key, timeout, debug, retry, signal). * @returns The parsed JSON response from the server, typed as `R`. * * @example * // Basic usage for the Grasshopper endpoint: * const response = await fetchCompute( * 'grasshopper', * { ... }, * { * serverUrl: 'https://my-server.com', * debug: true, * timeoutMs: 30_000, * retry: { attempts: 2 }, * signal: controller.signal, * } * ); */ declare function fetchCompute(endpoint: string, args: Record, config: ComputeConfig): Promise; //#endregion //#region src/core/compute-fetch/wire-size.d.ts /** * Side-channel carrying a response's wire size (its JSON text length) alongside * the parsed object, so downstream caches can budget by bytes without * re-serializing (audit C2/C3 — the response tree can be hundreds of MB, and * every extra `JSON.stringify` pass over it is a real cost). * * A `WeakMap` rather than a property on the response: the response type is the * server's schema, and an extra enumerable field would leak into every * `JSON.stringify(response)` on the way back out to clients. Derived copies * (e.g. the `algo`-stripped shallow copy in `runSolve`) must re-register — the * hint follows object identity, not content. * * The size is `text.length` (UTF-16 code units), not strict UTF-8 bytes — * compute responses are ASCII-dominated JSON (base64 + numerals), so the two * are interchangeable for budgeting purposes and `.length` is free. */ /** Record `response`'s wire size. No-op for non-object/null values. */ declare function setResponseWireSize(response: unknown, size: number): void; /** The wire size recorded for `response`, or undefined when never registered. */ declare function getResponseWireSize(response: unknown): number | undefined; //#endregion //#region src/core/utils/logger.d.ts /** * Logger interface for structured logging * * @public Implement this interface to provide custom logging behavior. */ interface Logger { debug(message: string, ...args: unknown[]): void; info(message: string, ...args: unknown[]): void; warn(message: string, ...args: unknown[]): void; error(message: string, ...args: unknown[]): void; } /** * Get the current logger instance * * @returns The current logger instance */ declare function getLogger(): Logger; /** * Set a custom logger instance * * @public Use this to configure custom logging behavior. * * @param logger - Custom logger implementation or null to disable logging * @throws {ComputeError} `INVALID_CONFIG` if the logger is missing any of * the four required methods — failing here beats a confusing * "getLogger().debug is not a function" at some later, unrelated call site. * * @example * ```typescript * import { setLogger } from '@selvajs/compute/core'; * * // Enable console logging * setLogger(console); * * // Use a custom logger * setLogger({ * debug: (msg, ...args) => myLogger.debug(msg, ...args), * info: (msg, ...args) => myLogger.info(msg, ...args), * warn: (msg, ...args) => myLogger.warn(msg, ...args), * error: (msg, ...args) => myLogger.error(msg, ...args) * }); * * // Disable logging * setLogger(null); * ``` */ declare function setLogger(logger: Logger | Console | null): void; /** * Enable debug logging to console * * @public Convenience method to enable console logging. * * @example * ```typescript * import { enableDebugLogging } from '@selvajs/compute/core'; * * enableDebugLogging(); * ``` */ declare function enableDebugLogging(): void; //#endregion //#region src/core/utils/read-field.d.ts /** * Case-insensitive single-key reader for wire payloads. * * The Rhino Compute family serializes the same logical field with different * casing depending on the server branch: * * - mcneel 8.x / 9.x: the IO schema is PascalCase (`ParamType`, `Default`, * `InnerTree`, …) because those C# classes carry no `[JsonProperty]`. * - VektorNode Compute8: the IO schema is camelCase (`paramType`, `default`, * …) because the fork added `[JsonProperty("camelCase")]`, BUT the nested * `default` DataTree wrapper stays PascalCase (`ParamName` / `InnerTree`) * since `Resthopper.IO.DataTree` is an external type the fork can't attribute. * * So a single response can mix casings, and which casing a given field uses * depends on the server branch. Rather than deep-camelCasing the whole payload * (the old `camelcaseKeys` approach — which corrupted user-authored value-list * label keys and item `data` JSON), read the specific fields we care about * case-insensitively and leave everything else verbatim. * * Prefers an exact-case match when present, then falls back to the first * case-insensitive match. Returns `undefined` when no key matches. * * @param obj - The source object (any non-object input yields `undefined`). * @param name - The logical field name, in any casing. */ declare function readField(obj: unknown, name: string): T | undefined; /** * True when `obj` has a key matching `name` (case-insensitively). Distinguishes * "field present but value is null/undefined" from "field absent" — needed where * presence itself carries meaning (e.g. an `innerTree` that exists but is empty). */ declare function hasField(obj: unknown, name: string): boolean; //#endregion //#region src/core/utils/encoding.d.ts /** * Decodes a base64 string to binary data (Uint8Array). * Normalizes and validates input per WHATWG forgiving-base64 so both runtimes fail consistently. * * @param base64File - Base64 encoded string * @returns Decoded binary data as Uint8Array * @throws {ComputeError} `ENCODING_ERROR` if invalid, or `ENVIRONMENT_ERROR` if the runtime has no decoder */ declare function decodeBase64ToBinary(base64File: string): Uint8Array; //#endregion //#region src/core/definition-ref.d.ts /** * By-reference definition form for solves. * * Lets a caller that already knows a definition's identity (e.g. a stored * version's UUID) schedule solves without materializing the multi-MB bytes: * cache keys and the server-pointer map are derived from `key` alone, and * `load()` is only called when an upload is genuinely unavoidable (first solve * of a definition, or a server-side pointer miss). */ /** * A definition identified by a stable key, with bytes materialized on demand. * * **Immutability contract — read this before constructing one.** `key` must * identify IMMUTABLE bytes: every `load()` for a given `key` must return the * same content, forever. All caching (the scheduler's result cache, the * server-pointer map, and any durable cache built on these keys) trusts the * key as the definition's identity WITHOUT looking at the bytes. If two * different byte contents ever share a key, cached solves from one are served * for the other — silent cache poisoning with no diagnostic. Use an identity * that can never be reused for different content (e.g. a version UUID), never * a mutable name or path. */ interface DefinitionRef { /** * Identity of immutable bytes (e.g. a version UUID). Two different byte * contents must never share a key — cache poisoning otherwise. */ key: string; /** * Materialize the bytes. Called ONLY when an upload is unavoidable — inside * the solve execution, so it counts toward the solve's abort semantics. */ load: () => Promise; } /** * Every definition form accepted by the solve entry points: * - a URL, base64 string, or plain string (content-hashed for caching) * - raw `.gh` bytes (content-hashed) * - a {@link DefinitionRef} (identity-keyed; bytes loaded lazily) */ type SolveDefinition = string | Uint8Array | DefinitionRef; /** Narrow a {@link SolveDefinition} to the by-reference form. */ declare function isDefinitionRef(definition: SolveDefinition): definition is DefinitionRef; //#endregion //#region src/core/server/validate-server-url.d.ts /** * The public McNeel endpoint's host — the default blocked host; users must point at * their own server. Compared against the parsed hostname lowercased and with any * trailing dot stripped, so the FQDN form (`compute.rhino3d.com.`) can't bypass it. * Known limitation: the endpoint's raw IP is not blocked — it sits behind a load * balancer with no single stable, verifiable address to pin. */ declare const DEFAULT_BLOCKED_HOST = "compute.rhino3d.com"; interface ValidateServerUrlOptions { /** * Hostnames rejected as a `serverUrl` — a backend's shared public endpoint, * which callers must not point at. Defaults to `[DEFAULT_BLOCKED_HOST]`; pass * `[]` to block nothing. Compared lowercased with any trailing dot stripped. */ blockedHosts?: readonly string[]; } /** * Validate and normalize a compute `serverUrl`. * * This is the single source of truth for "is this a usable server URL?" — both * `GrasshopperClient` (via `normalizeComputeConfig`) and the standalone-exported * `ComputeServerStats` constructor delegate here, so a given URL is accepted or * rejected identically no matter which entry point a caller uses. * * Rules (all enforced, on the *trimmed* input — the trimmed form is what's * returned, so no stray whitespace survives into later `fetch` calls): * - non-empty (after trim) * - `http://` or `https://` scheme (case-insensitive, per RFC 3986) * - parseable by `new URL()` * - no embedded credentials (`http://user:pass@host`) — `fetch`/`new Request` * reject credentialed URLs at runtime, so they must fail here instead * - no query string or fragment — endpoint paths are appended to this URL * (`${serverUrl}/version`), which a `?…` or `#…` suffix would corrupt * - not a blocked host (by default the public McNeel endpoint) — compared by * parsed hostname (lowercased, trailing dot stripped), so scheme, casing, port, * path, trailing-slash, or FQDN-dot variants can't slip past the block * * @param raw - The candidate server URL. * @param options - Override the blocked-host list for a non-Rhino backend. * @returns The trimmed, normalized URL with any trailing slashes removed. * @throws {ComputeError} `INVALID_CONFIG` if any rule fails. */ declare function validateServerUrl(raw: string, options?: ValidateServerUrlOptions): string; //#endregion //#region src/core/server/classify-probe-failure.d.ts /** * Why a liveness probe failed, and whether waiting can change the answer. * * `retryable` is the whole point: a powered-off VM and a booting one both read * as "offline" from a single probe, but only one of them will ever come up. A * caller that can't tell them apart has to assume the optimistic case and burn * its full retry window on a machine that is simply off. */ type ProbeVerdict = /** Nothing is listening on the port — the host answered, and said no. */ 'refused' | /** The hostname does not resolve. */ 'dns' | /** No answer within the timeout: a booting host swallows packets rather than refusing them. */ 'timeout' | /** The server answered, but rejected the probe's credentials (401/403). */ 'unauthorized' | /** The server answered with a non-2xx that isn't an auth rejection. */ 'http_error' | /** Connection failed in a way we can't attribute. */ 'unknown'; interface ProbeFailure { verdict: ProbeVerdict; /** Whether retrying the same probe could plausibly succeed later. */ retryable: boolean; /** Operator-facing sentence. Never includes the API key. */ summary: string; } /** * Classify a {@link ComputeServerStats.probeServer} result. * * A DNS failure is treated as retryable even though a missing record won't fix * itself: `EAI_AGAIN` is a *timeout* talking to the resolver, and the two are * not distinguishable from the error alone. Retrying a genuinely-wrong hostname * costs one window; giving up on a resolver hiccup breaks a server that is fine. * * @param probe - The `{ online, status?, error? }` a probe returned. An `online` * probe is not a failure and yields `null`. */ declare function classifyProbeFailure(probe: { online: boolean; status?: number; error?: string; }): ProbeFailure | null; //#endregion //#region src/core/files/types.d.ts /** * Raw file data from Grasshopper/Rhino Compute response, with metadata for processing. * Files are typically combined with additional files and packaged into a ZIP archive. * @see {@link extractFilesFromComputeResponse} for extraction from compute responses */ type FileData = { /** Base filename without extension (e.g., "model") */ fileName: string; /** File content, base64-encoded or plain string depending on isBase64Encoded flag */ data: string; /** File extension including the dot (e.g., ".3dm", ".json"). Appended to fileName to create the full filename */ fileType: string; /** Whether data is base64-encoded. If true, must be decoded to binary before use */ isBase64Encoded: boolean; /** Directory path for archive organization (e.g., "subfolder/nested"). Empty string for root-level files */ subFolder: string; /** Arbitrary metadata attached in Grasshopper. Not interpreted by compute; passed through for downstream consumers. May be absent on older payloads */ metadata?: Record; }; /** * Normalized file ready for consumption or archival. * Unified intermediate format from FileData or FileBaseInfo, ready to be packaged into archives or returned to callers. */ type ProcessedFile = { /** Full filename including extension (e.g., "model.3dm") */ fileName: string; /** File content as binary data (Uint8Array for decoded base64 or fetched binary) or text */ content: Uint8Array | string; /** File path for archive organization (e.g., "subfolder/model.3dm") */ path: string; /** * The sanitized `subFolder` this file came from, separately from `path`. * * `path` fuses folder and name for the archive, and a consumer that stores files * itself (rather than zipping them) otherwise has to re-split it — which is * ambiguous once a duplicate path has been renamed. `''` means archive root; * absent means the producer did not record one (hand-built `ProcessedFile`s). */ subFolder?: string; /** * Grasshopper-authored metadata carried through from {@link FileData}. Absent when * the source item had none, or for files fetched via {@link FileBaseInfo} (an * external URL has no GH metadata). */ metadata?: Record; }; /** * Reference to an external file to be fetched and included in file operations. * Specifies additional files (beyond compute response files) to fetch and process as ProcessedFile. * @see {@link fetchRemoteFiles} for how FileBaseInfo is fetched and converted */ type FileBaseInfo = { /** Destination filename for the file in the archive or result set (e.g., "additional-data.json") */ fileName: string; /** URL to fetch the file from. Must be accessible from the runtime environment */ filePath: string; /** Optional directory path for archive organization (e.g., "extras/docs"). When omitted, file lands at archive root */ subFolder?: string; }; //#endregion //#region src/core/files/handle-files.d.ts /** * Extracts and processes files from compute response data without downloading * them. Never throws: undecodable/unnamed items and failed external fetches are * logged and dropped per-file (see {@link fetchRemoteFiles}). */ declare const extractFilesFromComputeResponse: (downloadableFiles: FileData[], additionalFiles?: FileBaseInfo[] | FileBaseInfo | null) => Promise; /** Downloads files from a compute response as a ZIP archive. */ declare const downloadFileData: (downloadableFiles: FileData[], fileFoldername: string, additionalFiles?: FileBaseInfo[] | FileBaseInfo | null) => Promise; /** * Download files as one archive per `Sub Folder` root. * * `ROOT::Panels` and `OTHERROOT::Panels` produce `ROOT.zip` and `OTHERROOT.zip`, each containing * `Panels/…` — the root names the archive instead of nesting inside it. Files with no root fall * back to `fallbackName`, so a definition that never sets `Sub Folder` downloads exactly as before. * * Archives are saved one at a time: browsers discard concurrent downloads issued in the same tick, * and these are user-initiated saves rather than a throughput-bound batch. Note that saving more * than one file per gesture may prompt for permission. * * @param downloadableFiles - `FileData` items from the compute response. * @param fallbackName - Archive name for files with no `Sub Folder` root. * @param additionalFiles - Extra files to package; they carry no root and join the fallback archive. */ declare const downloadFileDataByRoot: (downloadableFiles: FileData[], fallbackName: string, additionalFiles?: FileBaseInfo[] | FileBaseInfo | null) => Promise; //#endregion //#region src/core/files/sub-folder.d.ts /** * The `Sub Folder` convention, as authored on Selva's Grasshopper file components. * * `::` nests, matching Rhino's layer separator (`ROOT::Panels`), and `/` and `\` are accepted * because people type them out of habit. The plugin normalizes to `/` before sending, so these * helpers also cover payloads from an older plugin that still emit `::`. * * The first segment is the **root**, which names the archive rather than becoming a folder inside * it: `ROOT::Panels` downloads as `ROOT.zip` containing `Panels/…`. Files sharing a root travel * together; distinct roots produce separate archives. */ /** * Split a `Sub Folder` value into folder segments; `/`, `\` and `::` all separate. * * Exported because anything rendering a folder tree has to agree with the archive on where the * boundaries are — splitting on `/` alone leaves `Main::Panels` as one literal segment and shows * a folder named after the separator. */ declare const subFolderSegments: (subFolder: string | undefined) => string[]; /** * Group files by their `Sub Folder` root, preserving encounter order. * * Rootless files group under `''` — a caller naming archives supplies its own fallback for that * bucket. Useful beyond downloading: a consumer writing to disk gets the same grouping without * touching the DOM. */ declare const groupFilesByRoot: >(files: readonly T[]) => Array<{ root: string; files: T[]; }>; //#endregion export { ServerErrorCodeMap as A, getLogger as C, fetchCompute as D, setResponseWireSize as E, ComputeError as M, ErrorCode as N, ComputeConfig as O, ErrorCodes as P, enableDebugLogging as S, getResponseWireSize as T, isDefinitionRef as _, extractFilesFromComputeResponse as a, readField as b, ProcessedFile as c, classifyProbeFailure as d, DEFAULT_BLOCKED_HOST as f, SolveDefinition as g, DefinitionRef as h, downloadFileDataByRoot as i, ServerTiming as j, RetryPolicy as k, ProbeFailure as l, validateServerUrl as m, subFolderSegments as n, FileBaseInfo as o, ValidateServerUrlOptions as p, downloadFileData as r, FileData as s, groupFilesByRoot as t, ProbeVerdict as u, decodeBase64ToBinary as v, setLogger as w, Logger as x, hasField as y }; //# sourceMappingURL=index-zlzEAi12.d.ts.map