@selvajs/compute 3.1.0-beta.3 → 3.1.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-33753HSV.cjs +2 -0
- package/dist/{chunk-JIE3W4KP.cjs.map → chunk-33753HSV.cjs.map} +1 -1
- package/dist/chunk-4JNRO7TX.cjs +62 -0
- package/dist/chunk-4JNRO7TX.cjs.map +1 -0
- package/dist/chunk-6V6SUB4V.js +62 -0
- package/dist/chunk-6V6SUB4V.js.map +1 -0
- package/dist/chunk-D7A3YIYD.cjs +4 -0
- package/dist/chunk-D7A3YIYD.cjs.map +1 -0
- package/dist/chunk-EMXDP7KY.js +4 -0
- package/dist/chunk-EMXDP7KY.js.map +1 -0
- package/dist/chunk-MDFVHHH6.js +2 -0
- package/dist/chunk-MDFVHHH6.js.map +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.d.cts +2 -2
- package/dist/grasshopper.d.ts +2 -2
- package/dist/grasshopper.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/{types-B-JygDUF.d.ts → types-BBSF_ISX.d.ts} +32 -3
- package/dist/{types-DGeAQnkB.d.cts → types-DxPi5SEx.d.cts} +32 -3
- package/dist/visualization-3XYZHAIV.js +2 -0
- package/dist/visualization-DEAMRV7R.cjs +2 -0
- package/dist/visualization-DEAMRV7R.cjs.map +1 -0
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.d.cts +44 -7
- package/dist/visualization.d.ts +44 -7
- package/dist/visualization.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-CTZ4ZOSM.js +0 -2
- package/dist/chunk-CTZ4ZOSM.js.map +0 -1
- package/dist/chunk-EUMIGWRX.cjs +0 -4
- package/dist/chunk-EUMIGWRX.cjs.map +0 -1
- package/dist/chunk-HNG75VAI.js +0 -55
- package/dist/chunk-HNG75VAI.js.map +0 -1
- package/dist/chunk-JIE3W4KP.cjs +0 -2
- package/dist/chunk-L3CNT26S.cjs +0 -55
- package/dist/chunk-L3CNT26S.cjs.map +0 -1
- package/dist/chunk-QAOHGIFT.js +0 -4
- package/dist/chunk-QAOHGIFT.js.map +0 -1
- package/dist/visualization-SI2GEY4M.cjs +0 -2
- package/dist/visualization-SI2GEY4M.cjs.map +0 -1
- package/dist/visualization-UJZN4PJD.js +0 -2
- /package/dist/{visualization-UJZN4PJD.js.map → visualization-3XYZHAIV.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/errors.ts","../src/core/utils/logger.ts","../src/core/utils/encoding.ts","../src/core/compute-fetch/compute-fetch.ts","../src/core/server/validate-server-url.ts","../src/core/server/compute-server-stats.ts","../src/core/utils/camel-case.ts","../src/core/files/handle-files.ts"],"sourcesContent":["/**\n * Error types and codes for `@selvajs/compute`.\n */\n\nexport const ErrorCodes = {\n\tNETWORK_ERROR: 'NETWORK_ERROR',\n\tAUTH_ERROR: 'AUTH_ERROR',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tCOMPUTATION_ERROR: 'COMPUTATION_ERROR',\n\tTIMEOUT_ERROR: 'TIMEOUT_ERROR',\n\tCORS_ERROR: 'CORS_ERROR',\n\tUNKNOWN_ERROR: 'UNKNOWN_ERROR',\n\tINVALID_STATE: 'INVALID_STATE',\n\tINVALID_INPUT: 'INVALID_INPUT',\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\tBROWSER_ONLY: 'BROWSER_ONLY',\n\tENVIRONMENT_ERROR: 'ENVIRONMENT_ERROR',\n\tENCODING_ERROR: 'ENCODING_ERROR',\n\t/** An input's `default` had a shape the normalizer didn't recognize (no innerTree key). */\n\tMALFORMED_DEFAULT: 'MALFORMED_DEFAULT',\n\t/** Scheduler latest-wins: this call was replaced by a newer one. */\n\tSUPERSEDED: 'SUPERSEDED',\n\t/** Scheduler / caller-supplied AbortSignal: this call was aborted. */\n\tABORTED: 'ABORTED',\n\t/**\n\t * A solve referenced a definition by `pointer` (server-side cache key), but the\n\t * server no longer holds that definition (evicted / GC'd / a different child in\n\t * the pool / server restarted). The caller should retry with the full\n\t * definition. Surfaced when the server tags its error body with\n\t * `code: \"definition_not_cached\"`, so it survives production message-scrubbing.\n\t */\n\tDEFINITION_NOT_CACHED: 'DEFINITION_NOT_CACHED'\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/**\n * Simplified error for Rhino Compute operations\n *\n * @public Use this for error handling with error codes and context.\n */\nexport class RhinoComputeError extends Error {\n\tpublic readonly code: ErrorCode;\n\tpublic readonly statusCode?: number;\n\tpublic readonly context?: Record<string, unknown>;\n\tpublic readonly originalError?: Error;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: ErrorCode = ErrorCodes.UNKNOWN_ERROR,\n\t\toptions?: { statusCode?: number; context?: Record<string, unknown>; originalError?: Error }\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'RhinoComputeError';\n\t\tthis.code = code;\n\t\tthis.statusCode = options?.statusCode;\n\t\tthis.context = options?.context;\n\t\tthis.originalError = options?.originalError;\n\t\tif (options?.originalError) {\n\t\t\t(this as { cause?: unknown }).cause = options.originalError;\n\t\t}\n\t}\n\n\t// ============================================================================\n\t// Static Validation Error Helpers\n\t// ============================================================================\n\n\t/**\n\t * Create an error for missing/empty values\n\t */\n\tstatic missingValues(\n\t\tinputName: string,\n\t\texpectedType?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(\n\t\t\t`Input \"${inputName}\" has no values defined${expectedType ? ` (expected ${expectedType})` : ''}`,\n\t\t\tErrorCodes.INVALID_INPUT,\n\t\t\t{ context: { inputName, expectedType, ...context } }\n\t\t);\n\t}\n\n\t/**\n\t * Create an error for unknown parameter type\n\t */\n\tstatic unknownParamType(\n\t\tparamType: string,\n\t\tparamName?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(`Unknown paramType: ${paramType}`, ErrorCodes.VALIDATION_ERROR, {\n\t\t\tcontext: { receivedParamType: paramType, paramName, ...context }\n\t\t});\n\t}\n}\n","import { RhinoComputeError, ErrorCodes } from '../errors';\n\n/**\n * Logger interface for structured logging\n *\n * @public Implement this interface to provide custom logging behavior.\n */\nexport interface Logger {\n\tdebug(message: string, ...args: unknown[]): void;\n\tinfo(message: string, ...args: unknown[]): void;\n\twarn(message: string, ...args: unknown[]): void;\n\terror(message: string, ...args: unknown[]): void;\n}\n\n/**\n * No-op logger implementation (default)\n * @internal\n */\nclass NoOpLogger implements Logger {\n\tdebug(): void {}\n\tinfo(): void {}\n\twarn(): void {}\n\terror(): void {}\n}\n\n/**\n * Console logger implementation\n * @internal\n */\nclass ConsoleLogger implements Logger {\n\tdebug(message: string, ...args: unknown[]): void {\n\t\tconsole.debug(message, ...args);\n\t}\n\n\tinfo(message: string, ...args: unknown[]): void {\n\t\tconsole.info(message, ...args);\n\t}\n\n\twarn(message: string, ...args: unknown[]): void {\n\t\tconsole.warn(message, ...args);\n\t}\n\n\terror(message: string, ...args: unknown[]): void {\n\t\tconsole.error(message, ...args);\n\t}\n}\n\n/**\n * Internal logger instance\n * @internal\n */\nlet internalLogger: Logger = new NoOpLogger();\n\n/**\n * Get the current logger instance\n *\n * @returns The current logger instance\n */\nexport function getLogger(): Logger {\n\treturn internalLogger;\n}\n\n/**\n * Set a custom logger instance\n *\n * @public Use this to configure custom logging behavior.\n *\n * @param logger - Custom logger implementation or null to disable logging\n * @throws {RhinoComputeError} `INVALID_CONFIG` if the logger is missing any of\n * the four required methods — failing here beats a confusing\n * \"getLogger().debug is not a function\" at some later, unrelated call site.\n *\n * @example\n * ```typescript\n * import { setLogger } from '@selvajs/compute';\n *\n * // Enable console logging\n * setLogger(console);\n *\n * // Use a custom logger\n * setLogger({\n * debug: (msg, ...args) => myLogger.debug(msg, ...args),\n * info: (msg, ...args) => myLogger.info(msg, ...args),\n * warn: (msg, ...args) => myLogger.warn(msg, ...args),\n * error: (msg, ...args) => myLogger.error(msg, ...args)\n * });\n *\n * // Disable logging\n * setLogger(null);\n * ```\n */\nexport function setLogger(logger: Logger | Console | null): void {\n\tif (logger === null) {\n\t\tinternalLogger = new NoOpLogger();\n\t\treturn;\n\t}\n\n\tconst missing = (['debug', 'info', 'warn', 'error'] as const).filter(\n\t\t(method) => typeof (logger as unknown as Record<string, unknown>)[method] !== 'function'\n\t);\n\tif (missing.length > 0) {\n\t\tthrow new RhinoComputeError(\n\t\t\t`Logger is missing required method(s): ${missing.join(', ')}. A logger must implement debug, info, warn and error.`,\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{ context: { missingMethods: missing } }\n\t\t);\n\t}\n\n\tinternalLogger = logger as Logger;\n}\n\n/**\n * Enable debug logging to console\n *\n * @public Convenience method to enable console logging.\n *\n * @example\n * ```typescript\n * import { enableDebugLogging } from '@selvajs/compute';\n *\n * enableDebugLogging();\n * ```\n */\nexport function enableDebugLogging(): void {\n\tsetLogger(new ConsoleLogger());\n}\n","import { RhinoComputeError, ErrorCodes } from '../errors';\n\n/** Node's `Buffer` when present (faster path), else `undefined` in browsers/workers. */\nfunction getNodeBuffer(): typeof Buffer | undefined {\n\tconst buf = (globalThis as { Buffer?: typeof Buffer }).Buffer;\n\treturn typeof buf === 'function' ? buf : undefined;\n}\n\n/**\n * Encodes a string to base64 (Node 20+ safe)\n *\n * @internal Internal encoding helper — kept internal to `@selvajs/compute`.\n *\n * @param str - String to encode\n * @returns Base64 encoded string\n */\nexport function encodeStringToBase64(str: string): string {\n\tconst Buffer = getNodeBuffer();\n\tif (Buffer) {\n\t\treturn Buffer.from(str, 'utf-8').toString('base64');\n\t}\n\t// Browser/worker fallback: UTF-8 encode, then reuse the byte-array encoder.\n\treturn base64ByteArray(new TextEncoder().encode(str));\n}\n\n/**\n * Checks if a string is valid base64\n *\n * @internal Internal encoding helper — kept internal to `@selvajs/compute`.\n *\n * @param str - String to check\n * @returns True if the string is valid base64\n */\nexport function isBase64(str: string): boolean {\n\tif (!str || str.length < 2) return false;\n\t// Length must be a multiple of 4, only alphabet chars + at most 2 trailing '='\n\tif (str.length % 4 !== 0) return false;\n\treturn /^[A-Za-z0-9+/]+={0,2}$/.test(str);\n}\n\n/**\n * Decodes a base64 string to binary data (Uint8Array)\n *\n * @internal Internal encoding helper — kept internal to `@selvajs/compute`.\n *\n * Input is normalized and validated per WHATWG forgiving-base64 (whitespace\n * stripped, padding checked) BEFORE decoding, so both runtimes fail the same\n * way: without this, Node's `Buffer.from(x, 'base64')` silently decodes\n * malformed input into garbage while browser `atob` throws a bare\n * `InvalidCharacterError` DOMException.\n *\n * @param base64File - Base64 encoded string\n * @returns Decoded binary data as Uint8Array\n * @throws {RhinoComputeError} `ENCODING_ERROR` if the input is not valid\n * base64, or `INVALID_STATE` if no decoder exists in this environment.\n */\nexport function decodeBase64ToBinary(base64File: string): Uint8Array {\n\t// Forgiving-base64 normalization: strip ASCII whitespace (wrapped /\n\t// pretty-printed payloads), then drop trailing padding only where the spec\n\t// allows it (total length a multiple of 4).\n\tlet data = base64File.replace(/[\\t\\n\\f\\r ]/g, '');\n\tif (data.length % 4 === 0) data = data.replace(/={1,2}$/, '');\n\tif (data.length % 4 === 1 || !/^[A-Za-z0-9+/]*$/.test(data)) {\n\t\tthrow new RhinoComputeError('Invalid base64 input.', ErrorCodes.ENCODING_ERROR, {\n\t\t\tcontext: { inputLength: base64File.length }\n\t\t});\n\t}\n\n\t// Prefer Buffer in Node — it's faster and avoids the latin-1 string detour\n\t// that atob + charCodeAt requires.\n\tconst Buffer = getNodeBuffer();\n\tif (Buffer) {\n\t\tconst buf = Buffer.from(data, 'base64');\n\t\treturn new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n\t}\n\tif (typeof globalThis.atob === 'function') {\n\t\tconst binary = globalThis.atob(data);\n\t\tconst bytes = new Uint8Array(binary.length);\n\t\tfor (let i = 0; i < binary.length; i++) {\n\t\t\tbytes[i] = binary.charCodeAt(i) & 0xff;\n\t\t}\n\t\treturn bytes;\n\t}\n\n\tthrow new RhinoComputeError(\n\t\t'Base64 decoding not supported in this environment.',\n\t\tErrorCodes.INVALID_STATE,\n\t\t{ context: { environmentInfo: 'atob or Buffer not available' } }\n\t);\n}\n\n/**\n * UTF-8 byte length of a string (what actually goes over the wire), without\n * allocating an encoded copy — `TextEncoder.encode` on a multi-MB request body\n * would double its memory just to measure it.\n *\n * @internal Internal encoding helper — kept internal to `@selvajs/compute`.\n */\nexport function utf8ByteLength(str: string): number {\n\tconst Buffer = getNodeBuffer();\n\tif (Buffer) {\n\t\treturn Buffer.byteLength(str, 'utf-8');\n\t}\n\tlet bytes = 0;\n\tfor (let i = 0; i < str.length; i++) {\n\t\tconst code = str.charCodeAt(i);\n\t\tif (code < 0x80) {\n\t\t\tbytes += 1;\n\t\t} else if (code < 0x800) {\n\t\t\tbytes += 2;\n\t\t} else if (\n\t\t\tcode >= 0xd800 &&\n\t\t\tcode <= 0xdbff &&\n\t\t\ti + 1 < str.length &&\n\t\t\t(str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n\t\t) {\n\t\t\t// Surrogate pair → one 4-byte code point; lone surrogates fall through\n\t\t\t// to 3 bytes (the replacement-character encoding TextEncoder emits).\n\t\t\tbytes += 4;\n\t\t\ti++;\n\t\t} else {\n\t\t\tbytes += 3;\n\t\t}\n\t}\n\treturn bytes;\n}\n\n/**\n * Encodes binary data (Uint8Array) to base64 string.\n *\n * @internal Internal encoding helper — kept internal to `@selvajs/compute`.\n *\n * Uses Node's `Buffer` when available (faster, single allocation) and falls\n * back to `btoa` over a latin-1 string in browsers/workers.\n */\nexport function base64ByteArray(bytes: Uint8Array): string {\n\tconst Buffer = getNodeBuffer();\n\tif (Buffer) {\n\t\treturn Buffer.from(bytes).toString('base64');\n\t}\n\tif (typeof globalThis.btoa === 'function') {\n\t\t// Build a latin-1 string in chunks to avoid blowing the call stack on\n\t\t// large inputs (a single fromCharCode(...verylargearray) can exceed it).\n\t\tconst CHUNK = 0x8000;\n\t\tlet s = '';\n\t\tfor (let i = 0; i < bytes.length; i += CHUNK) {\n\t\t\t// A Uint8Array subarray is array-like, so pass it straight to\n\t\t\t// fromCharCode.apply — no need to copy it into a plain Array first.\n\t\t\ts += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK) as unknown as number[]);\n\t\t}\n\t\treturn globalThis.btoa(s);\n\t}\n\tthrow new RhinoComputeError(\n\t\t'Base64 encoding not supported in this environment.',\n\t\tErrorCodes.INVALID_STATE,\n\t\t{ context: { environmentInfo: 'btoa or Buffer not available' } }\n\t);\n}\n","import { RhinoComputeError, ErrorCodes, type ErrorCode } from '../errors';\nimport { getLogger } from '../utils/logger';\nimport { utf8ByteLength } from '../utils/encoding';\n\nimport type { ComputeConfig, RetryPolicy, ServerTiming } from '../types';\n\n// ============================================================================\n// Server-Timing\n// ============================================================================\n\n/**\n * Parse a `Server-Timing` header value into typed durations (ms).\n *\n * Header grammar (RFC 9110 §10.1.10), as emitted by the solve endpoint:\n * `decode;dur=3, solve;dur=120, encode;dur=8`\n *\n * Returns null when the header is absent or carries no recognizable metric, so\n * the caller can skip the callback entirely.\n *\n * @internal exported for tests\n */\nexport function parseServerTiming(headerValue: string | null): ServerTiming | null {\n\tif (!headerValue) return null;\n\tconst timing: ServerTiming = { raw: headerValue };\n\tlet sawMetric = false;\n\tfor (const part of headerValue.split(',')) {\n\t\tconst [name, ...params] = part.trim().split(';');\n\t\tconst durParam = params.find((p) => p.trim().toLowerCase().startsWith('dur'));\n\t\tif (!durParam) continue;\n\t\tconst dur = Number(durParam.split('=')[1]);\n\t\tif (!Number.isFinite(dur)) continue;\n\t\tconst key = name.trim().toLowerCase();\n\t\tif (key === 'decode' || key === 'solve' || key === 'encode') {\n\t\t\ttiming[key] = dur;\n\t\t\tsawMetric = true;\n\t\t}\n\t}\n\treturn sawMetric ? timing : null;\n}\n\n// ============================================================================\n// Retry Policy\n// ============================================================================\n\nconst DEFAULT_RETRY: Required<RetryPolicy> = {\n\tattempts: 0,\n\tbaseDelayMs: 500,\n\tmaxDelayMs: 30_000,\n\tretryOn429: true\n};\n\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\nfunction resolveRetryPolicy(policy: RetryPolicy | undefined): Required<RetryPolicy> {\n\tif (!policy) return DEFAULT_RETRY;\n\treturn {\n\t\tattempts: policy.attempts ?? DEFAULT_RETRY.attempts,\n\t\tbaseDelayMs: policy.baseDelayMs ?? DEFAULT_RETRY.baseDelayMs,\n\t\tmaxDelayMs: policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs,\n\t\tretryOn429: policy.retryOn429 ?? DEFAULT_RETRY.retryOn429\n\t};\n}\n\n/**\n * Parse a Retry-After header value (seconds-int or HTTP-date) into ms.\n * Returns null if the header is missing or unparseable.\n */\nfunction parseRetryAfter(headerValue: string | null): number | null {\n\tif (!headerValue) return null;\n\tconst seconds = Number(headerValue);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n\tconst dateMs = Date.parse(headerValue);\n\tif (Number.isFinite(dateMs)) {\n\t\tconst delta = dateMs - Date.now();\n\t\treturn delta > 0 ? delta : 0;\n\t}\n\treturn null;\n}\n\nfunction backoffDelay(attempt: number, policy: Required<RetryPolicy>): number {\n\tconst exponential = policy.baseDelayMs * Math.pow(2, attempt);\n\tconst jitter = Math.random() * policy.baseDelayMs;\n\treturn Math.min(exponential + jitter, policy.maxDelayMs);\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t\treturn;\n\t\t}\n\t\tconst id = setTimeout(() => {\n\t\t\tsignal?.removeEventListener('abort', onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(id);\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t};\n\t\tsignal?.addEventListener('abort', onAbort, { once: true });\n\t});\n}\n\n// ============================================================================\n// Error Handling\n// ============================================================================\n\nfunction throwHttpError(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\terrorBody: string,\n\tserverCode?: string\n): never {\n\tconst { status, statusText } = response;\n\n\tconst responseHeaders: Record<string, string> = {};\n\tresponse.headers.forEach((value, key) => {\n\t\tresponseHeaders[key] = value;\n\t});\n\n\tconst trimmed = errorBody.trim();\n\tconst bodyHint = trimmed ? ` — ${trimmed.slice(0, 200)}${trimmed.length > 200 ? '…' : ''}` : '';\n\n\tconst context = {\n\t\turl: fullUrl,\n\t\trequestId,\n\t\tmethod: 'POST',\n\t\trequestSize,\n\t\tserverUrl,\n\t\tresponseBody: errorBody || undefined,\n\t\tresponseHeaders\n\t};\n\n\tconst errorMap: Record<number, { message: string; code: ErrorCode }> = {\n\t\t401: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t403: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t404: { message: `Endpoint not found: ${fullUrl}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t413: {\n\t\t\tmessage: `Request too large: ${(requestSize / 1024).toFixed(2)}KB`,\n\t\t\tcode: ErrorCodes.VALIDATION_ERROR\n\t\t},\n\t\t429: { message: `Rate limit exceeded${bodyHint}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t500: { message: `Server error: ${statusText}${bodyHint}`, code: ErrorCodes.COMPUTATION_ERROR },\n\t\t502: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t503: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t504: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t}\n\t};\n\n\tconst error = errorMap[status] || {\n\t\tmessage: `HTTP ${status}: ${statusText}${bodyHint}`,\n\t\tcode: ErrorCodes.UNKNOWN_ERROR\n\t};\n\n\t// A machine code in the server's error body (e.g. \"definition_not_cached\")\n\t// outranks the status-based mapping: it's stable across the server's\n\t// production message-scrubbing, where the human message is replaced with a\n\t// generic string. Keep the status-derived message for context.\n\tconst code = mapServerErrorCode(serverCode) ?? error.code;\n\n\tthrow new RhinoComputeError(error.message, code, { statusCode: status, context });\n}\n\n/**\n * Map a server-supplied error code (from the JSON error body's `code` field) to\n * one of our {@link ErrorCodes}. Returns `undefined` for an absent or unknown\n * code so the caller falls back to its status-based mapping.\n */\nfunction mapServerErrorCode(serverCode?: string): ErrorCode | undefined {\n\tswitch (serverCode) {\n\t\tcase 'definition_not_cached':\n\t\t\treturn ErrorCodes.DEFINITION_NOT_CACHED;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n// ============================================================================\n// Request Helpers\n// ============================================================================\n\nfunction buildUrl(endpoint: string, serverUrl: string): string {\n\tconst base = serverUrl.replace(/\\/+$/, '');\n\tconst path = endpoint.replace(/^\\/+/, '');\n\treturn `${base}/${path}`;\n}\n\nfunction isLocalhost(serverUrl: string): boolean {\n\ttry {\n\t\t// `hostname` (not `host`) strips the port; IPv6 hostnames keep their\n\t\t// brackets, so `http://[::1]:6500` yields `[::1]`.\n\t\tconst hostname = new URL(serverUrl).hostname.toLowerCase();\n\t\treturn hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]';\n\t} catch {\n\t\treturn /(localhost|127\\.0\\.0\\.1|\\[::1\\])/i.test(serverUrl);\n\t}\n}\n\n/** Server URLs already warned about missing auth — warn once per server, not per request. */\nconst warnedNoAuth = new Set<string>();\n\nfunction buildHeaders(requestId: string, config: ComputeConfig): HeadersInit {\n\tconst headers: HeadersInit = {\n\t\t// Caller headers first so the transport's own headers below OVERWRITE them —\n\t\t// a caller can never clobber the request id, content type, or auth.\n\t\t...config.headers,\n\t\t'X-Request-ID': requestId,\n\t\t'Content-Type': 'application/json',\n\t\t...(config.authToken && { Authorization: config.authToken }),\n\t\t...(config.apiKey && { RhinoComputeKey: config.apiKey })\n\t};\n\n\tif (\n\t\t!config.apiKey &&\n\t\t!config.authToken &&\n\t\t!warnedNoAuth.has(config.serverUrl) &&\n\t\t!isLocalhost(config.serverUrl)\n\t) {\n\t\twarnedNoAuth.add(config.serverUrl);\n\t\tgetLogger().warn(\n\t\t\t`⚠️ [Rhino Compute] Request [${requestId}] targets remote server (${config.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited. (warned once per server)`\n\t\t);\n\t}\n\n\treturn headers;\n}\n\nfunction generateRequestId(): string {\n\treturn `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n}\n\nfunction log(message: string, debug?: boolean): void {\n\tif (debug) getLogger().debug(message);\n}\n\n/**\n * Compose a caller-supplied AbortSignal with an optional timeout. Returns a\n * combined signal, or `undefined` if neither was given.\n *\n * Uses `AbortSignal.timeout` (not setTimeout) so the timer is not throttled\n * when the tab is hidden. Falls back to a manual timer for older runtimes.\n *\n * @internal exported for tests\n */\nexport function composeSignal(\n\tcallerSignal: AbortSignal | undefined,\n\ttimeoutMs: number | undefined\n): { signal: AbortSignal | undefined; cleanup: () => void } {\n\tconst signals: AbortSignal[] = [];\n\tlet cleanup = () => {};\n\n\tif (callerSignal) signals.push(callerSignal);\n\n\tif (timeoutMs && timeoutMs > 0) {\n\t\tif (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {\n\t\t\tsignals.push(AbortSignal.timeout(timeoutMs));\n\t\t} else {\n\t\t\t// Fallback for runtimes without AbortSignal.timeout\n\t\t\tconst ctrl = new AbortController();\n\t\t\tconst id = setTimeout(() => ctrl.abort(), timeoutMs);\n\t\t\tcleanup = () => clearTimeout(id);\n\t\t\tsignals.push(ctrl.signal);\n\t\t}\n\t}\n\n\tif (signals.length === 0) return { signal: undefined, cleanup };\n\tif (signals.length === 1) return { signal: signals[0], cleanup };\n\n\tif (typeof AbortSignal !== 'undefined' && typeof (AbortSignal as any).any === 'function') {\n\t\treturn { signal: (AbortSignal as any).any(signals) as AbortSignal, cleanup };\n\t}\n\n\t// Manual composition fallback\n\tconst ctrl = new AbortController();\n\tconst onAbort = () => ctrl.abort();\n\tfor (const s of signals) {\n\t\tif (s.aborted) {\n\t\t\tctrl.abort();\n\t\t\tbreak;\n\t\t}\n\t\ts.addEventListener('abort', onAbort, { once: true });\n\t}\n\tconst prevCleanup = cleanup;\n\tcleanup = () => {\n\t\tprevCleanup();\n\t\tfor (const s of signals) s.removeEventListener('abort', onAbort);\n\t};\n\treturn { signal: ctrl.signal, cleanup };\n}\n\n// ============================================================================\n// Response Processing\n// ============================================================================\n\nasync function handleResponse(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\tstartTime: number,\n\tdebug?: boolean,\n\tonServerTiming?: (timing: ServerTiming) => void\n): Promise<any> {\n\tconst responseTime = Math.round(performance.now() - startTime);\n\n\tif (!response.ok) {\n\t\t// Read body once and reuse\n\t\tlet errorBody = await response.text();\n\n\t\t// Enhanced logging for errors\n\t\tif (debug) {\n\t\t\tlog(\n\t\t\t\t`❌ Request [${requestId}] failed with HTTP ${response.status} in ${responseTime}ms`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t\tlog(` URL: ${fullUrl}`, true);\n\t\t\tlog(` Status: ${response.status} ${response.statusText}`, true);\n\t\t\tif (errorBody) {\n\t\t\t\tlog(\n\t\t\t\t\t` Response body: ${errorBody.substring(0, 500)}${errorBody.length > 500 ? '...' : ''}`,\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// A machine-readable code the server may tag onto its error body (e.g.\n\t\t// \"definition_not_cached\"). Unlike the human `message`, it isn't scrubbed in\n\t\t// the server's production (non-debug) mode, so it's the reliable signal for\n\t\t// classifying the error (see throwHttpError → mapServerErrorCode).\n\t\tlet serverCode: string | undefined;\n\n\t\t// The machine code (e.g. `definition_not_cached`) can ride any error status,\n\t\t// not just 500, and must outrank the status-based mapping — so read it here.\n\t\ttry {\n\t\t\tconst parsedForCode = JSON.parse(errorBody);\n\t\t\tif (typeof parsedForCode?.code === 'string') serverCode = parsedForCode.code;\n\t\t} catch {\n\t\t\t// Non-JSON body — nothing to extract.\n\t\t}\n\n\t\t// Check if it's a valid compute response with errors/warnings\n\t\tif (response.status === 500) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(errorBody);\n\t\t\t\t// If it has values, it's a partial success with errors\n\t\t\t\tif (parsed?.values && (parsed.errors || parsed.warnings)) {\n\t\t\t\t\tif (debug) {\n\t\t\t\t\t\tlog(\n\t\t\t\t\t\t\t`⚠️ Request [${requestId}] completed with Grasshopper errors in ${responseTime}ms`,\n\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (parsed.errors?.length > 0) {\n\t\t\t\t\t\t\tlog(` Errors: ${JSON.stringify(parsed.errors, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (parsed.warnings?.length > 0) {\n\t\t\t\t\t\t\tlog(` Warnings: ${JSON.stringify(parsed.warnings, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\n\t\t\t\t// Raw server-side exception. The Compute8 server's exception handler\n\t\t\t\t// (compute.geometry Startup.cs) emits:\n\t\t\t\t// { error: \"Internal Server Error\", message: \"<category>: <detail>\",\n\t\t\t\t// stackTrace?: string[] } // stackTrace only when Config.Debug\n\t\t\t\t// The actionable part is `message` — surface it, with the optional\n\t\t\t\t// stack appended for debugging. We prefer `message`/`error` (current\n\t\t\t\t// server) and keep `Message`/`ExceptionType`/`StackTrace` (old\n\t\t\t\t// PascalCase .NET shape) as a back-compat fallback so an older server\n\t\t\t\t// still produces a useful message.\n\t\t\t\tconst serverMessage =\n\t\t\t\t\t(typeof parsed?.message === 'string' && parsed.message) ||\n\t\t\t\t\t(typeof parsed?.Message === 'string' && parsed.Message) ||\n\t\t\t\t\t'';\n\t\t\t\tconst exceptionType =\n\t\t\t\t\t(typeof parsed?.ExceptionType === 'string' && parsed.ExceptionType) || '';\n\t\t\t\tconst stack = parsed?.stackTrace ?? parsed?.StackTrace;\n\t\t\t\tconst stackStr = Array.isArray(stack) ? stack.join('\\n') : stack || '';\n\n\t\t\t\tif (serverMessage) {\n\t\t\t\t\t// Don't repeat the generic \"Internal Server Error\" label when the\n\t\t\t\t\t// message already carries the real detail.\n\t\t\t\t\tconst prefix = exceptionType ? `${exceptionType}: ` : '';\n\t\t\t\t\terrorBody = `${prefix}${serverMessage}${stackStr ? `\\n${stackStr}` : ''}`;\n\t\t\t\t} else if (parsed?.error) {\n\t\t\t\t\terrorBody =\n\t\t\t\t\t\ttypeof parsed.error === 'string' ? parsed.error : JSON.stringify(parsed.error, null, 2);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tif (debug) {\n\t\t\t\t\tlog(` Failed to parse error body as JSON: ${e}`, true);\n\t\t\t\t}\n\t\t\t\t// Not valid JSON, proceed with HTTP error\n\t\t\t}\n\t\t}\n\n\t\tthrowHttpError(response, fullUrl, requestId, requestSize, serverUrl, errorBody, serverCode);\n\t}\n\n\tlog(`✅ Request [${requestId}] completed in ${responseTime}ms`, debug);\n\n\t// Surface the server's per-request timing breakdown (if it sent one and a\n\t// caller is listening). Best-effort: a throwing callback must not fail the\n\t// request, since the body parse below is the real result.\n\tif (onServerTiming) {\n\t\tconst timing = parseServerTiming(response.headers.get('Server-Timing'));\n\t\tif (timing) {\n\t\t\ttry {\n\t\t\t\tonServerTiming(timing);\n\t\t\t} catch (err) {\n\t\t\t\tif (debug) log(` onServerTiming callback threw: ${err}`, true);\n\t\t\t}\n\t\t}\n\t}\n\n\ttry {\n\t\treturn await response.json();\n\t} catch (error) {\n\t\tthrow new RhinoComputeError('Failed to parse JSON response', ErrorCodes.NETWORK_ERROR, {\n\t\t\tstatusCode: response.status,\n\t\t\tcontext: {\n\t\t\t\turl: fullUrl,\n\t\t\t\trequestId\n\t\t\t},\n\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t});\n\t}\n}\n\n// ============================================================================\n// Single attempt\n// ============================================================================\n\ninterface AttemptContext {\n\tendpoint: string;\n\tbody: string;\n\trequestSize: number;\n\tfullUrl: string;\n\trequestId: string;\n\theaders: HeadersInit;\n\tconfig: ComputeConfig;\n}\n\ninterface AttemptResult {\n\tok: true;\n\tvalue: any;\n}\n\ninterface AttemptRetry {\n\tok: false;\n\tretry: true;\n\tdelayMs: number;\n\tcause: RhinoComputeError;\n}\n\ninterface AttemptFatal {\n\tok: false;\n\tretry: false;\n\tcause: RhinoComputeError;\n}\n\nasync function attemptFetch(\n\tctx: AttemptContext,\n\tretryPolicy: Required<RetryPolicy>,\n\tattempt: number,\n\ttotalAttempts: number\n): Promise<AttemptResult | AttemptRetry | AttemptFatal> {\n\tconst { signal, cleanup } = composeSignal(ctx.config.signal, ctx.config.timeoutMs);\n\tconst startTime = performance.now();\n\n\ttry {\n\t\tconst response = await fetch(ctx.fullUrl, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: ctx.body,\n\t\t\theaders: ctx.headers,\n\t\t\tsignal\n\t\t});\n\n\t\t// 429 with Retry-After or retryable 5xx → maybe retry\n\t\tconst isRetryableStatus =\n\t\t\tRETRYABLE_STATUS.has(response.status) || (retryPolicy.retryOn429 && response.status === 429);\n\n\t\tif (isRetryableStatus && attempt < totalAttempts - 1) {\n\t\t\tconst retryAfterMs = parseRetryAfter(response.headers.get('Retry-After'));\n\t\t\t// Clamp Retry-After to maxDelayMs so a bad header can't force an\n\t\t\t// arbitrarily long sleep. backoffDelay already clamps.\n\t\t\tconst delayMs =\n\t\t\t\tretryAfterMs !== null\n\t\t\t\t\t? Math.min(retryAfterMs, retryPolicy.maxDelayMs)\n\t\t\t\t\t: backoffDelay(attempt, retryPolicy);\n\t\t\t// Drain the body so the connection can be reused on the next attempt.\n\t\t\t// On the *final* attempt we deliberately fall through — handleResponse\n\t\t\t// reads the body itself to surface the error context.\n\t\t\tawait response.text().catch(() => {});\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tretry: true,\n\t\t\t\tdelayMs,\n\t\t\t\tcause: new RhinoComputeError(\n\t\t\t\t\t`HTTP ${response.status} ${response.statusText} (will retry)`,\n\t\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t{ statusCode: response.status, context: { requestId: ctx.requestId } }\n\t\t\t\t)\n\t\t\t};\n\t\t}\n\n\t\tconst value = await handleResponse(\n\t\t\tresponse,\n\t\t\tctx.fullUrl,\n\t\t\tctx.requestId,\n\t\t\tctx.requestSize,\n\t\t\tctx.config.serverUrl,\n\t\t\tstartTime,\n\t\t\tctx.config.debug,\n\t\t\tctx.config.onServerTiming\n\t\t);\n\t\treturn { ok: true, value };\n\t} catch (error) {\n\t\t// Caller-aborted vs timeout-aborted distinction\n\t\tif (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {\n\t\t\tconst callerAborted = ctx.config.signal?.aborted === true;\n\n\t\t\tif (callerAborted) {\n\t\t\t\t// Caller cancellation is never retried — propagate immediately\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: false,\n\t\t\t\t\tcause: new RhinoComputeError('Request aborted by caller', ErrorCodes.ABORTED, {\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t},\n\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Timeout — retryable up to attempts limit\n\t\t\tconst fatal = new RhinoComputeError(\n\t\t\t\t`Request timed out after ${ctx.config.timeoutMs}ms`,\n\t\t\t\tErrorCodes.TIMEOUT_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\ttimeoutMs: ctx.config.timeoutMs,\n\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// Network error (TypeError) — retryable\n\t\tif (error instanceof TypeError) {\n\t\t\tconst fatal = new RhinoComputeError(\n\t\t\t\t`Network error: ${error.message}`,\n\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t},\n\t\t\t\t\toriginalError: error\n\t\t\t\t}\n\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// RhinoComputeError thrown from handleResponse — already has full context.\n\t\t// Retryable only if it carries a retryable status code.\n\t\tif (error instanceof RhinoComputeError) {\n\t\t\tconst status = error.statusCode;\n\t\t\t// A 2xx whose body failed to parse (NETWORK_ERROR from handleResponse)\n\t\t\t// means the stream was cut mid-body — as transient as any network error.\n\t\t\tconst isTruncatedSuccess =\n\t\t\t\terror.code === ErrorCodes.NETWORK_ERROR &&\n\t\t\t\tstatus !== undefined &&\n\t\t\t\tstatus >= 200 &&\n\t\t\t\tstatus < 300;\n\t\t\tconst retryable =\n\t\t\t\tisTruncatedSuccess ||\n\t\t\t\t(status !== undefined &&\n\t\t\t\t\t(RETRYABLE_STATUS.has(status) || (retryPolicy.retryOn429 && status === 429)));\n\t\t\tif (retryable && attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: error\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: error };\n\t\t}\n\n\t\t// Unknown — wrap and don't retry\n\t\treturn {\n\t\t\tok: false,\n\t\t\tretry: false,\n\t\t\tcause: new RhinoComputeError(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\tErrorCodes.UNKNOWN_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: { endpoint: ctx.endpoint, requestId: ctx.requestId },\n\t\t\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t}\n\t\t\t)\n\t\t};\n\t} finally {\n\t\tcleanup();\n\t}\n}\n\n// ============================================================================\n// Main Function\n// ============================================================================\n\n/**\n * Generic Rhino Compute fetch function.\n * Sends a POST request to any Compute endpoint with pre-prepared arguments.\n *\n * Use this for advanced, low-level control over compute requests. For most use cases, prefer higher-level APIs.\n *\n * The transport is response-type-agnostic: it does not know which response a\n * given endpoint returns. Callers supply the response type via `R` (defaulting\n * to `unknown`, which forces an explicit narrowing before use).\n *\n * @typeParam R - The expected response shape. The caller names it at the call site.\n * @param endpoint - The Compute API endpoint (e.g., 'grasshopper', 'io', 'mesh').\n * @param args - Pre-prepared arguments for the request body.\n * @param config - Compute configuration (server URL, API key, timeout, debug, retry, signal).\n * @returns The parsed JSON response from the server, typed as `R`.\n *\n * @example\n * // Basic usage for the Grasshopper endpoint:\n * const response = await fetchRhinoCompute(\n * 'grasshopper',\n * { ... },\n * {\n * serverUrl: 'https://my-server.com',\n * debug: true,\n * timeoutMs: 30_000,\n * retry: { attempts: 2 },\n * signal: controller.signal,\n * }\n * );\n */\nexport async function fetchRhinoCompute<R = unknown>(\n\tendpoint: string,\n\targs: Record<string, any>,\n\tconfig: ComputeConfig\n): Promise<R> {\n\tconst requestId = generateRequestId();\n\tconst body = JSON.stringify(args);\n\t// Wire size in UTF-8 bytes — `body.length` counts UTF-16 code units and\n\t// undercounts non-ASCII payloads (matters for the 413 message and size logs).\n\tconst requestSize = utf8ByteLength(body);\n\tconst fullUrl = buildUrl(endpoint, config.serverUrl);\n\tconst headers = buildHeaders(requestId, config);\n\tconst retryPolicy = resolveRetryPolicy(config.retry);\n\tconst totalAttempts = retryPolicy.attempts + 1;\n\n\tif (config.debug) {\n\t\tconst sizeKb = (requestSize / 1024).toFixed(2);\n\t\tconst emoji = requestSize > 100000 ? '⚠️' : '🚀';\n\t\tlog(`${emoji} Starting compute request [${requestId}]: ${endpoint} (${sizeKb}KB)`, true);\n\t}\n\n\tconst ctx: AttemptContext = {\n\t\tendpoint,\n\t\tbody,\n\t\trequestSize,\n\t\tfullUrl,\n\t\trequestId,\n\t\theaders,\n\t\tconfig\n\t};\n\n\tlet lastError: RhinoComputeError | null = null;\n\n\tfor (let attempt = 0; attempt < totalAttempts; attempt++) {\n\t\tconst result = await attemptFetch(ctx, retryPolicy, attempt, totalAttempts);\n\n\t\tif (result.ok) return result.value as R;\n\n\t\tif (!result.retry) throw result.cause;\n\n\t\tlastError = result.cause;\n\t\tif (config.debug) {\n\t\t\tlog(\n\t\t\t\t`🔁 Request [${requestId}] retrying after ${result.delayMs}ms (attempt ${attempt + 2}/${totalAttempts}): ${result.cause.message}`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\tawait sleep(result.delayMs, config.signal);\n\t\t} catch {\n\t\t\t// Caller cancelled during backoff\n\t\t\tthrow new RhinoComputeError('Request aborted by caller', ErrorCodes.ABORTED, {\n\t\t\t\tcontext: { endpoint, requestId, requestSize },\n\t\t\t\toriginalError: lastError\n\t\t\t});\n\t\t}\n\t}\n\n\t// Exhausted retries — throw the last seen error\n\tthrow (\n\t\tlastError ??\n\t\tnew RhinoComputeError('Unknown error after retries', ErrorCodes.UNKNOWN_ERROR, {\n\t\t\tcontext: { endpoint, requestId, requestSize }\n\t\t})\n\t);\n}\n","import { RhinoComputeError, ErrorCodes } from '@/core/errors';\n\n/** The public McNeel endpoint's host — disallowed as a `serverUrl`; users must point at their own server. */\nconst DEFAULT_PUBLIC_HOST = 'compute.rhino3d.com';\n\n/**\n * Validate and normalize a Rhino Compute `serverUrl`.\n *\n * This is the single source of truth for \"is this a usable server URL?\" — both\n * `GrasshopperClient` (via `normalizeComputeConfig`) and the standalone-exported\n * `ComputeServerStats` constructor delegate here, so a given URL is accepted or\n * rejected identically no matter which entry point a caller uses.\n *\n * Rules (all enforced):\n * - non-empty (after trim)\n * - `http://` or `https://` scheme\n * - parseable by `new URL()`\n * - not the public McNeel endpoint — compared by parsed hostname, so scheme,\n * casing, port, path, or trailing-slash variants can't slip past the block\n *\n * @param raw - The candidate server URL.\n * @returns The normalized URL with any trailing slashes removed.\n * @throws {RhinoComputeError} `INVALID_CONFIG` if any rule fails.\n */\nexport function validateServerUrl(raw: string): string {\n\tif (!raw?.trim()) {\n\t\tthrow new RhinoComputeError('serverUrl is required', ErrorCodes.INVALID_CONFIG, {\n\t\t\tcontext: { receivedServerUrl: raw }\n\t\t});\n\t}\n\n\tif (!raw.match(/^https?:\\/\\//)) {\n\t\tthrow new RhinoComputeError(\n\t\t\t`Invalid serverUrl: \"${raw}\". Must start with \"http://\" or \"https://\". ` +\n\t\t\t\t`For example: \"http://localhost:5000\" or \"https://example.com\"`,\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{ context: { receivedServerUrl: raw } }\n\t\t);\n\t}\n\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(raw);\n\t} catch (err) {\n\t\tthrow new RhinoComputeError(\n\t\t\t`Invalid serverUrl: \"${raw}\". Must be a valid URL. ` +\n\t\t\t\t`Received error: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{\n\t\t\t\tcontext: { receivedServerUrl: raw },\n\t\t\t\toriginalError: err instanceof Error ? err : undefined\n\t\t\t}\n\t\t);\n\t}\n\n\tif (parsed.hostname.toLowerCase() === DEFAULT_PUBLIC_HOST) {\n\t\tthrow new RhinoComputeError(\n\t\t\t'serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.',\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{ context: { receivedServerUrl: raw } }\n\t\t);\n\t}\n\n\treturn raw.replace(/\\/+$/, '');\n}\n","import { RhinoComputeError, ErrorCodes } from '../errors';\nimport { getLogger } from '../utils/logger';\nimport { validateServerUrl } from './validate-server-url';\n\n/**\n * ComputeServerStats provides methods to query Rhino Compute server statistics.\n *\n * @public Use this for server health monitoring and statistics.\n *\n * @example\n * ```typescript\n * const stats = new ComputeServerStats('http://localhost:6500', 'your-api-key');\n *\n * try {\n * const isOnline = await stats.isServerOnline();\n * const children = await stats.getActiveChildren();\n * const version = await stats.getVersion();\n *\n * // Or get everything at once\n * const allStats = await stats.getServerStats();\n * } finally {\n * await stats.dispose(); // Clean up resources\n * }\n * ```\n */\nexport default class ComputeServerStats {\n\tprivate readonly serverUrl: string;\n\tprivate readonly apiKey?: string;\n\tprivate disposed = false;\n\tprivate activeMonitors: Set<() => void> = new Set();\n\tprivate activeTimeouts: Set<ReturnType<typeof setTimeout>> = new Set();\n\n\t/**\n\t * @param serverUrl - Base URL of the Rhino Compute server with http:// or https:// scheme (e.g., 'http://localhost:6500')\n\t * @param apiKey - Optional API key for authentication\n\t */\n\t/** Timeout (ms) for the fast read/monitoring endpoints. */\n\tprivate static readonly DEFAULT_TIMEOUT_MS = 5000;\n\n\t/** Timeout (ms) for child-lifecycle POSTs — a cold Windows child can take ~30s to spawn. */\n\tprivate static readonly LIFECYCLE_TIMEOUT_MS = 60_000;\n\n\tconstructor(serverUrl: string, apiKey?: string) {\n\t\tthis.serverUrl = validateServerUrl(serverUrl);\n\t\tthis.apiKey = apiKey;\n\t}\n\n\t/**\n\t * Build request headers with optional API key.\n\t */\n\tprivate buildHeaders(): Record<string, string> {\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Content-Type': 'application/json'\n\t\t};\n\n\t\tif (this.apiKey) {\n\t\t\theaders['RhinoComputeKey'] = this.apiKey;\n\t\t}\n\n\t\treturn headers;\n\t}\n\n\t/**\n\t * `fetch` wrapper that aborts after `timeoutMs` so a hung connection can't stall\n\t * a probe (or the `monitor()` loop) forever. Pass `0` to disable the timeout.\n\t */\n\tprivate fetchWithTimeout(\n\t\turl: string,\n\t\tinit: RequestInit = {},\n\t\ttimeoutMs: number = ComputeServerStats.DEFAULT_TIMEOUT_MS\n\t): Promise<Response> {\n\t\t// Merge caller headers OVER the defaults instead of `{ headers: …, ...init }`,\n\t\t// where any `init.headers` would silently replace the whole set (dropping\n\t\t// the API key). `new Headers()` normalizes all three HeadersInit shapes.\n\t\tconst headers: Record<string, string> = this.buildHeaders();\n\t\tif (init.headers) {\n\t\t\tnew Headers(init.headers).forEach((value, key) => {\n\t\t\t\theaders[key] = value;\n\t\t\t});\n\t\t}\n\t\tconst requestInit: RequestInit = { ...init, headers };\n\t\tif (timeoutMs > 0 && !requestInit.signal) {\n\t\t\trequestInit.signal = AbortSignal.timeout(timeoutMs);\n\t\t}\n\t\treturn fetch(url, requestInit);\n\t}\n\n\t/**\n\t * Check if the server is online.\n\t *\n\t * This is a single-sample probe: it returns `true` only on a 2xx from the\n\t * proxy liveness root `/`, and `false` for every other outcome (non-2xx,\n\t * network error, or timeout). A cold or briefly-busy-but-up server can therefore\n\t * read as offline — callers that gate on this (e.g. client construction)\n\t * should retry rather than treat a single `false` as authoritative.\n\t *\n\t * @param timeoutMs - Abort the probe after this many ms (default: 5000).\n\t * Pass `0` to disable the timeout. Prevents a hung connection from\n\t * stalling the caller indefinitely.\n\t */\n\tpublic async isServerOnline(timeoutMs: number = 5000): Promise<boolean> {\n\t\tthis.ensureNotDisposed();\n\n\t\t// The rhino.compute proxy has no `/healthcheck` route; its real liveness\n\t\t// signal is `GET /`, which returns \"compute.rhino3d running\". Probing an\n\t\t// unknown path would instead be forwarded to a child and only tells us the\n\t\t// proxy can reach one.\n\t\tconst url = `${this.serverUrl}/`;\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(url, { method: 'GET' }, timeoutMs);\n\n\t\t\treturn response.ok;\n\t\t} catch (err) {\n\t\t\tgetLogger().debug('[ComputeServerStats] Fetch error:', err);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Get the number of active child processes on the server.\n\t *\n\t * By default the proxy's `/activechildren` endpoint will *spawn* children up\n\t * to the configured count if none are running, then report the count — which\n\t * wakes (and bills) an idle server. Pass `{ initialize: false }` for a passive\n\t * read that reports the current count without spawning; use this for\n\t * monitoring or before a purge/probe where you must not wake the server.\n\t *\n\t * @param options.initialize - When `false`, append `?initialize=false` so the\n\t * server reports without spawning. Defaults to `true` (the server's default).\n\t * @returns Number of active children, or null if unavailable\n\t */\n\tpublic async getActiveChildren(options: { initialize?: boolean } = {}): Promise<number | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\tconst { initialize = true } = options;\n\t\tconst url = initialize\n\t\t\t? `${this.serverUrl}/activechildren`\n\t\t\t: `${this.serverUrl}/activechildren?initialize=false`;\n\n\t\t// `initialize` mode may spawn children before answering — give it the\n\t\t// lifecycle budget; the passive read stays on the short default.\n\t\tconst timeoutMs = initialize\n\t\t\t? ComputeServerStats.LIFECYCLE_TIMEOUT_MS\n\t\t\t: ComputeServerStats.DEFAULT_TIMEOUT_MS;\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(url, {}, timeoutMs);\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to fetch active children:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst text = await response.text();\n\t\t\tconst count = parseInt(text.trim(), 10);\n\n\t\t\tif (isNaN(count)) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Invalid active children response:', text);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn count;\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error fetching active children:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Get the server version information.\n\t *\n\t * @returns Version object with rhino, compute, and git_sha, or null if unavailable\n\t */\n\tpublic async getVersion(): Promise<{\n\t\trhino: string;\n\t\tcompute: string;\n\t\tgit_sha: string | null;\n\t} | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/version`);\n\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to fetch version:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// Read body as text first, then try JSON.parse — avoids the\n\t\t\t// \"Body has already been read\" error if response.json() fails.\n\t\t\tconst text = await response.text();\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(text);\n\t\t\t\treturn {\n\t\t\t\t\trhino: json.rhino ?? '',\n\t\t\t\t\tcompute: json.compute ?? '',\n\t\t\t\t\tgit_sha: json.git_sha ?? null\n\t\t\t\t};\n\t\t\t} catch {\n\t\t\t\treturn { rhino: text, compute: '', git_sha: null };\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error fetching version:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Get the plugins installed on the server.\n\t *\n\t * Returns a `name → version` map of non-core plugins the server has loaded,\n\t * or `null` if the request failed. Pass `kind` to choose which inventory:\n\t * `'gh'` (default) lists Grasshopper add-on assemblies via\n\t * `/plugins/gh/installed`; `'rhino'` lists Rhino plugins via\n\t * `/plugins/rhino/installed`. Plugins that ship with Rhino / are core\n\t * libraries are excluded by the server.\n\t *\n\t * @param kind - `'gh'` for Grasshopper add-ons (default) or `'rhino'` for Rhino plugins.\n\t * @returns Map of plugin name to version, or `null` on failure.\n\t *\n\t * @example\n\t * ```ts\n\t * const gh = await stats.getInstalledPlugins(); // Grasshopper add-ons\n\t * const selvaVersion = gh?.['Selva'] ?? null;\n\t * ```\n\t */\n\tpublic async getInstalledPlugins(\n\t\tkind: 'gh' | 'rhino' = 'gh'\n\t): Promise<Record<string, string> | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/plugins/${kind}/installed`);\n\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn(`[ComputeServerStats] Failed to fetch ${kind} plugins:`, response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// Text-first so a non-JSON body can't throw \"body already read\".\n\t\t\tconst text = await response.text();\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(text);\n\t\t\t\treturn json && typeof json === 'object' ? (json as Record<string, string>) : null;\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tgetLogger().warn(`[ComputeServerStats] Error fetching ${kind} plugins:`, err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Get comprehensive server statistics.\n\t * Fetches all available server information in parallel.\n\t *\n\t * @returns Object containing server status and available stats\n\t */\n\tpublic async getServerStats(): Promise<{\n\t\tisOnline: boolean;\n\t\tversion?: { rhino: string; compute: string; git_sha: string | null };\n\t\tactiveChildren?: number;\n\t}> {\n\t\tthis.ensureNotDisposed();\n\n\t\tconst isOnline = await this.isServerOnline();\n\n\t\tif (!isOnline) {\n\t\t\treturn { isOnline: false };\n\t\t}\n\n\t\t// Passive child count — never spawn from a stats read, or merely viewing\n\t\t// server health would wake (and bill) an idle server.\n\t\tconst [version, activeChildren] = await Promise.all([\n\t\t\tthis.getVersion(),\n\t\t\tthis.getActiveChildren({ initialize: false })\n\t\t]);\n\n\t\treturn {\n\t\t\tisOnline: true,\n\t\t\t...(version && { version }),\n\t\t\t...(activeChildren !== null && { activeChildren })\n\t\t};\n\t}\n\n\t/**\n\t * Purge the server's solve-results / URL-data cache.\n\t *\n\t * POSTs to `cache/purge` and returns the number of entries removed, or `null`\n\t * if the request failed. This clears cached solve responses and fetched\n\t * definition-URL data; it does NOT evict the definition cache (active\n\t * `pointer` references stay valid).\n\t *\n\t * **Caveat:** `cache/purge` is forwarded by the rhino.compute proxy to a\n\t * single round-robin-selected child, so in a multi-child deployment one call\n\t * purges one child's cache. Call repeatedly (or size the pool to 1) if you\n\t * need a fleet-wide purge.\n\t *\n\t * @returns Number of entries removed, or `null` on failure.\n\t *\n\t * @example\n\t * ```ts\n\t * const removed = await stats.purgeCache();\n\t * if (removed !== null) console.log(`Purged ${removed} cached solves`);\n\t * ```\n\t */\n\tpublic async purgeCache(): Promise<number | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`, {\n\t\t\t\tmethod: 'POST'\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to purge cache:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// Read text-first so a non-JSON body can't throw \"body already read\".\n\t\t\tconst text = await response.text();\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(text);\n\t\t\t\treturn typeof json.purged === 'number' ? json.purged : null;\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error purging cache:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Best-effort fleet-wide cache purge across a multi-child deployment.\n\t *\n\t * A single {@link purgeCache} POST is forwarded by the rhino.compute proxy to\n\t * just ONE round-robin-selected child, so the other children keep serving\n\t * stale cached solves. There is no proxy endpoint that addresses children\n\t * individually, so this method reads the active child count (passively, never\n\t * spawning) and fires `2 × count` sequential purges, relying on the proxy's\n\t * round-robin to spread the hits across the pool.\n\t *\n\t * **This is best-effort, not a guarantee.** Round-robin can revisit one child\n\t * and skip another; under concurrent traffic the rotation drifts. The result's\n\t * `confident` flag is `true` only when the server reports a single child (where\n\t * one purge is exact) — surface it so callers don't over-promise. For a hard\n\t * fleet-wide guarantee, run the deployment at `--childcount 1` or add a\n\t * server-side fan-out endpoint.\n\t *\n\t * @returns `{ totalPurged, calls, children, confident }`, or `null` if the\n\t * child count couldn't be read (server unreachable). `totalPurged` sums the\n\t * per-call counts; `calls` is how many purges were issued; `children` is the\n\t * reported pool size; `confident` is `true` only at a single-child pool.\n\t *\n\t * @example\n\t * ```ts\n\t * const r = await stats.purgeAllChildren();\n\t * if (r && !r.confident) {\n\t * console.warn(`Purged ~${r.totalPurged} across ${r.children} children (best-effort)`);\n\t * }\n\t * ```\n\t */\n\tpublic async purgeAllChildren(): Promise<{\n\t\ttotalPurged: number;\n\t\tcalls: number;\n\t\tchildren: number;\n\t\tconfident: boolean;\n\t} | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\t// Passive read — must not spawn children just to purge them.\n\t\tconst children = await this.getActiveChildren({ initialize: false });\n\t\tif (children === null) {\n\t\t\tgetLogger().warn('[ComputeServerStats] purgeAllChildren: could not read child count');\n\t\t\treturn null;\n\t\t}\n\n\t\tif (children === 0) {\n\t\t\t// No live children means nothing is cached on the compute side.\n\t\t\treturn { totalPurged: 0, calls: 0, children: 0, confident: true };\n\t\t}\n\n\t\t// 2× the pool size gives round-robin a strong chance of reaching every\n\t\t// child at least once. Sequential (not parallel) so the proxy advances its\n\t\t// round-robin cursor one child per call rather than racing them onto one.\n\t\tconst calls = children * 2;\n\t\tlet totalPurged = 0;\n\t\tfor (let i = 0; i < calls; i++) {\n\t\t\tconst purged = await this.purgeCache();\n\t\t\tif (purged !== null) totalPurged += purged;\n\t\t}\n\n\t\treturn { totalPurged, calls, children, confident: children === 1 };\n\t}\n\n\t/**\n\t * Get the server's current UTC clock.\n\t *\n\t * GETs `/servertime`, which the server emits as a JSON-encoded ISO-8601\n\t * timestamp (e.g. `\"2026-06-18T08:30:00Z\"`). Useful for detecting clock skew\n\t * between caller and server. Returns `null` if the request failed or the body\n\t * isn't a parseable date.\n\t *\n\t * @returns A `Date` for the server's UTC time, or `null` on failure.\n\t */\n\tpublic async getServerTime(): Promise<Date | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/servertime`);\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to fetch server time:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// Body is a JSON string (\"2026-…Z\"); strip surrounding quotes if present.\n\t\t\tconst text = (await response.text()).trim().replace(/^\"|\"$/g, '');\n\t\t\tconst date = new Date(text);\n\t\t\treturn isNaN(date.getTime()) ? null : date;\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error fetching server time:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Get how long the rhino.compute proxy has been idle.\n\t *\n\t * GETs `/idlespan` on the proxy, which returns the seconds elapsed since the\n\t * last request was forwarded to a compute child. This is a proxy-level metric\n\t * (not proxied to a child) used by autoscalers to decide when a node can be\n\t * drained. Returns `null` if unavailable.\n\t *\n\t * @returns Idle time in seconds, or `null` on failure.\n\t */\n\tpublic async getIdleSpan(): Promise<number | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to fetch idle span:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst seconds = parseFloat((await response.text()).trim());\n\t\t\treturn isNaN(seconds) ? null : seconds;\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error fetching idle span:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Fill the compute child pool up to the server's configured baseline.\n\t *\n\t * POSTs `/launch-children`. No-op when the pool is already at or above the\n\t * configured `--childcount`. Returns `{ spawned, active }` — how many children\n\t * were started and the resulting child count — or `null` on failure.\n\t *\n\t * To raise capacity above the baseline use {@link launchChild}; the baseline\n\t * itself can only be changed by restarting rhino.compute.\n\t *\n\t * @returns `{ spawned, active }`, or `null` on failure.\n\t */\n\tpublic async launchChildren(): Promise<{ spawned: number[]; active: number } | null> {\n\t\treturn this.postJson('/launch-children');\n\t}\n\n\t/**\n\t * Add a single compute child to the pool, optionally on a specific port.\n\t *\n\t * POSTs `/launch-child` (with `?port=N` when `port` is given). Unlike\n\t * {@link launchChildren}, this can push the pool above the baseline, up to the\n\t * server's `MaxChildren` cap. Returns `{ spawned: [port] }` on success, or\n\t * `null` on failure (server replies 400 for a bad port, 409 if the port is in\n\t * use, 503 at the max-children cap).\n\t *\n\t * @param port - Optional specific port to launch on; otherwise the next free one.\n\t * @returns `{ spawned }` listing the launched port, or `null` on failure.\n\t */\n\tpublic async launchChild(port?: number): Promise<{ spawned: number[] } | null> {\n\t\tconst path = port === undefined ? '/launch-child' : `/launch-child?port=${port}`;\n\t\treturn this.postJson(path);\n\t}\n\n\t/**\n\t * Gracefully shut down compute children without respawning them.\n\t *\n\t * POSTs `/shutdown-children`. With no `port` it shuts down every child; with\n\t * `port` it targets just that one. Children do not respawn, but the next\n\t * `/grasshopper` request auto-spawns the pool back to the baseline. Returns\n\t * `{ shutdown, active }` — how many were stopped and the remaining count — or\n\t * `null` on failure.\n\t *\n\t * @param port - Optional port to target; omit to shut down all children.\n\t * @returns `{ shutdown, active }`, or `null` on failure.\n\t */\n\tpublic async shutdownChildren(\n\t\tport?: number\n\t): Promise<{ shutdown: number; active: number } | null> {\n\t\tconst path = port === undefined ? '/shutdown-children' : `/shutdown-children?port=${port}`;\n\t\treturn this.postJson(path);\n\t}\n\n\t/**\n\t * Shut down compute children and respawn replacements (rolling restart).\n\t *\n\t * POSTs `/recycle-children`. With no `port` it recycles every child; with\n\t * `port` it recycles just that one. The server recycles sequentially (each\n\t * replacement is serving before the next child is stopped) so the pool never\n\t * drops to zero mid-recycle. Returns `{ shutdown, spawned, active }`, or\n\t * `null` on failure.\n\t *\n\t * @param port - Optional port to target; omit to recycle all children.\n\t * @returns `{ shutdown, spawned, active }`, or `null` on failure.\n\t */\n\tpublic async recycleChildren(\n\t\tport?: number\n\t): Promise<{ shutdown: number; spawned: number[]; active: number } | null> {\n\t\tconst path = port === undefined ? '/recycle-children' : `/recycle-children?port=${port}`;\n\t\treturn this.postJson(path);\n\t}\n\n\t/**\n\t * POST a control endpoint that replies with a JSON object and return it,\n\t * degrading to `null` on any non-2xx, non-JSON, or network failure. Shared by\n\t * the child-lifecycle methods so their failure semantics stay identical. Uses\n\t * the longer lifecycle timeout since a spawn/recycle can take ~30s.\n\t */\n\tprivate async postJson<T>(path: string): Promise<T | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(\n\t\t\t\t`${this.serverUrl}${path}`,\n\t\t\t\t{ method: 'POST' },\n\t\t\t\tComputeServerStats.LIFECYCLE_TIMEOUT_MS\n\t\t\t);\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn(`[ComputeServerStats] POST ${path} failed:`, response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t// Text-first so a non-JSON body can't throw \"body already read\".\n\t\t\tconst text = await response.text();\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(text) as T;\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tgetLogger().warn(`[ComputeServerStats] Error on POST ${path}:`, err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Continuously monitor server stats at specified interval.\n\t *\n\t * @param callback - Function called with stats on each interval\n\t * @param intervalMs - Milliseconds between checks (default: 5000)\n\t * @returns Function to stop monitoring\n\t *\n\t * @example\n\t * ```typescript\n\t * const stopMonitoring = stats.monitor((data) => {\n\t * console.log('Server stats:', data);\n\t * }, 3000);\n\t *\n\t * // Later...\n\t * stopMonitoring();\n\t * ```\n\t */\n\tpublic monitor(\n\t\tcallback: (stats: Awaited<ReturnType<typeof this.getServerStats>>) => void,\n\t\tintervalMs: number = 5000\n\t): () => void {\n\t\tthis.ensureNotDisposed();\n\n\t\tlet active = true;\n\t\tlet currentTimeoutId: ReturnType<typeof setTimeout> | null = null;\n\n\t\tgetLogger().info(`🔄 Starting server stats monitoring every ${intervalMs}ms`);\n\n\t\tconst check = async () => {\n\t\t\t// Clear current timeout from tracking since it has fired\n\t\t\tif (currentTimeoutId !== null) {\n\t\t\t\tthis.activeTimeouts.delete(currentTimeoutId);\n\t\t\t\tcurrentTimeoutId = null;\n\t\t\t}\n\n\t\t\tif (!active || this.disposed) return;\n\n\t\t\ttry {\n\t\t\t\tconst _stats = await this.getServerStats();\n\n\t\t\t\t// Check again after async operation to prevent race condition\n\t\t\t\tif (!active || this.disposed) return;\n\n\t\t\t\ttry {\n\t\t\t\t\tcallback(_stats);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tgetLogger().error('[ComputeServerStats] Monitor callback threw:', err);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tgetLogger().error('[ComputeServerStats] Failed to fetch stats during monitor:', err);\n\t\t\t}\n\n\t\t\tif (active && !this.disposed) {\n\t\t\t\tcurrentTimeoutId = setTimeout(() => void check(), intervalMs);\n\t\t\t\tthis.activeTimeouts.add(currentTimeoutId);\n\t\t\t}\n\t\t};\n\n\t\tconst stopMonitoring = () => {\n\t\t\tactive = false;\n\n\t\t\t// Clear any pending timeout\n\t\t\tif (currentTimeoutId !== null) {\n\t\t\t\tclearTimeout(currentTimeoutId);\n\t\t\t\tthis.activeTimeouts.delete(currentTimeoutId);\n\t\t\t\tcurrentTimeoutId = null;\n\t\t\t}\n\n\t\t\tthis.activeMonitors.delete(stopMonitoring);\n\t\t};\n\n\t\tthis.activeMonitors.add(stopMonitoring);\n\n\t\t// Explicitly mark as fire-and-forget since we don't need to await the initial call\n\t\tvoid check();\n\n\t\treturn stopMonitoring;\n\t}\n\n\t/**\n\t * Disposes of all resources and stops all active monitors.\n\t * Call this when you're done using the stats instance.\n\t */\n\tpublic async dispose(): Promise<void> {\n\t\tif (this.disposed) return;\n\n\t\tthis.disposed = true;\n\n\t\t// Stop all active monitors (this will also clear their timeouts)\n\t\tfor (const stopMonitor of this.activeMonitors) {\n\t\t\tstopMonitor();\n\t\t}\n\t\tthis.activeMonitors.clear();\n\n\t\t// Clear any remaining timeouts (defensive cleanup)\n\t\tfor (const timeoutId of this.activeTimeouts) {\n\t\t\tclearTimeout(timeoutId);\n\t\t}\n\t\tthis.activeTimeouts.clear();\n\t}\n\n\t/**\n\t * Ensures the instance hasn't been disposed.\n\t */\n\tprivate ensureNotDisposed(): void {\n\t\tif (this.disposed) {\n\t\t\tthrow new RhinoComputeError(\n\t\t\t\t'ComputeServerStats has been disposed and cannot be used',\n\t\t\t\tErrorCodes.INVALID_STATE,\n\t\t\t\t{ context: { disposed: this.disposed } }\n\t\t\t);\n\t\t}\n\t}\n}\n","/**\n * Converts a string to camelCase.\n * @param str - The string to convert\n * @param options - Options object\n * - preserveSpaces: If true, spaces are preserved (default: false)\n */\nexport function toCamelCase(str: string, options: { preserveSpaces?: boolean } = {}): string {\n\tconst { preserveSpaces = false } = options;\n\t// Whitespace acts as a separator unless we're explicitly preserving it.\n\tconst sep = preserveSpaces ? /[-_]+(.)?/g : /[\\s-_]+(.)?/g;\n\tconst head = str.trim();\n\treturn (\n\t\thead.charAt(0).toLowerCase() + head.slice(1).replace(sep, (_, c) => (c ? c.toUpperCase() : ''))\n\t);\n}\n\n/**\n * Recursively converts all object keys to camelCase.\n *\n * @warning Do not use `deep: true` on Rhino Compute wire payloads: it\n * corrupts user-authored keys (value-list labels, item `data` JSON). Read the\n * specific fields you need case-insensitively with `readField`/`hasField` from\n * `core/utils/read-field` instead. Shallow (non-deep) use on wrapper keys is fine.\n *\n * @param obj - The object to process\n * @param options - Options object\n * - deep: If true, process deeply\n * - preserveSpaces: If true, spaces are preserved in keys\n * @returns The new object with camelCased keys\n * @internal\n */\nexport function camelcaseKeys(\n\tobj: unknown,\n\toptions: { deep?: boolean; preserveSpaces?: boolean } = {}\n): unknown {\n\tif (!obj || typeof obj !== 'object') {\n\t\treturn obj;\n\t}\n\n\tif (Array.isArray(obj)) {\n\t\treturn options.deep ? obj.map((item) => camelcaseKeys(item, options)) : obj;\n\t}\n\n\treturn Object.keys(obj).reduce(\n\t\t(result, key) => {\n\t\t\tconst camelKey = toCamelCase(key, { preserveSpaces: options.preserveSpaces });\n\t\t\tconst value = (obj as any)[key];\n\t\t\t(result as any)[camelKey] = options.deep ? camelcaseKeys(value, options) : value;\n\t\t\treturn result;\n\t\t},\n\t\t{} as Record<string, unknown>\n\t);\n}\n","import { RhinoComputeError, ErrorCodes } from '@/core/errors';\nimport { getLogger } from '@/core/utils/logger';\nimport { decodeBase64ToBinary } from '@/core/utils/encoding';\n\nimport { FileBaseInfo, FileData, ProcessedFile } from './types';\n\n/**\n * Extracts and processes files from compute response data without downloading them.\n * Returns an array of ProcessedFile objects that can be used programmatically.\n *\n * @param downloadableFiles - An array of FileData items from the compute response.\n * @param additionalFiles - Optional additional files to include (fetched from URLs).\n * @returns A Promise resolving to an array of ProcessedFile objects.\n * @throws Will throw an error if file processing fails.\n *\n * @example\n * const files = await extractFilesFromComputeResponse(fileData);\n * files.forEach(file => {\n * console.log(`File: ${file.fileName}, Size: ${file.content.length}`);\n * });\n */\nexport const extractFilesFromComputeResponse = async (\n\tdownloadableFiles: FileData[],\n\tadditionalFiles: FileBaseInfo[] | FileBaseInfo | null = null\n): Promise<ProcessedFile[]> => {\n\ttry {\n\t\treturn await processFiles(downloadableFiles, additionalFiles);\n\t} catch (err) {\n\t\tthrow new RhinoComputeError(\n\t\t\t'Failed to extract files from compute response',\n\t\t\tErrorCodes.INVALID_STATE,\n\t\t\t{\n\t\t\t\tcontext: { originalError: err instanceof Error ? err.message : String(err) },\n\t\t\t\toriginalError: err instanceof Error ? err : undefined\n\t\t\t}\n\t\t);\n\t}\n};\n\n/**\n * Downloads files from a compute response as a ZIP archive.\n * Packages multiple files into a single ZIP file and triggers a browser download.\n *\n * @param downloadableFiles - An array of FileData items from the compute response.\n * @param additionalFiles - Optional additional files to include in the ZIP (fetched from URLs).\n * @param fileFoldername - The name of the ZIP file (without extension).\n * @throws Will throw an error if the file handling or download fails.\n *\n * @example\n * await downloadDataFromComputeResponse(fileData, null, 'my-export');\n * // Downloads 'my-export.zip'\n */\nexport const downloadFileData = async (\n\tdownloadableFiles: FileData[],\n\tfileFoldername: string,\n\tadditionalFiles: FileBaseInfo[] | FileBaseInfo | null = null\n): Promise<void> => {\n\t// Check if we're in a browser environment\n\tif (typeof document === 'undefined' || typeof Blob === 'undefined') {\n\t\tthrow new RhinoComputeError(\n\t\t\t'File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).',\n\t\t\tErrorCodes.BROWSER_ONLY,\n\t\t\t{\n\t\t\t\tcontext: {\n\t\t\t\t\tenvironment: typeof window !== 'undefined' ? 'browser (SSR)' : 'Node.js',\n\t\t\t\t\tdocumentAvailable: typeof document !== 'undefined',\n\t\t\t\t\tblobAvailable: typeof Blob !== 'undefined'\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\ttry {\n\t\tconst processedFiles = await processFiles(downloadableFiles, additionalFiles);\n\t\tawait createAndDownloadZip(processedFiles, fileFoldername);\n\t} catch (err) {\n\t\t// Re-throw if it's already a RhinoComputeError\n\t\tif (err instanceof RhinoComputeError) {\n\t\t\tthrow err;\n\t\t}\n\t\tthrow new RhinoComputeError(\n\t\t\t'Failed to download files from compute response',\n\t\t\tErrorCodes.INVALID_STATE,\n\t\t\t{\n\t\t\t\tcontext: { originalError: err instanceof Error ? err.message : String(err) },\n\t\t\t\toriginalError: err instanceof Error ? err : undefined\n\t\t\t}\n\t\t);\n\t}\n};\n\n/**\n * Decode the inline files carried in a compute response into `ProcessedFile`s.\n *\n * Pure and synchronous: base64 items are decoded to binary, plain-text items are\n * passed through, and the archive path is derived from `subFolder` + name.\n * Degrades per-file like {@link fetchRemoteFiles}: an item with no usable `data`\n * or with undecodable base64 is logged and skipped, never aborting the batch.\n * This is the half of file handling that both public entry points share; it\n * never touches the network and never throws.\n *\n * @param dataItems - `FileData` items from the compute response.\n * @returns The decoded files.\n */\nconst decodeResponseFiles = (dataItems: FileData[]): ProcessedFile[] => {\n\tconst processedFiles: ProcessedFile[] = [];\n\n\tdataItems.forEach((item) => {\n\t\tconst fileName = `${item.fileName}${item.fileType}`;\n\t\tconst filePath =\n\t\t\titem.subFolder && item.subFolder.trim() !== '' ? `${item.subFolder}/${fileName}` : fileName;\n\n\t\tif (item.isBase64Encoded === true && item.data) {\n\t\t\t// `decodeBase64ToBinary` already returns a correctly-bounded view;\n\t\t\t// re-wrapping `.buffer` would discard its byteOffset/byteLength and\n\t\t\t// expose the whole (possibly pooled) backing buffer as corrupt content.\n\t\t\ttry {\n\t\t\t\tprocessedFiles.push({\n\t\t\t\t\tfileName,\n\t\t\t\t\tcontent: decodeBase64ToBinary(item.data),\n\t\t\t\t\tpath: filePath\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tgetLogger().warn(`Skipping file \"${filePath}\": base64 decode failed.`, err);\n\t\t\t}\n\t\t} else if (item.isBase64Encoded === false && item.data) {\n\t\t\tprocessedFiles.push({\n\t\t\t\tfileName,\n\t\t\t\tcontent: item.data,\n\t\t\t\tpath: filePath\n\t\t\t});\n\t\t} else {\n\t\t\tgetLogger().warn(`Skipping file \"${filePath}\": item carries no usable data.`);\n\t\t}\n\t});\n\n\treturn processedFiles;\n};\n\n/** Abort a hung external-file fetch — one dead URL must degrade the batch, not stall it forever. */\nconst REMOTE_FILE_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch externally-referenced files over HTTP into `ProcessedFile`s.\n *\n * Async and fallible by nature. A failed fetch (network error, non-OK status,\n * or timeout after {@link REMOTE_FILE_TIMEOUT_MS}) is logged and that file is\n * dropped — the rest still resolve — so one dead URL degrades the result rather\n * than aborting the whole batch. This swallow is deliberate and pinned by\n * tests; callers receive only the files that succeeded.\n *\n * @param refs - External file references to fetch.\n * @returns The successfully-fetched files (failures omitted).\n */\nconst fetchRemoteFiles = async (refs: FileBaseInfo[]): Promise<ProcessedFile[]> => {\n\tconst fetched = await Promise.all(\n\t\trefs.map(async (file) => {\n\t\t\ttry {\n\t\t\t\tconst signal =\n\t\t\t\t\ttypeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'\n\t\t\t\t\t\t? AbortSignal.timeout(REMOTE_FILE_TIMEOUT_MS)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst response = await fetch(file.filePath, { signal });\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tgetLogger().warn(`Failed to fetch additional file from URL: ${file.filePath}`);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tconst fileBlob = await response.blob();\n\t\t\t\tconst arrayBuffer = await fileBlob.arrayBuffer();\n\t\t\t\treturn {\n\t\t\t\t\tfileName: file.fileName,\n\t\t\t\t\tcontent: new Uint8Array(arrayBuffer),\n\t\t\t\t\tpath: file.fileName\n\t\t\t\t} as ProcessedFile;\n\t\t\t} catch (error) {\n\t\t\t\tgetLogger().error(`Error fetching additional file from URL: ${file.filePath}`, error);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t})\n\t);\n\n\treturn fetched.filter((f): f is ProcessedFile => f !== null);\n};\n\n/**\n * Compose the decoded response files with any fetched external files.\n *\n * @param dataItems - `FileData` items from the compute response.\n * @param additionalFiles - Optional external file references to fetch and include.\n * @returns A Promise resolving to the combined `ProcessedFile` list.\n */\nconst processFiles = async (\n\tdataItems: FileData[],\n\tadditionalFiles: FileBaseInfo[] | FileBaseInfo | null\n): Promise<ProcessedFile[]> => {\n\tconst processedFiles = decodeResponseFiles(dataItems);\n\n\tif (additionalFiles) {\n\t\tconst filesArray = Array.isArray(additionalFiles) ? additionalFiles : [additionalFiles];\n\t\tprocessedFiles.push(...(await fetchRemoteFiles(filesArray)));\n\t}\n\n\treturn processedFiles;\n};\n\n/**\n * Creates a ZIP archive from processed files and triggers a browser download.\n *\n * @param files - An array of ProcessedFile objects to include in the ZIP.\n * @param zipName - The name of the ZIP file (without extension).\n * @returns A Promise that resolves when the ZIP is generated and download is triggered.\n */\nasync function createAndDownloadZip(files: ProcessedFile[], zipName: string): Promise<void> {\n\tconst { zip, strToU8 } = await import('fflate');\n\n\t// Convert files to fflate format. Zip entries are keyed by path, so two\n\t// files with the same path would silently overwrite each other — rename\n\t// collisions (\"model.txt\" → \"model-2.txt\") instead of losing data.\n\tconst zipData: Record<string, Uint8Array> = {};\n\tfiles.forEach((file) => {\n\t\tconst path = uniqueZipPath(file.path, zipData);\n\t\tif (path !== file.path) {\n\t\t\tgetLogger().warn(`Duplicate archive path \"${file.path}\" — storing as \"${path}\".`);\n\t\t}\n\t\tzipData[path] = typeof file.content === 'string' ? strToU8(file.content) : file.content;\n\t});\n\n\t// Async `zip` deflates on a worker thread instead of blocking the main thread\n\t// like `zipSync` — keeps the UI responsive for large geometry exports.\n\tconst zipped = await new Promise<Uint8Array>((resolve, reject) => {\n\t\tzip(zipData, { level: 6 }, (err, data) => (err ? reject(err) : resolve(data)));\n\t});\n\n\tconst blob = new Blob([zipped as BlobPart], { type: 'application/zip' });\n\tsaveFile(blob, `${zipName}.zip`);\n}\n\n/**\n * First archive path not already taken in `taken`, disambiguating with a\n * numeric suffix before the extension: `dir/model.txt` → `dir/model-2.txt`.\n */\nfunction uniqueZipPath(path: string, taken: Record<string, Uint8Array>): string {\n\tconst has = (p: string) => Object.prototype.hasOwnProperty.call(taken, p);\n\tif (!has(path)) return path;\n\tconst slash = path.lastIndexOf('/');\n\tconst dot = path.lastIndexOf('.');\n\tconst stemEnd = dot > slash ? dot : path.length;\n\tconst stem = path.slice(0, stemEnd);\n\tconst ext = path.slice(stemEnd);\n\tfor (let i = 2; ; i++) {\n\t\tconst candidate = `${stem}-${i}${ext}`;\n\t\tif (!has(candidate)) return candidate;\n\t}\n}\n\n/**\n * Saves a Blob object as a file in the user's browser.\n *\n * @param blob - The Blob object representing the file content.\n * @param filename - The name to give the downloaded file (including extension).\n * @throws {RhinoComputeError} If not running in a browser environment.\n */\nfunction saveFile(blob: Blob, filename: string) {\n\tif (typeof document === 'undefined') {\n\t\tthrow new RhinoComputeError(\n\t\t\t'saveFile requires a browser environment with DOM API access.',\n\t\t\tErrorCodes.BROWSER_ONLY,\n\t\t\t{\n\t\t\t\tcontext: { function: 'saveFile', requiredAPI: 'document' }\n\t\t\t}\n\t\t);\n\t}\n\n\tconst url = URL.createObjectURL(blob);\n\tconst a = document.createElement('a');\n\ta.href = url;\n\ta.download = filename;\n\t// Firefox requires the anchor to be in the DOM for the click to download.\n\tdocument.body.appendChild(a);\n\ta.click();\n\ta.remove();\n\t// Revoking synchronously can abort the download in some browsers — the\n\t// browser only pins the blob once the download has actually started.\n\tsetTimeout(() => URL.revokeObjectURL(url), 10_000);\n}\n"],"mappings":"mOAIO,IAAMA,EAAa,CACzB,cAAe,gBACf,WAAY,aACZ,iBAAkB,mBAClB,kBAAmB,oBAC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AOjC,CAAG,EAAIgC,EAAQE,CAAI,CAAE,CAC9E,CAAC,EAEKC,EAAO,IAAI,KAAK,CAACJ,CAAkB,EAAG,CAAE,KAAM,iBAAkB,CAAC,EACvEK,GAASD,EAAM,GAAGV,CAAO,MAAM,CAChC,CAMA,SAASK,GAAcD,EAAcQ,EAA2C,CAC/E,IAAMC,EAAOC,GAAc,OAAO,UAAU,eAAe,KAAKF,EAAOE,CAAC,EACxE,GAAI,CAACD,EAAIT,CAAI,EAAG,OAAOA,EACvB,IAAMW,EAAQX,EAAK,YAAY,GAAG,EAC5BY,EAAMZ,EAAK,YAAY,GAAG,EAC1Ba,EAAUD,EAAMD,EAAQC,EAAMZ,EAAK,OACnCc,EAAOd,EAAK,MAAM,EAAGa,CAAO,EAC5BE,EAAMf,EAAK,MAAMa,CAAO,EAC9B,QAASG,EAAI,GAAKA,IAAK,CACtB,IAAMC,EAAY,GAAGH,CAAI,IAAIE,CAAC,GAAGD,CAAG,GACpC,GAAI,CAACN,EAAIQ,CAAS,EAAG,OAAOA,CAC7B,CACD,CASA,SAASV,GAASD,EAAYY,EAAkB,CAC/C,GAAI,OAAO,SAAa,IACvB,MAAM,IAAI9C,EACT,+DACAC,EAAW,aACX,CACC,QAAS,CAAE,SAAU,WAAY,YAAa,UAAW,CAC1D,CACD,EAGD,IAAM8C,EAAM,IAAI,gBAAgBb,CAAI,EAC9Bc,EAAI,SAAS,cAAc,GAAG,EACpCA,EAAE,KAAOD,EACTC,EAAE,SAAWF,EAEb,SAAS,KAAK,YAAYE,CAAC,EAC3BA,EAAE,MAAM,EACRA,EAAE,OAAO,EAGT,WAAW,IAAM,IAAI,gBAAgBD,CAAG,EAAG,GAAM,CAClD","names":["ErrorCodes","RhinoComputeError","_RhinoComputeError","message","code","options","__publicField","inputName","expectedType","context","paramType","paramName","NoOpLogger","ConsoleLogger","message","args","internalLogger","getLogger","setLogger","logger","missing","method","RhinoComputeError","ErrorCodes","enableDebugLogging","getNodeBuffer","buf","encodeStringToBase64","str","Buffer","base64ByteArray","isBase64","decodeBase64ToBinary","base64File","data","RhinoComputeError","ErrorCodes","binary","bytes","utf8ByteLength","i","code","s","parseServerTiming","headerValue","timing","sawMetric","part","name","params","durParam","p","dur","key","DEFAULT_RETRY","RETRYABLE_STATUS","resolveRetryPolicy","policy","parseRetryAfter","seconds","dateMs","delta","backoffDelay","attempt","exponential","jitter","sleep","ms","signal","resolve","reject","id","onAbort","throwHttpError","response","fullUrl","requestId","requestSize","serverUrl","errorBody","serverCode","status","statusText","responseHeaders","value","trimmed","bodyHint","context","error","ErrorCodes","code","mapServerErrorCode","RhinoComputeError","buildUrl","endpoint","base","path","isLocalhost","hostname","warnedNoAuth","buildHeaders","config","headers","getLogger","generateRequestId","log","message","debug","composeSignal","callerSignal","timeoutMs","signals","cleanup","ctrl","prevCleanup","handleResponse","startTime","onServerTiming","responseTime","parsedForCode","parsed","serverMessage","exceptionType","stack","stackStr","e","err","attemptFetch","ctx","retryPolicy","totalAttempts","retryAfterMs","delayMs","fatal","fetchRhinoCompute","args","body","utf8ByteLength","sizeKb","emoji","lastError","result","DEFAULT_PUBLIC_HOST","validateServerUrl","raw","RhinoComputeError","ErrorCodes","parsed","err","_ComputeServerStats","serverUrl","apiKey","__publicField","validateServerUrl","headers","url","init","timeoutMs","value","key","requestInit","err","getLogger","options","initialize","response","text","count","json","kind","version","activeChildren","children","calls","totalPurged","i","purged","date","seconds","port","path","callback","intervalMs","active","currentTimeoutId","check","_stats","stopMonitoring","stopMonitor","timeoutId","RhinoComputeError","ErrorCodes","ComputeServerStats","toCamelCase","str","options","preserveSpaces","sep","head","_","c","camelcaseKeys","obj","item","result","key","camelKey","value","extractFilesFromComputeResponse","downloadableFiles","additionalFiles","processFiles","err","RhinoComputeError","ErrorCodes","downloadFileData","fileFoldername","processedFiles","createAndDownloadZip","decodeResponseFiles","dataItems","item","fileName","filePath","decodeBase64ToBinary","getLogger","REMOTE_FILE_TIMEOUT_MS","fetchRemoteFiles","refs","file","signal","response","arrayBuffer","error","f","filesArray","files","zipName","zip","strToU8","zipData","path","uniqueZipPath","zipped","resolve","reject","data","blob","saveFile","taken","has","p","slash","dot","stemEnd","stem","ext","i","candidate","filename","url","a"]}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkL3CNT26Scjs = require('./chunk-L3CNT26S.cjs');require('./chunk-EUMIGWRX.cjs');exports.BINARY_MESH_MAGIC = _chunkL3CNT26Scjs.s; exports.BINARY_MESH_VERSION = _chunkL3CNT26Scjs.t; exports.EDGE_USERDATA_KIND = _chunkL3CNT26Scjs.h; exports.FLAG_DELTA_ENCODED = _chunkL3CNT26Scjs.v; exports.FLAG_FLOAT32 = _chunkL3CNT26Scjs.u; exports.FLAG_HAS_UVS = _chunkL3CNT26Scjs.w; exports.FLAG_HAS_VERTEX_COLORS = _chunkL3CNT26Scjs.x; exports.Materials = _chunkL3CNT26Scjs.q; exports.SCALE_FACTORS = _chunkL3CNT26Scjs.D; exports.addEdges = _chunkL3CNT26Scjs.i; exports.applyOffset = _chunkL3CNT26Scjs.c; exports.clearTextureCache = _chunkL3CNT26Scjs.z; exports.computeCombinedBoundingBox = _chunkL3CNT26Scjs.d; exports.createCameraController = _chunkL3CNT26Scjs.e; exports.createGrid = _chunkL3CNT26Scjs.f; exports.createLabelLayer = _chunkL3CNT26Scjs.m; exports.createMeasureTool = _chunkL3CNT26Scjs.o; exports.createRenderPipeline = _chunkL3CNT26Scjs.l; exports.createViewGizmo = _chunkL3CNT26Scjs.g; exports.getThreeMeshesFromComputeResponse = _chunkL3CNT26Scjs.E; exports.initThree = _chunkL3CNT26Scjs.p; exports.isEdgeOverlay = _chunkL3CNT26Scjs.j; exports.parseBinaryMeshBatch = _chunkL3CNT26Scjs.y; exports.parseColor = _chunkL3CNT26Scjs.b; exports.parseDisplayItems = _chunkL3CNT26Scjs.r; exports.parseMeshBatch = _chunkL3CNT26Scjs.A; exports.parseMeshBatchBlob = _chunkL3CNT26Scjs.C; exports.parseMeshBatchObject = _chunkL3CNT26Scjs.B; exports.removeEdges = _chunkL3CNT26Scjs.k; exports.snapToVertex = _chunkL3CNT26Scjs.n; exports.updateScene = _chunkL3CNT26Scjs.a;
|
|
2
|
-
//# sourceMappingURL=visualization-SI2GEY4M.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/visualization-SI2GEY4M.cjs"],"names":[],"mappings":"AAAA,iIAA0P,gCAA6B,y8CAA4qB","file":"/home/runner/work/selva-compute/selva-compute/dist/visualization-SI2GEY4M.cjs"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{A as _,B as G,C as L,D as u,E as R,a as e,b as r,c as o,d as t,e as a,f as s,g as p,h as i,i as n,j as m,k as l,l as f,m as y,n as d,o as h,p as x,q as C,r as g,s as c,t as M,u as E,v as B,w as O,x as j,y as A,z as D}from"./chunk-HNG75VAI.js";import"./chunk-QAOHGIFT.js";export{c as BINARY_MESH_MAGIC,M as BINARY_MESH_VERSION,i as EDGE_USERDATA_KIND,B as FLAG_DELTA_ENCODED,E as FLAG_FLOAT32,O as FLAG_HAS_UVS,j as FLAG_HAS_VERTEX_COLORS,C as Materials,u as SCALE_FACTORS,n as addEdges,o as applyOffset,D as clearTextureCache,t as computeCombinedBoundingBox,a as createCameraController,s as createGrid,y as createLabelLayer,h as createMeasureTool,f as createRenderPipeline,p as createViewGizmo,R as getThreeMeshesFromComputeResponse,x as initThree,m as isEdgeOverlay,A as parseBinaryMeshBatch,r as parseColor,g as parseDisplayItems,_ as parseMeshBatch,L as parseMeshBatchBlob,G as parseMeshBatchObject,l as removeEdges,d as snapToVertex,e as updateScene};
|
|
2
|
-
//# sourceMappingURL=visualization-UJZN4PJD.js.map
|
|
File without changes
|